library frappe.test_runner;

import 'event_stream_test.dart' as eventStreamTest;
import 'property_test.dart' as propertyTest;
import 'constant_property_test.dart' as constantPropertyTest;
import 'stream_property_test.dart' as streamPropertyTest;
import 'computed_property_test.dart' as computedPropertyTest;
import 'collect_reactable_test.dart' as collectReactableTest;

void main() {
  eventStreamTest.main();
  propertyTest.main();
  constantPropertyTest.main();
  streamPropertyTest.main();
  computedPropertyTest.main();
  collectReactableTest.main();
}

library frappe.test_runner;

import 'event_stream_test.dart' as event_stream_test;
import 'property_test.dart' as property_test;
import 'constant_property_test.dart' as constant_property_test;
import 'stream_property_test.dart' as stream_property_test;
import 'computed_property_test.dart' as computed_property_test;
import 'collect_reactable_test.dart' as collect_reactable_test;

void main() {
  event_stream_test.main();
  property_test.main();
  constant_property_test.main();
  stream_property_test.main();
  computed_property_test.main();
  collect_reactable_test.main();
}

Use underscores for import aliases

Use underscores for import aliases


import 'dart:async';

import 'package:build/build.dart';
import 'package:build_test/build_test.dart';
import 'package:moor_generator/integrations/build.dart';
import 'package:test/test.dart';

void main() {
  test('generator emits warning about wrong language version', () async {
    final logs = StreamController<String>();

    final expectation = expectLater(
      logs.stream,
      emits(
        allOf(
          contains('Dart 2.1'),
          contains('Please consider raising the minimum SDK version'),
        ),
      ),
    );

    await testBuilder(
      moorBuilder(BuilderOptions.empty),
      {
        'foo|lib/a.dart': '''
// @dart = 2.1

import 'package:moor/moor.dart';

@UseMoor(tables: [])
class Database {}
        ''',
      },
      reader: await PackageAssetReader.currentIsolate(),
      onLog: (log) {
        logs.add(log.message);
      },
    );

    await expectation;
    await logs.close();
  });
}

import 'dart:async';

import 'package:build/build.dart';
import 'package:build_test/build_test.dart';
import 'package:moor_generator/integrations/build.dart';
import 'package:test/test.dart';

void main() {
  test('generator emits warning about wrong language version', () async {
    final logs = StreamController<String>();

    final expectation = expectLater(
      logs.stream,
      emitsThrough(
        allOf(
          contains('Dart 2.1'),
          contains('Please consider raising the minimum SDK version'),
        ),
      ),
    );

    await testBuilder(
      moorBuilder(BuilderOptions.empty),
      {
        'foo|lib/a.dart': '''
// @dart = 2.1

import 'package:moor/moor.dart';

@UseMoor(tables: [])
class Database {}
        ''',
      },
      reader: await PackageAssetReader.currentIsolate(),
      onLog: (log) {
        logs.add(log.message);
      },
    );

    await expectation;
    await logs.close();
  });
}

Use emitsThrough instead of emits

Use emitsThrough instead of emits


main() {
  var s = "Hello!";
  var l = [0, 1];
  var m = {
    "l": l,
    "s": s,
    new DateTime.now(): "today",
    new DateTime.now().add(const Duration(days: 1)): "tomorrow",
    true: true,
    1: "one",
    1.1: "one-point-one",
  };
  print("Hello, world!"); // BREAKPOINT1
}

main() {
  var s = "Hello!";
  var l = [0, 1];
  var m = {
    "l": l,
    "s": s,
    new DateTime.now(): "today",
    new DateTime.now().add(const Duration(days: 1)): "tomorrow",
    true: true,
    1: "one",
    1.1: "one-point-one",
  };
  if (m[true]) {
    print("Hello, world!"); // BREAKPOINT1
  }
}

Fix compile warning in Dart test project


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

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

}

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

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

}

Add test for insertTask function

Add test for insertTask function


// 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 _InvocationMirror implements InvocationMirror {
  static final int METHOD = 0;
  static final int GETTER = 1;
  static final int SETTER = 2;

  final String memberName;
  final List positionalArguments;
  final Map<String,dynamic> namedArguments = null;

  final int _type;

  _InvocationMirror(this.memberName, this._type, this.positionalArguments);

  static _allocateInvocationMirror(name, arguments) {
    return new _InvocationMirror(name, METHOD, arguments);
  }

  bool get isMethod => _type == METHOD;
  bool get isAccessor => _type != METHOD;
  bool get isGetter => _type == GETTER;
  bool get isSetter => _type == SETTER;

  invokeOn(Object receiver) {
    throw new UnsupportedOperation("invokeOn not implemented yet");
  }
}

// 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 _InvocationMirror implements InvocationMirror {
  static final int METHOD = 0;
  static final int GETTER = 1;
  static final int SETTER = 2;

  final String memberName;
  final List positionalArguments;
  final Map<String,dynamic> namedArguments = null;

  final int _type;

  _InvocationMirror(this.memberName, this._type, this.positionalArguments);

  static _allocateInvocationMirror(name, arguments) {
    return new _InvocationMirror(name, METHOD, arguments);
  }

  bool get isMethod => _type == METHOD;
  bool get isAccessor => _type != METHOD;
  bool get isGetter => _type == GETTER;
  bool get isSetter => _type == SETTER;

  invokeOn(Object receiver) {
    throw new UnsupportedError("invokeOn not implemented yet");
  }
}

Fix throw statement in _InvocationMirror.invokeOn on VM's library.

UnsupportedOperation was renamed to UnsupportedError.

R=fschneider@google.com

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

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


library dart_coveralls.calc;

import 'dart:io';

import 'package:dart_coveralls/dart_coveralls.dart';

import 'command_line.dart';

class CalcPart extends Object with CommandLinePart {
  final ArgParser parser;

  CalcPart() : parser = _initializeParser();

  static ArgParser _initializeParser() {
    var _parser = new ArgParser(allowTrailingOptions: true);
    _parser
      ..addFlag("help", help: "Prints this help", negatable: false)
      ..addOption("workers",
          help: "Number of workers for parsing", defaultsTo: "1")
      ..addOption("output", help: "Output file path")
      ..addOption("package-root",
          help: "Root of the analyzed package", defaultsTo: ".");
    return _parser;
  }

  execute(ArgResults res) {
    if (res.rest.length != 1) return print(parser.usage);

    var pRoot = new Directory(res["package-root"]);
    var file = new File(res.rest.single);
    var workers = int.parse(res["workers"]);

    if (!pRoot.existsSync()) return print("Root directory does not exist");
    if (!file.existsSync()) return print("Dart file does not exist");

    var collector = new LcovCollector(pRoot, file);

    return collector.getLcovInformation(workers: workers).then((r) {
      if (res["output"] != null) {
        return new File(res["output"]).writeAsStringSync(r.toString());
      }
      return print(r.toString());
    });
  }
}

library dart_coveralls.calc;

import 'dart:io';

import 'package:dart_coveralls/dart_coveralls.dart';

import 'command_line.dart';

class CalcPart extends Object with CommandLinePart {
  final ArgParser parser;

  CalcPart() : parser = _initializeParser();

  static ArgParser _initializeParser() {
    var _parser = new ArgParser(allowTrailingOptions: true);
    _parser
      ..addFlag("help", help: "Prints this help", negatable: false)
      ..addOption("workers",
          help: "Number of workers for parsing", defaultsTo: "1")
      ..addOption("output", help: "Output file path")
      ..addOption("package-root",
          help: "Root of the analyzed package", defaultsTo: ".");
    return _parser;
  }

  execute(ArgResults res) {
    if (res.rest.length != 1) return print(parser.usage);

    var pRoot = new Directory(res["package-root"]);
    var file = new File(res.rest.single);
    var workers = int.parse(res["workers"]);

    if (!pRoot.existsSync()) return print("Root directory does not exist");
    if (!file.existsSync()) return print("Dart file does not exist");

    var collector = new LcovCollector(pRoot, file);

    return collector.getLcovInformation(workers: workers).then((r) {
      print(r.processResult.stdout);
      if (res["output"] != null) {
        return new File(res["output"]).writeAsStringSync(r.result);
      }
      return print(r.result);
    });
  }
}

Fix problem with instance of coverage result


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

@PluginInstance()
Plugin plugin;
@BotInstance()
BotConnector bot;

@Command("qr", description: "Generate QR Codes", usage: "<input>")
qr(CommandEvent event) => event.transform((input) {
  return shortenUrl("https://chart.googleapis.com/chart?chs=178x178&cht=qr&chl=${Uri.encodeComponent(input)}");
}, prefix: "QR");

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

@PluginInstance()
Plugin plugin;
@BotInstance()
BotConnector bot;

@Command("qr", description: "Generate QR Codes", usage: "<input>")
qr(CommandEvent event) => event.transform((input) {
  return shortenUrl("https://api.qrserver.com/v1/create-qr-code/?size=150x150&data=${Uri.encodeComponent(input)}");
}, prefix: "QR");

Use a different QR Generator API

Use a different QR Generator API


// @dart=2.9

import 'package:flutter/material.dart';

import '../../features/help/presentation/pages/help_page.dart';
import '../error/failure.dart';
import '../helpers/failure_mapper_helper.dart';

Future<void> showFailureAlertDialog({
  @required BuildContext context,
  @required Failure failure,
  bool showHelp = false,
}) {
  return showDialog(
    context: context,
    barrierDismissible: true,
    builder: (context) {
      return AlertDialog(
        title: Text(FailureMapperHelper.mapFailureToMessage(failure)),
        content: Text(FailureMapperHelper.mapFailureToSuggestion(failure)),
        actions: <Widget>[
          if (showHelp)
            TextButton(
              onPressed: () {
                Navigator.of(context).push(
                  MaterialPageRoute(
                    fullscreenDialog: true,
                    builder: (context) => const HelpPage(),
                  ),
                );
              },
              child: const Text('HELP'),
            ),
          TextButton(
            child: const Text('CLOSE'),
            onPressed: () {
              Navigator.of(context).pop();
            },
          ),
        ],
      );
    },
  );
}

// @dart=2.9

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

import '../../features/help/presentation/pages/help_page.dart';
import '../../translations/locale_keys.g.dart';
import '../error/failure.dart';
import '../helpers/failure_mapper_helper.dart';

Future<void> showFailureAlertDialog({
  @required BuildContext context,
  @required Failure failure,
  bool showHelp = false,
}) {
  return showDialog(
    context: context,
    barrierDismissible: true,
    builder: (context) {
      return AlertDialog(
        title: Text(FailureMapperHelper.mapFailureToMessage(failure)),
        content: Text(FailureMapperHelper.mapFailureToSuggestion(failure)),
        actions: <Widget>[
          if (showHelp)
            TextButton(
              onPressed: () {
                Navigator.of(context).push(
                  MaterialPageRoute(
                    fullscreenDialog: true,
                    builder: (context) => const HelpPage(),
                  ),
                );
              },
              child: const Text(LocaleKeys.button_help).tr(),
            ),
          TextButton(
            child: const Text(LocaleKeys.button_close).tr(),
            onPressed: () {
              Navigator.of(context).pop();
            },
          ),
        ],
      );
    },
  );
}

Update failure alert dialog with translation keys.


library list_tasks;

import 'dart:html';
import 'package:ddays/storageservice.dart' show loadFromStorage;

LIElement singleTaskElement(String tasksummary) {
  LIElement li = new LIElement();
  ParagraphElement p = new ParagraphElement();
  p
   ..text = tasksummary
    ..classes.add('summarytext');
  li
    ..classes.add('singletask')
    ..append(p);
  return li;
}

LIElement editTaskElement(String tasksummary) {
  LIElement li = new LIElement();
  TextInputElement ti = new TextInputElement();
  ti
    ..value = tasksummary
    ..classes.add('summarytext');
  li
    ..classes.add('singletask')
    ..casses.add('hideedittask')
    ..append(ti);
  return li;
}

// append for each task in tasks a singletask
// element to div '#listtasks'.
void displayTasks() {
  DivElement div = querySelector('#listtasks');
  List tl = loadFromStorage();
  tl.forEach((i) => div.append(singleTaskElement(i['summary'])));

}
// insert Task into displayed tasklist at index 0;
void insertTask(String tasksummary) {
  LIElement st = singleTaskElement(tasksummary);
  querySelector('#listtasks').children.insert(0,st);
}

library list_tasks;

import 'dart:html';
import 'package:ddays/storageservice.dart' show loadFromStorage;

LIElement singleTaskElement(String tasksummary) {
  LIElement li = new LIElement();
  ParagraphElement p = new ParagraphElement();
  p
   ..text = tasksummary
    ..classes.add('summarytext');
  li
    ..classes.add('singletask')
    ..append(p);
  return li;
}

LIElement editTaskElement(String tasksummary) {
  LIElement li = new LIElement();
  TextInputElement ti = new TextInputElement();
  ti
    ..value = tasksummary
    ..classes.add('summarytext');
  li
    ..classes.add('singletask')
    ..classes.add('hideedittask')
    ..append(ti);
  return li;
}

// append for each task in tasks a singletask
// element to div '#listtasks'.
void displayTasks() {
  DivElement div = querySelector('#listtasks');
  List tl = loadFromStorage();
  tl.forEach((i) => div.append(singleTaskElement(i['summary'])));

}
// insert Task into displayed tasklist at index 0;
void insertTask(String tasksummary) {
  LIElement st = singleTaskElement(tasksummary);
  querySelector('#listtasks').children.insert(0,st);
}

Fix typo in classes.add ...

Fix typo in classes.add ...


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

import 'package:scheduled_test/scheduled_stream.dart';

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

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

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

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

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

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

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

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

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

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

Fix binstub test on windows.

Fix binstub test on windows.

R=nweiz@google.com

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

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


// Copyright (c) 2014, the Liquid 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.

part of liquid;

/// [Context] that is used to propagate information through Virtual DOM.
///
/// [Component]'s implement this interface.
abstract class Context implements vdom.Context {
  /// Parent is attached to the DOM
  bool get isAttached;

  /// Depth relative to other Contexts, it is used to sort write tasks by
  /// its depth, so the lowest depth have the highest priority and will
  /// be executed first.
  int get _depth;
}

// Copyright (c) 2014, the Liquid 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.

part of liquid;

/// [Context] that is used to propagate information through Virtual DOM.
///
/// [Component]'s implement this interface.
abstract class Context implements vdom.Context {
  /// Parent is attached to the Document.
  bool get isAttached;

  /// Depth relative to other Contexts, it is used to sort write tasks by
  /// its depth, so the lowest depth have the highest priority and will
  /// be executed first.
  int get _depth;
}

Fix comment in Context class

Fix comment in Context class


#library('roguekit');

#import('dart:html', prefix: 'html');

#import('content.dart');
#import('engine.dart');
#import('ui.dart');
#import('util.dart');

main() {
  final content = createContent();

  final terminal = new DomTerminal(100, 40, html.document.query('#terminal'));
  final keyboard = new Keyboard(html.document);
  final ui = new UserInterface(keyboard, terminal);
  ui.push(new MainMenuScreen(content));

  final element = html.document.query('pre');

  tick(time) {
    ui.tick();
    html.window.webkitRequestAnimationFrame(tick, element);
  }

  html.window.webkitRequestAnimationFrame(tick, element);
}

class Fps {
  Fps() : ticks = new List(NUM_TICKS) {
    for (var i = 0; i < NUM_TICKS; i++) ticks[i] = 0;
  }

  tick(time) {
    // Get the duration between the oldest and newest ticks in the buffer.
    final start = ticks[head];
    final end = time;
    print((end - start) / NUM_TICKS);

    // Add it to the buffer.
    ticks[head] = time;
    head = (head + 1) % NUM_TICKS;
  }

  static final NUM_TICKS = 100;
  /// Circular buffer of past frame times.
  final List ticks;
  int head = 0;
}

#library('roguekit');

#import('dart:html', prefix: 'html');

#import('content.dart');
#import('engine.dart');
#import('ui.dart');
#import('util.dart');

main() {
  final content = createContent();

  final terminal = new DomTerminal(100, 40, html.document.query('#terminal'));
  final keyboard = new Keyboard(html.document);
  final ui = new UserInterface(keyboard, terminal);

  ui.push(new MainMenuScreen(content));

  /*
  final home = new HeroHome();
  final game = new Game(content.areas[0], 0, home);
  ui.push(new GameScreen(home, game));
  */

  final element = html.document.query('pre');

  tick(time) {
    ui.tick();
    html.window.webkitRequestAnimationFrame(tick, element);
  }

  html.window.webkitRequestAnimationFrame(tick, element);
}

class Fps {
  Fps() : ticks = new List(NUM_TICKS) {
    for (var i = 0; i < NUM_TICKS; i++) ticks[i] = 0;
  }

  tick(time) {
    // Get the duration between the oldest and newest ticks in the buffer.
    final start = ticks[head];
    final end = time;
    print((end - start) / NUM_TICKS);

    // Add it to the buffer.
    ticks[head] = time;
    head = (head + 1) % NUM_TICKS;
  }

  static final NUM_TICKS = 100;
  /// Circular buffer of past frame times.
  final List ticks;
  int head = 0;
}

Add temp code for going straight to game.


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

import 'package:angular/angular.dart';
import 'package:angular_components/content/deferred_content_aware.dart';

import 'material_drawer_base.dart';

/// A persistent drawer that can be pinned open or closed.
///
/// Need to include package:angular_components/app_layout/layout.scss.css
/// in the list of styleUrls of the containing component.
///
/// Works with deferred content.
/// __Example usage:__
///     <material-drawer persistent #drawer="drawer">
///         ... content here ...
///     </material-drawer>
///     <material-button (trigger)="drawer.toggle()">
///       Toggle Drawer
///     </material-button>
@Directive(
  selector: 'material-drawer[persistent]',
  exportAs: 'drawer',
  providers: const [
    const Provider(DeferredContentAware,
        useExisting: MaterialPersistentDrawerDirective),
  ],
  host: const {
    '[class.mat-drawer-collapsed]': '!visible',
    '[class.mat-drawer-expanded]': 'visible',
  },
  // TODO(google): Change to `Visibility.local` to reduce code size.
  visibility: Visibility.all,
)
class MaterialPersistentDrawerDirective extends MaterialDrawerBase {
  MaterialPersistentDrawerDirective() : super();
}

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

import 'package:angular/angular.dart';
import 'package:angular_components/content/deferred_content_aware.dart';

import 'material_drawer_base.dart';

/// A persistent drawer that can be pinned open or closed.
///
/// Need to include package:angular_components/app_layout/layout.scss.css
/// in the list of styleUrls of the containing component.
///
/// Works with deferred content.
/// __Example usage:__
///     <material-drawer persistent #drawer="drawer">
///         ... content here ...
///     </material-drawer>
///     <material-button (trigger)="drawer.toggle()">
///       Toggle Drawer
///     </material-button>
@Directive(
  selector: 'material-drawer[persistent]',
  exportAs: 'drawer',
  providers: const [
    const Provider(DeferredContentAware,
        useExisting: MaterialPersistentDrawerDirective),
  ],
  host: const {
    '[class.mat-drawer-collapsed]': '!visible',
    '[class.mat-drawer-expanded]': 'visible',
  },
  visibility: Visibility.all, // Injected by child elements.
)
class MaterialPersistentDrawerDirective extends MaterialDrawerBase {
  MaterialPersistentDrawerDirective() : super();
}

Remove visibility.all from @Component annotations. This is potentially BREAKING
change.

Please review carefully. Breakage will only be caught if the code is covered by
tests. Reject this change if you believe it breaks you.

If the component needs to be injected anywhere in the app, you can get a
runtime exception after this change. This should be caught by tests using your
components, and fixing the issue should be trivial, as the exceptions have good
error messages, such as "No provider found for FooComponent".

PiperOrigin-RevId: 189922359


// 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 polymer.src.reflected_type;

// These are used by _getReflectedTypeWorkaround, see http://dartbug.com/12607
@MirrorsUsed(targets:
    const ['_js_helper.createRuntimeType', 'dart._js_mirrors.JsClassMirror'],
    override: 'polymer.src.reflected_type')
import 'dart:mirrors';

// Horrible hack to work around: http://dartbug.com/12607
Type getReflectedTypeWorkaround(ClassMirror cls) {
  // On Dart VM, just return reflectedType.
  if (1.0 is! int) return cls.reflectedType;

  var mangledName = reflect(cls).getField(_mangledNameField).reflectee;
  Type type = _jsHelper.invoke(#createRuntimeType, [mangledName]).reflectee;
  return type;
}

final LibraryMirror _jsHelper =
    currentMirrorSystem().libraries[Uri.parse('dart:_js_helper')];

final Symbol _mangledNameField = () {
  var jsClassMirrorMirror = reflect(reflectClass(ClassMirror)).type;
  for (var name in jsClassMirrorMirror.variables.keys) {
    if (MirrorSystem.getName(name) == '_mangledName') return name;
  }
}();

// 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 polymer.src.reflected_type;

// These are used by _getReflectedTypeWorkaround, see http://dartbug.com/12607
@MirrorsUsed(targets:
    const ['_js_helper.createRuntimeType', 'dart._js_mirrors.JsClassMirror'],
    override: 'polymer.src.reflected_type')
import 'dart:mirrors';

// Horrible hack to work around: http://dartbug.com/12607
Type getReflectedTypeWorkaround(ClassMirror cls) {
  // On Dart VM, just return reflectedType.
  if (1.0 is! int) return cls.reflectedType;

  var mangledName = reflect(cls).getField(_mangledNameField).reflectee;
  Type type = _jsHelper.invoke(#createRuntimeType, [mangledName]).reflectee;
  return type;
}

final LibraryMirror _jsHelper =
    currentMirrorSystem().libraries[Uri.parse('dart:_js_helper')];

final Symbol _mangledNameField = () {
  var jsClassMirrorMirror = reflect(reflectClass(ClassMirror)).type;
  for (var name in jsClassMirrorMirror.declarations.keys) {
    if (MirrorSystem.getName(name) == '_mangledName') return name;
  }
}();

Remove use of deprecated mirror API from code that only runs against dart2js.

R=ahe@google.com, jmesserly@google.com

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

git-svn-id: 0aa7e0b98478d6ef7145d04e8154f8ab2209deba@30902 260f80e4-7a28-3924-810f-c04153c831b5


/// A wrapper around a native element inside of a View.
///
/// An `ElementRef` is backed by a render-specific element. In the browser, this
/// is usually a DOM element.
// Note: We don't expose things like `Injector`, `ViewContainer`, ... here, i.e.
// users have to ask for what they need. With that, we can build better analysis
// tools and could do better codegen in the future.
class ElementRef {
  /// The underlying native element or `null` if direct access to native
  /// elements is not supported (e.g. when the application runs in a web
  /// worker).
  ///
  /// Use with caution: Use this API as the last resort when direct access to
  /// DOM is needed. Use templating and data-binding provided by Angular
  /// instead. Alternatively you take a look at [Renderer] which provides API
  /// that can safely be used even when direct access to native elements is not
  /// supported.
  ///
  /// Relying on direct DOM access creates tight coupling between your
  /// application and rendering layers which will make it impossible to separate
  /// the two and deploy your application into a web worker.
  dynamic nativeElement;
  ElementRef(dynamic nativeElement) {
    this.nativeElement = nativeElement;
  }
}

/// A wrapper around a native element inside of a View.
///
/// An `ElementRef` is backed by a render-specific element. In the browser, this
/// is usually a DOM element.
// Note: We don't expose things like `Injector`, `ViewContainer`, ... here, i.e.
// users have to ask for what they need. With that, we can build better analysis
// tools and could do better codegen in the future.
class ElementRef {
  /// The underlying native element.
  ///
  /// Use with caution: Use this API as the last resort when direct access to
  /// DOM is needed. Use templating and data-binding provided by Angular
  /// instead.
  final dynamic nativeElement;
  ElementRef(this.nativeElement);
}

Make nativeElement final.
doc(ElementRef): cleanup.

-------------
Created by MOE: https://github.com/google/moe
MOE_MIGRATED_REVID=153537946


library sample_api;

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

import 'package:rpc/rpc.dart';

final List<String> names = ['Joe', 'John', 'Doe', 'Dohn'];

class StringResponse {
  String response;
  StringResponse(this.response);
}

@ApiClass(name: 'sample', version: 'v1')
class SampleApi {
  @ApiMethod(method: 'GET', path: 'hello/{name}')
  StringResponse hello(String name) {
    if (names.contains(name) == false) {
      throw new RpcError(HttpStatus.NOT_FOUND, 'Name not found', '$name doesn\'t exists');
    }

    return new StringResponse('Hello, $name');
  }

  @ApiMethod(method: 'GET', path: 'helloasync/{name}')
  Future<StringResponse> helloAsync(String name) async {
    if (names.contains(name) == false) {
      throw new RpcError(HttpStatus.NOT_IMPLEMENTED, 'Name not found', '$name doesn\'t exists');
    }

    return new StringResponse('Hello, $name');
  }
}

library sample_api;

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

import 'package:rpc/rpc.dart';

final List<String> names = ['Joe', 'John', 'Doe', 'Dohn'];

class StringResponse {
  String response;
  StringResponse(this.response);
}

@ApiClass(name: 'sample', version: 'v1')
class SampleApi {
  @ApiMethod(method: 'GET', path: 'hello1/{name}')
  StringResponse hello(String name) {
    if (names.contains(name) == false) {
      throw new RpcError(HttpStatus.NOT_FOUND, 'Name not found', '$name doesn\'t exists');
    }

    return new StringResponse('Hello, $name');
  }

  @ApiMethod(method: 'GET', path: 'hello2/{name}')
  Future<StringResponse> helloAsync(String name) async {
    if (names.contains(name) == false) {
      throw new RpcError(HttpStatus.NOT_FOUND, 'Name not found', '$name doesn\'t exists');
    }

    return new StringResponse('Hello, $name');
  }

  @ApiMethod(method: 'GET', path: 'hello3/{name}')
  Future<StringResponse> helloAsyncWithCompleter(String name) {
    var completer = new Completer();

    if (names.contains(name)) {
      completer.complete(new StringResponse('Hello, $name'));
    } else {
      throw new RpcError(HttpStatus.NOT_FOUND, 'Name not found', '$name doesn\'t exists');
    }

    return completer.future;
  }

  @ApiMethod(method: 'GET', path: 'hello4/{name}')
  Future<StringResponse> helloAsyncWithCompleterAndDelay(String name) async {
    var completer = new Completer();

    new Future.delayed(const Duration(seconds: 1), () {
      if (names.contains(name)) {
        completer.complete(new StringResponse('Hello, $name'));
      } else {
        completer.completeError(new RpcError(HttpStatus.NOT_FOUND, 'Name not found', '$name doesn\'t exists'));
      }
    });

    return completer.future;
  }
}

Add hello api method with completer and delay


import 'dart:io';
import 'dart:convert';
import 'package:source_maps/source_maps.dart';

main(List<String> args) {
  if (args.length < 2) {
    print('usage: read.dart <source-map-file> <name>');
    exit(1);
  }
  var sourcemapFile = new File.fromUri(Uri.base.resolve(args[0]));
  if (!sourcemapFile.existsSync()) {
    print('no source-map-file in ${args[0]}');
    exit(1);
  }
  var name = args[1];
  var json = jsonDecode(sourcemapFile.readAsStringSync());
  SingleMapping mapping = parseJson(json);
  var extensions = json['x_org_dartlang_dart2js'];
  if (extensions == null) {
    print('source-map file has no dart2js extensions');
    exit(1);
  }
  var minifiedNames = extensions['minified_names'];
  if (minifiedNames == null) {
    print('source-map file has no minified names in the dart2js extensions');
    exit(1);
  }
  var gid = minifiedNames['global'][name];
  if (gid != null) print('$name => ${mapping.names[gid]} (a global name)');
  var iid = minifiedNames['instance'][name];
  if (iid != null) print('$name => ${mapping.names[iid]} (an instance name)');
  if (gid == null && iid == null) print('Name \'$name\' not found.');
}

import 'dart:io';
import 'dart:convert';
import 'package:source_maps/source_maps.dart';
import 'package:dart2js_tools/src/dart2js_mapping.dart';

main(List<String> args) {
  if (args.length < 2) {
    print('usage: read.dart <source-map-file> <name>');
    exit(1);
  }
  var name = args[1];

  var sourcemapFile = new File.fromUri(Uri.base.resolve(args[0]));
  if (!sourcemapFile.existsSync()) {
    print('Error: no such file: $sourcemapFile');
    exit(1);
  }
  var json = jsonDecode(sourcemapFile.readAsStringSync());
  Dart2jsMapping mapping = Dart2jsMapping(parseJson(json), json);
  var global = mapping.globalNames[name];
  if (global != null) print('$name => $global (a global name)');
  var instance = mapping.instanceNames[name];
  if (instance != null) print('$name => $instance (an instance name)');
  if (global == null && instance == null) print('Name \'$name\' not found.');
}

Update lookup-name tool to use the dart2js_mapping implementation.

Note: the current implementation broke when we changed the encoding.
Change-Id: I48d9e5fedad3f3be85fc1e73dd5dd091bb7278b0
Reviewed-on: https://dart-review.googlesource.com/c/84881
Commit-Queue: Sigmund Cherem <beaea8fd7d2a56555046ba4f362c8a93e3938576@google.com>
Commit-Queue: Stephen Adams <60cb5b73b7e0cb7dcda53302da4fab6ecfc7fa8b@google.com>
Auto-Submit: Sigmund Cherem <beaea8fd7d2a56555046ba4f362c8a93e3938576@google.com>
Reviewed-by: Stephen Adams <60cb5b73b7e0cb7dcda53302da4fab6ecfc7fa8b@google.com>


import 'dart:io' as io;
import 'package:flutter_tools/src/device.dart';
import 'package:flutter_tools/src/doctor.dart';
import 'package:flutter_tools/src/base/context.dart';
import 'package:flutter_tools/src/base/logger.dart';

// import 'package:flutter_tools/src/commands/run.dart';
// import 'package:flutter_tools/src/commands/install.dart';

import '../lib/run_command.dart';

main(List<String> args) async {

  // Initialize globals.
  context[Logger] = new StdoutLogger();
  context[DeviceManager] = new DeviceManager();
  Doctor.initGlobal();

  // DeviceManager dm = context[DeviceManager];
  // var devices = await dm.getDevices();

  // print(devices);

  // print ("Devices enum complete");

  print ("About to create Run");

  RunCommand runCmd = new RunCommand();
  runCmd.run();

// InstallCommand installCommand = new InstallCommand();
// installCommand.run();
  //
  // RunCommand runCommand = new RunCommand();
  // runCommand.argResults = new
  // runCommand.argResults['hot'] = true;
  // runCommand.run();

}

import 'dart:io' as io;
import 'package:flutter_tools/src/android/android_sdk.dart';
import 'package:flutter_tools/src/device.dart';
import 'package:flutter_tools/src/doctor.dart';
import 'package:flutter_tools/src/base/context.dart';
import 'package:flutter_tools/src/base/logger.dart';

// import 'package:flutter_tools/src/commands/run.dart';
// import 'package:flutter_tools/src/commands/install.dart';

import '../lib/run_command.dart';

main(List<String> args) async {

  // Initialize globals.
  context[Logger] = new StdoutLogger();
  context[DeviceManager] = new DeviceManager();
  Doctor.initGlobal();

  context[AndroidSdk] = AndroidSdk.locateAndroidSdk();

  // DeviceManager dm = context[DeviceManager];
  // var devices = await dm.getDevices();

  // print(devices);

  // print ("Devices enum complete");

  print ("About to create Run");

  RunCommand runCmd = new RunCommand();
  runCmd.run();

// InstallCommand installCommand = new InstallCommand();
// installCommand.run();
  //
  // RunCommand runCommand = new RunCommand();
  // runCommand.argResults = new
  // runCommand.argResults['hot'] = true;
  // runCommand.run();

}

Add Android SDK to the context

Add Android SDK to the context


part of eventsourcing;

QueryHandler csvExtractor(
    QueryHandler sub, String array, String field, List<String> columns) {
  final String columnSeperator = "\\|";
  final String rowSeperator = "\\\$";

  return (Map<String, dynamic> data, QueriableConnection db) async {
    final Map result = await sub(new Map.from(data), db);

    final List arr = result[array];
    for (Map o in arr) {
      if (o.containsKey(field)) {
        final String x = o[field];
        final List<String> rows = x.split(rowSeperator);
        final List newField = [];

        for (int j = 0; j < rows.length; j++) {
          final Map newRow = {};
          final List<String> y = rows[j].split(columnSeperator);
          for (int k = 0; k < columns.length; k++) newRow[columns[k]] = y[k];
          newField.add(newRow);
        }
        o[field] = newField;
      }
    }

    return result;
  };
}

part of eventsourcing;

QueryHandler csvExtractor(
    QueryHandler sub, String array, String field, List<String> columns) {
  final String columnSeperator = "|";
  final String rowSeperator = "\$";

  return (Map<String, dynamic> data, QueriableConnection db) async {
    final Map result = await sub(new Map.from(data), db);

    final List arr = result[array];
    for (Map o in arr) {
      if (o.containsKey(field) && o[field] != null) {
        final String x = o[field];
        final List<String> rows = x.split(rowSeperator);
        final List newField = [];

        for (int j = 0; j < rows.length; j++) {
          final Map newRow = {};
          final List<String> y = rows[j].split(columnSeperator);
          for (int k = 0; k < columns.length; k++) newRow[columns[k]] = y[k];
          newField.add(newRow);
        }
        o[field] = newField;
      }
    }

    return result;
  };
}

Fix escaping of CSV parts

Fix escaping of CSV parts


import 'package:device_info_plus/device_info_plus.dart';

abstract class DeviceInfo {
  /// The end-user-visible name for the device.
  Future<String> get model;

  /// A unique identifier for the device.
  Future<String> get uniqueId;
}

class DeviceInfoImpl implements DeviceInfo {
  final DeviceInfoPlugin deviceInfoPlugin;

  DeviceInfoImpl(this.deviceInfoPlugin);

  @override
  Future<String> get model async {
    final androidInfo = await deviceInfoPlugin.androidInfo;
    return androidInfo.model;
  }

  @override
  Future<String> get uniqueId async {
    final androidInfo = await deviceInfoPlugin.androidInfo;
    return androidInfo.androidId;
  }
}

import 'package:device_info_plus/device_info_plus.dart';
import 'dart:io' show Platform;

abstract class DeviceInfo {
  /// The end-user-visible name for the device.
  Future<String> get model;

  /// A unique identifier for the device.
  Future<String> get uniqueId;
}

class DeviceInfoImpl implements DeviceInfo {
  final DeviceInfoPlugin deviceInfoPlugin;

  DeviceInfoImpl(this.deviceInfoPlugin);

  @override
  Future<String> get model async {
    if (Platform.isAndroid) {
      final androidInfo = await deviceInfoPlugin.androidInfo;
      return androidInfo.model;
    } else {
      final iosInfo = await deviceInfoPlugin.iosInfo;
      return iosInfo.utsname.machine;
    }
  }

  @override
  Future<String> get uniqueId async {
    if (Platform.isAndroid) {
      final androidInfo = await deviceInfoPlugin.androidInfo;
      return androidInfo.androidId;
    } else {
      final iosInfo = await deviceInfoPlugin.iosInfo;
      return iosInfo.identifierForVendor;
    }
  }
}

Add iOS support in device info check.

Add iOS support in device info check.


// Copyright (c) 2017, the Dart project authors.  Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
//
// Test that type tests are not misoptimized.
// VMOptions=--optimization-counter-threshold=1000 --optimization-filter=IsAnInt

main() {
  train();
  if (IsAnInt("This is not an int")) throw "oops";
}

// Prime the IC with things that are and are not ints.
void train() {
  for (int i = 0; i < 10000; i++) {
    IsAnInt(42); // Smi - always goes first in the generated code.
    IsAnInt(1 << 62); // Mint on 64 bit platforms.
    IsAnInt(1 << 62);
    IsAnInt(4200000000000000000000000000000000000); // BigInt
    IsAnInt(4200000000000000000000000000000000000);
    // This one that is not an int goes last in the IC because it is called
    // less frequently.
    IsAnInt(4.2);
  }
}

bool IsAnInt(f) => f is int;

// Copyright (c) 2017, the Dart project authors.  Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
//
// Test that type tests are not misoptimized.
// VMOptions=--optimization-counter-threshold=1000 --optimization-filter=IsAnInt

main() {
  train();
  if (IsAnInt("This is not an int")) throw "oops";
}

// Prime the IC with things that are and are not ints.
void train() {
  int sum = 0;
  for (int i = 0; i < 10000; i++) {
    IsAnInt(42); // Smi - always goes first in the generated code.
    IsAnInt(1 << 62); // Mint on 64 bit platforms.
    IsAnInt(1 << 62);
    IsAnInt(4200000000000000000000000000000000000); // BigInt
    IsAnInt(4200000000000000000000000000000000000);
    // This one that is not an int goes last in the IC because it is called
    // less frequently.
    IsAnInt(4.2);
  }
}

int IsAnInt(Foo f) => f is int;

Revert "Fix misoptimization of 'is' test"

R=johnniwinther@google.com
BUG=

This reverts commits fc693153d1c79e8303abe05697a1d8458b0fef62
and b7797ac45fe6d58d5dae6c4db3094afb1dfaa4bc, code review at
https://codereview.chromium.org/2904543002.  Revert is due to
an AOT failure.
Review-Url: https://codereview.chromium.org/2908153002 .


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

class PlaceholderSnapSheetExample extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Placeholder example'),
      ),
      body: SnappingSheet(
          child: Placeholder(
            color: Colors.red,
          ),
          sheetBelow: SnappingSheetContent(
              child: Placeholder(
                color: Colors.blue,
              ),
              heightBehavior: SnappingSheetHeight.fixed(expandOnSnapPositionOverflow: false)),
          grabbing: Container(
            color: Colors.white.withOpacity(0.0),
            child: Placeholder(
              color: Colors.green,
            ),
          ),
          sheetAbove: SnappingSheetContent(
            child: Placeholder(
              color: Colors.purple,
            ),
            heightBehavior: SnappingSheetHeight.fixed(expandOnSnapPositionOverflow: false),
          )),
    );
  }
}

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

class PlaceholderSnapSheetExample extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Placeholder example'),
      ),
      body: SnappingSheet(
          child: Placeholder(
            color: Colors.red,
          ),
          sheetBelow: SnappingSheetContent(
              child: Placeholder(
                color: Colors.blue,
              ),
              heightBehavior: SnappingSheetHeight.fit()),
          grabbing: Container(
            color: Colors.white.withOpacity(0.0),
            child: Placeholder(
              color: Colors.green,
            ),
          ),
          sheetAbove: SnappingSheetContent(
            child: Placeholder(
              color: Colors.purple,
            ),
            heightBehavior: SnappingSheetHeight.fit(),
          )),
    );
  }
}

Revert placeholder example to use hight fit again


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

abstract class Timer {
  /**
   * Creates a new timer. The [callback] callback is invoked after
   * [milliSeconds] milliseconds.
   */
  factory Timer(int milliSeconds, void callback(Timer timer)) {
    if (_TimerFactory._factory == null) {
      throw new UnsupportedOperationException("Timer interface not supported.");
    }
    return _TimerFactory._factory(milliSeconds, callback, false);
  }

  /**
   * Creates a new repeating timer. The [callback] is invoked every
   * [milliSeconds] millisecond until cancelled.
   */
  factory Timer.repeating(int milliSeconds, void callback(Timer timer)) {
    if (_TimerFactory._factory == null) {
      throw new UnsupportedOperationException("Timer interface not supported.");
    }
    return _TimerFactory._factory(milliSeconds, callback, true);
  }

  /**
   * Cancels the timer.
   */
  void cancel();
}

// TODO(ajohnsen): Patch timer once we have support for patching named
//                 factory constructors in the VM.

typedef Timer _TimerFactoryClosure(int milliSeconds,
                                   void callback(Timer timer),
                                   bool repeating);

class _TimerFactory {
  static _TimerFactoryClosure _factory;
}

void _setTimerFactoryClosure(_TimerFactoryClosure closure) {
  _TimerFactory._factory = closure;
}

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

abstract class Timer {
  /**
   * Creates a new timer. The [callback] callback is invoked after
   * [milliSeconds] milliseconds.
   */
  factory Timer(int milliSeconds, void callback(Timer timer)) {
    if (_TimerFactory._factory == null) {
      throw new UnsupportedOperationException("Timer interface not supported.");
    }
    return _TimerFactory._factory(milliSeconds, callback, false);
  }

  /**
   * Creates a new repeating timer. The [callback] is invoked every
   * [milliSeconds] millisecond until cancelled.
   */
  factory Timer.repeating(int milliSeconds, void callback(Timer timer)) {
    if (_TimerFactory._factory == null) {
      throw new UnsupportedOperationException("Timer interface not supported.");
    }
    return _TimerFactory._factory(milliSeconds, callback, true);
  }

  /**
   * Cancels the timer.
   */
  void cancel();
}

// TODO(ajohnsen): Patch timer once we have support for patching named
//                 factory constructors in the VM.

typedef Timer _TimerFactoryClosure(int milliSeconds,
                                   void callback(Timer timer),
                                   bool repeating);

class _TimerFactory {
  static _TimerFactoryClosure _factory;
}

// TODO(ahe): Warning: this is NOT called by Dartium. Instead, it sets
// [_TimerFactory._factory] directly.
void _setTimerFactoryClosure(_TimerFactoryClosure closure) {
  _TimerFactory._factory = closure;
}

Add warning for future maintainers of Timer.

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

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


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

import 'dart:io';
import 'dart:isolate';

const SPAWN_PACKAGE_ROOT = "otherPackageRoot";

void main([args, port]) {
  if (port != null) {
    testPackageRoot(args);
    return;
  }
  var p = new ReceivePort();
  Isolate.spawnUri(Platform.script,
                   [p.sendPort, Platform.packageRoot],
                   {},
                   packageRoot: SPAWN_PACKAGE_ROOT);
  p.listen((msg) {
    p.close();
  });
}

void testPackageRoot(args) {
  var parentPackageRoot = args[1];
  if (parentPackageRoot == Platform.packageRoot) {
    throw "Got parent package root";
  }
  if (Platform.packageRoot != SPAWN_PACKAGE_ROOT) {
    throw "Wrong package root";
  }
  args[0].send(null);
}

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

import 'dart:io';
import 'dart:isolate';

final SPAWN_PACKAGE_ROOT = Uri.parse("otherPackageRoot");

void main([args, port]) {
  if (port != null) {
    testPackageRoot(args);
    return;
  }
  var p = new ReceivePort();
  Isolate.spawnUri(Platform.script,
                   [p.sendPort, Platform.packageRoot],
                   {},
                   packageRoot: SPAWN_PACKAGE_ROOT);
  p.listen((msg) {
    p.close();
  });
}

void testPackageRoot(args) {
  var parentPackageRoot = args[1];
  if (parentPackageRoot == Platform.packageRoot) {
    throw "Got parent package root";
  }
  if (Uri.parse(Platform.packageRoot) != SPAWN_PACKAGE_ROOT) {
    throw "Wrong package root";
  }
  args[0].send(null);
}

Fix test in checked mode.

Fix test in checked mode.

BUG=

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

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


@TestOn('windows')

import 'dart:ffi';
import 'package:ffi/ffi.dart';

import 'package:test/test.dart';
import 'package:win32/win32.dart';

void main() {
  test('Volume management API', () {
    final volumeNamePtr =
        allocate<Uint16>(count: MAX_PATH).cast<Utf16>().cast<Utf16>();

    final hFindVolume = FindFirstVolume(volumeNamePtr, MAX_PATH);
    expect(hFindVolume, isNot(INVALID_HANDLE_VALUE));

    final volume = volumeNamePtr.unpackString(MAX_PATH);

    expect(volume, startsWith('\\\\?\\'));

    free(volumeNamePtr);
  });

  test('Power management API', () {
    final powerStatus = SYSTEM_POWER_STATUS.allocate();

    final result = GetSystemPowerStatus(powerStatus.addressOf);

    // Sanity check results against some API provided ranges
    final validBatteryPercentages = [for (var i = 0; i <= 100; i += 1) i]
      ..add(255); // [0..100, 255]

    expect(result, isNonZero);
    expect(powerStatus.ACLineStatus, isIn([0, 1, 255]));
    expect(powerStatus.SystemStatusFlag, isIn([0, 1]));
    expect(powerStatus.BatteryLifePercent, isIn(validBatteryPercentages));

    free(powerStatus.addressOf);
  });
}

@TestOn('windows')

import 'dart:ffi';
import 'package:ffi/ffi.dart';

import 'package:test/test.dart';
import 'package:win32/win32.dart';

void main() {
  test('Volume management API', () {
    final volumeNamePtr =
        allocate<Uint16>(count: MAX_PATH).cast<Utf16>().cast<Utf16>();

    final hFindVolume = FindFirstVolume(volumeNamePtr, MAX_PATH);
    expect(hFindVolume, isNot(INVALID_HANDLE_VALUE));

    final volume = volumeNamePtr.unpackString(MAX_PATH);

    expect(volume, startsWith(r'\\?\'));

    free(volumeNamePtr);
  });

  test('Power management API', () {
    final powerStatus = SYSTEM_POWER_STATUS.allocate();

    final result = GetSystemPowerStatus(powerStatus.addressOf);

    // Sanity check results against some API provided ranges
    final validBatteryPercentages = [for (var i = 0; i <= 100; i += 1) i]
      ..add(255); // [0..100, 255]

    expect(result, isNonZero);
    expect(powerStatus.ACLineStatus, isIn([0, 1, 255]));
    expect(powerStatus.SystemStatusFlag, isIn([0, 1]));
    expect(powerStatus.BatteryLifePercent, isIn(validBatteryPercentages));

    free(powerStatus.addressOf);
  });
}

Use raw string for legibility

Use raw string for legibility


// Copyright (c) 2014, the Dart project authors.  Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
//
// Test write barrier verification mode.
// VMOptions=--verified_mem --verify_before_gc --verify_after_gc --old_gen_growth_rate=1

var a = [];

void main() {
  for (int i = 0; i < 12; ++i) {
    a.add(new List(12345));
  }
  for (int i = 0; i < 1234; ++i) {
    a[0] = new List(100000);
  }
}

// Copyright (c) 2014, the Dart project authors.  Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
//
// Test write barrier verification mode.
// VMOptions=--verify_before_gc --verify_after_gc --old_gen_growth_rate=1

var a = [];

void main() {
  for (int i = 0; i < 12; ++i) {
    a.add(new List(12345));
  }
  for (int i = 0; i < 1234; ++i) {
    a[0] = new List(100000);
  }
}

Remove verified-mem option from test as it is being deprecated.

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


import 'package:ddays/storageservice.dart';
import 'package:test/test.dart';
import 'dart:html';
import 'dart:convert';

void initStorage() {
  window.localStorage[STORAGE_KEY] = JSON.encode([]);
}

void main() {
  test('

Add initstorage function for tests

Add initstorage function for tests


library pin;

import 'dart:async';
import 'dart:collection';
import 'dart:convert';
import 'dart:io';
import 'dart:mirrors';

import 'package:crypto/crypto.dart';
import 'package:http/http.dart' as LibHttp;
import 'package:path/path.dart' as LibPath;
import 'package:logging/logging.dart';

import 'package:oauth2/oauth2.dart' as OAuth2;
import 'package:google_oauth2_client/google_oauth2_console.dart' as GoogleOAuth;
import 'package:google_drive_v2_api/drive_v2_api_console.dart' as GoogleDrive;
import 'package:google_drive_v2_api/drive_v2_api_client.dart' as GoogleDriveClient show File, FileList;

part 'google/oauth.dart';
part 'google/drive.dart';

part 'utility/logger.dart';
part 'utility/serializer.dart';
part 'utility/time.dart';
part 'utility/utility.dart';

library pin;

import 'dart:async';
import 'dart:collection';
import 'dart:convert';
import 'dart:io';
import 'dart:mirrors';

import 'package:crypto/crypto.dart';
import 'package:http/http.dart' as LibHttp;
import 'package:path/path.dart' as LibPath;
import 'package:logging/logging.dart';

import 'package:oauth2/oauth2.dart' as OAuth2;
import 'package:google_oauth2_client/google_oauth2_console.dart' as GoogleOAuth;
import 'package:google_drive_v2_api/drive_v2_api_console.dart' as GoogleDrive;
import 'package:google_drive_v2_api/drive_v2_api_client.dart' as GoogleDriveClient show File, FileList;

part 'google/oauth.dart';
part 'google/drive.dart';

part 'utility/logger.dart';
part 'utility/serializable.dart';
part 'utility/time.dart';
part 'utility/utility.dart';

Fix part code file name.

Fix part code file name.


part of app;

/**
 * Notification resource.
 */
@Injectable()
class NotificationsResource {
  final Api _api;

  NotificationsResource(this._api);

  /**
   * Returns all (or unread only) notifications for actually logged in user.
   */
  Future<List<Notification>> readAll([bool unreadOnly = false]) {
    var params = unreadOnly
      ? {'unread': unreadOnly}
      : {};
    return _api.get('notifications', params: params).then((HttpResponse response) {
      var notifications = response.data.map((data) {
        return new Notification(data['id'], DateTime.parse(data['created']), data['read'], data['text'], data['target']);
      });
      return new Future.value(notifications);
    });
  }

  /**
   * Marks all notifications as read.
   */
  Future updateAll(bool read) {
    return _api.put('notifications', data: {'read' : read}).then((_) {
      return new Future.value();
    });
  }
}

part of app;

/**
 * Notification resource.
 */
@Injectable()
class NotificationsResource {
  final Api _api;

  NotificationsResource(this._api);

  /**
   * Returns all (or unread only) notifications for currently logged user.
   */
  Future<List<Notification>> readAll([bool unreadOnly = false]) {
    var params = unreadOnly
      ? {'unread': unreadOnly}
      : {};
    return _api.get('notifications', params: params).then((HttpResponse response) {
      var notifications = response.data.map((data) {
        return new Notification(data['id'], DateTime.parse(data['created']), data['read'], data['text'], data['target']);
      });
      return new Future.value(notifications);
    });
  }

  /**
   * Marks all notifications as read.
   */
  Future updateAll(bool read) {
    return _api.put('notifications', data: {'read' : read}).then((_) {
      return new Future.value();
    });
  }

  /**
   * Marks given notification as read.
   */
  Future update(Notification notification, bool read) {
    return _api.put('notifications/' + notification.id.toString(), data: {'read' : read}).then((_) {
      return new Future.value();
    });
  }
}

Add update method for single notification


part of xml;

/// Enum of the different XML Node types.
class XmlNodeType {

  static const ELEMENT = const XmlNodeType._('ELEMENT');
  static const ATTRIBUTE = const XmlNodeType._('ATTRIBUTE');
  static const TEXT = const XmlNodeType._('TEXT');
  static const CDATA = const XmlNodeType._('CDATA');
  static const PROCESSING = const XmlNodeType._('PROCESSING');
  static const COMMENT = const XmlNodeType._('COMMENT');
  static const DOCUMENT = const XmlNodeType._('DOCUMENT');
  static const DOCUMENT_FRAGMENT = const XmlNodeType._('DOCUMENT_FRAGMENT');
  static const DOCUMENT_TYPE = const XmlNodeType._('DOCUMENT_TYPE');

  final String _type;

  const XmlNodeType._(this._type);

  @override
  String toString() => 'XmlNodeType.$_type';

}

part of xml;

/// Enum of the different XML Node types.
enum XmlNodeType {
  ELEMENT,
  ATTRIBUTE,
  TEXT,
  CDATA,
  PROCESSING,
  COMMENT,
  DOCUMENT,
  DOCUMENT_FRAGMENT,
  DOCUMENT_TYPE
}

Make the XmlNodeType an enum

Make the XmlNodeType an enum


#library('Collection View for My Comic Book Collection');

#import('https://raw.github.com/eee-c/hipster-mvc/master/HipsterView.dart');

class Comics extends HipsterView {
  Comics([collection, el]):
    super(collection:collection, el:el);

  post_initialize() {
    _subscribeEvents();
    _attachUiHandlers();
  }

  _subscribeEvents() {
    if (collection == null) return;

    collection.on.load.add((event) { render(); });
    collection.on.insert.add((event) { render(); });
  }

  render() {
    el.innerHTML = template(collection);
  }

  template(list) {
    // This is silly, but [].forEach is broke
    if (list.length == 0) return '';

    var html = '';
    list.forEach((comic) {
      html += _singleComicBookTemplate(comic);
    });
    return html;
  }

  _singleComicBookTemplate(comic) {
    return """

        ${comic['title']}
        (${comic['author']})
        [delete]

    """;
  }

  _attachUiHandlers() {
    attachHandler(el, 'click .delete', (event) {
      print("[delete] ${event.target.parent.id}");
      collection[event.target.parent.id].
        delete().
        then((_) {
          event.target.parent.remove();
        });
    });
  }

}

#library('Collection View for My Comic Book Collection');

#import('https://raw.github.com/eee-c/hipster-mvc/master/HipsterView.dart');

class Comics extends HipsterView {
  Comics([collection, el]):
    super(collection:collection, el:el);

  post_initialize() {
    _subscribeEvents();
    _attachUiHandlers();
  }

  _subscribeEvents() {
    if (collection == null) return;

    collection.on.load.add((event) { render(); });
    collection.on.insert.add((event) { render(); });
  }

  render() {
    el.innerHTML = template(collection);
  }

  template(list) {
    // This is silly, but [].forEach is broke
    if (list.length == 0) return '';

    var html = '';
    list.forEach((comic) {
      html = html.concat(
        _singleComicBookTemplate(comic)
      );
    });
    return html;
  }

  _singleComicBookTemplate(comic) {
    return """

        ${comic['title']}
        (${comic['author']})
        [delete]

    """;
  }

  _attachUiHandlers() {
    attachHandler(el, 'click .delete', (event) {
      print("[delete] ${event.target.parent.id}");
      collection[event.target.parent.id].
        delete().
        then((_) {
          event.target.parent.remove();
        });
    });
  }

}

Update for new concat syntax

Update for new concat syntax


import 'package:flutter/foundation.dart';
import 'package:flutter/widgets.dart';
import 'package:qr/qr.dart';

import 'qr_painter.dart';

class QrImage extends StatelessWidget {
  QrImage({
    @required String data,
    this.size,
    this.padding = const EdgeInsets.all(10.0),
    this.backgroundColor,
    Color foregroundColor = const Color(0xFF000000),
    int version = 4,
    int errorCorrectionLevel = QrErrorCorrectLevel.L,
    this.onError,
  }) : _painter = new QrPainter(data, foregroundColor, version, errorCorrectionLevel, onError: onError);

  final QrPainter _painter;
  final Color backgroundColor;
  final EdgeInsets padding;
  final double size;
  final QrError onError;

  @override
  Widget build(BuildContext context) {
    return new Container(
      width: size,
      height: size,
      color: backgroundColor,
      child: new Padding(
        padding: this.padding,
        child: new CustomPaint(
          painter: _painter,
        ),
      ),
    );
  }
}

import 'package:flutter/foundation.dart';
import 'package:flutter/widgets.dart';
import 'package:qr/qr.dart';

import 'qr_painter.dart';

class QrImage extends StatelessWidget {
  QrImage({
    @required String data,
    this.size,
    this.padding = const EdgeInsets.all(10.0),
    this.backgroundColor,
    Color foregroundColor = const Color(0xFF000000),
    int version = 4,
    int errorCorrectionLevel = QrErrorCorrectLevel.L,
    this.onError,
  }) : _painter = new QrPainter(data, foregroundColor, version, errorCorrectionLevel, onError: onError);

  final QrPainter _painter;
  final Color backgroundColor;
  final EdgeInsets padding;
  final double size;
  final QrError onError;

  @override
  Widget build(BuildContext context) {
    return LayoutBuilder(
      builder: (context, constraints) {
        double widgetSize = size ?? constraints.biggest.shortestSide;
        return new Container(
          width: widgetSize,
          height: widgetSize,
          color: backgroundColor,
          child: new Padding(
            padding: this.padding,
            child: new CustomPaint(
              painter: _painter,
            ),
          ),
        );
      },
    );
  }
}

Add automatic widget size determination when no size property is provided.


library storageservice;

import 'dart:html';
import 'dart:convert';

final String STORAGE_KEY = 'ddays';

// add an item to a given List, then save
// this list in localStorage with the key 'STORAGE_KEY'.
void saveToStorage(storedlist, item) {
  storedlist.add(item);
  window.localStorage[STORAGE_KEY] = JSON.encode(storedlist);
}

// restore a to localstorage, under key 'STORAGE_KEY',
// saved List.
List loadFromStorage() {
  return JSON.decode(window.localStorage[STORAGE_KEY]);
}

// delete a item from local Storage object with key 'STORAGE_KEY'.
void deleteItemInStorage(item) {
  var storedlist = loadFromStorage().where((i) => i.timestamp == item.timestamp);
  window.localStorage[STORAGE_KEY] = JSON.encode(storedlist);
}

// delete localStorage key.
void deleteStorage() {
  window.localStorage.clear();
}

library storageservice;

import 'dart:html';
import 'dart:convert';

final String STORAGE_KEY = 'ddays';

List tasklist = [];

// add an item to a given List, then save
// this list in localStorage with the key 'STORAGE_KEY'.
void saveToStorage(item) {
  tasklist.add(item);
  window.localStorage[STORAGE_KEY] = JSON.encode(storedlist);
}

// restore a to localstorage, under key 'STORAGE_KEY',
// saved List.
List loadFromStorage() {
  return JSON.decode(window.localStorage[STORAGE_KEY]);
}

// delete a item from local Storage object with key 'STORAGE_KEY'.
void deleteItemInStorage(item) {
  var storedlist = loadFromStorage().where((i) => i.timestamp == item.timestamp);
  window.localStorage[STORAGE_KEY] = JSON.encode(storedlist);
}

// delete localStorage key.
void deleteStorage() {
  window.localStorage.clear();
}

Add reference to global tasklist.

Add reference to global tasklist.


import 'package:flutter/material.dart';

class BulletItem extends StatelessWidget {
  final String text;

  const BulletItem(this.text, {Key key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Padding(
        padding: const EdgeInsets.only(
          left: 10,
        ),
        child: Row(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            const Text('•'),
            const SizedBox(width: 4),
            Expanded(
              child: Text(text),
            ),
          ],
        ));
  }
}

import 'package:flutter/material.dart';

class BulletItem extends StatelessWidget {
  final String text;
  final double fontSize;

  const BulletItem(
    this.text, {
    Key key,
    this.fontSize = 14,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Padding(
        padding: const EdgeInsets.only(
          left: 10,
        ),
        child: Row(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(
              '•',
              style: TextStyle(fontSize: fontSize),
            ),
            const SizedBox(width: 4),
            Expanded(
              child: Text(
                text,
                style: TextStyle(fontSize: fontSize),
              ),
            ),
          ],
        ));
  }
}

Allow font size for BulletItem.

Allow font size for BulletItem.


import 'dart:io';
import "controllers/HomeController.dart";
import "controllers/ApiController.dart";

typedef bool Handler(HttpRequest request);

void main() {

  String connectionStringRedis = "127.0.0.1:6379/0";

  HttpServer.bind(InternetAddress.ANY_IP_V4, 80).then((HttpServer server) {

    foobar breaking the build on purpose!!

    var routeTable = new Map<String, Handler>();
    var homeController = new HomeController();
    var apiController = new ApiController(connectionStringRedis);

    routeTable["/"] = homeController.Index;
    routeTable["/pingdom"] = homeController.Pingdom;
    routeTable["/api/users"] = apiController.Users;
    routeTable["/api/polls"] = apiController.Polls;
    routeTable["/api/votes"] = apiController.Votes;

    server.listen((HttpRequest request) {

      var now = new DateTime.now();
      var path = request.uri.path;
      print("$now: $path");

      var routeFound = false;
      routeTable.keys.forEach((String pattern)
      {
        if ((!routeFound) && (path == pattern)) // TODO check patterns with placeholders
        {
          routeFound = routeTable[pattern](request);
        }
      });

      if (!routeFound) {
        request.response.statusCode = 404;
        request.response.write("404 not found");
        request.response.close();
      }
    });

  var now = new DateTime.now();
  print("$now: listing....");
  });

}

import 'dart:io';
import "controllers/HomeController.dart";
import "controllers/ApiController.dart";

typedef bool Handler(HttpRequest request);

void main() {

  String connectionStringRedis = "127.0.0.1:6379/0";

  HttpServer.bind(InternetAddress.ANY_IP_V4, 80).then((HttpServer server) {

    var routeTable = new Map<String, Handler>();
    var homeController = new HomeController();
    var apiController = new ApiController(connectionStringRedis);

    routeTable["/"] = homeController.Index;
    routeTable["/pingdom"] = homeController.Pingdom;
    routeTable["/api/users"] = apiController.Users;
    routeTable["/api/polls"] = apiController.Polls;
    routeTable["/api/votes"] = apiController.Votes;

    server.listen((HttpRequest request) {

      var now = new DateTime.now();
      var path = request.uri.path;
      print("$now: $path");

      var routeFound = false;
      routeTable.keys.forEach((String pattern)
      {
        if ((!routeFound) && (path == pattern)) // TODO check patterns with placeholders
        {
          routeFound = routeTable[pattern](request);
        }
      });

      if (!routeFound) {
        request.response.statusCode = 404;
        request.response.write("404 not found");
        request.response.close();
      }
    });

  var now = new DateTime.now();
  print("$now: listing....");
  });

}

Revert "breaking the build on purpose"

Revert "breaking the build on purpose"

This reverts commit b294e5ffb1fd96119a6f5c0b139a3639e4b8a29e.


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

import 'dart:io';

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

const SCRIPT = """
import 'dart:io';

main() {
  ProcessSignal.SIGHUP.watch().listen(print);

  print("ready");
}
""";

main() {
  initConfig();
  integration('forwards signals to the inner script', () {
    d.dir(appPath, [
      d.appPubspec(),
      d.dir("bin", [
        d.file("script.dart", SCRIPT)
      ])
    ]).create();

    var pub = pubRun(args: ["bin/script"]);

    pub.stdout.expect("ready");
    pub.signal(Process.SIGINT);
    pub.stdout.expect("SIGINT");

    pub.kill();
  });
}

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

import 'dart:io';

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

const SCRIPT = """
import 'dart:io';

main() {
  ProcessSignal.SIGHUP.watch().listen(print);

  print("ready");
}
""";

main() {
  initConfig();
  integration('forwards signals to the inner script', () {
    d.dir(appPath, [
      d.appPubspec(),
      d.dir("bin", [
        d.file("script.dart", SCRIPT)
      ])
    ]).create();

    var pub = pubRun(args: ["bin/script"]);

    pub.stdout.expect("ready");
    pub.signal(ProcessSignal.SIGHUP);
    pub.stdout.expect("SIGHUP");

    pub.kill();
  });
}

Fix windows signal test
(this amends a bit the changes in
https://code.google.com/p/dart/source/detail?r=44902)

R=kevmoo@google.com

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

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


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);
  }
}

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}",
    "--trust-type-annotations",
    "--trust-primitives"
  ];

  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);
  }
}

Use some dart2js flags to improve compiled output.


part of quiz;

// RequestSunk is one of the base classes in the Aqueduct pipeline
class QuizRequestSink extends RequestSink {
  // Configuration loaded by Dart library safe_config also from Stable|Kernel
  static String ConfigurationKey = "QuizRequestSink.Configuration";
  final Logger log = new Logger('QuizRequestSink');

  QuizRequestSink(Map<String, dynamic> options) : super(options) {
    var dataModel = new ManagedDataModel.fromPackageContainingType(QuizRequestSink);

    var config = options[ConfigurationKey];
    var db = config.database;
    var persistentStore = new PostgreSQLPersistentStore.fromConnectionInfo(db.username, db.password, db.host, db.port, db.databaseName);

    logger.onRecord.listen((rec) => print("${rec.level.name}: ${rec.time}: ${rec.message}"));

    context = new ManagedContext(dataModel, persistentStore);
  }

  ManagedContext context;

  @override
  void setupRouter(Router router) {
    router
      .route("/api/questions/[:index(\\d+)]")
      .generate(() => new QuestionController());

    // Catch-all for static files
    router
      .route("/*")
      .generate(() => new StaticFilesController());
    Response.addEncoder(io.ContentType.parse("application/javascript"), (j) => j.toString());
  }
}

// QuizConfiguration reads and validates the DB configuration from a YAML file
// See https://pub.dartlang.org/packages/safe_config for documentation of ConfigurationItem
class QuizConfiguration extends ConfigurationItem {
  QuizConfiguration(String fileName) : super.fromFile(fileName);

  DatabaseConnectionConfiguration database;
}

part of quiz;

// RequestSunk is one of the base classes in the Aqueduct pipeline
class QuizRequestSink extends RequestSink {
  // Configuration loaded by Dart library safe_config also from Stable|Kernel
  static String ConfigurationKey = "QuizRequestSink.Configuration";
  final Logger log = new Logger('QuizRequestSink');

  QuizRequestSink(Map<String, dynamic> options) : super(options) {
    var dataModel = new ManagedDataModel.fromCurrentMirrorSystem();

    var config = options[ConfigurationKey];
    var db = config.database;
    var persistentStore = new PostgreSQLPersistentStore.fromConnectionInfo(db.username, db.password, db.host, db.port, db.databaseName);

    logger.onRecord.listen((rec) => print("${rec.level.name}: ${rec.time}: ${rec.message}"));

    context = new ManagedContext(dataModel, persistentStore);
  }

  ManagedContext context;

  @override
  void setupRouter(Router router) {
    router
      .route("/api/questions/[:index(\\d+)]")
      .generate(() => new QuestionController());

    // Catch-all for static files
    router
      .route("/*")
      .generate(() => new StaticFilesController());
    Response.addEncoder(io.ContentType.parse("application/javascript"), (j) => j.toString());
  }
}

// QuizConfiguration reads and validates the DB configuration from a YAML file
// See https://pub.dartlang.org/packages/safe_config for documentation of ConfigurationItem
class QuizConfiguration extends ConfigurationItem {
  QuizConfiguration(String fileName) : super.fromFile(fileName);

  DatabaseConnectionConfiguration database;
}

Replace deprecated ManagedDataModel.fromPackageContainingType() by ManagedDataModel.fromCurrentMirrorSystem().


library more.iterable.math;

import 'dart:collection' show IterableBase;

import 'package:more/src/iterable/fold.dart';

/// Returns an iterable over the fibonacci sequence starting with [f0] and
/// [f1]. The default sequence is indefinitely long and by default starts
/// with 0, 1, 1, 2, 3, 5, 8, 13, ...
Iterable<int> fibonacci([int f0 = 0, int f1 = 1]) {
  return fold([f0, f1], (args) => args[0] + args[1]);
}

/// Returns an iterable over the digits of the [number], in the optionally
/// given [base].
Iterable<int> digits(int number, [int base = 10]) {
  return DigitIterable(number.abs(), base);
}

class DigitIterable extends IterableBase<int> {
  final int number;
  final int base;

  DigitIterable(this.number, this.base);

  @override
  Iterator<int> get iterator => DigitIterator(number, base);
}

class DigitIterator extends Iterator<int> {
  int number;
  final int base;

  DigitIterator(this.number, this.base);

  @override
  int current;

  @override
  bool moveNext() {
    if (number == null) {
      current = null;
      return false;
    } else {
      current = number % base;
      number = number ~/ base;
      if (number == 0) {
        number = null;
      }
      return true;
    }
  }
}

library more.iterable.math;

import 'package:more/src/iterable/fold.dart';

/// Returns an iterable over the fibonacci sequence starting with [f0] and
/// [f1]. The default sequence is indefinitely long and by default starts
/// with 0, 1, 1, 2, 3, 5, 8, 13, ...
Iterable<int> fibonacci([int f0 = 0, int f1 = 1]) {
  return fold([f0, f1], (args) => args[0] + args[1]);
}

/// Returns an iterable over the digits of the [value], in the optionally
/// given [base].
Iterable<int> digits(int value, [int base = 10]) sync* {
  if (value == 0) {
    yield 0;
  } else {
    var number = value.abs();
    while (number != 0) {
      final next = number ~/ base;
      yield number - next * base;
      number = next;
    }
  }
}

Simplify the implementation of the digits iterable.


// 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:test/test.dart';

import '../utils.dart';

void main() {
  group('help', help);
}

void help() {
  TestProject p;

  tearDown(() => p?.dispose());

  test('pub', () {
    p = project();
    var result = p.runSync('help', ['pub']);

    var pubHelpResult = p.runSync('pub', ['help']);
    expect(result.stdout, contains(pubHelpResult.stdout));
    expect(result.stderr, contains(pubHelpResult.stderr));
  });
}

// 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:args/command_runner.dart';
import 'package:dartdev/dartdev.dart';
import 'package:test/test.dart';

import '../utils.dart';

void main() {
  group('help', help);
}

void help() {
  TestProject p;

  tearDown(() => p?.dispose());

  /// Commands not tested by the following loop.
  List<String> _commandsNotTested = <String>[
    'help', // `dart help help` is redundant
    'test' // TODO(jwren) not yet implemented, dartbug.com/41041
  ];
  DartdevRunner([]).commands.forEach((String commandKey, Command command) {
    if (!_commandsNotTested.contains(commandKey)) {
      test('(help $commandKey == $commandKey --help)', () {
        p = project();
        var result = p.runSync('help', [commandKey]);

        var verbHelpResult = p.runSync(commandKey, ['--help']);
        expect(result.stdout, contains(verbHelpResult.stdout));
        expect(result.stderr, contains(verbHelpResult.stderr));
      });
    }
  });

  test('(help pub == pub help)', () {
    p = project();
    var result = p.runSync('help', ['pub']);

    var pubHelpResult = p.runSync('pub', ['help']);
    expect(result.stdout, contains(pubHelpResult.stdout));
    expect(result.stderr, contains(pubHelpResult.stderr));
  });

  test('(--help flags also have -h abbr)', () {
    DartdevRunner([]).commands.forEach((String commandKey, Command command) {
      var helpOption = command.argParser.options['help'];
      // Some commands (like pub which use
      // "argParser = ArgParser.allowAnything()") may not have the help Option
      // accessible with the API used above:
      if (helpOption != null) {
        expect(helpOption.abbr, 'h', reason: '');
      }
    });
  });
}

Add some additional tests to test the commands that are currently passing the help <verb> == <verb> --help assertion.

Bug: https://github.com/dart-lang/sdk/issues/41041
Change-Id: I440c76fc84d0d222d8d996c622c711c31b13e948
Reviewed-on: https://dart-review.googlesource.com/c/sdk/+/140144
Reviewed-by: Devon Carew <e996497f4f2225f0ee7a9f4d1696ee710b488b66@google.com>
Commit-Queue: Jaime Wren <cd1ab83d11dd618c6b8cd01592020d0bd5183fdc@google.com>


part of 'user_history_bloc.dart';

abstract class UserHistoryEvent extends Equatable {
  const UserHistoryEvent();

  @override
  List<Object> get props => [];
}

class UserHistoryFetched extends UserHistoryEvent {
  final String tautulliId;
  final bool? grouping;
  final bool? includeActivity;
  final String? user;
  final int? userId;
  final int? ratingKey;
  final int? parentRatingKey;
  final int? grandparentRatingKey;
  final DateTime? startDate;
  final DateTime? before;
  final DateTime? after;
  final int? sectionId;
  final String? mediaType;
  final String? transcodeDecision;
  final String? guid;
  final String? orderColumn;
  final String? orderDir;
  final int? start;
  final int? length;
  final String? search;
  final bool freshFetch;
  final SettingsBloc settingsBloc;

  const UserHistoryFetched({
    required this.tautulliId,
    this.grouping,
    this.includeActivity,
    this.user,
    this.userId,
    this.ratingKey,
    this.parentRatingKey,
    this.grandparentRatingKey,
    this.startDate,
    this.before,
    this.after,
    this.sectionId,
    this.mediaType,
    this.transcodeDecision,
    this.guid,
    this.orderColumn,
    this.orderDir,
    this.start,
    this.length,
    this.search,
    this.freshFetch = false,
    required this.settingsBloc,
  });

  @override
  List<Object> get props => [tautulliId, freshFetch, settingsBloc];
}

part of 'user_history_bloc.dart';

abstract class UserHistoryEvent extends Equatable {
  const UserHistoryEvent();

  @override
  List<Object> get props => [];
}

class UserHistoryFetched extends UserHistoryEvent {
  final String tautulliId;
  final bool? grouping;
  final bool? includeActivity;
  final String? user;
  final int userId;
  final int? ratingKey;
  final int? parentRatingKey;
  final int? grandparentRatingKey;
  final DateTime? startDate;
  final DateTime? before;
  final DateTime? after;
  final int? sectionId;
  final String? mediaType;
  final String? transcodeDecision;
  final String? guid;
  final String? orderColumn;
  final String? orderDir;
  final int? start;
  final int? length;
  final String? search;
  final bool freshFetch;
  final SettingsBloc settingsBloc;

  const UserHistoryFetched({
    required this.tautulliId,
    this.grouping,
    this.includeActivity,
    this.user,
    required this.userId,
    this.ratingKey,
    this.parentRatingKey,
    this.grandparentRatingKey,
    this.startDate,
    this.before,
    this.after,
    this.sectionId,
    this.mediaType,
    this.transcodeDecision,
    this.guid,
    this.orderColumn,
    this.orderDir,
    this.start,
    this.length,
    this.search,
    this.freshFetch = false,
    required this.settingsBloc,
  });

  @override
  List<Object> get props => [tautulliId, freshFetch, settingsBloc];
}

Make userId required for UserHistoryFetched event.


library bootstrap_spec;

import '_specs.dart';

void main() {
  describe('bootstrap', () {
    BodyElement body = window.document.querySelector('body');

    it('should default to whole page', () {
      body.innerHtml = '
{{"works"}}
';
      ngBootstrap();
      expect(body.innerHtml).toEqual('
works
');
    });

    it('should compile starting at ng-app node', () {
      body.setInnerHtml(
          '
{{ignor me}}

',
          treeSanitizer: new NullTreeSanitizer());
      ngBootstrap();
      expect(body.text).toEqual('{{ignor me}}works');
    });

    it('should compile starting at ng-app node', () {
      body.setInnerHtml(
          '
{{ignor me}}

',
          treeSanitizer: new NullTreeSanitizer());
      ngBootstrap(element:body.querySelector('div[ng-bind]'));
      expect(body.text).toEqual('{{ignor me}}works');
    });
  });
}

library bootstrap_spec;

import '_specs.dart';

void main() {
  describe('bootstrap', () {
    setBody(String html) {
      var body = window.document.querySelector('body');
      body.setInnerHtml(html, treeSanitizer: new NullTreeSanitizer());
      return $(body);
    }

    it('should default to whole page', () {
      var body = setBody('
{{"works"}}
');
      ngBootstrap();
      expect($(body).html()).toEqual('
works
');
    });

    it('should compile starting at ng-app node', () {
      var body = setBody(
          '
{{ignor me}}

');
      ngBootstrap();
      expect(body.text()).toEqual('{{ignor me}}works');
    });

    it('should compile starting at ng-app node', () {
      var body = setBody(
          '
{{ignor me}}

');
      ngBootstrap(element:body.find('div[ng-bind]').first);
      expect(body.text()).toEqual('{{ignor me}}works');
    });
  });
}

Use JQuery in the bootstrap test

test(bootstrap): Use JQuery in the bootstrap test


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

import '../../../../core/widgets/list_tile_group.dart';
import '../pages/server_settings_page.dart';
import 'settings_list_tile.dart';

class ServersGroup extends StatelessWidget {
  const ServersGroup({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return ListTileGroup(
      heading: 'Servers',
      listTiles: [
        SettingsListTile(
          sensitive: true,
          leading: WebsafeSvg.asset(
            'assets/logos/logo_flat.svg',
            color: Theme.of(context).colorScheme.tertiary,
            height: 35,
          ),
          title: 'Server Name',
          subtitle: 'https://tautulli.domain.com',
          onTap: () => Navigator.of(context).push(
            MaterialPageRoute(
              builder: (context) => const ServerSettingsPage(),
            ),
          ),
        ),
      ],
    );
  }
}

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

import '../../../../core/widgets/list_tile_group.dart';
import '../bloc/settings_bloc.dart';
import '../pages/server_settings_page.dart';
import 'settings_list_tile.dart';

class ServersGroup extends StatelessWidget {
  const ServersGroup({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return BlocBuilder<SettingsBloc, SettingsState>(
      builder: (context, state) {
        return ListTileGroup(
          heading: 'Servers',
          listTiles: state is SettingsSuccess
              ? state.serverList
                  .map(
                    (server) => SettingsListTile(
                      sensitive: true,
                      leading: WebsafeSvg.asset(
                        'assets/logos/logo_flat.svg',
                        color: Theme.of(context).colorScheme.tertiary,
                        height: 35,
                      ),
                      title: server.plexName,
                      subtitle: server.primaryActive!
                          ? server.primaryConnectionAddress
                          : server.secondaryConnectionAddress,
                      onTap: () => Navigator.of(context).push(
                        MaterialPageRoute(
                          builder: (context) => const ServerSettingsPage(),
                        ),
                      ),
                    ),
                  )
                  .toList()
              : [],
        );
      },
    );
  }
}

Build ListTiles from loaded servers.

Build ListTiles from loaded servers.


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

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

}

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

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

}

Check editTaskElement returns a LIElement.


part of dherkin_core;

class GherkinTable extends IterableBase {

  final String _SPACER = "\t\t  ";

  List<String> _columnNames = [];
  List<Map> _table = [];

  Iterator get iterator => _table.iterator;

  int get length => _table.length;

  bool get empty => _table.isEmpty;

  List<String> get names => _columnNames;

  void addRow(row) {
    if (_columnNames.isEmpty) {
      _columnNames.addAll(row);
    } else {
      _table.add(new Map.fromIterables(_columnNames, row));
    }
  }

  /**
   * Gherkin table
   */
  String gherkinRows() {
    var rows = [];

    if(!_table.isEmpty) {
      rows.add("$_SPACER|${_columnNames.join(" | ")}|");

      for(var row in _table) {
        rows.add("$_SPACER|${row.values.join(" | ")}|");
      }
    }

    return rows;
  }

  String toString() {
    return _table.toString();
  }
}

part of dherkin_core;

class GherkinTable extends IterableBase {

  final String _SPACER = "\t\t  ";

  List<String> _columnNames = [];
  List<Map> _table = [];

  Iterator get iterator => _table.iterator;

  int get length => _table.length;

  bool get empty => _table.isEmpty;

  List<String> get names => _columnNames;

  void addRow(row) {
    if (_columnNames.isEmpty) {
      _columnNames.addAll(row);
    } else {
      _table.add(new Map.fromIterables(_columnNames, row));
    }
  }

  /**
   * Gherkin table
   */
  List<String> gherkinRows() {
    var rows = [];

    if(!_table.isEmpty) {
      rows.add("$_SPACER|${_columnNames.join(" | ")}|");

      for(var row in _table) {
        rows.add("$_SPACER|${row.values.join(" | ")}|");
      }
    }

    return rows;
  }

  String toString() {
    return _table.toString();
  }
}

Fix crash in checked mode because of wrong output type.


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

import "package:expect/expect.dart";

class A {
  x(p1, p2) {
    print(p1 * p2);
    if (p1 * p2 == 12) return;
    x("3", "4");
  }
}

main() => Expect.throws(() => new A().x(1, 2),
                        (e) => e is NoSuchMethodError);

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

import "package:expect/expect.dart";

class A {
  x(p1, p2) {
    print(p1 * p2);
    if (p1 * p2 == 12) return;
    x("3", "4");
  }
}

main() {
  Expect.throws(() => new A().x(1, 2));
}

Change regression test now that String does have operator*.

It still doesn't work for string arguments, but that's a type/argument error.

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

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


library test.event_emitter;

import 'event_emitter_test.dart' as event_emitter_test;
import 'event_emitter_with_event_objects_test.dart' as event_objects_test;
import 'event_handlers_as_classes_test.dart' as event_handlers_test;
import 'package:test/test.dart';

void main () {
    group('[Event emitter]', event_emitter_test.main);
    group('[Event emitter with objects]', event_objects_test.main);
    group('[Event handlers as objects]', event_handlers_test.main);
}

library test.event_emitter;

import './event_emitter_test.dart' as event_emitter_test;
import './event_emitter_with_event_objects_test.dart' as event_objects_test;
import './event_handlers_as_classes_test.dart' as event_handlers_test;
import 'package:test/test.dart';

void main () {
    group('[Event emitter]', event_emitter_test.main);
    group('[Event emitter with objects]', event_objects_test.main);
    group('[Event handlers as objects]', event_handlers_test.main);
}

Change format of importing test packages