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

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

import 'material_icon.dart';

/// Adds a second icon to [MaterialIconComponent] that can be toggled on and
/// off.
///
/// See [https://www.google.com/design/icons/](https://goo.gl/YKrYlu) for
/// available icons. If the icon name contains spaces, replace them with
/// underscores.
///
/// The following css selectors can be used to target the icons for stylign in
/// various states:
/// - `.basic-icon`  -- Standard icon displayed when _not_ in the toggled state.
/// - `.toggled-icon`  -- Toggle icon displayed when in the toggled state.
/// - `.hide-icon` -- No icon when in a toggled state that doesn't have an icon.
@Directive(selector: 'material-icon[toggle]')
class MaterialIconToggleDirective implements AfterChanges {
  MaterialIconComponent iconRef;
  final ChangeDetectorRef _cdRef;
  bool _showToggled;
  bool _showBasic;
  bool _hideIcon;

  MaterialIconToggleDirective(this._cdRef, this.iconRef);

  /// The `Icon` model (third_party.dart_src.acx.model.ui.Icon) or icon
  /// identifier (String) to display.
  ///
  /// Defaults to a checkmark icon.
  @Input()
  dynamic toggledIcon = 'check';

  /// The `Icon` model (third_party.dart_src.acx.model.ui.Icon) or icon
  /// identifier (String) to display.
  ///
  /// If not provided this toggle icon will not display an icon in the standard
  /// state.
  @Input()
  dynamic icon;

  /// The toggled state of this icon.
  ///
  /// The [toggledIcon] is displayed when true.
  @Input()
  bool toggle;

  @override
  ngAfterChanges() {
    iconRef.icon = toggle ? toggledIcon : icon;
    _showToggled = toggle && _hasValue(toggledIcon);
    _showBasic = !toggle && _hasValue(icon);
    _hideIcon =
        (toggle && !_hasValue(toggledIcon)) || (!toggle && !_hasValue(icon));
    // Ensure the icon displayed by the underlying material-icon is updated.
    _cdRef.markForCheck();
  }

  @HostBinding('class.basic-icon.if')
  @visibleForTemplate
  bool get showBasic => _showBasic;

  @HostBinding('class.toggled-icon.if')
  @visibleForTemplate
  bool get showToggled => _showToggled;

  @HostBinding('class.hide-icon.if')
  @visibleForTemplate
  bool get hideIcon => _hideIcon;

  bool _hasValue(dynamic iconValue) => !(iconValue == null || iconValue == '');
}

Implement MaterialIconToggleDirective to allow for an icon with two states.

Supports switching between displaying the `icon` and `toggledIcon` via the toggle @Input.

PiperOrigin-RevId: 225255955


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

// SharedOptions=--enable-experiment=non-nullable

// Test that it is an error if a named parameter that is part of a required
// group is not bound to an argument at a call site.
typedef String F({required String x});

class A {
  A({required int a}) {}
  A.named() : this(); //# 01: compile-time error
  void m1({required int a}) {}
  F m2() => ({required String x}) => null;
}

class B extends A { B() : super(); } //# 02: compile-time error

void f({required int a}) {}

void Function({required int a}) g() => null;

main() {
  A a = new A(); //# 03: compile-time error
  A a = A(); //# 04: compile-time error
  f(); //# 05: compile-time error
  g()(); //# 06: compile-time error
  new A(a: 0).m1(); //# 07: compile-time error
  new A(a: 0).m2()(); //# 08: compile-time error
}

Add a language_2 test for missing arguments related to required named parameters

Change-Id: I4d08c5a7d7bd7950fab001281f26f2e838335339
Reviewed-on: https://dart-review.googlesource.com/c/sdk/+/100724
Reviewed-by: Paul Berry <72d414e3a99fb120308437779d51667bcc0984eb@google.com>
Commit-Queue: Brian Wilkerson <1f7641b6b14c52b9163524ab8d9aabff80176f21@google.com>


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

import 'dart:io' as io;
import 'dart:async';
import 'package:gcloud/db.dart' as db;
import 'package:gcloud/service_scope.dart' as ss;
import 'package:gcloud/src/datastore_impl.dart' as datastore_impl;
import 'package:sintr_common/auth.dart';
import "package:sintr_common/configuration.dart" as config;
import 'package:sintr_common/logging_utils.dart';
import 'package:sintr_common/logging_utils.dart' as log;
import 'package:sintr_common/tasks.dart' as tasks;

const LOOP_DELAY = const Duration(seconds: 600);
const String projectId = "liftoff-dev";

main(List<String> args) async {
  setupLogging();
  bool loop = false;

  // TODO: Replace this with the args parse package
  if (args.length != 0 && (args.length != 1 && args[0] == "--loop")) {
    print("Wait for workers to be done");
    print("Usage dart query.dart [--loop]");
    io.exit(1);
  }

  if (args.length == 1 && args[0] == "--loop") loop = true;

  config.configuration = new config.Configuration(projectId,
      cryptoTokensLocation:
          "${config.userHomePath}/Communications/CryptoTokens");

  var client = await getAuthedClient();

  tasks.TaskController taskController =
      new tasks.TaskController("example_task");

  var datastore = new datastore_impl.DatastoreImpl(client, 's~$projectId');
  var datastoreDB = new db.DatastoreDB(datastore);

  log.info("Setup done");

  await ss.fork(() async {
    db.registerDbService(datastoreDB);

    do {
      Map<String, int> readyCounts = await taskController.queryTasksReady();

      bool readyTasksLeft = false;

      for (String key in readyCounts.keys) {
        log.info("$key: ${readyCounts[key]}");

        var readyCount = readyCounts[key];
        if (readyCount == null || readyCount == 0) {

          // No more tasks ready
          // TODO: This doesn't mean that the job is done. Improve detection
        } else {
          readyTasksLeft = true;
        }
      }

      if (!readyTasksLeft) break;

      await new Future.delayed(LOOP_DELAY);
    } while (loop);

  });
}

Use more datastore efficent wait for done


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

class _MyInsertable extends Insertable<void> {
  const _MyInsertable();

  @override
  Map<String, Expression> toColumns(bool nullToAbsent) => const {};
}

void main() {
  test(
    'Insertable should have a const constructor so a subclass can be a const',
    () {
      const myInsertable = const _MyInsertable();
    },
  );
}

Add a test using a const insertable

:white_check_mark: Add a test using a const insertable


import 'dart:io';

import 'package:flutter_test/flutter_test.dart';
import 'package:path/path.dart';

Future testSameFileContent(String path1, String path2) async {
  // print(path1);
  expect(await File(path1).readAsString(), await File(path2).readAsString(),
      reason: '$path1 differs');
}

void main() {
  TestWidgetsFlutterBinding.ensureInitialized();

  group('macos', () {
    test('ios/macos sample implementation', () async {
      final ios = 'ios/Classes';
      final macos = 'macos/Classes';
      for (var file in [
        ...['.h', '.m'].map((ext) => 'SqfliteOperation$ext'),
        ...['.h', '.m'].map((ext) => 'SqflitePlugin$ext')
      ]) {
        await testSameFileContent(join(ios, file), join(macos, file));
      }
    });
  });
}

test: Make sure ios and macos implementation is always the same


// 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 'basic.dart';
import 'button_base.dart';
import 'ink_well.dart';
import 'material.dart';
import 'theme.dart';

// TODO(eseidel): This needs to change based on device size?
// http://www.google.com/design/spec/layout/metrics-keylines.html#metrics-keylines-keylines-spacing
const double _kSize = 56.0;

class FloatingActionButton extends ButtonBase {

  FloatingActionButton({
    String key,
    this.child,
    Function onPressed
  }) : super(key: key);

  Widget child;
  Function onPressed;

  void syncFields(FloatingActionButton source) {
    super.syncFields(source);
    child = source.child;
    onPressed = source.onPressed;
  }

  Widget buildContent() {
    return new Material(
      color: Theme.of(this).accent[200],
      edge: MaterialEdge.circle,
      level: highlight ? 3 : 2,
      child: new ClipOval(
        child: new Listener(
          onGestureTap: (_) {
            if (onPressed != null)
              onPressed();
          },
          child: new Container(
            width: _kSize,
            height: _kSize,
            child: new InkWell(child: new Center(child: child))
          )
        )
      )
    );
  }

}

// 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 'basic.dart';
import 'button_base.dart';
import 'ink_well.dart';
import 'material.dart';
import 'theme.dart';

// TODO(eseidel): This needs to change based on device size?
// http://www.google.com/design/spec/layout/metrics-keylines.html#metrics-keylines-keylines-spacing
const double _kSize = 56.0;

class FloatingActionButton extends ButtonBase {

  FloatingActionButton({
    String key,
    this.child,
    this.onPressed
  }) : super(key: key);

  Widget child;
  Function onPressed;

  void syncFields(FloatingActionButton source) {
    super.syncFields(source);
    child = source.child;
    onPressed = source.onPressed;
  }

  Widget buildContent() {
    return new Material(
      color: Theme.of(this).accent[200],
      edge: MaterialEdge.circle,
      level: highlight ? 3 : 2,
      child: new ClipOval(
        child: new Listener(
          onGestureTap: (_) {
            if (onPressed != null)
              onPressed();
          },
          child: new Container(
            width: _kSize,
            height: _kSize,
            child: new InkWell(child: new Center(child: child))
          )
        )
      )
    );
  }

}

Make FloatingActionButton respect the onPressed ctor arg.

BUG=
R=abarth@chromium.org

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


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

// On frogsh constant folded hex literals of large magnitude were truncated on
// constant folding - Issue 636 is 'fixed', remaining concerns at Issue 638.

highDigitTruncationTest() {
  Expect.equals(0x12345678A, 0x123456789 + 1);

  // in 32 bits this is 0xF0000000 which is negative.
  Expect.isTrue(0x1f0000000 > 0);

  Expect.equals(0xf0, 0xf * 16);
  Expect.equals(0xff0, 0xff * 16);
  Expect.equals(0xfff0, 0xfff * 16);
  Expect.equals(0xffff0, 0xffff * 16);
  Expect.equals(0xfffff0, 0xfffff * 16);
  Expect.equals(0xffffff0, 0xffffff * 16);
  Expect.equals(0xfffffff0, 0xfffffff * 16);
  Expect.equals(0xffffffff0, 0xffffffff * 16);
  Expect.equals(0xfffffffff0, 0xfffffffff * 16);
  Expect.equals(0xffffffffff0, 0xffffffffff * 16);
}

main() {
  highDigitTruncationTest();
}

Frog: Fix parsing of hex literals with >31 bits

BUG=
TEST=

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

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


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

import '../helpers/color_palette_helper.dart';

class MediaTypeIcon extends StatelessWidget {
  final String mediaType;
  final Color iconColor;

  const MediaTypeIcon({Key key, @required this.mediaType, this.iconColor})
      : super(key: key);

  @override
  Widget build(BuildContext context) {
    return _mapMediaTypeToIcon(mediaType, iconColor);
  }
}

FaIcon _mapMediaTypeToIcon(
  String mediaType,
  Color iconColor,
) {
  switch (mediaType) {
    case ('movie'):
      return FaIcon(
        FontAwesomeIcons.film,
        size: 18,
        color: iconColor ?? TautulliColorPalette.not_white,
      );
    case ('episode'):
    case ('season'):
    case ('show'):
      return FaIcon(
        FontAwesomeIcons.tv,
        size: 14,
        color: iconColor ?? TautulliColorPalette.not_white,
      );
    case ('track'):
    case ('album'):
      return FaIcon(
        FontAwesomeIcons.music,
        size: 16,
        color: iconColor ?? TautulliColorPalette.not_white,
      );
    case ('photo'):
      return FaIcon(
        FontAwesomeIcons.image,
        size: 18,
        color: iconColor ?? TautulliColorPalette.not_white,
      );
    case ('clip'):
      return FaIcon(
        FontAwesomeIcons.video,
        size: 17,
        color: iconColor ?? TautulliColorPalette.not_white,
      );
    default:
      return FaIcon(
        FontAwesomeIcons.questionCircle,
        size: 17,
        color: iconColor ?? TautulliColorPalette.not_white,
      );
  }
}

Add core media type icon widget.

Add core media type icon widget.


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

// Test that substitutions are emitted for classes that are only used as
// type arguments.

import 'package:expect/expect.dart';

class K {}

class A<T> {}

class B extends A<K> {}

class X<T> {}

main() {
  var v = new DateTime.now().millisecondsSinceEpoch != 42
    ? new X<B>() : new X<A<String>>();
  Expect.isFalse(v is X<A<String>>);
}

Add a test to test that substitutions are emitted for classes that are only used as type arguments.

R=floitsch@google.com

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

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


part of github.client;

class Commit {
  final GitHub github;

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

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

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

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

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

  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.commiter = User.fromJSON(github, input['commiter']);
    commit.message = input['message'];
    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 commiter;

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

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

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

  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.commiter = User.fromJSON(github, input['commiter']);
    commit.message = input['message'];

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

    return commit;
  }
}

Fix Bug in Commits API

Fix Bug in Commits API


part of elevator;

class CommandStack {

  Queue<String> _stack = new Queue();
  int _maxSize;
  int _idx = 1;
  List<List<String>> _shots = new List();

  CommandStack(this._maxSize);

  void add(String value) {
    _stack.addLast("${_idx++}: ${value}");
    if (_stack.length > _maxSize) {
      _stack.removeFirst();
    }
  }

  void addStackShot(int nbMsg) {
    List<String> shot = new List();
    shot.addAll(_stack.skip(_stack.length > nbMsg ? _stack.length - nbMsg : _stack.length));
    _shots.add(shot);
  }

  String toString() {
    String resets = _shots.fold("", (String result, List<String> values) => result + "\n" + values.fold("\nReset received:\n---------------", (String result, String value) => "${result}\n${value}"));
    String stack = _stack.fold("Command stack:\n--------------", (String result, String value) => "${result}\n${value}");
    return "${resets}\n\n${stack}";
  }

}

Add a stacktrace handler to understand why my elevator is reset


import "dart:async";
import "package:dart_amqp/dart_amqp.dart";

void main() async {
  Completer done = Completer();
  Client client = Client();
  Channel channel = await client.channel();
  Queue queue = await channel.privateQueue();

  // To work with publish confirmations we first need to enable support for
  // confirmations on the channel used by our queue.
  await queue.channel.confirmPublishedMessages();

  // Then register a handler to process publish notifications.
  queue.channel.publishNotifier((PublishNotification notification) {
    Object? msg = notification.message;
    String? corId = notification.properties?.corellationId;
    bool ack = notification.published;
    print(
        " [!] received delivery notification: msg: '$msg', correlation ID: '$corId', ACK'd?: $ack");
    done.complete();
  });

  MessageProperties msgProps = MessageProperties()..corellationId = "42";
  queue.publish("Hello World!", properties: msgProps);
  print(" [x] Sent 'Hello World!'; waiting for delivery confirmation");

  await done.future;
  await client.close();
}

Add example for using the publish notification feature


import 'dart:io';

import 'package:moor_ffi/moor_ffi.dart';
import 'package:path/path.dart';
import 'package:test/test.dart';
import 'package:tests/database/database.dart';

final File mainFile =
    File(join(Directory.systemTemp.path, 'moor-save-and-restore-tests-1'));
final File createdForSwap =
    File(join(Directory.systemTemp.path, 'moor-save-and-restore-tests-2'));

void main() {
  test('can save and restore a database', () async {
    if (await mainFile.exists()) {
      await mainFile.delete();
    }
    if (await createdForSwap.exists()) {
      await createdForSwap.delete();
    }

    const nameInSwap = 'swap user';
    const nameInMain = 'main';

    // Prepare the file we're swapping in later
    final dbForSetup = Database(VmDatabase(createdForSwap));
    await dbForSetup.into(dbForSetup.users).insert(
        UsersCompanion.insert(name: nameInSwap, birthDate: DateTime.now()));
    await dbForSetup.close();

    // Open the main file
    var db = Database(VmDatabase(mainFile));
    await db.into(db.users).insert(
        UsersCompanion.insert(name: nameInMain, birthDate: DateTime.now()));
    await db.close();

    // Copy swap file to main file
    await mainFile.writeAsBytes(await createdForSwap.readAsBytes(),
        flush: true);

    // Re-open database
    db = Database(VmDatabase(mainFile));
    final users = await db.select(db.users).get();

    expect(
      users.map((u) => u.name),
      allOf(contains(nameInSwap), isNot(contains(nameInMain))),
    );
  });
}

Add integration test to save and restore databases


/// Insertion Sort the input list
void insertionSort(List<int> items) {
  // Iterate through the array, knowing i-and-left is sorted and bubbling
  // to-the-right-of-i elements left until they reach the correct position
  for (int i = 0; i < items.length - 1; i++) {
    // Vars for the left and right comparators
    int l = i;
    int r = l + 1;

    while (l >= 0) {
      r = l + 1;
      if (items[l] > items[r]) {
        // Swap items
        final int higherNumber = items[l];
        items[l] = items[r];
        items[r] = higherNumber;
      }
      l--;
    }
  }
}

// ----- Test -----
void main() {
  // 1. Arrange
  final List<int> testedList = [10, 2, 8, 5, 6, 1, 4, 7, 9, 3];
  final List<int> expectedOutput = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

  // 2. Act
  insertionSort(testedList);
  print(testedList);

  // 3. Assert
  // No simple list equality in dart yet so using 'fold' to recursively check
  // each sorted element compared to the expected output at each index.
  int i = 0;
  final bool isEqual = testedList.fold(
    true,
    (result, item) => result && item == expectedOutput[i++],
  );
  print(isEqual);
}

Add Dart implementation of Insertion Sort


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

import 'dart:uri';
import 'dart:io';
import '../../../sdk/lib/_internal/compiler/compiler.dart' as api;
import '../../../sdk/lib/_internal/compiler/implementation/apiimpl.dart';
import '../../../sdk/lib/_internal/compiler/implementation/dart2jslib.dart'
    hide Compiler;
import '../../../sdk/lib/_internal/compiler/implementation/filenames.dart';
import '../../../sdk/lib/_internal/compiler/implementation/source_file_provider.dart';
import '../../../sdk/lib/_internal/libraries.dart';

class CollectingDiagnosticHandler extends FormattingDiagnosticHandler {
  bool hasWarnings = false;
  bool hasErrors = false;

  CollectingDiagnosticHandler(SourceFileProvider provider) : super(provider);

  void diagnosticHandler(Uri uri, int begin, int end, String message,
                         api.Diagnostic kind) {
    if (kind == api.Diagnostic.WARNING) {
      hasWarnings = true;
    }
    if (kind == api.Diagnostic.ERROR) {
      hasErrors = true;
    }
    super.diagnosticHandler(uri, begin, end, message, kind);
  }
}

void main() {
  Uri currentWorkingDirectory = getCurrentDirectory();
  var libraryRoot = currentWorkingDirectory.resolve('sdk/');
  var uriList = new List<Uri>();
  LIBRARIES.forEach((String name, LibraryInfo info) {
    if (info.documented) {
      uriList.add(new Uri.fromComponents(scheme: 'dart', path: name));
    }
  });
  var provider = new SourceFileProvider();
  var handler = new CollectingDiagnosticHandler(provider);
  var compiler = new Compiler(
      provider.readStringFromUri,
      handler.diagnosticHandler,
      libraryRoot, libraryRoot,
      <String>['--analyze-only']);
  compiler.librariesToAnalyzeWhenRun = uriList;
  compiler.run(null);
  Expect.isFalse(handler.hasWarnings);
  Expect.isFalse(handler.hasErrors);
}

Add dart2js unittest to analyze the API.

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

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


// 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 Foo {
  var x;
  var y;
  var z;
  var v;
  Foo() : x = {}, y = <int>{}, z = const {}, v = const <int>{};
}

main() {
  Expect.equals("{}", new Foo().x.toString());
  Expect.equals("{}", new Foo().y.toString());
  Expect.equals("{}", new Foo().z.toString());
  Expect.equals("{}", new Foo().v.toString());
}

Fix bug in partial parsing of map literal.

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

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


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

import 'package:newton/newton.dart';
import 'package:sky/animation/direction.dart';

// Base class for creating Simulations for the animation Timeline.
abstract class Force {
  Simulation release(double position, double velocity, Direction direction);
}

class SpringForce extends Force {
  SpringForce(this.spring, {this.left: 0.0, this.right: 1.0});

  final SpringDescription spring;
  // Where to put the spring's resting point when releasing left or right,
  // respectively.
  final double left, right;

  Simulation release(double position, double velocity, Direction direction) {
    // Target just past the endpoint, because the animation will stop once the
    // Spring gets within the epsilon, and we want to stop at the endpoint.
    double target = direction == Direction.reverse ?
        this.left - _kEpsilon : this.right + _kEpsilon;
    return new SpringSimulation(spring, position, target, velocity);
  }
}

final SpringDescription _kDefaultSpringDesc =
    new SpringDescription.withDampingRatio(mass: 1.0, springConstant: 500.0, ratio: 1.0);
final SpringForce kDefaultSpringForce = new SpringForce(_kDefaultSpringDesc);

const double _kEpsilon = 0.001;

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

import 'package:newton/newton.dart';
import 'package:sky/animation/direction.dart';

// Base class for creating Simulations for the animation Timeline.
abstract class Force {
  Simulation release(double position, double velocity, Direction direction);
}

class SpringForce extends Force {
  SpringForce(this.spring, {this.left: 0.0, this.right: 1.0});

  // We overshoot the target by this distance, but stop the simulation when
  // the spring gets within this distance (regardless of how fast it's moving).
  // This causes the spring to settle a bit faster than it otherwise would.
  static final Tolerance tolerance =
      new Tolerance(velocity: double.INFINITY, distance: 0.01);

  final SpringDescription spring;
  // Where to put the spring's resting point when releasing left or right,
  // respectively.
  final double left, right;

  Simulation release(double position, double velocity, Direction direction) {
    double target = direction == Direction.reverse ?
        this.left - tolerance.distance : this.right + tolerance.distance;
    return new SpringSimulation(spring, position, target, velocity)
      ..tolerance = tolerance;
  }
}

final SpringDescription _kDefaultSpringDesc =
    new SpringDescription.withDampingRatio(mass: 1.0, springConstant: 500.0, ratio: 1.0);
final SpringForce kDefaultSpringForce = new SpringForce(_kDefaultSpringDesc);

Adjust the SpringForce tolerance, used by Drawer and Dismissable.

They settle much faster after you fling them now.


import 'package:build/build.dart';
import 'package:moor_generator/src/analyzer/runner/file_graph.dart';
import 'package:moor_generator/src/analyzer/runner/results.dart';
import 'package:moor_generator/src/analyzer/session.dart';
import 'package:test/test.dart';

import '../utils/test_backend.dart';

void main() {
  TestBackend backend;
  MoorSession session;

  setUpAll(() {
    backend = TestBackend({
      AssetId.parse('test_lib|lib/entry.dart'): r'''
import 'package:moor/moor.dart';

class Foos extends Table {
  IntColumn get id => integer().autoIncrement()();
}

@UseMoor(include: {'db.moor'}, tables: [Foos])
class Database {}
     ''',
      AssetId.parse('test_lib|lib/db.moor'): r'''
import 'entry.dart';

CREATE TABLE bars (
  id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT
);
      ''',
    });
    session = backend.session;
  });

  tearDownAll(() {
    backend.finish();
  });

  test('handles cyclic imports', () async {
    final backendTask =
        backend.startTask(Uri.parse('package:test_lib/entry.dart'));
    final task = session.startTask(backendTask);
    await task.runTask();

    final file = session.registerFile(Uri.parse('package:test_lib/entry.dart'));

    expect(file.state, FileState.analyzed);
    expect(file.errors.errors, isEmpty);

    final result = file.currentResult as ParsedDartFile;
    final database = result.declaredDatabases.single;

    expect(database.allTables.map((t) => t.sqlName),
        containsAll(['foos', 'bars']));
  });
}

Write another integration test with cyclic queries


// 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.
//
// VMOptions=--old_gen_heap_size=7
// Test that compaction does occur on repeated add/remove.

main() {
  var x = {};
  for (int i = 0; i < 1000000; i++) {
    x[i] = 10;
    x.remove(i);
  }
}

Add regression test for Map compaction issue.

Original fix for the issue:
https://code.google.com/p/dart/source/detail?r=44671

R=kustermann@google.com

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

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


import 'dart:async';
import 'dart:html';

import 'package:async_helper/async_helper.dart';
import 'package:expect/expect.dart';

test() async {
  var list = await window.navigator.mediaDevices.enumerateDevices();
  Expect.isTrue(list is List<dynamic>, "Expected list to be List<dynamic>");
}

void main() {
  asyncStart();
  test().then((_) => asyncEnd());
}

Add test to enumerate media devices

Add test to enumerate media devices

Bug: https://github.com/dart-lang/sdk/issues/39627

Enumerating media devices gives back a cast error in html_dart2js. This
test should fail and the cast should be fixed such that it passes.

Change-Id: Ie2502f265448d078578113cbea57dd81d20015c7
Reviewed-on: https://dart-review.googlesource.com/c/sdk/+/128104
Commit-Queue: Srujan Gaddam <4175f2f2dd3cde6c8ffb10fc9674dc09abf813fe@google.com>
Reviewed-by: Sigmund Cherem <beaea8fd7d2a56555046ba4f362c8a93e3938576@google.com>


part of github.common;

/// The [UsersService] handles communication with authorizations related methods
/// of the GitHub API.
///
/// Note: You can only access this API via Basic Authentication using your
/// username and password, not tokens.
///
/// API docs: https://developer.github.com/v3/oauth_authorizations/
class AuthorizationsService extends Service {

  AuthorizationsService(GitHub github) : super(github);

  /// Lists all authorizations.
  ///
  /// API docs: https://developer.github.com/v3/oauth_authorizations/#list-your-authorizations
  Stream<Authorization> listAuthorizations() {
    return new PaginationHelper(_github).objects("GET", "/authorizations",
        Authorization.fromJSON);
  }

  /// Fetches an authorization specified by [name].
  ///
  /// API docs: https://developer.github.com/v3/oauth_authorizations/#get-a-single-authorization
  Future<Authorization> getAuthorization(int id) {
    return _github.getJSON("/authorizations/${id}", statusCode: 200,
        convert: Authorization.fromJSON);
  }

  // TODO: Implement remaining API methods of authorizations:
  // See https://developer.github.com/v3/oauth_authorizations/
}

part of github.common;

/// The [AuthorizationsService] handles communication with authorizations related methods
/// of the GitHub API.
///
/// Note: You can only access this API via Basic Authentication using your
/// username and password, not tokens.
///
/// API docs: https://developer.github.com/v3/oauth_authorizations/
class AuthorizationsService extends Service {

  AuthorizationsService(GitHub github) : super(github);

  /// Lists all authorizations.
  ///
  /// API docs: https://developer.github.com/v3/oauth_authorizations/#list-your-authorizations
  Stream<Authorization> listAuthorizations() {
    return new PaginationHelper(_github).objects("GET", "/authorizations",
        Authorization.fromJSON);
  }

  /// Fetches an authorization specified by [name].
  ///
  /// API docs: https://developer.github.com/v3/oauth_authorizations/#get-a-single-authorization
  Future<Authorization> getAuthorization(int id) {
    return _github.getJSON("/authorizations/${id}", statusCode: 200,
        convert: Authorization.fromJSON);
  }

  // TODO: Implement remaining API methods of authorizations:
  // See https://developer.github.com/v3/oauth_authorizations/
}

Fix Typo in Authorizations Service

Fix Typo in Authorizations Service


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

import 'dart:async';

import 'package:analyzer/dart/analysis/results.dart';
import 'package:analyzer/src/dart/analysis/driver.dart';
import 'package:analyzer_plugin/plugin/plugin.dart';
import 'package:analyzer_plugin/protocol/protocol.dart';
import 'package:analyzer_plugin/protocol/protocol_generated.dart';
import 'package:analyzer_plugin/src/utilities/completion/completion_core.dart';
import 'package:analyzer_plugin/utilities/completion/completion_core.dart';
import 'package:analyzer_plugin/utilities/generator.dart';

/**
 * A mixin that can be used when creating a subclass of [ServerPlugin] to
 * provide most of the implementation for handling code completion requests.
 *
 * Clients may not extend or implement this class, but are allowed to use it as
 * a mix-in when creating a subclass of [ServerPlugin].
 */
abstract class CompletionMixin implements ServerPlugin {
  /**
   * Return a list containing the completion contributors that should be used to
   * create completion suggestions when used in the context of the given
   * analysis [driver].
   */
  List<CompletionContributor> getCompletionContributors(
      covariant AnalysisDriverGeneric driver);

  /**
   * Return the result of using the given analysis [driver] to produce a fully
   * resolved AST for the file with the given [path].
   */
  Future<ResolveResult> getResolveResultForCompletion(
      covariant AnalysisDriverGeneric driver, String path);

  @override
  Future<CompletionGetSuggestionsResult> handleCompletionGetSuggestions(
      CompletionGetSuggestionsParams parameters) async {
    String path = parameters.file;
    ContextRoot contextRoot = contextRootContaining(path);
    if (contextRoot == null) {
      // Return an error from the request.
      throw new RequestFailure(
          RequestErrorFactory.pluginError('Failed to analyze $path', null));
    }
    AnalysisDriverGeneric driver = driverMap[contextRoot];
    ResolveResult analysisResult =
        await getResolveResultForCompletion(driver, path);
    CompletionRequestImpl request = new CompletionRequestImpl(
        resourceProvider, analysisResult, parameters.offset);
    CompletionGenerator generator =
        new CompletionGenerator(getCompletionContributors(driver));
    GeneratorResult result =
        await generator.generateCompletionResponse(request);
    result.sendNotifications(channel);
    return result.result;
  }
}

Add a mixing that handles most of the work for computing completions

R=maxkim@google.com

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


// 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 contains code for collecting statistics about the use of fields in
 * a summary file.
 */
library analyzer.tool.summary.stats;

import 'dart:io';

import 'package:analyzer/src/summary/base.dart';
import 'package:analyzer/src/summary/idl.dart';

main(List<String> args) {
  if (args.length != 1) {
    _printUsage();
    exitCode = 1;
    return;
  }

  String inputFilePath = args[0];

  // Read the input.
  SdkBundle bundle =
      new SdkBundle.fromBuffer(new File(inputFilePath).readAsBytesSync());

  // Compute and output stats.
  Stats stats = new Stats();
  stats.record(bundle);
  stats.dump();
}

/**
 * The name of the stats tool.
 */
const String BINARY_NAME = "stats";

/**
 * Print information about how to use the stats tool.
 */
void _printUsage() {
  print('Usage: $BINARY_NAME input_file_path');
}

/**
 * An instance of [Stats] keeps track of statistics about the use of fields in
 * summary objects.
 */
class Stats {
  /**
   * Map from type to field name to a count of how often the field is used.
   */
  Map<Type, Map<String, int>> counts = <Type, Map<String, int>>{};

  /**
   * Print out statistics gathered so far.
   */
  void dump() {
    counts.forEach((Type type, Map<String, int> typeCounts) {
      print(type);
      List<String> keys = typeCounts.keys.toList();
      keys.sort((String a, String b) => typeCounts[b].compareTo(typeCounts[a]));
      for (String key in keys) {
        print('  $key: ${typeCounts[key]}');
      }
      print('');
    });
  }

  /**
   * Record statistics for [obj] and all objects it refers to.
   */
  void record(SummaryClass obj) {
    Map<String, int> typeCounts =
        counts.putIfAbsent(obj.runtimeType, () => <String, int>{});
    obj.toMap().forEach((String key, Object value) {
      if (value == null ||
          value == 0 ||
          value == false ||
          value == '' ||
          value is List && value.isEmpty) {
        return;
      }
      if (!typeCounts.containsKey(key)) {
        typeCounts[key] = 0;
      }
      typeCounts[key]++;
      if (value is SummaryClass) {
        record(value);
      } else if (value is List) {
        value.forEach((Object element) {
          if (element is SummaryClass) {
            record(element);
          }
        });
      }
    });
  }
}

Create a tool for collecting statistics about summary files.

In addition to exploring how the summary format is used, it should be a
nice micro-benchmark for FlatBuffer deserialization efficiency.

R=scheglov@google.com

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


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

// These tests are for an experimental feature that treats Dart primitive types
// (int, bool, double, etc.) as non-nullable. This file is not evidence for an
// intention to officially support non-nullable primitives in Dart (or general
// NNBD, for that matter) so don't get too crazy about it.

library analyzer.test.src.task.non_null_primitives.checker_test;

import '../../../reflective_tests.dart';
import '../strong/strong_test_helper.dart';

void main() {
  initStrongModeTests();
  runReflectiveTests(NonNullCheckerTest);
}

@reflectiveTest
class NonNullCheckerTest {
  // Tests simple usage of ints as iterators for a loop. Not directly related to
  // non-nullability, but if it is implemented this should be more efficient,
  // since languages.length will not be null-checked on every iteration.
  void test_forLoop() {
    checkFile('''
class MyList {
  int length;
  MyList() {
    length = 6;
  }
  String operator [](int i) {
    return <String>["Dart", "Java", "JS", "C", "C++", "C#"][i];
  }
}

main() {
  var languages = new MyList();
  for (int i = 0; i < languages.length; ++i) {
    print(languages[i]);
  }
}
''');
  }
}

Add test harness for experimental non-null option

non_null_checker_test.dart is closely following
../strong/checker_test.dart.  Currently it includes a single test which
is not directly related to nullability.

BUG=
R=jmesserly@google.com

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


library compare_to_golden;

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

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

Future compareSummaryFileToGolden(String dartFileName,
    {String summaryExtension, String goldenExtension}) async {
  var input = getFile(dartFileName, summaryExtension);
  var golden = getFile(dartFileName, goldenExtension);

  expect(await input.readAsString(), await golden.readAsString());
}

File getFile(String dartFileName, String extension) =>
    _getFile('${p.withoutExtension(dartFileName)}${extension}');

File _getFile(String filename) {
  Uri fileUri = new Uri.file(p.join(_testFilesDir, filename));
  return new File.fromUri(fileUri);
}

final String _testFilesDir = p.join(_scriptDir(), 'test_files');

String _scriptDir() =>
    p.dirname(currentMirrorSystem().findLibrary(#compare_to_golden).uri.path);

library compare_to_golden;

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

import 'package:dart_style/src/dart_formatter.dart';
import 'package:path/path.dart' as p;
import 'package:test/test.dart';

Future compareSummaryFileToGolden(String dartFileName,
    {String summaryExtension, String goldenExtension}) async {
  var input = getFile(dartFileName, summaryExtension);
  var golden = getFile(dartFileName, goldenExtension);

  final formattedInput = _formatter.format(await input.readAsString());
  final formattedGolden = _formatter.format(await golden.readAsString());
  expect(formattedInput, formattedGolden);
}

File getFile(String dartFileName, String extension) =>
    _getFile('${p.withoutExtension(dartFileName)}${extension}');

File _getFile(String filename) {
  Uri fileUri = new Uri.file(p.join(_testFilesDir, filename));
  return new File.fromUri(fileUri);
}

final String _testFilesDir = p.join(_scriptDir(), 'test_files');

String _scriptDir() =>
    p.dirname(currentMirrorSystem().findLibrary(#compare_to_golden).uri.path);

final _formatter = new DartFormatter();

Format golden files during test.

Angular: Format golden files during test.

PiperOrigin-RevId: 160161091


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

import '../helpers/color_palette_helper.dart';

class TranscodeDecisionIcon extends StatelessWidget {
  final String transcodeDecision;

  const TranscodeDecisionIcon({
    Key key,
    @required this.transcodeDecision,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return _mapTranscodeDecisionToIcon(transcodeDecision);
  }
}

FaIcon _mapTranscodeDecisionToIcon(String transcodeDecision) {
  switch (transcodeDecision) {
    case ('transcode'):
      return FaIcon(
        FontAwesomeIcons.server,
        size: 15,
        color: TautulliColorPalette.not_white,
      );
    case ('copy'):
      return FaIcon(
        FontAwesomeIcons.stream,
        size: 18,
        color: TautulliColorPalette.not_white,
      );
    case ('direct play'):
      return FaIcon(
        FontAwesomeIcons.playCircle,
        size: 17,
        color: TautulliColorPalette.not_white,
      );
    default:
      return FaIcon(
        FontAwesomeIcons.questionCircle,
        size: 17,
        color: TautulliColorPalette.not_white,
      );
  }
}

Add core transcode decision icon widget.