/*
 * QR.Flutter
 * Copyright (c) 2019 the QR.Flutter authors.
 * See LICENSE for distribution and usage details.
 */
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,
    this.gapless = false,
  }) : _painter = QrPainter(
            data: data,
            color: foregroundColor,
            version: version,
            errorCorrectionLevel: errorCorrectionLevel,
            gapless: gapless,
            onError: onError);

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

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

/*
 * QR.Flutter
 * Copyright (c) 2019 the QR.Flutter authors.
 * See LICENSE for distribution and usage details.
 */
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,
    Key key,
    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,
    this.gapless = false,
  }) : _painter = QrPainter(
            data: data,
            color: foregroundColor,
            version: version,
            errorCorrectionLevel: errorCorrectionLevel,
            gapless: gapless,
            onError: onError
  ), super(key: key);

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

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

Allow setting a Key value on QrImage

Allow setting a Key value on QrImage


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

// @dart = 2.9

// ignore_for_file: directives_ordering
// ignore_for_file: library_prefixes

library js_ast;

export 'nodes.dart';
export 'builder.dart';
export 'printer.dart';
export 'template.dart';

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

// @dart = 2.9

// ignore_for_file: directives_ordering

library js_ast;

export 'nodes.dart';
export 'builder.dart';
export 'printer.dart';
export 'template.dart';

Remove an unneeded ignore comment in dev_compiler

Change-Id: I90d4ee37e1599ad6981b379ca35c282efef923eb
Reviewed-on: https://dart-review.googlesource.com/c/sdk/+/238982
Reviewed-by: Nicholas Shahan <03847abd2d8aadfe859ecb98095a31f9f515dc47@google.com>
Commit-Queue: Nicholas Shahan <03847abd2d8aadfe859ecb98095a31f9f515dc47@google.com>


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

import 'package:test_reflective_loader/test_reflective_loader.dart';

import 'sdk_version_async_exported_from_core_test.dart'
    as sdk_version_async_exported_from_core;

main() {
  defineReflectiveSuite(() {
    sdk_version_async_exported_from_core.main();
  }, name: 'hint');
}

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

import 'package:test_reflective_loader/test_reflective_loader.dart';

import 'sdk_constraint_extractor_test.dart' as sdk_constraint_extractor;
import 'sdk_version_async_exported_from_core_test.dart'
    as sdk_version_async_exported_from_core;

main() {
  defineReflectiveSuite(() {
    sdk_constraint_extractor.main();
    sdk_version_async_exported_from_core.main();
  }, name: 'hint');
}

Add a missed test file

Add a missed test file

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


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

final x = foo(499);
final y = foo(41) + 1;

final t = bar(499);
final u = bar(41) + 1;
final v = bar("some string");

foo(x) => x; // The return type will always be integer.
bar(x) => x; // The return type varies and can be integer or String.

main() {
  Expect.equals(499, x);
  Expect.equals(42, y);
  Expect.equals(499, t);
  Expect.equals(42, u);
  Expect.equals("some string", v);
}

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

final x = foo(499);
final y = foo(41) + 1;

final t = bar(499);
final u = bar(41) + 1;
final v = bar("some string");

foo(x) => x; // The return type will always be int.
bar(x) => x; // The return type varies and can be int or String.

main() {
  Expect.equals(499, x);
  Expect.equals(42, y);
  Expect.equals(499, t);
  Expect.equals(42, u);
  Expect.equals("some string", v);
}

Address comment of CL 10914097 .

Address comment of CL 10914097 .

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

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


// Copyright 2014 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

library source_path;

import 'package:polymer/polymer.dart';

@CustomTag('source-path')
class SourcePathElement extends PolymerElement {
  @published var path;
  @observable var isEmpty;

  SourcePathElement.created() : super.created();

  switchAction(event, detail, target) {
    final index = int.parse(target.attributes["data-target"]);
    path.removeRange(index + 1, path.length);
  }
}

// Copyright 2014 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

library source_path;

import 'package:polymer/polymer.dart';

@CustomTag('source-path')
class SourcePathElement extends PolymerElement {
  @published var path;
  @observable var isEmpty;

  SourcePathElement.created() : super.created();

  switchAction(event, detail, target) {
    final index = int.parse(target.attributes["data-target"]);
    path.removeRange(index + 1, path.length);
    event.preventDefault();
  }
}

Fix inline path bread crumbs control

Fix inline path bread crumbs control


import 'package:dynamic_color/dynamic_color.dart';
import 'package:dynamic_color/samples.dart';
import 'package:dynamic_color/test_utils.dart';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';

void main() {
  TestWidgetsFlutterBinding.ensureInitialized();

  testWidgets('DynamicColorBuilder', (WidgetTester tester) async {
    DynamicColorTestingUtils.setMockDynamicColors(
      colors: SampleCorePalettes.green,
    );

    const containerKey = Key('myContainer');

    await tester.pumpWidget(
      DynamicColorBuilder(
        builder: (ColorScheme? lightDynamic, ColorScheme? darkDynamic) {
          return Container(
            key: containerKey,
            color: lightDynamic?.primary ?? const Color(0x00000123),
          );
        },
      ),
    );

    await tester.pumpAndSettle();

    expect(
      (tester.firstWidget(find.byKey(containerKey)) as Container).color,
      const Color(0xff286b2a),
    );
  });
}

import 'package:dynamic_color/dynamic_color.dart';
import 'package:dynamic_color/samples.dart';
import 'package:dynamic_color/test_utils.dart';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';

void main() {
  TestWidgetsFlutterBinding.ensureInitialized();

  setUp(() {
    DynamicColorTestingUtils.setMockDynamicColors(
      colorPalette: SampleCorePalettes.green,
      controlAccentColor: Colors.amber,
    );
  });

  const containerKey = Key('myContainer');

  Widget dynamicColorBuilder() => DynamicColorBuilder(
        builder: (ColorScheme? lightDynamic, ColorScheme? darkDynamic) {
          return Container(
            key: containerKey,
            color: lightDynamic?.primary ?? const Color(0x00000123),
          );
        },
      );

  testWidgets('DynamicColorBuilder is correct on Android',
      (WidgetTester tester) async {
    DynamicColorTestingUtils.setMockDynamicColors(
      colorPalette: SampleCorePalettes.green,
    );

    await tester.pumpWidget(dynamicColorBuilder());
    await tester.pumpAndSettle();

    final container = tester.firstWidget(find.byKey(containerKey)) as Container;
    expect(container.color, const Color(0xff286b2a));
  });

  testWidgets('DynamicColorBuilder is correct on macOS',
      (WidgetTester tester) async {
    DynamicColorTestingUtils.setMockDynamicColors(
      controlAccentColor: Colors.amber,
    );
    await tester.pumpWidget(dynamicColorBuilder());
    await tester.pumpAndSettle();

    final container = tester.firstWidget(find.byKey(containerKey)) as Container;
    expect(container.color, const Color(0xff795900));
  });

  testWidgets('DynamicColorBuilder is correct on other platforms',
      (WidgetTester tester) async {
    DynamicColorTestingUtils.setMockDynamicColors();

    await tester.pumpWidget(dynamicColorBuilder());
    await tester.pumpAndSettle();

    final container = tester.firstWidget(find.byKey(containerKey)) as Container;
    expect(container.color, const Color(0x00000123));
  });
}

Improve testing coverage for `DynamicColorBuilder`


// Copyright (c) 2014, Robert Åkerblom-Andersson <Robert@dartvoid.com>

part of vane;

/// Http methods constants, declared for easy use with code completion and to
/// avoid typos.
const String GET      = "GET";
const String HEAD     = "HEAD";
const String POST     = "POST";
const String PUT      = "PUT";
const String DELETE   = "DELETE";
const String TRACE    = "TRACE";
const String OPTIONS  = "OPTIONS";
const String CONNECT  = "CONNECT";
const String PATCH    = "PATCH";

/// [Route] annotation used to declared the request handler for a specific path
class Route {
  final String path;
  final String method;
  final List<String> methods;

  const Route(this.path, {this.method: "", this.methods: const []});
}

// A class is used for this constant since the other entries in the pipeline
// list are also classes.
class _This {
  const _This();
}

/// [This] is a constant used to indentify the main handler in middleware
/// pipeline. With [This] it's possible to define where in the pipelien the
/// main handler should go, per default that is last in the the pipeline.
const This = const _This();

// Copyright (c) 2014, Robert Åkerblom-Andersson <Robert@dartvoid.com>

part of vane;

/// Http methods constants, declared for easy use with code completion and to
/// avoid typos.
const String GET      = "GET";
const String HEAD     = "HEAD";
const String POST     = "POST";
const String PUT      = "PUT";
const String DELETE   = "DELETE";
const String TRACE    = "TRACE";
const String OPTIONS  = "OPTIONS";
const String CONNECT  = "CONNECT";
const String PATCH    = "PATCH";

/// [Route] annotation used to declared the request handler for a specific path
class Route {
  final String path;
  final String method;
  final List<String> methods;

  const Route(this.path, {this.method: "", this.methods: const []});
}

// A class is used for this constant since the other entries in the pipeline
// list are also classes.
class _This {
  const _This();
}

/// [This] is a constant used to indentify the main handler in middleware
/// pipeline. With [This] it's possible to define where in the pipeline the
/// main handler should go, per default that is last in the the pipeline.
const This = const _This();

Fix a typo in the API doc

Fix a typo in the API doc


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

/**
 * Mixin for trackLayoutChanges property pass through to material popup to
 * avoid duplicate code in multiple components.
 */
class TrackLayoutChangesMixin {
  /// Sets whether the suggestion list scrolls with the input box.
  ///
  /// This is a pass through property, as defined in [PopupInterface].
  @Input()
  bool trackLayoutChanges = true;
}

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

/// Mixin for trackLayoutChanges property pass through to material popup to
/// avoid duplicate code in multiple components.
class TrackLayoutChangesMixin {
  /// Sets whether the suggestion list scrolls with the input box.
  ///
  /// This is a pass through property, as defined in [PopupInterface].
  @Input()
  bool trackLayoutChanges = true;
}

Fix violations of slash_for_doc_comments lint

Created using "dartfmt --fix-doc-comments -w".

PiperOrigin-RevId: 230878513


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

import 'device_button.dart';
import 'main_drawer.dart';

class AppPage extends ConsumerWidget {
  final Key _scaffoldKey = GlobalKey();
  final Widget? title;
  final Widget child;
  final void Function()? onBack;
  AppPage({Key? key, this.title, required this.child, this.onBack})
      : super(key: key);

  @override
  Widget build(BuildContext context, WidgetRef ref) => LayoutBuilder(
        builder: (context, constraints) {
          if (constraints.maxWidth < 540) {
            // Single column layout
            return _buildScaffold(context, ref, true);
          } else {
            // Two-column layout
            return Scaffold(
              body: Row(
                children: [
                  const SizedBox(
                    width: 240,
                    child: MainPageDrawer(shouldPop: false),
                  ),
                  Expanded(
                    child: _buildScaffold(context, ref, false),
                  ),
                ],
              ),
            );
          }
        },
      );

  Scaffold _buildScaffold(BuildContext context, WidgetRef ref, bool hasDrawer) {
    return Scaffold(
      key: _scaffoldKey,
      appBar: AppBar(
        leading: onBack != null
            ? BackButton(
                onPressed: onBack,
              )
            : null,
        title: title,
        centerTitle: true,
        actions: const [DeviceButton()],
      ),
      drawer: hasDrawer ? const MainPageDrawer() : null,
      body: child,
    );
  }
}

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

import 'device_button.dart';
import 'main_drawer.dart';

class AppPage extends ConsumerWidget {
  final Key _scaffoldKey = GlobalKey();
  final Widget? title;
  final Widget child;
  final void Function()? onBack;
  AppPage({Key? key, this.title, required this.child, this.onBack})
      : super(key: key);

  @override
  Widget build(BuildContext context, WidgetRef ref) => LayoutBuilder(
        builder: (context, constraints) {
          if (constraints.maxWidth < 540) {
            // Single column layout
            return _buildScaffold(context, ref, true);
          } else {
            // Two-column layout
            return Scaffold(
              body: Row(
                children: [
                  const SizedBox(
                    width: 240,
                    child: ListTileTheme(
                        style: ListTileStyle.drawer,
                        child: MainPageDrawer(shouldPop: false)),
                  ),
                  Expanded(
                    child: _buildScaffold(context, ref, false),
                  ),
                ],
              ),
            );
          }
        },
      );

  Scaffold _buildScaffold(BuildContext context, WidgetRef ref, bool hasDrawer) {
    return Scaffold(
      key: _scaffoldKey,
      appBar: AppBar(
        leading: onBack != null
            ? BackButton(
                onPressed: onBack,
              )
            : null,
        title: title,
        centerTitle: true,
        actions: const [DeviceButton()],
      ),
      drawer: hasDrawer ? const MainPageDrawer() : null,
      body: child,
    );
  }
}

Make ListTile use the drawer style when drawer is embedded.


part of darn;

class BuildCommand extends Command {
  @override
  ArgParser get arguments =>
    new ArgParser()
      ..addFlag("verbose", abbr: "v", defaultsTo: false, negatable: false, help: "Enables Verbose Output")
      ..addOption("arch", abbr: "a", allowed: POSSIBLE_ARCHS, allowMultiple: false, defaultsTo: "ia32")
      ..addOption("mode", abbr: "m", allowed: POSSIBLE_MODES, allowMultiple: false, defaultsTo: "release");

  @override
  String get name => "build";

  @override
  void run(ArgResults args) {

    String arch = args['arch'];

    String mode = args['mode'];

    var targets = args.rest.isNotEmpty ? args.rest : ["create_sdk"];

    verifyDartSource();

    var commands = [];

    var cmd = "python2 tools/build.py -m ${mode} -a ${arch} ${targets.join(" ")}";

    commands.add(cmd);

    executeCommands(commands);
  }
}

part of darn;

class BuildCommand extends Command {
  @override
  ArgParser get arguments =>
    new ArgParser()
      ..addFlag("verbose", abbr: "v", defaultsTo: false, negatable: false, help: "Enables Verbose Output")
      ..addOption("arch", abbr: "a", allowed: POSSIBLE_ARCHS, allowMultiple: false, defaultsTo: "ia32")
      ..addOption("mode", abbr: "m", allowed: POSSIBLE_MODES, allowMultiple: false, defaultsTo: "release");

  @override
  String get name => "build";

  @override
  void run(ArgResults args) {

    String arch = args['arch'];

    String mode = args['mode'];

    bool verbose = args['verbose'];

    var targets = args.rest.isNotEmpty ? args.rest : ["create_sdk"];

    verifyDartSource();

    var commands = [];

    var cmd = "python2 tools/build.py ${verbose ? "-v" : ""} -m ${mode} -a ${arch} ${targets.join(" ")}";

    commands.add(cmd);

    executeCommands(commands);
  }
}

Build Command: Actually Follow the Verbose Flag


library events;

import "dart:async";

class Event {
  String type;
  Event(this.type);
}

class Emitter {

  final _evtController = new StreamController<Event>.broadcast();

  Stream<Event> operator[] (type) => _evtController.stream.where((e) => e.type == type);

  Stream<T> getEventStream<T extends Event>(String type) {
    final controller = new StreamController<T>();
    _evtController.stream.where((e) => e.type == type).listen(
        controller.add,
        onDone: controller.close,
        onError: controller.addError);
    return controller.stream;
  }

  dispatch(evtOrType) {
    var evt = (evtOrType is String) ? new Event(evtOrType) : evtOrType;
    _evtController.add(evt);
  }
}

library events;

import "dart:async";

class Event {
  String type;
  Event(this.type);
}

class Emitter {

  final _evtController = new StreamController<Event>.broadcast();

  Stream<Event> operator[] (type) => _evtController.stream.where((e) => e.type == type);

  Stream<T> getEventStream<T extends Event>(String type) {
    return _evtController.stream.where((e) => e.type == type).map((e) => e as T);
  }

  dispatch(evtOrType) {
    var evt = (evtOrType is String) ? new Event(evtOrType) : evtOrType;
    _evtController.add(evt);
  }
}

Use .where().map() instead of StreamController


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

/**
 * Tests date formatting and parsing using locale data read from the
 * local file system.
 */
library date_time_format_file_test;

import '../lib/intl.dart';
import '../lib/date_symbol_data_file.dart';
import 'date_time_format_test_core.dart';
import '../../../pkg/unittest/lib/unittest.dart';

main() {
  runDateTests(['en_US']);
}

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

/**
 * Tests date formatting and parsing using locale data read from the
 * local file system.
 */
library date_time_format_file_test;

import '../lib/intl.dart';
import '../lib/date_symbol_data_local.dart';
import 'date_time_format_test_core.dart';
import '../../../pkg/unittest/lib/unittest.dart';

main() {
  runDateTests(['en_US']);
}

Make uninitialized Intl test not import dart:io
Review URL: https://codereview.chromium.org//11746005

git-svn-id: a8f079e7cfc3a289d8496d7b88aabbd5c45a3053@16586 260f80e4-7a28-3924-810f-c04153c831b5


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

// @dart = 2.9

/// Tool that consumes the .dill file of an entire dart-sdk and produces the
/// corresponding Javascript module.

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

void main(List<String> args) async {
  var result = await compileSdkFromDill(args);
  exitCode = result.exitCode;
}

#!/usr/bin/env dart
// Copyright (c) 2019, 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.

/// Tool that consumes the .dill file of an entire dart-sdk and produces the
/// corresponding Javascript module.

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

void main(List<String> args) async {
  var result = await compileSdkFromDill(args);
  exitCode = result.exitCode;
}

[ddc] Migrate compile sdk script to null safety

Issue: https://github.com/dart-lang/sdk/issues/46617
Change-Id: I48dcf20dc3cada2bd9d0c9dfb0e1f27f07d5e521
Reviewed-on: https://dart-review.googlesource.com/c/sdk/+/250350
Reviewed-by: Sigmund Cherem <beaea8fd7d2a56555046ba4f362c8a93e3938576@google.com>
Commit-Queue: Nicholas Shahan <03847abd2d8aadfe859ecb98095a31f9f515dc47@google.com>


/// XML pretty printer.
library xml.example.xml_pp;

import 'dart:io';

import 'package:args/args.dart' as args;
import 'package:xml/xml.dart' as xml;

final args.ArgParser argumentParser = args.ArgParser()
  ..addOption('indent',
      abbr: 'i',
      help: 'Customizes the indention when pretty printing.',
      defaultsTo: '  ');

void printUsage() {
  stdout.writeln('Usage: xml_pp [options] {files}');
  stdout.writeln();
  stdout.writeln(argumentParser.usage);
  exit(1);
}

void main(List<String> arguments) {
  final files = <File>[];
  final results = argumentParser.parse(arguments);
  final indent = results['indent'];

  for (final argument in results.rest) {
    final file = File(argument);
    if (file.existsSync()) {
      files.add(file);
    } else {
      stderr.writeln('File not found: $file');
      exit(2);
    }
  }
  if (files.isEmpty) {
    printUsage();
  }

  for (final file in files) {
    final document = xml.parse(file.readAsStringSync());
    stdout.writeln(document.toXmlString(pretty: true, indent: indent));
  }
}

/// XML pretty printer.
library xml.example.xml_pp;

import 'dart:io';

import 'package:args/args.dart' as args;
import 'package:xml/xml.dart' as xml;

final args.ArgParser argumentParser = args.ArgParser()
  ..addOption('indent',
      abbr: 'i',
      help: 'Customizes the indention when pretty printing.',
      defaultsTo: '  ')
  ..addFlag('pretty',
      abbr: 'p',
      help: 'Reformats the output to be pretty.',
      defaultsTo: true);

void printUsage() {
  stdout.writeln('Usage: xml_pp [options] {files}');
  stdout.writeln();
  stdout.writeln(argumentParser.usage);
  exit(1);
}

void main(List<String> arguments) {
  final files = <File>[];
  final results = argumentParser.parse(arguments);
  final indent = results['indent'];
  final pretty = results['pretty'];

  for (final argument in results.rest) {
    final file = File(argument);
    if (file.existsSync()) {
      files.add(file);
    } else {
      stderr.writeln('File not found: $file');
      exit(2);
    }
  }
  if (files.isEmpty) {
    printUsage();
  }

  for (final file in files) {
    final document = xml.parse(file.readAsStringSync());
    stdout.writeln(document.toXmlString(pretty: pretty, indent: indent));
  }
}

Add a pretty option to the formatter example.


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

library git.utils;

import 'dart:core';

/**
 * Convertes [sha] string to sha bytes.
 */
List<int> shaToBytes(String sha) {
  List<int> bytes = [];

  for (var i = 0; i < sha.length; i+=2) {
    bytes.add(int.parse('0x' + sha[i] + sha[i+1]));
  }
  return bytes;
}

/**
 * Converts [shaBytes] to HEX string.
 */
String shaBytesToString(List<int> shaBytes) {
  String sha = "";
  shaBytes.forEach((int byte) {
    sha += byte.toRadixString(16);
  });
  return sha;
}

/**
 * An empty function.
 */
void nopFunction() => null;

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

library git.utils;

import 'dart:core';

/**
 * Convertes [sha] string to sha bytes.
 */
List<int> shaToBytes(String sha) {
  List<int> bytes = [];

  for (var i = 0; i < sha.length; i+=2) {
    bytes.add(int.parse('0x' + sha[i] + sha[i+1]));
  }
  return bytes;
}

/**
 * Converts [shaBytes] to HEX string.
 */
String shaBytesToString(List<int> shaBytes) {
  String sha = "";
  shaBytes.forEach((int byte) {
    String shaPart = byte.toRadixString(16);
    if (shaPart.length == 1) shaPart = '0' + shaPart;
    sha += shaPart;
  });
  return sha;
}

/**
 * An empty function.
 */
void nopFunction() => null;

Fix bug in sha / bytes conversion.

Fix bug in sha / bytes conversion.


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

import "package:expect/expect.dart";

class A<T> {
  @NoInlining()
  A();

  @NoInlining()
  foo() => new B<T>();
}

class B<T> {
  T bar() => null;
}

typedef F();
typedef F2(x);

// Dart2js realized that the generic type for A was not needed, but then used
// it nevertheless when it constructed the closure.
main() {
  var f = new A<int>().foo().bar;
  Expect.isTrue(f is F);
  Expect.isFalse(f is F2);
}

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

import "package:expect/expect.dart";

class A<T> {
  @NoInline()
  A();

  @NoInline()
  foo() => new B<T>();
}

class B<T> {
  T bar() => null;
}

typedef F();
typedef F2(x);

// Dart2js realized that the generic type for A was not needed, but then used
// it nevertheless when it constructed the closure.
main() {
  var f = new A<int>().foo().bar;
  Expect.isTrue(f is F);
  Expect.isFalse(f is F2);
}

Update no-inline annotation in test.

Update no-inline annotation in test.

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

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


part of quiz;

class StaticFilesController extends HTTPController {
  final String basePath;
  final String defaultFile;

  StaticFilesController({this.basePath: "build/web", this.defaultFile: "index.html"});

  // Initially based on https://github.com/stablekernel/aqueduct/issues/157
  @httpGet getFile() async {
    String realPath = request.path.remainingPath;
    if (realPath.length == 0) {
      realPath = defaultFile;
    }
    String filePath = path.join(basePath, realPath);
    io.File file = new io.File(filePath);
    var fileContents = file.readAsBytesSync();

    String contentType = mime.lookupMimeType(filePath);

    return new Response.ok(fileContents)
      ..contentType = io.ContentType.parse(contentType);
  }
}

part of quiz;

class StaticFilesController extends HTTPController {
  final String basePath;
  final String defaultFile;

  StaticFilesController({this.basePath: "build/web", this.defaultFile: "index.html"});

  // Initially based on https://github.com/stablekernel/aqueduct/issues/157
  @httpGet getFile() async {
    String realPath = request.path.remainingPath;
    if (realPath.length == 0) {
      realPath = defaultFile;
    }
    String filePath = path.join(basePath, realPath);
    io.File file = new io.File(filePath);
    List<int> fileContents = file.readAsBytesSync();

    String contentType = mime.lookupMimeType(filePath);

    return new Response.ok(fileContents)
      ..contentType = io.ContentType.parse(contentType);
  }
}

Add type for the file contents.

Add type for the file contents.


import 'package:flutter/material.dart';

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

  @override
  Widget build(BuildContext context) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: <Widget>[
        Padding(
          padding: const EdgeInsets.only(bottom: 10),
          child: Text(
            'This app is not registered to a Tautulli server.',
            style: TextStyle(fontWeight: FontWeight.bold),
          ),
        ),
        Text('To register this app do the following:'),
        BulletItem('Open the Tautulli web interface on another device'),
        BulletItem('Navigate to Settings > Tautulli Remote App'),
        BulletItem('Select \'Register a new device\''),
        BulletItem('Use the button below to add a new server'),
      ],
    );
  }
}

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: Text('• $text'),
    );
  }
}

import 'package:flutter/material.dart';

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

  @override
  Widget build(BuildContext context) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: <Widget>[
        Padding(
          padding: const EdgeInsets.only(bottom: 10),
          child: Text(
            'This app is not registered to a Tautulli server.',
            style: TextStyle(fontWeight: FontWeight.bold),
          ),
        ),
        Text('To register with a Tautulli server:'),
        BulletItem('Open the Tautulli web interface on another device'),
        BulletItem('Navigate to Settings > Tautulli Remote App'),
        BulletItem('Select \'Register a new device\''),
        BulletItem('Use the button below to add a new server'),
      ],
    );
  }
}

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: Text('• $text'),
    );
  }
}

Tweak wording for server setup instructions.


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

library playfair;

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

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

part 'src/base.dart';

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

library playfair;

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

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

part 'src/base.dart';

Switch to the production name for fn3

Switch to the production name for fn3


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

// ignore_for_file: directives_ordering

/// Support for programming against the Win32 Windows Socket 2 library on
/// Windows operating systems.
///
/// This library extends the core `win32` library with Windows Socket functions.
/// Since this library is somewhat specialist and many of its function names are
/// likely to conflict with other libraries or programs, it is separately
/// exported.
///
/// The `winsock2` library will normally be used in conjunction with the main
/// `win32` library, and the latter will be required for constants and structs
/// used here.
library winsock2;

// Core Win32 APIs, constants and macros
export 'src/structs.g.dart'
    show addrinfo, fd_set, SOCKADDR, timeval, hostent, protoent, servent;
export 'src/structs.dart' show IN_ADDR;
export 'src/constants_winsock.dart';

// Traditional C-style Windows APIs
export 'src/ws2_32.dart';

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

// ignore_for_file: directives_ordering

/// Support for programming against the Win32 Windows Socket 2 library on
/// Windows operating systems.
///
/// This library extends the core `win32` library with Windows Socket functions.
/// Since this library is somewhat specialist and many of its function names
/// (e.g. `send`, `connect`) are likely to conflict with other libraries or
/// programs, it is separately exported.
///
/// To add Winsock2 support to your app, use the additional line below:
///
/// ```dart
/// import 'package:win32/win32.dart';
/// import 'package:win32/winsock2.dart' as winsock2;
/// ```
///
/// Now you can call, for instance, `winsock2.connect()` or `winsock2.send()`.
///
/// The `winsock2` library will normally be used in conjunction with the main
/// `win32` library, and the latter will be required for constants and structs
/// used here.
library winsock2;

// Core Win32 APIs, constants and macros
export 'src/structs.g.dart'
    show addrinfo, fd_set, SOCKADDR, timeval, hostent, protoent, servent;
export 'src/structs.dart' show IN_ADDR;
export 'src/constants_winsock.dart';

// Traditional C-style Windows APIs
export 'src/ws2_32.dart';

Add more explanation for importing winsock


import 'package:unittest/unittest.dart';
import 'package:workmantrainer/textmarker.dart';

void main() {
  test('check initialisation of TextMarker Class works.', () {
    var tm = new TextMarker('some text',0,2,"CORRECT");
    expect(tm.targettext, 'some text');
    expect(tm.startposition,0);
    expect(tm.endposition,2);
    expect(tm.textState, 'CORRECT');
  });
  test('typedCorrectly returns correct span element.', () {
    var tm = new TextMarker('some text', 0, 2, "Correct");
    var span = tm.typedCorrectly();
    expect(span.text, 'so');
  });
}

import 'package:unittest/unittest.dart';
import 'package:workmantrainer/textmarker.dart';

void main() {
  test('check initialisation of TextMarker Class works.', () {
    var tm = new TextMarker('some text',0,2,"CORRECT");
    expect(tm.targettext, 'some text');
    expect(tm.startposition,0);
    expect(tm.endposition,2);
    expect(tm.textState, 'CORRECT');
  });
  test('typedCorrectly returns correct span element.', () {
    var tm = new TextMarker('some text', 0, 2, "CORRECT");
    var span = tm.typedCorrectly();
    expect(span.text, 'so');
    expect(span.className, 'typedcorrect');
  });
}

Check Correct ClassName is set.

Check Correct ClassName is set.


import 'dart:convert';

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

void main() {
  test('maps without transormation', () {
    const type = BlobType();
    final data = Uint8List.fromList(List.generate(256, (i) => i));

    expect(type.mapToSqlVariable(data), data);
    expect(type.mapFromDatabaseResponse(data), data);
  });

  test('writes blob literals', () {
    const type = BlobType();
    const hex = '67656E6572616C206B656E6F626921';
    final data = Uint8List.fromList(utf8.encode('general kenobi!'));

    expect(type.mapToSqlConstant(data), equalsIgnoringCase("x'$hex'"));
  });
}

import 'dart:convert';

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

void main() {
  test('maps without transformation', () {
    const type = BlobType();
    final data = Uint8List.fromList(List.generate(256, (i) => i));

    expect(type.mapToSqlVariable(data), data);
    expect(type.mapFromDatabaseResponse(data), data);
  });

  test('writes blob literals', () {
    const type = BlobType();
    const hex = '67656E6572616C206B656E6F626921';
    final data = Uint8List.fromList(utf8.encode('general kenobi!'));

    expect(type.mapToSqlConstant(data), equalsIgnoringCase("x'$hex'"));
  });

  test('maps of string', () {
    const chars = 'AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz';
    const type = BlobType();
    final data = List.generate(256, (i) => chars[i % chars.length]);
    final dataString = data.join();
    final dataInt = data.map((e) => e.codeUnits[0]).toList();
    final dataUint8 = Uint8List.fromList(dataInt);
    expect(type.mapFromDatabaseResponse(dataString), dataUint8);
  });
}

Test for blob by string

Test for blob by string


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

// This file is separate from has_renderer so it doesn't add in the angular
// dependency and so 'dart:html' which stops tests from running as a simple
// dart_test.
import 'package:angular/angular.dart' show ComponentFactory;

import 'has_renderer.dart';

export 'has_renderer.dart';

/// Defines a method that returns a factory to render the Item.  The
/// component created must implement [RendersValue].
typedef ComponentFactory FactoryRenderer<T extends RendersValue, I>(I item);

/// HasFactoryRenderer defines a method that takes in an item and returns the
/// factory to use to render the item.
abstract class HasFactoryRenderer<T extends RendersValue, I> {
  FactoryRenderer<T, I> factoryRenderer;
}

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

// This file is separate from has_renderer.dart so it doesn't add the angular
// dependency and transitively 'dart:html', which doesn't work in a simple
// dart_test.
import 'package:angular/angular.dart' show ComponentFactory;

import 'has_renderer.dart';

export 'has_renderer.dart';

/// Defines a method that returns a factory to render the Item.  The component
/// created must implement [RendersValue].
typedef ComponentFactory FactoryRenderer<T extends RendersValue, I>(I item);

/// HasFactoryRenderer defines a method that takes in an item and returns the
/// factory to use to render the item.
abstract class HasFactoryRenderer<T extends RendersValue, I> {
  FactoryRenderer<T, I> factoryRenderer;
}

Clarify file comment about angular dependency.

Based on feedback from external sync
https://github.com/dart-lang/angular_components/pull/203

PiperOrigin-RevId: 179729861


part of nest_ui;

class BaseComponentBehaviors {

  Component component;

  BaseComponentBehaviors(this.component) {}

  // Show-hide behaviors
  //
  hide() => this.dom_element.style.display="none";
  show() => this.dom_element.style.display="";
  toggleDisplay() => _toggle(
    [show, hide],
    this.dom_element.style.display == 'none'
  );

  // Lock-unlock behaviors
  //
  lock()       => this.dom_element.classes.add("locked");
  unlock()     => this.dom_element.classes.remove("locked");
  toggleLock() => this.dom_element.classes.toggle("locked");

  // Enable-disable behaviors
  //
  disable() => {
    this.dom_element.classes.add('disabled');
    this.dom_element.setAttribute('disabled', 'disabled');
  }
  enable() => {
    this.dom_element.classes.add('disabled');
    this.dom_element.attributes.remove('disabled');
  }
  toggleDisable() => _toggle([enable, disable], this.dom_element.classes.contains('disabled'));

  _toggle(behaviors, condition) {
    if(condition)
      behaviors[0]();
    else
      behaviors[1]();
  }

  get dom_element => this.component.dom_element;

}

part of nest_ui;

class BaseComponentBehaviors {

  Component component;

  BaseComponentBehaviors(this.component) {}

  // Show-hide behaviors
  //
  hide() => this.dom_element.style.display="none";
  show() => this.dom_element.style.display="";
  toggleDisplay() => _toggle(
    [show, hide],
    this.dom_element.style.display == 'none'
  );

  // Lock-unlock behaviors
  //
  lock()       => this.dom_element.classes.add("locked");
  unlock()     => this.dom_element.classes.remove("locked");
  toggleLock() => this.dom_element.classes.toggle("locked");

  // Enable-disable behaviors
  //
  disable() {
    this.dom_element.classes.add('disabled');
    this.dom_element.setAttribute('disabled', 'disabled');
  }
  enable() {
    this.dom_element.classes.remove('disabled');
    this.dom_element.attributes.remove('disabled');
  }
  toggleDisable() => _toggle([enable, disable], this.dom_element.classes.contains('disabled'));

  _toggle(behaviors, condition) {
    if(condition)
      behaviors[0]();
    else
      behaviors[1]();
  }

  get dom_element => this.component.dom_element;

}

Add disabling/enabling behavior into BaseComponentBehavior class


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

library spark_widgets;

import 'dart:html';

import 'package:polymer/polymer.dart';

bool IS_DART2JS = identical(1, 1.0);

// NOTE: This SparkWidget element is not intended to use directly.
@CustomTag('spark-widget')
class SparkWidget extends PolymerElement {
  static const CSS_ENABLED = "enabled";
  static const CSS_DISABLED = "disabled";

  // Popular key codes
  static const DOWN_KEY = 40;
  static const UP_KEY = 38;
  static const ENTER_KEY = 13;
  static const ESCAPE_KEY = 27;

  SparkWidget.created() : super.created();

  @override
  bool get applyAuthorStyles => true;

  String joinClasses(List<String> cls) => cls.join(" ");

  Element getShadowDomElement(String selectors) =>
      shadowRoot.querySelector(selectors);

  void focus() {
    // Only the first found element that has 'focused' attribute on it will be
    // actually focused; if there are more than one, the rest will be ignored.
    Element elementToFocus = this.getShadowDomElement('[focused]');
    if (elementToFocus != null) {
      elementToFocus.focus();
    }
  }
}

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

library spark_widgets;

import 'dart:html';

import 'package:polymer/polymer.dart';

bool IS_DART2JS = identical(1, 1.0);

// NOTE: This SparkWidget element is not intended to use directly.
@CustomTag('spark-widget')
class SparkWidget extends PolymerElement {
  static const CSS_ENABLED = "enabled";
  static const CSS_DISABLED = "disabled";

  // Popular key codes
  static const DOWN_KEY = 40;
  static const UP_KEY = 38;
  static const ENTER_KEY = 13;
  static const ESCAPE_KEY = 27;

  SparkWidget.created() : super.created();

  String joinClasses(List<String> cls) => cls.join(" ");

  Element getShadowDomElement(String selectors) =>
      shadowRoot.querySelector(selectors);

  void focus() {
    // Only the first found element that has 'focused' attribute on it will be
    // actually focused; if there are more than one, the rest will be ignored.
    Element elementToFocus = this.getShadowDomElement('[focused]');
    if (elementToFocus != null) {
      elementToFocus.focus();
    }
  }
}

Remove overridden applyAuthorStyles (obsoleted in Chrome M34)


class Position {

  Position._({
    this.longitude,
    this.latitude,
    this.accuracy,
    this.altitude,
    this.altitudeAccuracy,
    this.heading,
    this.speed,
    this.speedAccuracy
  });

  final double latitude;
  final double longitude;
  final double altitude;
  final double accuracy;
  final double altitudeAccuracy;
  final double heading;
  final double speed;
  final double speedAccuracy;

  static Position fromMap(dynamic message) {
    final Map<dynamic, dynamic> map = message;

    return new Position._(
        latitude: map['latitude'],
        longitude: map['longitude'],
        altitude: map.containsKey('altitude') ? map['altitude'] : 0.0,
        accuracy: map.containsKey('accuracy') ? map['accuracy'] : 0.0,
        heading: map.containsKey('heading') ? map['heading'] : 0.0,
        speed: map.containsKey('speed') ? map['speed'] : 0.0,
        speedAccuracy: map.containsKey('speed_accuracy') ? map['speed_accuracy'] : 0.0,
    );
  }
}

/// Contains detail location information.
class Position {

  Position._({
    this.longitude,
    this.latitude,
    this.accuracy,
    this.altitude,
    this.heading,
    this.speed,
    this.speedAccuracy
  });

  /// Gets or sets the location latitude.
  final double latitude;
  /// Gets or sets the location longitude.
  final double longitude;
  /// Gets or sets the altitude of the device.
  ///
  /// The altitude is not available on all devices. In these cases the value is 0.0.
  final double altitude;
  /// Gets or sets the accuracy of the device.
  ///
  /// The accuracy is not available on all devices. In these cases the value is 0.0.
  final double accuracy;
  /// Gets or sets the heading of the device.
  ///
  /// The heading is not available on all devices. In these cases the value is 0.0.
  final double heading;
  /// Gets or sets the speed at which the device is travelling
  ///
  /// The speed is not available on all devices. In these cases the value is 0.0.
  final double speed;
  /// Gets or sets the accuracy at which the traveling speed of the device was determined.
  ///
  /// The speedAccuracy is not available on all devices. In these cases the value is 0.0.
  final double speedAccuracy;

  /// Converts the supplied [Map] to an instance of the [Position] class.
  static Position fromMap(dynamic message) {
    final Map<dynamic, dynamic> map = message;

    return new Position._(
        latitude: map['latitude'],
        longitude: map['longitude'],
        altitude: map.containsKey('altitude') ? map['altitude'] : 0.0,
        accuracy: map.containsKey('accuracy') ? map['accuracy'] : 0.0,
        heading: map.containsKey('heading') ? map['heading'] : 0.0,
        speed: map.containsKey('speed') ? map['speed'] : 0.0,
        speedAccuracy: map.containsKey('speed_accuracy') ? map['speed_accuracy'] : 0.0,
    );
  }
}

Add documentation to the Position class

Add documentation to the Position class


library textmarker;

import 'dart:html';

class TextMarker {
  String targettext;
  int startposition;
  int endposition;
  String textState; // were characters from start to end position typed correctly.

  TextMarker(this.targettext,this.startposition, this.endposition,this.textState);

  SpanElement textSpan(int start,end, String classname) {
    var span = new SpanElement()
      ..classes.add(classname)
      ..text = targettext.substring(start,end);
    return span;
  }
}

library textmarker;

import 'dart:html';

class TextMarker {
  String targettext;
  int startposition;
  int endposition;
  String textState; // were characters from start to end position typed correctly.

  TextMarker(this.targettext,this.startposition, this.endposition,this.textState);

  SpanElement textSpan(int start,end, String classname) {
    var span = new SpanElement()
      ..classes.add(classname)
      ..text = targettext.substring(start,end);
    return span;
  }
  SpanElement typedCorrectly(int start,end) {
    return textSpan(start,end, 'typedcorrect');
  }
  SpanElement typedIncorrectly(int start,end) {
    return textSpan(start,end, 'typedincorrect');
  }
  SpanElement yetToBeTyped(int start,end) {
    return textSpan(start,end, 'nottyped');
  }
}

Add span functions for different textstates.


part of streamy.testing;

class DynamicEntity extends RawEntity {

  DynamicEntity() : super();

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

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

  Type get streamyType => DynamicEntity;
}

class ClosureInvocationException extends StreamyException {

  final String memberName;

  ClosureInvocationException(this.memberName);

  String toString() => "Fields of DynamicEntity objects can't be invoked, as " +
      'they cannot contain closures. Field: $memberName';
}

part of streamy.testing;

class DynamicEntity extends RawEntity {

  DynamicEntity() : super();

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

  noSuchMethod(Invocation invocation) {
    var memberName = MirrorSystem.getName(invocation.memberName);
    if (invocation.isGetter) {
      return this[memberName];
    } else if (invocation.isSetter) {
      // Setter member names have an '=' at the end, strip it.
      var key = memberName.substring(0, memberName.length - 1);
      this[key] = invocation.positionalArguments[0];
    } else {
      // Perhaps the called was trying to call a nonexistent method,
      // or perhaps the caller was trying to invoke a data member as a
      // completion. Throw an appropriate error.
      if (containsKey(memberName)) {
        throw new ClosureInvocationException(memberName);
      } else {
        throw new NoSuchMethodError(this, memberName,
            invocation.positionalArguments, invocation.namedArguments);
      }
    }
  }

  Type get streamyType => DynamicEntity;
}

class ClosureInvocationException extends StreamyException {

  final String memberName;

  ClosureInvocationException(this.memberName);

  String toString() => "Fields of DynamicEntity objects can't be invoked, as " +
      'they cannot contain closures. Field: $memberName';
}

Remove obsolete namedArguments workaround in DynamicEntity


part of test.core;

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

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

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

part of test.core;

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

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

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

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

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


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

library freecell.tableau;

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

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

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

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

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

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

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

library freecell.tableau;

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

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

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

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

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

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

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

Add a getter to tell when you've wone

Add a getter to tell when you've wone


part of streamy.runtime;

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

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

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

  const _ErrorEntity();

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

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

const _INTERNAL_ERROR = const _ErrorEntity();

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

part of streamy.runtime;

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

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

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

  const _ErrorEntity();

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

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

const _INTERNAL_ERROR = const _ErrorEntity();

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

Add missing containsKey to _ErrorEntity

Add missing containsKey to _ErrorEntity


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

import 'dart:mojo_application';
import 'dart:mojo_bindings';
import 'dart:mojo_core';

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

class ConsoleApplication extends Application {
  ConsoleProxy _proxy;

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

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

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

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

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

import 'dart:async';
import 'dart:mojo_application';
import 'dart:mojo_bindings';
import 'dart:mojo_core';

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

class ConsoleApplication extends Application {
  ConsoleProxy _proxy;

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

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

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

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

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

Use await syntax in the console example.

BUG=none
R=zra@google.com

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


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

// Dart test program to test type-based optimization on fields.

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

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

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

// Dart test program to test type-based optimization on fields.

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

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

Fix type annotation error in test.

Fix type annotation error in test.

R=floitsch@google.com
BUG=
TEST=

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

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


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

class _Closure implements Function {

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

  int get hashCode native "Closure_hashCode";

  _Closure get call => this;

  _Closure _clone() native "Closure_clone";

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

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

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

class _Closure implements Function {

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

  int get hashCode native "Closure_hashCode";

  _Closure get call => this;

  _Closure _clone() native "Closure_clone";

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

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

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

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

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

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


part of github.client;

class Commit {
  final GitHub github;

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

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

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

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

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

  DateTime authoredAt;
  DateTime committedAt;

  Commit(this.github);

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

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

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

    return commit;
  }
}

part of github.client;

class Commit {
  final GitHub github;

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

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

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

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

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

  DateTime authoredAt;
  DateTime committedAt;

  String committerEmail;
  String authorEmail;

  Commit(this.github);

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

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

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

    return commit;
  }
}

Add Committer and Author Emails

Add Committer and Author Emails


library valorzhong_bones;

import 'dart:math' as Math;

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

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

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

const TWO_PI = Math.PI * 2;

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

Add helper function for string named 'capitalize '


part of pin;

class PinLogger {

  static Logger _logger;
  static File _file;

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

    return _logger;
  }

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

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

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

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

}

part of pin;

class PinLogger {

  static Logger _logger;
  static File _file;

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

    return _logger;
  }

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

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

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

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

}

Handle log to file exception.

Handle log to file exception.


import 'dart:ui';

import 'package:easy_localization/easy_localization.dart';

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

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

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

import 'dart:ui';

import 'package:easy_localization/easy_localization.dart';

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

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

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

Fix Swedish translations not being implemented.


part of streamy.runtime;

class DynamicEntity extends RawEntity {

  DynamicEntity() : super();

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

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

  Type get streamyType => DynamicEntity;
}

part of streamy.runtime;

class DynamicEntity extends RawEntity {

  DynamicEntity() : super();

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

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

  Type get streamyType => DynamicEntity;
}

Throw NoSuchMethodError if the caller requests a nonexistent member

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


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

#import("dart:io");

class ProcessStartExceptionTest {

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

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

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

main() {
  ProcessStartExceptionTest.testStartError();
}

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

#import("dart:io");

class ProcessStartExceptionTest {

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

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

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

main() {
  ProcessStartExceptionTest.testStartError();
}

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

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

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

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


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

library byte_stream;

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

import 'utils.dart';

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

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

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

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

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

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

library byte_stream;

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

import 'utils.dart';

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

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

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

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

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

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

This should speed up the library significant.

BUG=
R=sgjesse@google.com

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

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


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

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

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


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

library vm_service_client.exceptions;

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

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

  VMSentinelException(this.sentinel);

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

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

  VMErrorException(this.error);

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

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

  UnsupportedVersionException([this.version]);

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

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

library vm_service_client.exceptions;

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

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

  VMSentinelException(this.sentinel);

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

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

  VMErrorException(this.error);

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

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

  VMUnsupportedVersionException([this.version]);

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

Fix some bugs in the previous CL.

Fix some bugs in the previous CL.

R=kevmoo@google.com

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


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

class StayPoint extends Coordinate {
    LocationDegrees latitude;
    LocationDegrees longitude;

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

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

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

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

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

}

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

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

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

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

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

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

Fix issue with StayPoint class inheritance


library credentials;

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

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

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

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

library credentials;

import 'dart:convert';

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

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

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

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

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

Add JSON convertion for Credentials

Add JSON convertion for Credentials


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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

R=floitsch@google.com
BUG=
TEST=

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

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


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

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

RandomAccessFile _randomFile;
bool _haveWarned = false;

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

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

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

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

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

Random randomSource;
bool _haveWarned = false;

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

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

Use Random.secure() for random bytes

Use Random.secure() for random bytes


import 'dart:isolate';

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

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

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

Make the example a little bit more complicated

Added not necessary dependency to distributed_dart to test dependencies
check.


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

import 'package:analysis_server/src/services/correction/dart/abstract_producer.dart';
import 'package:analysis_server/src/services/correction/fix.dart';
import 'package:analyzer/dart/ast/ast.dart';
import 'package:analyzer_plugin/utilities/change_builder/change_builder_core.dart';
import 'package:analyzer_plugin/utilities/fixes/fixes.dart';

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

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

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

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

import 'package:analysis_server/src/services/correction/dart/abstract_producer.dart';
import 'package:analysis_server/src/services/correction/fix.dart';
import 'package:analyzer/dart/ast/ast.dart';
import 'package:analyzer_plugin/utilities/change_builder/change_builder_core.dart';
import 'package:analyzer_plugin/utilities/fixes/fixes.dart';

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

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

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

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

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

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