import 'package:analysis_server/src/analysis_server_abstract.dart';
import 'package:analyzer/exception/exception.dart';
import 'package:analyzer/instrumentation/instrumentation.dart';

/// An instrumentation service to show instrumentation errors as error
/// notifications to the user.
class ErrorNotifier extends NoopInstrumentationService {
  AbstractAnalysisServer server;

  @override
  void logException(dynamic exception,
      [StackTrace stackTrace,
      List<InstrumentationServiceAttachment> attachments]) {
    if (exception is SilentException) {
      // Silent exceptions should not be reported to the user.
      return;
    }

    var message = 'Internal error';
    if (exception is CaughtException && exception.message != null) {
      // TODO(mfairhurst): Use the outermost exception once crash reporting is
      // fixed and this becomes purely user-facing.
      exception = exception.rootCaughtException;
      // TODO(mfairhurst): Use the outermost message rather than the innermost
      // exception as its own message.
      message = exception.exception;
    }

    server.sendServerErrorNotification(message, exception, stackTrace,
        fatal: exception is FatalException);
  }
}

/// Server may throw a [FatalException] to send a fatal error response to the
/// IDEs.
class FatalException extends CaughtException {
  FatalException(String message, Object exception, stackTrace)
      : super.withMessage(message, exception, stackTrace);
}

import 'package:analysis_server/src/analysis_server_abstract.dart';
import 'package:analyzer/exception/exception.dart';
import 'package:analyzer/instrumentation/instrumentation.dart';

/// An instrumentation service to show instrumentation errors as error
/// notifications to the user.
class ErrorNotifier extends NoopInstrumentationService {
  AbstractAnalysisServer server;

  @override
  void logException(dynamic exception,
      [StackTrace stackTrace,
      List<InstrumentationServiceAttachment> attachments]) {
    if (exception is SilentException) {
      // Silent exceptions should not be reported to the user.
      return;
    }

    var message = 'Internal error';
    if (exception is CaughtException && exception.message != null) {
      // TODO(mfairhurst): Use the outermost exception once crash reporting is
      // fixed and this becomes purely user-facing.
      exception = exception.rootCaughtException;
      // TODO(mfairhurst): Use the outermost message rather than the innermost
      // exception as its own message.
      message = exception.message;
    }

    server.sendServerErrorNotification(message, exception, stackTrace,
        fatal: exception is FatalException);
  }
}

/// Server may throw a [FatalException] to send a fatal error response to the
/// IDEs.
class FatalException extends CaughtException {
  FatalException(String message, Object exception, stackTrace)
      : super.withMessage(message, exception, stackTrace);
}

[analysis_server] Fix crash reporting bug, casting exception to a string

Brian noticed this running unit tests. Who knows how many bug reports we
have missed from this -- we can only hope it is very few.

```
type '_TypeError' is not a subtype of type 'String'

package:analysis_server/src/server/error_notifier.dart 26:7        ErrorNotifier.logException
package:analysis_server/src/analysis_server.dart 266:54            AnalysisServer.handleRequest.<fn>
dart:async/zone.dart 1222:13                                       _rootRunBinary
dart:async/zone.dart 1107:19                                       _CustomZone.runBinary
dart:async/zone.dart 1601:18                                       runZonedGuarded.<fn>
dart:async/zone.dart 751:19                                        _ZoneDelegate.handleUncaughtError
...
```
Change-Id: Ib83dc99a88a1566ead5d59a9f71afc80416eb341
Reviewed-on: https://dart-review.googlesource.com/c/sdk/+/151464
Auto-Submit: Mike Fairhurst <2002604e76601be549134505841fea93de80dc45@google.com>
Commit-Queue: Konstantin Shcheglov <09e4d7516628963212bf4aace2f97603d2b706e4@google.com>
Reviewed-by: Konstantin Shcheglov <09e4d7516628963212bf4aace2f97603d2b706e4@google.com>


import 'package:drift/drift.dart';

// #docregion
// import the migrations tooling
import 'package:drift_dev/api/migrations.dart';
// #enddocregion

const kDebugBuild = true;

abstract class _$MyDatabase extends GeneratedDatabase {
  _$MyDatabase(QueryExecutor executor) : super(executor);
}

// #docregion

class MyDatabase extends _$MyDatabase {
// #enddocregion
  MyDatabase(QueryExecutor executor) : super(executor);

  @override
  Iterable<TableInfo<Table, dynamic>> get allTables =>
      throw UnimplementedError();

  @override
  int get schemaVersion => throw UnimplementedError();

  // #docregion
  @override
  MigrationStrategy get migration => MigrationStrategy(
        onCreate: (m) async {/* ... */},
        onUpgrade: (m, from, to) async {/* your existing migration logic */},
        beforeOpen: (details) async {
          // your existing beforeOpen callback, enable foreign keys, etc.

          if (kDebugBuild) {
            // This check pulls in a fair amount of code that's not needed
            // anywhere else, so we recommend only doing it in debug builds.
            await validateDatabaseSchema();
          }
        },
      );
}
// #enddocregion

import 'package:drift/drift.dart';

// #docregion
// import the migrations tooling
import 'package:drift_dev/api/migrations.dart';
// #enddocregion

const kDebugMode = true;

abstract class _$MyDatabase extends GeneratedDatabase {
  _$MyDatabase(QueryExecutor executor) : super(executor);
}

// #docregion

class MyDatabase extends _$MyDatabase {
// #enddocregion
  MyDatabase(QueryExecutor executor) : super(executor);

  @override
  Iterable<TableInfo<Table, dynamic>> get allTables =>
      throw UnimplementedError();

  @override
  int get schemaVersion => throw UnimplementedError();

  // #docregion
  @override
  MigrationStrategy get migration => MigrationStrategy(
        onCreate: (m) async {/* ... */},
        onUpgrade: (m, from, to) async {/* your existing migration logic */},
        beforeOpen: (details) async {
          // your existing beforeOpen callback, enable foreign keys, etc.

          if (kDebugMode) {
            // This check pulls in a fair amount of code that's not needed
            // anywhere else, so we recommend only doing it in debug builds.
            await validateDatabaseSchema();
          }
        },
      );
}
// #enddocregion

Fix runtime migration verification typo

Fix runtime migration verification typo


// Copyright (c) 2018, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

import 'package:analyzer/dart/analysis/analysis_context.dart';
import 'package:analyzer/file_system/file_system.dart';
import 'package:analyzer/src/dart/analysis/analysis_context_collection.dart';
import 'package:meta/meta.dart';

/// A collection of analysis contexts.
///
/// Clients may not extend, implement or mix-in this class.
abstract class AnalysisContextCollection {
  /// Initialize a newly created collection of analysis contexts that can
  /// analyze the files that are included by the list of [includedPaths].
  ///
  /// All paths must be absolute and normalized.
  ///
  /// If a [resourceProvider] is given, then it will be used to access the file
  /// system, otherwise the default resource provider will be used.
  factory AnalysisContextCollection({
    @required List<String> includedPaths,
    ResourceProvider resourceProvider,
  }) = AnalysisContextCollectionImpl;

  /// Return the existing [AnalysisContext] that should be used to analyze
  /// the given [path], or throw [StateError] if the [path] is not analyzed
  /// in any of the created analysis contexts.
  AnalysisContext contextFor(String path);
}

// Copyright (c) 2018, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

import 'package:analyzer/dart/analysis/analysis_context.dart';
import 'package:analyzer/file_system/file_system.dart';
import 'package:analyzer/src/dart/analysis/analysis_context_collection.dart';
import 'package:meta/meta.dart';

/// A collection of analysis contexts.
///
/// Clients may not extend, implement or mix-in this class.
abstract class AnalysisContextCollection {
  /// Initialize a newly created collection of analysis contexts that can
  /// analyze the files that are included by the list of [includedPaths].
  ///
  /// All paths must be absolute and normalized.
  ///
  /// If a [resourceProvider] is given, then it will be used to access the file
  /// system, otherwise the default resource provider will be used.
  factory AnalysisContextCollection({
    @required List<String> includedPaths,
    ResourceProvider resourceProvider,
  }) = AnalysisContextCollectionImpl;

  /// Return all of the analysis contexts in this collection.
  List<AnalysisContext> get contexts;

  /// Return the existing analysis context that should be used to analyze the
  /// given [path], or throw [StateError] if the [path] is not analyzed in any
  /// of the created analysis contexts.
  AnalysisContext contextFor(String path);
}

Add support for accessing all of the created contexts

Change-Id: I84284726dea1b12f8403456cbdb0a9a967624e0d
Reviewed-on: https://dart-review.googlesource.com/67380
Reviewed-by: Konstantin Shcheglov <09e4d7516628963212bf4aace2f97603d2b706e4@google.com>
Commit-Queue: Brian Wilkerson <1f7641b6b14c52b9163524ab8d9aabff80176f21@google.com>


// Copyright (c) 2018, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

import 'dart:async';
import 'dart:io';

import 'package:analysis_server/src/lsp/channel/lsp_byte_stream_channel.dart';
import 'package:analysis_server/src/lsp/lsp_socket_server.dart';

/**
 * Instances of the class [StdioServer] implement a simple server operating
 * over standard input and output. The primary responsibility of this server
 * is to split incoming messages on newlines and pass them along to the
 * analysis server.
 */
class LspStdioAnalysisServer {
  /**
   * An object that can handle either a WebSocket connection or a connection
   * to the client over stdio.
   */
  LspSocketServer socketServer;

  /**
   * Initialize a newly created stdio server.
   */
  LspStdioAnalysisServer(this.socketServer);

  /**
   * Begin serving requests over stdio.
   *
   * Return a future that will be completed when stdin closes.
   */
  Future serveStdio() {
    LspByteStreamServerChannel serverChannel = new LspByteStreamServerChannel(
        stdin, stdout, socketServer.instrumentationService);
    socketServer.createAnalysisServer(serverChannel);
    return serverChannel.closed;
  }
}

// Copyright (c) 2018, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

import 'dart:async';
import 'dart:io';

import 'package:analysis_server/src/lsp/channel/lsp_byte_stream_channel.dart';
import 'package:analysis_server/src/lsp/lsp_socket_server.dart';

/**
 * Instances of the class [StdioServer] implement a simple server operating
 * over standard input and output. The primary responsibility of this server
 * is to split incoming messages on newlines and pass them along to the
 * analysis server.
 */
class LspStdioAnalysisServer {
  /**
   * An object that can handle either a WebSocket connection or a connection
   * to the client over stdio.
   */
  LspSocketServer socketServer;

  /**
   * Initialize a newly created stdio server.
   */
  LspStdioAnalysisServer(this.socketServer);

  /**
   * Begin serving requests over stdio.
   *
   * Return a future that will be completed when stdin closes.
   */
  Future serveStdio() {
    LspByteStreamServerChannel serverChannel = new LspByteStreamServerChannel(
        stdin, stdout.nonBlocking, socketServer.instrumentationService);
    socketServer.createAnalysisServer(serverChannel);
    return serverChannel.closed;
  }
}

Use nonBlocking stdio for LSP

Use nonBlocking stdio for LSP

Change-Id: I20f7ed183d08b7fc778b4cb643eff6f82c9f3f48
Reviewed-on: https://dart-review.googlesource.com/c/90001
Reviewed-by: Brian Wilkerson <1f7641b6b14c52b9163524ab8d9aabff80176f21@google.com>
Commit-Queue: Danny Tuppeny <596a1fc21c51678cfafc48cd1efd53705f8b4f1d@google.com>


// Copyright (c) 2015, <your name>. All rights reserved. Use of this source code
// is governed by a BSD-style license that can be found in the LICENSE file.

library dartbase_console_client.test;

import 'package:dartbase_console_client/dartbase_console_client.dart';
import 'package:unittest/unittest.dart';

import 'package:dartbase_server/gamelogic.dart';

void main() {
  test('Start local client', () {
    LocalConsoleClient client = new LocalConsoleClient(2);
    expect(client.state, GameState.started);
  });

}

// Copyright (c) 2015, <your name>. All rights reserved. Use of this source code
// is governed by a BSD-style license that can be found in the LICENSE file.

library dartbase_console_client.test;

import 'package:dartbase_console_client/dartbase_console_client.dart';
import 'package:unittest/unittest.dart';

import 'package:dartbase_server/gamelogic.dart';

void main() {
  test('Start local client', () {
    LocalConsoleClient client = new LocalConsoleClient(2);
    expect(client.gameState, GameState.started);
  });

}

Fix game state getter name

Fix game state getter name


@TestOn('browser')
import 'package:angular/angular.dart';
import 'package:angular/experimental.dart';
import 'package:test/test.dart';

void main() {
  // This is relied on by internal clients until we introduce a sharding API.
  test('rootLegacyInjector should allow overriding ExceptionHandler', () {
    final appInjector = rootLegacyInjector(([parent]) {
      return new Injector.map({
        ExceptionHandler: new _CustomExceptionHandler(),
      }, parent);
    });

    // Normally errors here are forwarded to the ExceptionHandler.
    //
    // In the case of #1227, we accidentally always used the default
    // ExceptionHandler (BrowserExceptionHandler), meaning the user-defined
    // handler was ignored.
    (appInjector.get(NgZone) as NgZone).runGuarded(() {
      throw new _IntentionalError();
    });
    expect(
      _CustomExceptionHandler.lastCaught,
      const isInstanceOf<_IntentionalError>(),
    );
  });
}

class _IntentionalError extends Error {}

class _CustomExceptionHandler implements ExceptionHandler {
  static Object lastCaught;

  @override
  void call(exception, [stackTrace, String reason]) {
    lastCaught = exception;
  }
}

@TestOn('browser')
import 'package:angular/angular.dart';
import 'package:angular/experimental.dart';
import 'package:test/test.dart';

void main() {
  // This is relied on by internal clients until we introduce a sharding API.
  test('rootLegacyInjector should allow overriding ExceptionHandler', () {
    final appInjector = rootLegacyInjector(([parent]) {
      return new Injector.map({
        ExceptionHandler: new _CustomExceptionHandler(),
      }, parent);
    });

    // Normally errors here are forwarded to the ExceptionHandler.
    //
    // In the case of #1227, we accidentally always used the default
    // ExceptionHandler (BrowserExceptionHandler), meaning the user-defined
    // handler was ignored.
    (appInjector.get(NgZone) as NgZone).runGuarded(() {
      throw new _IntentionalError();
    });
    expect(
      _CustomExceptionHandler.lastCaught,
      const isInstanceOf<_IntentionalError>(),
    );
  });

  test('rootLegacyInjector should provide a working SlowComponentLoader', () {
    final appInjector = rootLegacyInjector(([parent]) {
      return new Injector.empty(parent);
    });

    // Easiest way to tell is make sure its the same const instance.
    expect(
      appInjector.get(SlowComponentLoader),
      const SlowComponentLoader(const ComponentLoader()),
    );
  });
}

class _IntentionalError extends Error {}

class _CustomExceptionHandler implements ExceptionHandler {
  static Object lastCaught;

  @override
  void call(exception, [stackTrace, String reason]) {
    lastCaught = exception;
  }
}

test(Core): Add a test that rootLegacyInjector supports SlowComponentLoader.

PiperOrigin-RevId: 192625887


// Copyright (c) 2016, the Dart project authors.  Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

import 'package:angular/angular.dart';
import 'package:angular_components/mixins/material_dropdown_base.dart';

/// A directive providing a [MenuRoot] through the injected [DropdownHandle].
@Directive(
  selector: '[menu-root]',
  providers: [ExistingProvider(MenuRoot, MenuRootDirective)],
)
class MenuRootDirective extends MenuRoot {
  final DropdownHandle _dropdown;

  MenuRootDirective(@Optional() this._dropdown) {
    visible = true;
  }

  @override
  void closeHierarchy() {
    visible = false;
    _dropdown.close();
  }
}

/// The root of a hierarchy of [MenuItemGroups].
///
/// This must be provided as it permits to close the menu hierarchy on menu
/// actions.
abstract class MenuRoot {
  void closeHierarchy();

  /// Is this menu closed or closing.
  bool visible;
}

// Copyright (c) 2016, the Dart project authors.  Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

import 'package:angular/angular.dart';
import 'package:angular_components/mixins/material_dropdown_base.dart';

/// A directive providing a [MenuRoot] through the injected [DropdownHandle].
@Directive(
  selector: '[menu-root]',
  providers: [ExistingProvider(MenuRoot, MenuRootDirective)],
)
class MenuRootDirective extends MenuRoot {
  final DropdownHandle _dropdown;

  MenuRootDirective(@Optional() this._dropdown) {
    visible = true;
  }

  @override
  void closeHierarchy() {
    visible = false;
    _dropdown?.close();
  }
}

/// The root of a hierarchy of [MenuItemGroups].
///
/// This must be provided as it permits to close the menu hierarchy on menu
/// actions.
abstract class MenuRoot {
  void closeHierarchy();

  /// Is this menu closed or closing.
  bool visible;
}

Use nullable access to the dropdown, as it is passed optionally in menu-root.

PiperOrigin-RevId: 256203326


import 'dart:async';
import 'dart:io';

import 'package:dartz/dartz.dart';
import 'package:meta/meta.dart';

import '../../../../core/error/exception.dart';
import '../../../../core/error/failure.dart';
import '../../../../core/network/network_info.dart';
import '../../domain/repositories/activity_repository.dart';
import '../datasources/activity_data_source.dart';

class ActivityRepositoryImpl implements ActivityRepository {
  final ActivityDataSource dataSource;
  final NetworkInfo networkInfo;

  ActivityRepositoryImpl({
    @required this.dataSource,
    @required this.networkInfo,
  });

  @override
  Future<Either<Failure, Map<String, Map<String, Object>>>>
      getActivity() async {
    if (await networkInfo.isConnected) {
      try {
        final activity = await dataSource.getActivity();
        return Right(activity);
      } on MissingServerException {
        return Left(MissingServerFailure());
      } on SettingsException {
        return Left(SettingsFailure());
      } on ServerException {
        return Left(ServerFailure());
      } on SocketException {
        return Left(SocketFailure());
      } on TlsException {
        return Left(TlsFailure());
      } on FormatException {
        return Left(UrlFormatFailure());
      } on ArgumentError {
        return Left(UrlFormatFailure());
      } on TimeoutException {
        return Left(TimeoutFailure());
      } on JsonException {
        return Left(JsonFailure());
      }
    } else {
      return Left(ConnectionFailure());
    }
  }
}

import 'dart:async';
import 'dart:io';

import 'package:dartz/dartz.dart';
import 'package:meta/meta.dart';

import '../../../../core/error/exception.dart';
import '../../../../core/error/failure.dart';
import '../../../../core/network/network_info.dart';
import '../../domain/repositories/activity_repository.dart';
import '../datasources/activity_data_source.dart';

class ActivityRepositoryImpl implements ActivityRepository {
  final ActivityDataSource dataSource;
  final NetworkInfo networkInfo;

  ActivityRepositoryImpl({
    @required this.dataSource,
    @required this.networkInfo,
  });

  @override
  Future<Either<Failure, Map<String, Map<String, Object>>>>
      getActivity() async {
    if (await networkInfo.isConnected) {
      try {
        final activity = await dataSource.getActivity();
        return Right(activity);
      } on MissingServerException {
        return Left(MissingServerFailure());
      } on SettingsException {
        return Left(SettingsFailure());
      } on ServerException {
        return Left(ServerFailure());
      } on SocketException {
        return Left(SocketFailure());
      } on TlsException {
        return Left(TlsFailure());
      } on FormatException {
        return Left(UrlFormatFailure());
      } on ArgumentError {
        return Left(UrlFormatFailure());
      } on TimeoutException {
        return Left(TimeoutFailure());
      } on JsonDecodeException {
        return Left(JsonFailure());
      }
    } else {
      return Left(ConnectionFailure());
    }
  }
}

Update exception catch to JsonDecodeException.


// Copyright (c) 2016, the Dart project authors.  Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

import 'package:angular_components/model/selection/selection_model.dart';

import 'delegating_selection_model.dart';

/// Single selection model that always has a value selected
class RadioGroupSingleSelectionModel<T>
    extends DelegatingSingleSelectionModel<T> {
  RadioGroupSingleSelectionModel([T initialValue])
      : super(new SelectionModel<T>.withList(
            selectedValues: initialValue == null ? const [] : [initialValue]));

  @override
  void clear() {}

  @override
  bool deselect(T value) => false;
}

// Copyright (c) 2016, the Dart project authors.  Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

import 'package:angular_components/model/selection/selection_model.dart';

import 'delegating_selection_model.dart';

/// Single selection model that always has a value selected
class RadioGroupSingleSelectionModel<T>
    extends DelegatingSingleSelectionModel<T> {
  RadioGroupSingleSelectionModel([T initialValue])
      : super(new SelectionModel<T>.single(
            selected: initialValue == null ? null : initialValue));

  @override
  void clear() {}

  @override
  bool deselect(T value) => false;
}

Use SelectionModel.single(), SelectionModel.multi() etc. instead of deprecated SelectionModel.withList()
Use SelectionModel.empty() instead of deprecated SelectionModel()

PiperOrigin-RevId: 200344866


import 'package:hello_dart/hello_dart.dart';

/// Your player.
class MyPlayer extends Player {

  /// Your program.
  start() {
  }

}

main() {
  createWorld('scenario.txt', new MyPlayer());
}

import 'package:hello_dart/hello_dart.dart';

/// Your player.
class MyPlayer extends Player {

  /// Your program.
  start() {
    move();
    goAroundTree();
  }

  goAroundTree() {

  }
}

main() {
  createWorld('scenario.txt', new MyPlayer());
}

Add some help to write the first function


// Copyright (c) 2014, the Dart project authors.  Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

import 'package:scheduled_test/scheduled_stream.dart';

import '../../../lib/src/exit_codes.dart' as exit_codes;
import '../../descriptor.dart' as d;
import '../../test_pub.dart';

main() {
  initConfig();
  integration("errors if an executable's script can't be found", () {
    d.dir("foo", [
      d.pubspec({
        "name": "foo",
        "executables": {
          "missing": "not_here",
          "nope": null
        }
      })
    ]).create();

    var pub = startPub(args: ["global", "activate", "-spath", "../foo"]);

    pub.stderr.expect('Warning: Executable "missing" runs '
        '"bin/not_here.dart", which was not found in foo.');
    pub.stderr.expect('Warning: Executable "nope" runs "bin/nope.dart", which '
        'was not found in foo.');
    pub.shouldExit();
  });
}

// Copyright (c) 2014, the Dart project authors.  Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

import 'package:path/path.dart' as p;

import '../../descriptor.dart' as d;
import '../../test_pub.dart';

main() {
  initConfig();
  integration("errors if an executable's script can't be found", () {
    d.dir("foo", [
      d.pubspec({
        "name": "foo",
        "executables": {
          "missing": "not_here",
          "nope": null
        }
      })
    ]).create();

    var pub = startPub(args: ["global", "activate", "-spath", "../foo"]);

    pub.stderr.expect('Warning: Executable "missing" runs '
        '"bin/not_here.dart", which was not found in foo.');
    pub.stderr.expect('Warning: Executable "nope" runs '
        '"${p.join('bin', 'nope.dart')}", which was not found in foo.');
    pub.shouldExit();
  });
}

Fix binstub test on windows.

Fix binstub test on windows.

R=nweiz@google.com

Review URL: https://codereview.chromium.org//586843002

git-svn-id: c93d8a2297af3b929165606efe145742a534bc71@40518 260f80e4-7a28-3924-810f-c04153c831b5


// Copyright (c) 2017, the Dart project authors.  Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

library fasta.function_type_builder;

import 'builder.dart' show LibraryBuilder, TypeBuilder, TypeVariableBuilder;

abstract class FunctionTypeBuilder extends TypeBuilder {
  final TypeBuilder returnType;
  final List typeVariables;
  final List formals;

  FunctionTypeBuilder(this.returnType, this.typeVariables, this.formals);

  @override
  String get name => null;

  @override
  String get debugName => "Function";

  @override
  StringBuffer printOn(StringBuffer buffer) {
    if (typeVariables != null) {
      buffer.write("<");
      bool isFirst = true;
      for (TypeVariableBuilder t in typeVariables) {
        if (!isFirst) {
          buffer.write(", ");
        } else {
          isFirst = false;
        }
        buffer.write(t.name);
      }
      buffer.write(">");
    }
    buffer.write("(");
    if (formals != null) {
      bool isFirst = true;
      for (TypeBuilder t in formals) {
        if (!isFirst) {
          buffer.write(", ");
        } else {
          isFirst = false;
        }
        buffer.write(t.fullNameForErrors);
      }
    }
    buffer.write(") -> ");
    buffer.write(returnType.fullNameForErrors);
    return buffer;
  }

  @override
  build(LibraryBuilder library) {}
}

// Copyright (c) 2017, the Dart project authors.  Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

library fasta.function_type_builder;

import 'builder.dart' show LibraryBuilder, TypeBuilder, TypeVariableBuilder;

abstract class FunctionTypeBuilder extends TypeBuilder {
  final TypeBuilder returnType;
  final List typeVariables;
  final List formals;

  FunctionTypeBuilder(this.returnType, this.typeVariables, this.formals);

  @override
  String get name => null;

  @override
  String get debugName => "Function";

  @override
  StringBuffer printOn(StringBuffer buffer) {
    if (typeVariables != null) {
      buffer.write("<");
      bool isFirst = true;
      for (TypeVariableBuilder t in typeVariables) {
        if (!isFirst) {
          buffer.write(", ");
        } else {
          isFirst = false;
        }
        buffer.write(t.name);
      }
      buffer.write(">");
    }
    buffer.write("(");
    if (formals != null) {
      bool isFirst = true;
      for (dynamic t in formals) {
        if (!isFirst) {
          buffer.write(", ");
        } else {
          isFirst = false;
        }
        buffer.write(t?.fullNameForErrors);
      }
    }
    buffer.write(") -> ");
    buffer.write(returnType?.fullNameForErrors);
    return buffer;
  }

  @override
  build(LibraryBuilder library) {}
}

Make debug printing of function types more robust.

Sometimes when printing stack states in the outline builder,
a formal in a function type is a FormalParameterBuilder,
and sometimes a formal or the return type is null.

Change-Id: I2bed0baae2a80e894e170a85744e382e763c8944
Reviewed-on: https://dart-review.googlesource.com/58207
Reviewed-by: Peter von der Ahé <ad40f903ca639ca334d95dc5a5f0ae92bd708079@google.com>
Commit-Queue: Aske Simon Christensen <589eb3fd9a84f06d0ac46d3aa71dddcfb0814ccd@google.com>


part of kcaa_model;

class RepairSlot extends Observable {
  @observable int id;
  @observable Ship ship;
  @observable DateTime eta;
  @observable String etaDatetimeString;

  RepairSlot();

  void update(Map<String, dynamic> data, Map<int, Ship> shipMap) {
    id = data["id"];
    if (data["ship_id"] != 0) {
      ship = shipMap[data["ship_id"]];
    }

    // ETA.
    if (data["eta"] != 0) {
      eta = new DateTime.fromMillisecondsSinceEpoch(data["eta"], isUtc: true)
        .toLocal();
      etaDatetimeString = formatShortTime(eta);
    }
  }
}

void handleRepairDock(Assistant assistant, AssistantModel model,
                      Map<String, dynamic> data) {
  model.numShipsBeingRepaired =
      data["slots"].where((s) => s["ship_id"] != 0).length;

  var slotsLength = data["slots"].length;
  resizeList(model.repairSlots, slotsLength, () => new RepairSlot());
  for (var i = 0; i < slotsLength; i++) {
    model.repairSlots[i].update(data["slots"][i], model.shipMap);
  }
}

part of kcaa_model;

class RepairSlot extends Observable {
  @observable int id;
  @observable Ship ship;
  @observable DateTime eta;
  @observable String etaDatetimeString;

  RepairSlot();

  void update(Map<String, dynamic> data, Map<int, Ship> shipMap) {
    id = data["id"];
    if (data["ship_id"] != 0) {
      ship = shipMap[data["ship_id"]];
    } else {
      ship = null;
    }

    // ETA.
    if (data["eta"] != 0) {
      eta = new DateTime.fromMillisecondsSinceEpoch(data["eta"], isUtc: true)
        .toLocal();
      etaDatetimeString = formatShortTime(eta);
    } else {
      eta = null;
      etaDatetimeString = null;
    }
  }
}

void handleRepairDock(Assistant assistant, AssistantModel model,
                      Map<String, dynamic> data) {
  model.numShipsBeingRepaired =
      data["slots"].where((s) => s["ship_id"] != 0).length;

  var slotsLength = data["slots"].length;
  resizeList(model.repairSlots, slotsLength, () => new RepairSlot());
  for (var i = 0; i < slotsLength; i++) {
    model.repairSlots[i].update(data["slots"][i], model.shipMap);
  }
}

Clear a repair slot when completed.

Clear a repair slot when completed.


// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

library playfair;

import 'dart:sky' as sky;
import 'dart:math' as math;

import 'package:sky/rendering.dart';
import 'package:sky/theme/typography.dart';
import 'package:sky/widgets.dart';

part 'src/base.dart';

// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

library playfair;

import 'dart:sky' as sky;
import 'dart:math' as math;

import 'package:sky/material.dart';
import 'package:sky/rendering.dart';
import 'package:sky/widgets.dart';

part 'src/base.dart';

Update imports after material.dart rename


import 'package:slugify/src/replacements.dart';

const dupeSpacePattern = r'\s{2,}';
const punctuationPattern = r'[^\w\s-]';

Slugify(String text, {String delimiter = '-', bool lowercase = true}) {
  // Trim leading and trailing whitespace
  String slug = text.trim();

  // Make the text lowercase (optional)
  if (lowercase) {
    slug = slug.toLowerCase();
  }

  // Substitute characters for their latin equivalent
  replacements.forEach((k, v) => slug = slug.replaceAll(k, v));

  slug = slug
      // Condense whitespaces to 1 space
      .replaceAll(RegExp(dupeSpacePattern), ' ')
      // Remove punctuation
      .replaceAll(RegExp(punctuationPattern), '')
      // Add delimiter
      .replaceAll(' ', delimiter);

  return slug;
}

import 'package:slugify/src/replacements.dart';

final _dupeSpaceRegExp = RegExp(r'\s{2,}');
final _punctuationRegExp = RegExp(r'[^\w\s-]');

/// Converts [text] to a slugified [String] separated by the [delimiter].
Slugify(String text, {String delimiter = '-', bool lowercase = true}) {
  // Trim leading and trailing whitespace.
  String slug = text.trim();

  // Make the text lowercase (optional).
  if (lowercase) {
    slug = slug.toLowerCase();
  }

  // Substitute characters for their latin equivalent.
  replacements.forEach((k, v) => slug = slug.replaceAll(k, v));

  slug = slug
      // Condense whitespaces to 1 space.
      .replaceAll(_dupeSpaceRegExp, ' ')
      // Remove punctuation.
      .replaceAll(_punctuationRegExp, '')
      // Replace space with the delimiter.
      .replaceAll(' ', delimiter);

  return slug;
}

Convert RegExp to final vars

Convert RegExp to final vars


/**
 * By importing this library, you get the two most important fuzzy logic hedges:
 * [very] and [fairly].
 *
 * This means you can do:
 *
 *     (fairly(joke.funny) & very(situation.tense)) >> (laughter.loud)
 */
library fuzzyhedges;

import 'fuzzylogic.dart';
import 'dart:math';

class _FuzzyHedge extends FuzzyTerm {
  _FuzzyHedge(FuzzyNode a, this.hedgeFunction) {
    children = new Set.from([a]);
  }

  final _HedgeFunction hedgeFunction;

  num getDegreeOfMembership(List<FuzzyValue> inputs) {
    return hedgeFunction(children.single.getDegreeOfMembershipWithInputs(inputs));
  }

  void setDegreeOfTruth(num degreeOfTruth, List<FuzzyValue> outputs) {
    // TODO: change DOT through hedgeFunction?
    children.single.setDegreeOfTruth(degreeOfTruth, outputs);
  }
}

typedef num _HedgeFunction(num degreeOfMembership);

FuzzyNode very(FuzzyNode node) =>
    new _FuzzyHedge(node, (num dom) => pow(dom, 2));
FuzzyNode fairly(FuzzyNode node) =>
    new _FuzzyHedge(node, (num dom) => sqrt(dom));

/**
 * By importing this library, you get the two most important fuzzy logic hedges:
 * [very] and [fairly].
 *
 * This means you can do:
 *
 *     (fairly(joke.funny) & very(situation.tense)) >> (laughter.loud)
 */
library fuzzyhedges;

import 'fuzzylogic.dart';
import 'dart:math';

class _FuzzyHedge extends FuzzyTerm {
  _FuzzyHedge(FuzzyNode a, this.hedgeFunction) {
    children = new Set.from([a]);
  }

  final _HedgeFunction hedgeFunction;

  num getDegreeOfMembershipWithInputs(List<FuzzyValue> inputs) {
    return hedgeFunction(children.single.getDegreeOfMembershipWithInputs(inputs));
  }

  void setDegreeOfTruth(num degreeOfTruth, List<FuzzyValue> outputs) {
    // TODO: change DOT through hedgeFunction?
    children.single.setDegreeOfTruth(degreeOfTruth, outputs);
  }
}

typedef num _HedgeFunction(num degreeOfMembership);

FuzzyNode very(FuzzyNode node) =>
    new _FuzzyHedge(node, (num dom) => pow(dom, 2));
FuzzyNode fairly(FuzzyNode node) =>
    new _FuzzyHedge(node, (num dom) => sqrt(dom));

Rename getDegreeOfMembership to getDegreeOfMembershipWithInputs even in FuzzyHedges


import 'package:ddays/list_tasks.dart';
import 'package:test/test.dart';
import 'dart:html';

void main() {
  test('sinlgeTaskElement returns a LIElement with correct p children', () {
  LIElement st = singleTaskElement('task1');
  expect(st.children[0].text, 'task1');
  expect(st.classes.contains('singletask'),true);
  expect(st.children[0].classes.contains('summarytext'),true);
  LIElement st2 = singleTaskElement('');
  expect(st2.children[0].text, '');
  expect(st2.children[0].classes.contains('summarytext'),true);
  });

}

import 'package:ddays/list_tasks.dart';
import 'package:test/test.dart';
import 'dart:html';

void main() {
  test('sinlgeTaskElement returns a LIElement with correct p children', () {
  LIElement st = singleTaskElement('task1');
  expect(st.children[0].text, 'task1');
  expect(st.classes.contains('singletask'),true);
  expect(st.children[0].classes.contains('summarytext'),true);
  LIElement st2 = singleTaskElement('');
  expect(st2.children[0].text, '');
  expect(st2.children[0].classes.contains('summarytext'),true);
  });
  test('insertTask should prepend a singleTaskElement into #listtasks children.',() {
    insertTask('some task');
    var li = querySelector('#listtasks').children[0];
    expect(li.children[0].text, 'some task');
    insertTask('other task');
    var li2 = querySelector('#listtasks').children[0];
    expect(li2.children[0].text, 'other task');
  });
  test('inserted tasks should be retrievable by their classname "singletask"', () {
    insertTask('more tasks');
    var retrieved = querySelector('.singletask');
    expect(retrieved.children[0].text, 'more tasks');
  });

}

Add tests for insertTask function

Add tests for insertTask function


import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/material.dart';

// [START listen_to_realtime_updates_listen_for_updates2]
class UserInformation extends StatefulWidget {
  @override
  _UserInformationState createState() => _UserInformationState();
}

class _UserInformationState extends State<UserInformation> {
  final Stream<QuerySnapshot> _usersStream =
      FirebaseFirestore.instance.collection('users').snapshots();

  @override
  Widget build(BuildContext context) {
    return StreamBuilder<QuerySnapshot>(
      stream: _usersStream,
      builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) {
        if (snapshot.hasError) {
          return const Text('Something went wrong');
        }

        if (snapshot.connectionState == ConnectionState.waiting) {
          return const Text("Loading");
        }

        return ListView(
          children: snapshot.data!.docs
              .map((DocumentSnapshot document) {
                Map<String, dynamic> data =
                    document.data()! as Map<String, dynamic>;
                return ListTile(
                  title: Text(data['full_name']),
                  subtitle: Text(data['company']),
                );
              })
              .toList()
              .cast(),
        );
      },
    );
  }
}
// [EMD listen_to_realtime_updates_listen_for_updates2]

import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/material.dart';

// [START listen_to_realtime_updates_listen_for_updates2]
class UserInformation extends StatefulWidget {
  @override
  _UserInformationState createState() => _UserInformationState();
}

class _UserInformationState extends State<UserInformation> {
  final Stream<QuerySnapshot> _usersStream =
      FirebaseFirestore.instance.collection('users').snapshots();

  @override
  Widget build(BuildContext context) {
    return StreamBuilder<QuerySnapshot>(
      stream: _usersStream,
      builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) {
        if (snapshot.hasError) {
          return const Text('Something went wrong');
        }

        if (snapshot.connectionState == ConnectionState.waiting) {
          return const Text("Loading");
        }

        return ListView(
          children: snapshot.data!.docs
              .map((DocumentSnapshot document) {
                Map<String, dynamic> data =
                    document.data()! as Map<String, dynamic>;
                return ListTile(
                  title: Text(data['full_name']),
                  subtitle: Text(data['company']),
                );
              })
              .toList()
              .cast(),
        );
      },
    );
  }
}
// [END listen_to_realtime_updates_listen_for_updates2]

Fix typo in region tag

Fix typo in region tag


import 'dart:ui';

import 'package:flutter/material.dart';

import 'poster_chooser.dart';

class PosterCard extends StatelessWidget {
  final dynamic item;
  final Widget details;

  const PosterCard({
    Key key,
    @required this.item,
    @required this.details,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Card(
      child: ClipRRect(
        borderRadius: BorderRadius.circular(4),
        child: Container(
          height: 100,
          child: Stack(
            children: [
              Positioned.fill(
                child: ImageFiltered(
                  imageFilter: ImageFilter.blur(
                    sigmaX: 25,
                    sigmaY: 25,
                  ),
                  child: Image.network(
                    item.posterUrl != null ? item.posterUrl : '',
                    fit: BoxFit.cover,
                  ),
                ),
              ),
              Container(
                color: Colors.black.withOpacity(0.4),
              ),
              Padding(
                padding: const EdgeInsets.all(4),
                child: Row(
                  children: [
                    PosterChooser(item: item),
                    Expanded(
                      child: Padding(
                        padding: const EdgeInsets.only(left: 6),
                        child: details,
                      ),
                    ),
                  ],
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

import 'dart:ui';

import 'package:flutter/material.dart';

import 'poster_chooser.dart';

class PosterCard extends StatelessWidget {
  final dynamic item;
  final Widget details;
  final Key heroTag;

  const PosterCard({
    Key key,
    @required this.item,
    @required this.details,
    this.heroTag,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Card(
      child: ClipRRect(
        borderRadius: BorderRadius.circular(4),
        child: Container(
          height: 100,
          child: Stack(
            children: [
              Positioned.fill(
                child: ImageFiltered(
                  imageFilter: ImageFilter.blur(
                    sigmaX: 25,
                    sigmaY: 25,
                  ),
                  child: Image.network(
                    item.posterUrl != null ? item.posterUrl : '',
                    fit: BoxFit.cover,
                  ),
                ),
              ),
              Container(
                color: Colors.black.withOpacity(0.4),
              ),
              Padding(
                padding: const EdgeInsets.all(4),
                child: Row(
                  children: [
                    Hero(
                      tag: heroTag ?? UniqueKey(),
                      child: PosterChooser(item: item),
                    ),
                    Expanded(
                      child: Padding(
                        padding: const EdgeInsets.only(left: 6),
                        child: details,
                      ),
                    ),
                  ],
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

Add Hero widget support to PosterCard.

Add Hero widget support to PosterCard.


// Copyright (c) 2013, the Dart project authors.  Please see the AUTHORS d.file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

library pub_tests;

import 'package:scheduled_test/scheduled_test.dart';

import '../descriptor.dart' as d;
import '../test_pub.dart';
import '../serve/utils.dart';

main() {
  initConfig();

  // An import error will cause the isolate API to fail synchronously while
  // loading the transformer.
  integration("fails to load a transform with an import error", () {
    d.dir(appPath, [
      d.pubspec({
        "name": "myapp",
        "transformers": ["myapp/src/transformer"]
      }),
      d.dir("lib", [d.dir("src", [
        d.file("transformer.dart", "import 'does/not/exist.dart';")
      ])])
    ]).create();

    createLockFile('myapp', pkg: ['barback']);
    var pub = startPubServe();
    pub.stderr.expect(endsWith("error: line 1 pos 1: library handler failed"));
    pub.shouldExit(1);
  });
}

// Copyright (c) 2013, the Dart project authors.  Please see the AUTHORS d.file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

library pub_tests;

import 'package:scheduled_test/scheduled_test.dart';

import '../descriptor.dart' as d;
import '../test_pub.dart';
import '../serve/utils.dart';

main() {
  initConfig();

  // An import error will cause the isolate API to fail synchronously while
  // loading the transformer.
  integration("fails to load a transform with an import error", () {
    d.dir(appPath, [
      d.pubspec({
        "name": "myapp",
        "transformers": ["myapp/src/transformer"]
      }),
      d.dir("lib", [d.dir("src", [
        d.file("transformer.dart", "import 'does/not/exist.dart';")
      ])])
    ]).create();

    createLockFile('myapp', pkg: ['barback']);
    var pub = startPubServe();
    pub.stderr.expect("'Unhandled exception:");
    pub.stderr.expect(startsWith("Failure getting "));
    pub.shouldExit(1);
  });
}

Fix another transformer load error test.

R=rnystrom@google.com
TBR

Review URL: https://codereview.chromium.org//302433002

git-svn-id: a962b240025cf0577aa172e20f49ccb159ba6be1@36604 260f80e4-7a28-3924-810f-c04153c831b5


// Copyright (c) 2013, the Dart project authors.  Please see the AUTHORS d.file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

library pub_tests;

import 'package:scheduled_test/scheduled_stream.dart';
import 'package:scheduled_test/scheduled_test.dart';

import '../descriptor.dart' as d;
import '../test_pub.dart';
import '../serve/utils.dart';

main() {
  initConfig();

  // A syntax error will cause the analyzer to fail to parse the transformer
  // when attempting to rewrite its imports.
  integration("fails to load a transform with a syntax error", () {
    d.dir(appPath, [
      d.pubspec({
        "name": "myapp",
        "transformers": ["myapp/src/transformer"]
      }),
      d.dir("lib", [d.dir("src", [
        d.file("transformer.dart", "syntax error")
      ])])
    ]).create();

    createLockFile('myapp', pkg: ['barback']);

    var pub = startPubServe();
    pub.stderr.expect(startsWith('Error on line'));
    pub.shouldExit(1);
    pub.stderr.expect(never(contains('This is an unexpected error')));
  });
}

// Copyright (c) 2013, the Dart project authors.  Please see the AUTHORS d.file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

library pub_tests;

import 'package:scheduled_test/scheduled_stream.dart';
import 'package:scheduled_test/scheduled_test.dart';

import '../descriptor.dart' as d;
import '../test_pub.dart';
import '../serve/utils.dart';

main() {
  initConfig();

  // A syntax error will cause the analyzer to fail to parse the transformer
  // when attempting to rewrite its imports.
  integration("fails to load a transform with a syntax error", () {
    d.dir(appPath, [
      d.pubspec({
        "name": "myapp",
        "transformers": ["myapp/src/transformer"]
      }),
      d.dir("lib", [d.dir("src", [
        d.file("transformer.dart", "syntax error")
      ])])
    ]).create();

    createLockFile('myapp', pkg: ['barback']);

    var pub = startPubServe();
    pub.stderr.expect(startsWith('Error in'));
    pub.shouldExit(1);
    pub.stderr.expect(never(contains('This is an unexpected error')));
  });
}

Fix test for analyzer error message.

Fix test for analyzer error message.

BUG=
R=nweiz@google.com

Review URL: https://codereview.chromium.org//192753005

git-svn-id: c93d8a2297af3b929165606efe145742a534bc71@33507 260f80e4-7a28-3924-810f-c04153c831b5


// Copyright (c) 2013, the Dart project authors.  Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

library barback.test.transformer.bad;

import 'dart:async';

import 'package:barback/barback.dart';
import 'package:barback/src/utils.dart';

import 'mock.dart';

/// A transformer that tries to load a secondary input and catches an
/// [AssetNotFoundException] if the input doesn't exist.
class CatchAssetNotFoundTransformer extends MockTransformer {
  /// The extension of assets this applies to.
  final String extension;

  /// The id of the secondary input to load.
  final AssetId input;

  CatchAssetNotFoundTransformer(this.extension, String input)
      : input = new AssetId.parse(input);

  Future<bool> doIsPrimary(Asset asset) =>
      new Future.value(asset.id.extension == extension);

  Future doApply(Transform transform) {
    return transform.getInput(input).then((_) {
      transform.addOutput(new Asset.fromString(
          transform.primaryInput.id, "success"));
    }).catchError((e) {
      if (e is! AssetNotFoundException) throw e;
      transform.addOutput(new Asset.fromString(
          transform.primaryInput.id, "failed to load $input"));
    });
  }
}

// Copyright (c) 2013, the Dart project authors.  Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

library barback.test.transformer.catch_asset_not_found;

import 'dart:async';

import 'package:barback/barback.dart';
import 'package:barback/src/utils.dart';

import 'mock.dart';

/// A transformer that tries to load a secondary input and catches an
/// [AssetNotFoundException] if the input doesn't exist.
class CatchAssetNotFoundTransformer extends MockTransformer {
  /// The extension of assets this applies to.
  final String extension;

  /// The id of the secondary input to load.
  final AssetId input;

  CatchAssetNotFoundTransformer(this.extension, String input)
      : input = new AssetId.parse(input);

  Future<bool> doIsPrimary(Asset asset) =>
      new Future.value(asset.id.extension == extension);

  Future doApply(Transform transform) {
    return transform.getInput(input).then((_) {
      transform.addOutput(new Asset.fromString(
          transform.primaryInput.id, "success"));
    }).catchError((e) {
      if (e is! AssetNotFoundException) throw e;
      transform.addOutput(new Asset.fromString(
          transform.primaryInput.id, "failed to load $input"));
    });
  }
}

Fix an analyzer warning in barback.

Fix an analyzer warning in barback.

R=rnystrom@google.com
BUG=

Review URL: https://codereview.chromium.org//196573013

git-svn-id: c93d8a2297af3b929165606efe145742a534bc71@33678 260f80e4-7a28-3924-810f-c04153c831b5


// Copyright (c) 2021, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

import "dart:async";

T id<T>(T value) => value;

main() async {
  FutureOr<int> x = 1 + id(1); // Should work, gives error.

  // Checking it!
  FutureOr<int> y = 1 + id(1)
    ..checkStaticType<Exactly<int>>();
  FutureOr<int> z = 1 + contextType(1)
    ..checkStaticType<Exactly<int>>();
}

extension<T> on T {
  void checkStaticType<R extends Exactly<T>>() {}
}

typedef Exactly<T> = T Function(T);
T contextType<T>(Object? o) => o as T;

// Copyright (c) 2021, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

import "dart:async";

T id<T>(T value) => value;

main() async {
  FutureOr<int> x = 1 + id(1);

  FutureOr<int> y = 1 + id(1)
    ..checkStaticType<Exactly<int>>();
  FutureOr<int> z = 1 + contextType(1)
    ..checkStaticType<Exactly<int>>();
}

extension<T> on T {
  void checkStaticType<R extends Exactly<T>>() {}
}

typedef Exactly<T> = T Function(T);
T contextType<T>(Object? o) => o as T;

Remove misleading comment from test

[cfe] Remove misleading comment from test

Change-Id: I97392718faf380d1431e76e808bbe775e25e3d4e
Reviewed-on: https://dart-review.googlesource.com/c/sdk/+/177860
Reviewed-by: Dmitry Stefantsov <95a4b7e39916a54bd6477bec6a6de014b977db32@google.com>
Commit-Queue: Johnni Winther <0f64ef784d57ffb064b634040f9eeba0d33d0be4@google.com>


// Copyright (c) 2015, the Dart project authors.  Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

import 'package:logging/logging.dart' as logging;

logging.Logger _logger = new logging.Logger("sintr_common");

info(String message) => _logger.info(message);
trace(String message) => _logger.finer(message);
debug(String message) => _logger.fine(message);
alert(String message) => _logger.shout(message);

perf(String name, int ms) => _logger.fine("PERF: $name : $ms");

/// Setup log streaming to the right place for local and remote deployment.
setupLogging() {
  // TODO(lukechurch): Add support for container logs
  _setupLocalLogging();
}

/// Setup log streaming to stdOut.
_setupLocalLogging() {
  // Setup the logging
  logging.hierarchicalLoggingEnabled = false;
  logging.Logger.root.level = logging.Level.FINE;
  logging.Logger.root.onRecord.listen((logging.LogRecord rec) {
    print('${rec.level.name}: ${rec.time}: ${rec.message}');
  });
}

// Copyright (c) 2015, the Dart project authors.  Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

import 'package:logging/logging.dart' as logging;

logging.Logger _logger = new logging.Logger("sintr_common");

info(String message) => _logger.info(message);
trace(String message) => _logger.finer(message);
debug(String message) => _logger.fine(message);
alert(String message) => _logger.shout(message);

perf(String name, int ms) => _logger.fine("PERF: $name : $ms");

/// Setup log streaming to the right place for local and remote deployment.
setupLogging() {
  // TODO(lukechurch): Add support for container logs
  _setupLocalLogging();
}

/// Setup log streaming to stdOut.
_setupLocalLogging() {
  // Setup the logging
  logging.hierarchicalLoggingEnabled = false;
  logging.Logger.root.level = logging.Level.FINER;
  logging.Logger.root.onRecord.listen((logging.LogRecord rec) {
    print('${rec.level.name}: ${rec.time}: ${rec.message}');
  });
}

Increase logging level on worker nodes

Increase logging level on worker nodes


import 'package:endpoints/endpoints.dart';
import 'package:appengine/appengine.dart';
import 'package:shelf/shelf.dart';
import 'package:shelf_appengine/shelf_appengine.dart' as shelf_ae;
import 'tictactoe_api.dart';

_handler(Request request) {
  var headers = {'Content-Type' : 'text/plain'};

  if (request.url.toString() != '/') {
    return ApiServer.cascadeResponse;
  }

  return context.assets.read('/index.html').then((stream) {
    return new Response.ok(stream);
  });
}

void main() {
  var api_server = new ApiServer();
  api_server.addApi(new TicTacToe());
  var cascade = new Cascade(statusCodes: [501])
    .add(api_server.handler)
    .add(_handler)
    .add(shelf_ae.assetHandler);

  shelf_ae.serve(cascade.handler);
}

import 'package:endpoints/endpoints.dart';
import 'package:appengine/appengine.dart';
import 'tictactoe_api.dart';

import 'dart:io';

ApiServer api_server;

_handler(HttpRequest request) {
  if (request.uri.path.startsWith('/_ah/spi/')) {
    api_server.handleRequest(request);
    return;
  }
  if (request.uri.path == '/') {
    context.assets.serve(request.response, '/index.html');
    return;
  }
  context.assets.serve(request.response, request.uri.path);
}

void main() {
  api_server = new ApiServer();
  api_server.addApi(new TicTacToe());
  runAppEngine(_handler).then((_) {
    // Server running.
  });
}

Use normal request handler instead of shelf


// Copyright (c) 2013, the Dart project authors.  Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
//
// Process test program to test process communication.
//
// VMOptions=
// VMOptions=--short_socket_read
// VMOptions=--short_socket_write
// VMOptions=--short_socket_read --short_socket_write

import "package:expect/expect.dart";
import 'dart:async';
import 'dart:io';
import 'dart:math';

import "process_test_util.dart";

void test(Future<Process> future, int expectedExitCode) {
  future.then((process) {
    process.exitCode.then((exitCode) {
      Expect.equals(expectedExitCode, exitCode);
    });

    process.stdout.listen((_) {});
    process.stderr.listen((_) {});
    process.stdin.writeln("Line1");
  });
}

main() {
  var scriptName = "process_stdin_transform_unsubscribe_script.dart";
  var scriptFile = new File("tests/standalone/io/$scriptName");
  if (!scriptFile.existsSync()) {
    scriptFile = new File("../tests/standalone/io/$scriptName");
  }
  Expect.isTrue(scriptFile.existsSync());
  test(Process.start(Platform.executable, [scriptFile.path]), 0);
}

// Copyright (c) 2013, the Dart project authors.  Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
//
// Process test program to test process communication.
//
// VMOptions=
// VMOptions=--short_socket_read
// VMOptions=--short_socket_write
// VMOptions=--short_socket_read --short_socket_write

import "package:expect/expect.dart";
import 'dart:async';
import 'dart:io';
import 'dart:math';

import "process_test_util.dart";

void test(Future<Process> future, int expectedExitCode) {
  future.then((process) {
    process.exitCode.then((exitCode) {
      Expect.equals(expectedExitCode, exitCode);
    });

    process.stdout.listen((_) {});
    process.stderr.listen((_) {});
    process.stdin.writeln("Line1");
    process.stdin.flush().then((_) {
      print("flush completed");
    });
  });
}

main() {
  var scriptName = "process_stdin_transform_unsubscribe_script.dart";
  var scriptFile = new File("tests/standalone/io/$scriptName");
  if (!scriptFile.existsSync()) {
    scriptFile = new File("../tests/standalone/io/$scriptName");
  }
  Expect.isTrue(scriptFile.existsSync());
  test(Process.start(Platform.executable, [scriptFile.path]), 0);
}

Add call to flush() to avoid flakiness

Add call to flush() to avoid flakiness

Related to #28558.

R=zra@google.com

Review-Url: https://codereview.chromium.org/2688243003 .


import 'dart:io';
import 'package:expect/minitest.dart';
import 'package:dev_compiler/src/kernel/command.dart';

main(List<String> args) {
  // Various URL schemes
  expect(stringToUri("dart:io").toString(), "dart:io");
  expect(stringToUri("package:expect/minitest.dart").toString(),
      "package:expect/minitest.dart");
  expect(stringToUri("foobar:whatnot").toString(), "foobar:whatnot");

  // Full Windows path
  expect(stringToUri("C:\\full\\windows\\path.foo", windows: true).toString(),
      "file:///C:/full/windows/path.foo");
  expect(stringToUri("C:/full/windows/path.foo", windows: true).toString(),
      "file:///C:/full/windows/path.foo");

  // Relative Windows path
  expect(
      stringToUri("partial\\windows\\path.foo", windows: true).toString(),
      "file://${Directory.current.path.replaceAll(r'\', r'/')}"
      "/partial/windows/path.foo");

  // Full Unix path
  expect(stringToUri("/full/path/to/foo.bar", windows: false).toString(),
      "file:///full/path/to/foo.bar");

  // Relative Unix path
  expect(
      stringToUri("partial/path/to/foo.bar", windows: false).toString(),
      "file://${Directory.current.path.replaceAll(r'\', r'/')}"
      "/partial/path/to/foo.bar");
}

import 'dart:io';
import 'package:expect/minitest.dart';
import 'package:dev_compiler/src/kernel/command.dart';

main(List<String> args) {
  // Various URL schemes
  expect(stringToUri("dart:io").toString(), "dart:io");
  expect(stringToUri("package:expect/minitest.dart").toString(),
      "package:expect/minitest.dart");
  expect(stringToUri("foobar:whatnot").toString(), "foobar:whatnot");

  // Full Windows path
  expect(stringToUri("C:\\full\\windows\\path.foo", windows: true).toString(),
      "file:///C:/full/windows/path.foo");
  expect(stringToUri("C:/full/windows/path.foo", windows: true).toString(),
      "file:///C:/full/windows/path.foo");

  // Relative Windows path
  expect(stringToUri("partial\\windows\\path.foo", windows: true).toString(),
      "file://${Directory.current.path}/partial/windows/path.foo");

  // Full Unix path
  expect(stringToUri("/full/path/to/foo.bar", windows: false).toString(),
      "file:///full/path/to/foo.bar");

  // Relative Unix path
  expect(stringToUri("partial/path/to/foo.bar", windows: false).toString(),
      "file://${Directory.current.path}/partial/path/to/foo.bar");
}

Revert "Fixup DDC test on Windows"

Revert "Fixup DDC test on Windows"

This reverts commit 70020cd30d9c8d4b42c42b702df2cf2bf6a77d18.

Reason for revert: Didn't quite work.

Original change's description:
> Fixup DDC test on Windows
>
> Directory.current.path on Windows uses "\" and not "/".
>
> Bug:
> Change-Id: I6ef789d586622f78d0401c1a892f6a475bf6d93a
> Reviewed-on: https://dart-review.googlesource.com/34100
> Reviewed-by: Jens Johansen <05223a3c6bdf76af6f84755eae231abeebcf4530@google.com>

TBR=dmitryas@google.com,05223a3c6bdf76af6f84755eae231abeebcf4530@google.com

Change-Id: Ied8897801005f1a1b83075c1fb2a0b905129bb18
No-Presubmit: true
No-Tree-Checks: true
No-Try: true
Reviewed-on: https://dart-review.googlesource.com/34001
Reviewed-by: Jens Johansen <05223a3c6bdf76af6f84755eae231abeebcf4530@google.com>
Commit-Queue: Jens Johansen <05223a3c6bdf76af6f84755eae231abeebcf4530@google.com>


import 'dart:async';
import 'dart:io';
import 'dart:math';

import 'package:json_rpc_2/json_rpc_2.dart';

import 'package:dart_language_server/dart_language_server.dart';

final random = new Random();

Future main() async {
  var log = new File('/tmp/wirelog.txt').openWrite();
  var channel = new StdIOStreamChannel();
  var logged = wireLog(channel, log);
  Timer timer;
  var server = new Peer(logged);
  server
    ..registerMethod('random_ints', (params) {
      return _randomInts(params['count'].value).toList();
    })
    ..registerMethod('start_notifications', () {
      timer ??= new Timer.periodic(const Duration(seconds: 3), (_) {
        server.sendNotification('some_notification', _randomInts(2));
      });
    })
    ..registerMethod('stop_notifications', () {
      timer?.cancel();
      timer = null;
    })
    ..registerFallback(([params]) {
      return 'fallback for "${params.method}" with params ${params.value}';
    });
  await server.listen();
  timer?.cancel();
  log.write('Done\n');
  log.close();
}

Iterable<int> _randomInts(int count) sync* {
  for (var i = 0; i < count; i++) {
    yield random.nextInt(100);
  }
}

import 'dart:async';
import 'dart:io';
import 'dart:math';

import 'package:json_rpc_2/json_rpc_2.dart';

import 'package:dart_language_server/dart_language_server.dart';

final random = new Random();

Future main() async {
  var log = new File('/tmp/wirelog.txt').openWrite();
  var channel = new StdIOStreamChannel();
  var logged = wireLog(channel, log);
  Timer timer;
  bool hasShutdown = false;
  var server = new Peer(logged);
  server
    ..registerMethod('shutdown', () {
      hasShutdown = true;
    })
    ..registerMethod('exit', () {
      server.close();
    })
    ..registerMethod('random_ints', (params) {
      return _randomInts(params['count'].value).toList();
    })
    ..registerMethod('start_notifications', () {
      timer ??= new Timer.periodic(const Duration(seconds: 3), (_) {
        server.sendNotification('some_notification', _randomInts(2));
      });
    })
    ..registerMethod('stop_notifications', () {
      timer?.cancel();
      timer = null;
    })
    ..registerFallback(([params]) {
      return 'fallback for "${params.method}" with params ${params.value}';
    });
  await server.listen();
  timer?.cancel();
  if (hasShutdown) {
    exitCode = 0;
  } else {
    exitCode = 1;
  }
  log.write('Done\n');
  log.close();
}

Iterable<int> _randomInts(int count) sync* {
  for (var i = 0; i < count; i++) {
    yield random.nextInt(100);
  }
}

Add `shutdown` and `exit` method handlers

This matches the language server protocol. Shutdown does not need to do
any useful cleanup. Correctly sets the exit code against the protocol
spec based on whether shutdown was called.


// Copyright (c) 2011, the Dart project authors.  Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

String getPlatformOutDir() {
  var os = new Platform().operatingSystem();
  if (os == 'linux') return 'out';
  if (os == 'macos') return 'xcodebuild';
  return '';  // Windows.
}

String getProcessTestFileName() {
  var outDir = getPlatformOutDir();
  var names = ['$outDir/Release_ia32/process_test',
               '$outDir/Debug_ia32/process_test'];

  for (var name in names) {
    if (new File(name).existsSync()) {
      return name;
    }
  }
  Expect.fail('Could not find the process_test executable.');
}

String getDartFileName() {
  var outDir = getPlatformOutDir();
  var names = ['$outDir/Release_ia32/dart',
               '$outDir/Debug_ia32/dart'];

  for (var name in names) {
    if (new File(name).existsSync()) {
      return name;
    }
  }
  Expect.fail('Could not find the dart executable.');
}

// Copyright (c) 2011, the Dart project authors.  Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

String getPlatformOutDir() {
  var os = new Platform().operatingSystem();
  if (os == 'linux') return 'out/';
  if (os == 'macos') return 'xcodebuild/';
  return '';  // Windows.
}

String getPlatformExecutableExtension() {
  var os = new Platform().operatingSystem();
  if (os == 'windows') return '.exe';
  return '';  // Linux and Mac OS.
}

String getProcessTestFileName() {
  var outDir = getPlatformOutDir();
  var extension = getPlatformExecutableExtension();
  var names = ['${outDir}Release_ia32/process_test$extension',
               '${outDir}Debug_ia32/process_test$extension'];

  for (var name in names) {
    if (new File(name).existsSync()) {
      return name;
    }
  }
  Expect.fail('Could not find the process_test executable.');
}

String getDartFileName() {
  var outDir = getPlatformOutDir();
  var extension = getPlatformExecutableExtension();
  var names = ['${outDir}Release_ia32/dart$extension',
               '${outDir}Debug_ia32/dart$extension'];

  for (var name in names) {
    if (new File(name).existsSync()) {
      return name;
    }
  }
  Expect.fail('Could not find the dart executable.');
}

Fix running process tests on Windows

Fix running process tests on Windows

TBR=ager@google.com

BUG=
TEST=

Review URL: http://codereview.chromium.org//8679008

git-svn-id: c93d8a2297af3b929165606efe145742a534bc71@1799 260f80e4-7a28-3924-810f-c04153c831b5


import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:toml/toml.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      theme: ThemeData(
        primarySwatch: Colors.blue,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key? key}) : super(key: key);

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('TOML example'),
      ),
      body: FutureBuilder<String>(
        future: rootBundle.loadString('assets/example.toml'),
        builder: (context, snapshot) {
          final text = snapshot.data;
          if (text == null) {
            return Center(
              child: CircularProgressIndicator(),
            );
          }
          final toml = TomlDocument.parse(text).toMap();
          return Center(
            child: Text(toml['str'] as String),
          );
        },
      ),
    );
  }
}

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:toml/toml.dart';

void main() {
  runApp(MyApp());
}

/// The main widget of the example application.
class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      theme: ThemeData(
        primarySwatch: Colors.blue,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: MyHomePage(),
    );
  }
}

/// The default route of [MyApp].
class MyHomePage extends StatelessWidget {
  /// Creates a [MyHomePage].
  MyHomePage({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('TOML example'),
      ),
      body: FutureBuilder<String>(
        future: rootBundle.loadString('assets/example.toml'),
        builder: (context, snapshot) {
          final text = snapshot.data;
          if (text == null) {
            return Center(
              child: CircularProgressIndicator(),
            );
          }
          final toml = TomlDocument.parse(text).toMap();
          return Center(
            child: Text(toml['str'] as String),
          );
        },
      ),
    );
  }
}

Fix lints of Flutter example

Fix lints of Flutter example


// Copyright (c) 2015, the Dart project authors.  Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

// Patch file for dart:developer library.

import 'dart:_js_helper' show patch, ForceInline;
import 'dart:_foreign_helper' show JS;

@patch
@ForceInline()
bool debugger({bool when: true, String message}) {
  if (when) {
    JS('', 'debugger');
  }
  return when;
}

@patch
Object inspect(Object object) {
  return object;
}

@patch
void log(String message,
         {DateTime time,
          int sequenceNumber,
          int level: 0,
          String name: '',
          Zone zone,
          Object error,
          StackTrace stackTrace}) {
  // TODO.
}

final _extensions = new Map<String, ServiceExtensionHandler>();

@patch
ServiceExtensionHandler _lookupExtension(String method) {
  return _extensions[method];
}

@patch
_registerExtension(String method, ServiceExtensionHandler handler) {
  _extensions[method] = handler;
}

@patch
int _getTraceClock() {
  // TODO.
  return _clockValue++;
}
int _clockValue = 0;

@patch
void _reportCompleteEvent(int start,
                          int end,
                          String category,
                          String name,
                          String argumentsAsJson) {
  // TODO.
}

@patch
int _getNextAsyncId() {
  return 0;
}

@patch
void _reportTaskEvent(int start,
                      int taskId,
                      String phase,
                      String category,
                      String name,
                      String argumentsAsJson) {
 // TODO.
}

Add missing patch methods to dart2js implementation of timeline

BUG=

Review URL: https://codereview.chromium.org/1400893002 .


import "package:polymorphic_bot/plugin.dart";
export "package:polymorphic_bot/plugin.dart";

@Command("reverse", allowVariables: true)
reverse(CommandEvent event) =>
    event.transform((input) => new String.fromCharCodes(input.codeUnits.reversed));

import "package:polymorphic_bot/plugin.dart";
export "package:polymorphic_bot/plugin.dart";

@Command("reverse", allowVariables: true)
reverse(CommandEvent event) =>
    event.transform((input) => flip(input));

Use Quiver for Reversing Strings

Use Quiver for Reversing Strings


library task;

class TaskNote {
  String notebody;
  TaskNote(this.notebody);
}

class Task {
  String summary;
  List<TaskNote> tasknotes = [];
  DateTime scheduled;
  Set<String> taskcategories = new Set();
  Task(this.summary, this.scheduled);

  void addNote(TaskNote note) {
    tasknotes.add(note);
  }

  void addCategory(String cat ) {
    taskcategories.add(cat);
  }
  void removeCategory(String cat) {
    taskcategories.remove(cat);
  }
}

library task;

class TaskNote {
  String notebody;
  TaskNote(this.notebody);
}

class Task {
  String summary;
  List<TaskNote> tasknotes = [];
  DateTime scheduled;
  int timestamp;
  Set<String> taskcategories = new Set();
  Task(this.summary, this.scheduled) {
    this.timestamp = new DateTime.now().millisecond;
  }

  void addNote(TaskNote note) {
    tasknotes.add(note);
  }

  void addCategory(String cat ) {
    taskcategories.add(cat);
  }
  void removeCategory(String cat) {
    taskcategories.remove(cat);
  }
}

Add timestamp to Task class.

Add timestamp to Task class.


// Copyright (c) 2014, the Dart project authors.  Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

import 'package:analysis_server/starter.dart';

/**
 * Create and run an analysis server.
 */
void main(List<String> args) {
  ServerStarter starter = new ServerStarter();
  starter.start(args);
}

// Copyright (c) 2014, the Dart project authors.  Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

import 'package:analysis_server/starter.dart';

/**
 * Create and run an analysis server.
 */
void main(List<String> args) async {
  ServerStarter starter = new ServerStarter();
  starter.start(args);
}

Normalize with the internal verison of this file.

Change-Id: I27d56a0f61bb68bfe9f0386dc7b140cdebba4522
Reviewed-on: https://dart-review.googlesource.com/72542
Reviewed-by: Brian Wilkerson <1f7641b6b14c52b9163524ab8d9aabff80176f21@google.com>
Commit-Queue: Devon Carew <e996497f4f2225f0ee7a9f4d1696ee710b488b66@google.com>


part of tmx;

class NodeDSL {
  XmlElement element;

  NodeDSL(this.element);

  static NodeDSL on(XmlElement element, Function fxn) {
    var node = new NodeDSL(element);
    fxn(node);
  }

  String strOr(String attrName, String defaultValue) {
    return _safely(attrName, defaultValue, (val) => val);
  }

  int intOr(String attrName, int defaultValue) {
    return _safely(attrName, defaultValue, (val) => int.parse(val) );
  }

  double doubleOr(String attrName, double defaultValue) {
    return _safely(attrName, defaultValue, (v) => double.parse(v));
  }

  bool boolOr(String attrName, bool defaultValue) {
    return _safely(attrName, defaultValue, (v) => v == "1");
  }

  _attr(String attrName) {
    return element.getAttribute(attrName);
  }

  _safely(String attrName, defaultValue, Function fxn) {
    String value = _attr(attrName);
    if (value != null) { return fxn(value); }
    return defaultValue;
  }
}

part of tmx;

class NodeDSL {
  XmlElement element;

  NodeDSL(this.element);

  static NodeDSL on(XmlElement element, Function fxn) {
    var node = new NodeDSL(element);
    fxn(node);
    return node;
  }

  String strOr(String attrName, String defaultValue) {
    return _safely(attrName, defaultValue, (val) => val);
  }

  int intOr(String attrName, int defaultValue) {
    return _safely(attrName, defaultValue, (val) => int.parse(val) );
  }

  double doubleOr(String attrName, double defaultValue) {
    return _safely(attrName, defaultValue, (v) => double.parse(v));
  }

  bool boolOr(String attrName, bool defaultValue) {
    return _safely(attrName, defaultValue, (v) => v == "1");
  }

  _attr(String attrName) {
    return element.getAttribute(attrName);
  }

  _safely(String attrName, defaultValue, Function fxn) {
    String value = _attr(attrName);
    if (value != null) { return fxn(value); }
    return defaultValue;
  }
}

Return a NodeDSL object from NodeDSL.on

Return a NodeDSL object from NodeDSL.on


// Copyright (c) 2014, Google Inc. Please see the AUTHORS file for details.
// All rights reserved. Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
library spark.services;

import 'dart:isolate';

import 'services.dart';

void main(List<String> args, SendPort sendPort) {
  final ServicesIsolate servicesIsolate = new ServicesIsolate(sendPort);
}

/**
 * This is a separate application spawned by Spark (via Services) as an isolate
 * for use in running long-running / heaving tasks.
 */
class ServicesIsolate {
  final SendPort sendPort;
  ServiceHandler handler;

  ServicesIsolate(this.sendPort) {
    print("This statement makes me crash"); // Remove this and isolate runs.
    ReceivePort receivePort = new ReceivePort();
    sendPort.send(receivePort.sendPort);
    handler = new ServiceHandler.worker(receivePort, sendPort);
  }
}

// Copyright (c) 2014, Google Inc. Please see the AUTHORS file for details.
// All rights reserved. Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
library spark.services;

import 'dart:isolate';

import 'services.dart';

void main(List<String> args, SendPort sendPort) {
  final ServicesIsolate servicesIsolate = new ServicesIsolate(sendPort);
}

/**
 * This is a separate application spawned by Spark (via Services) as an isolate
 * for use in running long-running / heaving tasks.
 */
class ServicesIsolate {
  final SendPort sendPort;
  ServiceHandler handler;

  ServicesIsolate(this.sendPort) {
    ReceivePort receivePort = new ReceivePort();
    sendPort.send(receivePort.sendPort);
    handler = new ServiceHandler.worker(receivePort, sendPort);
  }
}

Revert "This statement crashes the isolate."

This reverts commit 7cd8fdf8cb710042ff2e816db53da0c6c94cfc42.


import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:fluttertoast/fluttertoast.dart';

import '../../features/settings/presentation/bloc/settings_bloc.dart';

class DoubleTapToExit extends StatelessWidget {
  final Widget child;

  const DoubleTapToExit({
    Key? key,
    required this.child,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    DateTime? currentBackPressTime;

    return BlocBuilder<SettingsBloc, SettingsState>(
      builder: (context, state) {
        if (state is SettingsSuccess && state.appSettings.doubleTapToExit) {
          return WillPopScope(
            onWillPop: () {
              DateTime now = DateTime.now();

              if (currentBackPressTime == null ||
                  now.difference(currentBackPressTime!) >
                      const Duration(seconds: 2)) {
                currentBackPressTime = now;
                Fluttertoast.showToast(msg: 'Press again to exit app');
                return Future.value(false);
              }

              return Future.value(true);
            },
            child: child,
          );
        }
        return child;
      },
    );
  }
}

import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:fluttertoast/fluttertoast.dart';

import '../../features/settings/presentation/bloc/settings_bloc.dart';

class DoubleTapToExit extends StatelessWidget {
  final Widget child;

  const DoubleTapToExit({
    Key? key,
    required this.child,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    DateTime? currentBackPressTime;

    return BlocBuilder<SettingsBloc, SettingsState>(
      builder: (context, state) {
        if (state is SettingsSuccess && state.appSettings.doubleTapToExit) {
          return WillPopScope(
            onWillPop: () {
              DateTime now = DateTime.now();

              if (currentBackPressTime == null ||
                  now.difference(currentBackPressTime!) >
                      const Duration(seconds: 2)) {
                currentBackPressTime = now;
                Fluttertoast.showToast(
                  toastLength: Toast.LENGTH_SHORT,
                  msg: 'Press again to exit app',
                );
                return Future.value(false);
              }

              return Future.value(true);
            },
            child: child,
          );
        }
        return child;
      },
    );
  }
}

Reduce the length of the toast message.

Reduce the length of the toast message.


library common;

import 'dart:io';

final String BUILD_URL = '/build';
final String CLOSE_URL = '/close';
final String STATUS_URL = '/status';
final String BUILDLOG_FILE = '.buildlog';
final String BUILDLOCK_FILE = '.buildlock';
final String BUILD_DIR = 'build_out';
final String OUT_DIR = 'out';
final String SOURCE_PREFIX = '_source';

final ContentType JSON_TYPE = new ContentType('application', 'json');

final List<String> EXCLUDED_FILES = [
  BUILDLOG_FILE,
  BUILDLOCK_FILE,
  'pubspec.yaml',
  'pubspec.lock',
  'build.dart',
  '_build_server.dart',
];

final List<String> EXCLUDED_DIRS = [
  'packages',
];

bool isValidInputFile(String f) =>
    !(f.startsWith(BUILD_DIR) || EXCLUDED_FILES.contains(f));

library common;

import 'dart:io';

final String BUILD_URL = '/build';
final String CLOSE_URL = '/close';
final String STATUS_URL = '/status';
final String BUILDLOG_FILE = '.buildlog';
final String BUILDLOCK_FILE = '.buildlock';
final String BUILD_DIR = 'build_out';
final String OUT_DIR = 'out';
final String SOURCE_PREFIX = '_source';

final ContentType JSON_TYPE = new ContentType('application', 'json');

final List<String> EXCLUDED_FILES = [
  BUILDLOG_FILE,
  BUILDLOCK_FILE,
  'pubspec.yaml',
  'pubspec.lock',
  'build.dart',
  '_build_server.dart',
];

final List<String> EXCLUDED_DIRS = [
  'packages',
  '.git',
];

bool isValidInputFile(String f) =>
    !(f.startsWith(BUILD_DIR) || EXCLUDED_FILES.contains(f));

Add .git to excluded dirs

Add .git to excluded dirs


// Copyright (c) 2015, the Dart project authors.  Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

// @dart = 2.10

import '../universe/world_builder.dart' show SelectorConstraintsStrategy;
import '../world.dart';
import 'abstract_value_domain.dart';

/// Strategy for the abstraction of runtime values used by the global type
/// inference.
abstract class AbstractValueStrategy {
  /// Creates the abstract value domain for [closedWorld].
  AbstractValueDomain createDomain(covariant JClosedWorld closedWorld);

  /// Creates the [SelectorConstraintsStrategy] used by the backend enqueuer.
  SelectorConstraintsStrategy createSelectorStrategy();
}

// Copyright (c) 2015, the Dart project authors.  Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

import '../universe/world_builder.dart' show SelectorConstraintsStrategy;
import '../world_interfaces.dart';
import 'abstract_value_domain.dart';

/// Strategy for the abstraction of runtime values used by the global type
/// inference.
abstract class AbstractValueStrategy {
  /// Creates the abstract value domain for [closedWorld].
  AbstractValueDomain createDomain(covariant JClosedWorld closedWorld);

  /// Creates the [SelectorConstraintsStrategy] used by the backend enqueuer.
  SelectorConstraintsStrategy createSelectorStrategy();
}

[dart2js] Migrate abstract value strategy to null safety

Change-Id: Iae8a77663b3e87f7d05f7faa0c85bb8cf3bdfc9f
Reviewed-on: https://dart-review.googlesource.com/c/sdk/+/253003
Reviewed-by: Mayank Patke <e0355b78204b67a55a952941c68c8f1b40235938@google.com>
Commit-Queue: Sigmund Cherem <beaea8fd7d2a56555046ba4f362c8a93e3938576@google.com>


library angular2.examples.web_workers.todo.server_index;
import "index_common.dart" show TodoApp;
import "package:angular2/src/web_workers/debug_tools/multi_client_server_message_bus.dart";
import "package:angular2/src/web_workers/worker/application_common.dart"
  show bootstrapWebWorkerCommon;
import 'dart:io';
import "package:angular2/src/core/reflection/reflection_capabilities.dart";
import "package:angular2/src/core/reflection/reflection.dart";

void main() {
  reflector.reflectionCapabilities = new ReflectionCapabilities();
  HttpServer.bind('127.0.0.1', 1337).then((HttpServer server) {
    var bus = new MultiClientServerMessageBus.fromHttpServer(server);
    bootstrapWebWorkerCommon(TodoApp, bus).catchError((error) => throw error);
    print ("Server Listening for requests on 127.0.0.1:1337");
  });
}

library angular2.examples.web_workers.todo.server_index;
import "index_common.dart" show TodoApp;
import "package:angular2/src/web_workers/debug_tools/multi_client_server_message_bus.dart";
import "package:angular2/src/web_workers/worker/application_common.dart"
  show bootstrapWebWorkerCommon;
import 'dart:io';
import "package:angular2/src/core/reflection/reflection_capabilities.dart";
import "package:angular2/src/core/reflection/reflection.dart";
import "package:angular2/src/core/dom/html_adapter.dart";

void main() {
  Html5LibDomAdapter.makeCurrent();
  reflector.reflectionCapabilities = new ReflectionCapabilities();
  HttpServer.bind('127.0.0.1', 1337).then((HttpServer server) {
    var bus = new MultiClientServerMessageBus.fromHttpServer(server);
    bootstrapWebWorkerCommon(TodoApp, bus).catchError((error) => throw error);
    print ("Server Listening for requests on 127.0.0.1:1337");
  });
}

fix(WebWorker): Fix bug causing multi browser demo to crash

Closes #4839


import 'dart:async';

import 'package:drift/drift.dart';
import 'package:drift/src/runtime/executor/delayed_stream_queries.dart';
import 'package:drift/src/runtime/executor/stream_queries.dart';
import 'package:drift/src/runtime/executor/transactions.dart';
import 'package:meta/meta.dart';

part 'batch.dart';
part 'connection.dart';
part 'connection_user.dart';
part 'dao_base.dart';
part 'db_base.dart';
part 'stream_updates.dart';

/// Defines additional runtime behavior for drift. Changing the fields of this
/// class is rarely necessary.
class DriftRuntimeOptions {
  /// Don't warn when a database class isn't used as singleton.
  bool dontWarnAboutMultipleDatabases = false;

  /// The [ValueSerializer] that will be used by default in [DataClass.toJson].
  ValueSerializer defaultSerializer = const ValueSerializer.defaults();

  /// The function used by drift to emit debug prints.
  ///
  /// This is the function used with `logStatements: true` on databases and
  /// `debugLog` on isolates.
  void Function(String) debugPrint = print;
}

/// Stores the [DriftRuntimeOptions] describing global drift behavior across
/// databases.
///
/// Note that is is adapting this behavior is rarely needed.
DriftRuntimeOptions driftRuntimeOptions = DriftRuntimeOptions();

import 'dart:async';

import 'package:drift/drift.dart';
import 'package:drift/src/runtime/executor/delayed_stream_queries.dart';
import 'package:drift/src/runtime/executor/stream_queries.dart';
import 'package:drift/src/runtime/executor/transactions.dart';
import 'package:meta/meta.dart';

part 'batch.dart';
part 'connection.dart';
part 'connection_user.dart';
part 'dao_base.dart';
part 'db_base.dart';
part 'stream_updates.dart';

/// Defines additional runtime behavior for drift. Changing the fields of this
/// class is rarely necessary.
class DriftRuntimeOptions {
  /// Don't warn when a database class isn't used as singleton.
  bool dontWarnAboutMultipleDatabases = false;

  /// The [ValueSerializer] that will be used by default in [DataClass.toJson].
  ValueSerializer defaultSerializer = const ValueSerializer.defaults();

  /// The function used by drift to emit debug prints.
  ///
  /// This is the function used with `logStatements: true` on databases and
  /// `debugLog` on isolates.
  void Function(String) debugPrint = (text) =>
      RegExp('.{1,300}').allMatches(text).map((m) => m.group(0)).forEach(print);
}

/// Stores the [DriftRuntimeOptions] describing global drift behavior across
/// databases.
///
/// Note that is is adapting this behavior is rarely needed.
DriftRuntimeOptions driftRuntimeOptions = DriftRuntimeOptions();

Split debugPrint messages into 300 character chunks


// Copyright (c) 2016, the Dart project authors.  Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

import 'dart:html';

import 'package:angular/angular.dart';
import 'package:angular_components/material_button/material_button_base.dart';
import 'package:angular_components/material_ripple/material_ripple.dart';
import 'package:angular_components/material_tab/tab_mixin.dart';

/// A specialized button component used only by the tab strip.
@Component(
  selector: 'tab-button',
  template: r'''
          <div class="content">
            {{label}}
          </div>
          <material-ripple></material-ripple>
        ''',
  styleUrls: const ['tab_button.scss.css'],
  directives: const [MaterialRippleComponent],
)
class TabButtonComponent extends MaterialButtonBase with TabMixin {
  final Element _nativeElement;

  TabButtonComponent(this._nativeElement) : super(_nativeElement, 'tab');

  @override
  Element get nativeElement => _nativeElement;

  /// Whether the tab represented by this button is currently active.
  @Input('active')
  bool isActive;

  @HostBinding('class.focus')
  bool get hostClassFocus => visualFocus;

  @HostBinding('class.active')
  bool get hostClassActive => isActive || isMouseDown;
}

// Copyright (c) 2016, the Dart project authors.  Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

import 'dart:html';

import 'package:angular/angular.dart';
import 'package:angular_components/material_button/material_button_base.dart';
import 'package:angular_components/material_ripple/material_ripple.dart';
import 'package:angular_components/material_tab/tab_mixin.dart';

/// A specialized button component used only by the tab strip.
@Component(
  selector: 'tab-button',
  template: r'''
          <div class="content">
            {{label}}
          </div>
          <material-ripple></material-ripple>
        ''',
  styleUrls: const ['tab_button.scss.css'],
  directives: const [MaterialRippleComponent],
)
class TabButtonComponent extends MaterialButtonBase with TabMixin {
  final Element _nativeElement;

  TabButtonComponent(this._nativeElement) : super(_nativeElement, 'tab');

  @override
  Element get nativeElement => _nativeElement;

  /// Whether the tab represented by this button is currently active.
  @Input('active')
  bool isActive = false;

  @HostBinding('class.focus')
  bool get hostClassFocus => visualFocus;

  @HostBinding('class.active')
  bool get hostClassActive => isActive || isMouseDown;

  @HostBinding('attr.disabled')
  String get hostDisabled => disabled ? "" : null;
}

Support disabled attribute in tab button

PiperOrigin-RevId: 202175148


import 'package:meta/meta.dart';

import '../../../../core/api/tautulli_api/tautulli_api.dart' as tautulli_api;
import '../../../settings/presentation/bloc/settings_bloc.dart';

abstract class ImageUrlDataSource {
  Future<String> getImage({
    @required String tautulliId,
    String img,
    int ratingKey,
    int width,
    int height,
    int opacity,
    int background,
    int blur,
    String fallback,
    @required SettingsBloc settingsBloc,
  });
}

class ImageUrlDataSourceImpl implements ImageUrlDataSource {
  final tautulli_api.PmsImageProxy apiPmsImageProxy;

  ImageUrlDataSourceImpl({
    @required this.apiPmsImageProxy,
    String img,
    int ratingKey,
    int width,
    int height = 300,
    int opacity,
    int background,
    int blur,
    String fallback,
  });

  @override
  Future<String> getImage({
    @required String tautulliId,
    String img,
    int ratingKey,
    int width,
    int height,
    int opacity,
    int background,
    int blur,
    String fallback,
    @required SettingsBloc settingsBloc,
  }) async {
    final String url = await apiPmsImageProxy(
      tautulliId: tautulliId,
      img: img,
      ratingKey: ratingKey,
      width: width,
      height: height,
      opacity: opacity,
      background: background,
      blur: blur,
      fallback: fallback,
      settingsBloc: settingsBloc,
    );

    return url;
  }
}

import 'package:meta/meta.dart';

import '../../../../core/api/tautulli_api/tautulli_api.dart' as tautulli_api;
import '../../../settings/presentation/bloc/settings_bloc.dart';

abstract class ImageUrlDataSource {
  Future<String> getImage({
    @required String tautulliId,
    String img,
    int ratingKey,
    int width,
    int height,
    int opacity,
    int background,
    int blur,
    String fallback,
    @required SettingsBloc settingsBloc,
  });
}

class ImageUrlDataSourceImpl implements ImageUrlDataSource {
  final tautulli_api.PmsImageProxy apiPmsImageProxy;

  ImageUrlDataSourceImpl({
    @required this.apiPmsImageProxy,
    String img,
    int ratingKey,
    int width,
    int height,
    int opacity,
    int background,
    int blur,
    String fallback,
  });

  @override
  Future<String> getImage({
    @required String tautulliId,
    String img,
    int ratingKey,
    int width,
    int height,
    int opacity,
    int background,
    int blur,
    String fallback,
    @required SettingsBloc settingsBloc,
  }) async {
    final String url = await apiPmsImageProxy(
      tautulliId: tautulliId,
      img: img,
      ratingKey: ratingKey,
      width: width ?? 300,
      height: height ?? 450,
      opacity: opacity,
      background: background,
      blur: blur,
      fallback: fallback,
      settingsBloc: settingsBloc,
    );

    return url;
  }
}

Change default GetImageUrl height & width.

Fixes poster change in Tautulli not being reflected in Tautulli Remote.


// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

import 'dart:sky';

double timeBase = null;

void beginFrame(double timeStamp) {
  if (timeBase == null)
    timeBase = timeStamp;
  double delta = timeStamp - timeBase;
  PictureRecorder canvas = new PictureRecorder(view.width, view.height);
  canvas.translate(view.width / 2.0, view.height / 2.0);
  canvas.rotateDegrees(delta / 10);
  canvas.drawRect(new Rect.fromLTRB(-100.0, -100.0, 100.0, 100.0),
                  new Paint()..setARGB(255, 0, 255, 0));
  view.picture = canvas.endRecording();
  view.scheduleFrame();
}

void main() {
  view.setBeginFrameCallback(beginFrame);
  view.scheduleFrame();
}

// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

import 'dart:sky';

double timeBase = null;

void beginFrame(double timeStamp) {
  tracing.begin('beginFrame');
  if (timeBase == null)
    timeBase = timeStamp;
  double delta = timeStamp - timeBase;
  PictureRecorder canvas = new PictureRecorder(view.width, view.height);
  canvas.translate(view.width / 2.0, view.height / 2.0);
  canvas.rotateDegrees(delta / 10);
  canvas.drawRect(new Rect.fromLTRB(-100.0, -100.0, 100.0, 100.0),
                  new Paint()..setARGB(255, 0, 255, 0));
  view.picture = canvas.endRecording();
  view.scheduleFrame();
  tracing.end('beginFrame');
}

void main() {
  view.setBeginFrameCallback(beginFrame);
  view.scheduleFrame();
}

Make tracing work in the new .dart world.

R=abarth@chromium.org, viktorl@google.com

Review URL: https://codereview.chromium.org/1152483006


library new_task;

import 'dart:html';
import 'package:ddays/task.dart' show Task;
import 'package:ddays/storageservice.dart' show saveToStorage, STORAGE_KEY;

void saveTask(Event e) {
  e.preventDefault();
  InputElement summary = querySelector('[name="tsummary"]');
  Task task = new Task(summary.value.trim());

}

library new_task;

import 'dart:html';
import 'package:ddays/task.dart' show Task;
import 'package:ddays/storageservice.dart' show saveToStorage, STORAGE_KEY;
import 'package:ddays/list_tasks.dart' show displayTasks;

void saveTask(Event e) {
  e.preventDefault();
  InputElement summary = querySelector('[name="tsummary"]');
  Task task = new Task(summary.value.trim());
  saveToStorage({"summary": task.summary,
    "scheduled" : task.scheduled, "timestamp" : task.timestamp});
  summary.value = '';
  displayTasks();

}

Refresh task list view when new task is submitted