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

// Patch file for dart:developer library.

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

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

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

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

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

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

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

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

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

Add missing patch methods to dart2js implementation of timeline

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

// Patch file for dart:developer library.

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

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

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

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

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

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

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

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

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

@patch
int _getNextAsyncId() {
  return 0;
}

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


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

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

Use Quiver for Reversing Strings

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

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


library task;

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

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

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

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

Add timestamp to Task class.

library task;

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

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

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

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


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

import 'package:analysis_server/starter.dart';

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

Normalize with the internal verison of this file.

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

import 'package:analysis_server/starter.dart';

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


part of tmx;

class NodeDSL {
  XmlElement element;

  NodeDSL(this.element);

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

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

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

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

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

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

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

Return a NodeDSL object from NodeDSL.on

part of tmx;

class NodeDSL {
  XmlElement element;

  NodeDSL(this.element);

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

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

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

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

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

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

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


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

import 'dart:isolate';

import 'services.dart';

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

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

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

Revert "This statement crashes the isolate."

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

import 'dart:isolate';

import 'services.dart';

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

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

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


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

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

class DoubleTapToExit extends StatelessWidget {
  final Widget child;

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

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

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

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

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

Reduce the length of the toast message.

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

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

class DoubleTapToExit extends StatelessWidget {
  final Widget child;

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

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

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

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

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


library common;

import 'dart:io';

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

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

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

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

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

Add .git to excluded dirs

library common;

import 'dart:io';

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

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

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

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

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


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

// @dart = 2.10

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

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

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

Migrate abstract value strategy to null safety

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

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

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

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


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

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

Fix bug causing multi browser demo to crash

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

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


import 'dart:async';

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

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

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

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

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

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

Split debugPrint messages into 300 character chunks

import 'dart:async';

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

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

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

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

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

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


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

import 'dart:html';

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

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

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

  @override
  Element get nativeElement => _nativeElement;

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

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

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

Support disabled attribute in tab button

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

import 'dart:html';

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

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

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

  @override
  Element get nativeElement => _nativeElement;

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

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

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

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


import 'package:meta/meta.dart';

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

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

class ImageUrlDataSourceImpl implements ImageUrlDataSource {
  final tautulli_api.PmsImageProxy apiPmsImageProxy;

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

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

    return url;
  }
}

Change default GetImageUrl height & width.

import 'package:meta/meta.dart';

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

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

class ImageUrlDataSourceImpl implements ImageUrlDataSource {
  final tautulli_api.PmsImageProxy apiPmsImageProxy;

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

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

    return url;
  }
}


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

import 'dart:sky';

double timeBase = null;

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

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

Make tracing work in the new .dart world.

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

import 'dart:sky';

double timeBase = null;

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

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


library new_task;

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

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

}

Refresh task list view when new task is submitted

library new_task;

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

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

}


// 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=nonfunction-type-aliases

// Introduce an aliased type.

typedef T = Object;

// Use the aliased type.

abstract class C {
  T? v10;
  final T v12;
  C(): v12 = T();
  C.name1(this.v10, this.v12);
  factory C.name2(T arg1, T arg2) = C.name1;
}

abstract class D2 extends C with T {}
//             ^
// [analyzer] unspecified
// [cfe] unspecified

abstract class D3 implements T {}
//             ^
// [analyzer] unspecified
// [cfe] unspecified

abstract class D4 = C with T;
//             ^
// [analyzer] unspecified
// [cfe] unspecified

main() {
  T.named();
//  ^^^^^
// [analyzer] unspecified
// [cfe] unspecified

  T.staticMethod<T>();
//  ^^^^^^^^^^^^
// [analyzer] unspecified
// [cfe] Method not found: 'Object.staticMethod'.
//  ^^^^^^^^^^^^
// [cfe] A constructor invocation can't have type arguments on the constructor name.
}

Fix one more test with factory redirect to abstract class.

// 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=nonfunction-type-aliases

// Introduce an aliased type.

typedef T = Object;

// Use the aliased type.

abstract class C {
  T? v10;
  final T v12;
  C(): v12 = T();
  C.name1(this.v10, this.v12);
  factory C.name2(T arg1, T arg2) = C1.name1;
}

class C1 implements C {
  C1.name1(T arg1, T arg2);
  noSuchMethod(Invocation invocation) => throw 0;
}

abstract class D2 extends C with T {}
//             ^
// [analyzer] unspecified
// [cfe] unspecified

abstract class D3 implements T {}
//             ^
// [analyzer] unspecified
// [cfe] unspecified

abstract class D4 = C with T;
//             ^
// [analyzer] unspecified
// [cfe] unspecified

main() {
  T.named();
//  ^^^^^
// [analyzer] unspecified
// [cfe] unspecified

  T.staticMethod<T>();
//  ^^^^^^^^^^^^
// [analyzer] unspecified
// [cfe] Method not found: 'Object.staticMethod'.
//  ^^^^^^^^^^^^
// [cfe] A constructor invocation can't have type arguments on the constructor name.
}


import 'package:sky/widgets.dart';
import 'package:test/test.dart';

import 'build_utils.dart';

void main() {
  test('Can select a day', () {
    WidgetTester tester = new WidgetTester();

    DateTime currentValue;

    Widget builder() {
      return new Block([
        new DatePicker(
          selectedDate: new DateTime.utc(2015, 6, 9, 7, 12),
          firstDate: new DateTime.utc(2013),
          lastDate: new DateTime.utc(2018),
          onChanged: (DateTime dateTime) {
            currentValue = dateTime;
          }
        )
      ]);
    }

    tester.pumpFrame(builder);
    // TODO(abarth): We shouldn't need to pump a second frame here.
    tester.pumpFrame(builder);

    expect(currentValue, isNull);
    tester.tap(tester.findText('30'));
    expect(currentValue, equals(new DateTime(2013, 1, 30)));

  });
}

Test year selection for date picker

import 'package:sky/widgets.dart';
import 'package:test/test.dart';

import 'build_utils.dart';

void main() {
  test('Can select a day', () {
    WidgetTester tester = new WidgetTester();

    DateTime currentValue;

    Widget builder() {
      return new Block([
        new DatePicker(
          selectedDate: new DateTime.utc(2015, 6, 9, 7, 12),
          firstDate: new DateTime.utc(2013),
          lastDate: new DateTime.utc(2018),
          onChanged: (DateTime dateTime) {
            currentValue = dateTime;
          }
        )
      ]);
    }

    tester.pumpFrame(builder);
    // TODO(abarth): We shouldn't need to pump a second frame here.
    tester.pumpFrame(builder);

    expect(currentValue, isNull);
    tester.tap(tester.findText('2015'));
    tester.pumpFrame(builder);
    // TODO(jackson): We shouldn't need to pump a second frame here.
    tester.pumpFrame(builder);
    tester.tap(tester.findText('2014'));
    tester.pumpFrame(builder);
    // TODO(jackson): We shouldn't need to pump a second frame here.
    tester.pumpFrame(builder);
    expect(currentValue, equals(new DateTime(2014, 6, 9)));
    tester.tap(tester.findText('30'));
    expect(currentValue, equals(new DateTime(2013, 1, 30)));
  });
}


part of material;

class LambertMaterial implements Material {
  String name;

  Blending blending = const Blending(
      sourceColorFactor: BlendingFactor.sourceAlpha,
      destinationColorFactor: BlendingFactor.oneMinusSourceAlpha);

  DepthTest depthTest = const DepthTest();

  StencilTest stencilTest;

  CullingMode faceCulling;

  Vector3 diffuseColor = new Vector3(0.5, 0.5, 0.5);

  Texture2D diffuseMap;

  Vector3 emissionColor = new Vector3.zero();

  Texture2D emissionMap;

  double opacity = 1.0;

  Texture2D opacityMap;

  Texture2D bumpMap;

  Texture2D normalMap;
}

Drop ambition to add bump (height) mapping

part of material;

class LambertMaterial implements Material {
  String name;

  Blending blending = const Blending(
      sourceColorFactor: BlendingFactor.sourceAlpha,
      destinationColorFactor: BlendingFactor.oneMinusSourceAlpha);

  DepthTest depthTest = const DepthTest();

  StencilTest stencilTest;

  CullingMode faceCulling;

  Vector3 diffuseColor = new Vector3(0.5, 0.5, 0.5);

  Texture2D diffuseMap;

  Vector3 emissionColor = new Vector3.zero();

  Texture2D emissionMap;

  double opacity = 1.0;

  Texture2D opacityMap;

  Texture2D normalMap;
}


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

abstract class Link<T> {
  factory Link.create() = LinkFactory<T>.create;
}

class LinkFactory<T> {
  factory LinkFactory.create() { return null; }
}

main() {
  var a = new Link<int>.create();
}

Remove analyzer warning from test.

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

abstract class Link<T> {
  factory Link.create() = LinkFactory<T>.create;
}

class LinkFactory<T> implements Link<T> {
  factory LinkFactory.create() { return null; }
}

main() {
  var a = new Link<int>.create();
}


library LocationTest;
import '../../pkg/unittest/lib/unittest.dart';
import '../../pkg/unittest/lib/html_config.dart';
import 'dart:html';

main() {
  useHtmlConfiguration();

  var isLocation = predicate((x) => x is Location, 'is a Location');

  test('location hash', () {
      final location = window.location;
      expect(location, isLocation);

      // The only navigation we dare try is hash.
      location.hash = 'hello';
      var h = location.hash;
      expect(h, '#hello');
    });

  test('location.origin', () {
    var origin = window.location.origin;

    // We build up the origin from Uri, then make sure that it matches.
    var uri = new Uri(window.location.href);
    var reconstructedOrigin = '${uri.scheme}://${uri.host}';
    if (uri.port != 0) {
      reconstructedOrigin = '$reconstructedOrigin:${uri.port}';
    }

    expect(origin, reconstructedOrigin);
  });
}

Fix a test after recent uri change.

library LocationTest;
import '../../pkg/unittest/lib/unittest.dart';
import '../../pkg/unittest/lib/html_config.dart';
import 'dart:html';

main() {
  useHtmlConfiguration();

  var isLocation = predicate((x) => x is Location, 'is a Location');

  test('location hash', () {
      final location = window.location;
      expect(location, isLocation);

      // The only navigation we dare try is hash.
      location.hash = 'hello';
      var h = location.hash;
      expect(h, '#hello');
    });

  test('location.origin', () {
    var origin = window.location.origin;

    // We build up the origin from Uri, then make sure that it matches.
    var uri = Uri.parse(window.location.href);
    var reconstructedOrigin = '${uri.scheme}://${uri.host}';
    if (uri.port != 0) {
      reconstructedOrigin = '$reconstructedOrigin:${uri.port}';
    }

    expect(origin, reconstructedOrigin);
  });
}


// 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.
// Dart test program testing overridden messageNotUnderstood.

part of ManyOverriddenNoSuchMethodTest.dart;

class GetName {
  foo(a, b) => "foo";
}

String getName(im) => reflect(new GetName()).delegate(im);

class OverriddenNoSuchMethod {

  OverriddenNoSuchMethod() {}

  noSuchMethod(Invocation mirror) {
    Expect.equals("foo", getName(mirror));
    // 'foo' was called with two parameters (not counting receiver).
    List args = mirror.positionalArguments;
    Expect.equals(2, args.length);
    Expect.equals(101, args[0]);
    Expect.equals(202, args[1]);
    return 5;
  }

  static testMain() {
    var obj = new OverriddenNoSuchMethod();
    Expect.equals(5, obj.foo(101, 202));
  }
}

Fix another part-of related test failure

// 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.
// Dart test program testing overridden messageNotUnderstood.

part of OverriddenNoSuchMethodTest.dart;

class GetName {
  foo(a, b) => "foo";
}

String getName(im) => reflect(new GetName()).delegate(im);

class OverriddenNoSuchMethod {

  OverriddenNoSuchMethod() {}

  noSuchMethod(Invocation mirror) {
    Expect.equals("foo", getName(mirror));
    // 'foo' was called with two parameters (not counting receiver).
    List args = mirror.positionalArguments;
    Expect.equals(2, args.length);
    Expect.equals(101, args[0]);
    Expect.equals(202, args[1]);
    return 5;
  }

  static testMain() {
    var obj = new OverriddenNoSuchMethod();
    Expect.equals(5, obj.foo(101, 202));
  }
}


// To parse this JSON data, do
//
//     final studentIdBarcodeModel = studentIdBarcodeModelFromJson(jsonString);

import 'dart:convert';

StudentIdBarcodeModel studentIdBarcodeModelFromJson(String str) =>
    StudentIdBarcodeModel.fromJson(json.decode(str));

String studentIdBarcodeModelToJson(StudentIdBarcodeModel data) =>
    json.encode(data.toJson());

class StudentIdBarcodeModel {
  String studentId;
  int barCode;

  StudentIdBarcodeModel({
    this.studentId,
    this.barCode,
  });

  factory StudentIdBarcodeModel.fromJson(Map<String, dynamic> json) =>
      StudentIdBarcodeModel(
        studentId: json["studentId"],
        barCode: json["barCode"] == 0 ? null : json["barCode"],
      );

  Map<String, dynamic> toJson() => {
        "studentId": studentId,
        "barCode": barCode,
      };
}

Initialize barcode model barCode data type as int to resolve null exceptions

// To parse this JSON data, do
//
//     final studentIdBarcodeModel = studentIdBarcodeModelFromJson(jsonString);

import 'dart:convert';

StudentIdBarcodeModel studentIdBarcodeModelFromJson(String str) =>
    StudentIdBarcodeModel.fromJson(json.decode(str));

String studentIdBarcodeModelToJson(StudentIdBarcodeModel data) =>
    json.encode(data.toJson());

class StudentIdBarcodeModel {
  String studentId;
  int barCode;

  StudentIdBarcodeModel({
    this.studentId,
    this.barCode,
  });

  factory StudentIdBarcodeModel.fromJson(Map<String, dynamic> json) =>
      StudentIdBarcodeModel(
        studentId: json["studentId"],
        barCode: json["barCode"] == null ? 0 : json["barCode"],
      );

  Map<String, dynamic> toJson() => {
        "studentId": studentId,
        "barCode": barCode == null ? 0 : barCode,
      };
}


library oauth1;

export 'src/utils.dart';
export 'src/client_credentials.dart';
export 'src/credentials.dart';
export 'src/signature_method.dart';
export 'src/client.dart';
export 'src/authorization.dart';
export 'src/platform.dart';

Remove utils.dart export from library

library oauth1;

export 'src/client_credentials.dart';
export 'src/credentials.dart';
export 'src/signature_method.dart';
export 'src/client.dart';
export 'src/authorization.dart';
export 'src/platform.dart';


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

// TODO(google): Remove this once use of '#' in a template is either
// consistent, or has a way to declare specifically what you want - e.g. the
// component instance or the element ref. Today, using # on an HTML element will
// be an elementRef, but # on a component will be a component instance.

/// Place on an element or component to expose the [ElementRef] as 'ref'.
///
/// Example usage:
///     <material-button ref #button="ref"></materialButton>
///     <!-- You can now use 'button' in this template as a property -->
@Directive(
  selector: '[ref]', exportAs: 'ref',
  // TODO(google): Change to `Visibility.local` to reduce code size.
  visibility: Visibility.all,
)
class ReferenceDirective {
  final ElementRef elementRef;

  ReferenceDirective(this.elementRef);
}

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

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

// TODO(google): Remove this once use of '#' in a template is either
// consistent, or has a way to declare specifically what you want - e.g. the
// component instance or the element ref. Today, using # on an HTML element will
// be an elementRef, but # on a component will be a component instance.

/// Place on an element or component to expose the [ElementRef] as 'ref'.
///
/// Example usage:
///     <material-button ref #button="ref"></materialButton>
///     <!-- You can now use 'button' in this template as a property -->
@Directive(
  selector: '[ref]',
  exportAs: 'ref',
)
class ReferenceDirective {
  final ElementRef elementRef;

  ReferenceDirective(this.elementRef);
}


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

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

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

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.all(2),
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: <Widget>[
          FaIcon(
            FontAwesomeIcons.trash,
            size: 20,
            color: TautulliColorPalette.not_white,
          ),
          SizedBox(height: 4),
          Text(
            'Delete',
            textAlign: TextAlign.center,
            style: TextStyle(
              fontSize: 17,
              fontWeight: FontWeight.w400,
            ),
          ),
        ],
      ),
    );
  }
}

Use the same trash icon as server settings page.

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

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

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

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.all(2),
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: <Widget>[
          FaIcon(
            FontAwesomeIcons.trashAlt,
            size: 20,
            color: TautulliColorPalette.not_white,
          ),
          SizedBox(height: 4),
          Text(
            'Delete',
            textAlign: TextAlign.center,
            style: TextStyle(
              fontSize: 17,
              fontWeight: FontWeight.w400,
            ),
          ),
        ],
      ),
    );
  }
}


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

import "package:expect/expect.dart";
import "../language/compiler_annotations.dart";

@DontInline()
returnStringOrNull() {
  () => 42;
  return new DateTime.now().millisecondsSinceEpoch == 0 ? 'foo' : null;
}

main() {
  Expect.throws(() => 'foo' + returnStringOrNull(),
                (e) => e is ArgumentError);
  Expect.throws(() => 'foo'.split(returnStringOrNull()),
                (e) => e is ArgumentError || e is NoSuchMethodError);
}

Fix test to not reach out of current dir

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

import "package:expect/expect.dart";

@NoInline()
@AssumeDynamic()
returnStringOrNull() {
  return new DateTime.now().millisecondsSinceEpoch == 0 ? 'foo' : null;
}

main() {
  Expect.throws(() => 'foo' + returnStringOrNull(),
                (e) => e is ArgumentError);
  Expect.throws(() => 'foo'.split(returnStringOrNull()),
                (e) => e is ArgumentError || e is NoSuchMethodError);
}


part of streamy.runtime;

/// A [StreamTransformer] that de-duplicates entities. This will cause
/// metadata about the entity (Entity.streamy) to be inaccurate, but will
/// prevent multiple values from being published on [Stream]s when core [Entity]
/// data has not changed.
class EntityDedupTransformer extends StreamEventTransformer<Entity, Entity> {
  var _last = null;

  handleData(Entity data, EventSink<Entity> sink) {
    if (data != _last) {
      sink.add(data);
    }
    _last = data;
  }
}

/// A [StreamTransformer] that closes the stream after the RPC reply is
/// received.
class OneShotRequestTransformer implements StreamTransformer<Entity, Entity> {

  Stream<Entity> bind(Stream<Entity> input) {
    var output = new StreamController<Entity>();
    var sub;
    sub = input.listen((e) {
      output.add(e);
      if (e.streamy.source == 'RPC') {
        sub.cancel();
        output.close();
      }
    });
    sub
      ..onError(output.addError)
      ..onDone(output.close);
    return output.stream;
  }
}

abstract class RequestStreamTransformer {
  Stream bind(Request request, Stream stream);
}

class TransformingRequestHandler extends RequestHandler {
  final RequestHandler delegate;
  final RequestStreamTransformer transformer;

  TransformingRequestHandler(this.delegate, this.transformer);

  Stream handle(Request request) =>
      transformer.bind(request, delegate.handle(request));
}

Make transformer type parameters more concrete to let users control types.

part of streamy.runtime;

/// A [StreamTransformer] that de-duplicates entities. This will cause
/// metadata about the entity (Entity.streamy) to be inaccurate, but will
/// prevent multiple values from being published on [Stream]s when core [Entity]
/// data has not changed.
class EntityDedupTransformer<T extends Entity>
    extends StreamEventTransformer<T, T> {
  var _last = null;

  handleData(T data, EventSink<T> sink) {
    if (data != _last) {
      sink.add(data);
    }
    _last = data;
  }
}

/// A [StreamTransformer] that closes the stream after the RPC reply is
/// received.
class OneShotRequestTransformer<T extends Entity>
    implements StreamTransformer<T, T> {

  Stream<T> bind(Stream<T> input) {
    var output = new StreamController<T>();
    var sub;
    sub = input.listen((e) {
      output.add(e);
      if (e.streamy.source == 'RPC') {
        sub.cancel();
        output.close();
      }
    });
    sub
      ..onError(output.addError)
      ..onDone(output.close);
    return output.stream;
  }
}

abstract class RequestStreamTransformer {
  Stream bind(Request request, Stream stream);
}

class TransformingRequestHandler extends RequestHandler {
  final RequestHandler delegate;
  final RequestStreamTransformer transformer;

  TransformingRequestHandler(this.delegate, this.transformer);

  Stream handle(Request request) =>
      transformer.bind(request, delegate.handle(request));
}


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

library test.integration.analysis.error;

import 'package:analysis_server/src/protocol.dart';
import 'package:unittest/unittest.dart';

import '../../reflective_tests.dart';
import '../integration_tests.dart';

@ReflectiveTestCase()
class AnalysisErrorIntegrationTest extends AbstractAnalysisServerIntegrationTest
    {
  test_detect_simple_error() {
    String pathname = sourcePath('test.dart');
    writeFile(pathname,
        '''
main() {
  var x // parse error: missing ';'
}''');
    standardAnalysisSetup();
    return analysisFinished.then((_) {
      expect(currentAnalysisErrors[pathname], isList);
      List<AnalysisError> errors = currentAnalysisErrors[pathname];
      expect(errors, hasLength(1));
      expect(errors[0].location.file, equals(pathname));
    });
  }
}

main() {
  runReflectiveTests(AnalysisErrorIntegrationTest);
}

Fix integration test to avoid new 'Unused local variable' hint.

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

library test.integration.analysis.error;

import 'package:analysis_server/src/protocol.dart';
import 'package:unittest/unittest.dart';

import '../../reflective_tests.dart';
import '../integration_tests.dart';

@ReflectiveTestCase()
class AnalysisErrorIntegrationTest extends AbstractAnalysisServerIntegrationTest
    {
  test_detect_simple_error() {
    String pathname = sourcePath('test.dart');
    writeFile(pathname,
        '''
main() {
  print(null) // parse error: missing ';'
}''');
    standardAnalysisSetup();
    return analysisFinished.then((_) {
      expect(currentAnalysisErrors[pathname], isList);
      List<AnalysisError> errors = currentAnalysisErrors[pathname];
      expect(errors, hasLength(1));
      expect(errors[0].location.file, equals(pathname));
    });
  }
}

main() {
  runReflectiveTests(AnalysisErrorIntegrationTest);
}


// 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.
// Test that dart2js gvns dynamic getters that don't have side
// effects.

import 'compiler_helper.dart';
import 'parser_helper.dart';

const String TEST = r"""
class A {
  var foo;
  bar(a) {
    return a.foo + a.foo;
  }
}

main() {
  new A().bar(new Object());
}
""";

main() {
  Uri uri = new Uri.fromComponents(scheme: 'source');
  var compiler = compilerFor(TEST, uri);
  compiler.runCompiler(uri);
  String generated = compiler.assembledCode;
  RegExp regexp = new RegExp(r"get\$foo");
  Iterator matches = regexp.allMatches(generated).iterator;
  checkNumberOfMatches(matches, 1);
  var cls = findElement(compiler, 'A');
  Expect.isNotNull(cls);
  var element = cls.lookupLocalMember(buildSourceString('foo'));
  Expect.isNotNull(element);
  Expect.isFalse(compiler.world.userDefinedGetters.contains(element));
}

Fix build by updating test to use different check for user-defined getters.

// 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.
// Test that dart2js gvns dynamic getters that don't have side
// effects.

import 'compiler_helper.dart';
import 'parser_helper.dart';

const String TEST = r"""
class A {
  var foo;
  bar(a) {
    return a.foo + a.foo;
  }
}

main() {
  new A().bar(new Object());
}
""";

main() {
  Uri uri = new Uri.fromComponents(scheme: 'source');
  var compiler = compilerFor(TEST, uri);
  compiler.runCompiler(uri);
  String generated = compiler.assembledCode;
  RegExp regexp = new RegExp(r"get\$foo");
  Iterator matches = regexp.allMatches(generated).iterator;
  checkNumberOfMatches(matches, 1);
  var cls = findElement(compiler, 'A');
  Expect.isNotNull(cls);
  SourceString name = buildSourceString('foo');
  var element = cls.lookupLocalMember(name);
  Expect.isNotNull(element);
  Selector selector = new Selector.getter(name, null);
  Expect.isFalse(compiler.world.hasAnyUserDefinedGetter(selector));
}


import 'package:pay_platform_interface/core/payment_item.dart';

abstract class PayPlatform {
  /**
   * TBA
   */
  Future<bool> userCanPay(Map<String, dynamic> paymentProfile);

  /**
   * TBA
   */
  Future<Map<String, dynamic>> showPaymentSelector(
      Map<String, dynamic> paymentProfile, List<PaymentItem> paymentItems);
}

Add docu to the platform interface

import 'package:pay_platform_interface/core/payment_item.dart';

abstract class PayPlatform {
  /// Determines whether the caller can make a payment with a given
  /// configuration.
  ///
  /// Returns a [Future] that resolves to a boolean value with the result.
  Future<bool> userCanPay(Map<String, dynamic> paymentProfile);

  /// Triggers the action to show the payment selector to complete a payment
  /// with the configuration and a list of [PaymentItem] to determine the price
  /// elements to show in the payment selector.
  ///
  /// Returns a [Future] with the result of the selection.
  Future<Map<String, dynamic>> showPaymentSelector(
      Map<String, dynamic> paymentProfile, List<PaymentItem> paymentItems);
}


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

library native_types;

import 'test_base.dart';

abstract class C {}

class D {}

var foo = bar;
var bar = foo;

main() {
  expectTrue(1 is int);
  expectTrue(1 is! double);

  expectTrue(new List<int>() is List<int>);
  expectTrue(new List<int>() is! List<double>);
  expectTrue("hest" is String);
  expectTrue("hest" is! int);

  expectTrue(null is! String);
  expectTrue(null is dynamic);
  expectTrue(null is Object);

  expectTrue(true is bool);
  expectTrue(true is! int);

  // Test error and exception classes
  expectThrows(() => new C(), (e) => e is AbstractClassInstantiationError);

  expectThrows(() => new D().foo(), (e) => e is NoSuchMethodError);

  expectThrows(() => foo, (e) => e is CyclicInitializationError);

  expectThrows(() => [][1], (e) => e is RangeError);

  expectTrue(new UnsupportedError("") is UnsupportedError);

  expectTrue(new ArgumentError() is ArgumentError);

  expectTrue(
      new IntegerDivisionByZeroException() is IntegerDivisionByZeroException);
}

Add multitest markers to reify test

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

library native_types;

import 'test_base.dart';

abstract class C {}

class D {}

var foo = bar;
var bar = foo;

main() {
  expectTrue(1 is int);
  expectTrue(1 is! double);

  expectTrue(new List<int>() is List<int>);
  expectTrue(new List<int>() is! List<double>);
  expectTrue("hest" is String);
  expectTrue("hest" is! int);

  expectTrue(null is! String);
  expectTrue(null is dynamic);
  expectTrue(null is Object);

  expectTrue(true is bool);
  expectTrue(true is! int);

  // Test error and exception classes
  expectThrows(() => new C(), (e) => e is AbstractClassInstantiationError);  /// 01: static type warning

  expectThrows(() => new D().foo(), (e) => e is NoSuchMethodError);  /// 02: static type warning

  expectThrows(() => foo, (e) => e is CyclicInitializationError);

  expectThrows(() => [][1], (e) => e is RangeError);

  expectTrue(new UnsupportedError("") is UnsupportedError);

  expectTrue(new ArgumentError() is ArgumentError);

  expectTrue(
      new IntegerDivisionByZeroException() is IntegerDivisionByZeroException);
}


part of mac.utils;

Future<String> fetch(String url) async {
  var uri = Uri.parse(url);
  var client = new HttpClient();
  var request = await client.getUrl(uri);
  var response = await request.close();
  if (response.statusCode != 200) {
    throw new Exception("Failed to fetch ${url}");
  }
  return response.transform(UTF8.decoder).join().then((out) {
    client.close();
    return out;
  });
}

Future<dynamic> fetchJSON(String url) async {
  var text = await fetch(url);
  var json = JSON.decode(text);
  return json;
}

Prepare for Uint8List SDK breaking change

part of mac.utils;

Future<String> fetch(String url) async {
  var uri = Uri.parse(url);
  var client = new HttpClient();
  var request = await client.getUrl(uri);
  var response = await request.close();
  if (response.statusCode != 200) {
    throw new Exception("Failed to fetch ${url}");
  }
  return UTF8.decoder.bind(response).join().then((out) {
    client.close();
    return out;
  });
}

Future<dynamic> fetchJSON(String url) async {
  var text = await fetch(url);
  var json = JSON.decode(text);
  return json;
}


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

/// The colorful library.
library colorful;

class Color {
  int _r;
  int _g;
  int _b;

  Color(this._r, this._g, this._b);

  get r => _r;
  get g => _g;
  get b => _b;

  bool isValid() {
    return 0 <= this._r && this._r <= 255 &&
           0 <= this._g && this._g <= 255 &&
           0 <= this._b && this._b <= 255;
  }
}

Use double for RGB color.

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

/// The colorful library.
library colorful;

class Color {
  double _r;
  double _g;
  double _b;

  Color(this._r, this._g, this._b);

  get r => _r;
  get g => _g;
  get b => _b;

  bool isValid() {
    return 0.0 <= this._r && this._r <= 1.0 &&
           0.0 <= this._g && this._g <= 1.0 &&
           0.0 <= this._b && this._b <= 1.0;
  }

}


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

const String APP_ID = "2982LV-6WP5YYAWLQ";

@Command("w", description: "Wolfram Alpha", prefix: "Wolfram")
w(String input) => wolfram(input);

@Command("wolfram", description: "Wolfram Alpha", prefix: "Wolfram")
wolfram(String input) async {
  var url = "http://api.wolframalpha.com/v2/query?output=json&input=${Uri.encodeComponent(input)}&appid=${APP_ID}";
  var json = await fetchJSON(url);
  var result = json.queryresult;
  try {
    if (result.pods == null) {
      var dym = result.didyoumeans;
      if (dym != null && dym.isNotEmpty) {
        var word = dym[0].val;
        return "Did you mean ${word}?";
      } else {
        return "No Result Found.";
      }
    }

    var pods = new SimpleMap({});

    for (var pod in result.pods) {
      pods[pod.title] = pod;
    }

    var plainPods = [
      "Result",
      "Decimal approximation",
      "Response",
      "Definitions",
      "Definition"
    ];

    for (var p in plainPods) {
      if (pods.containsKey(p)) {
        return pods[p].subpods[0].plaintext;
      }
    }
  } catch (e) {
    return "Failed to get output.";
  }

  return "Pod is not yet supported.";
}

Add Support for Chemical Names and Formulas

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

const String APP_ID = "2982LV-6WP5YYAWLQ";

@Command("w", description: "Wolfram Alpha", prefix: "Wolfram")
w(String input) => wolfram(input);

@Command("wolfram", description: "Wolfram Alpha", prefix: "Wolfram")
wolfram(String input) async {
  var url = "http://api.wolframalpha.com/v2/query?output=json&input=${Uri.encodeComponent(input)}&appid=${APP_ID}";
  var json = await fetchJSON(url);
  var result = json.queryresult;
  try {
    if (result.pods == null) {
      var dym = result.didyoumeans;
      if (dym != null && dym.isNotEmpty) {
        var word = dym[0].val;
        return "Did you mean ${word}?";
      } else {
        return "No Result Found.";
      }
    }

    var pods = new SimpleMap({});

    for (var pod in result.pods) {
      pods[pod.title] = pod;
    }

    var plainPods = [
      "Result",
      "Decimal approximation",
      "Response",
      "Definitions",
      "Definition",
      "Chemical names and formulas"
    ];

    for (var p in plainPods) {
      if (pods.containsKey(p)) {
        return pods[p].subpods[0].plaintext;
      }
    }
  } catch (e) {
    return "Failed to get output.";
  }

  return "Pod is not yet supported.";
}


import '../lib/import_table.dart';

main() {
  List<String> paths = new List<String>();
  paths.add("file://");
  paths.add("file:///a");
  paths.add("file:///a/b");
  paths.add("file:///a/b/c");

  int end = paths.length;
  for (int i = 0; i < end; i++) {
    paths.add(paths[i] + "/d.dart");
    paths.add(paths[i] + "/e.dart");
    paths.add(paths[i] + "/");
  }
  paths[0] = "file:///";
  paths.sort();
  for (int i = 0; i < paths.length; i++) {
    for (int j = 0; j < paths.length; j++) {
      check(paths[i], paths[j]);
    }
  }
  check("", "");
}

void check(String target, String ref) {
  Uri uriTarget = Uri.parse(target);
  Uri uriRef = Uri.parse(ref);
  String relative = relativeUriPath(uriTarget, uriRef);
  if (Uri.base.resolveUri(uriTarget) !=
      Uri.base.resolveUri(uriRef).resolve(relative)) {
    throw "Failure on '$target' and '$ref': Got '$relative' which resolves to "
        "${uriRef.resolve(relative)}";
  }
}

Fix relative import from pkg/kernel/test to pkg/kernel/lib.

import 'package:kernel/import_table.dart';

main() {
  List<String> paths = new List<String>();
  paths.add("file://");
  paths.add("file:///a");
  paths.add("file:///a/b");
  paths.add("file:///a/b/c");

  int end = paths.length;
  for (int i = 0; i < end; i++) {
    paths.add(paths[i] + "/d.dart");
    paths.add(paths[i] + "/e.dart");
    paths.add(paths[i] + "/");
  }
  paths[0] = "file:///";
  paths.sort();
  for (int i = 0; i < paths.length; i++) {
    for (int j = 0; j < paths.length; j++) {
      check(paths[i], paths[j]);
    }
  }
  check("", "");
}

void check(String target, String ref) {
  Uri uriTarget = Uri.parse(target);
  Uri uriRef = Uri.parse(ref);
  String relative = relativeUriPath(uriTarget, uriRef);
  if (Uri.base.resolveUri(uriTarget) !=
      Uri.base.resolveUri(uriRef).resolve(relative)) {
    throw "Failure on '$target' and '$ref': Got '$relative' which resolves to "
        "${uriRef.resolve(relative)}";
  }
}


import 'dart:html';

import 'package:angular/angular.dart';
import 'package:angular_forms/angular_forms.dart';
import 'package:angular_router/angular_router.dart';
import 'package:gitpods/src/user/user.dart';
import 'package:gitpods/src/user/user_service.dart';

@Component(
  selector: 'profile',
  templateUrl: 'profile_component.html',
  directives: const [COMMON_DIRECTIVES, formDirectives],
)
class ProfileComponent implements OnInit {
  final Router _router;
  final UserService _userService;

  ProfileComponent(this._router, this._userService);

  bool loading;
  User user;

  @override
  void ngOnInit() {
    this._userService.me().then((user) => this.user = user);
  }

  void submit(Event e) {
    e.preventDefault();
    loading = true;

    this._userService.update(user).then((user) {
      loading = false;
      this._router.navigate(['/UserProfile',{'username': user.username}]);
    });
  }
}

Add LoadingComponent as directive to profile setting component

import 'dart:html';

import 'package:angular/angular.dart';
import 'package:angular_forms/angular_forms.dart';
import 'package:angular_router/angular_router.dart';
import 'package:gitpods/src/loading_component.dart';
import 'package:gitpods/src/user/user.dart';
import 'package:gitpods/src/user/user_service.dart';

@Component(
  selector: 'profile',
  templateUrl: 'profile_component.html',
  directives: const [
    COMMON_DIRECTIVES,
    formDirectives,
    LoadingComponent,
  ],
)
class ProfileComponent implements OnInit {
  final Router _router;
  final UserService _userService;

  ProfileComponent(this._router, this._userService);

  bool loading;
  User user;

  @override
  void ngOnInit() {
    this._userService.me().then((user) => this.user = user);
  }

  void submit(Event e) {
    e.preventDefault();
    loading = true;

    this._userService.update(user).then((user) {
      loading = false;
      this._router.navigate(['/UserProfile',{'username': user.username}]);
    });
  }
}


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

/**
 * Simple code with broad use cases.
 */
library quiver.core;

part 'src/core/hash.dart';
part 'src/core/optional.dart';

/**
 * Returns the first non-null argument. If all arguments are null, throws
 * an [ArgumentError].
 *
 * Note: if [o1] is an [Optional], this can be accomplished with `o1.or(o2)`.
 */
Object firstNonNull(o1, o2, [o3, o4]) {
  if (o1 != null) return o1;
  if (o2 != null) return o2;
  if (o3 != null) return o3;
  if (o4 != null) return o4;
  throw new ArgumentError('All arguments were null');
}

Change return type of firstNonNull to dynamic

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

/**
 * Simple code with broad use cases.
 */
library quiver.core;

part 'src/core/hash.dart';
part 'src/core/optional.dart';

/**
 * Returns the first non-null argument. If all arguments are null, throws
 * an [ArgumentError].
 *
 * Note: if [o1] is an [Optional], this can be accomplished with `o1.or(o2)`.
 */
firstNonNull(o1, o2, [o3, o4]) {
  if (o1 != null) return o1;
  if (o2 != null) return o2;
  if (o3 != null) return o3;
  if (o4 != null) return o4;
  throw new ArgumentError('All arguments were null');
}


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

/// Simple command line interface to launching browsers.
/// Uses the browser_controller framework.
/// The usage is:
///   DARTBIN launch_browser.dart BROWSER_NAME URL
/// DARTBIN should be the checked in stable binary.

import 'package:test_runner/src/browser_controller.dart';
import 'package:test_runner/src/configuration.dart';

void printHelp() {
  print("Usage pattern:");
  print("launch_browser.dart browser url");
  print("Supported browsers: ${Browser.supportedBrowsers}");
}

void main(List<String> arguments) {
  if (arguments.length != 2) {
    print("Wrong number of arguments, please pass in exactly two arguments");
    printHelp();
    return;
  }
  var name = arguments[0];

  if (!Browser.supportedBrowser(name)) {
    print("Specified browser not supported");
    printHelp();
    return;
  }

  var runtime = Runtime.find(name);
  var configuration = TestConfiguration(
      configuration: Configuration(
          "dummy configuration", null, null, null, runtime, null));
  var executable = configuration.browserLocation;
  var browser = Browser.byRuntime(runtime, executable);
  browser.start(arguments[1]);
}

Replace space from test config name

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

/// Simple command line interface to launching browsers.
/// Uses the browser_controller framework.
/// The usage is:
///   DARTBIN launch_browser.dart BROWSER_NAME URL
/// DARTBIN should be the checked in stable binary.

import 'package:test_runner/src/browser_controller.dart';
import 'package:test_runner/src/configuration.dart';

void printHelp() {
  print("Usage pattern:");
  print("launch_browser.dart browser url");
  print("Supported browsers: ${Browser.supportedBrowsers}");
}

void main(List<String> arguments) {
  if (arguments.length != 2) {
    print("Wrong number of arguments, please pass in exactly two arguments");
    printHelp();
    return;
  }
  var name = arguments[0];

  if (!Browser.supportedBrowser(name)) {
    print("Specified browser not supported");
    printHelp();
    return;
  }

  var runtime = Runtime.find(name);
  var configuration = TestConfiguration(
      configuration: Configuration(
          "dummy-configuration", null, null, null, runtime, null));
  var executable = configuration.browserLocation;
  var browser = Browser.byRuntime(runtime, executable);
  browser.start(arguments[1]);
}


import 'package:flutter/widgets.dart';

void main() {
  runApp(new Center(child: new Text('Hello, world!')));
}

class MySampleHome extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new Container();
  }
}

Add missing text direction for running flutter tests

import 'package:flutter/widgets.dart';

void main() {
  runApp(new Center(
      child: new Text(
    'Hello, world!',
    textDirection: TextDirection.ltr,
  )));
}

class MySampleHome extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new Container();
  }
}


part of ChattyWorker;

_workerStarter(message) {
  message[0].startWorking(message[1]);
}

abstract class Boss {

  ReceivePort response;
  SendPort request;

  Boss() {
    response = new ReceivePort();
    response.listen((message) {
      if (message is SendPort) {
        request = message;
        speak(Status.READY);
      } else {
        manage(message);
      }
    });
  }

  void doYourJob(Worker worker) {
    Isolate.spawn(_workerStarter, [worker, response.sendPort]);
  }

  void manage(message);

  void speak(message) {
    request.send(message);
  }

  void byebye() {
    response.close();
  }

}

Revert "rename manager to workerStarter"

part of ChattyWorker;

_manager(message) {
  message[0].startWorking(message[1]);
}

abstract class Boss {

  ReceivePort response;
  SendPort request;

  Boss() {
    response = new ReceivePort();
    response.listen((message) {
      if (message is SendPort) {
        request = message;
        speak(Status.READY);
      } else {
        manage(message);
      }
    });
  }

  void doYourJob(Worker worker) {
    Isolate.spawn(_manager, [worker, response.sendPort]);
  }

  void manage(message);

  void speak(message) {
    request.send(message);
  }

  void byebye() {
    response.close();
  }

}


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

library dart2js.serialization.compilation1_test;

import 'compilation_test_helper.dart' as test;
import 'test_data.dart';

main() {
  test.main(['0', '0']);
}

Rename library name in test.

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

library dart2js.serialization.compilation0_test;

import 'compilation_test_helper.dart' as test;
import 'test_data.dart';

main() {
  test.main(['0', '0']);
}


import 'package:moor_generator/src/analyzer/errors.dart';
import 'package:test/test.dart';

import '../utils.dart';

void main() {
  group("reports error when an import can't be found", () {
    test('in moor file', () async {
      final state = TestState.withContent({
        'foo|lib/a.moor': '''
import 'b.moor';
        ''',
      });

      final result = await state.analyze('package:foo/a.moor');

      expect(
        result.errors.errors,
        contains(const TypeMatcher<ErrorInMoorFile>().having(
          (e) => e.message,
          'message',
          allOf(contains('b.moor'), contains('file does not exist')),
        )),
      );
    });

    test('in a dart file', () async {
      final state = TestState.withContent({
        'foo|lib/a.dart': '''
import 'package:moor/moor.dart';

@UseMoor(include: {'b.moor'})
class Database {

}
            ''',
      });

      final result = await state.analyze('package:foo/a.dart');

      expect(
        result.errors.errors,
        contains(const TypeMatcher<ErrorInDartCode>().having(
          (e) => e.message,
          'message',
          allOf(contains('b.moor'), contains('file does not exist')),
        )),
      );
    });
  });
}

Add another missing analyzer tag to test

import 'package:moor_generator/src/analyzer/errors.dart';
import 'package:test/test.dart';

import '../utils.dart';

void main() {
  group("reports error when an import can't be found", () {
    test('in moor file', () async {
      final state = TestState.withContent({
        'foo|lib/a.moor': '''
import 'b.moor';
        ''',
      });

      final result = await state.analyze('package:foo/a.moor');

      expect(
        result.errors.errors,
        contains(const TypeMatcher<ErrorInMoorFile>().having(
          (e) => e.message,
          'message',
          allOf(contains('b.moor'), contains('file does not exist')),
        )),
      );
    });

    test('in a dart file', () async {
      final state = TestState.withContent({
        'foo|lib/a.dart': '''
import 'package:moor/moor.dart';

@UseMoor(include: {'b.moor'})
class Database {

}
            ''',
      });

      final result = await state.analyze('package:foo/a.dart');

      expect(
        result.errors.errors,
        contains(const TypeMatcher<ErrorInDartCode>().having(
          (e) => e.message,
          'message',
          allOf(contains('b.moor'), contains('file does not exist')),
        )),
      );
    }, tags: 'analyzer');
  });
}


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

library barback.transform_logger;

import 'package:source_maps/span.dart';

/// Object used to report warnings and errors encountered while running a
/// transformer.
class TransformLogger {

  bool _shouldPrint;

  TransformLogger(this._shouldPrint);

  /// Logs an informative message.
  ///
  /// If present, [span] indicates the location in the input asset that caused
  /// the message.
  void info(String message, [Span span]) {
    _printMessage('info', message, span);
  }

  /// Logs a warning message.
  ///
  /// If present, [span] indicates the location in the input asset that caused
  /// the warning.
  void warning(String message, [Span span]) {
    _printMessage('warning', message, span);
  }

  /// Logs an error message.
  ///
  /// If present, [span] indicates the location in the input asset that caused
  /// the error.
  // TODO(sigmund,nweiz): clarify when an error should be logged or thrown.
  void error(String message, [Span span]) {
    _printMessage('error', message, span);
  }

  // TODO(sigmund,rnystrom): do something better than printing.
  _printMessage(String prefix, String message, Span span) {
    if (!_shouldPrint) return;
    print(span == null ? '$prefix $message'
        : '$prefix ${span.getLocationMessage(message)}');
  }
}

Use our own DiagnosticHandler for dart2js.

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

library barback.transform_logger;

import 'package:source_maps/span.dart';

/// Object used to report warnings and errors encountered while running a
/// transformer.
class TransformLogger {

  bool _shouldPrint;

  TransformLogger(this._shouldPrint);

  /// Logs an informative message.
  ///
  /// If present, [span] indicates the location in the input asset that caused
  /// the message.
  void info(String message, [Span span]) {
    _printMessage('info', message, span);
  }

  /// Logs a warning message.
  ///
  /// If present, [span] indicates the location in the input asset that caused
  /// the warning.
  void warning(String message, [Span span]) {
    _printMessage('warning', message, span);
  }

  /// Logs an error message.
  ///
  /// If present, [span] indicates the location in the input asset that caused
  /// the error.
  // TODO(sigmund,nweiz): clarify when an error should be logged or thrown.
  void error(String message, [Span span]) {
    _printMessage('error', message, span);
  }

  // TODO(sigmund,rnystrom): do something better than printing.
  _printMessage(String prefix, String message, Span span) {
    if (!_shouldPrint) return;
    print(span == null ? '$prefix: $message'
        : '$prefix ${span.getLocationMessage(message)}');
  }
}


import 'package:args/args.dart';
import 'package:build/build.dart';
import 'package:source_gen/source_gen.dart';
import 'package:angular/source_gen.dart';
import 'package:angular_compiler/angular_compiler.dart';

const String TEMPLATE_EXTENSION_PARAM = 'template_extension';
const String CODEGEN_MODE_PARAM = 'codegen_mode';

Builder templateBuilder(BuilderOptions options) {
  final compilerFlags = new CompilerFlags(
    genDebugInfo: options.config[CODEGEN_MODE_PARAM] == 'debug',
  );
  if (options.config[CODEGEN_MODE_PARAM] == 'outline') {
    return new TemplateOutliner(compilerFlags,
        extension: options.config[TEMPLATE_EXTENSION_PARAM]);
  }
  return new LibraryBuilder(new TemplateGenerator(compilerFlags),
      generatedExtension: options.config[TEMPLATE_EXTENSION_PARAM]);
}

Builder templatePlaceholderBuilder(_) => const TemplatePlaceholderBuilder();

final _argParser = new ArgParser()
  ..addOption(CODEGEN_MODE_PARAM,
      help: 'What mode to run the code generator in. Either release or debug.')
  ..addOption(TEMPLATE_EXTENSION_PARAM,
      help: 'Generated template extension.', defaultsTo: '.template.dart');

Remove unused local var _argParser.


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

import "dart:io";

test(int milliseconds) {
  var watch = new Stopwatch();
  watch.start();
  sleep(new Duration(milliseconds: milliseconds));
  watch.stop();
  Expect.isTrue(watch.elapsedMilliseconds >= milliseconds);
}

main() {
  test(1);
  test(10);
  test(100);
}

Make sleep test resilient to timer rounding issues

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

import "dart:io";

test(int milliseconds) {
  var watch = new Stopwatch();
  watch.start();
  sleep(new Duration(milliseconds: milliseconds));
  watch.stop();
  Expect.isTrue(watch.elapsedMilliseconds + 1 >= milliseconds);
}

main() {
  test(1);
  test(10);
  test(100);
}


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

library kernel.transformations.setup_builtin_library;

import '../ast.dart';

// The DartVM has a special `dart:_builtin` library which exposes a
// `_getMainClosure()` method.  We need to change this method to return a
// closure of `main()`.
Program transformProgram(Program program,
    {String libraryUri: 'dart:_builtin'}) {
  Procedure mainMethod = program.mainMethod;

  Library builtinLibrary;
  for (Library library in program.libraries) {
    if (library.importUri.toString() == libraryUri) {
      builtinLibrary = library;
      break;
    }
  }

  if (builtinLibrary == null) {
    throw new Exception('Could not find "dart:_builtin" library');
  }

  FunctionNode getMainClosure;
  for (Procedure procedure in builtinLibrary.procedures) {
    if (procedure.name.name == '_getMainClosure') {
      getMainClosure = procedure.function;
      break;
    }
  }

  if (getMainClosure == null) {
    throw new Exception('Could not find "_getMainClosure" in "$libraryUri"');
  }

  var returnMainStatement = new ReturnStatement(new StaticGet(mainMethod));
  getMainClosure.body = returnMainStatement;
  returnMainStatement.parent = getMainClosure;

  return program;
}

Allow main to be null for modular tranformation.

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

library kernel.transformations.setup_builtin_library;

import '../ast.dart';

// The DartVM has a special `dart:_builtin` library which exposes a
// `_getMainClosure()` method.  We need to change this method to return a
// closure of `main()`.
Program transformProgram(Program program,
    {String libraryUri: 'dart:_builtin'}) {
  Procedure mainMethod = program.mainMethod;

  if (mainMethod == null) return program;

  Library builtinLibrary;
  for (Library library in program.libraries) {
    if (library.importUri.toString() == libraryUri) {
      builtinLibrary = library;
      break;
    }
  }

  if (builtinLibrary == null) {
    throw new Exception('Could not find "dart:_builtin" library');
  }

  FunctionNode getMainClosure;
  for (Procedure procedure in builtinLibrary.procedures) {
    if (procedure.name.name == '_getMainClosure') {
      getMainClosure = procedure.function;
      break;
    }
  }

  if (getMainClosure == null) {
    throw new Exception('Could not find "_getMainClosure" in "$libraryUri"');
  }

  var returnMainStatement = new ReturnStatement(new StaticGet(mainMethod));
  getMainClosure.body = returnMainStatement;
  returnMainStatement.parent = getMainClosure;

  return program;
}


// 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 `x ?? y` results in type LUB(x!, y)
void main() {
  f1(null, 2);
}

void f1(
    int? nullableInt,
    int nonNullInt,
) {
  (nullableInt ?? nonNullInt) + 1;
  (nullableInt ?? nullableInt) + 1;
//^^^^^^^^^^^^^^^^^^^^^^^^^^^^
// [analyzer] STATIC_WARNING.UNCHECKED_USE_OF_NULLABLE_VALUE
// [cfe] unspecified
  (nonNullInt ?? nullableInt) + 1;
//               ^^^^^^^^^^^
// [analyzer] STATIC_WARNING.DEAD_NULL_AWARE_EXPRESSION
//^^^^^^^^^^^^^^^^^^^^^^^^^^^
// [analyzer] STATIC_WARNING.UNCHECKED_USE_OF_NULLABLE_VALUE
// [cfe] unspecified
  (nonNullInt ?? nonNullInt) + 1;
//               ^^^^^^^^^^
// [analyzer] STATIC_WARNING.DEAD_NULL_AWARE_EXPRESSION
}

// TODO(mfairhurst) add cases with type parameter types

Fix a test to get the analyzer nnbd bot to pass

// 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 `x ?? y` results in type LUB(x!, y)
void main() {
  f1(null, 2);
}

void f1(
    int? nullableInt,
    int nonNullInt,
) {
  (nullableInt ?? nonNullInt) + 1;
  (nullableInt ?? nullableInt) + 1;
//^^^^^^^^^^^^^^^^^^^^^^^^^^^^
// [analyzer] STATIC_WARNING.USE_OF_NULLABLE_VALUE
// [cfe] unspecified
  (nonNullInt ?? nullableInt) + 1;
//               ^^^^^^^^^^^
// [analyzer] STATIC_WARNING.DEAD_NULL_AWARE_EXPRESSION
//^^^^^^^^^^^^^^^^^^^^^^^^^^^
// [analyzer] STATIC_WARNING.USE_OF_NULLABLE_VALUE
// [cfe] unspecified
  (nonNullInt ?? nonNullInt) + 1;
//               ^^^^^^^^^^
// [analyzer] STATIC_WARNING.DEAD_NULL_AWARE_EXPRESSION
}

// TODO(mfairhurst) add cases with type parameter types


library list_tasks;

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

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

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

DivElement taskContainer(String tasksummary) {
  DivElement div = new DivElement();
  div
    ..classes.add('taskcontainer')
    ..append(singleTaskElement(tasksummary))
    ..append(editTaskElement(tasksummary));
  return div;
}

// append for each task in tasks a singletask
// element to div '#listtasks'.
void displayTasks() {
  DivElement div = querySelector('#listtasks');
  List tl = loadFromStorage();
  tl.forEach((i) {
    div.append(singleTaskElement(i['summary']));
    div.append(editTaskElement(i['summary']));
  });
}
// insert Task into displayed tasklist at index 0;
void insertTask(String tasksummary) {
  DivElement div = taskContainer(tasksummary);
  querySelector('#listtasks').children.insert(0, div);
}

Change displayTasks to use taskContainer element.

library list_tasks;

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

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

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

DivElement taskContainer(String tasksummary) {
  DivElement div = new DivElement();
  div
    ..classes.add('taskcontainer')
    ..append(singleTaskElement(tasksummary))
    ..append(editTaskElement(tasksummary));
  return div;
}

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

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


import 'dart:io';
import 'package:twitter/twitter.dart';

main(){
  var envVars = Platform.environment;
  print(envVars['CONSUMER_KEY']);
  print(envVars['CONSUMER_SECRET']);
  print(envVars['ACCESS_TOKEN']);
  print(envVars['ACCESS_TOKEN_SECRET']);
  var map = {
      "consumerKey": envVars['CONSUMER_KEY'],
      "consumerSecret": envVars['CONSUMER_SECRET'],
      "accessToken": envVars['ACCESS_TOKEN'],
      "accessSecret": envVars['ACCESS_TOKEN_SECRET']
  };
  var twitter = new Twitter.fromMap(map);
  try {
    var a = twitter.request("GET", "statuses/home_timeline.json");
    a.then((value){
      new File("test.json").writeAsString(value.body);
    });
  } catch(e) {
  } finally {
  }
  return;
}

Fix example according to filename

import 'dart:io';
import 'package:twitter/twitter.dart';

main() {
  var envVars = Platform.environment;
  print(envVars['CONSUMER_KEY']);
  print(envVars['CONSUMER_SECRET']);
  print(envVars['ACCESS_TOKEN']);
  print(envVars['ACCESS_TOKEN_SECRET']);
  var map = {
      "consumerKey": envVars['CONSUMER_KEY'],
      "consumerSecret": envVars['CONSUMER_SECRET'],
      "accessToken": envVars['ACCESS_TOKEN'],
      "accessSecret": envVars['ACCESS_TOKEN_SECRET']
  };
  Twitter twitter = new Twitter.fromMap(map);

  try {
    var a = twitter.request("POST", "statuses/update.json",body: {"status":"test"});
    a.then((value){
      new File("test.json").writeAsString(value.body);
    });
  } catch(e) {
  } finally {
  }
  return;
}


library frappe.test_runner;

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

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

Use underscores for import aliases

library frappe.test_runner;

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

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


import 'dart:async';

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

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

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

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

import 'package:moor/moor.dart';

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

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

Use emitsThrough instead of emits

import 'dart:async';

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

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

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

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

import 'package:moor/moor.dart';

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

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


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

Fix compile warning in Dart test project

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


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

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

}

Add test for insertTask function

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

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

}


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

class _InvocationMirror implements InvocationMirror {
  static final int METHOD = 0;
  static final int GETTER = 1;
  static final int SETTER = 2;

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

  final int _type;

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

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

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

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

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

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

class _InvocationMirror implements InvocationMirror {
  static final int METHOD = 0;
  static final int GETTER = 1;
  static final int SETTER = 2;

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

  final int _type;

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

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

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

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