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

#library('ShadowDOMTest');

#import('dart:html');

// Test that children of a shadow host get distributed properly to the
// insertion points of a shadow subtree. Output should be three boxes,
// ordered blue, red, green down the page.
main() {
  var div = new DivElement();
  document.body.elements.add(div);

  // build some DOM elements
  var bluebox = _colorBox('blue', 40, 20);
  bluebox.classes.add('foo');
  var redbox = _colorBox('red', 30, 30);
  var greenbox = _colorBox('green', 60, 10);

  // assemble DOM
  var sRoot = new ShadowRoot(div);
  sRoot.nodes.add(new Element.html('<content select=".foo"></content>'));
  sRoot.nodes.add(redbox);
  sRoot.nodes.add(new Element.tag('content'));

  div.nodes.add(bluebox);
  div.nodes.add(greenbox);
}

DivElement _colorBox(String color, int width, int height) {
  var style = ('background-color:$color; '
      'width:${width}px; height:${height}px;');
  return new Element.html('

');
}

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

library ShadowDOMTest;

import 'dart:html';

// Test that children of a shadow host get distributed properly to the
// insertion points of a shadow subtree. Output should be three boxes,
// ordered blue, red, green down the page.
main() {
  var div = new DivElement();
  document.body.elements.add(div);

  // build some DOM elements
  var bluebox = _colorBox('blue', 40, 20);
  bluebox.classes.add('foo');
  var redbox = _colorBox('red', 30, 30);
  var greenbox = _colorBox('green', 60, 10);

  // assemble DOM
  var sRoot = new ShadowRoot(div);
  sRoot.nodes.add(new Element.html('<content select=".foo"></content>'));
  sRoot.nodes.add(redbox);
  sRoot.nodes.add(new Element.tag('content'));

  div.nodes.add(bluebox);
  div.nodes.add(greenbox);
}

DivElement _colorBox(String color, int width, int height) {
  var style = ('background-color:$color; '
      'width:${width}px; height:${height}px;');
  return new Element.html('

');
}

Update library syntax (tests/html directory).
Review URL: https://codereview.chromium.org//11364181

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


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

patch class NoSuchMethodError {
  /* patch */ static String safeToString(Object object) {
    if (object is int || object is double || object is bool || null == object) {
      return object.toString();
    }
    if (object is String) {
      String escaped = object.replaceAll('"', '\\"');
      return '"$escaped"';
    }
    return Object._toString(object);
  }
}

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

patch class NoSuchMethodError {
  /* patch */ static String safeToString(Object object) {
    if (object is int || object is double || object is bool || null == object) {
      return object.toString();
    }
    if (object is String) {
      // TODO(ahe): Remove hack when http://dartbug.com/4995 is fixed.
      const hack = '\\' '"';
      String escaped = object.replaceAll('"',  hack);
      return '"$escaped"';
    }
    return Object._toString(object);
  }
}

Work around for bug 4995 to unbreak VM build.

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

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


// 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=constant-update-2018

// Tests that non-deferred type literals are constant expressions.

import "dart:core";
import "dart:core" as core;
import "dart:core" deferred as dcore;

// Declares F function type alias, M mixin and C class.
import "constant_type_literal_types.dart";
import "constant_type_literal_types.dart" as p;
import "constant_type_literal_types.dart" deferred as d;

main() {
  const Test(int, core.int);
  const Test(C, p.C);
  const Test(M, p.M);
  const Test(F, p.F);
  const c1 = //
      dcore. //# 01: compile-time error
          int;
  const Test(c1, int);
  const c2 = //
      d. //# 02: compile-time error
          C;
  const Test(c2, C);
}

class Test {
  const Test(Type t1, Type t2) : assert(identical(t1, t2));
}

// 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=constant-update-2018

// Tests that non-deferred type literals are constant expressions.

import "dart:core";
import "dart:core" as core;
// No reloading support for deferred loading.
// See https://github.com/dart-lang/sdk/issues/33118,
import "dart:core" deferred as dcore; //# 01: crash on reload

// Declares F function type alias, M mixin and C class.
import "constant_type_literal_types.dart";
import "constant_type_literal_types.dart" as p;
// No reloading support for deferred loading.
// See https://github.com/dart-lang/sdk/issues/33118,
import "constant_type_literal_types.dart" deferred as d; //# 02: crash on reload

main() {
  const Test(int, core.int);
  const Test(C, p.C);
  const Test(M, p.M);
  const Test(F, p.F);
  const c1 = //
      dcore. //# 01: compile-time error
          int;
  const Test(c1, int);
  const c2 = //
      d. //# 02: compile-time error
          C;
  const Test(c2, C);
}

class Test {
  const Test(Type t1, Type t2) : assert(identical(t1, t2));
}

[gardening] Make deferred imports part of the corresponding tests.

See https://github.com/dart-lang/sdk/issues/36418 for more info.

Change-Id: I5e26b295699c52db2e542330c23f8ec3095d78e9
Reviewed-on: https://dart-review.googlesource.com/c/sdk/+/98840
Reviewed-by: Stevie Strickland <cce218d042444252b7ac446d60910fca7732559c@google.com>
Commit-Queue: Stevie Strickland <cce218d042444252b7ac446d60910fca7732559c@google.com>


library polymer.tool.uncomment_test_section_in_pubspec;

import 'dart:io';

import 'package:path/path.dart';

main() {
  var path = relative(
      join(dirname(dirname(Platform.script.path.substring(1))), 'pubspec.yaml'));
  print('uncomment_test_section_in_pubspec: processing $path');
  var pubspec = new File(path);
  if (!pubspec.existsSync()) {
    print('uncomment_test_section_in_pubspec error: '
        'pubspec.yaml not found: $path.');
    exit(1);
  }
  var contents = pubspec.readAsStringSync();
  var begin = contents.indexOf("# ---prehook: begin uncomment---");
  if (begin == -1) {
    print('uncomment_test_section_in_pubspec error: '
        'start of commented section not found.');
    exit(1);
  }
  var end = contents.indexOf("# ---prehook: end uncomment---", begin);
  if (end == -1) {
    print('uncomment_test_section_in_pubspec error: '
        'end of commented section not found.');
    exit(1);
  }
  var newContents = new StringBuffer()
      ..write(contents.substring(0, begin))
      ..write(contents.substring(begin, end).replaceAll('\n# ', '\n'))
      ..write(contents.substring(end));
  pubspec.writeAsStringSync(newContents.toString());
  print('updated pubspec successfully');
}

library polymer.tool.uncomment_test_section_in_pubspec;

import 'dart:io';

import 'package:path/path.dart';

main() {
  var scriptPath = Platform.script.path;
  if (context.style.name == 'windows') scriptPath = scriptPath.substring(1);
  var path = join(dirname(dirname(scriptPath)), 'pubspec.yaml');
  print('uncomment_test_section_in_pubspec: processing $path');
  var pubspec = new File(path);
  if (!pubspec.existsSync()) {
    print('uncomment_test_section_in_pubspec error: '
        'pubspec.yaml not found: $path.');
    exit(1);
  }
  var contents = pubspec.readAsStringSync();
  var begin = contents.indexOf("# ---prehook: begin uncomment---");
  if (begin == -1) {
    print('uncomment_test_section_in_pubspec error: '
        'start of commented section not found.');
    exit(1);
  }
  var end = contents.indexOf("# ---prehook: end uncomment---", begin);
  if (end == -1) {
    print('uncomment_test_section_in_pubspec error: '
        'end of commented section not found.');
    exit(1);
  }
  var newContents = new StringBuffer()
      ..write(contents.substring(0, begin))
      ..write(contents.substring(begin, end).replaceAll('\n# ', '\n'))
      ..write(contents.substring(end));
  pubspec.writeAsStringSync(newContents.toString());
  print('updated pubspec successfully');
}

Remove relative path, but do special check for windows


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

/**
 * The StringBuffer class is useful for concatenating strings
 * efficiently. Only on a call to [toString] are the strings
 * concatenated to a single String.
 */
interface StringBuffer default StringBufferImpl {
  /**
   * Creates the string buffer with an initial content.
   */
  StringBuffer([Object content]);

  /**
   * Returns the length of the buffer.
   */
  int get length();

  /**
   * Returns whether the buffer is empty.
   */
  bool isEmpty();

  /**
   * Adds [obj] to the buffer. Returns [:this:].
   */
  StringBuffer add(Object obj);

  /**
   * Adds all items in [objects] to the buffer. Returns [:this:].
   */
  StringBuffer addAll(Collection<Object> objects);

  /**
   * Clears the string buffer. Returns [:this:].
   */
  StringBuffer clear();

  /**
   * Returns the contents of buffer as a concatenated string.
   */
  String toString();
}

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

/**
 * The StringBuffer class is useful for concatenating strings
 * efficiently. Only on a call to [toString] are the strings
 * concatenated to a single String.
 */
interface StringBuffer default StringBufferImpl {
  /**
   * Creates the string buffer with an initial content.
   */
  StringBuffer([Object content]);

  /**
   * Returns the length of the buffer.
   */
  int get length();

  /**
   * Returns whether the buffer is empty.
   */
  bool isEmpty();

  /**
   * Converts [obj] to a string and adds it to the buffer. Returns [:this:].
   */
  StringBuffer add(Object obj);

  /**
   * Adds the string representation of [charCode] to the buffer.
   * Returns [this].
   */
  StringBuffer addCharCode(int charCode);

  /**
   * Adds all items in [objects] to the buffer. Returns [:this:].
   */
  StringBuffer addAll(Collection<Object> objects);

  /**
   * Clears the string buffer. Returns [:this:].
   */
  StringBuffer clear();

  /**
   * Returns the contents of buffer as a concatenated string.
   */
  String toString();
}

Add addCharCode to StringBuffer interface. Already implemented by all implementations.

R=floitsch@google.com
BUG=
TEST=

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

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


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

library filenames;

import 'dart:io';

// For information about how to convert Windows file names to URIs:
// http://blogs.msdn.com/b/ie/archive/2006/12/06/file-uris-in-windows.aspx

String nativeToUriPath(String filename) {
  // TODO(ahe): It would be nice to use a Dart library instead.
  if (!Platform.isWindows) return filename;
  filename = filename.replaceAll('\\', '/');
  if (filename.length > 2 && filename[1] == ':') {
    filename = "/$filename";
  }
  return filename;
}

String uriPathToNative(String path) {
  // TODO(ahe): It would be nice to use a Dart library instead.
  if (!Platform.isWindows) return path;
  if (path.length > 3 && path[0] == '/' && path[2] == ':') {
    return path.substring(1).replaceAll('/', '\\');
  } else {
    return path.replaceAll('/', '\\');
  }
}

final Uri currentDirectory = new Uri(
    scheme: 'file',
    path: appendSlash(nativeToUriPath(new File('.').fullPathSync())));

String appendSlash(String path) => path.endsWith('/') ? path : '$path/';

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

library filenames;

import 'dart:io' show Platform;

// For information about how to convert Windows file names to URIs:
// http://blogs.msdn.com/b/ie/archive/2006/12/06/file-uris-in-windows.aspx

String nativeToUriPath(String filename) {
  // TODO(ahe): It would be nice to use a Dart library instead.
  if (!Platform.isWindows) return filename;
  filename = filename.replaceAll('\\', '/');
  if (filename.length > 2 && filename[1] == ':') {
    filename = "/$filename";
  }
  return filename;
}

String uriPathToNative(String path) {
  // TODO(ahe): It would be nice to use a Dart library instead.
  if (!Platform.isWindows) return path;
  if (path.length > 3 && path[0] == '/' && path[2] == ':') {
    return path.substring(1).replaceAll('/', '\\');
  } else {
    return path.replaceAll('/', '\\');
  }
}

final Uri currentDirectory = Uri.base;

String appendSlash(String path) => path.endsWith('/') ? path : '$path/';

Remove used of deprecated File.fullPathSync.

BUG=

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

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


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

library spark_widgets;

import 'dart:html';

import 'package:polymer/polymer.dart';

bool IS_DART2JS = identical(1, 1.0);

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

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

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

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

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

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

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

library spark_widgets;

import 'dart:html';

import 'package:polymer/polymer.dart';

bool IS_DART2JS = identical(1, 1.0);

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

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

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

  // TODO(ussuri): Temporarily leave for experiments. Remove soon: unsupported
  // at least from Chrome M34.
  @deprecated
  @override
  bool get applyAuthorStyles => false;

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

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

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

Revert overridden applyAuthorStyles for now for explicitness and experiments


import 'dart:ffi';
import 'dart:io';

import 'package:flutter_driver/driver_extension.dart';
import 'package:test/test.dart';
import 'package:sqlite3/sqlite3.dart';
import 'package:sqlite3/src/ffi/ffi.dart' show char, Utf8Utils, PointerUtils;
import 'package:sqlite3/open.dart';

typedef _sqlite3_compileoption_get_native = Pointer<Uint8> Function(Int32 n);
typedef _sqlite3_compileoption_get_dart = Pointer<Uint8> Function(int n);

void main() {
  enableFlutterDriverExtension();

  tearDownAll(() {
    // See https://github.com/flutter/flutter/issues/12427#issuecomment-464449765
    Future.delayed(const Duration(milliseconds: 50)).then((_) => exit(0));
  });

  test('can open sqlite3', () {
    print(sqlite3.version);

    final getCompileOption = open.openSqlite().lookupFunction<
        _sqlite3_compileoption_get_native,
        _sqlite3_compileoption_get_dart>('sqlite3_compileoption_get');

    String? lastOption;
    var i = 0;
    do {
      final ptr = getCompileOption(i).cast<char>();

      if (!ptr.isNullPointer) {
        lastOption = ptr.readString();
        print('Compile-option: $lastOption');
      }

      i++;
    } while (lastOption != null);
  });
}

import 'dart:ffi';
import 'dart:io';

import 'package:flutter_driver/driver_extension.dart';
import 'package:test/test.dart';
import 'package:sqlite3/sqlite3.dart';
import 'package:sqlite3/src/ffi/ffi.dart' show char, Utf8Utils, PointerUtils;
import 'package:sqlite3/open.dart';

typedef _sqlite3_compileoption_get_native = Pointer<Uint8> Function(Int32 n);
typedef _sqlite3_compileoption_get_dart = Pointer<Uint8> Function(int n);

void main() {
  enableFlutterDriverExtension();

  tearDownAll(() {
    // See https://github.com/flutter/flutter/issues/12427#issuecomment-464449765
    Future.delayed(const Duration(milliseconds: 50)).then((_) => exit(0));
  });

  test('can open sqlite3', () {
    print(sqlite3.version);

    final getCompileOption = open.openSqlite().lookupFunction<
        _sqlite3_compileoption_get_native,
        _sqlite3_compileoption_get_dart>('sqlite3_compileoption_get');

    String? lastOption;
    var i = 0;
    do {
      final ptr = getCompileOption(i).cast<char>();

      if (!ptr.isNullPointer) {
        lastOption = ptr.readString();
        print('Compile-option: $lastOption');
      } else {
        lastOption = null;
      }

      i++;
    } while (lastOption != null);
  });
}

Fix infinite loop in test

Fix infinite loop in test


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

/// Support for doing something awesome.
///
/// More dartdocs go here.
library fnx_rest;

import 'dart:async';
import 'package:http/browser_client.dart' as http;

import 'package:http/src/response.dart';
import 'src/rest_client.dart';
export 'src/rest_client.dart';

class HttpRestClient extends RestClient {

  HttpRestClient.root(String url) : this(null, url);
  HttpRestClient(RestClient parent, String url) : super(new BrowserHttpClient(), parent, url);

}

class BrowserHttpClient extends HttpClient {

  http.BrowserClient _client = new http.BrowserClient();

  @override
  Future<Response> get(String url, {Map<String, String> headers}) {
    return _client.get(url, headers: headers);
  }

  @override
  Future<Response> delete(String url, {Map<String, String> headers}) {
    return _client.delete(url, headers: headers);
  }

  @override
  Future<Response> post(String url, data, {Map<String, String> headers}) {
    return _client.post(url, headers: headers, body: data);
  }

  @override
  Future<Response> put(String url, data, {Map<String, String> headers}) {
    return _client.post(url, headers: headers, body: data);
  }
}

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

/// Support for doing something awesome.
///
/// More dartdocs go here.
library fnx_rest;

import 'dart:async';
import 'package:http/browser_client.dart' as http;

import 'package:http/src/response.dart';
import 'src/rest_client.dart';
export 'src/rest_client.dart';

class HttpRestClient extends RestClient {

  HttpRestClient.root(String url) : this(null, url);
  HttpRestClient(RestClient parent, String url) : super(new BrowserHttpClient(), parent, url);

}

class BrowserHttpClient extends HttpClient {

  http.BrowserClient _client = new http.BrowserClient();

  @override
  Future<Response> get(String url, {Map<String, String> headers}) {
    return _client.get(url, headers: headers);
  }

  @override
  Future<Response> delete(String url, {Map<String, String> headers}) {
    return _client.delete(url, headers: headers);
  }

  @override
  Future<Response> post(String url, data, {Map<String, String> headers}) {
    return _client.post(url, headers: headers, body: data);
  }

  @override
  Future<Response> put(String url, data, {Map<String, String> headers}) {
    return _client.put(url, headers: headers, body: data);
  }
}

FIX HttpClient.put should call correct method


import "package:bitesize_screencasts/customer/customer.dart";
import "package:bitesize_screencasts/customer/customer_location_parser.dart";
import "package:unittest/unittest.dart";
import "dart:html";

void main() {

  group("Customer Location Tests", () {

    test("Customer Location Parser should parse customer entirely", () {
      window.location.href = "#firstName=Walter,lastName=White,age=43,wealth=95000";
      Customer expectedCustomer = new Customer("Walter", "White", 43, 95000);

      Customer parsedCustomer = CustomerLocationParser.parseFromLocationFragment();

      expect(expectedCustomer.firstName, equals(parsedCustomer.firstName));
      expect(expectedCustomer.lastName, equals(parsedCustomer.lastName));
      expect(expectedCustomer.age, equals(parsedCustomer.age));
      expect(expectedCustomer.wealth, equals(parsedCustomer.wealth));

    });

  });

}

import "package:bitesize_screencasts/customer/customer.dart";
import "package:bitesize_screencasts/customer/customer_location_parser.dart";
import "package:unittest/unittest.dart";
import "dart:html";
import 'package:unittest/html_config.dart';
import 'package:unittest/html_enhanced_config.dart';

void main() {

  useHtmlEnhancedConfiguration();

  group("Customer Location Tests", () {

    test("Customer Location Parser should parse customer entirely", () {
      window.location.href = "#firstName=Walter,lastName=White,age=43,wealth=95000";
      Customer expectedCustomer = new Customer("Walter", "White", 43, 95000);

      Customer parsedCustomer = CustomerLocationParser.parseFromLocationFragment();

      expect(expectedCustomer.firstName, equals(parsedCustomer.firstName));
      expect(expectedCustomer.lastName, equals(parsedCustomer.lastName));
      expect(expectedCustomer.age, equals(parsedCustomer.age));
      expect(expectedCustomer.wealth, equals(parsedCustomer.wealth));

    });

  });

}

Add html configuration for customer location test


library arpoador;

import 'dart:io';
import 'dart:typed_data';

class Momentum {

  static listen({port: 8777, address: "127.0.0.1",
      handler(socket)}) {
    var server = new ServerSocket(address, port);
    while (true) {
      server.spawnAccept(handler);
    }
  }

  static handle(socket, fn(req, res)) {
    var buffer = socket.readNext();
    if (buffer != null) {
      var response = new Response(socket);
      fn(new Request(), response);
      response.doFlush();
    }
    socket.close();
  }

}

class Request {

}

class Response {

  var socket, statusCode = 200, headerMap = {}, responseContent = "";

  Response(this.socket);

  writeHead(statusCode, headerMap) {
    this.statusCode = statusCode;
    this.headerMap = headerMap;
  }

  end(responseContent) {
    this.responseContent = responseContent;
  }

  doFlush() {
    var body = responseContent,
      header = "HTTP/1.1 200 OK\nContent-Type: text/html\nContent-Length: ",
      s = "${header}${body.length}\n\n${body}";
    var len = s.length, i, a = new Uint8List(len);
    for (i = 0; i < len; i++) {
      a[i] = s.codeUnitAt(i);
    }
    socket.write(a.buffer);
  }

}

library arpoador;

import 'dart:io';
import 'dart:typed_data';

class Momentum {

  /// For now, the handler callback should be a static method or function.
  /// It seems that instance methods don't work as handler callbacks yet.
  static listen({port: 8777, address: "127.0.0.1",
      handler(socket)}) {
    var server = new ServerSocket(address, port);
    while (true) {
      server.spawnAccept(handler);
    }
  }

  static handle(socket, fn(req, res)) {
    var buffer = socket.readNext();
    if (buffer != null) {
      var response = new Response(socket);
      fn(new Request(), response);
      response.doFlush();
    }
    socket.close();
  }

}

class Request {

}

class Response {

  var socket, statusCode = 200, headerMap = {}, responseContent = "";

  Response(this.socket);

  writeHead(statusCode, headerMap) {
    this.statusCode = statusCode;
    this.headerMap = headerMap;
  }

  end(responseContent) {
    this.responseContent = responseContent;
  }

  doFlush() {
    var body = responseContent,
      header = "HTTP/1.1 200 OK\nContent-Type: text/html\nContent-Length: ",
      s = "${header}${body.length}\n\n${body}";
    var len = s.length, i, a = new Uint8List(len);
    for (i = 0; i < len; i++) {
      a[i] = s.codeUnitAt(i);
    }
    socket.write(a.buffer);
  }

}

Document the listen method a little.

Document the listen method a little.


class lowercase {}

class UPPERCASE {}

class MyClass {
  void method1() => print('Called method1!');
  void Method2() => print('Called method2!');
  void get() => print('Called get()!');
  void set() => print('Called set()!');

  String? _foo;
  String? get foo => _foo;
  set foo(String? value) => _foo = value;
}

void main() async {
  var FOO = MyClass();
  FOO.method1();
  FOO.Method2();
  FOO.get();
  FOO.set();
  FOO.foo = FOO.foo;

  void Function()? nullableFunc;

  nullableFunc();
  nullableFunc!();
  nullableFunc?();

  var val = 'test' as dynamic;
  print('!$val世界!');

  final a = await null;
  if (a == null) {
    print(false);
    for (var i in []) {
      if (i == 0) {
        continue;
      }
      break;
    }
  } else {}

  try {
    assert(true == true);
  } on Exception {
    throw Exception('test');
  } catch (e) {
    rethrow;
  } finally {}

  switch (true) {
    case false:
      break;
    default:
  }

  while (1 == 2) {
    do {} while (false);
  }
}

class lowercase {}

class UPPERCASE {}

class MyClass {
  void method1() => print('Called method1!');
  void Method2() => print('Called method2!');
  void get() => print('Called get()!');
  void set() => print('Called set()!');

  String? _foo;
  String? get foo => _foo;
  set foo(String? value) => _foo = value;
}

void main() async {
  var FOO = MyClass();
  FOO.method1();
  FOO.Method2();
  FOO.get();
  FOO.set();
  FOO.foo = FOO.foo;

  void Function() notNullableFunc = () {};
  void Function()? nullableFunc;

  notNullableFunc();
  nullableFunc!();

  var val = 'test' as dynamic;
  print('!$val世界!');

  final a = await null;
  if (a == null) {
    print(false);
    for (var i in []) {
      if (i == 0) {
        continue;
      }
      break;
    }
  } else {}

  try {
    assert(true == true);
  } on Exception {
    throw Exception('test');
  } catch (e) {
    rethrow;
  } finally {}

  switch (true) {
    case false:
      break;
    default:
  }

  while (1 == 2) {
    do {} while (false);
  }
}

Fix analysis error in manual testing file


// 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=extension-methods

// It is an error to have a setter and a getter in an extension where
// the return type of the getter is not assignable to the argument type
// of the setter.
extension E1 on int {
  static int get property => 1;
  //     ^^
  // [analyzer] unspecified
  // [cfe] unspecified
  static void set property(String value) {}
  //                       ^^
  // [analyzer] unspecified
  // [cfe] unspecified
  int get property2 => 1;
  //  ^^
  // [analyzer] unspecified
  // [cfe] unspecified
  void set property2(String x) {}
  //                 ^^
  // [analyzer] unspecified
  // [cfe] unspecified
}

void main() {}

// 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=extension-methods

// It is an error to have a setter and a getter in an extension where
// the return type of the getter is not assignable to the argument type
// of the setter.
extension E1 on int {
  static int get property => 1;
  //     ^^
  // [cfe] unspecified
  //             ^^^^^^^^
  // [analyzer] STATIC_WARNING.MISMATCHED_GETTER_AND_SETTER_TYPES
  static void set property(String value) {}
  //                       ^^
  // [cfe] unspecified
  int get property2 => 1;
  //  ^^
  // [cfe] unspecified
  //      ^^^^^^^^^
  // [analyzer] STATIC_WARNING.MISMATCHED_GETTER_AND_SETTER_TYPES
  void set property2(String x) {}
  //                 ^^
  // [cfe] unspecified
}

void main() {}

Update test expectations to match analyzer behavior

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


typedef HttpRequest HttpRequestFactory();
typedef void HttpClientResponseCallback(HttpRequest request);

class Resource {
  String url;

  final HttpRequestFactory httpRequestFactory;

  Resource(String url, [HttpRequestFactory httpRequestFactory = null])
  : url = url,
    httpRequestFactory = (httpRequestFactory != null) ? httpRequestFactory : (() => new HttpRequest()) {
  }

  void query(Map<String, String> params, void onSuccess(Object data)) {
    HttpRequest r = httpRequestFactory();
    _addResponseHandler(r, onSuccess);

    r.open('GET', url, true);
  }

  void get(Map<String, String> params, void onSuccess(Object data)) {
    HttpRequest r = httpRequestFactory();
    _addResponseHandler(r, onSuccess);

    String id = params['id'];
    String getUrl = '${url}/${id}';

    r.open('GET', url, true);
  }

  void _addResponseHandler(HttpRequest request, void onSuccess(Object data)) {
    request.on.load.add((event) {
      Object data = JSON.parse(request.responseText);
      onSuccess(data);
    });
  }
}

typedef HttpRequest HttpRequestFactory();
typedef void HttpClientResponseCallback(HttpRequest request);

class Resource {
  String url;

  final HttpRequestFactory httpRequestFactory;

  Resource(String url, [HttpRequestFactory httpRequestFactory = null])
  : url = url,
    httpRequestFactory = (httpRequestFactory != null) ? httpRequestFactory : (() => new HttpRequest()) {
  }

  void query(Map<String, String> params, void onSuccess(Object data)) {
    HttpRequest r = httpRequestFactory();
    _addResponseHandler(r, onSuccess);

    r.open('GET', url, true);
    r.send();
  }

  void get(Map<String, String> params, void onSuccess(Object data)) {
    HttpRequest r = httpRequestFactory();
    _addResponseHandler(r, onSuccess);

    String id = params['id'];
    String getUrl = '${url}/${id}';

    r.open('GET', url, true);
    r.send();
  }

  void _addResponseHandler(HttpRequest request, void onSuccess(Object data)) {
    request.on.load.add((event) {
      Object data = JSON.parse(request.responseText);
      onSuccess(data);
    });
  }
}

Call .send() on HttpRequest to fire it off


part of irc;

class BotConfig {
  String host;
  int port;
  String nickname;
  String realname;
  String username;
  bool synchronous;

  BotConfig({this.host: "irc.esper.net", this.port: 6667, this.nickname:"DartBot", this.username: "DartBot", this.realname: "Dart IRC Bot", this.synchronous: false});
}

class Channel {
  Client client;
  String name;

  Channel(this.client, this.name);

  void message(String message) => client.message(name, message);

  void notice(String message) => client.notice(name, message);

  void op(String user) => mode("+o", user);

  void deop(String user) => mode("-o", user);

  void voice(String user) => mode("+v", user);

  void devoice(String user) => mode("-v", user);

  void mode(String mode, [String user = null]) {
    if (user != null) {
      client.send("MODE ${name} ${mode} ${user}");
    } else {
      client.send("MODE ${name} ${mode}");
    }
  }

  bool operator ==(Channel channel) => this.name == channel.name;
}

part of irc;

class BotConfig {
  String host;
  int port;
  String nickname;
  String realname;
  String username;
  bool synchronous;

  BotConfig({this.host: "irc.esper.net", this.port: 6667, this.nickname:"DartBot", this.username: "DartBot", this.realname: "Dart IRC Bot", this.synchronous: false});
}

class Channel {
  Client client;
  String name;

  Channel(this.client, this.name);

  void message(String message) => client.message(name, message);

  void notice(String message) => client.notice(name, message);

  void op(String user) => mode("+o", user);

  void deop(String user) => mode("-o", user);

  void voice(String user) => mode("+v", user);

  void devoice(String user) => mode("-v", user);

  void ban(String user) => mode("+b", user);

  void unban(String user) => mode("-b", user);

  void kick(String user) => client.send("KICK ${name} ${user}");

  void mode(String mode, [String user = null]) {
    if (user != null) {
      client.send("MODE ${name} ${mode} ${user}");
    } else {
      client.send("MODE ${name} ${mode}");
    }
  }

  bool operator ==(Channel channel) => this.name == channel.name;
}

Add Ban, Unban, and Kick support

Add Ban, Unban, and Kick support


/*
 * Package : dartivity_database
 * Author : S. Hamblett <steve.hamblett@linux.com>
 * Date   : 05/011/2015
 * Copyright :  S.Hamblett 2015
 */

part of dartivity_database;

class DartivityCache {
  /// The cache
  Map<String, dynamic> _cache;

  DartivityCache() {
    _cache = new Map<String, dynamic>();
  }

  /// get
  dynamic get(String key) {
    if (_cache.containsKey(key)) {
      return _cache[key];
    } else {
      return null;
    }
  }

  /// put
  put(String key, dynamic resource) {
    _cache[key] = resource;
  }

  /// clear
  void clear() {
    _cache.clear();
  }
}

/*
 * Package : dartivity_database
 * Author : S. Hamblett <steve.hamblett@linux.com>
 * Date   : 05/011/2015
 * Copyright :  S.Hamblett 2015
 */

part of dartivity_database;

class DartivityCache {
  /// The cache
  Map<String, dynamic> _cache;

  DartivityCache() {
    _cache = new Map<String, dynamic>();
  }

  /// get
  dynamic get(String key) {
    if (_cache.containsKey(key)) {
      return _cache[key];
    } else {
      return null;
    }
  }

  /// put
  void put(String key, dynamic resource) {
    _cache[key] = resource;
  }

  /// delete
  void delete(String key) {
    if (_cache.containsKey(key)) {
      _cache.remove(key);
    }
  }
  /// clear
  void clear() {
    _cache.clear();
  }
}

Add the general purpose cache

Add the general purpose cache


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

import 'dart:html';
import 'package:polymer/polymer.dart';
import 'package:observatory/service.dart';
import 'service_ref.dart';

@CustomTag('function-ref')
class FunctionRefElement extends ServiceRefElement {
  @published bool qualified = true;

  FunctionRefElement.created() : super.created();

  refChanged(oldValue) {
    super.refChanged(oldValue);
    _updateShadowDom();
  }

  ServiceFunction get function => ref;
  void _updateShadowDom() {
    clearShadowRoot();
    if (ref == null) {
      return;
    }
    if (qualified) {
      if (function.dartOwner is ServiceFunction) {
        var functionRef = new Element.tag('function-ref');
        functionRef.ref = function.dartOwner;
        functionRef.qualified = true;
        shadowRoot.children.add(functionRef);
        insertTextSpanIntoShadowRoot('.');
      } else if (function.dartOwner is Class) {
        var classRef = new Element.tag('class-ref');
        classRef.ref = function.dartOwner;
        shadowRoot.children.add(classRef);
        insertTextSpanIntoShadowRoot('.');
      }
    }
    insertLinkIntoShadowRoot(name, url, hoverText);
  }
}

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

import 'dart:html';
import 'package:polymer/polymer.dart';
import 'package:observatory/service.dart';
import 'service_ref.dart';

@CustomTag('function-ref')
class FunctionRefElement extends ServiceRefElement {
  @published bool qualified = true;

  FunctionRefElement.created() : super.created();

  refChanged(oldValue) {
    super.refChanged(oldValue);
    _updateShadowDom();
  }

  ServiceFunction get function => ref;
  void _updateShadowDom() {
    clearShadowRoot();
    if (ref == null) {
      return;
    }
    if (!function.kind.isDart()) {
      insertTextSpanIntoShadowRoot(name);
      return;
    }
    if (qualified) {
      if (function.dartOwner is ServiceFunction) {
        var functionRef = new Element.tag('function-ref');
        functionRef.ref = function.dartOwner;
        functionRef.qualified = true;
        shadowRoot.children.add(functionRef);
        insertTextSpanIntoShadowRoot('.');
      } else if (function.dartOwner is Class) {
        var classRef = new Element.tag('class-ref');
        classRef.ref = function.dartOwner;
        shadowRoot.children.add(classRef);
        insertTextSpanIntoShadowRoot('.');
      }
    }
    insertLinkIntoShadowRoot(name, url, hoverText);
  }
}

Make function-ref only show a link for Dart functions

BUG=

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


import 'dart:async';
import 'dart:convert';

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

import 'pay_platform_interface.dart';

class PayMethodChannel extends PayPlatform {
  final MethodChannel _channel =
      const MethodChannel('plugins.flutter.io/pay_channel');

  @override
  Future<bool> userCanPay(Map<String, dynamic> paymentProfile) async =>
      await _channel.invokeMethod('userCanPay', jsonEncode(paymentProfile));

  @override
  Future<Map<String, dynamic>> showPaymentSelector(
          Map<String, dynamic> paymentProfile,
          List<PaymentItem> paymentItems) async =>
      jsonDecode(
        await _channel.invokeMethod('showPaymentSelector', {
          'payment_profile': jsonEncode(paymentProfile),
          'payment_items': paymentItems.map((item) => item.toMap()).toList(),
        }),
      );
}

import 'dart:async';
import 'dart:convert';

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

import 'pay_platform_interface.dart';

class PayMethodChannel extends PayPlatform {
  final MethodChannel _channel =
      const MethodChannel('plugins.flutter.io/pay_channel');

  @override
  Future<bool> userCanPay(Map<String, dynamic> paymentProfile) async =>
      await _channel.invokeMethod('userCanPay', jsonEncode(paymentProfile));

  @override
  Future<Map<String, dynamic>> showPaymentSelector(
      Map<String, dynamic> paymentProfile,
      List<PaymentItem> paymentItems) async {
    final paymentResult = await _channel.invokeMethod('showPaymentSelector', {
      'payment_profile': jsonEncode(paymentProfile),
      'payment_items': paymentItems.map((item) => item.toMap()).toList(),
    });

    return jsonDecode(paymentResult);
  }
}

Remove unnecessary arrow expression in complex statement


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

import 'package:angular/angular.dart';
import 'package:angular_components/model/ui/highlighted_text_model.dart';

/// A component that presents a list of [HighlightedTextSegment]s.
///
/// Example parent component:
///
///     var highlighter = new TextHighlighter();
///     var segments = highlighter.highlight(text, ['search', 'tokens']);
///
/// And template:
///
///     <highlighted-text [segments]="segments"></highlighted-text>
///
/// Use [HighlightedValueComponent] for highlighting a value instead of
/// providing segments as required by this component.
@Component(
  selector: 'highlighted-text',
  templateUrl: 'highlighted_text.html',
  styleUrls: const ['highlighted_text.scss.css'],
  directives: const [NgFor],
  changeDetection: ChangeDetectionStrategy.OnPush,
  // TODO(google): Change to `Visibility.local` to reduce code size.
  visibility: Visibility.all,
)
class HighlightedTextComponent {
  /// List of [HighlightedTextSegment]s to present.
  @Input()
  List<HighlightedTextSegment> segments;
}

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

import 'package:angular/angular.dart';
import 'package:angular_components/model/ui/highlighted_text_model.dart';

/// A component that presents a list of [HighlightedTextSegment]s.
///
/// Example parent component:
///
///     var highlighter = new TextHighlighter();
///     var segments = highlighter.highlight(text, ['search', 'tokens']);
///
/// And template:
///
///     <highlighted-text [segments]="segments"></highlighted-text>
///
/// Use [HighlightedValueComponent] for highlighting a value instead of
/// providing segments as required by this component.
@Component(
  selector: 'highlighted-text',
  templateUrl: 'highlighted_text.html',
  styleUrls: const ['highlighted_text.scss.css'],
  directives: const [NgFor],
  changeDetection: ChangeDetectionStrategy.OnPush,
)
class HighlightedTextComponent {
  /// List of [HighlightedTextSegment]s to present.
  @Input()
  List<HighlightedTextSegment> segments;
}

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

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

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

PiperOrigin-RevId: 190966716


library board_test;

import 'package:unittest/unittest.dart';
import 'package:dartless_server/dartless_server.dart';

void main() {
  group('board static data', () {
    test('contains passage', () {
      expect(Board.ALL_PASSAGES, contains(const Passage(Board_Room.STUDY, Board_Room.KITCHEN)));
      expect(Board.ALL_PASSAGES, contains(const Passage(Board_Room.CONSERVATORY, Board_Room.LOUNGE)));
    });
    test('contains hallways', () {
      expect(Board.ALL_HALLWAYS, contains(const Hallway(Board_Room.STUDY, Board_Room.HALL)));
      expect(Board.ALL_HALLWAYS, contains(const Hallway(Board_Room.HALL, Board_Room.LOUNGE)));
    });
    test('Scarlet starts in the hall/lounge hallway', () {
      expect(Board.getStart(Character.SCARLET),
          equals(const Hallway(Board_Room.HALL, Board_Room.LOUNGE)));
    });
  });
}

library board_test;

import 'package:unittest/unittest.dart';
import 'package:dartless_server/dartless_server.dart';

void main() {
  group('board static data', () {
    test('contains passage', () {
      expect(Board.ALL_PASSAGES, contains(const Passage(Board_Room.STUDY, Board_Room.KITCHEN)));
      expect(Board.ALL_PASSAGES, contains(const Passage(Board_Room.CONSERVATORY, Board_Room.LOUNGE)));
    });
    test('contains hallways', () {
      expect(Board.ALL_HALLWAYS, contains(const Hallway(2, 1)));
      expect(Board.ALL_HALLWAYS, contains(const Hallway(4, 1)));
    });
    test('Scarlet starts in the hall/lounge hallway', () {
      expect(Board.getStart(Character.SCARLET),
          equals(const Hallway(1, 1)));
    });
  });
}

Test updates for x, y changes

Test updates for x, y changes


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

library colorful.test;

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

void main() {
  test('instance fields of class Color', () {
    Color c1 = new Color(22,33,44);
    expect(c1.r, 22);
    expect(c1.b, 44);
    expect(c1.g, 33);
  });
}

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

library colorful.test;

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

void main() {
  test('instance fields of class Color', () {
    Color c1 = new Color(22,33,44);
    expect(c1.r, 22);
    expect(c1.b, 44);
    expect(c1.g, 33);
  });
  test('isValid returns true for acceptable rgb values', () {
    Color c1 = new Color(0,0,0);
    expect(c1.isValid(), true);
    Color c2 = new Color(255,255,255);
    expect(c2.isValid(), true);
    Color c3 = new Color(0,0,255);
    expect(c2.isValid(), true);
  });
}

Add test for isValid for acceptable values.


import '../../core/parser.dart';
import '../action/cast.dart';
import '../action/pick.dart';
import 'sequence.dart';

extension SurroundedByParserExtension<T> on Parser<T> {
  /// Returns a parser that consumes input [before] and [after] the reciever, but
  /// discards their parse results and only returns the result of the reciever.
  ///
  /// If a single [before] parser is provided, the same parser is also used to
  /// consume input afterwards. To skip the [before] or [after] parsing pass an
  /// `epsilon()` parser.
  ///
  /// For example, the parser `digit().plus().surroundedBy(char('['), char(']'))`
  /// returns `'42'` for the input `'[42]'`.
  Parser<T> surroundedBy(Parser<void> before, [Parser<void>? after]) =>
      [before, this, after ?? before].toSequenceParser().pick(1).cast<T>();
}

import '../../core/parser.dart';
import '../action/cast.dart';
import '../action/pick.dart';
import 'sequence.dart';

extension SurroundedByParserExtension<T> on Parser<T> {
  /// Returns a parser that consumes input [before] and [after] the reciever, but
  /// discards their parse results and only returns the result of the reciever.
  ///
  /// If a single [before] parser is provided, the same parser is also used to
  /// consume input afterwards. To skip the [before] or [after] parsing pass an
  /// `epsilon()` parser.
  ///
  /// For example, the parser `digit().surroundedBy(char('['), char(']'))`
  /// returns `'3'` for the input `'[3]'`.
  Parser<T> surroundedBy(Parser<void> before, [Parser<void>? after]) =>
      [before, this, after ?? before].toSequenceParser().pick(1).cast<T>();
}

Fix the example of the spearated by docstring


@deprecated('Use dart:math instead.')
library angular.core.facade.math;

import 'dart:core' show double, num;
import 'dart:math' as math;

const NaN = double.NAN;

class Math {
  static num pow(num x, num exponent) {
    return math.pow(x, exponent);
  }

  static num max(num a, num b) => math.max(a, b);

  static num min(num a, num b) => math.min(a, b);

  static num floor(num a) => a.floor();

  static num ceil(num a) => a.ceil();

  static num sqrt(num x) => math.sqrt(x);

  static num round(num x) => x.round();
}

@Deprecated('Use dart:math instead.')
library angular.core.facade.math;

import 'dart:core' show double, num;
import 'dart:math' as math;

const NaN = double.NAN;

class Math {
  static num pow(num x, num exponent) {
    return math.pow(x, exponent);
  }

  static num max(num a, num b) => math.max(a, b);

  static num min(num a, num b) => math.min(a, b);

  static num floor(num a) => a.floor();

  static num ceil(num a) => a.ceil();

  static num sqrt(num x) => math.sqrt(x);

  static num round(num x) => x.round();
}

Fix the Math facade (improper annotation): @Deprecated(description).

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


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) {
    final settingsState = context.read<SettingsBloc>().state as SettingsSuccess;
    DateTime? currentBackPressTime;

    if (!settingsState.appSettings.doubleTapToExit) return child;

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

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

Fix DoubleTapToExit after setting changes.


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

import 'frame.dart';
import 'trace.dart';

/// A thunk for lazily constructing a [Trace].
typedef Trace TraceThunk();

/// A wrapper around a [TraceThunk]. This works around issue 9579 by avoiding
/// the conversion of native [StackTrace]s to strings until it's absolutely
/// necessary.
class LazyTrace implements Trace {
  final TraceThunk _thunk;
  Trace _inner;

  LazyTrace(this._thunk);

  Trace get _trace {
    if (_inner == null) _inner = _thunk();
    return _inner;
  }

  List<Frame> get frames => _trace.frames;
  StackTrace get vmTrace => _trace.vmTrace;
  Trace get terse => new LazyTrace(() => _trace.terse);
  Trace foldFrames(bool predicate(frame)) =>
    new LazyTrace(() => _trace.foldFrames(predicate));
  String toString() => _trace.toString();
}

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

library lazy_trace;

import 'frame.dart';
import 'trace.dart';

/// A thunk for lazily constructing a [Trace].
typedef Trace TraceThunk();

/// A wrapper around a [TraceThunk]. This works around issue 9579 by avoiding
/// the conversion of native [StackTrace]s to strings until it's absolutely
/// necessary.
class LazyTrace implements Trace {
  final TraceThunk _thunk;
  Trace _inner;

  LazyTrace(this._thunk);

  Trace get _trace {
    if (_inner == null) _inner = _thunk();
    return _inner;
  }

  List<Frame> get frames => _trace.frames;
  StackTrace get vmTrace => _trace.vmTrace;
  Trace get terse => new LazyTrace(() => _trace.terse);
  Trace foldFrames(bool predicate(frame)) =>
    new LazyTrace(() => _trace.foldFrames(predicate));
  String toString() => _trace.toString();

  // Work around issue 14075.
  set frames(_) => throw new UnimplementedError();
}

Work around issue 14125 in stack_trace by adding a dummy setter.

R=rnystrom@google.com
BUG=13945

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

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


part of mustache;

class _CharReader {

  String _source;
  Iterator<int> _itr;
  int _i, _c;
  int _line = 1, _column = 1;

  _CharReader(String source)
      : _source = source,
        _itr = source.runes.iterator {  //FIXME runes etc. Not sure if this is the right count.

    if (source == null)
      throw new ArgumentError('Source is null.');

    _i = 0;

    if (source == '') {
    	_c = _EOF;
    } else {
    	_itr.moveNext();
    	_c = _itr.current;
    }
  }

  int get line => _line;
  int get column => _column;

  int read() {
    var c = _c;
    if (_itr.moveNext()) {
    	_i++;
    	_c = _itr.current;
    } else {
    	_c = _EOF;
    }

    if (c == _NEWLINE) {
    	_line++;
    	_column = 1;
    } else {
    	_column++;
    }

    return c;
  }

  int peek() => _c;

  String readWhile(bool test(int charCode)) {

    if (peek() == _EOF)
      throw new MustacheFormatException('Unexpected end of input.', line, column);

    int start = _i;

    while (peek() != _EOF && test(peek())) {
      read();
    }

    int end = peek() == _EOF ? _source.length : _i;
    return _source.slice(start, end);
  }
}

part of mustache;

class _CharReader {

  String _source;
  Iterator<int> _itr;
  int _i, _c;
  int _line = 1, _column = 1;

  _CharReader(String source)
      : _source = source,
        _itr = source.runes.iterator {  //FIXME runes etc. Not sure if this is the right count.

    if (source == null)
      throw new ArgumentError('Source is null.');

    _i = 0;

    if (source == '') {
    	_c = _EOF;
    } else {
    	_itr.moveNext();
    	_c = _itr.current;
    }
  }

  int get line => _line;
  int get column => _column;

  int read() {
    var c = _c;
    if (_itr.moveNext()) {
    	_i++;
    	_c = _itr.current;
    } else {
    	_c = _EOF;
    }

    if (c == _NEWLINE) {
    	_line++;
    	_column = 1;
    } else {
    	_column++;
    }

    return c;
  }

  int peek() => _c;

  String readWhile(bool test(int charCode)) {

    if (peek() == _EOF)
      throw new MustacheFormatException('Unexpected end of input.', line, column);

    int start = _i;

    while (peek() != _EOF && test(peek())) {
      read();
    }

    int end = peek() == _EOF ? _source.length : _i;
    return _source.substring(start, end);
  }
}

Update to Dart M4 release

Update to Dart M4 release


// 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 "compiler_annotations.dart";

class A {
  int field;

  @DontInline
  A(param) {
    // Currently defeat inlining by using a closure.
    var bar = () => 42;
    field = param + 42;
  }
  A.redirect() : this('foo');
}

main() {
  Expect.equals(42 + 42, new A(42).field);
  Expect.throws(() => new A.redirect(), (e) => e is ArgumentError);
}

// 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 "compiler_annotations.dart";

class A {
  int field;

  @DontInline
  A(param) {
    // Currently defeat inlining by using a closure.
    var bar = () => 42;
    field = param + 42;
  }
  A.redirect() : this('foo');
}

main() {
  Expect.equals(42 + 42, new A(42).field);
  Expect.throws(() => new A.redirect(),
                (e) => e is ArgumentError || e is TypeError);
}

Fix test for checked mode.

Fix test for checked mode.

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

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


library sprites;

import 'dart:sky';
import 'dart:math' as Math;
import 'package:vector_math/vector_math_64.dart';
import 'package:sky/framework/app.dart';
import 'package:sky/framework/rendering/box.dart';
import 'package:sky/framework/rendering/node.dart';
import 'package:sky/framework/scheduler.dart' as scheduler;
import 'package:sky/framework/net/image_cache.dart' as image_cache;

part 'sprite_box.dart';
part 'transform_node.dart';
part 'sprite_node.dart';
part 'image_map.dart';

library sprites;

import 'dart:sky';
import 'dart:math' as Math;
import 'package:vector_math/vector_math_64.dart';
import 'package:sky/framework/app.dart';
import 'package:sky/framework/rendering/box.dart';
import 'package:sky/framework/rendering/object.dart';
import 'package:sky/framework/scheduler.dart' as scheduler;
import 'package:sky/framework/net/image_cache.dart' as image_cache;

part 'sprite_box.dart';
part 'transform_node.dart';
part 'sprite_node.dart';
part 'image_map.dart';

Fix examples/game to work after Hixie's grand rename.

TBR=viktorl@google.com

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


// Copyright (c) 2013, the Clean 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 hop_runner;

import 'package:hop/hop.dart';
import 'package:hop/hop_tasks.dart';
import '../test/test_all.dart' as test_all;

void main (List<String> args) {
  var paths = ['lib/clean_data.dart'];

  addTask('docs', createDartDocTask(paths, linkApi: true));
  addTask('analyze', createAnalyzerTask(paths));
  addTask('test', createUnitTestTask(test_all.run));

  runHop(args);
}

// Copyright (c) 2013, the Clean 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 hop_runner;

import 'package:hop/hop.dart';
import 'package:hop/hop_tasks.dart';
import '../test/test_all.dart' as test_all;

void main (List<String> args) {
  var paths = ['lib/client.dart', 'lib/client_backend.dart',
               'lib/client_browser.dart', 'lib/common.dart', 'lib/server.dart'];

  addTask('docs', createDartDocTask(paths, linkApi: true));
  addTask('analyze', createAnalyzerTask(paths));
  addTask('test', createUnitTestTask(test_all.run));

  runHop(args);
}

Fix library paths in analyze.

Fix library paths in analyze.


import "dart:io";
import "dart:async";
import "dart:convert";

import "../lib/urls.dart" as urls;
import "core.dart";

Codec<Object, List<int>> JSON_TO_BYTES = JSON.fuse(UTF8);

Future createMindMap(HttpRequest request) {
  return Core.instance.createMap().then((mapId) {
      return request.response.redirect(new Uri(path:urls.map.reverse([mapId])));
  });
}

Future addNode(HttpRequest req) {
  var args = urls.addToMap.parse(req.uri.path);
  // assume that we only get one event
  return JSON_TO_BYTES.decoder.bind(req).single.then((data) {
    var contents = data["contents"];
    return Core.instance.addNode(int.parse(args[0]), contents).then((nodeId) {
      req.response.write(JSON_TO_BYTES.encode({
        'id': nodeId
      }));
      return req.response.close();
    });
  });
}

import "dart:io";
import "dart:async";
import "dart:convert";

import "../lib/urls.dart" as urls;
import "core.dart";

Codec<Object, List<int>> JSON_TO_BYTES = JSON.fuse(UTF8);

Future createMindMap(HttpRequest request) {
  return Core.instance.createMap().then((mapId) {
      return request.response.redirect(new Uri(path:urls.map.reverse([mapId])));
  });
}

Future addNode(HttpRequest req) {
  var args = urls.addToMap.parse(req.uri.path);
  // assume that we only get one event
  return JSON_TO_BYTES.decoder.bind(req).single.then((data) {
    return data["contents"];
  }).then((contents) {
    return Core.instance.addNode(int.parse(args[0]), contents);
  }).then((nodeId) {
    req.response.write(JSON_TO_BYTES.encode({
      'id': nodeId
    }));
    return req.response.close();
  });
}

Refactor addNode to be more dart-y

Refactor addNode to be more dart-y

No nested callbacks


import 'dart:async';

import "../SBURBSim.dart";
import "../formats/Formats.dart";
import "../includes/path_utils.dart";
import "resource.dart";

export "resource.dart";

abstract class Loader {

    static Map<String, Resource<dynamic>> _resources = <String, Resource<dynamic>>{};

    static void init() {
        Formats.init();
    }

    static Future<T> getResource<T, U>(String path, [FileFormat<U, T> format]) async {
        if (_resources.containsKey(path)) {
            Resource<dynamic> res = _resources[path];
            if (res is Resource<T>) {
                if (res.object != null) {
                    return res.object;
                } else {
                    return res.addListener();
                }
            } else {
                throw "Requested resource ($path) is ${res.object.runtimeType}. Expected $T";
            }
        } else {
            return _load(path, format);
        }
    }

    static Future<T> _load<T, U>(String path, [FileFormat<U, T> format = null]) {
        if(_resources.containsKey(path)) {
            throw "Resource $path has already been requested for loading";
        }

        if (format == null) {
            String extension = path.split(".").last;
            format = Formats.getFormatForExtension(extension);
        }

        Resource<T> res = new Resource<T>(path);
        _resources[path] = res;

        format.requestFromUrl(PathUtils.adjusted(path))..then((T item) => res.populate(item));

        return res.addListener();
    }
}

import 'dart:async';

import "../SBURBSim.dart";
import "../formats/Formats.dart";
import "../includes/path_utils.dart";
import "resource.dart";

export "resource.dart";

abstract class Loader {

    static Map<String, Resource<dynamic>> _resources = <String, Resource<dynamic>>{};

    static void init() {
        Formats.init();
    }

    static Future<T> getResource<T>(String path, [FileFormat<dynamic, T> format]) async {
        if (_resources.containsKey(path)) {
            Resource<dynamic> res = _resources[path];
            if (res is Resource<T>) {
                if (res.object != null) {
                    return res.object;
                } else {
                    return res.addListener();
                }
            } else {
                throw "Requested resource ($path) is ${res.object.runtimeType}. Expected $T";
            }
        } else {
            return _load(path, format);
        }
    }

    static Future<T> _load<T>(String path, [FileFormat<dynamic, T> format = null]) {
        if(_resources.containsKey(path)) {
            throw "Resource $path has already been requested for loading";
        }

        if (format == null) {
            String extension = path.split(".").last;
            format = Formats.getFormatForExtension(extension);
        }

        Resource<T> res = new Resource<T>(path);
        _resources[path] = res;

        format.requestFromUrl(PathUtils.adjusted(path))..then((T item) => res.populate(item));

        return res.addListener();
    }
}

Remove unnecessary second generic which always ended up dynamic anyway


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

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

class PageBody extends StatelessWidget {
  final Widget child;

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

  @override
  Widget build(BuildContext context) {
    return SafeArea(
      child: Padding(
        padding: const EdgeInsets.all(8.0),
        child: BlocBuilder<SettingsBloc, SettingsState>(
          builder: (context, state) {
            if (state is SettingsSuccess) return child;

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

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

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

class PageBody extends StatelessWidget {
  final Widget child;

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

  @override
  Widget build(BuildContext context) {
    return SafeArea(
      child: BlocBuilder<SettingsBloc, SettingsState>(
        builder: (context, state) {
          if (state is SettingsSuccess) return child;

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

Remove padding from PageBody widget.

Remove padding from PageBody widget.


/*
 * QR.Flutter
 * Copyright (c) 2019 the QR.Flutter authors.
 * See LICENSE for distribution and usage details.
 */
import 'package:flutter/foundation.dart';
import 'package:flutter/widgets.dart';
import 'package:qr/qr.dart';

import 'qr_painter.dart';

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

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

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

/*
 * QR.Flutter
 * Copyright (c) 2019 the QR.Flutter authors.
 * See LICENSE for distribution and usage details.
 */
import 'package:flutter/foundation.dart';
import 'package:flutter/widgets.dart';
import 'package:qr/qr.dart';

import 'qr_painter.dart';

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

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

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

Set gapless mode as the default on QrImage

This shouldn't really create any immediate issues. If you're a fan of the gap, please make sure to set the value explicitly.


part of discord;

/// Sent when a user leaves a guild, can be a leave, kick, or ban.
class GuildMemberRemoveEvent {
  /// The guild the user left.
  Guild guild;

  ///The user that left.
  User user;

  GuildMemberRemoveEvent._new(Client client, Map<String, dynamic> json) {
    if (client.ready) {
      this.guild = client.guilds[json['d']['guild_id']];
      this.user =
          new User._new(client, json['d']['user'] as Map<String, dynamic>);
      guild.members.remove(user.id);
      client._events.onGuildMemberRemove.add(this);
    }
  }
}

part of discord;

/// Sent when a user leaves a guild, can be a leave, kick, or ban.
class GuildMemberRemoveEvent {
  /// The guild the user left.
  Guild guild;

  ///The user that left.
  User user;

  GuildMemberRemoveEvent._new(Client client, Map<String, dynamic> json) {
    if (client.ready && json['d']['user']['id'] != client.user.id) {
      this.guild = client.guilds[json['d']['guild_id']];
      this.user =
          new User._new(client, json['d']['user'] as Map<String, dynamic>);
      guild.members.remove(user.id);
      client._events.onGuildMemberRemove.add(this);
    }
  }
}

Fix crash caused by bot leaving a guild

Fix crash caused by bot leaving a guild


library sintr_worker_lib.instrumentation_lib;

class LogItemProcessor {
  StringBuffer message = new StringBuffer();

  String processLine(String ln) {
    String lastResult = null;

    if (ln.startsWith("~")) {
      lastResult = message.toString();
      message.clear();
    }
    message.write(ln);

    if (lastResult != null) {
      List<String> splits = lastResult.split(":");
      String msgType = splits[1];

      int time = int.parse(splits[0].substring(1));
      if (msgType == "Log" && splits[2] == "SEVERE") return lastResult;
    }
  }

  String close() {
    String lastResult = message.toString();
    List<String> splits = lastResult.split(":");
    String msgType = splits[1];

    int time = int.parse(splits[0].substring(1));
    if (msgType == "Log" && splits[2] == "SEVERE") return lastResult;
  }
}

library sintr_worker_lib.instrumentation_lib;

class LogItemProcessor {
  StringBuffer message = new StringBuffer();

  String processLine(String ln) {
    String lastResult = null;

    if (ln.startsWith("~")) {
      lastResult = message.toString();
      message.clear();
    }
    message.write(ln);

    if (lastResult != null && lastResult != "") {

      if (!lastResult.startsWith("~")) return null;

      List<String> splits = lastResult.split(":");
      String msgType = splits[1];
      int time = int.parse(splits[0].substring(1));
      if (msgType == "Log" && splits[2] == "SEVERE") return lastResult;
    }
  }

  String close() {
    String lastResult = message.toString();

    if (lastResult == null || lastResult == "") return null;
    if (!lastResult.startsWith("~")) return null;

    List<String> splits = lastResult.split(":");
    String msgType = splits[1];

    int time = int.parse(splits[0].substring(1));
    if (msgType == "Log" && splits[2] == "SEVERE") return lastResult;
  }
}

Fix initial line empty bug

Fix initial line empty bug


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

// Test correct loop invariant code motion and type propagation from is-checks
// and null-comparisons.

class B {
  var b;
  B(this.b);
}

class C {
  final f0;

  final a;
  C() : a = new B(0);
}

foo(x) {
  for (var i = 0; i < 10; i++) {
    i + i;
    i + i;
    if (x is C) {
      x.a.b < 0;
    }
  }
}

class Y { var f = null; }

bar(y) {
  var x = y.f;
  for (var i = 0; i < 10; i++) {
    if (x != null) {
      x.a.b < 0;
    }
  }
}

main () {
  var o = new Y();
  o.f = new C();
  bar(o);
  o.f = null;
  bar(o);

  for (var i = 0; i < 1000; i++) bar(o);

  foo(new C());
  foo(0);

  for (var i = 0; i < 1000; i++) foo(0);
}

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

// Test correct loop invariant code motion and type propagation from is-checks
// and null-comparisons.

class B {
  var b;
  B(this.b);
}

class C {
  final f0 = null;

  final a;
  C() : a = new B(0);
}

foo(x) {
  for (var i = 0; i < 10; i++) {
    i + i;
    i + i;
    if (x is C) {
      x.a.b < 0;
    }
  }
}

class Y { var f = null; }

bar(y) {
  var x = y.f;
  for (var i = 0; i < 10; i++) {
    if (x != null) {
      x.a.b < 0;
    }
  }
}

main () {
  var o = new Y();
  o.f = new C();
  bar(o);
  o.f = null;
  bar(o);

  for (var i = 0; i < 1000; i++) bar(o);

  foo(new C());
  foo(0);

  for (var i = 0; i < 1000; i++) foo(0);
}

Fix analyzer warning in a unit test.

Fix analyzer warning in a unit test.

Add initializer for a final field.

TBR=rmacnak@google.com

BUG=

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


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

// Test that a cycle in redirecting factories leads to a compile-time error.

class A {
  factory A.foo() = B;
}

class B<T> implements A {
  factory B() = C.bar;
}

class C<T> implements B {
  factory C.bar() = C.foo;
  factory C.foo() = C
    .bar /// 01: compile-time error
;
  C();
}

main() {
  new A<int>.foo();
}

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

// Test that a cycle in redirecting factories leads to a compile-time error.

class A {
  factory A.foo() = B;
}

class B implements A {
  factory B() = C.bar;
}

class C implements B {
  factory C.bar() = C.foo;
  factory C.foo() = C
    .bar /// 01: compile-time error
;
  C();
}

main() {
  new A.foo();
}

Fix merge error in test.

Fix merge error in test.

R=ngeoffray@google.com

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

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


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

library barback;

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

export 'src/asset.dart';
export 'src/asset_id.dart';
export 'src/asset_provider.dart';
export 'src/errors.dart';
export 'src/transform.dart' show Transform;
export 'src/transformer.dart';

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

export 'src/asset.dart';
export 'src/asset_id.dart';
export 'src/asset_provider.dart';
export 'src/errors.dart';
export 'src/transform.dart' show Transform;
export 'src/transformer.dart';

Remove unneeded imports to fix broken bots.

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

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


part of widgets;

class FloatingActionButton extends StyleComponent {
  static final Style _style = new Style('''
    position: absolute;
    display: flex;
    justify-content: center;
    align-items: center;
    bottom: 16px;
    right: 16px;
    width: 56px;
    height: 56px;
    background-color: #F44336;
    color: white;
    border-radius: 28px;
    box-shadow: 0 10px 20px rgba(0,0,0,0.19), 0 6px 6px rgba(0,0,0,0.23);'''
  );

  Style get style => _style;

  FloatingActionButton({ Object key, Node content }) : super(key: key, content: content);
}

part of widgets;

class FloatingActionButton extends StyleComponent {

  // TODO(rafaelw): Ganesh has problems with box shadows
  // box-shadow: 0 10px 20px rgba(0,0,0,0.19), 0 6px 6px rgba(0,0,0,0.23);

  static final Style _style = new Style('''
    position: absolute;
    display: flex;
    justify-content: center;
    align-items: center;
    bottom: 16px;
    right: 16px;
    width: 56px;
    height: 56px;
    background-color: #F44336;
    color: white;
    border-radius: 28px;'''
  );

  Style get style => _style;

  FloatingActionButton({ Object key, Node content }) : super(key: key, content: content);
}

Remove box shadow on floating action button until ganesh fixes its bug

TBR=abarth

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


// Copyright (c) 2015 Justin Andresen. All rights reserved.
// This software may be modified and distributed under the terms
// of the MIT license. See the LICENSE file for details.

library yaml2toml.src.converter;

import 'dart:async';

import 'package:yaml/yaml.dart';
import 'package:toml/encoder.dart';

/// Converter for YAML to TOML.
class Yaml2TomlConverter {

  /// Converts a YAML document to a TOML document.
  ///
  /// [yaml] contains the contents of the YAML document.
  /// Returns a [Future] of the generted TOML document.
  Future<String> convert(String yaml){
    var encoder = new TomlEncoder();
    return new Future.microtask(
        () => encoder.encode(loadYaml(yaml)));
  }

}

// Copyright (c) 2015 Justin Andresen. All rights reserved.
// This software may be modified and distributed under the terms
// of the MIT license. See the LICENSE file for details.

library yaml2toml.src.converter;

import 'dart:async';

import 'package:yaml/yaml.dart';
import 'package:toml/encoder.dart';

/// Converter for YAML to TOML.
class Yaml2TomlConverter {

  /// Converts a YAML document to a TOML document.
  ///
  /// [yaml] contains the contents of the YAML document.
  /// Returns a future of the generted TOML document.
  Future<String> convert(String yaml){
    var encoder = new TomlEncoder();
    return new Future.microtask(
        () => encoder.encode(loadYaml(yaml)));
  }

}

Remove dartdoc reference to external class.


// Copyright (c) 2013, the polymer_elements.dart project authors.  Please see
// the AUTHORS file for details. All rights reserved. Use of this source code is
// governed by a BSD-style license that can be found in the LICENSE file.
// This work is a port of the polymer-elements from the Polymer project,
// http://www.polymer-project.org/.

library polymer_elements.polymer_signals;

import 'dart:html';

import 'package:polymer/polymer.dart';

@CustomTag('polymer-signals')
class PolymerSignals extends PolymerElement {

  PolymerSignals.created() : super.created();

      enteredView() {
        _signals.add(this);
      }

      leftView() {
        _signals.remove(this);
      }
}

// private shared database
List _signals = [];
// signal dispatcher
_notify(name, data) {
  // convert generic-signal event to named-signal event
  var signal = new CustomEvent('polymersignal' + name,
    canBubble: true,
    detail: data
  );
  // dispatch named-signal to all 'signals' instances,
  // only interested listeners will react
  _signals.forEach((s) {
    s.dispatchEvent(signal);
  });
}

@initMethod
registerListener(){
// signal listener at document
  document.addEventListener('polymer-signal', (e) {
    _notify(e.detail['name'], e.detail['data']);
  });
}

// Copyright (c) 2013, the polymer_elements.dart project authors.  Please see
// the AUTHORS file for details. All rights reserved. Use of this source code is
// governed by a BSD-style license that can be found in the LICENSE file.
// This work is a port of the polymer-elements from the Polymer project,
// http://www.polymer-project.org/.

library polymer_elements.polymer_signals;

import 'dart:html';

import 'package:polymer/polymer.dart';

@CustomTag('polymer-signals')
class PolymerSignals extends PolymerElement {

  PolymerSignals.created() : super.created();

      enteredView() {
        _signals.add(this);
      }

      leftView() {
        _signals.remove(this);
      }
}

// private shared database
List _signals = [];
// signal dispatcher
_notify(name, data) {
  // convert generic-signal event to named-signal event
  var signal = new CustomEvent('polymer-signal' + name,
    canBubble: true,
    detail: data
  );
  // dispatch named-signal to all 'signals' instances,
  // only interested listeners will react
  _signals.forEach((s) {
    s.dispatchEvent(signal);
  });
}

@initMethod
registerListener(){
// signal listener at document
  document.addEventListener('polymer-signal', (e) {
    _notify(e.detail['name'], e.detail['data']);
  });
}

Rename events now that dashes are supported


// 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 'layout2.dart';
import 'dart:sky' as sky;

class AppView {
  RenderView _renderView;

  void _beginFrame(double timeStamp) {
    RenderNode.flushLayout();
    _renderView.paintFrame();
  }

  void _handleEvent(sky.Event event) {
    if (event is! sky.PointerEvent)
      return;
    HitTestResult result = new HitTestResult();
    _renderView.hitTest(result, x: event.x, y: event.y);
    result.path.reversed.forEach((RenderNode node) {
      node.handlePointer(event);
    });
  }

  AppView(RenderBox root) {
    sky.view.setEventCallback(_handleEvent);
    sky.view.setBeginFrameCallback(_beginFrame);

    _renderView = new RenderView(root: root);
    _renderView.layout(newWidth: sky.view.width, newHeight: sky.view.height);

    sky.view.scheduleFrame();
  }
}

// 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 'layout2.dart';
import 'dart:sky' as sky;

class AppView {

  AppView(RenderBox root) {
    sky.view.setEventCallback(_handleEvent);
    sky.view.setBeginFrameCallback(_beginFrame);

    _renderView = new RenderView(root: root);
    _renderView.layout(newWidth: sky.view.width, newHeight: sky.view.height);

    sky.view.scheduleFrame();
  }

  RenderView _renderView;

  void _beginFrame(double timeStamp) {
    RenderNode.flushLayout();
    _renderView.paintFrame();
  }

  void _handleEvent(sky.Event event) {
    if (event is! sky.PointerEvent)
      return;
    HitTestResult result = new HitTestResult();
    _renderView.hitTest(result, x: event.x, y: event.y);
    result.path.reversed.forEach((RenderNode node) {
      node.handlePointer(event);
    });
  }

}

Rearrange AppView so that the constructor is first.

R=abarth@chromium.org

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


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

import 'package:logging/logging.dart' as logging;

logging.Logger _logger = new logging.Logger("sintr_common");

info(String message) => _logger.info(message);
trace(String message) => _logger.finer(message);
debug(String message) => _logger.fine(message);
alert(String message) => _logger.shout(message);

perf(String name, int ms) => _logger.fine("PERF: $name : $ms");

/// Setup log streaming to the right place for local and remote deployment.
setupLogging() {
  // TODO(lukechurch): Add support for container logs
  _setupLocalLogging();
}

/// Setup log streaming to stdOut.
_setupLocalLogging() {
  // Setup the logging
  logging.hierarchicalLoggingEnabled = false;
  logging.Logger.root.level = logging.Level.FINER;
  logging.Logger.root.onRecord.listen((logging.LogRecord rec) {
    print('${rec.level.name}: ${rec.time}: ${rec.message}');
  });
}

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

import 'package:logging/logging.dart' as logging;

logging.Logger _logger;

info(String message) => _logger.info(message);
trace(String message) => _logger.finer(message);
debug(String message) => _logger.fine(message);
alert(String message) => _logger.shout(message);

perf(String name, int ms) => _logger.fine("PERF: $name : $ms");

/// Setup log streaming to the right place for local and remote deployment.
setupLogging([String loggerName = "sintr_common"]) {
  _logger = new logging.Logger(loggerName);

  // TODO(lukechurch): Add support for container logs
  _setupLocalLogging();
}

/// Setup log streaming to stdOut.
_setupLocalLogging() {
  // Setup the logging
  logging.hierarchicalLoggingEnabled = false;
  logging.Logger.root.level = logging.Level.ALL;
  logging.Logger.root.onRecord.listen((logging.LogRecord rec) {
    print('${rec.loggerName}: ${rec.level.name}: ${rec.time}: ${rec.message}');
  });
}

Include logging group in the messages

Include logging group in the messages


part of classes;

final String driverURL = 'http://ergast.com/api/f1/drivers.json?limit=1000';

class Driver {
    static List drivers = [];

    static final Random indexGen = new Random();

    String _url;
    String _givenName;
    String _familyName;
    String _dateOfBirth;
    String _nationality;

    String get url         => _url;
    String get fullName    => '$_givenName $_familyName';
    String get dateOfBirth => _dateOfBirth;
    String get nationality => _nationality;

    Driver() {
        var index = indexGen.nextInt(drivers.length);

        _url         = drivers[index]['url'];
        _givenName   = drivers[index]['givenName'];
        _familyName  = drivers[index]['familyName'];
        _dateOfBirth = drivers[index]['dateOfBirth'];
        _nationality = drivers[index]['nationality'];
    }

    static Future getDrivers() {
        var path = driverURL;
        return HttpRequest.getString(path)
            .then(_parseDriversFromJSON);
    }

    static _parseDriversFromJSON(String jsonString) {
        Map driversResult = JSON.decode(jsonString);
        drivers = driversResult['MRData']['DriverTable']['Drivers'];
    }
}

part of classes;

final String driverURL = 'http://ergast.com/api/f1/drivers.json?limit=1000';

class Driver {
    static List drivers = [];

    static final Random indexGen = new Random();

    String _url;
    String _givenName;
    String _familyName;
    String _nationality;
    DateTime _dateOfBirth;

    String get url         => _url;
    String get fullName    => '$_givenName $_familyName';
    String get nationality => _nationality;
    String get dateOfBirth => '${_dateOfBirth.day}/${_dateOfBirth.month}/${_dateOfBirth.year}';

    Driver() {
        var i = indexGen.nextInt(drivers.length);

        _url         = drivers[i]['url'];
        _givenName   = drivers[i]['givenName'];
        _familyName  = drivers[i]['familyName'];
        _nationality = drivers[i]['nationality'];
        _dateOfBirth = DateTime.parse(drivers[i]['dateOfBirth']);
    }

    static Future getDrivers() {
        var path = driverURL;
        return HttpRequest.getString(path)
            .then(_parseDriversFromJSON);
    }

    static _parseDriversFromJSON(String jsonString) {
        Map driversResult = JSON.decode(jsonString);
        drivers = driversResult['MRData']['DriverTable']['Drivers'];
    }
}

Format dateOfBirth as DateTime object

Format dateOfBirth as DateTime object


// 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',
  host: const {
    '[class.focus]': 'visualFocus',
    '[class.active]': 'isActive || isMouseDown',
  },
  template: r'''
          <div class="content">
            {{label}}
          </div>
          <material-ripple></material-ripple>
        ''',
  styleUrls: const ['tab_button.scss.css'],
  directives: const [MaterialRippleComponent],
  // TODO(google): Change to `Visibility.local` to reduce code size.
  visibility: Visibility.all,
)
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;
}

// 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',
  host: const {
    '[class.focus]': 'visualFocus',
    '[class.active]': 'isActive || isMouseDown',
  },
  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;
}

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

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

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

PiperOrigin-RevId: 190251676


part of tmx;

class ObjectGroup {
  String name;
  String color;

  double opacity = 1.0;
  bool visible = true;

  TileMap map;

  Map<String, String> properties = {};
  List<TmxObject> tmxObjects = [];

  ObjectGroup.fromXML(XmlElement element) {
    if (element == null) { throw 'arg "element" cannot be null'; }

    NodeDSL.on(element, (dsl) {
      name = dsl.strOr('name', name);
      color = dsl.strOr('color', color);
      opacity = dsl.doubleOr('opacity', opacity);
      visible = dsl.boolOr('visible', visible);
    });

    properties = TileMapParser._parseProperties(TileMapParser._getPropertyNodes(element));

    var objectNodes = element.children
        .where((node) => node is XmlElement)
        .where((node) => node.name.local == 'object');
    tmxObjects = objectNodes.map((objectNode) =>  new TmxObject.fromXML(objectNode));
  }
}

part of tmx;

class ObjectGroup {
  String name;
  String color;

  double opacity = 1.0;
  bool visible = true;

  TileMap map;

  Map<String, String> properties = {};
  List<TmxObject> tmxObjects = [];

  ObjectGroup.fromXML(XmlElement element) {
    if (element == null) { throw 'arg "element" cannot be null'; }

    NodeDSL.on(element, (dsl) {
      name = dsl.strOr('name', name);
      color = dsl.strOr('color', color);
      opacity = dsl.doubleOr('opacity', opacity);
      visible = dsl.boolOr('visible', visible);
    });

    properties = TileMapParser._parseProperties(TileMapParser._getPropertyNodes(element));

    var objectNodes = element.children
        .where((node) => node is XmlElement)
        .where((node) => node.name.local == 'object');
    tmxObjects = objectNodes.map((objectNode)
      =>  new TmxObject.fromXML(objectNode)).toList();
  }
}

Convert from Iterable to List.

Convert from Iterable to List.


import 'package:source_span/source_span.dart';

import '../token.dart';
import 'definition.dart';
import 'directive.dart';
import 'selection_set.dart';
import 'variable_definitions.dart';

class OperationDefinitionContext extends DefinitionContext {
  final Token TYPE, NAME;
  final VariableDefinitionsContext variableDefinitions;
  final List<DirectiveContext> directives = [];
  final SelectionSetContext selectionSet;

  bool get isMutation => TYPE?.text == 'mutation';

  bool get isQuery => TYPE?.text == 'query' || TYPE == null;

  String get name => NAME?.text;

  OperationDefinitionContext(
      this.TYPE, this.NAME, this.variableDefinitions, this.selectionSet) {
    assert(TYPE == null || TYPE.text == 'query' || TYPE.text == 'mutation');
  }

  @override
  FileSpan get span {
    if (TYPE == null) return selectionSet.span;
    var out = TYPE.span.expand(NAME.span);
    out = directives.fold<FileSpan>(out, (o, d) => o.expand(d.span));
    return out.expand(selectionSet.span);
  }
}

import 'package:source_span/source_span.dart';

import '../token.dart';
import 'definition.dart';
import 'directive.dart';
import 'selection_set.dart';
import 'variable_definitions.dart';

class OperationDefinitionContext extends DefinitionContext {
  final Token TYPE, NAME;
  final VariableDefinitionsContext variableDefinitions;
  final List<DirectiveContext> directives = [];
  final SelectionSetContext selectionSet;

  bool get isMutation => TYPE?.text == 'mutation';

  bool get isQuery => TYPE?.text == 'query' || TYPE == null;

  String get name => NAME?.text;

  OperationDefinitionContext(
      this.TYPE, this.NAME, this.variableDefinitions, this.selectionSet) {
    assert(TYPE == null || TYPE.text == 'query' || TYPE.text == 'mutation');
  }

  @override
  FileSpan get span {
    if (TYPE == null) return selectionSet.span;
    var out = NAME == null ? TYPE.span : TYPE.span.expand(NAME.span);
    out = directives.fold<FileSpan>(out, (o, d) => o.expand(d.span));
    return out.expand(selectionSet.span);
  }
}

Fix span expansion when operation name is null


/*
 * Package : Cbor
 * Author : S. Hamblett <steve.hamblett@linux.com>
 * Date   : 12/12/2016
 * Copyright :  S.Hamblett
 */

part of cbor;

/// The standard output class.
class OutputStandard extends Output {
  /// Construction
  @override
  OutputStandard() {
    this._buffer = new typed.Uint8Buffer();
    this._pauseBuffer = new typed.Uint8Buffer();
  }

  @override
  void clear() {
    _buffer.clear();
  }

  @override
  int size() {
    return _buffer.length;
  }

  void putByte(int value) {
    _buffer.add(value);
  }

  void putBytes(typed.Uint8Buffer data) {
    _buffer.addAll(data);
  }

  void mark() {
    _markPos = _buffer.length;
  }

  void resetToMark() {
    if (_buffer.length > _markPos) {
      _buffer.removeRange(_markPos, _buffer.length);
    }
  }

  void pause() {
    if (!_paused) {
      _pauseBuffer.clear();
      _pauseBuffer.addAll(_buffer);
      _buffer.clear();
      _paused = true;
    }
  }

  void restart([bool append = false]) {
    if (_paused) {
      if (append) {
        _pauseBuffer.addAll(_buffer);
      }
      _buffer.clear();
      _buffer.addAll(_pauseBuffer);
      _paused = false;
    }
  }

  /// Additional methods.

  List<int> getDataAsList() {
    return _buffer.toList();
  }
}

/*
 * Package : Cbor
 * Author : S. Hamblett <steve.hamblett@linux.com>
 * Date   : 12/12/2016
 * Copyright :  S.Hamblett
 */

part of cbor;

/// The standard output class.
class OutputStandard extends Output {
  /// Construction
  @override
  OutputStandard() {
    _buffer = typed.Uint8Buffer();
    _pauseBuffer = typed.Uint8Buffer();
  }

  @override
  void clear() {
    _buffer.clear();
  }

  @override
  int size() => _buffer.length;

  @override
  void putByte(int value) {
    _buffer.add(value);
  }

  @override
  void putBytes(typed.Uint8Buffer data) {
    _buffer.addAll(data);
  }

  @override
  void mark() {
    _markPos = _buffer.length;
  }

  @override
  void resetToMark() {
    if (_buffer.length > _markPos) {
      _buffer.removeRange(_markPos, _buffer.length);
    }
  }

  @override
  void pause() {
    if (!_paused) {
      _pauseBuffer.clear();
      _pauseBuffer.addAll(_buffer);
      _buffer.clear();
      _paused = true;
    }
  }

  @override
  void restart([bool append = false]) {
    if (_paused) {
      if (append) {
        _pauseBuffer.addAll(_buffer);
      }
      _buffer.clear();
      _buffer.addAll(_pauseBuffer);
      _paused = false;
    }
  }

  /// Additional methods.

  List<int> getDataAsList() => _buffer.toList();
}

Update to Dart 2.6.1, linter updates and general tidy up