part of test.core;

gameTest() {
  group("Game constructor", () {
    Game game;
    setUp((){
      game = new Game();
    });
    tearDown((){
      game = null;
    });
    test("Instance of", () {
      expect(game.canvas, new isInstanceOf<CanvasElement>());

      expect(game.stage, new isInstanceOf<StageXL.Stage>());
      expect(game.renderLoop, new isInstanceOf<StageXL.RenderLoop>());
      expect(game.resourceManager, new isInstanceOf<StageXL.ResourceManager>());

      expect(game.stateManager, new isInstanceOf<StateManager>());
      expect(game.add, new isInstanceOf<GameObjectFactory>());
      expect(game.physics, new isInstanceOf<PhysicsSystem>());
      expect(game.world, new isInstanceOf<World>());
      expect(game.camera, new isInstanceOf<Camera>());
      expect(game.keyboard, new isInstanceOf<Keyboard>());
      expect(game.touch, new isInstanceOf<Touch>());
    });
    test("Default settings", () {
      expect(game.canvas.attributes["screencanvas"] == "true", isTrue);
      expect(game.canvas.width, equals(Game.DEFAULT_WIDTH));
      expect(game.canvas.height, equals(Game.DEFAULT_HEIGHT));
    });
  });
}

part of test.core;

gameTest() {
  group("Game constructor", () {
    Game game;
    setUp((){
      game = new Game();
    });
    tearDown((){
      game = null;
    });
    test("Instance of", () {
      expect(game.canvas, new isInstanceOf<CanvasElement>());

      expect(game.stage, new isInstanceOf<StageXL.Stage>());
      expect(game.renderLoop, new isInstanceOf<StageXL.RenderLoop>());
      expect(game.resourceManager, new isInstanceOf<StageXL.ResourceManager>());

      expect(game.stateManager, new isInstanceOf<StateManager>());
      expect(game.add, new isInstanceOf<GameObjectFactory>());
      expect(game.physics, new isInstanceOf<PhysicsSystem>());
      expect(game.world, new isInstanceOf<World>());
      expect(game.camera, new isInstanceOf<Camera>());
      expect(game.keyboard, new isInstanceOf<Keyboard>());
      expect(game.touch, new isInstanceOf<Touch>());
    });
    test("Default settings", () {
      expect(game.canvas.attributes["screencanvas"] == "true", isTrue);
      expect(game.canvas.width, equals(Game.DEFAULT_WIDTH));
      expect(game.canvas.height, equals(Game.DEFAULT_HEIGHT));

      expect(game.stage.align, equals(StageXL.StageAlign.NONE));
      expect(game.stage.scaleMode, equals(StageXL.StageScaleMode.SHOW_ALL));
      expect(game.stage.focus, equals(game.world));
    });
    //TODO: Why does this work? Need to make it better.
    test("Fullscreen", () {
      game = new Game(fullScreen:true);
      expect(game.canvas.width, equals(Game.DEFAULT_WIDTH * Game.DEFAULT_MIN_SCALE));
      expect(game.canvas.height, equals(Game.DEFAULT_HEIGHT * Game.DEFAULT_MIN_SCALE));
    });
  });
}

Add full screen test and more details to default settings test.


// Copyright 2014 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 freecell.tableau;

import '../deck/deck.dart';

part 'pile.dart';
part 'column.dart';
part 'cell.dart';
part 'tower.dart';

const int kNumberOfColumns = 8;
const int kNumberOfCells = 4;
const int kNumberOfTowers = 4;

class Tableau {
  List<Column> columns;
  List<Cell> cells;
  List<Tower> towers;

  Tableau() {
    columns = new List<Column>.from(
        new Iterable.generate(kNumberOfColumns, (i) => new Column()));
    cells = new List<Cell>.from(
        new Iterable.generate(kNumberOfCells, (i) => new Cell()));
    towers = new List<Tower>.from(
        new Iterable.generate(kNumberOfTowers, (i) => new Tower()));
  }

  void deal(Deck deck) {
    int i = 0;
    while (!deck.isEmpty) {
      Card card = deck.takeNext();
      columns[i]._deal(card);
      i = (i + 1) % kNumberOfColumns;
    }
  }
}

// Copyright 2014 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 freecell.tableau;

import '../deck/deck.dart';

part 'pile.dart';
part 'column.dart';
part 'cell.dart';
part 'tower.dart';

const int kNumberOfColumns = 8;
const int kNumberOfCells = 4;
const int kNumberOfTowers = 4;

class Tableau {
  List<Column> columns;
  List<Cell> cells;
  List<Tower> towers;

  Tableau() {
    columns = new List<Column>.from(
        new Iterable.generate(kNumberOfColumns, (i) => new Column()));
    cells = new List<Cell>.from(
        new Iterable.generate(kNumberOfCells, (i) => new Cell()));
    towers = new List<Tower>.from(
        new Iterable.generate(kNumberOfTowers, (i) => new Tower()));
  }

  bool get hasWon() {
    return towers.every((tower) => tower.isFull);
  }

  void deal(Deck deck) {
    int i = 0;
    while (!deck.isEmpty) {
      Card card = deck.takeNext();
      columns[i]._deal(card);
      i = (i + 1) % kNumberOfColumns;
    }
  }
}

Add a getter to tell when you've wone

Add a getter to tell when you've wone


part of streamy.runtime;

/// Produces an entity from a given JSON map
typedef Entity EntityFactory(Map json);

/// Information about a type generated from a discovery document
class TypeInfo {
  final EntityFactory _ef;
  TypeInfo(this._ef);
  Entity fromJson(Map json) => this._ef(json);
}

/// A sentinel value which indicates that an RPC returned an error.
class _ErrorEntity implements Entity {

  const _ErrorEntity();

  operator[](key) => throw "Not implemented";
  operator[]=(key, value) {
    throw "Not implemented";
  }
  toJson() => throw "Not implemented";
  clone() => throw "Not implemented";
  contains(key) => throw "Not implemented";
  remove(key) => throw "Not implemented";
  get local => throw "Not implemented";
  get fieldNames => throw "Not implemented";
  get streamyType => throw "Not implemented";
  get streamy => throw "Not implemented";

  bool equals(Object other) => other is _ErrorEntity;
  int get hashCode => "error".hashCode;
  toString() => "Internal Streamy sentinel value - should not be exposed.";
}

const _INTERNAL_ERROR = const _ErrorEntity();

/// Walk a map-like structure through a list of keys, beginning with an initial value.
_walk(initial, pieces) => pieces.fold(initial,
      (current, keyPiece) => current != null ? current[keyPiece] : null);

part of streamy.runtime;

/// Produces an entity from a given JSON map
typedef Entity EntityFactory(Map json);

/// Information about a type generated from a discovery document
class TypeInfo {
  final EntityFactory _ef;
  TypeInfo(this._ef);
  Entity fromJson(Map json) => this._ef(json);
}

/// A sentinel value which indicates that an RPC returned an error.
class _ErrorEntity implements Entity {

  const _ErrorEntity();

  operator[](key) => throw "Not implemented";
  operator[]=(key, value) {
    throw "Not implemented";
  }
  toJson() => throw "Not implemented";
  clone() => throw "Not implemented";
  @deprecated  // defined here solely to conform to the interface
  contains(key) => throw "Not implemented";
  containsKey(key) => throw "Not implemented";
  remove(key) => throw "Not implemented";
  get local => throw "Not implemented";
  get fieldNames => throw "Not implemented";
  get streamyType => throw "Not implemented";
  get streamy => throw "Not implemented";

  bool equals(Object other) => other is _ErrorEntity;
  int get hashCode => "error".hashCode;
  toString() => "Internal Streamy sentinel value - should not be exposed.";
}

const _INTERNAL_ERROR = const _ErrorEntity();

/// Walk a map-like structure through a list of keys, beginning with an initial value.
_walk(initial, pieces) => pieces.fold(initial,
      (current, keyPiece) => current != null ? current[keyPiece] : null);

Add missing containsKey to _ErrorEntity

Add missing containsKey to _ErrorEntity


// 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:mojo_application';
import 'dart:mojo_bindings';
import 'dart:mojo_core';

import 'package:mojo/services/console/public/interfaces/console.mojom.dart';

class ConsoleApplication extends Application {
  ConsoleProxy _proxy;

  ConsoleApplication.fromHandle(MojoHandle handle) : super.fromHandle(handle);

  void initialize(List<String> args) {
    _proxy = new ConsoleProxy.unbound();
    connectToService("mojo:console", _proxy);

    _proxy.readLine().then((result) {
        _proxy.printLines([result.line]).then((result) {
            _proxy.close();
            close();
          });
      });
  }
}

main(List args) {
  var appHandle = new MojoHandle(args[0]);
  var consoleApplication = new ConsoleApplication.fromHandle(appHandle);
  consoleApplication.listen();
}

// 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:async';
import 'dart:mojo_application';
import 'dart:mojo_bindings';
import 'dart:mojo_core';

import 'package:mojo/services/console/public/interfaces/console.mojom.dart';

class ConsoleApplication extends Application {
  ConsoleProxy _proxy;

  ConsoleApplication.fromHandle(MojoHandle handle) : super.fromHandle(handle);

  void initialize(List<String> args) {
    _proxy = new ConsoleProxy.unbound();
    connectToService("mojo:console", _proxy);
    run();
  }

  run() async {
    var result = await _proxy.readLine();
    await _proxy.printLines([result.line]);

    _proxy.close();
    close();
  }
}

main(List args) {
  var appHandle = new MojoHandle(args[0]);
  var consoleApplication = new ConsoleApplication.fromHandle(appHandle);
  consoleApplication.listen();
}

Use await syntax in the console example.

BUG=none
R=zra@google.com

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


// Copyright (c) 2012, 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 test program to test type-based optimization on fields.

class A {
  int a = 0;
  int b = 0;
  foo() {
    var c = b + 27;
    for (var i = 0; i < 1 ; i++) {
      for (var j = 0; j < 1; j++) {
        Expect.equals(50, c + 23);
      }
    }
    return a > 0.2;
  }
  setA(value) { a = value; }
  setB(value) { b = value; }
  operator >(other) => other === 0.2;
}

main() {
  var a = new A();
  Expect.isFalse(a.foo());
  a.setA(new A());
  a.setB(0);
  Expect.isTrue(a.foo());
}

// Copyright (c) 2012, 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 test program to test type-based optimization on fields.

class A {
  var a = 0;
  var b = 0;
  foo() {
    var c = b + 27;
    for (var i = 0; i < 1 ; i++) {
      for (var j = 0; j < 1; j++) {
        Expect.equals(50, c + 23);
      }
    }
    return a > 0.2;
  }
  setA(value) { a = value; }
  setB(value) { b = value; }
  operator >(other) => other === 0.2;
}

main() {
  var a = new A();
  Expect.isFalse(a.foo());
  a.setA(new A());
  a.setB(0);
  Expect.isTrue(a.foo());
}

Fix type annotation error in test.

Fix type annotation error in test.

R=floitsch@google.com
BUG=
TEST=

Review URL: https://chromiumcodereview.appspot.com//10693163

git-svn-id: c93d8a2297af3b929165606efe145742a534bc71@9592 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.

class _Closure implements Function {

  bool operator ==(other) native "Closure_equals";

  int get hashCode native "Closure_hashCode";

  _Closure get call => this;

  _Closure _clone() native "Closure_clone";

  // No instance fields should be declared before the following 3 fields whose
  // offsets must be identical in Dart and C++.

  // The following 3 fields are declared both in raw_object.h (for direct access
  // from C++ code) and also here so that the offset-to-field map used by
  // deferred objects is properly initialized.
  // Caution: These fields are not Dart instances, but VM objects.
  var instantiator_;
  var function_;
  var context_;
}

// 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.

class _Closure implements Function {

  bool operator ==(other) native "Closure_equals";

  int get hashCode native "Closure_hashCode";

  _Closure get call => this;

  _Closure _clone() native "Closure_clone";

  // No instance fields should be declared before the following 3 fields whose
  // offsets must be identical in Dart and C++.

  // The following 3 fields are declared both in raw_object.h (for direct access
  // from C++ code) and also here so that the offset-to-field map used by
  // deferred objects is properly initialized.
  // Caution: These fields are not Dart instances, but VM objects.
  // The fields had to be renamed here so that they would be private fields
  // in dart
  // instantiator_ ===> _instantiator
  // function_ ===> _function
  // context_ ===> _context
  var _instantiator;
  var _function;
  var _context;
}

Fix for regression in content shell tests (see b/36131545)

Renamed public fields in class _Closure to make them private fields,
these fields were added to ensure that the offset of _Closure fields
matched up in Dart and C++ (definition of closure object in raw_object.h).

R=regis@google.com, rmacnak@google.com

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


part of github.client;

class Commit {
  final GitHub github;

  @ApiName("html_url")
  String url;
  String sha;

  @ApiName("commit/message")
  String message;
  User author;
  User committer;

  @ApiName("stats/additions")
  int additionsCount;

  @ApiName("stats/deletions")
  int deletionsCount;

  @ApiName("commit/comments_count")
  int commentsCount;

  DateTime authoredAt;
  DateTime committedAt;

  Commit(this.github);

  static Commit fromJSON(GitHub github, input) {
    var commit = new Commit(github);
    commit.url = input['html_url'];
    commit.author = User.fromJSON(github, input['author']);
    commit.committer = User.fromJSON(github, input['committer']);
    commit.message = input['commit']['message'];

    commit.authoredAt = parse_date(input['commit']['author']['date']);
    commit.committedAt = parse_date(input['commit']['committer']['date']);

    if (input['stats'] != null) {
      commit.additionsCount = input['stats']['additions'];
      commit.deletionsCount = input['stats']['deletions'];
      commit.commentsCount = input['commit']['comments_count'];
    }

    return commit;
  }
}

part of github.client;

class Commit {
  final GitHub github;

  @ApiName("html_url")
  String url;
  String sha;

  @ApiName("commit/message")
  String message;
  User author;
  User committer;

  @ApiName("stats/additions")
  int additionsCount;

  @ApiName("stats/deletions")
  int deletionsCount;

  @ApiName("commit/comments_count")
  int commentsCount;

  DateTime authoredAt;
  DateTime committedAt;

  String committerEmail;
  String authorEmail;

  Commit(this.github);

  static Commit fromJSON(GitHub github, input) {
    var commit = new Commit(github);
    commit.url = input['html_url'];
    commit.author = User.fromJSON(github, input['author']);
    commit.committer = User.fromJSON(github, input['committer']);
    commit.message = input['commit']['message'];

    commit.authoredAt = parse_date(input['commit']['author']['date']);
    commit.committedAt = parse_date(input['commit']['committer']['date']);
    commit.committerEmail = input['commit']['committer']['email'];
    commit.authorEmail = input['commit']['author']['email'];

    if (input['stats'] != null) {
      commit.additionsCount = input['stats']['additions'];
      commit.deletionsCount = input['stats']['deletions'];
      commit.commentsCount = input['commit']['comments_count'];
    }

    return commit;
  }
}

Add Committer and Author Emails

Add Committer and Author Emails


library valorzhong_bones;

import 'dart:math' as Math;

import 'package:stagexl/stagexl.dart';
import 'package:valorzhong_injector/valorzhong_injector.dart';

part 'src/application.dart';
part 'src/screen.dart';
part 'src/utils/color_helper.dart';

part 'src/controls/component.dart';
part 'src/controls/container.dart';
part 'src/controls/layout.dart';
part 'src/controls/progress_bar.dart';
part 'src/controls/button.dart';
part 'src/controls/scale9.dart';

const TWO_PI = Math.PI * 2;

capitalize(String str) => str[0].toUpperCase() + str.substring(1);

Add helper function for string named 'capitalize '


part of pin;

class PinLogger {

  static Logger _logger;
  static File _file;

  static Logger get instance {
    if (_logger == null) {
      int now = PinTime.getTime();
      _file = new File('logs/system-${now}.log');
      _logger = Logger.root;
      _logger.level = Level.FINE;
      _logger.onRecord.listen(_printLogRecord);
      _logger.onRecord.listen(_fileLogRecord);
    }

    return _logger;
  }

  void set level(Level value) {
    _logger.level = value;
  }

  static void _printLogRecord(LogRecord r) {
    print(_formatLogRecord(r));
  }

  static void _fileLogRecord(LogRecord r) {
    _file.writeAsString(_formatLogRecord(r) + '\n', mode: FileMode.APPEND);
  }

  static String _formatLogRecord(LogRecord r) {
    return "[${r.time}][${r.level}]: ${r.message}";
  }

}

part of pin;

class PinLogger {

  static Logger _logger;
  static File _file;

  static Logger get instance {
    if (_logger == null) {
      int now = PinTime.getTime();
      _file = new File('logs/system-${now}.log');
      _logger = Logger.root;
      _logger.level = Level.FINE;
      _logger.onRecord.listen(_printLogRecord);
      _logger.onRecord.listen(_fileLogRecord);
    }

    return _logger;
  }

  void set level(Level value) {
    _logger.level = value;
  }

  static void _printLogRecord(LogRecord r) {
    print(_formatLogRecord(r));
  }

  static void _fileLogRecord(LogRecord r) {
    _file
    .writeAsString(_formatLogRecord(r) + '\n', mode: FileMode.APPEND)
    .catchError((e, trace) {
      print('Error: ${e}');
      if (trace != null) {
        print('StackTrace: ${trace}');
      }
    });
  }

  static String _formatLogRecord(LogRecord r) {
    return "[${r.time}][${r.level}]: ${r.message}";
  }

}

Handle log to file exception.

Handle log to file exception.


import 'dart:ui';

import 'package:easy_localization/easy_localization.dart';

import '../../translations/locale_keys.g.dart';

class TranslationHelper {
  static List<Locale> supportedLocales() {
    return [
      const Locale('de'),
      const Locale('el'),
      const Locale('en'),
      const Locale('es'),
      const Locale('fr'),
      const Locale('it'),
      const Locale('nl'),
      const Locale('pt', 'BR'),
      const Locale('pt', 'PT'),
    ];
  }

  static String localeToString(Locale locale) {
    if (locale.languageCode == 'de') {
      return 'Deutsch';
    } else if (locale.languageCode == 'el') {
      return 'Eλληνικά';
    } else if (locale.languageCode == 'en') {
      return 'English';
    } else if (locale.languageCode == 'es') {
      return 'Español';
    } else if (locale.languageCode == 'fr') {
      return 'Français';
    } else if (locale.languageCode == 'it') {
      return 'Italiano';
    } else if (locale.languageCode == 'nl') {
      return 'Nederlands';
    } else if (locale.languageCode == 'pt') {
      if (locale.countryCode == 'BR') {
        return 'Português (Brasil)';
      } else {
        return 'Português (Portugal)';
      }
    } else {
      return LocaleKeys.general_unknown.tr();
    }
  }
}

import 'dart:ui';

import 'package:easy_localization/easy_localization.dart';

import '../../translations/locale_keys.g.dart';

class TranslationHelper {
  static List<Locale> supportedLocales() {
    return [
      const Locale('de'),
      const Locale('el'),
      const Locale('en'),
      const Locale('es'),
      const Locale('fr'),
      const Locale('it'),
      const Locale('nl'),
      const Locale('pt', 'BR'),
      const Locale('pt', 'PT'),
      const Locale('sv'),
    ];
  }

  static String localeToString(Locale locale) {
    if (locale.languageCode == 'de') {
      return 'Deutsch';
    } else if (locale.languageCode == 'el') {
      return 'Eλληνικά';
    } else if (locale.languageCode == 'en') {
      return 'English';
    } else if (locale.languageCode == 'es') {
      return 'Español';
    } else if (locale.languageCode == 'fr') {
      return 'Français';
    } else if (locale.languageCode == 'it') {
      return 'Italiano';
    } else if (locale.languageCode == 'nl') {
      return 'Nederlands';
    } else if (locale.languageCode == 'pt') {
      if (locale.countryCode == 'BR') {
        return 'Português (Brasil)';
      } else {
        return 'Português (Portugal)';
      }
    } else if (locale.languageCode == 'sv') {
      return 'Svenska';
    } else {
      return LocaleKeys.general_unknown.tr();
    }
  }
}

Fix Swedish translations not being implemented.


part of streamy.runtime;

class DynamicEntity extends RawEntity {

  DynamicEntity() : super();

  DynamicEntity.fromMap(Map data) {
    data.forEach((key, value) {
      this[key] = value;
    });
  }

  noSuchMethod(Invocation invocation) {
    var memberName = MirrorSystem.getName(invocation.memberName);
    if (invocation.isGetter) {
      return this[memberName];
    } else if (invocation.isSetter) {
      // Setter member names have an '=' at the end, strip it.
      var key = memberName.substring(0, memberName.length - 1);
      this[key] = invocation.positionalArguments[0];
    } else {
      throw new ClosureInvocationException(memberName);
    }
  }

  Type get streamyType => DynamicEntity;
}

part of streamy.runtime;

class DynamicEntity extends RawEntity {

  DynamicEntity() : super();

  DynamicEntity.fromMap(Map data) {
    data.forEach((key, value) {
      this[key] = value;
    });
  }

  noSuchMethod(Invocation invocation) {
    var memberName = MirrorSystem.getName(invocation.memberName);
    if (invocation.isGetter) {
      return this[memberName];
    } else if (invocation.isSetter) {
      // Setter member names have an '=' at the end, strip it.
      var key = memberName.substring(0, memberName.length - 1);
      this[key] = invocation.positionalArguments[0];
    } else {
      // Perhaps the called was trying to call a nonexistent method,
      // or perhaps the caller was trying to invoke a data member as a
      // completion. Throw an appropriate error.
      if (contains(memberName)) {
        throw new ClosureInvocationException(memberName);
      } else {
        // The Invocation class and NoSuchMethodError have different ideas
        // about the type of the named arguments map.
        Map<String, dynamic> namedArgs = {};
        for (key in invocation.namedArguments.keys) {
          namedArgs[key.toString()] = invocation.namedArguments[key];
        }
        throw new NoSuchMethodError(this, memberName,
            invocation.positionalArguments, namedArgs);
      }
    }
  }

  Type get streamyType => DynamicEntity;
}

Throw NoSuchMethodError if the caller requests a nonexistent member

Angular--and potentially other callers--expect that when a method such
as containsKey is called on a DynamicEntity, that the object will throw
NoSuchMethodError. DynamicEntity, on the other hand, wants to ensure
that no one stashes a completion in a DynamicEntity and tries to call
it later. This patch accomodates both needs.


// Copyright (c) 2012, 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.

#import("dart:io");

class ProcessStartExceptionTest {

  static void testStartError() {
    Process process =
        new Process.start("__path_to_something_that_should_not_exist__",
                          const []);

    process.onExit = (int exitCode) {
      Expect.fail("exit handler called");
    };

    process.onError = (ProcessException e) {
      Expect.equals(2, e.errorCode);
    };
  }
}

main() {
  ProcessStartExceptionTest.testStartError();
}

// Copyright (c) 2012, 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.

#import("dart:io");

class ProcessStartExceptionTest {

  static void testStartError() {
    Process process =
        new Process.start("__path_to_something_that_should_not_exist__",
                          const []);

    process.onExit = (int exitCode) {
      Expect.fail("exit handler called");
    };

    process.onError = (ProcessException e) {
      Expect.equals(2, e.errorCode, e.toString());
    };
  }
}

main() {
  ProcessStartExceptionTest.testStartError();
}

Print the actual error message on failure in the ProcessStartException test.

R=iposva@google.com,sgjesse@google.com
BUG=
TEST=

Review URL: https://chromiumcodereview.appspot.com//9856020

git-svn-id: c93d8a2297af3b929165606efe145742a534bc71@5842 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 byte_stream;

import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'dart:typed_data';

import 'utils.dart';

/// A stream of chunks of bytes representing a single piece of data.
class ByteStream extends StreamView<List<int>> {
  ByteStream(Stream<List<int>> stream)
    : super(stream);

  /// Returns a single-subscription byte stream that will emit the given bytes
  /// in a single chunk.
  factory ByteStream.fromBytes(List<int> bytes) =>
    new ByteStream(streamFromIterable([bytes]));

  /// Collects the data of this stream in a [Uint8List].
  Future<Uint8List> toBytes() {
    /// TODO(nweiz): use BufferList when issue 6409 is fixed.
    return fold(<int>[], (buffer, chunk) {
      buffer.addAll(chunk);
      return buffer;
    }).then(toUint8List);
  }

  /// Collect the data of this stream in a [String], decoded according to
  /// [encoding], which defaults to `UTF8`.
  Future<String> bytesToString([Encoding encoding=UTF8]) =>
      toBytes().then((bytes) => encoding.decode(bytes));

  Stream<String> toStringStream([Encoding encoding=UTF8]) =>
    transform(encoding.decoder);
}

// 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 byte_stream;

import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'dart:typed_data';

import 'utils.dart';

/// A stream of chunks of bytes representing a single piece of data.
class ByteStream extends StreamView<List<int>> {
  ByteStream(Stream<List<int>> stream)
    : super(stream);

  /// Returns a single-subscription byte stream that will emit the given bytes
  /// in a single chunk.
  factory ByteStream.fromBytes(List<int> bytes) =>
    new ByteStream(streamFromIterable([bytes]));

  /// Collects the data of this stream in a [Uint8List].
  Future<Uint8List> toBytes() {
    return fold(new BytesBuilder(), (builder, chunk) => builder..add(chunk))
      .then((builder) => builder.takeBytes());
  }

  /// Collect the data of this stream in a [String], decoded according to
  /// [encoding], which defaults to `UTF8`.
  Future<String> bytesToString([Encoding encoding=UTF8]) =>
      toBytes().then((bytes) => encoding.decode(bytes));

  Stream<String> toStringStream([Encoding encoding=UTF8]) =>
    transform(encoding.decoder);
}

Use BytesBuilder in pkg:http, when accumulating binary data.

This should speed up the library significant.

BUG=
R=sgjesse@google.com

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

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


String Function() generator() {
  int nextId = 0;
  String prefix = '';
  return () {
    if (++nextId >= 0x3FFFFFFFFFFFFFFF) {
      nextId = 0;
      prefix = '\$' + prefix;
    }
    return prefix + nextId.toString();
  };
}

String Function() generator() {
  int nextId = 0;
  String prefix = '';
  return () {
    /// fix '0x3FFFFFFFFFFFFFFF' can't be represented exactly in JavaScript.
    if (++nextId >= 0x3FFFFFFF) {
      nextId = 0;
      prefix = '\$' + prefix;
    }
    return prefix + nextId.toString();
  };
}

Fix '0x3FFFFFFFFFFFFFFF' can't be represented exactly in JavaScript.


// 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.

library vm_service_client.exceptions;

import 'error.dart';
import 'sentinel.dart';

/// An exception thrown when the client attempts to load a remote object that's
/// no longer available.
class VMSentinelException implements Exception {
  /// The sentinel indicating what happened to the remote object.
  final VMSentinel sentinel;

  VMSentinelException(this.sentinel);

  String toString() => "Unexpected $sentinel sentinel.";
}

/// An exception that represents a Dart exception in the remote VM.
class VMErrorException implements Exception {
  /// The error in the remote VM.
  final VMErrorRef error;

  VMErrorException(this.error);

  String toString() => "Remote VM ${error.kind}: ${error.message}";
}

/// An exception indicating that the VM service client doesn't support the
/// current protocol version.
class VMUnsupportedVersionException implements Exception {
  /// The version reported by the VM service protocol.
  ///
  /// This may be `null` if the reported version isn't in a format the client
  /// understands.
  final VMServiceVersion version;

  UnsupportedVersionException([this.version]);

  String toString() => version == null
      ? "The VM service protocol is an unsupported version."
      : "The VM service protocol is unsupported version $version.";
}

// 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.

library vm_service_client.exceptions;

import 'error.dart';
import 'sentinel.dart';
import 'service_version.dart';

/// An exception thrown when the client attempts to load a remote object that's
/// no longer available.
class VMSentinelException implements Exception {
  /// The sentinel indicating what happened to the remote object.
  final VMSentinel sentinel;

  VMSentinelException(this.sentinel);

  String toString() => "Unexpected $sentinel sentinel.";
}

/// An exception that represents a Dart exception in the remote VM.
class VMErrorException implements Exception {
  /// The error in the remote VM.
  final VMErrorRef error;

  VMErrorException(this.error);

  String toString() => "Remote VM ${error.kind}: ${error.message}";
}

/// An exception indicating that the VM service client doesn't support the
/// current protocol version.
class VMUnsupportedVersionException implements Exception {
  /// The version reported by the VM service protocol.
  ///
  /// This may be `null` if the reported version isn't in a format the client
  /// understands.
  final VMServiceVersion version;

  VMUnsupportedVersionException([this.version]);

  String toString() => version == null
      ? "The VM service protocol is an unsupported version."
      : "The VM service protocol is unsupported version $version.";
}

Fix some bugs in the previous CL.

Fix some bugs in the previous CL.

R=kevmoo@google.com

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


import 'coordinate.dart';
import 'location.dart';

class StayPoint extends Coordinate {
    LocationDegrees latitude;
    LocationDegrees longitude;

    DateTime arrival;
    DateTime departure;
    List<Location> locationsInvolved;

    StayPoint({this.latitude,
                  this.longitude,
                  this.arrival,
                  this.departure,
                  this.locationsInvolved})
        : super(latitude: latitude, longitude: longitude);

    StayPoint.fromLocations({this.locationsInvolved}) {
        double sumLatitude = 0.0;
        double sumLongitude = 0.0;

        for (Location location in locationsInvolved) {
            sumLatitude += location.latitude.degrees;
            sumLongitude += location.longitude.degrees;
        }

        this.latitude = new LocationDegrees(degrees: sumLatitude);
        this.longitude = new LocationDegrees(degrees: sumLongitude);
        this.arrival = locationsInvolved.first.timestamp;
        this.departure = locationsInvolved.last.timestamp;
        this.locationsInvolved = locationsInvolved;
    }

}

import 'coordinate.dart';
import 'location.dart';

class StayPoint extends Coordinate {
    DateTime arrival;
    DateTime departure;
    List<Location> locationsInvolved;

    StayPoint({latitude, longitude,
                  this.arrival,
                  this.departure,
                  this.locationsInvolved})
        : super(latitude: latitude, longitude: longitude);

    StayPoint.fromLocations({this.locationsInvolved})
        : this.arrival = locationsInvolved.first.timestamp,
          this.departure = locationsInvolved.last.timestamp,
          super(latitude: sumLatitude(locationsInvolved), longitude: sumLongitude(locationsInvolved));

    static LocationDegrees sumLatitude(List<Location> locations) {
        return new LocationDegrees(degrees: locations.fold(0.0, (value, element) => value + element.latitude.degrees));
    }

    static LocationDegrees sumLongitude(List<Location> locations) {
        return new LocationDegrees(degrees: locations.fold(0.0, (value, element) => value + element.longitude.degrees));
    }
}

Fix issue with StayPoint class inheritance


library credentials;

/**
 * A class describing OAuth credentials except for client credentials.
 */
class Credentials {
  final String _token;
  final String _tokenSecret;

  Credentials(this._token, this._tokenSecret);
  factory Credentials.fromMap(Map<String, String> parameters) {
    if (!parameters.containsKey('oauth_token')) {
      throw new ArgumentError("params doesn't have a key 'oauth_token'");
    }
    if (!parameters.containsKey('oauth_token_secret')) {
      throw new ArgumentError("params doesn't have a key 'oauth_token_secret'");
    }
    return new Credentials(parameters['oauth_token'], parameters['oauth_token_secret']);
  }

  String get token => _token;
  String get tokenSecret => _tokenSecret;

  String toString() {
    return 'oauth_token=$token&oauth_token_secret=$tokenSecret';
  }
}

library credentials;

import 'dart:convert';

/**
 * A class describing OAuth credentials except for client credential
 */
class Credentials {
  final String _token;
  final String _tokenSecret;

  Credentials(this._token, this._tokenSecret);
  factory Credentials.fromMap(Map<String, String> parameters) {
    if (!parameters.containsKey('oauth_token')) {
      throw new ArgumentError("params doesn't have a key 'oauth_token'");
    }
    if (!parameters.containsKey('oauth_token_secret')) {
      throw new ArgumentError("params doesn't have a key 'oauth_token_secret'");
    }
    return new Credentials(parameters['oauth_token'], parameters['oauth_token_secret']);
  }
  factory Credentials.fromJSON(String json) {
    return new Credentials.fromMap(JSON.decode(json));
  }

  String get token => _token;
  String get tokenSecret => _tokenSecret;

  String toString() {
    return 'oauth_token=$token&oauth_token_secret=$tokenSecret';
  }

  Map toJSON() {
    return {
      "oauth_token": token,
      "oauth_token_secret": tokenSecret
    };
  }
}

Add JSON convertion for Credentials

Add JSON convertion for Credentials


// Copyright (c) 2012, 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.

class A {
  operator ==(other) => 1;
  operator <(other) => null;
  operator <=(other) => 499;
  operator >(other) => "foo";
  operator >=(other) => 42;
}

// This triggered a bug in Dart2Js: equality operator was always boolified.
equals(a) {
  try {
    Expect.equals(1, a == a);
  } catch(TypeError e) {
    // In checked mode the test doesn't do anything.
  }
}

equalsNull(a) {
  try {
    Expect.equals(false, a == null);
  } catch(TypeError e) {
    // In checked mode the test doesn't do anything.
  }
}

less(a) {
  try {
    Expect.equals(null, a < a);
  } catch(TypeError e) {}
}

lessEqual(a) {
  try {
    Expect.equals(499, a <= a);
  } catch(TypeError e) {}
}

greater(a) {
  try {
    Expect.equals("foo", a > a);
  } catch(TypeError e) {}
}

greaterEqual(a) {
  try {
    Expect.equals(42, a >= a);
  } catch(TypeError e) {}
}

main() {
  var a = new A();
  equals(a);
  equalsNull(a);
  less(a);
  lessEqual(a);
  greater(a);
  greaterEqual(a);
}

// Copyright (c) 2012, 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.

class A {
  operator ==(other) => 1;
  operator <(other) => null;
  operator <=(other) => 499;
  operator >(other) => "foo";
  operator >=(other) => 42;
}

// This triggered a bug in Dart2Js: equality operator was always boolified.
equals(a) {
  try {
    Expect.equals(1, a == a);
  } catch(TypeError e) {
    // In checked mode the test doesn't do anything.
  }
}

less(a) {
  try {
    Expect.equals(null, a < a);
  } catch(TypeError e) {}
}

lessEqual(a) {
  try {
    Expect.equals(499, a <= a);
  } catch(TypeError e) {}
}

greater(a) {
  try {
    Expect.equals("foo", a > a);
  } catch(TypeError e) {}
}

greaterEqual(a) {
  try {
    Expect.equals(42, a >= a);
  } catch(TypeError e) {}
}

main() {
  var a = new A();
  equals(a);
  less(a);
  lessEqual(a);
  greater(a);
  greaterEqual(a);
}

Fix VM tests by removing test that was not enabled before my commit in any case.

I enabled the test and updated it with the new equality semantics that the
VM does not implement yet. I don't think the test adds much value.

R=floitsch@google.com
BUG=
TEST=

Review URL: https://chromiumcodereview.appspot.com//10699074

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


library oauth.utils;
import 'dart:async';
import 'dart:io';
import 'dart:math';

Future get async => new Future.delayed(const Duration(milliseconds: 0),
                                       () => null);

RandomAccessFile _randomFile;
bool _haveWarned = false;

List<int> getRandomBytes(int count) {
  if(!Platform.isWindows) {
    if(_randomFile == null) {
      _randomFile = new File("/dev/urandom").openSync();
    }

    return _randomFile.readSync(count);
  } else {
    if(!_haveWarned) {
      _haveWarned = true;
      print(
          "Dart does not presently provide access to secure random numbers on Windows. " +
          "You should therefore not use the OAuth library in 'production' environments " +
          "on a Windows machine!");
    }

    var r = new Random();
    return new List<int>.generate(count, (_) => r.nextInt(255), growable: false);
  }
}

library oauth.utils;
import 'dart:async';
import 'dart:math';

Future get async => new Future.delayed(const Duration(milliseconds: 0),
                                       () => null);

Random randomSource;
bool _haveWarned = false;

List<int> getRandomBytes(int count) {
    if (randomSource == null) {
      randomSource = new Random.secure();
    }

    // N.B. Random.nextInt():
    // Generates a non-negative random integer uniformly distributed in the
    // range from 0, inclusive, to max, *exclusive*.
    return new List<int>.generate(count,
      (_) => randomSource.nextInt(256), growable: false);
}

Use Random.secure() for random bytes

Use Random.secure() for random bytes


import 'dart:isolate';

main(){
  port.receive((msg,reply){
      print("hellodistributedworld received: ${msg['msg']}");
      msg['reply'].send("OK: ${msg['msg']}");
  });
}

import 'dart:isolate';
import "package:distributed_dart/distributed_dart.dart";

main(){
  port.receive((msg,reply){
      print("hellodistributedworld received: ${msg['msg']}");
      msg['reply'].send("OK: ${msg['msg']}");
  });
}

Make the example a little bit more complicated

Added not necessary dependency to distributed_dart to test dependencies
check.


// Copyright (c) 2020, 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/src/services/correction/dart/abstract_producer.dart';
import 'package:analysis_server/src/services/correction/fix.dart';
import 'package:analyzer/dart/ast/ast.dart';
import 'package:analyzer_plugin/utilities/change_builder/change_builder_core.dart';
import 'package:analyzer_plugin/utilities/fixes/fixes.dart';

class AddStatic extends CorrectionProducer {
  @override
  FixKind get fixKind => DartFixKind.ADD_STATIC;

  @override
  Future<void> compute(ChangeBuilder builder) async {
    var declaration = node.thisOrAncestorOfType<FieldDeclaration>();
    await builder.addDartFileEdit(file, (builder) {
      var offset = declaration.firstTokenAfterCommentAndMetadata.offset;
      builder.addSimpleInsertion(offset, 'static ');
    });
  }

  /// Return an instance of this class. Used as a tear-off in `FixProcessor`.
  static AddStatic newInstance() => AddStatic();
}

// Copyright (c) 2020, 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/src/services/correction/dart/abstract_producer.dart';
import 'package:analysis_server/src/services/correction/fix.dart';
import 'package:analyzer/dart/ast/ast.dart';
import 'package:analyzer_plugin/utilities/change_builder/change_builder_core.dart';
import 'package:analyzer_plugin/utilities/fixes/fixes.dart';

class AddStatic extends CorrectionProducer {
  @override
  FixKind get fixKind => DartFixKind.ADD_STATIC;

  @override
  Future<void> compute(ChangeBuilder builder) async {
    var declaration = node.thisOrAncestorOfType<FieldDeclaration>();
    if (declaration == null) {
      return;
    }
    await builder.addDartFileEdit(file, (builder) {
      var offset = declaration.firstTokenAfterCommentAndMetadata.offset;
      builder.addSimpleInsertion(offset, 'static ');
    });
  }

  /// Return an instance of this class. Used as a tear-off in `FixProcessor`.
  static AddStatic newInstance() => AddStatic();
}

Fix an npe in AddStatic when the field declaration cannot be found

I wasn't able to find a test case that reproduced the bug.

Fixes: https://github.com/Dart-Code/Dart-Code/issues/3205
Change-Id: Ie45c76ef7ed18755ccc576ad9aa39ff35055233e
Reviewed-on: https://dart-review.googlesource.com/c/sdk/+/192281
Reviewed-by: Konstantin Shcheglov <09e4d7516628963212bf4aace2f97603d2b706e4@google.com>
Commit-Queue: Brian Wilkerson <1f7641b6b14c52b9163524ab8d9aabff80176f21@google.com>


class Address {
  String name;
  String mailAddress;

  const Address([this.mailAddress, this.name]);

  /// Generates an address that must conform to RFC 5322.
  /// For example, `name <foo@domain.com>`, `<foo@domain.com>`
  /// and `foo.domain.com`.
  @override
  String toString() {
    var fromName = name ?? '';
    // ToDo base64 fromName (add _IRMetaInformation as argument)
    return '$fromName <$mailAddress>';
  }
}

class Address {
  String name;
  String mailAddress;

  Address([this.mailAddress, this.name]);

  /// Generates an address that must conform to RFC 5322.
  /// For example, `name <foo@domain.com>`, `<foo@domain.com>`
  /// and `foo.domain.com`.
  @override
  String toString() {
    var fromName = name ?? '';
    // ToDo base64 fromName (add _IRMetaInformation as argument)
    return '$fromName <$mailAddress>';
  }
}

fix: Address cannot be const as name and mailAddress are not final

`name` and `mailAddress` cannot be declared final in minor library version changes.


import "package:legit/legit.dart";

void main() {
  var git = new GitClient();

  git.listTree("HEAD").then((files) {
    print(files.map((it) => it.path).join("\n"));
  });
}

import "package:legit/legit.dart";

void main() {
  var git = new GitClient();

  git.listTree("HEAD").then((files) {
    print(files.map((it) => it.path + " (" + it.blob + ")").join("\n"));
  });
}

Add Blob to Tree Example

Add Blob to Tree Example


import 'package:angular2/angular2.dart';
import 'package:fnx_ui/src/util/ui.dart' as ui;
import 'dart:html';
import 'package:fnx_ui/fnx_ui.dart';
import 'package:fnx_ui/src/validator.dart';

@Component(
    selector: 'fnx-submit-bar',
    template: r'''

  {{ goBackLabel }}

  <button type="submit" class="btn bg--important" attr.data-prefix="{{formValid ? 'check' : 'not_interested'}}">
    {{ label }}
  </button>

''')
class FnxSubmitBar {

  @Input() String label = "Submit";
  @Input() String goBackLabel = "Back";
  @Input() bool back = false;

  final FnxForm _form;

  FnxSubmitBar(this._form);

  bool get formValid {
    if (_form == null) return true;
    return _form.isValid();
  }

  void goBack(Event event) {
    ui.killEvent(event);
    window.history.back();
  }
}

const FNX_BUTTON_DIRECTIVES = const [FnxSubmitBar];

import 'package:angular2/angular2.dart';
import 'package:fnx_ui/src/util/ui.dart' as ui;
import 'dart:html';
import 'package:fnx_ui/fnx_ui.dart';
import 'package:fnx_ui/src/validator.dart';

@Component(
    selector: 'fnx-submit-bar',
    template: r'''

  {{ goBackLabel }}

  <button type="submit" class="btn bg--important" attr.data-prefix="{{formValid ? 'check' : 'not_interested'}}">
    {{ label }}
  </button>

''')
class FnxSubmitBar {

  @Input() String label = "Submit";
  @Input() String goBackLabel = "Back";
  @Input() bool back = false;

  final FnxForm _form;

  FnxSubmitBar(@Optional() this._form) {
    if (_form == null) {
      throw new Exception("To use fnx-submit-bar, please wrap your form into <fnx-form></fnx-form> component!");
    }
  }

  bool get formValid {
    if (_form == null) return true;
    return _form.isValid();
  }

  void goBack(Event event) {
    ui.killEvent(event);
    window.history.back();
  }
}

const FNX_BUTTON_DIRECTIVES = const [FnxSubmitBar];

FIX fnx-submit-bar: make FnxForm dependency optional

So angluar won't complain while trying to instantiate fnx-submit-bar. Fail with more explanatory message, instructing the user how to fix it.


// 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:async';

/// Represents the state of expansion of an option in a material tree.
///
/// If [expanded] is true, then the option's children will be expanded.
/// The material tree will sync state with options inheriting from
/// MaterialTreeExpandState.
///
/// Pre-existing values will be overwritten if `MaterialTree.expandAll` is set
/// to true.
abstract class MaterialTreeExpandState {
  bool _pending = false;
  bool _expanded = false;

  /// Whether this option is expanded (or should be upon becoming visible)
  bool get expanded => _expanded;
  set expanded(bool expanded) {
    if (_expanded == expanded) return;
    _expanded = expanded;
    if (!_pending) {
      _pending = true;
      // Schedules a microtask (if one isn't pending already). This ensures that
      // any iterative code deciding the value of expanded doesn't flood the
      // stream with incidental events (only broadcasts when writing is done)
      scheduleMicrotask(() {
        _pending = false;
        _expandEvents.add(_expanded);
      });
    }
  }

  StreamController<bool> _expandEvents = StreamController.broadcast(sync: true);
  Stream<bool> get expandEvents => _expandEvents.stream.distinct();
}

// 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:async';

/// Represents the state of expansion of an option in a material tree.
///
/// If [expanded] is true, then the option's children will be expanded.
/// The material tree will sync state with options inheriting from
/// MaterialTreeExpandState.
///
/// Pre-existing values will be overwritten if `MaterialTree.expandAll` is set
/// to true.
abstract class MaterialTreeExpandState {
  bool _pending = false;
  bool _expanded = false;

  /// Whether this option is expanded (or should be upon becoming visible)
  bool get expanded => _expanded;
  set expanded(bool expanded) {
    if (_expanded == expanded) return;
    _expanded = expanded;
    if (!_pending) {
      _pending = true;
      // Schedules a microtask (if one isn't pending already). This ensures that
      // any iterative code deciding the value of expanded doesn't flood the
      // stream with incidental events (only broadcasts when writing is done)
      scheduleMicrotask(() {
        _pending = false;
        _expandEvents.add(_expanded);
      });
    }
  }

  final _expandEvents = StreamController<bool>.broadcast(sync: true);
  Stream<bool> get expandEvents => _expandEvents.stream.distinct();
}

Make a private field final.

Make a private field final.

PiperOrigin-RevId: 252820617


library irc;

import 'dart:io';
import 'dart:async';
import 'dart:convert';
import 'package:irc_message/irc_message.dart' as IRCParser;

import 'package:event_bus/event_bus.dart' show EventType, EventBus;

export "bot/bot.dart";

part 'client.dart';
//part 'bot.dart';
part 'events.dart';
part 'types.dart';
part 'colors.dart';

library irc;

import 'dart:io';
import 'dart:async';
import 'dart:convert';
import 'package:irc_message/irc_message.dart' as IRCParser;

import 'package:event_bus/event_bus.dart' show EventType, EventBus;

export "bot/bot.dart";

part 'client.dart';
part 'events.dart';
part 'types.dart';
part 'colors.dart';

Remove a Commented out line of code

Remove a Commented out line of code


import 'package:win32/win32.dart';

void main() {
  final result = MessageBox(
      NULL,
      TEXT('Resource not available\nDo you want to try again?'),
      TEXT('Account Details'),
      MB_ICONWARNING | MB_CANCELTRYCONTINUE | MB_DEFBUTTON2);

  switch (result) {
    case IDCANCEL:
      print('Cancel pressed');
      break;
    case IDTRYAGAIN:
      print('Try Again pressed');
      break;
    case IDCONTINUE:
      print('Continue pressed');
      break;
  }
}

import 'package:win32/win32.dart';

void main() {
  final result = MessageBox(
      NULL,
      TEXT('This is not really an error, but we are pretending for the sake '
          'of this test.\n\nResource error.\nDo you want to try again?'),
      TEXT('Dart MessageBox Test'),
      MB_ICONWARNING | // Warning
          MB_CANCELTRYCONTINUE | // Action button
          MB_DEFBUTTON2 // Second button is the default
      );

  switch (result) {
    case IDCANCEL:
      print('Cancel pressed');
      break;
    case IDTRYAGAIN:
      print('Try Again pressed');
      break;
    case IDCONTINUE:
      print('Continue pressed');
      break;
  }
}

Clarify that this isn't a real error

Clarify that this isn't a real error


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

import '../../../../core/error/failure.dart';
import 'graph_data.dart';

enum GraphCurrentState {
  inProgress,
  failure,
  success,
}

class GraphState extends Equatable {
  final GraphData graphData;
  final GraphCurrentState graphCurrentState;
  final String yAxis;
  final Failure failure;
  final String failureMessage;
  final String failureSuggestion;

  GraphState({
    @required this.graphData,
    @required this.graphCurrentState,
    @required this.yAxis,
    this.failure,
    this.failureMessage,
    this.failureSuggestion,
  });

  GraphState copyWith({
    GraphData graphData,
    GraphCurrentState graphCurrentState,
    String yAxis,
    Failure failure,
    String failureMessage,
    String failureSuggestion,
  }) {
    return GraphState(
      graphData: graphData ?? this.graphData,
      graphCurrentState: graphCurrentState ?? this.graphCurrentState,
      yAxis: yAxis ?? this.yAxis,
      failure: failure ?? this.failure,
      failureMessage: failureMessage ?? this.failureMessage,
      failureSuggestion: failureSuggestion ?? this.failureSuggestion,
    );
  }

  @override
  List<Object> get props => [
        graphData,
        graphCurrentState,
        yAxis,
        failure,
        failureMessage,
        failureSuggestion,
      ];
}

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

import '../../../../core/error/failure.dart';
import 'graph_data.dart';

enum GraphCurrentState {
  inProgress,
  failure,
  success,
}

enum GraphType {
  playsByDate,
  playsByDayOfWeek,
  playsByHourOfDay,
}

class GraphState extends Equatable {
  final GraphData graphData;
  final GraphCurrentState graphCurrentState;
  final GraphType graphType;
  final String yAxis;
  final Failure failure;
  final String failureMessage;
  final String failureSuggestion;

  GraphState({
    @required this.graphData,
    @required this.graphCurrentState,
    @required this.graphType,
    @required this.yAxis,
    this.failure,
    this.failureMessage,
    this.failureSuggestion,
  });

  GraphState copyWith({
    GraphData graphData,
    GraphCurrentState graphCurrentState,
    GraphType graphType,
    String yAxis,
    Failure failure,
    String failureMessage,
    String failureSuggestion,
  }) {
    return GraphState(
      graphData: graphData ?? this.graphData,
      graphCurrentState: graphCurrentState ?? this.graphCurrentState,
      graphType: graphType ?? this.graphType,
      yAxis: yAxis ?? this.yAxis,
      failure: failure ?? this.failure,
      failureMessage: failureMessage ?? this.failureMessage,
      failureSuggestion: failureSuggestion ?? this.failureSuggestion,
    );
  }

  @override
  List<Object> get props => [
        graphData,
        graphCurrentState,
        graphType,
        yAxis,
        failure,
        failureMessage,
        failureSuggestion,
      ];
}

Add GraphType enum to GraphState.

Add GraphType enum to GraphState.


// Copyright (c) 2017. 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_forms/angular_forms.dart';

@Component(
  selector: 'my-app',
  template: '''

{{title}}

{{hero.name}} details!

id: {{hero.id}}

  		name:
  		<input [(ngModel)]="hero.name" placeholder="name">

  ''',
  directives: const [formDirectives],
)
class AppComponent {
 final title = 'Tour of Heroes';
 Hero hero = new Hero(1, 'Windstorm');
}

class Hero {
	final int id;
	String name;

	Hero(this.id, this.name);
}

// Copyright (c) 2017. 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_forms/angular_forms.dart';

@Component(
  selector: 'my-app',
  templateUrl: 'app_component.html',
  directives: const [formDirectives],
)
class AppComponent {
 final title = 'Tour of Heroes';
 Hero hero = new Hero(1, 'Windstorm');
}

class Hero {
	final int id;
	String name;

	Hero(this.id, this.name);
}

Split template into own file

Split template into own file


import 'package:meta/meta.dart';

import '../../../../core/api/tautulli_api.dart';
import '../../domain/entities/metadata_item.dart';
import '../models/metadata_item_model.dart';

abstract class MetadataDataSource {
  Future<MetadataItem> getMetadata({
    @required String tautulliId,
    int ratingKey,
    int syncId,
  });
}

class MetadataDataSourceImpl implements MetadataDataSource {
  final TautulliApi tautulliApi;

  MetadataDataSourceImpl({@required this.tautulliApi});

  @override
  Future<MetadataItem> getMetadata({
    String tautulliId,
    int ratingKey,
    int syncId,
  }) async {
    final metadataItemJson = await tautulliApi.getMetadata(
      tautulliId: tautulliId,
      ratingKey: ratingKey,
      syncId: syncId,
    );

    MetadataItem metadataItem =
        MetadataItemModel.fromJson(metadataItemJson['response']['data']);

    return metadataItem;
  }
}

import 'package:meta/meta.dart';

import '../../../../core/api/tautulli_api.dart';
import '../../../../core/error/exception.dart';
import '../../domain/entities/metadata_item.dart';
import '../models/metadata_item_model.dart';

abstract class MetadataDataSource {
  Future<MetadataItem> getMetadata({
    @required String tautulliId,
    int ratingKey,
    int syncId,
  });
}

class MetadataDataSourceImpl implements MetadataDataSource {
  final TautulliApi tautulliApi;

  MetadataDataSourceImpl({@required this.tautulliApi});

  @override
  Future<MetadataItem> getMetadata({
    @required String tautulliId,
    int ratingKey,
    int syncId,
  }) async {
    final metadataItemJson = await tautulliApi.getMetadata(
      tautulliId: tautulliId,
      ratingKey: ratingKey,
      syncId: syncId,
    );

    Map<String, dynamic> metadataMap = metadataItemJson['response']['data'];

    if (metadataMap.isEmpty) {
      throw MetadataEmptyException;
    } else {
      MetadataItem metadataItem = MetadataItemModel.fromJson(metadataMap);

      return metadataItem;
    }
  }
}

Throw exception on empty Metadata.

Throw exception on empty Metadata.


import 'package:flutter/material.dart';

import '../../../../core/widgets/grid_image_item.dart';
import '../../domain/entities/media_item.dart';
import '../../domain/entities/metadata_item.dart';
import '../pages/media_item_page.dart';

class MediaAlbumsTab extends StatelessWidget {
  final MediaItem item;
  final List<MetadataItem> albums;

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

  @override
  Widget build(BuildContext context) {
    return MediaQuery.removePadding(
      context: context,
      removeTop: true,
      child: GridView.count(
        crossAxisCount: 2,
        childAspectRatio: 1,
        children: albums
            .map(
              (album) => PosterGridItem(
                item: album,
                onTap: () {
                  Navigator.of(context).push(
                    MaterialPageRoute(
                      builder: (context) {
                        MediaItem mediaItem = MediaItem(
                          mediaIndex: album.mediaIndex,
                          mediaType: album.mediaType,
                          parentTitle: item.title,
                          grandparentTitle: item.parentTitle,
                          posterUrl: album.posterUrl,
                          ratingKey: album.ratingKey,
                          title: album.title,
                          year: album.year,
                        );
                        return MediaItemPage(
                          item: mediaItem,
                          heroTag: album.ratingKey,
                        );
                      },
                    ),
                  );
                },
              ),
            )
            .toList(),
      ),
    );
  }
}

import 'package:flutter/material.dart';

import '../../../../core/widgets/grid_image_item.dart';
import '../../domain/entities/media_item.dart';
import '../../domain/entities/metadata_item.dart';
import '../pages/media_item_page.dart';

class MediaAlbumsTab extends StatelessWidget {
  final MediaItem item;
  final List<MetadataItem> albums;

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

  @override
  Widget build(BuildContext context) {
    return MediaQuery.removePadding(
      context: context,
      removeTop: true,
      child: GridView.count(
        crossAxisCount: 3,
        childAspectRatio: 1,
        children: albums
            .map(
              (album) => PosterGridItem(
                item: album,
                onTap: () {
                  Navigator.of(context).push(
                    MaterialPageRoute(
                      builder: (context) {
                        MediaItem mediaItem = MediaItem(
                          mediaIndex: album.mediaIndex,
                          mediaType: album.mediaType,
                          parentTitle: item.title,
                          grandparentTitle: item.parentTitle,
                          posterUrl: album.posterUrl,
                          ratingKey: album.ratingKey,
                          title: album.title,
                          year: album.year,
                        );
                        return MediaItemPage(
                          item: mediaItem,
                          heroTag: album.ratingKey,
                        );
                      },
                    ),
                  );
                },
              ),
            )
            .toList(),
      ),
    );
  }
}

Make albums 3 across on media details page.


import 'package:ds/Task.dart';
import 'package:test/test.dart';

void main() {
  test('Task gets initialized correctly', () {
    var t1 = new Task('task1');
    expect(t1.summary, 'task1');
    expect(t1.contents.length, 0);
    expect(t1.scheduled, null);
    expect(t1.categories.length, 7);
    expect(t1.categories.contains('work'), true);
    expect(t1.categories.contains('travel'), true);
    expect(t1.categories.contains('holiday'), false);
  });
  test('Adding a content inserts into contents', () {
    var t1 = new Task('task1');
    t1.addContent('first content');
    t1.addContent('second content');
    expect(t1.contents.length, 2);
    expect(t1.contents[0], 'second content');
  });
  test('Adding a custom category adds it to categories', () {
    var t1 = new Task('task1');
    t1.addCategory('holiday');
    expect(t1.categories.length, 8);
    expect(t1.categories.contains('holiday'), true);
  });
}

import 'package:ds/Task.dart';
import 'package:test/test.dart';

void main() {
  test('Task gets initialized correctly', () {
    var t1 = new Task('task1');
    expect(t1.summary, 'task1');
    expect(t1.contents.length, 0);
    expect(t1.scheduled, null);
    expect(t1.categories.length, 7);
    expect(t1.categories.contains('work'), true);
    expect(t1.categories.contains('travel'), true);
    expect(t1.categories.contains('holiday'), false);
  });
  test('Adding a content inserts into contents', () {
    var t1 = new Task('task1');
    t1.addContent('first content');
    t1.addContent('second content');
    expect(t1.contents.length, 2);
    expect(t1.contents[0], 'second content');
  });
  test('Adding a custom category adds it to categories', () {
    var t1 = new Task('task1');
    t1.addCategory('holiday');
    expect(t1.categories.length, 8);
    expect(t1.categories.contains('holiday'), true);
  });
  test('categoryBackground returns the color code for a task category', () {
    var t1 = new Task('task1');
    expect(t1.categoryBackground('work'), "#112211");
    expect(t1.categoryBackground('travel'), '#b3534b');
    expect(t1.categoryBackground('holiday'), '#888888');
  });
}

Add tests for categoryBackground method.


library velvet_fog_machine;

import 'dart:math';

// The "Originator"
class VelvetFogMachine {
  // The Memento
  Playing _nowPlaying;

  // Set the state
  void play(String title, String album, [double time = 0.0]) {
    print("Playing $title // $album @ ${time.toStringAsFixed(2)}");
    _nowPlaying = new Playing(title, album, time);
  }

  Playing get nowPlaying {
    _nowPlaying.time = 5*rand.nextDouble();
    return _nowPlaying;
  }

  // Restore from memento
  void backTo(Playing memento) {
    print("  *** Whoa! This was a good one, let's hear it again :) ***");
    play(memento.title, memento.album, memento.time);
  }
}

final rand = new Random(1);

// The Memento
class Playing {
  String title, album;
  double time;
  Playing(this.title, this.album, this.time);
}

library velvet_fog_machine;

import 'dart:math';
final rand = new Random(1);

// The "Originator"
class VelvetFogMachine {
  Song currentSong;
  double currentTime;

  // Set the state
  void play(String title, String album, [double time = 0.0]) {
    _play(new Song(title, album), time);
  }

  void _play(Song s, double t) {
    currentSong = s;
    currentTime = t;
    print("Playing $currentSong @ ${currentTime.toStringAsFixed(2)}");
  }

  // Create a memento of the current state
  Playing get nowPlaying {
    // Simulate playing at some time later:
    var time = 5*rand.nextDouble();

    return new Playing(currentSong, time);
  }

  // Restore from memento
  void backTo(Playing p) {
    print("  *** Whoa! This was a good one, let's hear it again :) ***");
    _play(p.song, p.time);
  }
}

class Song {
  String title, album;
  Song(this.title, this.album);
  String toString() => "$title // $album";
}

// The Memento
class Playing {
  Song song;
  double time;
  Playing(this.song, this.time);
}

Improve memento example w/ more realistic originator structure


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

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

class PageBody extends StatelessWidget {
  final Widget child;
  final bool loading;

  const PageBody({
    Key? key,
    required this.child,
    this.loading = false,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return SafeArea(
      child: BlocBuilder<SettingsBloc, SettingsState>(
        builder: (context, state) {
          if (state is SettingsSuccess) {
            return Stack(
              children: [
                if (loading) const LinearProgressIndicator(),
                child,
              ],
            );
          }

          return const SettingsNotLoaded();
        },
      ),
    );
  }
}

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

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

class PageBody extends StatelessWidget {
  final Widget child;
  final bool loading;

  const PageBody({
    Key? key,
    required this.child,
    this.loading = false,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return SafeArea(
      child: BlocBuilder<SettingsBloc, SettingsState>(
        builder: (context, state) {
          if (state is SettingsSuccess) {
            return Stack(
              children: [
                child,
                if (loading) const LinearProgressIndicator(),
              ],
            );
          }

          return const SettingsNotLoaded();
        },
      ),
    );
  }
}

Move progress indicator above child in stack.


import 'package:flutter/material.dart';

class Heading extends StatelessWidget {
  final String text;

  const Heading({
    super.key,
    required this.text,
  });

  @override
  Widget build(BuildContext context) {
    return Text(
      text,
      style: TextStyle(
        fontWeight: FontWeight.bold,
        fontSize: 15,
        color: Theme.of(context).colorScheme.secondary,
      ),
    );
  }
}

import 'package:flutter/material.dart';

class Heading extends StatelessWidget {
  final String text;
  final Color? color;

  const Heading({
    super.key,
    required this.text,
    this.color,
  });

  @override
  Widget build(BuildContext context) {
    return Text(
      text,
      style: TextStyle(
        fontWeight: FontWeight.bold,
        fontSize: 15,
        color: color ?? Theme.of(context).colorScheme.secondary,
      ),
    );
  }
}

Add color support for Heading.

Add color support for Heading.


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=null]) {
    this.timestamp = new DateTime.now().millisecondsSinceEpoch;
  }

  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=null]) {
    this.timestamp = new DateTime.now().millisecondsSinceEpoch;
  }
  Task.fromJson(String json) {
    Map data = json.parse(json);
    var sched = data['scheduled'];
    summary = data['summary'];
    scheduled = (sched.trim() == '') ? null : new DateTime(sched);
  }

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

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

Add serialisation method for class instance


// 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.

// VMOptions=--enable-isolate-groups
// VMOptions=--no-enable-isolate-groups

import "dart:isolate";

import "package:expect/expect.dart";

void test(port) {
  Expect.isNull(const String.fromEnvironment('NOT_FOUND'));
  Expect.equals(
      'x', const String.fromEnvironment('NOT_FOUND', defaultValue: 'x'));
  if (port != null) port.send(null);
}

main() {
  test(null);
  var port = new ReceivePort();
  Isolate.spawn(test, port.sendPort);
  port.listen((_) => port.close());
}

// 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.

// VMOptions=--enable-isolate-groups
// VMOptions=--no-enable-isolate-groups

import "dart:isolate";

import "package:expect/expect.dart";

void test(port) {
  Expect.equals('', const String.fromEnvironment('NOT_FOUND'));
  Expect.equals(
      'x', const String.fromEnvironment('NOT_FOUND', defaultValue: 'x'));
  if (port != null) port.send(null);
}

main() {
  test(null);
  var port = new ReceivePort();
  Isolate.spawn(test, port.sendPort);
  port.listen((_) => port.close());
}

Adjust test for new default values of .fromEnvironment

Breaking change #40678 mandates new default values for
String.fromEnvironment, this CL adjusts the expectations of a test
accordingly.

Change-Id: Ib8a26005673d07c67f65708fc9c4ae7b17421670
Reviewed-on: https://dart-review.googlesource.com/c/sdk/+/139811
Reviewed-by: Johnni Winther <0f64ef784d57ffb064b634040f9eeba0d33d0be4@google.com>
Commit-Queue: Erik Ernst <251bb01623bfda2cd9151e339a6e783ca432874c@google.com>


/// This is kept as a seperate library from the generator intentionally to
/// minimize transitive dependencies of types that are annotated as
/// serializable.
library source_gen.json_serial.annotation;

class JsonSerializable {
  const JsonSerializable();
}

Add doc comment about why the annotation library is separate from the generator library


// 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.
// Test optimizations with static fields with precompilation.
// VMOptions=--noopt --inlining-hotness=0

import 'package:expect/expect.dart';

init() => 123;

final a = init();

main() {
  var s = 0;
  for (var i = 0; i < 10; i++) {
    s += a;
  }
  Expect.equals(10 * 123, s);
}

// 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.
// Test optimizations with static fields with precompilation.
// VMOptions=--inlining-hotness=0

import 'package:expect/expect.dart';

init() => 123;

final a = init();

main() {
  var s = 0;
  for (var i = 0; i < 10; i++) {
    s += a;
  }
  Expect.equals(10 * 123, s);
}

Fix test by removing the --noopt flag from the test file.

Not all platforms (ia32) support --noopt, and test.py --noopt will run the test
with this option anyway.

TBR=rmacnak@google.com

BUG=

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


// 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 byte_stream;

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

import 'utils.dart';

/// A stream of chunks of bytes representing a single piece of data.
class ByteStream extends StreamView<List<int>> {
  ByteStream(Stream<List<int>> stream)
    : super(stream);

  /// Returns a single-subscription byte stream that will emit the given bytes
  /// in a single chunk.
  factory ByteStream.fromBytes(List<int> bytes) =>
    new ByteStream(streamFromIterable([bytes]));

  /// Collects the data of this stream in a [Uint8List].
  Future<Uint8List> toBytes() {
    /// TODO(nweiz): use BufferList when issue 6409 is fixed.
    return reduce(<int>[], (buffer, chunk) {
      buffer.addAll(chunk);
      return buffer;
    }).then(toUint8List);
  }

  /// Collect the data of this stream in a [String], decoded according to
  /// [encoding], which defaults to `Encoding.UTF_8`.
  Future<String> bytesToString([Encoding encoding=Encoding.UTF_8]) =>
      toBytes().then((bytes) => decodeString(bytes, encoding));

  Stream<String> toStringStream([Encoding encoding=Encoding.UTF_8]) =>
      map((bytes) => decodeString(bytes, encoding));
}

// 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 byte_stream;

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

import 'utils.dart';

/// A stream of chunks of bytes representing a single piece of data.
class ByteStream extends StreamView<List<int>> {
  ByteStream(Stream<List<int>> stream)
    : super(stream);

  /// Returns a single-subscription byte stream that will emit the given bytes
  /// in a single chunk.
  factory ByteStream.fromBytes(List<int> bytes) =>
    new ByteStream(streamFromIterable([bytes]));

  /// Collects the data of this stream in a [Uint8List].
  Future<Uint8List> toBytes() {
    /// TODO(nweiz): use BufferList when issue 6409 is fixed.
    return fold(<int>[], (buffer, chunk) {
      buffer.addAll(chunk);
      return buffer;
    }).then(toUint8List);
  }

  /// Collect the data of this stream in a [String], decoded according to
  /// [encoding], which defaults to `Encoding.UTF_8`.
  Future<String> bytesToString([Encoding encoding=Encoding.UTF_8]) =>
      toBytes().then((bytes) => decodeString(bytes, encoding));

  Stream<String> toStringStream([Encoding encoding=Encoding.UTF_8]) =>
      map((bytes) => decodeString(bytes, encoding));
}

Add Iterable.fold (and Stream.fold) which replace `reduce`.

For now this is just a copy. In a next step we will change the behavior of
`reduce`.

BUG= http://dartbug.com/9536

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

git-svn-id: a0fc6a377c96b9059f80895148836233a16d98be@20978 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 uri.builder;

import 'package:quiver/strings.dart' show emptyToNull;

/**
 * A mutable holder for incrementally building [Uri]s.
 */
class UriBuilder {
  String fragment;
  String host;
  String path;
  int port;
  Map<String, String> queryParameters;
  String scheme;
  String userInfo;

  UriBuilder()
      : fragment = '',
        host = '',
        path = '',
        port = 0,
        queryParameters = <String, String>{};

  UriBuilder.fromUri(Uri uri)
      : fragment = uri.fragment,
        host = uri.host,
        path = uri.path,
        port = uri.port,
        queryParameters = new Map<String, String>.from(uri.queryParameters),
        scheme = uri.scheme,
        userInfo = uri.userInfo;

  Uri build() => new Uri(
      fragment: emptyToNull(fragment),
      host: emptyToNull(host),
      path: emptyToNull(path),
      port: port,
      queryParameters: queryParameters.isEmpty? null : queryParameters,
      scheme: emptyToNull(scheme),
      userInfo: emptyToNull(userInfo));

  String toString() => build().toString();
}

// 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 uri.builder;

import 'package:quiver/strings.dart' show emptyToNull, nullToEmpty;

/**
 * A mutable holder for incrementally building [Uri]s.
 */
class UriBuilder {
  String fragment;
  String host;
  String path;
  int port;
  Map<String, String> queryParameters;
  String scheme;
  String userInfo;

  UriBuilder()
      : fragment = '',
        host = '',
        path = '',
        port = 0,
        queryParameters = <String, String>{};

  UriBuilder.fromUri(Uri uri)
      : fragment = uri.fragment,
        host = uri.host,
        path = uri.path,
        port = uri.port,
        queryParameters = new Map<String, String>.from(uri.queryParameters),
        scheme = uri.scheme,
        userInfo = uri.userInfo;

  Uri build() => new Uri(
      fragment: emptyToNull(fragment),
      host: emptyToNull(host),
      path: emptyToNull(path),
      port: port,
      queryParameters: queryParameters.isEmpty? null : queryParameters,
      scheme: nullToEmpty(scheme),
      userInfo: nullToEmpty(userInfo));

  String toString() => build().toString();
}

Fix the UriBuilder fix for 1.5

Fix the UriBuilder fix for 1.5


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

import '1620_generic_function_member_test.template.dart';

void main() {
  tearDown(disposeAnyRunningTest);

  test('generic function member should return normally', () async {
    final testBed = NgTestBed.forComponent(TestComponentNgFactory);
    final testFixture = await testBed.create();
    expect(testFixture.text, 'foo');
  });
}

class Data {
  final String name;

  Data(this.name);
}

@Component(
  selector: 'generic',
  template: '{{render(value)}}',
)
class GenericComponent<T> {
  @Input()
  String Function(T data) render;

  @Input()
  T value;
}

@Component(
  selector: 'test',
  template: '<generic [render]="render" [value]="value"></generic>',
  directives: [GenericComponent],
  directiveTypes: [Typed<GenericComponent<Data>>()],
)
class TestComponent {
  final value = Data('foo');

  String render(Data data) => data.name;
}

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

import '1620_generic_function_member_test.template.dart' as ng;

void main() {
  tearDown(disposeAnyRunningTest);

  test('generic function member should return normally', () async {
    final testBed = NgTestBed.forComponent(ng.TestComponentNgFactory);
    final testFixture = await testBed.create();
    expect(testFixture.text, 'foo');
  });
}

class Data {
  final String name;

  Data(this.name);
}

@Component(
  selector: 'generic',
  template: '{{render(value)}}',
)
class GenericComponent<T> {
  @Input()
  String Function(T data) render;

  @Input()
  T value;
}

@Component(
  selector: 'test',
  template: '<generic [render]="render" [value]="value"></generic>',
  directives: [GenericComponent],
  directiveTypes: [Typed<GenericComponent<Data>>()],
)
class TestComponent {
  final value = Data('foo');

  String render(Data data) => data.name;
}

Use ng prefix for generated import.

Use ng prefix for generated import.

Hoping this will fix analysis error on travis.

PiperOrigin-RevId: 214804749


library hop_runner;

import 'package:hop/hop.dart';
import 'package:hop/hop_tasks.dart';

void main(args) {

  var paths = ['lib/mongo_dart.dart','example/blog.dart']; //etc etc etc

  addTask('analyze_libs', createAnalyzerTask(paths));

  addTask('docs',createDartDocTask(['lib/mongo_dart.dart'], linkApi: true, excludeLibs: ['fixnum']));

  runHop(args);
}

library hop_runner;

import 'package:hop/hop.dart';
import 'package:hop/hop_tasks.dart';

void main(args) {

  var paths = ['lib/mongo_dart.dart','example/blog.dart']; //etc etc etc

  addTask('analyze_libs', createAnalyzerTask(paths));

//  addTask('docs',createDartDocTask(['lib/mongo_dart.dart'], linkApi: true, excludeLibs: ['fixnum']));

  runHop(args);
}

Remove doc generation (breaking in current dart release)


import 'package:flutter/material.dart';

import 'heading.dart';

class ListTileGroup extends StatelessWidget {
  final String? heading;
  final List<Widget> listTiles;

  const ListTileGroup({
    Key? key,
    this.heading,
    required this.listTiles,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Column(
      mainAxisSize: MainAxisSize.min,
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        heading != null
            ? Padding(
                padding: const EdgeInsets.only(
                  left: 8,
                  right: 8,
                ),
                child: Heading(
                  text: heading!,
                ),
              )
            : const SizedBox(height: 0, width: 0),
        Padding(
          padding: EdgeInsets.only(top: heading != null ? 8 : 0),
          child: ClipRRect(
            borderRadius: BorderRadius.circular(4),
            child: Column(
              mainAxisSize: MainAxisSize.min,
              children: listTiles,
            ),
          ),
        ),
      ],
    );
  }
}

import 'package:flutter/material.dart';

import 'heading.dart';

class ListTileGroup extends StatelessWidget {
  final String? heading;
  final List<Widget> listTiles;

  const ListTileGroup({
    Key? key,
    this.heading,
    required this.listTiles,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Column(
      mainAxisSize: MainAxisSize.min,
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        heading != null
            ? Padding(
                padding: const EdgeInsets.symmetric(horizontal: 8),
                child: Heading(
                  text: heading!,
                ),
              )
            : const SizedBox(height: 0, width: 0),
        Padding(
          padding: EdgeInsets.only(top: heading != null ? 8 : 0),
          child: ClipRRect(
            borderRadius: BorderRadius.circular(4),
            child: Column(
              mainAxisSize: MainAxisSize.min,
              children: listTiles,
            ),
          ),
        ),
      ],
    );
  }
}

Fix padding code for ListTileGroup.

Fix padding code for ListTileGroup.


library dartson.transformers.DateTime;

import 'package:dartson/type_transformer.dart';

/// A simple DateTime transformer which uses the toString() method.
class DateTimeParser extends TypeTransformer<DateTime> {
  DateTime decode(dynamic value) => DateTime.parse(value);
  dynamic encode(DateTime value) => value.toString();
}

library dartson.transformers.DateTime;

import 'package:dartson/type_transformer.dart';

/// A simple DateTime transformer which uses the toString() method.
class DateTimeParser extends TypeTransformer<DateTime> {
  DateTime decode(dynamic value) => DateTime.parse(value);
  dynamic encode(DateTime value) => value.toUtc().toIso8601String();
}

Switch to ISO 8601 with Z-notation

Switch to ISO 8601 with Z-notation

ISO8601 with Z-notation is what's the most commonly used format for representing Dates in JSON (at least it's what's used in all browser's Javascript default JSON serializers).


library polymorphic.grind;

import "package:grinder/grinder.dart";

void main(List<String> args) {
  task("clean", defaultClean);
  task("package", package);
  task("build", null, ["clean", "package"]);
  task("test", test);
  task("ci", null, ["test", "build"]);

  startGrinder(args);
}

test(GrinderContext context) {
  runDartScript(context, "test/all.dart");
}

package(GrinderContext context) {
  ensureOutDirectory();

  var args = [
    "--enable-experimental-mirrors",
    "--categories=Server",
    "--output-type=dart",
    "bin/polymorphic.dart",
    "-o",
    "build/out/PolymorphicBot.dart",
    "-m"
  ];

  return runProcessAsync(context, "dart2js", arguments: args).then((_) {
    new FileSet.fromDir(getDir("build/out"), pattern: "*.deps").files.forEach((file) {
      deleteEntity(file);
    });
  });
}

ensureOutDirectory() {
  var dir = getDir("build/out");

  if (!dir.existsSync()) {
    dir.createSync(recursive: true);
  }
}

library polymorphic.grind;

import "dart:io";

import "package:grinder/grinder.dart";
import "package:yaml/yaml.dart";

void main(List<String> args) {
  task("clean", defaultClean);
  task("package", package);
  task("build", null, ["clean", "package"]);
  task("test", test);
  task("ci", null, ["test", "build"]);

  startGrinder(args);
}

test(GrinderContext context) {
  runDartScript(context, "test/all.dart");
}

package(GrinderContext context) {
  ensureOutDirectory();
  var pubspec = loadYaml(new File("pubspec.yaml").readAsStringSync());
  var version = pubspec["version"];

  var args = [
    "--enable-experimental-mirrors",
    "--categories=Server",
    "--output-type=dart",
    "bin/polymorphic.dart",
    "-o",
    "build/out/PolymorphicBot.dart",
    "-m",
    "-Dcompiled=true",
    "-Dversion=${version}"
  ];

  return runProcessAsync(context, "dart2js", arguments: args).then((_) {
    new FileSet.fromDir(getDir("build/out"), pattern: "*.deps").files.forEach((file) {
      deleteEntity(file);
    });
  });
}

ensureOutDirectory() {
  var dir = getDir("build/out");

  if (!dir.existsSync()) {
    dir.createSync(recursive: true);
  }
}

Add 'compiled' and 'version' tags to compiled script.


// @dart=2.12

abstract class Mixin1 {
  String get overriddenString => 'mixin1';

  String get interfaceString;
  set interfaceString(String string);
  bool hasInterfaceString();
}

abstract class Mixin2 {
  String get overriddenString => 'mixin2';

  bool hasOverriddenHasMethod() => false;
}

abstract class Mixin3 {}

Drop dart version from a file

Drop dart version from a file


/// The primary library for the [AngularDart web framework][AngularDart].
///
/// Import this library as follows:
///
/// ```
/// import 'package:angular/angular.dart';
/// ```
///
/// For help using this library, see the AngularDart documentation:
///
/// * [AngularDart guide][]
/// * [AngularDart cheat sheet][cheatsheet]
///
/// [AngularDart]: https://webdev.dartlang.org/angular
/// [AngularDart guide]: https://webdev.dartlang.org/angular/guide
/// [cheatsheet]: https://webdev.dartlang.org/angular/cheatsheet

library angular;

export 'core.dart';
export 'src/common/common_directives.dart';
export 'src/common/directives.dart';
export 'src/common/pipes.dart';
export 'src/core/application_ref.dart' show PlatformRef, ApplicationRef;
export 'src/core/linker.dart';
export 'src/core/testability/testability.dart';
export 'src/platform/bootstrap.dart';
export 'src/platform/dom/events/event_manager.dart' show EventManagerPlugin;

/// The primary library for the [AngularDart web framework][AngularDart].
///
/// Import this library as follows:
///
/// ```
/// import 'package:angular/angular.dart';
/// ```
///
/// For help using this library, see the AngularDart documentation:
///
/// * [AngularDart guide][]
/// * [AngularDart cheat sheet][cheatsheet]
///
/// [AngularDart]: https://webdev.dartlang.org/angular
/// [AngularDart guide]: https://webdev.dartlang.org/angular/guide
/// [cheatsheet]: https://webdev.dartlang.org/angular/cheatsheet

library angular;

export 'core.dart';
export 'src/common/common_directives.dart';
export 'src/common/directives.dart';
export 'src/common/pipes.dart';
export 'src/core/application_ref.dart' show PlatformRef, ApplicationRef;
export 'src/core/linker.dart';
export 'src/core/testability/testability.dart';
export 'src/platform/bootstrap.dart' hide bootstrap;
export 'src/platform/browser/tools/tools.dart'
    show enableDebugTools, disableDebugTools;
export 'src/platform/dom/events/event_manager.dart' show EventManagerPlugin;

Remove the stub "bootstrap" method from AngularDart.

... and "hide bootstrap" from client code, it is no longer needed.

PiperOrigin-RevId: 191307697


// 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 'package:sky/framework/components/popup_menu.dart';
import 'package:sky/framework/fn.dart';
import 'package:sky/framework/theme/view-configuration.dart';

class StockMenu extends Component {
  static final Style _style = new Style('''
    position: absolute;
    right: 8px;
    top: ${8 + kStatusBarHeight}px;''');

  PopupMenuController controller;

  StockMenu({Object key, this.controller}) : super(key: key);

  UINode build() {
    return new StyleNode(
      new PopupMenu(
        controller: controller,
        items: [
          [new Text('Add stock')],
          [new Text('Remove stock')],
          [new Text('Help & feedback')],
        ],
        level: 4),
        _style
    );
  }
}

// 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 'package:sky/framework/components/popup_menu.dart';
import 'package:sky/framework/fn.dart';
import 'package:sky/framework/theme/view_configuration.dart';

class StockMenu extends Component {
  static final Style _style = new Style('''
    position: absolute;
    right: 8px;
    top: ${8 + kStatusBarHeight}px;''');

  PopupMenuController controller;

  StockMenu({Object key, this.controller}) : super(key: key);

  UINode build() {
    return new StyleNode(
      new PopupMenu(
        controller: controller,
        items: [
          [new Text('Add stock')],
          [new Text('Remove stock')],
          [new Text('Help & feedback')],
        ],
        level: 4),
        _style
    );
  }
}

Rename view-configuration to view_configuration to make analyzer happy.

Analyzer was complaining about '-' not being an allowed character
in dart file names.

R=jamesr@chromium.org


import 'dart:html';
import 'package:game_loop/game_loop.dart';
import 'package:asset_pack/asset_pack.dart';
import 'package:tilebasedwordsearch/dictionary.dart';
import 'package:tilebasedwordsearch/game.dart';

CanvasElement _canvasElement;
GameLoop _gameLoop;
AssetManager assetManager = new AssetManager();
Dictionary dictionary;
Game game;

void initialize() {
  dictionary = new Dictionary.fromFile(assetManager['game.dictionary']);
}

void startNewGame() {
  game = new Game();
}

bool f = true;
void gameUpdate(GameLoop gameLoop) {
  // Game logic goes here.
  if (f) {
    print(assetManager['game.dictionary']);
    f = false;
  }
}

void gameRender(GameLoop gameLoop) {
  // Paint here.
}

main() {
  _canvasElement = query('#frontBuffer');
  _gameLoop = new GameLoop(_canvasElement);
  _gameLoop.onUpdate = gameUpdate;
  _gameLoop.onRender = gameRender;
  assetManager.loadPack('game', 'assets.pack')
      .then((_) => initialize())
      .then((_) => _gameLoop.start());
}

import 'dart:html';
import 'package:game_loop/game_loop.dart';
import 'package:asset_pack/asset_pack.dart';
import 'package:tilebasedwordsearch/dictionary.dart';
import 'package:tilebasedwordsearch/game.dart';

CanvasElement _canvasElement;
GameLoop _gameLoop;
AssetManager assetManager = new AssetManager();
Dictionary dictionary;
Game game;

void initialize() {
  dictionary = new Dictionary.fromFile(assetManager['game.dictionary']);
}

void startNewGame() {
  game = new Game();
}

bool f = true;
void gameUpdate(GameLoop gameLoop) {
  // Game logic goes here.
  if (f) {
    print(assetManager['game.dictionary']);
    f = false;
  }
}

void gameRender(GameLoop gameLoop) {
  // Paint here.
}

void gameTouchStart(GameLoop gameLoop, GameLoopTouch touch) {
  print('Start ${touch.id}');
}

void gameTouchEnd(GameLoop gameLoop, GameLoopTouch touch) {
  print('End ${touch.id}');
}

main() {
  _canvasElement = query('#frontBuffer');
  _gameLoop = new GameLoop(_canvasElement);
  _gameLoop.onUpdate = gameUpdate;
  _gameLoop.onRender = gameRender;
  _gameLoop.onTouchStart = gameTouchStart;
  _gameLoop.onTouchEnd = gameTouchEnd;
  assetManager.loadPack('game', 'assets.pack')
      .then((_) => initialize())
      .then((_) => _gameLoop.start());
}

Debug log for touch events.

Debug log for touch events.

Signed-off-by: John McCutchan <a51dda7c7ff50b61eaea0444371f4a6a9301e501@johnmccutchan.com>


// Copyright (c) 2016, <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.

import 'package:angular2/core.dart';
import 'package:logging/logging.dart';
import 'package:angular2/common.dart';
import 'package:fnx_ui/src/util/ui.dart' as ui;
import 'dart:html';
import 'package:fnx_ui/src/validator.dart';
import 'dart:async';

@Component(
  selector: 'fnx-form',
  templateUrl: 'fnx_form.html'
)
class FnxForm extends FnxValidatorComponent {

  final Logger log = new Logger("FnxForm");

  final EventEmitter<Event> submit = new EventEmitter<Event>();

  String id = ui.uid('form-');

  /// Handles submitting the underlying form event.
  /// Only propagates the submit event when this form is valid.
  /// Forces validation of all components inside this form.
  void submitForm(Event event) {
    markAsTouched();
    if (event != null) {
      event.preventDefault();
      event.stopPropagation();
    }

    if (isValid()) {
      submit.emit(event);
    }
  }

  @override
  bool hasValidValue() {
    return true;
  }

}

// Copyright (c) 2016, <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.

import 'package:angular2/core.dart';
import 'package:logging/logging.dart';
import 'package:angular2/common.dart';
import 'package:fnx_ui/src/util/ui.dart' as ui;
import 'dart:html';
import 'package:fnx_ui/src/validator.dart';
import 'dart:async';

@Component(
  selector: 'fnx-form',
  templateUrl: 'fnx_form.html'
)
class FnxForm extends FnxValidatorComponent {

  final Logger log = new Logger("FnxForm");

  @Output()
  final EventEmitter<Event> submit = new EventEmitter<Event>();

  String id = ui.uid('form-');

  /// Handles submitting the underlying form event.
  /// Only propagates the submit event when this form is valid.
  /// Forces validation of all components inside this form.
  void submitForm(Event event) {
    markAsTouched();
    if (event != null) {
      event.preventDefault();
      event.stopPropagation();
    }

    if (isValid()) {
      submit.emit(event);
    }
  }

  @override
  bool hasValidValue() {
    return true;
  }

}

FIX properly annotate output event emitter


import 'dart:io';
import 'dart:convert' show JSON;

main() {
    int port = 3000;

    HttpServer.bind('localhost', port).then((HttpServer server) {
        print('Server started on port: $port');
        server.listen((HttpRequest request) {
                String str = request.uri.queryParameters['str'] ?? '';
                String ch = request.uri.queryParameters['ch'] ?? ' ';
                String len = request.uri.queryParameters['len'] ?? '0';

                Map output = {'str': str.padLeft(int.parse(len), ch)};

                request.response..headers.set(HttpHeaders.CONTENT_TYPE, 'application/json');
                request.response..headers.set('Access-Control-Allow-Origin','*');
                request.response..write(JSON.encode(output))..close();
            });
        });
}

import 'dart:convert' show JSON;
import 'dart:io';

main() {
    int port = 3000;

    HttpServer.bind('localhost', port).then((HttpServer server) {
        print('Server started on port: $port');
        server.listen((HttpRequest request) {
                String str = request.uri.queryParameters['str'] ?? '';
                String ch = request.uri.queryParameters['ch'] ?? ' ';
                String len = request.uri.queryParameters['len'] ?? '0';

                Map output = {'str': str.padLeft(int.parse(len), ch)};

                request.response
                    ..headers.set(HttpHeaders.CONTENT_TYPE, 'application/json')
                    ..headers.set('Access-Control-Allow-Origin', '*')
                    ..write(JSON.encode(output))
                    ..close();

            });
        });
}

Use more method chaining for cleaner code