content_type
stringclasses
8 values
main_lang
stringclasses
7 values
message
stringlengths
1
50
sha
stringlengths
40
40
patch
stringlengths
52
962k
file_count
int64
1
300
Javascript
Javascript
prevent npe when module definition outside of it
5c735eb4ab07144a62949472ed388cb185099201
<ide><path>src/ngMock/angular-mocks.js <ide> window.jstestdriver && (function(window) { <ide> try { <ide> injector.invoke(blockFns[i] || angular.noop, this); <ide> } catch (e) { <del> if(e.stack) e.stack += '\n' + errorForStack.stack; <add> if(e.stack && errorForStack) e.stack += '\n' + errorForStack.stack; <ide> throw e; <ide> } finally { <ide> errorForStack = null;
1
Go
Go
update error return in bridge driver's getnetwork
df56ce5f4768a46b61cb6300c2cb1ad8b7493f60
<ide><path>libnetwork/drivers/bridge/bridge.go <ide> func (d *driver) getNetwork(id types.UUID) (*bridgeNetwork, error) { <ide> return nw, nil <ide> } <ide> <del> return nil, nil <add> return nil, types.NotFoundErrorf("network not found: %s", id) <ide> } <ide> <ide> func parseNetworkGenericOptions(data interface{}) (*networkConfiguration, error) {
1
Javascript
Javascript
utilize cache object
b9d2369f3d0e601f1d5ddc05e5008e931bac9003
<ide><path>packages/ember-handlebars/lib/helpers/binding.js <ide> import jQuery from "ember-views/system/jquery"; <ide> import { isArray } from "ember-metal/utils"; <ide> import { getEscaped as handlebarsGetEscaped } from "ember-handlebars/ext"; <ide> import keys from "ember-runtime/keys"; <add>import Cache from "ember-metal/cache"; <ide> <ide> import { <ide> _HandlebarsBoundView, <ide> function _triageMustacheHelper(property, options) { <ide> return helpers.bind.call(this, property, options); <ide> } <ide> <add>export var ISNT_HELPER_CACHE = new Cache(1000, function(key) { <add> return key.indexOf('-') === -1; <add>}); <add> <ide> /** <ide> Used to lookup/resolve handlebars helpers. The lookup order is: <ide> <ide> function resolveHelper(container, name) { <ide> return helpers[name]; <ide> } <ide> <del> if (!container || name.indexOf('-') === -1) { <add> if (!container || ISNT_HELPER_CACHE.get(name)) { <ide> return; <ide> } <ide> <ide> function boundIfHelper(property, fn) { <ide> return bind.call(context, property, fn, true, shouldDisplayIfHelperContent, shouldDisplayIfHelperContent, ['isTruthy', 'length']); <ide> } <ide> <del> <ide> /** <ide> @private <ide> <ide><path>packages/ember-metal/lib/binding.js <ide> import { <ide> _suspendObserver <ide> } from "ember-metal/observer"; <ide> import run from "ember-metal/run_loop"; <add>import { <add> isGlobal as isGlobalPath <add>} from "ember-metal/path_cache"; <add> <ide> <ide> // ES6TODO: where is Ember.lookup defined? <ide> /** <ide> import run from "ember-metal/run_loop"; <ide> */ <ide> Ember.LOG_BINDINGS = false || !!Ember.ENV.LOG_BINDINGS; <ide> <del>var IS_GLOBAL = /^([A-Z$]|([0-9][A-Z$]))/; <del> <ide> /** <ide> Returns true if the provided path is global (e.g., `MyApp.fooController.bar`) <ide> instead of local (`foo.bar.baz`). <ide> var IS_GLOBAL = /^([A-Z$]|([0-9][A-Z$]))/; <ide> @param {String} path <ide> @return Boolean <ide> */ <del>function isGlobalPath(path) { <del> return IS_GLOBAL.test(path); <del>} <ide> <ide> function getWithGlobals(obj, path) { <ide> return get(isGlobalPath(path) ? Ember.lookup : obj, path); <ide><path>packages/ember-metal/lib/main.js <ide> import { <ide> } from "ember-metal/utils"; <ide> import EmberError from "ember-metal/error"; <ide> import EnumerableUtils from "ember-metal/enumerable_utils"; <del> <add>import Cache from "ember-metal/cache"; <ide> import {create, platform} from "ember-metal/platform"; <ide> import {map, forEach, filter, indexOf} from "ember-metal/array"; <ide> import Logger from "ember-metal/logger"; <ide> EmberInstrumentation.reset = reset; <ide> Ember.instrument = instrument; <ide> Ember.subscribe = subscribe; <ide> <add>Ember._Cache = Cache; <add> <ide> Ember.generateGuid = generateGuid; <ide> Ember.GUID_KEY = GUID_KEY; <ide> Ember.create = create; <ide><path>packages/ember-metal/lib/path_cache.js <add>import Cache from 'ember-metal/cache'; <add> <add>var IS_GLOBAL = /^([A-Z$]|([0-9][A-Z$]))/; <add>var IS_GLOBAL_PATH = /^([A-Z$]|([0-9][A-Z$])).*[\.]/; <add>var HAS_THIS = 'this.'; <add> <add>var isGlobalCache = new Cache(1000, function(key) { return IS_GLOBAL.test(key); }); <add>var isGlobalPathCache = new Cache(1000, function(key) { return IS_GLOBAL_PATH.test(key); }); <add>var hasThisCache = new Cache(1000, function(key) { return key.indexOf(HAS_THIS) !== -1; }); <add>var isPathCache = new Cache(1000, function(key) { return key.indexOf('.') !== -1; }); <add> <add>export var caches = { <add> isGlobalCache: isGlobalCache, <add> isGlobalPathCache: isGlobalPathCache, <add> hasThisCache: hasThisCache, <add> isPathCache: isPathCache <add>}; <add> <add>export function isGlobal(path) { <add> return isGlobalCache.get(path); <add>} <add> <add>export function isGlobalPath(path) { <add> return isGlobalPathCache.get(path); <add>} <add> <add>export function hasThis(path) { <add> return hasThisCache.get(path); <add>} <add> <add>export function isPath(path) { <add> return isPathCache.get(path); <add>} <ide><path>packages/ember-metal/lib/properties.js <ide> import { overrideChains } from "ember-metal/property_events"; <ide> import { get } from "ember-metal/property_get"; <ide> import { set } from "ember-metal/property_set"; <ide> <del>var metaFor = meta, <del> objectDefineProperty = platform.defineProperty; <add>var metaFor = meta; <add>var objectDefineProperty = platform.defineProperty; <ide> <ide> var MANDATORY_SETTER = Ember.ENV.MANDATORY_SETTER; <ide> <ide><path>packages/ember-metal/lib/property_events.js <ide> var deferred = 0; <ide> @return {void} <ide> */ <ide> function propertyWillChange(obj, keyName) { <del> var m = obj[META_KEY], <del> watching = (m && m.watching[keyName] > 0) || keyName === 'length', <del> proto = m && m.proto, <del> desc = m && m.descs[keyName]; <add> var m = obj[META_KEY]; <add> var watching = (m && m.watching[keyName] > 0) || keyName === 'length'; <add> var proto = m && m.proto; <add> var desc = m && m.descs[keyName]; <ide> <ide> if (!watching) { return; } <ide> if (proto === obj) { return; } <ide> function propertyWillChange(obj, keyName) { <ide> @return {void} <ide> */ <ide> function propertyDidChange(obj, keyName) { <del> var m = obj[META_KEY], <del> watching = (m && m.watching[keyName] > 0) || keyName === 'length', <del> proto = m && m.proto, <del> desc = m && m.descs[keyName]; <add> var m = obj[META_KEY]; <add> var watching = (m && m.watching[keyName] > 0) || keyName === 'length'; <add> var proto = m && m.proto; <add> var desc = m && m.descs[keyName]; <ide> <ide> if (proto === obj) { return; } <ide> <ide> function chainsWillChange(obj, keyName, m) { <ide> return; <ide> } <ide> <del> var nodes = m.chainWatchers[keyName], <del> events = [], <del> i, l; <add> var nodes = m.chainWatchers[keyName]; <add> var events = []; <add> var i, l; <ide> <ide> for(i = 0, l = nodes.length; i < l; i++) { <ide> nodes[i].willChange(events); <ide> function chainsDidChange(obj, keyName, m, suppressEvents) { <ide> return; <ide> } <ide> <del> var nodes = m.chainWatchers[keyName], <del> events = suppressEvents ? null : [], <del> i, l; <add> var nodes = m.chainWatchers[keyName]; <add> var events = suppressEvents ? null : []; <add> var i, l; <ide> <ide> for(i = 0, l = nodes.length; i < l; i++) { <ide> nodes[i].didChange(events); <ide><path>packages/ember-metal/lib/property_get.js <ide> import Ember from "ember-metal/core"; <ide> import { META_KEY } from "ember-metal/utils"; <ide> import EmberError from "ember-metal/error"; <del> <del>var get; <add>import { <add> isGlobalPath, <add> isPath, <add> hasThis as pathHasThis <add>} from "ember-metal/path_cache"; <ide> <ide> var MANDATORY_SETTER = Ember.ENV.MANDATORY_SETTER; <del> <del>var IS_GLOBAL_PATH = /^([A-Z$]|([0-9][A-Z$])).*[\.]/; <del>var HAS_THIS = 'this.'; <ide> var FIRST_KEY = /^([^\.]+)/; <ide> <ide> // .......................................................... <ide> var get = function get(obj, keyName) { <ide> return obj; <ide> } <ide> <del> if (!keyName && 'string'===typeof obj) { <add> if (!keyName && 'string' === typeof obj) { <ide> keyName = obj; <ide> obj = null; <ide> } <ide> var get = function get(obj, keyName) { <ide> <ide> var meta = obj[META_KEY], desc = meta && meta.descs[keyName], ret; <ide> <del> if (desc === undefined && keyName.indexOf('.') !== -1) { <add> if (desc === undefined && isPath(keyName)) { <ide> return _getPath(obj, keyName); <ide> } <ide> <ide> if (Ember.config.overrideAccessors) { <ide> @return {Array} a temporary array with the normalized target/path pair. <ide> */ <ide> function normalizeTuple(target, path) { <del> var hasThis = path.indexOf(HAS_THIS) === 0, <del> isGlobal = !hasThis && IS_GLOBAL_PATH.test(path), <del> key; <add> var hasThis = pathHasThis(path); <add> var isGlobal = !hasThis && isGlobalPath(path); <add> var key; <ide> <ide> if (!target || isGlobal) target = Ember.lookup; <ide> if (hasThis) path = path.slice(5); <ide> function _getPath(root, path) { <ide> // If there is no root and path is a key name, return that <ide> // property from the global object. <ide> // E.g. get('Ember') -> Ember <del> if (root === null && path.indexOf('.') === -1) { return get(Ember.lookup, path); } <add> if (root === null && !isPath(path)) { <add> return get(Ember.lookup, path); <add> } <ide> <ide> // detect complicated paths and normalize them <del> hasThis = path.indexOf(HAS_THIS) === 0; <add> hasThis = pathHasThis(path); <ide> <ide> if (!root || hasThis) { <ide> tuple = normalizeTuple(root, path); <ide><path>packages/ember-metal/lib/property_set.js <ide> import { <ide> } from "ember-metal/property_events"; <ide> import { defineProperty } from "ember-metal/properties"; <ide> import EmberError from "ember-metal/error"; <add>import { <add> isPath <add>} from "ember-metal/path_cache"; <add> <ide> <ide> var MANDATORY_SETTER = Ember.ENV.MANDATORY_SETTER; <ide> var IS_GLOBAL = /^([A-Z$]|([0-9][A-Z$]))/; <ide> var set = function set(obj, keyName, value, tolerant) { <ide> var meta = obj[META_KEY], desc = meta && meta.descs[keyName], <ide> isUnknown, currentValue; <ide> <del> if (desc === undefined && keyName.indexOf('.') !== -1) { <add> if (desc === undefined && isPath(keyName)) { <ide> return setPath(obj, keyName, value, tolerant); <ide> } <ide> <ide><path>packages/ember-runtime/lib/system/string.js <ide> import { <ide> inspect as emberInspect <ide> } from "ember-metal/utils"; <ide> <add>import Cache from "ember-metal/cache"; <add> <ide> var STRING_DASHERIZE_REGEXP = (/[ _]/g); <del>var STRING_DASHERIZE_CACHE = {}; <add> <add>var STRING_DASHERIZE_CACHE = new Cache(1000, function(key) { <add> return decamelize(key).replace(STRING_DASHERIZE_REGEXP, '-'); <add>}); <add> <add>var CAMELIZE_CACHE = new Cache(1000, function(key) { <add> return key.replace(STRING_CAMELIZE_REGEXP, function(match, separator, chr) { <add> return chr ? chr.toUpperCase() : ''; <add> }).replace(/^([A-Z])/, function(match, separator, chr) { <add> return match.toLowerCase(); <add> }); <add>}); <add> <add>var CLASSIFY_CACHE = new Cache(1000, function(str) { <add> var parts = str.split("."), <add> out = []; <add> <add> for (var i=0, l=parts.length; i<l; i++) { <add> var camelized = camelize(parts[i]); <add> out.push(camelized.charAt(0).toUpperCase() + camelized.substr(1)); <add> } <add> <add> return out.join("."); <add>}); <add> <add>var UNDERSCORE_CACHE = new Cache(1000, function(str) { <add> return str.replace(STRING_UNDERSCORE_REGEXP_1, '$1_$2'). <add> replace(STRING_UNDERSCORE_REGEXP_2, '_').toLowerCase(); <add>}); <add> <add>var CAPITALIZE_CACHE = new Cache(1000, function(str) { <add> return str.charAt(0).toUpperCase() + str.substr(1); <add>}); <add> <add>var DECAMELIZE_CACHE = new Cache(1000, function(str) { <add> return str.replace(STRING_DECAMELIZE_REGEXP, '$1_$2').toLowerCase(); <add>}); <add> <ide> var STRING_DECAMELIZE_REGEXP = (/([a-z\d])([A-Z])/g); <ide> var STRING_CAMELIZE_REGEXP = (/(\-|_|\.|\s)+(.)?/g); <ide> var STRING_UNDERSCORE_REGEXP_1 = (/([a-z\d])([A-Z]+)/g); <ide> function w(str) { <ide> } <ide> <ide> function decamelize(str) { <del> return str.replace(STRING_DECAMELIZE_REGEXP, '$1_$2').toLowerCase(); <add> return DECAMELIZE_CACHE.get(str); <ide> } <ide> <ide> function dasherize(str) { <del> var cache = STRING_DASHERIZE_CACHE, <del> hit = cache.hasOwnProperty(str), <del> ret; <del> <del> if (hit) { <del> return cache[str]; <del> } else { <del> ret = decamelize(str).replace(STRING_DASHERIZE_REGEXP,'-'); <del> cache[str] = ret; <del> } <del> <del> return ret; <add> return STRING_DASHERIZE_CACHE.get(str); <ide> } <ide> <ide> function camelize(str) { <del> return str.replace(STRING_CAMELIZE_REGEXP, function(match, separator, chr) { <del> return chr ? chr.toUpperCase() : ''; <del> }).replace(/^([A-Z])/, function(match, separator, chr) { <del> return match.toLowerCase(); <del> }); <add> return CAMELIZE_CACHE.get(str); <ide> } <ide> <ide> function classify(str) { <del> var parts = str.split("."), <del> out = []; <del> <del> for (var i=0, l=parts.length; i<l; i++) { <del> var camelized = camelize(parts[i]); <del> out.push(camelized.charAt(0).toUpperCase() + camelized.substr(1)); <del> } <del> <del> return out.join("."); <add> return CLASSIFY_CACHE.get(str); <ide> } <ide> <ide> function underscore(str) { <del> return str.replace(STRING_UNDERSCORE_REGEXP_1, '$1_$2'). <del> replace(STRING_UNDERSCORE_REGEXP_2, '_').toLowerCase(); <add> return UNDERSCORE_CACHE.get(str); <ide> } <ide> <ide> function capitalize(str) { <del> return str.charAt(0).toUpperCase() + str.substr(1); <add> return CAPITALIZE_CACHE.get(str); <ide> } <ide> <ide> /**
9
Javascript
Javascript
fix indexof and object.keys for ie8
81859d278cd3fa78f0d25fb5a0b4e4b6e31f2d87
<ide><path>src/lib/locale/locales.js <ide> import compareArrays from '../utils/compare-arrays'; <ide> import { deprecateSimple } from '../utils/deprecate'; <ide> import { mergeConfigs } from './set'; <ide> import { Locale } from './constructor'; <add>import keys from '../utils/keys'; <ide> <ide> // internal storage for locale config files <ide> var locales = {}; <ide> export function getLocale (key) { <ide> } <ide> <ide> export function listLocales() { <del> return Object.keys(locales); <add> return keys(locales); <ide> } <ide><path>src/lib/utils/keys.js <add>import hasOwnProp from './has-own-prop'; <add> <add>var keys; <add> <add>if (Object.keys) { <add> keys = Object.keys; <add>} else { <add> keys = function (obj) { <add> var i, res = []; <add> for (i in obj) { <add> if (hasOwnProp(obj, i)) { <add> res.push(i); <add> } <add> } <add> return res; <add> }; <add>} <add> <add>export { keys as default }; <ide><path>src/test/moment/locale.js <ide> import { module, test } from '../qunit'; <ide> import moment from '../../moment'; <ide> import each from '../helpers/each'; <add>import indexOf from '../../lib/utils/index-of'; <ide> <ide> module('locale', { <ide> setup : function () { <ide> test('defineLocale', function (assert) { <ide> <ide> test('locales', function (assert) { <ide> moment.defineLocale('dude', {months: ['Movember']}); <del> assert.equal(true, !!~moment.locales().indexOf('dude'), 'locales returns an array of defined locales'); <del> assert.equal(true, !!~moment.locales().indexOf('en'), 'locales should always include english'); <add> assert.equal(true, !!~indexOf.call(moment.locales(), 'dude'), 'locales returns an array of defined locales'); <add> assert.equal(true, !!~indexOf.call(moment.locales(), 'en'), 'locales should always include english'); <ide> moment.defineLocale('dude', null); <ide> }); <ide>
3
PHP
PHP
bind real paths into container
f6b3c2d56cbb71d5413e8b27226a380591adda85
<ide><path>src/Illuminate/Foundation/Application.php <ide> public function redirectIfTrailingSlash() <ide> */ <ide> public function bindInstallPaths(array $paths) <ide> { <del> $this->instance('path', $paths['app']); <add> $this->instance('path', realpath($paths['app'])); <ide> <ide> foreach (array_except($paths, array('app')) as $key => $value) <ide> { <del> $this->instance("path.{$key}", $value); <add> $this->instance("path.{$key}", realpath($value)); <ide> } <ide> } <ide>
1
Ruby
Ruby
fix typo in strong params hash deprecation message
385e0a3311960032fa149f8650d73fd483dc5f75
<ide><path>actionpack/lib/action_controller/metal/strong_parameters.rb <ide> def stringify_keys # :nodoc: <ide> def method_missing(method_sym, *args, &block) <ide> if @parameters.respond_to?(method_sym) <ide> message = <<-DEPRECATE.squish <del> Method #{ method_sym } is deprecated and will be removed in Rails 5.1, <add> Method #{method_sym} is deprecated and will be removed in Rails 5.1, <ide> as `ActionController::Parameters` no longer inherits from <ide> hash. Using this deprecated behavior exposes potential security <ide> problems. If you continue to use this method you may be creating <del> a security vulunerability in your app that can be exploited. Instead, <add> a security vulnerability in your app that can be exploited. Instead, <ide> consider using one of these documented methods which are not <ide> deprecated: http://api.rubyonrails.org/v#{ActionPack.version}/classes/ActionController/Parameters.html <ide> DEPRECATE
1
Ruby
Ruby
fix broken tests
23f99ed7eb602c05952e53bc14afb9e692f7053d
<ide><path>railties/test/generators/app_generator_test.rb <ide> def test_generator_for_yarn <ide> end <ide> <ide> def test_generator_for_yarn_skipped <del> run_generator([destination_root]) <add> run_generator([destination_root, "--skip-yarn"]) <ide> assert_no_file "vendor/package.json" <ide> <del> assert_file "config/environments/production.rb" do |content| <add> assert_file "config/initializers/assets.rb" do |content| <ide> assert_no_match(/node_modules/, content) <ide> end <ide> end <ide> def test_create_keeps <ide> test/helpers <ide> test/integration <ide> tmp <del> vendor/assets/stylesheets <ide> ) <ide> folders_with_keep.each do |folder| <ide> assert_file("#{folder}/.keep")
1
PHP
PHP
move bootstraps to base classes
bcc539ee62052e4562b94a592cf5fc980016e4d0
<ide><path>app/Console/Kernel.php <ide> <ide> class Kernel extends ConsoleKernel { <ide> <del> /** <del> * The bootstrap classes for the application. <del> * <del> * @return void <del> */ <del> protected $bootstrappers = [ <del> 'Illuminate\Foundation\Bootstrap\LoadEnvironment', <del> 'Illuminate\Foundation\Bootstrap\LoadConfiguration', <del> 'Illuminate\Foundation\Bootstrap\RegisterProviders', <del> 'Illuminate\Foundation\Bootstrap\BootProviders', <del> ]; <del> <ide> /** <ide> * Run the console application. <ide> * <ide><path>app/Http/Kernel.php <ide> <ide> class Kernel extends HttpKernel { <ide> <del> /** <del> * The bootstrap classes for the application. <del> * <del> * @return void <del> */ <del> protected $bootstrappers = [ <del> 'Illuminate\Foundation\Bootstrap\LoadEnvironment', <del> 'Illuminate\Foundation\Bootstrap\HandleExceptions', <del> 'Illuminate\Foundation\Bootstrap\LoadConfiguration', <del> 'Illuminate\Foundation\Bootstrap\RegisterProviders', <del> 'Illuminate\Foundation\Bootstrap\BootProviders', <del> ]; <del> <ide> /** <ide> * The application's HTTP middleware stack. <ide> *
2
Python
Python
fix typo in test
797cbe4f0a4f631bc3e40d0325cd78aef6228348
<ide><path>libcloud/test/compute/test_openstack.py <ide> def test_ex_create_router(self): <ide> self.assertEqual(router.name, 'router1') <ide> <ide> def test_ex_delete_router(self): <del> router = self.driver.ex_list_router()[0] <add> router = self.driver.ex_list_routers()[0] <ide> self.assertTrue(self.driver.ex_delete_router(router=router)) <ide> <ide> class OpenStack_1_1_FactoryMethodTests(OpenStack_1_1_Tests):
1
Javascript
Javascript
correct redirection to route api to routing guide
33001ed3e60f4b2a9ee57e5f727ba951435cd34d
<ide><path>packages/ember-routing/lib/system/route.js <ide> export function hasDefaultSerialize(route) { <ide> <ide> /** <ide> The `Route` class is used to define individual routes. Refer to <del> the [routing guide](https://emberjs.com/guides/routing/) for documentation. <add> the [routing guide](https://guides.emberjs.com/release/routing/) for documentation. <ide> <ide> @class Route <ide> @extends EmberObject
1
Ruby
Ruby
add headings to rake routes table
a6277629faf48469ac5ea4f6899b44a213d88c9f
<ide><path>actionpack/lib/action_dispatch/routing/inspector.rb <ide> def format(formatter, filter = nil) <ide> routes_to_display = filter_routes(filter) <ide> <ide> routes = collect_routes(routes_to_display) <add> <add> formatter.header routes <ide> formatter.section routes <ide> <ide> @engines.each do |name, engine_routes| <ide> def section(routes) <ide> @buffer << draw_section(routes) <ide> end <ide> <add> def header(routes) <add> @buffer << draw_header(routes) <add> end <add> <ide> private <ide> def draw_section(routes) <del> name_width = routes.map { |r| r[:name].length }.max <del> verb_width = routes.map { |r| r[:verb].length }.max <del> path_width = routes.map { |r| r[:path].length }.max <add> name_width, verb_width, path_width = widths(routes) <ide> <ide> routes.map do |r| <ide> "#{r[:name].rjust(name_width)} #{r[:verb].ljust(verb_width)} #{r[:path].ljust(path_width)} #{r[:reqs]}" <ide> end <ide> end <add> <add> def draw_header(routes) <add> name_width, verb_width, path_width = widths(routes) <add> <add> "#{"Prefix".rjust(name_width)} #{"Verb".ljust(verb_width)} #{"URI Pattern".ljust(path_width)} Controller#Action" <add> end <add> <add> def widths(routes) <add> [routes.map { |r| r[:name].length }.max, <add> routes.map { |r| r[:verb].length }.max, <add> routes.map { |r| r[:path].length }.max] <add> end <ide> end <ide> <ide> class HtmlTableFormatter
1
Java
Java
fix imports in react native template
04a011236b8f715ab7ee5dc15a0151151740cc87
<ide><path>template/android/app/src/debug/java/com/helloworld/ReactNativeFlipper.java <ide> */ <ide> package com.helloworld; <ide> <add>import android.content.Context; <add>import com.facebook.flipper.android.AndroidFlipperClient; <add>import com.facebook.flipper.android.utils.FlipperUtils; <add>import com.facebook.flipper.core.FlipperClient; <add>import com.facebook.flipper.plugins.crashreporter.CrashReporterPlugin; <add>import com.facebook.flipper.plugins.databases.DatabasesFlipperPlugin; <ide> import com.facebook.flipper.plugins.fresco.FrescoFlipperPlugin; <ide> import com.facebook.flipper.plugins.inspector.DescriptorMapping; <ide> import com.facebook.flipper.plugins.inspector.InspectorFlipperPlugin;
1
Python
Python
fix typo in comment
353e75f510d17c9c3237e55fd91303db1a81eb0f
<ide><path>glances/exports/glances_kafka.py <ide> def __init__(self, config=None, args=None): <ide> # Optionals configuration keys <ide> self.compression = None <ide> <del> # Load the Cassandra configuration file section <add> # Load the Kafka configuration file section <ide> self.export_enable = self.load_conf('kafka', <ide> mandatories=['host', 'port', 'topic'], <ide> options=['compression'])
1
Python
Python
add support for msvc cross-compilation
66807e995de9a16b1cfe035f76958a178c381854
<ide><path>tools/gyp/pylib/gyp/generator/msvs.py <ide> # letters. <ide> VALID_MSVS_GUID_CHARS = re.compile(r'^[A-F0-9\-]+$') <ide> <add>generator_supports_multiple_toolsets = gyp.common.CrossCompileRequested() <ide> <ide> generator_default_variables = { <ide> 'DRIVER_PREFIX': '', <ide> 'STATIC_LIB_SUFFIX': '.lib', <ide> 'SHARED_LIB_SUFFIX': '.dll', <ide> 'INTERMEDIATE_DIR': '$(IntDir)', <del> 'SHARED_INTERMEDIATE_DIR': '$(OutDir)obj/global_intermediate', <add> 'SHARED_INTERMEDIATE_DIR': '$(OutDir)/obj/global_intermediate', <ide> 'OS': 'win', <ide> 'PRODUCT_DIR': '$(OutDir)', <ide> 'LIB_DIR': '$(OutDir)lib', <ide> def _ConfigTargetVersion(config_data): <ide> return config_data.get('msvs_target_version', 'Windows7') <ide> <ide> <del>def _ConfigPlatform(config_data): <add>def _ConfigPlatform(config_data, spec): <ide> return config_data.get('msvs_configuration_platform', 'Win32') <ide> <ide> <ide> def _ConfigBaseName(config_name, platform_name): <ide> return config_name <ide> <ide> <del>def _ConfigFullName(config_name, config_data): <del> platform_name = _ConfigPlatform(config_data) <add>def _ConfigFullName(config_name, config_data, spec): <add> platform_name = _ConfigPlatform(config_data, spec) <ide> return '%s|%s' % (_ConfigBaseName(config_name, platform_name), platform_name) <ide> <ide> <ide> def _GetMsbuildToolsetOfProject(proj_path, spec, version): <ide> return toolset <ide> <ide> <del>def _GenerateProject(project, options, version, generator_flags): <add>def _GenerateProject(project, options, version, generator_flags, spec): <ide> """Generates a vcproj file. <ide> <ide> Arguments: <ide> def _GenerateProject(project, options, version, generator_flags): <ide> return [] <ide> <ide> if version.UsesVcxproj(): <del> return _GenerateMSBuildProject(project, options, version, generator_flags) <add> return _GenerateMSBuildProject(project, options, version, generator_flags, spec) <ide> else: <ide> return _GenerateMSVSProject(project, options, version, generator_flags) <ide> <ide> def _GetUniquePlatforms(spec): <ide> # Gather list of unique platforms. <ide> platforms = OrderedSet() <ide> for configuration in spec['configurations']: <del> platforms.add(_ConfigPlatform(spec['configurations'][configuration])) <add> platforms.add(_ConfigPlatform(spec['configurations'][configuration], spec)) <ide> platforms = list(platforms) <ide> return platforms <ide> <ide> def _GatherSolutionFolders(sln_projects, project_objects, flat): <ide> # Convert into a tree of dicts on path. <ide> for p in sln_projects: <ide> gyp_file, target = gyp.common.ParseQualifiedTarget(p)[0:2] <add> if p.endswith("#host"): <add> target += "_host" <ide> gyp_dir = os.path.dirname(gyp_file) <ide> path_dict = _GetPathDict(root, gyp_dir) <ide> path_dict[target + '.vcproj'] = project_objects[p] <ide> def _GetPathOfProject(qualified_target, spec, options, msvs_version): <ide> default_config = _GetDefaultConfiguration(spec) <ide> proj_filename = default_config.get('msvs_existing_vcproj') <ide> if not proj_filename: <del> proj_filename = (spec['target_name'] + options.suffix + <add> proj_filename = spec['target_name'] <add> if spec['toolset'] == 'host': <add> proj_filename += "_host" <add> proj_filename = (proj_filename + options.suffix + <ide> msvs_version.ProjectExtension()) <ide> <ide> build_file = gyp.common.BuildFile(qualified_target) <ide> def _GetPlatformOverridesOfProject(spec): <ide> # solution configurations for this target. <ide> config_platform_overrides = {} <ide> for config_name, c in spec['configurations'].items(): <del> config_fullname = _ConfigFullName(config_name, c) <del> platform = c.get('msvs_target_platform', _ConfigPlatform(c)) <add> config_fullname = _ConfigFullName(config_name, c, spec) <add> platform = c.get('msvs_target_platform', _ConfigPlatform(c, spec)) <ide> fixed_config_fullname = '%s|%s' % ( <del> _ConfigBaseName(config_name, _ConfigPlatform(c)), platform) <add> _ConfigBaseName(config_name, _ConfigPlatform(c, spec)), platform) <add> if spec['toolset'] == 'host' and generator_supports_multiple_toolsets: <add> fixed_config_fullname = '%s|x64' % (config_name,) <ide> config_platform_overrides[config_fullname] = fixed_config_fullname <ide> return config_platform_overrides <ide> <ide> def _CreateProjectObjects(target_list, target_dicts, options, msvs_version): <ide> projects = {} <ide> for qualified_target in target_list: <ide> spec = target_dicts[qualified_target] <del> if spec['toolset'] != 'target': <del> raise GypError( <del> 'Multiple toolsets not supported in msvs build (target %s)' % <del> qualified_target) <ide> proj_path, fixpath_prefix = _GetPathOfProject(qualified_target, spec, <ide> options, msvs_version) <ide> guid = _GetGuidOfProject(proj_path, spec) <ide> overrides = _GetPlatformOverridesOfProject(spec) <ide> build_file = gyp.common.BuildFile(qualified_target) <ide> # Create object for this project. <add> target_name = spec['target_name'] <add> if spec['toolset'] == 'host': <add> target_name += '_host' <ide> obj = MSVSNew.MSVSProject( <ide> proj_path, <del> name=spec['target_name'], <add> name=target_name, <ide> guid=guid, <ide> spec=spec, <ide> build_file=build_file, <ide> def GenerateOutput(target_list, target_dicts, data, params): <ide> for qualified_target in target_list: <ide> spec = target_dicts[qualified_target] <ide> for config_name, config in spec['configurations'].items(): <del> configs.add(_ConfigFullName(config_name, config)) <add> config_name = _ConfigFullName(config_name, config, spec) <add> configs.add(config_name) <add> if config_name == 'Release|arm64': <add> configs.add("Release|x64") <ide> configs = list(configs) <ide> <ide> # Figure out all the projects that will be generated and their guids <ide> def GenerateOutput(target_list, target_dicts, data, params): <ide> for project in project_objects.values(): <ide> fixpath_prefix = project.fixpath_prefix <ide> missing_sources.extend(_GenerateProject(project, options, msvs_version, <del> generator_flags)) <add> generator_flags, spec)) <ide> fixpath_prefix = None <ide> <ide> for build_file in data: <ide> # Validate build_file extension <add> target_only_configs = configs <add> if generator_supports_multiple_toolsets: <add> target_only_configs = [i for i in configs if i.endswith('arm64')] <ide> if not build_file.endswith('.gyp'): <ide> continue <ide> sln_path = os.path.splitext(build_file)[0] + options.suffix + '.sln' <ide> def GenerateOutput(target_list, target_dicts, data, params): <ide> # Create solution. <ide> sln = MSVSNew.MSVSSolution(sln_path, <ide> entries=root_entries, <del> variants=configs, <add> variants=target_only_configs, <ide> websiteProperties=False, <ide> version=msvs_version) <ide> sln.Write() <ide> def _GenerateMSBuildRuleXmlFile(xml_path, msbuild_rules): <ide> easy_xml.WriteXmlIfChanged(content, xml_path, pretty=True, win32=True) <ide> <ide> <del>def _GetConfigurationAndPlatform(name, settings): <add>def _GetConfigurationAndPlatform(name, settings, spec): <ide> configuration = name.rsplit('_', 1)[0] <ide> platform = settings.get('msvs_configuration_platform', 'Win32') <add> if spec['toolset'] == 'host' and platform == 'arm64': <add> platform = 'x64' # Host-only tools are always built for x64 <ide> return (configuration, platform) <ide> <ide> <del>def _GetConfigurationCondition(name, settings): <add>def _GetConfigurationCondition(name, settings, spec): <ide> return (r"'$(Configuration)|$(Platform)'=='%s|%s'" % <del> _GetConfigurationAndPlatform(name, settings)) <add> _GetConfigurationAndPlatform(name, settings, spec)) <ide> <ide> <del>def _GetMSBuildProjectConfigurations(configurations): <add>def _GetMSBuildProjectConfigurations(configurations, spec): <ide> group = ['ItemGroup', {'Label': 'ProjectConfigurations'}] <ide> for (name, settings) in sorted(configurations.items()): <del> configuration, platform = _GetConfigurationAndPlatform(name, settings) <add> configuration, platform = _GetConfigurationAndPlatform(name, settings, spec) <ide> designation = '%s|%s' % (configuration, platform) <ide> group.append( <ide> ['ProjectConfiguration', {'Include': designation}, <ide> def _GetMSBuildGlobalProperties(spec, version, guid, gyp_file_name): <ide> platform_name = None <ide> msvs_windows_sdk_version = None <ide> for configuration in spec['configurations'].values(): <del> platform_name = platform_name or _ConfigPlatform(configuration) <add> platform_name = platform_name or _ConfigPlatform(configuration, spec) <ide> msvs_windows_sdk_version = (msvs_windows_sdk_version or <ide> _ConfigWindowsTargetPlatformVersion(configuration, version)) <ide> if platform_name and msvs_windows_sdk_version: <ide> def _GetMSBuildConfigurationDetails(spec, build_file): <ide> properties = {} <ide> for name, settings in spec['configurations'].items(): <ide> msbuild_attributes = _GetMSBuildAttributes(spec, settings, build_file) <del> condition = _GetConfigurationCondition(name, settings) <add> condition = _GetConfigurationCondition(name, settings, spec) <ide> character_set = msbuild_attributes.get('CharacterSet') <ide> config_type = msbuild_attributes.get('ConfigurationType') <ide> _AddConditionalProperty(properties, condition, 'ConfigurationType', <ide> def _GetMSBuildLocalProperties(msbuild_toolset): <ide> return properties <ide> <ide> <del>def _GetMSBuildPropertySheets(configurations): <add>def _GetMSBuildPropertySheets(configurations, spec): <ide> user_props = r'$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props' <ide> additional_props = {} <ide> props_specified = False <ide> for name, settings in sorted(configurations.items()): <del> configuration = _GetConfigurationCondition(name, settings) <add> configuration = _GetConfigurationCondition(name, settings, spec) <ide> if 'msbuild_props' in settings: <ide> additional_props[configuration] = _FixPaths(settings['msbuild_props']) <ide> props_specified = True <ide> def _GetMSBuildConfigurationGlobalProperties(spec, configurations, build_file): <ide> <ide> properties = {} <ide> for (name, configuration) in sorted(configurations.items()): <del> condition = _GetConfigurationCondition(name, configuration) <add> condition = _GetConfigurationCondition(name, configuration, spec) <ide> attributes = _GetMSBuildAttributes(spec, configuration, build_file) <ide> msbuild_settings = configuration['finalized_msbuild_settings'] <ide> _AddConditionalProperty(properties, condition, 'IntDir', <ide> def _GetMSBuildToolSettingsSections(spec, configurations): <ide> for (name, configuration) in sorted(configurations.items()): <ide> msbuild_settings = configuration['finalized_msbuild_settings'] <ide> group = ['ItemDefinitionGroup', <del> {'Condition': _GetConfigurationCondition(name, configuration)} <add> {'Condition': <add> _GetConfigurationCondition(name, configuration, spec) <add> } <ide> ] <ide> for tool_name, tool_settings in sorted(msbuild_settings.items()): <ide> # Skip the tool named '' which is a holder of global settings handled <ide> def _AddSources2(spec, sources, exclusions, grouped_sources, <ide> extensions_excluded_from_precompile = ['.c'] <ide> <ide> if precompiled_source == source: <del> condition = _GetConfigurationCondition(config_name, configuration) <add> condition = _GetConfigurationCondition( <add> config_name, configuration, spec <add> ) <ide> detail.append(['PrecompiledHeader', <ide> {'Condition': condition}, <ide> 'Create' <ide> def _AddSources2(spec, sources, exclusions, grouped_sources, <ide> _GetUniquePlatforms(spec)) <ide> grouped_sources[group].append([element, {'Include': source}] + detail) <ide> <del> <del>def _GetMSBuildProjectReferences(project): <add>def _GetMSBuildProjectReferences(project, spec): <add> current_configuration = spec['default_configuration'] <ide> references = [] <ide> if project.dependencies: <ide> group = ['ItemGroup'] <add> added_dependency_set = set() <ide> for dependency in project.dependencies: <add> dependency_spec = dependency.spec <add> should_skip_dep = False <add> if project.spec["toolset"] == 'target': <add> if dependency_spec['toolset'] == 'host': <add> if dependency_spec['type'] == 'static_library': <add> should_skip_dep = True <add> if dependency.name.startswith('run_'): <add> should_skip_dep = False <add> if should_skip_dep: <add> continue <add> <add> canonical_name = dependency.name.replace('_host', '') <add> added_dependency_set.add(canonical_name) <ide> guid = dependency.guid <ide> project_dir = os.path.split(project.path)[0] <ide> relative_path = gyp.common.RelativePath(dependency.path, project_dir) <ide> def _GetMSBuildProjectReferences(project): <ide> return references <ide> <ide> <del>def _GenerateMSBuildProject(project, options, version, generator_flags): <add>def _GenerateMSBuildProject(project, options, version, generator_flags, spec): <ide> spec = project.spec <ide> configurations = spec['configurations'] <ide> project_dir, project_file_name = os.path.split(project.path) <ide> def _GenerateMSBuildProject(project, options, version, generator_flags): <ide> 'DefaultTargets': 'Build' <ide> }] <ide> <del> content += _GetMSBuildProjectConfigurations(configurations) <add> content += _GetMSBuildProjectConfigurations(configurations, spec) <ide> content += _GetMSBuildGlobalProperties(spec, version, project.guid, <ide> project_file_name) <ide> content += import_default_section <ide> def _GenerateMSBuildProject(project, options, version, generator_flags): <ide> content += _GetMSBuildLocalProperties(project.msbuild_toolset) <ide> content += import_cpp_props_section <ide> content += import_masm_props_section <del> if spec.get('msvs_enable_marmasm'): <add> if spec.get('msvs_enable_marmasm') or True: <ide> content += import_marmasm_props_section <ide> content += _GetMSBuildExtensions(props_files_of_rules) <del> content += _GetMSBuildPropertySheets(configurations) <add> content += _GetMSBuildPropertySheets(configurations, spec) <ide> content += macro_section <ide> content += _GetMSBuildConfigurationGlobalProperties(spec, configurations, <ide> project.build_file) <ide> content += _GetMSBuildToolSettingsSections(spec, configurations) <ide> content += _GetMSBuildSources( <ide> spec, sources, exclusions, rule_dependencies, extension_to_rule_name, <ide> actions_spec, sources_handled_by_action, list_excluded) <del> content += _GetMSBuildProjectReferences(project) <add> content += _GetMSBuildProjectReferences(project, spec) <ide> content += import_cpp_targets_section <ide> content += import_masm_targets_section <ide> if spec.get('msvs_enable_marmasm'): <ide> def _GenerateActionsForMSBuild(spec, actions_to_add): <ide> sources_handled_by_action = OrderedSet() <ide> actions_spec = [] <ide> for primary_input, actions in actions_to_add.items(): <add> if generator_supports_multiple_toolsets: <add> primary_input = primary_input.replace(".exe", "_host.exe") <ide> inputs = OrderedSet() <ide> outputs = OrderedSet() <ide> descriptions = [] <ide> commands = [] <ide> for action in actions: <add> def fixup_host_exe(i): <add> if "$(OutDir)" in i: <add> i = i.replace('.exe', '_host.exe') <add> return i <add> if generator_supports_multiple_toolsets: <add> action['inputs'] = [fixup_host_exe(i) for i in action['inputs']] <ide> inputs.update(OrderedSet(action['inputs'])) <ide> outputs.update(OrderedSet(action['outputs'])) <ide> descriptions.append(action['description']) <ide> cmd = action['command'] <add> if generator_supports_multiple_toolsets: <add> cmd = cmd.replace('.exe', "_host.exe") <ide> # For most actions, add 'call' so that actions that invoke batch files <ide> # return and continue executing. msbuild_use_call provides a way to <ide> # disable this but I have not seen any adverse effect from doing that
1
Ruby
Ruby
remove unused @cache_hit hash assignment
ebb83e46ba0c11e9a087949138233ca8dd9ef690
<ide><path>actionview/lib/action_view/base.rb <ide> def initialize(lookup_context = nil, assigns = {}, controller = nil, formats = N <ide> @view_renderer = ActionView::Renderer.new @lookup_context <ide> @current_template = nil <ide> <del> @cache_hit = {} <ide> assign(assigns) <ide> assign_controller(controller) <ide> _prepare_context
1
PHP
PHP
fix first method on eloquent builder
751dff74fa541ec1a832320585abd8a9060e9f39
<ide><path>src/Illuminate/Database/Eloquent/Builder.php <ide> public function find($id, $columns = array('*')) <ide> */ <ide> public function first($columns = array('*')) <ide> { <del> return $this->get($columns)->first(); <add> return $this->take(1)->get($columns)->first(); <ide> } <ide> <ide> /** <ide><path>tests/Database/DatabaseEloquentBuilderTest.php <ide> public function testFindMethod() <ide> <ide> public function testFirstMethod() <ide> { <del> $builder = $this->getMock('Illuminate\Database\Eloquent\Builder', array('get'), $this->getMocks()); <add> $builder = $this->getMock('Illuminate\Database\Eloquent\Builder', array('get', 'take'), $this->getMocks()); <ide> $collection = m::mock('stdClass'); <ide> $collection->shouldReceive('first')->once()->andReturn('bar'); <add> $builder->expects($this->once())->method('take')->with($this->equalTo(1))->will($this->returnValue($builder)); <ide> $builder->expects($this->once())->method('get')->with($this->equalTo(array('*')))->will($this->returnValue($collection)); <ide> <ide> $result = $builder->first();
2
Javascript
Javascript
avoid concatenating strings in buildfragment
9c98e4e86eda857ee063bc48adbc1a11bb5506ee
<ide><path>src/manipulation/buildFragment.js <ide> import jQuery from "../core.js"; <ide> import toType from "../core/toType.js"; <ide> import isAttached from "../core/isAttached.js"; <add>import arr from "../var/arr.js"; <ide> import rtagName from "./var/rtagName.js"; <ide> import rscriptType from "./var/rscriptType.js"; <ide> import wrapMap from "./wrapMap.js"; <ide> function buildFragment( elems, context, scripts, selection, ignored ) { <ide> <ide> // Deserialize a standard representation <ide> tag = ( rtagName.exec( elem ) || [ "", "" ] )[ 1 ].toLowerCase(); <del> wrap = wrapMap[ tag ] || wrapMap._default; <del> tmp.innerHTML = wrap[ 1 ] + jQuery.htmlPrefilter( elem ) + wrap[ 2 ]; <add> wrap = wrapMap[ tag ] || arr; <ide> <del> // Descend through wrappers to the right content <del> j = wrap[ 0 ]; <del> while ( j-- ) { <del> tmp = tmp.lastChild; <add> // Create wrappers & descend into them. <add> j = wrap.length; <add> while ( --j > -1 ) { <add> tmp = tmp.appendChild( context.createElement( wrap[ j ] ) ); <ide> } <ide> <add> tmp.innerHTML = jQuery.htmlPrefilter( elem ); <add> <ide> jQuery.merge( nodes, tmp.childNodes ); <ide> <ide> // Remember the top-level container <ide><path>src/manipulation/wrapMap.js <del>// We have to close these tags to support XHTML (#13200) <ide> var wrapMap = { <ide> <ide> // Table parts need to be wrapped with `<table>` or they're <ide> // stripped to their contents when put in a div. <ide> // XHTML parsers do not magically insert elements in the <ide> // same way that tag soup parsers do, so we cannot shorten <ide> // this by omitting <tbody> or other required elements. <del> thead: [ 1, "<table>", "</table>" ], <del> col: [ 2, "<table><colgroup>", "</colgroup></table>" ], <del> tr: [ 2, "<table><tbody>", "</tbody></table>" ], <del> td: [ 3, "<table><tbody><tr>", "</tr></tbody></table>" ], <del> <del> _default: [ 0, "", "" ] <add> thead: [ "table" ], <add> col: [ "colgroup", "table" ], <add> tr: [ "tbody", "table" ], <add> td: [ "tr", "tbody", "table" ] <ide> }; <ide> <ide> wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead; <ide><path>test/unit/manipulation.js <ide> QUnit.test( "Sanitized HTML doesn't get unsanitized", function( assert ) { <ide> test( "<noembed><noembed/><img src=url404 onerror=xss(12)>" ); <ide> } <ide> } ); <add> <add>QUnit.test( "Works with invalid attempts to close the table wrapper", function( assert ) { <add> assert.expect( 3 ); <add> <add> // This test case attempts to close the tags which wrap input <add> // based on matching done in wrapMap which should be ignored. <add> var elem = jQuery( "<td></td></tr></tbody></table><td></td>" ); <add> assert.strictEqual( elem.length, 2, "Two elements created" ); <add> assert.strictEqual( elem[ 0 ].nodeName.toLowerCase(), "td", "First element is td" ); <add> assert.strictEqual( elem[ 1 ].nodeName.toLowerCase(), "td", "Second element is td" ); <add>} );
3
Python
Python
remove timeout from urllib
d379ef22e9c5106c0c05c740403b1094442b176f
<ide><path>glances/compat.py <ide> from xmlrpc.client import Fault, ProtocolError, ServerProxy, Transport <ide> from xmlrpc.server import SimpleXMLRPCRequestHandler, SimpleXMLRPCServer <ide> from urllib.request import urlopen <del> from urllib.error import URLError, timeout <add> from urllib.error import URLError <ide> <ide> input = input <ide> range = range
1
Java
Java
fix viewpager behavior with nodes
b8313b282b67ded62bac83dbbcd801215bfbdcc2
<ide><path>ReactAndroid/src/main/java/com/facebook/react/flat/FlatNativeViewHierarchyManager.java <ide> <ide> import javax.annotation.Nullable; <ide> <add>import java.util.ArrayList; <ide> import java.util.Collection; <add>import java.util.List; <ide> <ide> import android.graphics.Rect; <ide> import android.view.View; <ide> public void addRootView( <ide> <ide> ViewGroup viewGroup = (ViewGroup) view; <ide> ViewGroupManager viewManager = (ViewGroupManager) resolveViewManager(reactTag); <del> for (int i = 0; i < viewsToAdd.length; ++i) { <del> int tag = Math.abs(viewsToAdd[i]); <del> viewManager.addView(viewGroup, resolveView(tag), i); <add> List<View> listOfViews = new ArrayList<>(viewsToAdd.length); <add> <add> // batch the set of additions - some view managers can take advantage of the batching to <add> // decrease operations, etc. <add> for (int viewIdToAdd : viewsToAdd) { <add> int tag = Math.abs(viewIdToAdd); <add> listOfViews.add(resolveView(tag)); <ide> } <add> viewManager.addViews(viewGroup, listOfViews); <ide> } <ide> <ide> /** <ide> protected void dropView(View view) { <ide> <ide> ViewGroup viewGroup = (ViewGroup) view; <ide> ViewGroupManager viewManager = (ViewGroupManager) resolveViewManager(viewTag); <del> for (int i = viewManager.getChildCount(viewGroup) - 1; i >= 0; --i) { <del> viewManager.removeViewAt(viewGroup, i); <del> } <add> viewManager.removeAllViews(viewGroup); <ide> } <ide> } <ide> } <ide><path>ReactAndroid/src/main/java/com/facebook/react/flat/FlatUIImplementation.java <ide> public static FlatUIImplementation createInstance( <ide> viewManagers.add(new RCTTextInlineImageManager()); <ide> viewManagers.add(new RCTImageViewManager()); <ide> viewManagers.add(new RCTTextInputManager()); <add> viewManagers.add(new RCTViewPagerManager()); <ide> viewManagers.add(new RCTModalHostManager(reactContext)); <ide> <ide> ViewManagerRegistry viewManagerRegistry = new ViewManagerRegistry(viewManagers); <ide><path>ReactAndroid/src/main/java/com/facebook/react/flat/RCTViewPagerManager.java <add>/** <add> * Copyright (c) 2015-present, Facebook, Inc. <add> * All rights reserved. <add> * <add> * This source code is licensed under the BSD-style license found in the <add> * LICENSE file in the root directory of this source tree. An additional grant <add> * of patent rights can be found in the PATENTS file in the same directory. <add> */ <add> <add>package com.facebook.react.flat; <add> <add>import java.util.List; <add> <add>import android.view.View; <add> <add>import com.facebook.react.views.viewpager.ReactViewPager; <add>import com.facebook.react.views.viewpager.ReactViewPagerManager; <add> <add>/* package */ class RCTViewPagerManager extends ReactViewPagerManager { <add> <add> @Override <add> public void addViews(ReactViewPager parent, List<View> views) { <add> parent.setViews(views); <add> } <add> <add> @Override <add> public void removeAllViews(ReactViewPager parent) { <add> parent.removeAllViewsFromAdapter(); <add> } <add>}
3
Text
Text
add changelog for [ci skip]
b38c370b0cbb6df0ba934d98311b3c7b1877429e
<ide><path>actionpack/CHANGELOG.md <add>* Fallback `ActionController::Parameters#to_s` to `Hash#to_s`. <add> <add> *Kir Shatrov* <add> <ide> * `driven_by` now registers poltergeist and capybara-webkit <ide> <ide> If driver poltergeist or capybara-webkit is set for System Tests,
1
Python
Python
hold the process until enter is pressed
bc76490acd4e47b14172e0b7dbf75f61ba435773
<ide><path>numpy/distutils/core.py <ide> def _command_line_ok(_cache=[]): <ide> <ide> def setup(**attr): <ide> <del> interactive = len(sys.argv)<=1 <del> if interactive: <add> if len(sys.argv)<=1: <ide> from interactive import interactive_sys_argv <ide> sys.argv[:] = interactive_sys_argv(sys.argv) <add> if len(sys.argv)>1: <add> try: <add> r = setup(**attr) <add> except Exception, msg: <add> print '-'*72 <add> print 'setup failed with:',msg <add> raw_input('Press ENTER to close the interactive session..') <add> raise msg <add> print '-'*72 <add> raw_input('Press ENTER to close the interactive session..') <add> print '='*72 <add> return r <ide> <ide> cmdclass = numpy_cmdclass.copy() <ide> <ide> def setup(**attr): <ide> and not new_attr.has_key('headers'): <ide> new_attr['headers'] = [] <ide> <del> if interactive: <del> try: <del> r = old_setup(**new_attr) <del> except Exception, msg: <del> print '-'*72 <del> print 'setup failed with:',msg <del> raw_input('Press ENTER to close the interactive session..') <del> raise msg <del> print '-'*72 <del> raw_input('Press ENTER to close the interactive session..') <del> print '='*72 <del> else: <del> return old_setup(**new_attr) <add> return old_setup(**new_attr) <ide> <ide> def _check_append_library(libraries, item): <ide> import warnings
1
PHP
PHP
implement locale routing
cf24df89336316e74b50d2973b040657cdfafef5
<ide><path>src/Illuminate/Foundation/Application.php <ide> class Application extends Container implements HttpKernelInterface { <ide> /** <ide> * Create a new Illuminate application instance. <ide> * <add> * @param \Illuminate\Http\Request $request <ide> * @return void <ide> */ <del> public function __construct() <add> public function __construct(Request $request = null) <ide> { <del> $this['request'] = Request::createFromGlobals(); <add> $this['request'] = $this->createRequest($request); <ide> <ide> // The exception handler class takes care of determining which of the bound <ide> // exception handler Closures should be called for a given exception and <ide> public function __construct() <ide> $this->register(new EventServiceProvider($this)); <ide> } <ide> <add> /** <add> * Create the request for the application. <add> * <add> * @param \Illuminate\Http\Request $request <add> * @return \Illuminate\Htto\Request <add> */ <add> protected function createRequest(Request $request = null) <add> { <add> $request = $request ?: Request::createFromGlobals(); <add> <add> $this->registerLocaleHandler($request); <add> <add> return $request; <add> } <add> <add> /** <add> * Register the URI locale boot handler. <add> * <add> * @param Illuminate\Http\Request $request <add> * @return void <add> */ <add> protected function registerLocaleHandler(Request $request) <add> { <add> $this->booting(function($app) use ($request) <add> { <add> $locales = $app['config']->get('app.locales', array()); <add> <add> // Here, we will check to see if the incoming request begins with any of the <add> // supported locales. If it does, we will set that locale as this default <add> // for an application and remove it from the current request path info. <add> $locale = $request->handleUriLocales($locales); <add> <add> if ($locale) <add> { <add> $app->setLocale($locale); <add> <add> $app['url']->setPrefix($locale); <add> } <add> }); <add> } <add> <ide> /** <ide> * Bind the installation paths to the application. <ide> * <ide><path>src/Illuminate/Http/Request.php <ide> public function instance() <ide> return $this; <ide> } <ide> <add> /** <add> * Setup the path info for a locale based URI. <add> * <add> * @param array $locales <add> * @return string <add> */ <add> public function handleUriLocales(array $locales) <add> { <add> $path = $this->getPathInfo(); <add> <add> foreach ($locales as $locale) <add> { <add> if (starts_with($path, '/'.$locale)) return $this->removeLocaleFromUri($locale); <add> } <add> } <add> <add> /** <add> * Remove the given locale from the URI. <add> * <add> * @param string $locale <add> * @return string <add> */ <add> protected function removeLocaleFromUri($locale) <add> { <add> $this->pathInfo = '/'.ltrim(substr($this->getPathInfo(), strlen($locale) + 1), '/'); <add> <add> return $locale; <add> } <add> <ide> /** <ide> * Get the root URL for the application. <ide> * <ide><path>src/Illuminate/Routing/UrlGenerator.php <ide> public function to($path, $parameters = array(), $secure = null) <ide> <ide> $root = $this->getRootUrl($scheme); <ide> <del> return $root.$this->getPrefix().'/'.trim($path.'/'.$tail, '/'); <add> return trim($root.$this->getPrefix().'/'.trim($path.'/'.$tail, '/'), '/'); <ide> } <ide> <ide> /** <ide><path>tests/Foundation/FoundationApplicationTest.php <ide> public function testServiceProvidersAreCorrectlyRegistered() <ide> $this->assertTrue(in_array($class, $app->getLoadedProviders())); <ide> } <ide> <add> <add> public function testLocaleDetectionOnBoot() <add> { <add> $request = Illuminate\Http\Request::create('/en/foo/bar', 'GET'); <add> $application = $this->getMock('Illuminate\Foundation\Application', array('setLocale'), array($request)); <add> $application->instance('config', $config = m::mock('StdClass')); <add> $config->shouldReceive('get')->once()->with('app.locales', array())->andReturn(array('en')); <add> $application->instance('url', $url = m::mock('StdClass')); <add> $url->shouldReceive('setPrefix')->once()->with('en'); <add> $application->expects($this->once())->method('setLocale')->with($this->equalTo('en')); <add> <add> $application->boot(); <add> } <add> <ide> } <ide> <ide> class ApplicationCustomExceptionHandlerStub extends Illuminate\Foundation\Application { <ide><path>tests/Routing/RoutingUrlGeneratorTest.php <ide> public function testBasicUrlGeneration() <ide> $gen = $this->getGenerator(); <ide> $gen->setRequest(Request::create('http://foobar.com/foo/bar', 'GET')); <ide> <del> $this->assertEquals('http://foobar.com/', $gen->to('/')); <add> $this->assertEquals('http://foobar.com', $gen->to('/')); <ide> $this->assertEquals('http://foobar.com/something', $gen->to('/something')); <ide> $this->assertEquals('http://foobar.com/something', $gen->to('something')); <ide> <del> $this->assertEquals('https://foobar.com/', $gen->secure('/')); <add> $this->assertEquals('https://foobar.com', $gen->secure('/')); <ide> $this->assertEquals('https://foobar.com/something', $gen->secure('/something')); <ide> $this->assertEquals('https://foobar.com/something', $gen->secure('something')); <ide>
5
Text
Text
add details for inspect command usage
59ef08c87836cab7540c07403a19ae5ea4eb85b9
<ide><path>docs/reference/commandline/inspect.md <ide> Options: <ide> <ide> ## Description <ide> <del>By default, `docker inspect` will render all results in a JSON array. If the container and <del>image have the same name, this will return container JSON for unspecified type. <add>Docker inspect provides detailed information on constructs controlled by Docker. <add> <add>By default, `docker inspect` will render results in a JSON array. <add> <add>## Request a custom response format (--format) <add> <ide> If a format is specified, the given template will be executed for each result. <ide> <ide> Go's [text/template](http://golang.org/pkg/text/template/) package <ide> describes all the details of the format. <ide> <add>## Specify target type (--type) <add> <add>`--type container|image|node|network|secret|service|volume|task|plugin` <add> <add>The `docker inspect` command matches any type of object by either ID or name. <add>In some cases multiple type of objects (for example, a container and a volume) <add>exist with the same name, making the result ambigious. <add> <add>To restrict `docker inspect` to a specific type of object, use the `--type` <add>option. <add> <add>The following example inspects a _volume_ named "myvolume" <add> <add>```bash <add>$ docker inspect --type=volume myvolume <add>``` <add> <ide> ## Examples <ide> <ide> ### Get an instance's IP address
1
Javascript
Javascript
add simple node build
76f157e3dd18d0501b4ed083e54b444ce11d232f
<ide><path>packages/react-transport-dom-webpack/npm/plugin.js <ide> 'use strict'; <ide> <del>if (process.env.NODE_ENV === 'production') { <del> module.exports = require('./cjs/react-transport-dom-webpack-plugin.production.min.js'); <del>} else { <del> module.exports = require('./cjs/react-transport-dom-webpack-plugin.development.js'); <del>} <add>module.exports = require('./cjs/react-transport-dom-webpack-plugin.js'); <ide><path>scripts/rollup/build.js <ide> process.on('unhandledRejection', err => { <ide> }); <ide> <ide> const { <add> NODE_ES2015, <ide> UMD_DEV, <ide> UMD_PROD, <ide> UMD_PROFILING, <ide> function getFormat(bundleType) { <ide> case UMD_PROD: <ide> case UMD_PROFILING: <ide> return `umd`; <add> case NODE_ES2015: <ide> case NODE_DEV: <ide> case NODE_PROD: <ide> case NODE_PROFILING: <ide> function getFormat(bundleType) { <ide> <ide> function isProductionBundleType(bundleType) { <ide> switch (bundleType) { <add> case NODE_ES2015: <ide> case UMD_DEV: <ide> case NODE_DEV: <ide> case FB_WWW_DEV: <ide> function isProductionBundleType(bundleType) { <ide> <ide> function isProfilingBundleType(bundleType) { <ide> switch (bundleType) { <add> case NODE_ES2015: <ide> case FB_WWW_DEV: <ide> case FB_WWW_PROD: <ide> case NODE_DEV: <ide> async function buildEverything() { <ide> // eslint-disable-next-line no-for-of-loops/no-for-of-loops <ide> for (const bundle of Bundles.bundles) { <ide> bundles.push( <add> [bundle, NODE_ES2015], <ide> [bundle, UMD_DEV], <ide> [bundle, UMD_PROD], <ide> [bundle, UMD_PROFILING], <ide><path>scripts/rollup/bundles.js <ide> const __EXPERIMENTAL__ = <ide> : true; <ide> <ide> const bundleTypes = { <add> NODE_ES2015: 'NODE_ES2015', <ide> UMD_DEV: 'UMD_DEV', <ide> UMD_PROD: 'UMD_PROD', <ide> UMD_PROFILING: 'UMD_PROFILING', <ide> const bundleTypes = { <ide> }; <ide> <ide> const { <add> NODE_ES2015, <ide> UMD_DEV, <ide> UMD_PROD, <ide> UMD_PROFILING, <ide> const bundles = [ <ide> <ide> /******* React Transport DOM Webpack Plugin *******/ <ide> { <del> bundleTypes: [NODE_DEV, NODE_PROD], <add> bundleTypes: [NODE_ES2015], <ide> moduleType: RENDERER_UTILS, <ide> entry: 'react-transport-dom-webpack/plugin', <ide> global: 'ReactFlightWebpackPlugin', <ide> externals: [], <del> babel: opts => <del> Object.assign({}, opts, { <del> // Include JSX <del> presets: opts.presets.concat([ <del> require.resolve('@babel/preset-react'), <del> require.resolve('@babel/preset-flow'), <del> ]), <del> plugins: opts.plugins.concat([ <del> [require.resolve('@babel/plugin-transform-classes'), {loose: true}], <del> ]), <del> }), <ide> }, <ide> <ide> /******* React Transport DOM Server Relay *******/ <ide> function getFilename(bundle, bundleType) { <ide> // we do this to replace / to -, for react-dom/server <ide> name = name.replace('/index.', '.').replace('/', '-'); <ide> switch (bundleType) { <add> case NODE_ES2015: <add> return `${name}.js`; <ide> case UMD_DEV: <ide> return `${name}.development.js`; <ide> case UMD_PROD: <ide><path>scripts/rollup/packaging.js <ide> const { <ide> } = require('./utils'); <ide> <ide> const { <add> NODE_ES2015, <ide> UMD_DEV, <ide> UMD_PROD, <ide> UMD_PROFILING, <ide> function getPackageName(name) { <ide> <ide> function getBundleOutputPath(bundleType, filename, packageName) { <ide> switch (bundleType) { <add> case NODE_ES2015: <add> return `build/node_modules/${packageName}/cjs/${filename}`; <ide> case NODE_DEV: <ide> case NODE_PROD: <ide> case NODE_PROFILING: <ide><path>scripts/rollup/validate/eslintrc.cjs2015.js <add>'use strict'; <add> <add>module.exports = { <add> env: { <add> commonjs: true, <add> browser: true, <add> }, <add> globals: { <add> // ES 6 <add> Map: true, <add> Set: true, <add> Proxy: true, <add> Symbol: true, <add> WeakMap: true, <add> WeakSet: true, <add> Uint16Array: true, <add> Reflect: true, <add> // Vendor specific <add> MSApp: true, <add> __REACT_DEVTOOLS_GLOBAL_HOOK__: true, <add> // CommonJS / Node <add> process: true, <add> setImmediate: true, <add> Buffer: true, <add> // Trusted Types <add> trustedTypes: true, <add> <add> // Scheduler profiling <add> SharedArrayBuffer: true, <add> Int32Array: true, <add> ArrayBuffer: true, <add> <add> // Flight <add> Uint8Array: true, <add> Promise: true, <add> <add> // Flight Webpack <add> __webpack_chunk_load__: true, <add> __webpack_require__: true, <add> <add> // jest <add> expect: true, <add> }, <add> parserOptions: { <add> ecmaVersion: 2015, <add> sourceType: 'script', <add> }, <add> rules: { <add> 'no-undef': 'error', <add> 'no-shadow-restricted-names': 'error', <add> }, <add> <add> // These plugins aren't used, but eslint complains if an eslint-ignore comment <add> // references unused plugins. An alternate approach could be to strip <add> // eslint-ignore comments as part of the build. <add> plugins: ['jest', 'no-for-of-loops', 'react', 'react-internal'], <add>}; <ide><path>scripts/rollup/validate/index.js <ide> const {bundles, getFilename, bundleTypes} = require('../bundles'); <ide> const Packaging = require('../packaging'); <ide> <ide> const { <add> NODE_ES2015, <ide> UMD_DEV, <ide> UMD_PROD, <ide> UMD_PROFILING, <ide> function getFormat(bundleType) { <ide> case UMD_PROD: <ide> case UMD_PROFILING: <ide> return 'umd'; <add> case NODE_ES2015: <add> return 'cjs2015'; <ide> case NODE_DEV: <ide> case NODE_PROD: <ide> case NODE_PROFILING: <ide> function getESLintInstance(format) { <ide> <ide> const esLints = { <ide> cjs: getESLintInstance('cjs'), <add> cjs2015: getESLintInstance('cjs2015'), <ide> rn: getESLintInstance('rn'), <ide> fb: getESLintInstance('fb'), <ide> umd: getESLintInstance('umd'), <ide><path>scripts/rollup/wrappers.js <ide> const {bundleTypes, moduleTypes} = require('./bundles'); <ide> const reactVersion = require('../../package.json').version; <ide> <ide> const { <add> NODE_ES2015, <ide> UMD_DEV, <ide> UMD_PROD, <ide> UMD_PROFILING, <ide> const license = ` * Copyright (c) Facebook, Inc. and its affiliates. <ide> * LICENSE file in the root directory of this source tree.`; <ide> <ide> const wrappers = { <add> /***************** NODE_ES2015 *****************/ <add> [NODE_ES2015](source, globalName, filename, moduleType) { <add> return `/** @license React v${reactVersion} <add> * ${filename} <add> * <add>${license} <add> */ <add> <add>'use strict'; <add> <add>${source}`; <add> }, <add> <ide> /***************** UMD_DEV *****************/ <ide> [UMD_DEV](source, globalName, filename, moduleType) { <ide> return `/** @license React v${reactVersion}
7
Text
Text
add section stub about pull requests
f80d694a9500821ad9b1f5ee2f70ba7865a230bb
<ide><path>laravel/documentation/contrib/github.md <ide> - [The Basics](#the-basics) <ide> - [Repositories](#repositories) <ide> - [Branches](#branches) <add>- [Pull Requests](#pull-requests) <ide> <del><a name='the-basics'></a> <add><a name="the-basics"></a> <ide> ## The Basics <ide> <ide> Because Laravel's development and source control is done through GitHub, anyone is able to make contributions to it. Anyone can fix bugs, add features or improve the documentation. <ide> <ide> After submitting proposed changes to the project, the Laravel team will review the changes and make the decision to commit them to Laravel's core. <ide> <del><a name='repositories'></a> <add><a name="repositories"></a> <ide> ## Repositories <ide> <ide> Laravel's home on GitHub is at [github.com/laravel](https://github.com/laravel). Laravel has several repositories. For basic contributions, the only repository you need to pay attention to is the **laravel** repository, located at [github.com/laravel/laravel](https://github.com/laravel/laravel). <ide> <del><a name='branches'></a> <add><a name="branches"></a> <ide> ## Branches <ide> <ide> The **laravel** repository has multiple branches, each serving a specific purpose: <ide> The **laravel** repository has multiple branches, each serving a specific purpos <ide> <ide> Once certain milestones have been reached and/or Taylor Otwell and the Laravel team is happy with the stability and additional features of the current development branch, the changes in the **develop** branch are pulled into the **master** branch, thus creating and releasing the newest stable version of Laravel for the world to use. <ide> <add><a name="pull-requests"></a> <add>## Pull Requests <add> <add>Contributing with pull requests. <add> <ide> *Further Reading* <ide> <ide> - [Contributing to Laravel via Command-Line](docs/contrib/command-line)
1
PHP
PHP
add integration tests for --version and --help
d35a88cb595768d8b3bc0a1f86d21407e10017d6
<ide><path>tests/TestCase/Console/ShellDispatcherTest.php <ide> public function testShiftArgs() <ide> $this->assertNull($this->dispatcher->shiftArgs()); <ide> $this->assertSame([], $this->dispatcher->args); <ide> } <add> <add> /** <add> * Test how `bin/cake --help` works. <add> * <add> * @return void <add> */ <add> public function testHelpOption() <add> { <add> $mockShell = $this->getMock('Cake\Shell\CommandListShell', ['main', 'initialize', 'startup']); <add> $mockShell->expects($this->once()) <add> ->method('main'); <add> <add> $dispatcher = $this->getMock('Cake\Console\ShellDispatcher', ['findShell', '_stop']); <add> $dispatcher->expects($this->once()) <add> ->method('findShell') <add> ->with('command_list') <add> ->will($this->returnValue($mockShell)); <add> $dispatcher->args = ['--help']; <add> $dispatcher->dispatch(); <add> } <add> <add> /** <add> * Test how `bin/cake --version` works. <add> * <add> * @return void <add> */ <add> public function testVersionOption() <add> { <add> $mockShell = $this->getMock('Cake\Shell\CommandListShell', ['main', 'initialize', 'startup']); <add> $mockShell->expects($this->once()) <add> ->method('main'); <add> <add> $dispatcher = $this->getMock('Cake\Console\ShellDispatcher', ['findShell', '_stop']); <add> $dispatcher->expects($this->once()) <add> ->method('findShell') <add> ->with('command_list') <add> ->will($this->returnValue($mockShell)); <add> $dispatcher->args = ['--version']; <add> $dispatcher->dispatch(); <add> } <ide> }
1
Java
Java
add integration test for gh-24110
fb13f6f0bc300ac8001d5cfc53b89f6136be0569
<ide><path>spring-core/src/test/java/org/springframework/core/annotation/AnnotatedElementUtilsTests.java <ide> void getMergedAnnotationWithImplicitAliasesInMetaAnnotationOnComposedAnnotation( <ide> assertThat(isAnnotated(element, name)).isTrue(); <ide> } <ide> <add> @Test <add> void getMergedAnnotationWithImplicitAliasesWithDefaultsInMetaAnnotationOnComposedAnnotation() { <add> Class<?> element = ImplicitAliasesWithDefaultsClass.class; <add> String name = AliasesWithDefaults.class.getName(); <add> AliasesWithDefaults annotation = getMergedAnnotation(element, AliasesWithDefaults.class); <add> <add> assertThat(annotation).as("Should find @AliasesWithDefaults on " + element.getSimpleName()).isNotNull(); <add> assertThat(annotation.a1()).as("a1").isEqualTo("ImplicitAliasesWithDefaults"); <add> assertThat(annotation.a2()).as("a2").isEqualTo("ImplicitAliasesWithDefaults"); <add> <add> // Verify contracts between utility methods: <add> assertThat(isAnnotated(element, name)).isTrue(); <add> } <add> <ide> @Test <ide> void getMergedAnnotationAttributesWithInvalidConventionBasedComposedAnnotation() { <ide> Class<?> element = InvalidConventionBasedComposedContextConfigClass.class; <ide> static class MetaCycleAnnotatedClass { <ide> String[] xmlConfigFiles() default {}; <ide> } <ide> <del> <ide> @ContextConfig <ide> @Retention(RetentionPolicy.RUNTIME) <ide> @interface AliasedComposedContextConfig { <ide> static class MetaCycleAnnotatedClass { <ide> @interface ComposedImplicitAliasesContextConfig { <ide> } <ide> <add> @Retention(RetentionPolicy.RUNTIME) <add> @interface AliasesWithDefaults { <add> <add> @AliasFor("a2") <add> String a1() default "AliasesWithDefaults"; <add> <add> @AliasFor("a1") <add> String a2() default "AliasesWithDefaults"; <add> } <add> <add> @Retention(RetentionPolicy.RUNTIME) <add> @AliasesWithDefaults <add> @interface ImplicitAliasesWithDefaults { <add> <add> @AliasFor(annotation = AliasesWithDefaults.class, attribute = "a1") <add> String b1() default "ImplicitAliasesWithDefaults"; <add> <add> @AliasFor(annotation = AliasesWithDefaults.class, attribute = "a2") <add> String b2() default "ImplicitAliasesWithDefaults"; <add> } <add> <ide> @ImplicitAliasesContextConfig <ide> @Retention(RetentionPolicy.RUNTIME) <ide> @interface TransitiveImplicitAliasesContextConfig { <ide> static class ImplicitAliasesContextConfigClass2 { <ide> static class ImplicitAliasesContextConfigClass3 { <ide> } <ide> <add> @ImplicitAliasesWithDefaults <add> static class ImplicitAliasesWithDefaultsClass { <add> } <add> <ide> @TransitiveImplicitAliasesContextConfig(groovy = "test.groovy") <ide> static class TransitiveImplicitAliasesContextConfigClass { <ide> }
1
PHP
PHP
fix docblock declaration
a141f5120e5fa7e86c58de10f59513fd3fd80a38
<ide><path>src/Illuminate/Foundation/Auth/AuthenticatesAndRegistersUsers.php <ide> public function getRegister() <ide> /** <ide> * Handle a registration request for the application. <ide> * <del> * @param \Illuminate\Foundation\Http\FormRequest $request <add> * @param \Illuminate\Http\Request $request <ide> * @return \Illuminate\Http\Response <ide> */ <ide> public function postRegister(Request $request)
1
Python
Python
fix xlnet test
3268ebd2290800036fce0b931dc6c9b87b76e098
<ide><path>transformers/tests/modeling_xlnet_test.py <ide> def create_and_check_xlnet_base_model(self, config, input_ids_1, input_ids_2, in <ide> [[self.seq_length, self.batch_size, self.hidden_size]] * self.num_hidden_layers) <ide> <ide> def create_and_check_xlnet_base_model_with_att_output(self, config, input_ids_1, input_ids_2, input_ids_q, perm_mask, input_mask, <del> target_mapping, segment_ids, lm_labels, sequence_labels, is_impossible_labels): <add> target_mapping, segment_ids, lm_labels, sequence_labels, is_impossible_labels, token_labels): <ide> model = XLNetModel(config) <ide> model.eval() <ide>
1
Ruby
Ruby
use canonicalized name in nosuchkegerror message
e236901e56addff6c887db15c7db47360e463359
<ide><path>Library/Homebrew/extend/ARGV.rb <ide> def kegs <ide> require 'formula' <ide> @kegs ||= downcased_unique_named.collect do |name| <ide> canonical_name = Formula.canonical_name(name) <del> rack = HOMEBREW_CELLAR + if canonical_name.include? "/" <add> <add> if canonical_name.include? "/" <ide> # canonical_name returns a path if it was a formula installed via a <ide> # URL. And we only want the name. FIXME that function is insane. <del> Pathname.new(canonical_name).stem <add> rack = HOMEBREW_CELLAR/Pathname.new(canonical_name).stem <ide> else <del> canonical_name <add> rack = HOMEBREW_CELLAR/canonical_name <ide> end <del> dirs = rack.children.select{ |pn| pn.directory? } rescue [] <del> raise NoSuchKegError.new(name) if not rack.directory? or dirs.length == 0 <add> <add> dirs = rack.directory? ? rack.subdirs : [] <add> raise NoSuchKegError.new(rack.basename.to_s) if not rack.directory? or dirs.empty? <ide> <ide> linked_keg_ref = HOMEBREW_REPOSITORY/"Library/LinkedKegs"/name <ide>
1
Python
Python
improve assert message of assert_array_max_ulp
48089a72d6f4c3805ce0a53618cc9652287c5018
<ide><path>numpy/testing/_private/utils.py <ide> def assert_array_max_ulp(a, b, maxulp=1, dtype=None): <ide> import numpy as np <ide> ret = nulp_diff(a, b, dtype) <ide> if not np.all(ret <= maxulp): <del> raise AssertionError("Arrays are not almost equal up to %g ULP" % <del> maxulp) <add> raise AssertionError("Arrays are not almost equal up to %g " <add> "ULP (max difference is %g ULP)" % <add> (maxulp, np.max(ret))) <ide> return ret <ide> <ide>
1
Text
Text
add @shezi thanks!
e32aaa29b8e8665faf63ab4646cfba7aed6d9d8c
<ide><path>docs/topics/credits.md <ide> The following people have helped make REST framework great. <ide> * Michael Mior - [michaelmior] <ide> * Marc Tamlyn - [mjtamlyn] <ide> * Richard Wackerbarth - [wackerbarth] <add>* Johannes Spielmann - [shezi] <ide> <ide> Many thanks to everyone who's contributed to the project. <ide> <ide> You can also contact [@_tomchristie][twitter] directly on twitter. <ide> [michaelmior]: https://github.com/michaelmior <ide> [mjtamlyn]: https://github.com/mjtamlyn <ide> [wackerbarth]: https://github.com/wackerbarth <add>[shezi]: https://github.com/shezi
1
Javascript
Javascript
save shared data structures to local variables
c5f2eeaafe09026bceda4b90981836eed6a607e6
<ide><path>packages/ember-handlebars/lib/helpers/binding.js <ide> require('ember-handlebars/views/metamorph_view'); <ide> <ide> var get = Ember.get, getPath = Ember.getPath, set = Ember.set, fmt = Ember.String.fmt; <ide> <add>var EmberHandlebars = Ember.Handlebars, helpers = EmberHandlebars.helpers; <add>var helpers = EmberHandlebars.helpers; <add> <ide> (function() { <ide> // Binds a property into the DOM. This will create a hook in DOM that the <ide> // KVO system will look for and upate if the property changes. <ide> var get = Ember.get, getPath = Ember.getPath, set = Ember.set, fmt = Ember.Strin <ide> data.buffer.push(getPath(this, property)); <ide> } <ide> }; <del> <add> <ide> /** <ide> '_triageMustache' is used internally select between a binding and helper for <ide> the given context. Until this point, it would be hard to determine if the <ide> mustache is a property reference or a regular helper reference. This triage <ide> helper resolves that. <del> <add> <ide> This would not be typically invoked by directly. <del> <add> <ide> @private <ide> @name Handlebars.helpers._triageMustache <ide> @param {String} property Property/helperID to triage <ide> @param {Function} fn Context to provide for rendering <ide> @returns {String} HTML string <ide> */ <del> Ember.Handlebars.registerHelper('_triageMustache', function(property, fn) { <add> EmberHandlebars.registerHelper('_triageMustache', function(property, fn) { <ide> ember_assert("You cannot pass more than one argument to the _triageMustache helper", arguments.length <= 2); <del> if (Ember.Handlebars.helpers[property]) { <del> return Ember.Handlebars.helpers[property].call(this, fn); <add> if (helpers[property]) { <add> return helpers[property].call(this, fn); <ide> } <ide> else { <del> return Ember.Handlebars.helpers.bind.apply(this, arguments); <add> return helpers.bind.apply(this, arguments); <ide> } <ide> }); <ide> <ide> var get = Ember.get, getPath = Ember.getPath, set = Ember.set, fmt = Ember.Strin <ide> @param {Function} fn Context to provide for rendering <ide> @returns {String} HTML string <ide> */ <del> Ember.Handlebars.registerHelper('bind', function(property, fn) { <add> EmberHandlebars.registerHelper('bind', function(property, fn) { <ide> ember_assert("You cannot pass more than one argument to the bind helper", arguments.length <= 2); <ide> <ide> var context = (fn.contexts && fn.contexts[0]) || this; <ide> var get = Ember.get, getPath = Ember.getPath, set = Ember.set, fmt = Ember.Strin <ide> @param {Function} fn Context to provide for rendering <ide> @returns {String} HTML string <ide> */ <del> Ember.Handlebars.registerHelper('boundIf', function(property, fn) { <add> EmberHandlebars.registerHelper('boundIf', function(property, fn) { <ide> var context = (fn.contexts && fn.contexts[0]) || this; <ide> <ide> return bind.call(context, property, fn, true, function(result) { <ide> var get = Ember.get, getPath = Ember.getPath, set = Ember.set, fmt = Ember.Strin <ide> @param {Hash} options <ide> @returns {String} HTML string <ide> */ <del>Ember.Handlebars.registerHelper('with', function(context, options) { <add>EmberHandlebars.registerHelper('with', function(context, options) { <ide> ember_assert("You must pass exactly one argument to the with helper", arguments.length == 2); <ide> ember_assert("You must pass a block to the with helper", options.fn && options.fn !== Handlebars.VM.noop); <ide> <del> return Ember.Handlebars.helpers.bind.call(options.contexts[0], context, options); <add> return helpers.bind.call(options.contexts[0], context, options); <ide> }); <ide> <ide> <ide> Ember.Handlebars.registerHelper('with', function(context, options) { <ide> @param {Hash} options <ide> @returns {String} HTML string <ide> */ <del>Ember.Handlebars.registerHelper('if', function(context, options) { <add>EmberHandlebars.registerHelper('if', function(context, options) { <ide> ember_assert("You must pass exactly one argument to the if helper", arguments.length == 2); <ide> ember_assert("You must pass a block to the if helper", options.fn && options.fn !== Handlebars.VM.noop); <ide> <del> return Ember.Handlebars.helpers.boundIf.call(options.contexts[0], context, options); <add> return helpers.boundIf.call(options.contexts[0], context, options); <ide> }); <ide> <ide> /** <ide> Ember.Handlebars.registerHelper('if', function(context, options) { <ide> @param {Hash} options <ide> @returns {String} HTML string <ide> */ <del>Ember.Handlebars.registerHelper('unless', function(context, options) { <add>EmberHandlebars.registerHelper('unless', function(context, options) { <ide> ember_assert("You must pass exactly one argument to the unless helper", arguments.length == 2); <ide> ember_assert("You must pass a block to the unless helper", options.fn && options.fn !== Handlebars.VM.noop); <ide> <ide> Ember.Handlebars.registerHelper('unless', function(context, options) { <ide> options.fn = inverse; <ide> options.inverse = fn; <ide> <del> return Ember.Handlebars.helpers.boundIf.call(options.contexts[0], context, options); <add> return helpers.boundIf.call(options.contexts[0], context, options); <ide> }); <ide> <ide> /** <ide> Ember.Handlebars.registerHelper('unless', function(context, options) { <ide> @param {Hash} options <ide> @returns {String} HTML string <ide> */ <del>Ember.Handlebars.registerHelper('bindAttr', function(options) { <add>EmberHandlebars.registerHelper('bindAttr', function(options) { <ide> <ide> var attrs = options.hash; <ide> <ide> Ember.Handlebars.registerHelper('bindAttr', function(options) { <ide> // Handle classes differently, as we can bind multiple classes <ide> var classBindings = attrs['class']; <ide> if (classBindings !== null && classBindings !== undefined) { <del> var classResults = Ember.Handlebars.bindClasses(this, classBindings, view, dataId); <add> var classResults = EmberHandlebars.bindClasses(this, classBindings, view, dataId); <ide> ret.push('class="' + classResults.join(' ') + '"'); <ide> delete attrs['class']; <ide> } <ide> Ember.Handlebars.registerHelper('bindAttr', function(options) { <ide> <ide> // Add the unique identifier <ide> ret.push('data-bindAttr-' + dataId + '="' + dataId + '"'); <del> return new Ember.Handlebars.SafeString(ret.join(' ')); <add> return new EmberHandlebars.SafeString(ret.join(' ')); <ide> }); <ide> <ide> /** <ide> Ember.Handlebars.registerHelper('bindAttr', function(options) { <ide> <ide> @returns {Array} An array of class names to add <ide> */ <del>Ember.Handlebars.bindClasses = function(context, classBindings, view, bindAttrId) { <add>EmberHandlebars.bindClasses = function(context, classBindings, view, bindAttrId) { <ide> var ret = [], newClass, value, elem; <ide> <ide> // Helper method to retrieve the property from the context and <ide> // determine which class string to return, based on whether it is <ide> // a Boolean or not. <ide> var classStringForProperty = function(property) { <ide> var split = property.split(':'), <del> property = split[0], <ide> className = split[1]; <ide> <add> property = split[0]; <add> <ide> var val = getPath(context, property); <ide> <ide> // If value is a Boolean and true, return the dasherized property
1
Go
Go
handle long log messages correctly on sizedlogger
bb11365e96a4f25fe20606b30cbfb79998fadff3
<ide><path>daemon/logger/awslogs/cloudwatchlogs.go <ide> func (l *logStream) Name() string { <ide> return name <ide> } <ide> <add>// BufSize returns the maximum bytes CloudWatch can handle. <ide> func (l *logStream) BufSize() int { <ide> return maximumBytesPerEvent <ide> } <ide><path>daemon/logger/copier.go <ide> func (c *Copier) copySrc(name string, src io.Reader) { <ide> <ide> bufSize := defaultBufSize <ide> if sizedLogger, ok := c.dst.(SizedLogger); ok { <del> bufSize = sizedLogger.BufSize() <add> size := sizedLogger.BufSize() <add> // Loggers that wrap another loggers would have BufSize(), but cannot return the size <add> // when the wrapped loggers doesn't have BufSize(). <add> if size > 0 { <add> bufSize = size <add> } <ide> } <ide> buf := make([]byte, bufSize) <ide> <ide><path>daemon/logger/copier_test.go <ide> func TestCopierSlow(t *testing.T) { <ide> } <ide> <ide> func TestCopierWithSized(t *testing.T) { <add> t.Run("as is", func(t *testing.T) { <add> testCopierWithSized(t, func(l SizedLogger) SizedLogger { <add> return l <add> }) <add> }) <add> t.Run("With RingLogger", func(t *testing.T) { <add> testCopierWithSized(t, func(l SizedLogger) SizedLogger { <add> return newRingLogger(l, Info{}, defaultRingMaxSize) <add> }) <add> }) <add>} <add> <add>func testCopierWithSized(t *testing.T, loggerFactory func(SizedLogger) SizedLogger) { <ide> var jsonBuf bytes.Buffer <ide> expectedMsgs := 2 <del> sizedLogger := &TestSizedLoggerJSON{Encoder: json.NewEncoder(&jsonBuf)} <del> logbuf := bytes.NewBufferString(strings.Repeat(".", sizedLogger.BufSize()*expectedMsgs)) <add> sizedLogger := loggerFactory(&TestSizedLoggerJSON{Encoder: json.NewEncoder(&jsonBuf)}) <add> <add> size := sizedLogger.BufSize() <add> if size < 0 { <add> size = 100 <add> } <add> logbuf := bytes.NewBufferString(strings.Repeat(".", size*expectedMsgs)) <ide> c := NewCopier(map[string]io.Reader{"stdout": logbuf}, sizedLogger) <ide> <ide> c.Run() <ide> // Wait for Copier to finish writing to the buffered logger. <ide> c.Wait() <ide> c.Close() <ide> <add> sizedLogger.Close() <add> <ide> recvdMsgs := 0 <ide> dec := json.NewDecoder(&jsonBuf) <ide> for { <ide> func TestCopierWithSized(t *testing.T) { <ide> recvdMsgs++ <ide> } <ide> if recvdMsgs != expectedMsgs { <del> t.Fatalf("expected to receive %d messages, actually received %d", expectedMsgs, recvdMsgs) <add> t.Fatalf("expected to receive %d messages, actually received %d %q", expectedMsgs, recvdMsgs, jsonBuf.String()) <ide> } <ide> } <ide> <ide><path>daemon/logger/loggerutils/cache/local_cache.go <ide> type loggerWithCache struct { <ide> cache logger.Logger <ide> } <ide> <add>var _ logger.SizedLogger = &loggerWithCache{} <add> <add>// BufSize returns the buffer size of the underlying logger. <add>// Returns -1 if the logger doesn't match SizedLogger interface. <add>func (l *loggerWithCache) BufSize() int { <add> if sl, ok := l.l.(logger.SizedLogger); ok { <add> return sl.BufSize() <add> } <add> return -1 <add>} <add> <ide> func (l *loggerWithCache) Log(msg *logger.Message) error { <ide> // copy the message as the original will be reset once the call to `Log` is complete <ide> dup := logger.NewMessage() <ide><path>daemon/logger/ring.go <ide> type RingLogger struct { <ide> closeFlag int32 <ide> } <ide> <add>var _ SizedLogger = &RingLogger{} <add> <ide> type ringWithReader struct { <ide> *RingLogger <ide> } <ide> func NewRingLogger(driver Logger, logInfo Info, maxSize int64) Logger { <ide> return l <ide> } <ide> <add>// BufSize returns the buffer size of the underlying logger. <add>// Returns -1 if the logger doesn't match SizedLogger interface. <add>func (r *RingLogger) BufSize() int { <add> if sl, ok := r.l.(SizedLogger); ok { <add> return sl.BufSize() <add> } <add> return -1 <add>} <add> <ide> // Log queues messages into the ring buffer <ide> func (r *RingLogger) Log(msg *Message) error { <ide> if r.closed() {
5
PHP
PHP
fix doctype declarations
936aa9159ef916a9b26444f8b70c6d93457b1d88
<ide><path>resources/views/errors/503.blade.php <add><!DOCTYPE html> <ide> <html> <ide> <head> <ide> <title>Be right back.</title> <ide><path>resources/views/welcome.blade.php <add><!DOCTYPE html> <ide> <html> <ide> <head> <ide> <title>Laravel</title>
2
Ruby
Ruby
remove habtm special cases from reflections
957d7ae037b156e69c5999e48038b5c6b7235159
<ide><path>activerecord/lib/active_record/reflection.rb <ide> module Reflection # :nodoc: <ide> <ide> def self.create(macro, name, scope, options, ar) <ide> case macro <del> when :has_and_belongs_to_many <del> klass = AssociationReflection <ide> when :has_many, :belongs_to, :has_one <ide> klass = options[:through] ? ThroughReflection : AssociationReflection <ide> when :composed_of <ide> def klass <ide> <ide> def initialize(macro, name, scope, options, active_record) <ide> super <del> @collection = [:has_many, :has_and_belongs_to_many].include?(macro) <add> @collection = :has_many == macro <ide> @automatic_inverse_of = nil <ide> @type = options[:as] && "#{options[:as]}_type" <ide> @foreign_type = options[:foreign_type] || "#{name}_type" <ide> def counter_cache_column <ide> <ide> def check_validity! <ide> check_validity_of_inverse! <del> <del> if has_and_belongs_to_many? && association_foreign_key == foreign_key <del> raise HasAndBelongsToManyAssociationForeignKeyNeeded.new(self) <del> end <ide> end <ide> <ide> def check_validity_of_inverse! <ide> def belongs_to? <ide> macro == :belongs_to <ide> end <ide> <del> def has_and_belongs_to_many? <del> macro == :has_and_belongs_to_many <del> end <del> <ide> def association_class <ide> case macro <ide> when :belongs_to <ide> def association_class <ide> else <ide> Associations::BelongsToAssociation <ide> end <del> when :has_and_belongs_to_many <del> Associations::HasAndBelongsToManyAssociation <ide> when :has_many <ide> if options[:through] <ide> Associations::HasManyThroughAssociation <ide> def source_macro <ide> <ide> # A through association is nested if there would be more than one join table <ide> def nested? <del> chain.length > 2 || through_reflection.has_and_belongs_to_many? <add> chain.length > 2 <ide> end <ide> <ide> # We want to use the klass from this reflection, rather than just delegate straight to
1
Text
Text
change incorrect example url
df33035a3c10934f153bc5a43042cf78a3dfce52
<ide><path>docs/tutorial/2-requests-and-responses.md <ide> Notice that we're no longer explicitly tying our requests or responses to a give <ide> <ide> ## Adding optional format suffixes to our URLs <ide> <del>To take advantage of the fact that our responses are no longer hardwired to a single content type let's add support for format suffixes to our API endpoints. Using format suffixes gives us URLs that explicitly refer to a given format, and means our API will be able to handle URLs such as [http://example.com/api/items/4/.json][json-url]. <add>To take advantage of the fact that our responses are no longer hardwired to a single content type let's add support for format suffixes to our API endpoints. Using format suffixes gives us URLs that explicitly refer to a given format, and means our API will be able to handle URLs such as [http://example.com/api/items/4.json][json-url]. <ide> <ide> Start by adding a `format` keyword argument to both of the views, like so. <ide> <ide> See the [browsable api][browsable-api] topic for more information about the brow <ide> <ide> In [tutorial part 3][tut-3], we'll start using class-based views, and see how generic views reduce the amount of code we need to write. <ide> <del>[json-url]: http://example.com/api/items/4/.json <add>[json-url]: http://example.com/api/items/4.json <ide> [devserver]: http://127.0.0.1:8000/snippets/ <ide> [browsable-api]: ../topics/browsable-api.md <ide> [tut-1]: 1-serialization.md
1
Java
Java
add context to redbox report api
e3c27f585aaeb685e86250f45fc790c06932af0d
<ide><path>ReactAndroid/src/main/java/com/facebook/react/devsupport/DevSupportManagerImpl.java <ide> public void run() { <ide> // JS errors are reported here after source mapping. <ide> if (mRedBoxHandler != null) { <ide> mRedBoxHandler.handleRedbox(message, stack, RedBoxHandler.ErrorType.JS); <del> mRedBoxDialog.resetReporting(true); <add> mRedBoxDialog.resetReporting(); <ide> } <ide> mRedBoxDialog.show(); <ide> } <ide> public void run() { <ide> // inside {@link #updateJSError} after source mapping. <ide> if (mRedBoxHandler != null && errorType == ErrorType.NATIVE) { <ide> mRedBoxHandler.handleRedbox(message, stack, RedBoxHandler.ErrorType.NATIVE); <del> mRedBoxDialog.resetReporting(true); <del> } else { <del> mRedBoxDialog.resetReporting(false); <ide> } <add> mRedBoxDialog.resetReporting(); <ide> mRedBoxDialog.show(); <ide> } <ide> }); <ide><path>ReactAndroid/src/main/java/com/facebook/react/devsupport/RedBoxDialog.java <ide> public void onClick(View view) { <ide> String sourceUrl = mDevSupportManager.getSourceUrl(); <ide> <ide> mRedBoxHandler.reportRedbox( <del> title, <del> stack, <del> sourceUrl, <del> Assertions.assertNotNull(mReportCompletedListener)); <add> view.getContext(), <add> title, <add> stack, <add> sourceUrl, <add> Assertions.assertNotNull(mReportCompletedListener)); <ide> } <ide> }; <ide> <ide> public void setExceptionDetails(String title, StackFrame[] stack) { <ide> /** <ide> * Show the report button, hide the report textview and the loading indicator. <ide> */ <del> public void resetReporting(boolean enabled) { <add> public void resetReporting() { <ide> if (mRedBoxHandler == null || !mRedBoxHandler.isReportEnabled()) { <ide> return; <ide> } <ide> isReporting = false; <ide> Assertions.assertNotNull(mReportTextView).setVisibility(View.GONE); <ide> Assertions.assertNotNull(mLoadingIndicator).setVisibility(View.GONE); <ide> Assertions.assertNotNull(mLineSeparator).setVisibility(View.GONE); <del> Assertions.assertNotNull(mReportButton).setVisibility( <del> enabled ? View.VISIBLE : View.GONE); <add> Assertions.assertNotNull(mReportButton).setVisibility(View.VISIBLE); <ide> Assertions.assertNotNull(mReportButton).setEnabled(true); <ide> } <ide> <ide><path>ReactAndroid/src/main/java/com/facebook/react/devsupport/RedBoxHandler.java <ide> <ide> package com.facebook.react.devsupport; <ide> <add>import android.content.Context; <ide> import android.text.SpannedString; <ide> <ide> import com.facebook.react.devsupport.interfaces.StackFrame; <ide> interface ReportCompletedListener { <ide> * Report the information from the redbox and set up a callback listener. <ide> */ <ide> void reportRedbox( <del> String title, <del> StackFrame[] stack, <del> String sourceUrl, <del> ReportCompletedListener reportCompletedListener); <add> Context context, <add> String title, <add> StackFrame[] stack, <add> String sourceUrl, <add> ReportCompletedListener reportCompletedListener); <ide> }
3
Text
Text
update starter template
287b267305e84debbfcff2001faf832bf74e0146
<ide><path>.github/ISSUE_TEMPLATE.md <ide> ## Description <ide> Briefly describe the issue. <del>Include a [reduced test case](https://css-tricks.com/reduced-test-cases/), we have a [starter template](http://jsbin.com/axedog/edit?html,output) on JSBin you can use. <add>Include a [reduced test case](https://css-tricks.com/reduced-test-cases/), we have a [starter template](https://codepen.io/gkatsev/pen/GwZegv?editors=1000#0) on JSBin you can use. <ide> <ide> ## Steps to reproduce <ide> Explain in detail the exact steps necessary to reproduce the issue. <ide><path>.github/PULL_REQUEST_TEMPLATE.md <ide> Please list the specific changes involved in this pull request. <ide> - [ ] Change has been verified in an actual browser (Chome, Firefox, IE) <ide> - [ ] Unit Tests updated or fixed <ide> - [ ] Docs/guides updated <del> - [ ] Example created ([starter template on JSBin](http://jsbin.com/axedog/edit?html,output)) <add> - [ ] Example created ([starter template on JSBin](https://codepen.io/gkatsev/pen/GwZegv?editors=1000#0)) <ide> - [ ] Reviewed by Two Core Contributors <ide><path>CONTRIBUTING.md <ide> Guidelines for bug reports: <ide> 1. If your issue is with a particular video.js plugin or subproject, please open an issue against that project. See [list of some potential other projects above](#other-repositories-where-issues-could-be-filed) <ide> 1. Use the [GitHub issue search](https://github.com/videojs/video.js/issues) — check if the issue has already been reported. <ide> 1. Check if the issue has already been fixed — try to reproduce it using the latest `master` branch in the repository. <del>1. Isolate the problem — **create a [reduced test case](https://css-tricks.com/reduced-test-cases/)** with a live example. You can possibly use [this JSBin example](http://jsbin.com/axedog/edit) as a starting point -- don't forget to update it to the videojs version you use. <add>1. Isolate the problem — **create a [reduced test case](https://css-tricks.com/reduced-test-cases/)** with a live example. You can possibly use [this codepen tempalte](https://codepen.io/gkatsev/pen/GwZegv?editors=1000#0) as a starting point -- don't forget to update it to the videojs version you use. <ide> 1. Answer all questions in the [issue template][]. The questions in the issue template are designed to try and provide the maintainers with as much information possible to minimize back-and-forth to get the issue resolved. <ide> <ide> A good bug report should be as detailed as possible, so that others won't have to follow up for the essential details. <ide><path>docs/guides/faq.md <ide> Yes! See [ReactJS integration example][react-guide]. <ide> <ide> [slack]: https://videojs.slack.com <ide> <del>[starter-example]: https://jsbin.com/axedog/edit?html,output <add>[starter-example]: https://codepen.io/gkatsev/pen/GwZegv?editors=1000#0 <ide> <ide> [techorder]: /docs/guides/options.md#techorder <ide>
4
Ruby
Ruby
fix punctuation errors
31110c50e499067ccb8b4c0693d81f4153e6e155
<ide><path>activeresource/lib/active_resource/validations.rb <ide> class ResourceInvalid < ClientError #:nodoc: <ide> # Active Resource validation is reported to and from this object, which is used by Base#save <ide> # to determine whether the object in a valid state to be saved. See usage example in Validations. <ide> class Errors < ActiveModel::Errors <del> # Grabs errors from an array of messages (like ActiveRecord::Validations) <add> # Grabs errors from an array of messages (like ActiveRecord::Validations). <ide> # The second parameter directs the errors cache to be cleared (default) <del> # or not (by passing true) <add> # or not (by passing true). <ide> def from_array(messages, save_cache = false) <ide> clear unless save_cache <ide> humanized_attributes = Hash[@base.attributes.keys.map { |attr_name| [attr_name.humanize, attr_name] }] <ide> def save_with_validation(options={}) <ide> <ide> # clear the remote validations so they don't interfere with the local <ide> # ones. Otherwise we get an endless loop and can never change the <del> # fields so as to make the resource valid <add> # fields so as to make the resource valid. <ide> @remote_errors = nil <ide> if perform_validation && valid? || !perform_validation <ide> save_without_validation <ide> def save_with_validation(options={}) <ide> rescue ResourceInvalid => error <ide> # cache the remote errors because every call to <tt>valid?</tt> clears <ide> # all errors. We must keep a copy to add these back after local <del> # validations <add> # validations. <ide> @remote_errors = error <ide> load_remote_errors(@remote_errors, true) <ide> false <ide> end <ide> <ide> <ide> # Loads the set of remote errors into the object's Errors based on the <del> # content-type of the error-block received <add> # content-type of the error-block received. <ide> def load_remote_errors(remote_errors, save_cache = false ) #:nodoc: <ide> case self.class.format <ide> when ActiveResource::Formats[:xml]
1
Ruby
Ruby
remove old metadata when installing with `--force`
31d7d6e5f3ec88ffbaf8aa86ac6239e79cd9d160
<ide><path>Library/Homebrew/cask/lib/hbc/cask.rb <ide> def metadata_versioned_container_path <ide> end <ide> <ide> def metadata_path(timestamp = :latest, create = false) <del> return nil unless metadata_versioned_container_path.respond_to?(:join) <ide> if create && timestamp == :latest <ide> raise CaskError, "Cannot create metadata path when timestamp is :latest" <ide> end <ide><path>Library/Homebrew/cask/lib/hbc/installer.rb <ide> def disable_accessibility_access <ide> end <ide> <ide> def save_caskfile <del> timestamp = :now <del> create = true <del> savedir = @cask.metadata_subdir("Casks", timestamp, create) <del> if Dir.entries(savedir).size > 2 <del> # should not happen <del> raise CaskAlreadyInstalledError, @cask unless force <del> savedir.rmtree <del> FileUtils.mkdir_p savedir <add> unless (old_savedirs = Pathname.glob(@cask.metadata_path("*"))).empty? <add> old_savedirs.each(&:rmtree) <ide> end <del> FileUtils.copy(@cask.sourcefile_path, savedir) if @cask.sourcefile_path <add> <add> return unless @cask.sourcefile_path <add> <add> savedir = @cask.metadata_subdir("Casks", :now, true) <add> savedir.mkpath <add> FileUtils.copy @cask.sourcefile_path, savedir <ide> end <ide> <ide> def uninstall
2
Python
Python
increase tolerance of failing heartbeat test
594c6eef6938d7a4975a0d87003160c2390d7ebb
<ide><path>tests/jobs/test_local_task_job.py <ide> def test_heartbeat_failed_fast(self): <ide> time2 = heartbeat_records[i] <ide> # Assert that difference small enough <ide> delta = (time2 - time1).total_seconds() <del> assert abs(delta - job.heartrate) < 0.5 <add> assert abs(delta - job.heartrate) < 0.8 <ide> <ide> def test_mark_success_no_kill(self, caplog, get_test_dag, session): <ide> """
1
Python
Python
remove extra whitespace
8dd800dd9afad99f7d8dd9ab8a8f059b93d7f92b
<ide><path>celery/worker/request.py <ide> def __optimize__(): <ide> @python_2_unicode_compatible <ide> class Request(object): <ide> """A request for task execution.""" <del> <add> <ide> acknowledged = False <ide> time_start = None <ide> worker_pid = None <ide> class Request(object): <ide> _terminate_on_ack = None <ide> _apply_result = None <ide> _tzlocal = None <del> <add> <ide> if not IS_PYPY: # pragma: no cover <ide> __slots__ = ( <ide> '_app', '_type', 'name', 'id', '_root_id', '_parent_id', <ide> class Request(object): <ide> '_args', '_kwargs', '_decoded', '__payload', <ide> '__weakref__', '__dict__', <ide> ) <del> <add> <ide> def __init__(self, message, on_ack=noop, <ide> hostname=None, eventer=None, app=None, <ide> connection_errors=None, request_dict=None, <ide> def __init__(self, message, on_ack=noop, <ide> self._eventer = eventer <ide> self._connection_errors = connection_errors or () <ide> self._task = task or self._app.tasks[self._type] <del> <add> <ide> # timezone means the message is timezone-aware, and the only timezone <ide> # supported at this point is UTC. <ide> eta = self._request_dict.get('eta') <ide> def __init__(self, message, on_ack=noop, <ide> self._eta = maybe_make_aware(eta, self.tzlocal) <ide> else: <ide> self._eta = None <del> <add> <ide> expires = self._request_dict.get('expires') <ide> if expires is not None: <ide> try: <ide> def __init__(self, message, on_ack=noop, <ide> self._expires = maybe_make_aware(expires, self.tzlocal) <ide> else: <ide> self._expires = None <del> <add> <ide> delivery_info = message.delivery_info or {} <ide> properties = message.properties or {} <ide> self._delivery_info = { <ide> def __init__(self, message, on_ack=noop, <ide> @property <ide> def delivery_info(self): <ide> return self._delivery_info <del> <add> <ide> @property <ide> def message(self): <ide> return self._message <del> <add> <ide> @property <ide> def request_dict(self): <ide> return self._request_dict <del> <add> <ide> @property <ide> def body(self): <ide> return self._body <del> <add> <ide> @property <ide> def app(self): <ide> return self._app <del> <add> <ide> @property <ide> def utc(self): <ide> return self._utc <del> <add> <ide> @property <ide> def content_type(self): <ide> return self._content_type <del> <add> <ide> @property <ide> def content_encoding(self): <ide> return self._content_encoding <del> <add> <ide> @property <ide> def type(self): <ide> return self._type <del> <add> <ide> @property <ide> def root_id(self): <ide> return self._root_id <del> <add> <ide> @property <ide> def parent_id(self): <ide> return self._parent_id <del> <add> <ide> @property <ide> def argsrepr(self): <ide> return self._argsrepr <del> <add> <ide> @property <ide> def args(self): <ide> return self._args <del> <add> <ide> @property <ide> def kwargs(self): <ide> return self._kwargs <del> <add> <ide> @property <ide> def kwargsrepr(self): <ide> return self._kwargsrepr <del> <add> <ide> @property <ide> def on_ack(self): <ide> return self._on_ack <del> <add> <ide> @property <ide> def on_reject(self): <ide> return self._on_reject <del> <add> <ide> @on_reject.setter <ide> def on_reject(self, value): <ide> self._on_reject = value <del> <add> <ide> @property <ide> def hostname(self): <ide> return self._hostname <del> <add> <ide> @property <ide> def eventer(self): <ide> return self._eventer <del> <add> <ide> @eventer.setter <ide> def eventer(self, eventer): <ide> self._eventer = eventer <del> <add> <ide> @property <ide> def connection_errors(self): <ide> return self._connection_errors <del> <add> <ide> @property <ide> def task(self): <ide> return self._task <del> <add> <ide> @property <ide> def eta(self): <ide> return self._eta <del> <add> <ide> @property <ide> def expires(self): <ide> return self._expires <del> <add> <ide> @expires.setter <ide> def expires(self, value): <ide> self._expires = value <del> <add> <ide> @property <ide> def tzlocal(self): <ide> if self._tzlocal is None: <ide> def execute_using_pool(self, pool, **kwargs): <ide> task = self._task <ide> if self.revoked(): <ide> raise TaskRevokedError(task_id) <del> <add> <ide> time_limit, soft_time_limit = self.time_limits <ide> result = pool.apply_async( <ide> trace_task_ret, <ide> def execute_using_pool(self, pool, **kwargs): <ide> # cannot create weakref to None <ide> self._apply_result = maybe(ref, result) <ide> return result <del> <add> <ide> def execute(self, loglevel=None, logfile=None): <ide> """Execute the task in a :func:`~celery.app.trace.trace_task`. <ide> <ide> def execute(self, loglevel=None, logfile=None): <ide> """ <ide> if self.revoked(): <ide> return <del> <add> <ide> # acknowledge task as being processed. <ide> if not self.task.acks_late: <ide> self.acknowledge() <del> <add> <ide> _, _, embed = self._payload <ide> request = self._request_dict <ide> # pylint: disable=unpacking-non-sequence <ide> def execute(self, loglevel=None, logfile=None): <ide> app=self._app)[0] <ide> self.acknowledge() <ide> return retval <del> <add> <ide> def maybe_expire(self): <ide> """If expired, mark the task as revoked.""" <ide> if self._expires: <ide> now = datetime.now(self._expires.tzinfo) <ide> if now > self._expires: <ide> revoked_tasks.add(self.id) <ide> return True <del> <add> <ide> def terminate(self, pool, signal=None): <ide> signal = _signals.signum(signal or TERM_SIGNAME) <ide> if self.time_start: <ide> def terminate(self, pool, signal=None): <ide> obj = self._apply_result() # is a weakref <ide> if obj is not None: <ide> obj.terminate(signal) <del> <add> <ide> def _announce_revoked(self, reason, terminated, signum, expired): <ide> task_ready(self) <ide> self.send_event('task-revoked', <ide> def _announce_revoked(self, reason, terminated, signum, expired): <ide> self._already_revoked = True <ide> send_revoked(self.task, request=self._context, <ide> terminated=terminated, signum=signum, expired=expired) <del> <add> <ide> def revoked(self): <ide> """If revoked, skip task and mark state.""" <ide> expired = False <ide> def revoked(self): <ide> ) <ide> return True <ide> return False <del> <add> <ide> def send_event(self, type, **fields): <ide> if self._eventer and self._eventer.enabled and self.task.send_events: <ide> self._eventer.send(type, uuid=self.id, **fields) <del> <add> <ide> def on_accepted(self, pid, time_accepted): <ide> """Handler called when task is accepted by worker pool.""" <ide> self.worker_pid = pid <ide> def on_accepted(self, pid, time_accepted): <ide> debug('Task accepted: %s[%s] pid:%r', self.name, self.id, pid) <ide> if self._terminate_on_ack is not None: <ide> self.terminate(*self._terminate_on_ack) <del> <add> <ide> def on_timeout(self, soft, timeout): <ide> """Handler called if the task times out.""" <ide> if soft: <ide> def on_timeout(self, soft, timeout): <ide> error('Hard time limit (%ss) exceeded for %s[%s]', <ide> timeout, self.name, self.id) <ide> exc = TimeLimitExceeded(timeout) <del> <add> <ide> self.task.backend.mark_as_failure( <ide> self.id, exc, request=self._context, <ide> store_result=self.store_errors, <ide> ) <del> <add> <ide> if self.task.acks_late and self.task.acks_on_failure_or_timeout: <ide> self.acknowledge() <del> <add> <ide> def on_success(self, failed__retval__runtime, **kwargs): <ide> """Handler called if the task was successfully processed.""" <ide> failed, retval, runtime = failed__retval__runtime <ide> def on_success(self, failed__retval__runtime, **kwargs): <ide> raise retval.exception <ide> return self.on_failure(retval, return_ok=True) <ide> task_ready(self) <del> <add> <ide> if self.task.acks_late: <ide> self.acknowledge() <del> <add> <ide> self.send_event('task-succeeded', result=retval, runtime=runtime) <del> <add> <ide> def on_retry(self, exc_info): <ide> """Handler called if the task should be retried.""" <ide> if self.task.acks_late: <ide> self.acknowledge() <del> <add> <ide> self.send_event('task-retried', <ide> exception=safe_repr(exc_info.exception.exc), <ide> traceback=safe_str(exc_info.traceback)) <del> <add> <ide> def on_failure(self, exc_info, send_failed_event=True, return_ok=False): <ide> """Handler called if the task raised an exception.""" <ide> task_ready(self) <ide> def on_failure(self, exc_info, send_failed_event=True, return_ok=False): <ide> return self.reject(requeue=exc_info.exception.requeue) <ide> elif isinstance(exc_info.exception, Ignore): <ide> return self.acknowledge() <del> <add> <ide> exc = exc_info.exception <del> <add> <ide> if isinstance(exc, Retry): <ide> return self.on_retry(exc_info) <del> <add> <ide> # These are special cases where the process wouldn't've had <ide> # time to write the result. <ide> if isinstance(exc, Terminated): <ide> def on_failure(self, exc_info, send_failed_event=True, return_ok=False): <ide> send_failed_event = False <ide> elif ack: <ide> self.acknowledge() <del> <add> <ide> if send_failed_event: <ide> self.send_event( <ide> 'task-failed', <ide> exception=safe_repr(get_pickled_exception(exc_info.exception)), <ide> traceback=exc_info.traceback, <ide> ) <del> <add> <ide> if not return_ok: <ide> error('Task handler raised error: %r', exc, <ide> exc_info=exc_info.exc_info) <del> <add> <ide> def acknowledge(self): <ide> """Acknowledge task.""" <ide> if not self.acknowledged: <ide> self._on_ack(logger, self._connection_errors) <ide> self.acknowledged = True <del> <add> <ide> def reject(self, requeue=False): <ide> if not self.acknowledged: <ide> self._on_reject(logger, self._connection_errors, requeue) <ide> self.acknowledged = True <ide> self.send_event('task-rejected', requeue=requeue) <del> <add> <ide> def info(self, safe=False): <ide> return { <ide> 'id': self.id, <ide> def info(self, safe=False): <ide> 'delivery_info': self.delivery_info, <ide> 'worker_pid': self.worker_pid, <ide> } <del> <add> <ide> def humaninfo(self): <ide> return '{0.name}[{0.id}]'.format(self) <del> <add> <ide> def __str__(self): <ide> """``str(self)``.""" <ide> return ' '.join([ <ide> self.humaninfo(), <ide> ' ETA:[{0}]'.format(self._eta) if self._eta else '', <ide> ' expires:[{0}]'.format(self._expires) if self._expires else '', <ide> ]) <del> <add> <ide> def __repr__(self): <ide> """``repr(self)``.""" <ide> return '<{0}: {1} {2} {3}>'.format( <ide> type(self).__name__, self.humaninfo(), <ide> self._argsrepr, self._kwargsrepr, <ide> ) <del> <add> <ide> @cached_property <ide> def _payload(self): <ide> return self.__payload <del> <add> <ide> @cached_property <ide> def chord(self): <ide> # used by backend.mark_as_failure when failure is reported <ide> def chord(self): <ide> # payload is a property, so pylint doesn't think it's a tuple. <ide> _, _, embed = self._payload <ide> return embed.get('chord') <del> <add> <ide> @cached_property <ide> def errbacks(self): <ide> # used by backend.mark_as_failure when failure is reported <ide> def errbacks(self): <ide> # payload is a property, so pylint doesn't think it's a tuple. <ide> _, _, embed = self._payload <ide> return embed.get('errbacks') <del> <add> <ide> @cached_property <ide> def group(self): <ide> # used by backend.on_chord_part_return when failures reported <ide> # by parent process <ide> return self._request_dict.get('group') <del> <add> <ide> @cached_property <ide> def _context(self): <ide> """Context (:class:`~celery.app.task.Context`) of this task.""" <ide> def create_request_cls(base, task, pool, hostname, eventer, <ide> apply_async = pool.apply_async <ide> acks_late = task.acks_late <ide> events = eventer and eventer.enabled <del> <add> <ide> class Request(base): <del> <add> <ide> def execute_using_pool(self, pool, **kwargs): <ide> task_id = self.task_id <ide> if (self.expires or task_id in revoked_tasks) and self.revoked(): <ide> raise TaskRevokedError(task_id) <del> <add> <ide> time_limit, soft_time_limit = self.time_limits <ide> result = apply_async( <ide> trace, <ide> def execute_using_pool(self, pool, **kwargs): <ide> # pylint: disable=attribute-defined-outside-init <ide> self._apply_result = maybe(ref, result) <ide> return result <del> <add> <ide> def on_success(self, failed__retval__runtime, **kwargs): <ide> failed, retval, runtime = failed__retval__runtime <ide> if failed: <ide> def on_success(self, failed__retval__runtime, **kwargs): <ide> raise retval.exception <ide> return self.on_failure(retval, return_ok=True) <ide> task_ready(self) <del> <add> <ide> if acks_late: <ide> self.acknowledge() <del> <add> <ide> if events: <ide> self.send_event( <ide> 'task-succeeded', result=retval, runtime=runtime, <ide> ) <del> <add> <ide> return Request <ide><path>t/unit/worker/test_request.py <ide> def test_args(self): <ide> args = (2, 2) <ide> assert self.get_request( <ide> self.add.s(*args)).args == args <del> <add> <ide> def test_kwargs(self): <ide> kwargs = {'1': '2', '3': '4'} <ide> assert self.get_request( <ide> self.add.s(**kwargs)).kwargs == kwargs <del> <add> <ide> def test_info_function(self): <ide> import string <ide> import random <ide> def test_info_function(self): <ide> self.add.s(*args)).info(safe=True).get('args')) == args <ide> assert list(self.get_request( <ide> self.add.s(*args)).info(safe=False).get('args')) == args <del> <add> <ide> def test_no_shadow_header(self): <ide> request = self.get_request(self.add.s(2, 2), <ide> exclude_headers=['shadow'])
2
PHP
PHP
handle carbon 2 tests
ef681e23923540ddc9021af8b1e8c075faebaace
<ide><path>tests/Support/DateFacadeTest.php <ide> public function testCarbonImmutable() <ide> 'locale' => 'fr', <ide> ])); <ide> $this->assertSame('fr', Date::now()->locale); <del> Date::swap(null); <add> Date::swap(Carbon::class); <ide> $this->assertSame('en', Date::now()->locale); <ide> include_once __DIR__.'/fixtures/CustomDateClass.php'; <ide> Date::swap(\CustomDateClass::class); <ide><path>tests/Support/SupportCarbonTest.php <ide> <ide> use DateTime; <ide> use DateTimeInterface; <add>use Carbon\CarbonImmutable; <ide> use Illuminate\Support\Carbon; <ide> use PHPUnit\Framework\TestCase; <ide> use Carbon\Carbon as BaseCarbon; <ide> public function testCarbonAllowsCustomSerializer() <ide> <ide> public function testCarbonCanSerializeToJson() <ide> { <del> $this->assertSame([ <add> $this->assertSame(class_exists(CarbonImmutable::class) ? '2017-06-27T13:14:15.000000Z' : [ <ide> 'date' => '2017-06-27 13:14:15.000000', <ide> 'timezone_type' => 3, <ide> 'timezone' => 'UTC',
2
Javascript
Javascript
add tests for d3.geo.bounds
bdc7c3f9e6e63510ec0d5dc015006eae201a6954
<ide><path>test/geo/bounds-test.js <add>require("../env"); <add> <add>var vows = require("vows"), <add> assert = require("assert"); <add> <add>var suite = vows.describe("d3.geo.bounds"); <add> <add>var ε = 1e-6; <add> <add>suite.addBatch({ <add> "bounds": { <add> topic: function() { <add> return d3.geo.bounds; <add> }, <add> "Feature": function(bounds) { <add> assert.deepEqual(bounds({ <add> type: "Feature", <add> geometry: { <add> type: "MultiPoint", <add> coordinates: [[-123, 39], [-122, 38]] <add> } <add> }), [[-123, 38], [-122, 39]]) <add> }, <add> "FeatureCollection": function(bounds) { <add> assert.deepEqual(bounds({ <add> type: "FeatureCollection", <add> features: [ <add> { <add> type: "Feature", <add> geometry: { <add> type: "Point", <add> coordinates: [-123, 39] <add> } <add> }, <add> { <add> type: "Feature", <add> geometry: { <add> type: "Point", <add> coordinates: [-122, 38] <add> } <add> } <add> ] <add> }), [[-123, 38], [-122, 39]]) <add> }, <add> "GeometryCollection": function(bounds) { <add> assert.deepEqual(bounds({ <add> type: "GeometryCollection", <add> geometries: [ <add> { <add> type: "Point", <add> coordinates: [-123, 39] <add> }, <add> { <add> type: "Point", <add> coordinates: [-122, 38] <add> } <add> ] <add> }), [[-123, 38], [-122, 39]]) <add> }, <add> "LineString": function(bounds) { <add> assert.deepEqual(bounds({ <add> type: "LineString", <add> coordinates: [[-123, 39], [-122, 38]] <add> }), [[-123, 38], [-122, 39]]) <add> }, <add> "MultiLineString": function(bounds) { <add> assert.deepEqual(bounds({ <add> type: "MultiLineString", <add> coordinates: [[[-123, 39], [-122, 38]]] <add> }), [[-123, 38], [-122, 39]]) <add> }, <add> "MultiPoint": function(bounds) { <add> assert.deepEqual(bounds({ <add> type: "MultiPoint", <add> coordinates: [[-123, 39], [-122, 38]] <add> }), [[-123, 38], [-122, 39]]) <add> }, <add> "MultiPolygon": function(bounds) { <add> assert.deepEqual(bounds({ <add> type: "MultiPolygon", <add> coordinates: [[[[-123, 39], [-122, 39], [-122, 38], [-123, 39]], [[10, 20], [20, 20], [20, 10], [10, 10], [10, 20]]]] <add> }), [[-123, 38], [-122, 39]]) <add> }, <add> "Point": function(bounds) { <add> assert.deepEqual(bounds({ <add> type: "Point", <add> coordinates: [-123, 39] <add> }), [[-123, 39], [-123, 39]]) <add> }, <add> "Polygon": function(bounds) { <add> assert.deepEqual(bounds({ <add> type: "Polygon", <add> coordinates: [[[-123, 39], [-122, 39], [-122, 38], [-123, 39]], [[10, 20], [20, 20], [20, 10], [10, 10], [10, 20]]] <add> }), [[-123, 38], [-122, 39]]) <add> } <add> } <add>}); <add> <add>suite.export(module);
1
Java
Java
trim expressions supplied to @disabledif
b6220cc19d3cb924f8a62c77977732ea5e8340dc
<ide><path>spring-test/src/main/java/org/springframework/test/context/junit/jupiter/DisabledIfCondition.java <ide> private ConditionEvaluationResult evaluateDisabledIf(ExtensionContext extensionC <ide> Optional<DisabledIf> disabledIf = findMergedAnnotation(element, DisabledIf.class); <ide> Assert.state(disabledIf.isPresent(), () -> "@DisabledIf must be present on " + element); <ide> <del> String expression = disabledIf.map(DisabledIf::expression).filter(StringUtils::hasText).orElseThrow( <del> () -> new IllegalStateException( <del> String.format("The expression in @DisabledIf on [%s] must not be blank", element))); <add> // @formatter:off <add> String expression = disabledIf.map(DisabledIf::expression).map(String::trim).filter(StringUtils::hasLength) <add> .orElseThrow(() -> new IllegalStateException(String.format( <add> "The expression in @DisabledIf on [%s] must not be blank", element))); <add> // @formatter:on <ide> <ide> if (isDisabled(expression, extensionContext)) { <ide> String reason = disabledIf.map(DisabledIf::reason).filter(StringUtils::hasText).orElseGet( <ide><path>spring-test/src/test/java/org/springframework/test/context/junit/jupiter/DisabledIfTestCase.java <ide> void disabledByStringTrue() { <ide> fail("This test must be disabled"); <ide> } <ide> <add> @Test <add> @DisabledIf(" true ") <add> void disabledByStringTrueWithSurroundingWhitespace() { <add> fail("This test must be disabled"); <add> } <add> <ide> @Test <ide> @DisabledIf("TrUe") <ide> void disabledByStringTrueIgnoreCase() { <ide> void disabledByPropertyPlaceholder() { <ide> fail("This test must be disabled"); <ide> } <ide> <add> @Test <add> @DisabledIf("\t${foo} ") <add> void disabledByPropertyPlaceholderWithSurroundingWhitespace() { <add> fail("This test must be disabled"); <add> } <add> <ide> @Test <ide> @DisabledIf("#{T(java.lang.Boolean).TRUE}") <ide> void disabledBySpelBoolean() { <ide> fail("This test must be disabled"); <ide> } <ide> <add> @Test <add> @DisabledIf(" #{T(java.lang.Boolean).TRUE} ") <add> void disabledBySpelBooleanWithSurroundingWhitespace() { <add> fail("This test must be disabled"); <add> } <add> <ide> @Test <ide> @DisabledIf("#{'tr' + 'ue'}") <ide> void disabledBySpelStringConcatenation() {
2
Ruby
Ruby
fix ruby path for ruby 1.8
0357673f213046b3bd29109be2e14c978e2aca3d
<ide><path>Library/Homebrew/cmd/config.rb <ide> def describe_python <ide> def describe_ruby <ide> ruby = which "ruby" <ide> return "N/A" if ruby.nil? <del> ruby_binary = Utils.popen_read ruby, "-e", \ <add> ruby_binary = Utils.popen_read ruby, "-rrbconfig", "-e", \ <ide> 'include RbConfig;print"#{CONFIG["bindir"]}/#{CONFIG["ruby_install_name"]}#{CONFIG["EXEEXT"]}"' <ide> ruby_binary = Pathname.new(ruby_binary).realpath <ide> if ruby == ruby_binary
1
Javascript
Javascript
deprecate unused function converttocontext
488d28d391ceb1d86f2f704d8fb4080802dfead4
<ide><path>lib/repl.js <ide> function regexpEscape(s) { <ide> * @param {String} cmd The cmd to convert. <ide> * @return {String} The converted command. <ide> */ <del>REPLServer.prototype.convertToContext = function(cmd) { <add>// TODO(princejwesley): Remove it prior to v8.0.0 release <add>// Reference: https://github.com/nodejs/node/pull/7829 <add>REPLServer.prototype.convertToContext = util.deprecate(function(cmd) { <ide> const scopeVar = /^\s*var\s*([_\w\$]+)(.*)$/m; <ide> const scopeFunc = /^\s*function\s*([_\w\$]+)/; <ide> var matches; <ide> REPLServer.prototype.convertToContext = function(cmd) { <ide> } <ide> <ide> return cmd; <del>}; <add>}, 'replServer.convertToContext() is deprecated'); <ide> <ide> function bailOnIllegalToken(parser) { <ide> return parser._literal === null && <ide><path>test/parallel/test-repl-deprecated.js <add>'use strict'; <add>const common = require('../common'); <add>const assert = require('assert'); <add>const repl = require('repl'); <add> <add>const expected = [ <add> 'replServer.convertToContext() is deprecated' <add>]; <add> <add>process.on('warning', common.mustCall((warning) => { <add> assert.strictEqual(warning.name, 'DeprecationWarning'); <add> assert.notStrictEqual(expected.indexOf(warning.message), -1, <add> `unexpected error message: "${warning.message}"`); <add> // Remove a warning message after it is seen so that we guarantee that we get <add> // each message only once. <add> expected.splice(expected.indexOf(warning.message), 1); <add>}, expected.length)); <add> <add>// Create a dummy stream that does nothing <add>const stream = new common.ArrayStream(); <add> <add>const replServer = repl.start({ <add> input: stream, <add> output: stream <add>}); <add> <add>const cmd = replServer.convertToContext('var name = "nodejs"'); <add>assert.strictEqual(cmd, 'self.context.name = "nodejs"');
2
Ruby
Ruby
add example for a nil name in link_to
46a4ac8a3656fba62d9fbeee79cf8f7306d6a8aa
<ide><path>actionview/lib/action_view/helpers/url_helper.rb <ide> def _filtered_referrer # :nodoc: <ide> # link_to "Profiles", controller: "profiles" <ide> # # => <a href="/profiles">Profiles</a> <ide> # <add> # When name is +nil+ the href is presented instead <add> # <add> # link_to nil, "http://example.com" <add> # # => <a href="http://www.example.com">http://www.example.com</a> <add> # <ide> # You can use a block as well if your link target is hard to fit into the name parameter. ERB example: <ide> # <ide> # <%= link_to(@profile) do %>
1
Javascript
Javascript
remove $temporary$object types
8a59153bd7325055dcca33571ee0484f8f00fb30
<ide><path>Libraries/Components/Touchable/Touchable.flow.js <ide> import * as React from 'react'; <ide> * } <ide> */ <ide> <del>// Default amount "active" region protrudes beyond box <add>/** <add> * Touchable states. <add> */ <add> <add>const States = { <add> NOT_RESPONDER: 'NOT_RESPONDER', // Not the responder <add> RESPONDER_INACTIVE_PRESS_IN: 'RESPONDER_INACTIVE_PRESS_IN', // Responder, inactive, in the `PressRect` <add> RESPONDER_INACTIVE_PRESS_OUT: 'RESPONDER_INACTIVE_PRESS_OUT', // Responder, inactive, out of `PressRect` <add> RESPONDER_ACTIVE_PRESS_IN: 'RESPONDER_ACTIVE_PRESS_IN', // Responder, active, in the `PressRect` <add> RESPONDER_ACTIVE_PRESS_OUT: 'RESPONDER_ACTIVE_PRESS_OUT', // Responder, active, out of `PressRect` <add> RESPONDER_ACTIVE_LONG_PRESS_IN: 'RESPONDER_ACTIVE_LONG_PRESS_IN', // Responder, active, in the `PressRect`, after long press threshold <add> RESPONDER_ACTIVE_LONG_PRESS_OUT: 'RESPONDER_ACTIVE_LONG_PRESS_OUT', // Responder, active, out of `PressRect`, after long press threshold <add> ERROR: 'ERROR', <add>}; <add> <add>type State = <add> | typeof States.NOT_RESPONDER <add> | typeof States.RESPONDER_INACTIVE_PRESS_IN <add> | typeof States.RESPONDER_INACTIVE_PRESS_OUT <add> | typeof States.RESPONDER_ACTIVE_PRESS_IN <add> | typeof States.RESPONDER_ACTIVE_PRESS_OUT <add> | typeof States.RESPONDER_ACTIVE_LONG_PRESS_IN <add> | typeof States.RESPONDER_ACTIVE_LONG_PRESS_OUT <add> | typeof States.ERROR; <ide> <ide> /** <ide> * By convention, methods prefixed with underscores are meant to be @private, <ide> interface TouchableMixinType { <ide> * @return {object} State object to be placed inside of <ide> * `this.state.touchable`. <ide> */ <del> touchableGetInitialState: () => $TEMPORARY$object<{| <del> touchable: $TEMPORARY$object<{|responderID: null, touchState: void|}>, <del> |}>; <add> touchableGetInitialState: () => { <add> touchable: { <add> touchState: ?State, <add> responderID: ?PressEvent['currentTarget'], <add> }, <add> }; <ide> <ide> // ==== Hooks to Gesture Responder system ==== <ide> /** <ide><path>Libraries/Components/Touchable/Touchable.js <ide> const TouchableMixin = { <ide> * @return {object} State object to be placed inside of <ide> * `this.state.touchable`. <ide> */ <del> touchableGetInitialState: function (): $TEMPORARY$object<{| <del> touchable: $TEMPORARY$object<{|responderID: null, touchState: void|}>, <del> |}> { <add> touchableGetInitialState: function (): { <add> touchable: { <add> touchState: ?State, <add> responderID: ?PressEvent['currentTarget'], <add> }, <add> } { <ide> return { <ide> touchable: {touchState: undefined, responderID: null}, <ide> }; <ide><path>Libraries/Core/ReactNativeVersionCheck.js <ide> exports.checkVersions = function checkVersions(): void { <ide> }; <ide> <ide> function _formatVersion( <del> version: <del> | {major: number, minor: number, patch: number, prerelease: ?number} <del> | {major: number, minor: number, patch: number, prerelease: ?string} <del> | $TEMPORARY$object<{ <del> major: number, <del> minor: number, <del> patch: number, <del> prerelease: null, <del> }>, <add> version: (typeof Platform)['constants']['reactNativeVersion'], <ide> ): string { <ide> return ( <ide> `${version.major}.${version.minor}.${version.patch}` + <ide><path>Libraries/Interaction/PanResponder.js <ide> const PanResponder: PanResponderType = { <ide> * accordingly. (numberActiveTouches) may not be totally accurate unless you <ide> * are the responder. <ide> */ <del> create(config: PanResponderConfig): $TEMPORARY$object<{| <add> create(config: PanResponderConfig): { <ide> getInteractionHandle: () => ?number, <ide> panHandlers: PanHandlers, <del> |}> { <add> } { <ide> const interactionState = { <ide> handle: (null: ?number), <ide> }; <ide><path>Libraries/Lists/__tests__/VirtualizedSectionList-test.js <ide> describe('VirtualizedSectionList', () => { <ide> describe('scrollToLocation', () => { <ide> const ITEM_HEIGHT = 100; <ide> <del> const createVirtualizedSectionList = ( <del> props: void | $TEMPORARY$object<{stickySectionHeadersEnabled: boolean}>, <del> ) => { <add> const createVirtualizedSectionList = (props?: { <add> stickySectionHeadersEnabled: boolean, <add> }) => { <ide> const component = ReactTestRenderer.create( <ide> <VirtualizedSectionList <ide> sections={[ <ide><path>Libraries/LogBox/UI/LogBoxInspector.js <ide> const headerTitleMap = { <ide> component: 'Render Error', <ide> }; <ide> <del>function LogBoxInspectorBody( <del> props: $TEMPORARY$object<{log: LogBoxLog, onRetry: () => void}>, <del>) { <add>function LogBoxInspectorBody(props: {log: LogBoxLog, onRetry: () => void}) { <ide> const [collapsed, setCollapsed] = React.useState(true); <ide> <ide> React.useEffect(() => { <ide><path>Libraries/LogBox/UI/LogBoxInspectorStackFrame.js <ide> import LogBoxButton from './LogBoxButton'; <ide> import * as LogBoxStyle from './LogBoxStyle'; <ide> import * as React from 'react'; <ide> <del>type Props = $ReadOnly<{| <add>type Props = $ReadOnly<{ <ide> frame: StackFrame, <ide> onPress?: ?(event: PressEvent) => void, <del>|}>; <add>}>; <ide> <ide> function LogBoxInspectorStackFrame(props: Props): React.Node { <ide> const {frame, onPress} = props; <ide><path>Libraries/LogBox/UI/LogBoxNotification.js <ide> import LogBoxMessage from './LogBoxMessage'; <ide> import * as LogBoxStyle from './LogBoxStyle'; <ide> import * as React from 'react'; <ide> <del>type Props = $ReadOnly<{| <add>type Props = $ReadOnly<{ <ide> log: LogBoxLog, <ide> totalLogCount: number, <ide> level: 'warn' | 'error', <ide> onPressOpen: () => void, <ide> onPressDismiss: () => void, <del>|}>; <add>}>; <ide> <ide> function LogBoxLogNotification(props: Props): React.Node { <ide> const {totalLogCount, level, log} = props; <ide> function LogBoxLogNotification(props: Props): React.Node { <ide> ); <ide> } <ide> <del>function CountBadge( <del> props: $TEMPORARY$object<{count: number, level: 'error' | 'warn'}>, <del>) { <add>function CountBadge(props: {count: number, level: 'error' | 'warn'}) { <ide> return ( <ide> <View style={countStyles.outside}> <ide> {/* $FlowFixMe[incompatible-type] (>=0.114.0) This suppression was added <ide> function CountBadge( <ide> ); <ide> } <ide> <del>function Message(props: $TEMPORARY$object<{message: MessageType}>) { <add>function Message(props: {message: MessageType}) { <ide> return ( <ide> <View style={messageStyles.container}> <ide> <Text numberOfLines={1} style={messageStyles.text}> <ide> function Message(props: $TEMPORARY$object<{message: MessageType}>) { <ide> ); <ide> } <ide> <del>function DismissButton(props: $TEMPORARY$object<{onPress: () => void}>) { <add>function DismissButton(props: {onPress: () => void}) { <ide> return ( <ide> <View style={dismissStyles.container}> <ide> <LogBoxButton <ide><path>Libraries/ReactNative/getCachedComponentWithDebugName.js <ide> * @format <ide> */ <ide> <del>import type {AbstractComponent, Node} from 'react'; <add>import type {AbstractComponent} from 'react'; <ide> <del>type NoopComponent = AbstractComponent<{children: Node}>; <add>import * as React from 'react'; <add> <add>type NoopComponent = AbstractComponent<{children: React.Node}>; <ide> <ide> const cache: Map< <ide> string, // displayName <ide> export default function getCachedComponentWithDisplayName( <ide> let ComponentWithDisplayName = cache.get(displayName); <ide> <ide> if (!ComponentWithDisplayName) { <del> ComponentWithDisplayName = ({ <del> children, <del> }: $TEMPORARY$object<{children: Node}>) => children; <add> ComponentWithDisplayName = ({children}: {children: React.Node}) => children; <ide> // $FlowFixMe[prop-missing] <ide> ComponentWithDisplayName.displayName = displayName; <ide> cache.set(displayName, ComponentWithDisplayName); <ide><path>Libraries/Utilities/__tests__/useRefEffect-test.js <ide> import {act, create} from 'react-test-renderer'; <ide> function TestView({ <ide> childKey = null, <ide> effect, <del>}: <del> | $FlowFixMe <del> | $TEMPORARY$object<{ <del> childKey: $TEMPORARY$string<'bar'>, <del> effect: () => () => void, <del> }> <del> | $TEMPORARY$object<{childKey: $TEMPORARY$string<'foo'>, effect: () => void}> <del> | $TEMPORARY$object<{ <del> childKey: $TEMPORARY$string<'foo'>, <del> effect: () => () => void, <del> }>) { <add>}: { <add> childKey: ?string, <add> effect: () => (() => void) | void, <add>}) { <ide> const ref = useRefEffect(effect); <ide> return <View key={childKey} ref={ref} testID={childKey} />; <ide> } <ide><path>Libraries/Utilities/stringifySafe.js <ide> export function createStringifySafeWithLimits(limits: {| <ide> maxArrayLimit = Number.POSITIVE_INFINITY, <ide> maxObjectKeysLimit = Number.POSITIVE_INFINITY, <ide> } = limits; <del> const stack: Array< <del> string | {+[string]: mixed} | {'...(truncated keys)...': number}, <del> > = []; <add> const stack: Array<mixed> = []; <ide> /* $FlowFixMe[missing-this-annot] The 'this' type annotation(s) required by <ide> * Flow's LTI update could not be added via codemod */ <ide> function replacer(key: string, value: mixed): mixed { <ide> export function createStringifySafeWithLimits(limits: {| <ide> return value; <ide> } <ide> <del> let retval: <del> | string <del> | {+[string]: mixed} <del> | $TEMPORARY$object<{'...(truncated keys)...': number}> = value; <add> let retval: mixed = value; <ide> if (Array.isArray(value)) { <ide> if (stack.length >= maxDepth) { <ide> retval = `[ ... array with ${value.length} values ... ]`; <ide><path>Libraries/Utilities/useWindowDimensions.js <ide> export default function useWindowDimensions(): <ide> useEffect(() => { <ide> function handleChange({ <ide> window, <del> }: <del> | $FlowFixMe <del> | $TEMPORARY$object<{window: DisplayMetrics | DisplayMetricsAndroid}>) { <add> }: { <add> window: DisplayMetrics | DisplayMetricsAndroid, <add> }) { <ide> if ( <ide> dimensions.width !== window.width || <ide> dimensions.height !== window.height || <ide><path>packages/rn-tester/js/components/RNTesterExampleFilter.js <ide> class RNTesterExampleFilter<T> extends React.Component<Props<T>, State> { <ide> } <ide> <ide> _renderFilteredSections( <del> filteredSections: Array< <del> $TEMPORARY$object<{data: Array<T>, key: string, title: string}>, <del> >, <del> ): ?React.Element<any> { <add> filteredSections: $ReadOnlyArray<{ <add> data: Array<T>, <add> key: string, <add> title: string, <add> }>, <add> ): React.Node { <ide> if (this.props.page === 'examples_page') { <ide> return ( <ide> <ScrollView <ide><path>packages/rn-tester/js/components/RNTesterNavbar.js <ide> const BookmarkTab = ({ <ide> handleNavBarPress, <ide> isBookmarkActive, <ide> theme, <del>}: $TEMPORARY$object<{ <add>}: { <ide> handleNavBarPress: (data: {screen: string}) => void, <ide> isBookmarkActive: boolean, <ide> theme: RNTesterTheme, <del>}>) => ( <add>}) => ( <ide> <View style={styles.centerBox}> <ide> <View <ide> style={[
14
Text
Text
update devops flight-manuals
2cc38f6cc5664f93e68e0a058fda51221b5f4437
<ide><path>docs/devops.md <ide> There are some known limitations and tradeoffs when using the beta version of th <ide> <ide> - #### Sign in page may look different than production <ide> <del> We use a test tenant for freecodecamp.dev on Auth0, and hence do not have the ability to set a custom domain. This makes it so that all the redirect callbacks and the login page appear at a default domain like: `https://freecodecamp-dev.auth0.com/`. This does not affect the functionality is as close to production as we can get. <add> We use a test tenant for freeCodeCamp.dev on Auth0, and hence do not have the ability to set a custom domain. This makes it so that all the redirect callbacks and the login page appear at a default domain like: `https://freecodecamp-dev.auth0.com/`. This does not affect the functionality is as close to production as we can get. <ide> <ide> ## Reporting issues and leaving feedback <ide> <ide> You may send an email to `dev[at]freecodecamp.org` if you have any queries. As a <ide> <ide> As a member of the staff, you may have been given access to our cloud service providers like Azure, Digital Ocean, etc. <ide> <del>Here are some handy commands that you can use to work on the Virtual Machines (VM), for instance performing maintenance updates or doing general houeskeeping. <add>Here are some handy commands that you can use to work on the Virtual Machines (VM), for instance performing maintenance updates or doing general housekeeping. <ide> <ide> ## Get a list of the VMs <ide> <ide> doctl auth init <ide> doctl compute droplet list --format "ID,Name,PublicIPv4" <ide> ``` <ide> <del>## Spin a VM (or VM Scale Set) <add>## Spin new Resources <ide> <del>> Todo: Add instructions for spinning VM(s) <del> <del><!-- <del> <del>The below instructions are stale. <del> <del>### 0. Prerequisites (workspace Setup) for Staff <del> <del>Get a login session on `azure cli`, and clone the <del>[`infra`](https://github.com/freeCodeCamp/infra) for setting up template <del>workspace. <del> <del>```console <del>az login <del>git clone https://github.com/freeCodeCamp/infra <del>cd infra <del>``` <del> <del>Use the Scratchpad subdirectory for temporary files, and making one-off edits. <del>The contents in this subdirectory are intentionally ignored from source control. <del> <del>### 1. Provision VMs on Azure. <del> <del>List all Resource Groups <del> <del>```console <del>az group list --output table <del>``` <del> <del>```console <del>Name Location Status <del>--------------------------------- ------------- --------- <del>tools-rg eastus Succeeded <del>``` <del> <del>Create a Resource Group <del> <del>``` <del>az group create --location eastus --name stg-rg <del>``` <del> <del>```console <del>az group list --output table <del>``` <del> <del>```console <del>Name Location Status <del>--------------------------------- ------------- --------- <del>tools-rg eastus Succeeded <del>stg-rg eastus Succeeded <del>``` <del> <del>Next per the need, provision a single VM or a scaleset. <del> <del>#### A. provision single instances <del> <del>```console <del>az vm create \ <del> --resource-group stg-rg-eastus \ <del> --name <VIRTUAL_MACHINE_NAME> \ <del> --image UbuntuLTS \ <del> --size <VIRTUAL_MACHINE_SKU> <del> --custom-data cloud-init/nginx-cloud-init.yaml \ <del> --admin-username <USERNAME> \ <del> --ssh-key-values <SSH_KEYS>.pub <del>``` <del> <del>#### B. provision scaleset instance <del> <del>```console <del>az vmss create \ <del> --resource-group stg-rg-eastus \ <del> --name <VIRTUAL_MACHINE_SCALESET_NAME> \ <del> --image UbuntuLTS \ <del> --size <VIRTUAL_MACHINE_SKU> <del> --upgrade-policy-mode automatic \ <del> --custom-data cloud-init/nginx-cloud-init.yaml \ <del> --admin-username <USERNAME> \ <del> --ssh-key-values <SSH_KEYS>.pub <del>``` <del> <del>> [!NOTE] <del>> <del>> - The custom-data config should allow you to configure and add SSH keys, <del>> install packages etc. via the `cloud-init` templates in your local <del>> workspace. Tweak the files in your local workspace as needed. The cloud-init <del>> config is optional and you can omit it completely to do setups manually as <del>> well. <del>> <del>> - The virtual machine SKU is something like: **Standard_B2s** which can be <del>> retrived by executing something like <del>> `az vm list-sizes -l eastus --output table` or checking the Azure portal <del>> pricing. <del> <del>--> <add>We are working on creating our IaC setup, and while that is in works you can use the Azure portal or the Azure CLI to spin new virtual machines and other resources. <ide> <add>> [!TIP] <add>> No matter your choice of spinning resources, we have a few [handy cloud-init config files](https://github.com/freeCodeCamp/infra/tree/main/cloud-init) to help you do some of the basic provisioning like installing docker or adding SSH keys, etc. <ide> ## Keep VMs updated <ide> <ide> You should keep the VMs up to date by performing updates and upgrades. This will <ide> The NGINX config is available on <ide> <ide> Provisioning VMs with the Code <ide> <del>#### 1. (Optional) Install NGINX and configure from repository. <del> <del>The basic setup should be ready OOTB, via the cloud-init configuration. SSH and <del>make changes as necessary for the particular instance(s). <del> <del>If you did not use the cloud-init config previously use the below for manual <del>setup of NGINX and error pages: <add>1. Install NGINX and configure from repository. <ide> <del>```console <del>sudo su <add> ```console <add> sudo su <ide> <del>cd /var/www/html <del>git clone https://github.com/freeCodeCamp/error-pages <add> cd /var/www/html <add> git clone https://github.com/freeCodeCamp/error-pages <ide> <del>cd /etc/ <del>rm -rf nginx <del>git clone https://github.com/freeCodeCamp/nginx-config nginx <add> cd /etc/ <add> rm -rf nginx <add> git clone https://github.com/freeCodeCamp/nginx-config nginx <ide> <del>cd /etc/nginx <del>``` <add> cd /etc/nginx <add> ``` <ide> <del>#### 2. Install Cloudflare origin certificates and upstream application config. <add>2. Install Cloudflare origin certificates and upstream application config. <ide> <del>Get the Cloudflare origin certificates from the secure storage and install at <del>required locations. <add> Get the Cloudflare origin certificates from the secure storage and install at <add> required locations. <ide> <del>**OR** <add> **OR** <ide> <del>Move over existing certificates: <add> Move over existing certificates: <ide> <del>```console <del># Local <del>scp -r username@source-server-public-ip:/etc/nginx/ssl ./ <del>scp -pr ./ssl username@target-server-public-ip:/tmp/ <add> ```console <add> # Local <add> scp -r username@source-server-public-ip:/etc/nginx/ssl ./ <add> scp -pr ./ssl username@target-server-public-ip:/tmp/ <ide> <del># Remote <del>rm -rf ./ssl <del>mv /tmp/ssl ./ <del>``` <add> # Remote <add> rm -rf ./ssl <add> mv /tmp/ssl ./ <add> ``` <ide> <del>Update Upstream Configurations: <add> Update Upstream Configurations: <ide> <del>```console <del>vi configs/upstreams.conf <del>``` <add> ```console <add> vi configs/upstreams.conf <add> ``` <ide> <del>Add/update the source/origin application IP addresses. <add> Add/update the source/origin application IP addresses. <ide> <del>#### 3. Setup networking and firewalls. <add>3. Setup networking and firewalls. <ide> <del>Configure Azure firewalls and `ufw` as needed for ingress origin addresses. <add> Configure Azure firewalls and `ufw` as needed for ingress origin addresses. <ide> <del>#### 4. Add the VM to the load balancer backend pool. <add>4. Add the VM to the load balancer backend pool. <ide> <del>Configure and add rules to load balancer if needed. You may also need to add the <del>VMs to load balancer backend pool if needed. <add> Configure and add rules to load balancer if needed. You may also need to add the <add> VMs to load balancer backend pool if needed. <ide> <ide> ### Logging and Monitoring <ide> <ide> 1. Check status for NGINX service using the below command: <ide> <del>```console <del>sudo systemctl status nginx <del>``` <add> ```console <add> sudo systemctl status nginx <add> ``` <ide> <ide> 2. Logging and monitoring for the servers are available at: <ide> <del>> <h3 align="center"><a href='https://amplify.nginx.com' _target='blank'>https://amplify.nginx.com</a></h3> <add> NGINX Amplify: [https://amplify.nginx.com]('https://amplify.nginx.com'), our current basic monitoring dashboard. We are working on more granular metrics for better observability <ide> <ide> ### Updating Instances (Maintenance) <ide> <ide> Provisioning VMs with the Code <ide> <ide> 1. Install Node LTS. <ide> <del>2. Update `npm` and install PM2 and setup logrotate and startup on boot <add>2. Update `npm` and install PM2 and setup `logrotate` and startup on boot <ide> <ide> ```console <ide> npm i -g npm <ide> pm2 monit <ide> <ide> Code changes need to be deployed to the API instances from time to time. It can <ide> be a rolling update or a manual update. The later is essential when changing <del>dependencies or adding enviroment variables. <add>dependencies or adding environment variables. <ide> <ide> > [!DANGER] The automated pipelines are not handling dependencies updates at the <ide> > minute. We need to do a manual update before any deployment pipeline runs. <ide> Provisioning VMs with the Code <ide> <ide> 1. Install Node LTS. <ide> <del>2. Update `npm` and install PM2 and setup logrotate and startup on boot <add>2. Update `npm` and install PM2 and setup `logrotate` and startup on boot <ide> <ide> ```console <ide> npm i -g npm <ide> pm2 monit <ide> <ide> Code changes need to be deployed to the API instances from time to time. It can <ide> be a rolling update or a manual update. The later is essential when changing <del>dependencies or adding enviroment variables. <add>dependencies or adding environment variables. <ide> <ide> > [!DANGER] The automated pipelines are not handling dependencies updates at the <ide> > minute. We need to do a manual update before any deployment pipeline runs. <ide> pm2 reload all --update-env && pm2 logs <ide> <ide> > [!NOTE] We are handling rolling updates to code, logic, via pipelines. You <ide> > should not need to run these commands. These are here for documentation. <add> <add>## Work on Chat Servers <add> <add>Our chat servers are available with a HA configuration [recommended in Rocket.Chat docs](https://docs.rocket.chat/installation/docker-containers/high-availability-install). The `docker-compose` file for this is [available here](https://github.com/freeCodeCamp/chat-config). <add> <add> <add>We provision redundant NGINX instances which are themselves load balanced (Azure Load Balancer) in front of the Rocket.Chat cluster. The NGINX configuration file are [available here](https://github.com/freeCodeCamp/chat-nginx-config). <add> <add>### First Install <add> <add>Provisioning VMs with the Code <add> <add>**NGINX Cluster:** <add> <add>1. Install NGINX and configure from repository. <add> <add> ```console <add> sudo su <add> <add> cd /var/www/html <add> git clone https://github.com/freeCodeCamp/error-pages <add> <add> cd /etc/ <add> rm -rf nginx <add> git clone https://github.com/freeCodeCamp/chat-nginx-config nginx <add> <add> cd /etc/nginx <add> ``` <add> <add>2. Install Cloudflare origin certificates and upstream application config. <add> <add> Get the Cloudflare origin certificates from the secure storage and install at <add> required locations. <add> <add> **OR** <add> <add> Move over existing certificates: <add> <add> ```console <add> # Local <add> scp -r username@source-server-public-ip:/etc/nginx/ssl ./ <add> scp -pr ./ssl username@target-server-public-ip:/tmp/ <add> <add> # Remote <add> rm -rf ./ssl <add> mv /tmp/ssl ./ <add> ``` <add> <add> Update Upstream Configurations: <add> <add> ```console <add> vi configs/upstreams.conf <add> ``` <add> <add> Add/update the source/origin application IP addresses. <add> <add>3. Setup networking and firewalls. <add> <add> Configure Azure firewalls and `ufw` as needed for ingress origin addresses. <add> <add>4. Add the VM to the load balancer backend pool. <add> <add> Configure and add rules to load balancer if needed. You may also need to add the <add> VMs to load balancer backend pool if needed. <add> <add>**Docker Cluster:** <add> <add>1. Install Docker and configure from the repository <add> <add> ```console <add> git clone https://github.com/freeCodeCamp/chat-config.git chat <add> cd chat <add> ``` <add> <add>2. Configure the required environment variables and instance IP addresses. <add> <add>3. Run rocket-chat server <add> <add> ```console <add> docker-compose config <add> docker-compose up -d <add> ``` <add> <add>### Logging and Monitoring <add> <add>1. Check status for NGINX service using the below command: <add> <add> ```console <add> sudo systemctl status nginx <add> ``` <add> <add>2. Check status for running docker instances with: <add> <add> ```console <add> docker ps <add> ``` <add> <add>### Updating Instances (Maintenance) <add> <add> <add>**NGINX Cluster:** <add> <add>Config changes to our NGINX instances are maintained on GitHub, these should be <add>deployed on each instance like so: <add> <add>1. SSH into the instance and enter sudo <add> <add> ```console <add> sudo su <add> ``` <add> <add>2. Get the latest config code. <add> <add> ```console <add> cd /etc/nginx <add> git fetch --all --prune <add> git reset --hard origin/main <add> ``` <add> <add>3. Test and reload the config <add> [with Signals](https://docs.nginx.com/nginx/admin-guide/basic-functionality/runtime-control/#controlling-nginx). <add> <add> ```console <add> nginx -t <add> nginx -s reload <add> ``` <add> <add>**Docker Cluster:** <add> <add>1. SSH into the instance and navigate to the chat config path <add> <add> ```console <add> cd ~/chat <add> ``` <add> <add>2. Get the latest config code. <add> <add> ```console <add> git fetch --all --prune <add> git reset --hard origin/main <add> ``` <add> <add>3. Pull down the latest docker image for Rocket.Chat <add> <add> ```console <add> docker-compose pull <add> ``` <add> <add>4. Update the running instances <add> <add> ```console <add> docker-compose up -d <add> ``` <add> <add>5. Validate the instances are up <add> <add> ```console <add> docker ps <add> ``` <add> <add>6. Cleanup extraneous resources <add> <add> ```console <add> docker system prune --volumes <add> ``` <add> <add> Output: <add> <add> ```console <add> WARNING! This will remove: <add> - all stopped containers <add> - all networks not used by at least one container <add> - all volumes not used by at least one container <add> - all dangling images <add> - all dangling build cache <add> <add> Are you sure you want to continue? [y/N] y <add> ``` <add> <add> Select yes (y) to remove everything that is not in use. <add> <add>## Updating Node.js versions on VMs <add> <add>List currently installed node & npm versions <add> <add>```console <add>nvm -v <add>node -v <add>npm -v <add> <add>nvm ls <add>``` <add> <add>Install the latest Node.js LTS, and reinstall any global packages <add> <add>```console <add>nvm install 'lts/*' --reinstall-packages-from=default <add>``` <add> <add>Verify installed packages <add> <add>```console <add>npm ls -g --depth=0 <add>``` <add> <add>Alias `default` Node.js versions to the current `stable` <add> <add>```console <add>nvm alias default stable <add>``` <add> <add> <add>(Optional) Uninstall old versions <add> <add>```console <add>nvm uninstall <version> <add>``` <add>> [!WARNING] <add>> If using PM2 for processes you would also need to bring up the applications and save the process list for automatic recovery on restarts. <add> <add>Quick commands for PM2 to list, resurrect saved processes, etc. <add> <add>```console <add>pm2 ls <add>``` <add> <add>```console <add>pm2 resurrect <add>``` <add> <add>```console <add>pm2 save <add>``` <add> <add>```console <add>pm2 logs <add>``` <add> <add>> [!DANGER] <add>> For client applications, the shell script can't be resurrected between Node.js versions with `pm2 resurrect`. Deploy processes from scratch instead. This should become nicer when we move to a docker based setup. <add> <add>## Installing and Updating Azure Pipeline Agents <add> <add> <add>See: https://docs.microsoft.com/en-us/azure/devops/pipelines/agents/v2-linux?view=azure-devops and follow the instructions to stop, remove and reinstall agents. Broadly you can follow the steps listed here. <add> <add>You would need a PAT, that you can grab from here: https://dev.azure.com/freeCodeCamp-org/_usersSettings/tokens <add> <add>### Installing agents on Deployment targets <add> <add>Navigate to [Azure Devops](https://dev.azure.com/freeCodeCamp-org) and register the agent from scratch in the requisite [deployment groups](https://dev.azure.com/freeCodeCamp-org/freeCodeCamp/_machinegroup). <add> <add>> [!NOTE] <add>> You should run the scripts in the home directory, and make sure no other `azagent` directory exists. <add> <add>### Updating agents <add> <add>Currently updating agents requires them to be removed and reconfigured. This is required for them to correctly pick up `PATH` values and other system environment variables correctly. We need to do this for instance updating Node.js on our deployment target VMs. <add> <add>1. Navigate and check status of the service <add> <add> ```console <add> cd ~/azagent <add> sudo ./svc.sh status <add> ``` <add> <add>2. Stop the service <add> <add> ```console <add> sudo ./svc.sh stop <add> ``` <add> <add>3. Uninstall the service <add> <add> ```console <add> sudo ./svc.sh uninstall <add> ``` <add> <add>4. Remove the agent from the pipeline pool <add> <add> ```console <add> ./config.sh remove <add> ``` <add> <add>5. Remove the config files <add> <add> ```console <add> cd ~ <add> rm -rf ~/azagent <add> ``` <add> <add>Once You have completed the steps above, you can repeat the same steps as installing the agent.
1
Python
Python
add the flang compiler
3ff922786efcfbee29ae2636be8b381f5e376f69
<ide><path>numpy/distutils/fcompiler/__init__.py <ide> def wrap_unlinkable_objects(self, objects, output_dir, extra_dll_dir): <ide> _default_compilers = ( <ide> # sys.platform mappings <ide> ('win32', ('gnu', 'intelv', 'absoft', 'compaqv', 'intelev', 'gnu95', 'g95', <del> 'intelvem', 'intelem')), <add> 'intelvem', 'intelem', 'flang')), <ide> ('cygwin.*', ('gnu', 'intelv', 'absoft', 'compaqv', 'intelev', 'gnu95', 'g95')), <ide> ('linux.*', ('gnu95', 'intel', 'lahey', 'pg', 'absoft', 'nag', 'vast', 'compaq', <ide> 'intele', 'intelem', 'gnu', 'g95', 'pathf95', 'nagfor')), <ide> def get_default_fcompiler(osname=None, platform=None, requiref90=False, <ide> platform.""" <ide> matching_compiler_types = available_fcompilers_for_platform(osname, <ide> platform) <add> log.info("get_default_fcompiler: matching types: '%s'", <add> matching_compiler_types) <ide> compiler_type = _find_existing_fcompiler(matching_compiler_types, <ide> osname=osname, <ide> platform=platform, <ide><path>numpy/distutils/fcompiler/pg.py <ide> # http://www.pgroup.com <ide> from __future__ import division, absolute_import, print_function <ide> <del>from numpy.distutils.fcompiler import FCompiler <add>import sys <add>import os <add> <add>from numpy.distutils.fcompiler import FCompiler, dummy_fortran_file <ide> from sys import platform <add>from os.path import join, dirname, normpath <add> <add>compilers = ['PGroupFCompiler', 'PGroupFlangCompiler'] <ide> <del>compilers = ['PGroupFCompiler'] <ide> <ide> class PGroupFCompiler(FCompiler): <ide> <ide> compiler_type = 'pg' <ide> description = 'Portland Group Fortran Compiler' <del> version_pattern = r'\s*pg(f77|f90|hpf|fortran) (?P<version>[\d.-]+).*' <add> version_pattern = r'\s*pg(f77|f90|hpf|fortran) (?P<version>[\d.-]+).*' <ide> <ide> if platform == 'darwin': <ide> executables = { <del> 'version_cmd' : ["<F77>", "-V"], <del> 'compiler_f77' : ["pgfortran", "-dynamiclib"], <del> 'compiler_fix' : ["pgfortran", "-Mfixed", "-dynamiclib"], <del> 'compiler_f90' : ["pgfortran", "-dynamiclib"], <del> 'linker_so' : ["libtool"], <del> 'archiver' : ["ar", "-cr"], <del> 'ranlib' : ["ranlib"] <add> 'version_cmd': ["<F77>", "-V"], <add> 'compiler_f77': ["pgfortran", "-dynamiclib"], <add> 'compiler_fix': ["pgfortran", "-Mfixed", "-dynamiclib"], <add> 'compiler_f90': ["pgfortran", "-dynamiclib"], <add> 'linker_so': ["libtool"], <add> 'archiver': ["ar", "-cr"], <add> 'ranlib': ["ranlib"] <ide> } <ide> pic_flags = [''] <ide> else: <ide> executables = { <del> 'version_cmd' : ["<F77>", "-V"], <del> 'compiler_f77' : ["pgfortran"], <del> 'compiler_fix' : ["pgfortran", "-Mfixed"], <del> 'compiler_f90' : ["pgfortran"], <del> 'linker_so' : ["pgfortran", "-shared", "-fpic"], <del> 'archiver' : ["ar", "-cr"], <del> 'ranlib' : ["ranlib"] <add> 'version_cmd': ["<F77>", "-V"], <add> 'compiler_f77': ["pgfortran"], <add> 'compiler_fix': ["pgfortran", "-Mfixed"], <add> 'compiler_f90': ["pgfortran"], <add> 'linker_so': ["pgfortran", "-shared", "-fpic"], <add> 'archiver': ["ar", "-cr"], <add> 'ranlib': ["ranlib"] <ide> } <ide> pic_flags = ['-fpic'] <ide> <del> <ide> module_dir_switch = '-module ' <ide> module_include_switch = '-I' <ide> <ide> def get_flags(self): <ide> opt = ['-Minform=inform', '-Mnosecond_underscore'] <ide> return self.pic_flags + opt <add> <ide> def get_flags_opt(self): <ide> return ['-fast'] <add> <ide> def get_flags_debug(self): <ide> return ['-g'] <ide> <ide> def get_flags_linker_so(self): <ide> def runtime_library_dir_option(self, dir): <ide> return '-R"%s"' % dir <ide> <add> <add>if sys.version_info >= (3, 5): <add> import subprocess <add> import shlex <add> import functools <add> <add> class PGroupFlangCompiler(FCompiler): <add> compiler_type = 'flang' <add> description = 'Portland Group Fortran LLVM Compiler' <add> version_pattern = r'\s*(flang|clang) version (?P<version>[\d.-]+).*' <add> <add> ar_exe = 'lib.exe' <add> possible_executables = ['flang'] <add> <add> executables = { <add> 'version_cmd': ["<F77>", "--version"], <add> 'compiler_f77': ["flang"], <add> 'compiler_fix': ["flang"], <add> 'compiler_f90': ["flang"], <add> 'linker_so': [None], <add> 'archiver': [ar_exe, "/verbose", "/OUT:"], <add> 'ranlib': None <add> } <add> <add> library_switch = '/OUT:' # No space after /OUT:! <add> module_dir_switch = '-module ' # Don't remove ending space! <add> <add> def get_libraries(self): <add> opt = FCompiler.get_libraries(self) <add> opt.extend(['flang', 'flangrti', 'ompstub']) <add> return opt <add> <add> @functools.lru_cache(maxsize=128) <add> def get_library_dirs(self): <add> """List of compiler library directories.""" <add> opt = FCompiler.get_library_dirs(self) <add> flang_dir = dirname(self.executables['compiler_f77'][0]) <add> opt.append(normpath(join(flang_dir, '..', 'lib'))) <add> <add> return opt <add> <add> def get_flags(self): <add> return [] <add> <add> def get_flags_free(self): <add> return [] <add> <add> def get_flags_debug(self): <add> return ['-g'] <add> <add> def get_flags_opt(self): <add> return ['-O3'] <add> <add> def get_flags_arch(self): <add> return [] <add> <add> def runtime_library_dir_option(self, dir): <add> raise NotImplementedError <add> <add>else: <add> from numpy.distutils.fcompiler import CompilerNotFound <add> <add> # No point in supporting on older Pythons because not ABI compatible <add> class PGroupFlangCompiler(FCompiler): <add> compiler_type = 'flang' <add> description = 'Portland Group Fortran LLVM Compiler' <add> <add> def get_version(self): <add> raise CompilerNotFound('Flang unsupported on Python < 3.5') <add> <add> <ide> if __name__ == '__main__': <ide> from distutils import log <ide> log.set_verbosity(2) <ide> from numpy.distutils import customized_fcompiler <del> print(customized_fcompiler(compiler='pg').get_version()) <add> if 'flang' in sys.argv: <add> print(customized_fcompiler(compiler='flang').get_version()) <add> else: <add> print(customized_fcompiler(compiler='pg').get_version())
2
Python
Python
make transformer layer back compatible
ac5fff19dcb54bb341b7bfb3cf9f554f2d5f92a5
<ide><path>official/nlp/modeling/layers/transformer.py <ide> def build(self, input_shape): <ide> kernel_constraint=self._kernel_constraint, <ide> bias_constraint=self._bias_constraint, <ide> name="self_attention") <del> <add> # pylint: disable=protected-access <add> self._attention_layer.build([input_tensor_shape] * 3) <add> self._attention_output_dense = self._attention_layer._output_dense <add> # pylint: enable=protected-access <ide> self._attention_dropout = tf.keras.layers.Dropout(rate=self._dropout_rate) <ide> # Use float32 in layernorm for numeric stability. <ide> # It is probably safe in mixed_float16, but we haven't validated this yet.
1
Javascript
Javascript
resolve all modules through module resolver (#963)
efe0c7b43323d753c52befbd214850bf80fd7279
<ide><path>server/build/webpack.js <ide> export default async function createCompiler (dir, { dev = false, quiet = false <ide> if (!(/\.js$/.test(interpolatedName))) { <ide> return { content, sourceMap } <ide> } <del> <add> const babelRuntimePath = require.resolve('babel-runtime/package') <add> .replace(/[\\/]package\.json$/, '') <ide> const transpiled = babelCore.transform(content, { <ide> presets: [require.resolve('babel-preset-es2015')], <ide> sourceMaps: dev ? 'both' : false, <del> // Here we need to resolve styled-jsx/style to the absolute paths. <add> // Here we need to resolve all modules to the absolute paths. <ide> // Earlier we did it with the babel-preset. <ide> // But since we don't transpile ES2015 in the preset this is not resolving. <ide> // That's why we need to do it here. <ide> export default async function createCompiler (dir, { dev = false, quiet = false <ide> require.resolve('babel-plugin-module-resolver'), <ide> { <ide> alias: { <del> 'styled-jsx/style': require.resolve('styled-jsx/style') <add> 'babel-runtime': babelRuntimePath, <add> react: require.resolve('react'), <add> 'react-dom': require.resolve('react-dom'), <add> 'react-dom/server': require.resolve('react-dom/server'), <add> 'next/link': require.resolve('../../lib/link'), <add> 'next/prefetch': require.resolve('../../lib/prefetch'), <add> 'next/css': require.resolve('../../lib/css'), <add> 'next/head': require.resolve('../../lib/head'), <add> 'next/document': require.resolve('../../server/document'), <add> 'next/router': require.resolve('../../lib/router') <ide> } <ide> } <ide> ]
1
PHP
PHP
update docblocks with 'path' in $params
a51f6c78c603d9dbd21b9d76b4f420be5a710f0b
<ide><path>src/Routing/RouteBuilder.php <ide> public function redirect($route, $url, array $options = []) <ide> * This method creates a scoped route collection that includes <ide> * relevant prefix information. <ide> * <del> * The path parameter is used to generate the routing parameter name. <add> * The $name parameter is used to generate the routing parameter name. <ide> * For example a path of `admin` would result in `'prefix' => 'admin'` being <ide> * applied to all connected routes. <ide> * <ide> * You can re-open a prefix as many times as necessary, as well as nest prefixes. <ide> * Nested prefixes will result in prefix values like `admin/api` which translates <ide> * to the `Controller\Admin\Api\` namespace. <ide> * <add> * If you need to have prefix with dots, eg: '/api/v1.0', use 'path' key <add> * for $params argument: <add> * <add> * ``` <add> * $route->prefix('api', function($route) { <add> * $route->prefix('v10', ['path' => '/v1.0'], function($route) { <add> * // Translates to `Controller\Api\V10\` namespace <add> * }); <add> * }); <add> * ``` <add> * <ide> * @param string $name The prefix name to use. <ide> * @param array|callable $params An array of routing defaults to add to each connected route. <ide> * If you have no parameters, this argument can be a callable.
1
Javascript
Javascript
add support for title in schema
d064fbe79f8dd6e0c583812a0075dd7b114ef652
<ide><path>test/Schemas.lint.js <ide> describe("Schemas", () => { <ide> const allowedProperties = [ <ide> "definitions", <ide> "$ref", <del> "id", <add> "$id", <add> "title", <ide> "items", <ide> "properties", <ide> "additionalProperties", <ide><path>tooling/format-schemas.js <ide> const PROPERTIES = [ <ide> "$ref", <ide> "definitions", <ide> <add> "$id", <ide> "id", <add> "title", <ide> "description", <ide> "type", <ide>
2
Python
Python
fix some typos.
7866fbaa1a9d89cc168bc950fa47f5de3b173ca8
<ide><path>keras/layers/convolutional.py <ide> class Conv3D(_Conv): <ide> When using this layer as the first layer in a model, <ide> provide the keyword argument `input_shape` <ide> (tuple of integers, does not include the sample axis), <del> e.g. `input_shape=(128, 128, 128, 3)` for 128x128x128 volumes <add> e.g. `input_shape=(128, 128, 128, 1)` for 128x128x128 volumes <ide> with a single channel, <ide> in `data_format="channels_last"`. <ide> <ide> # Arguments <ide> filters: Integer, the dimensionality of the output space <ide> (i.e. the number output of filters in the convolution). <ide> kernel_size: An integer or tuple/list of 3 integers, specifying the <del> width and height of the 3D convolution window. <add> depth, height and width of the 3D convolution window. <ide> Can be a single integer to specify the same value for <ide> all spatial dimensions. <ide> strides: An integer or tuple/list of 3 integers,
1
Text
Text
add changelog entry ref
8eac0a6b5817defabef6cee2f12baeda26e91d8f
<ide><path>railties/CHANGELOG.md <add>* Add public API to register new extensions for `rake notes`. <add> <add> Example: <add> <add> config.annotations.register_extensions("scss", "sass") { |tag| /\/\/\s*(#{tag}):?\s*(.*)$/ } <add> <add> *Roberto Miranda* <add> <ide> * Removed unnecessary `rails application` command. <ide> <ide> *Arun Agrawal*
1
Ruby
Ruby
combine superenv tests
3516bb68d3ca06d14fbcec343fa8792cef922792
<ide><path>Library/Homebrew/test/test_ENV.rb <ide> def setup <ide> class SuperenvTests < Test::Unit::TestCase <ide> include SharedEnvTests <ide> <add> attr_reader :env, :bin <add> <ide> def setup <ide> @env = {}.extend(Superenv) <add> @bin = HOMEBREW_REPOSITORY/"Library/ENV/#{MacOS::Xcode.version}" <add> bin.mkpath <add> end <add> <add> def test_bin <add> assert_equal bin, Superenv.bin <add> end <add> <add> def test_initializes_deps <add> assert_equal [], env.deps <add> assert_equal [], env.keg_only_deps <add> end <add> <add> def teardown <add> bin.rmtree <ide> end <ide> end <ide><path>Library/Homebrew/test/test_superenv.rb <del>require 'testing_env' <del>require 'extend/ENV/super' <del> <del>class SuperenvTests < Test::Unit::TestCase <del> attr_reader :env, :bin <del> <del> def setup <del> @env = {}.extend(Superenv) <del> @bin = HOMEBREW_REPOSITORY/"Library/ENV/#{MacOS::Xcode.version}" <del> bin.mkpath <del> end <del> <del> def test_bin <del> assert_equal bin, Superenv.bin <del> end <del> <del> def test_initializes_deps <del> assert_equal [], env.deps <del> assert_equal [], env.keg_only_deps <del> end <del> <del> def teardown <del> bin.rmtree <del> end <del>end
2
Python
Python
patch spacy.train for new pipeline management
97c9b5db8b6219d53967a136fa9fdd63bd06fca5
<ide><path>spacy/cli/train.py <ide> def train(cmd, lang, output_dir, train_data, dev_data, n_iter=10, n_sents=0, <ide> n_train_words = corpus.count_train() <ide> <ide> lang_class = util.get_lang_class(lang) <del> nlp = lang_class(pipeline=pipeline) <add> nlp = lang_class() <ide> if vectors: <ide> util.load_model(vectors, vocab=nlp.vocab) <add> for name in pipeline: <add> nlp.add_pipe(nlp.create_pipe(name), name=name) <ide> optimizer = nlp.begin_training(lambda: corpus.train_tuples, device=use_gpu) <ide> nlp._optimizer = None <ide> <ide> def train(cmd, lang, output_dir, train_data, dev_data, n_iter=10, n_sents=0, <ide> epoch_model_path = output_path / ('model%d' % i) <ide> nlp.to_disk(epoch_model_path) <ide> nlp_loaded = lang_class(pipeline=pipeline) <add> for name in pipeline: <add> nlp_loaded.add_pipe(nlp.create_pipe(name), name=name) <ide> nlp_loaded = nlp_loaded.from_disk(epoch_model_path) <ide> dev_docs = list(corpus.dev_docs( <ide> nlp_loaded, <ide> def train(cmd, lang, output_dir, train_data, dev_data, n_iter=10, n_sents=0, <ide> gpu_wps = nwords/(end_time-start_time) <ide> with Model.use_device('cpu'): <ide> nlp_loaded = lang_class(pipeline=pipeline) <add> for name in pipeline: <add> nlp_loaded.add_pipe(nlp.create_pipe(name), name=name) <add> <ide> nlp_loaded = nlp_loaded.from_disk(epoch_model_path) <ide> dev_docs = list(corpus.dev_docs( <ide> nlp_loaded, gold_preproc=gold_preproc))
1
Text
Text
add theme guides to the index
d237b3448c0f4b5c04cbe805f42bf10f60fe8b8b
<ide><path>docs/index.md <ide> * [Serialization](advanced/serialization.md) <ide> * [View System](advanced/view-system.md) <ide> * [Scopes and Scope Descriptors](advanced/scopes-and-scope-descriptors.md) <add> <add>### Upgrading to 1.0 APIs <add> <add>* [Upgrading your UI Theme](upgrading/upgrading-your-ui-theme.md) <add>* [Upgrading your Syntax Theme](upgrading/upgrading-your-syntax-theme.md)
1
Javascript
Javascript
add more info about watching and tracking
7c792f4cc99515ac27ed317e0e35e40940b3a400
<ide><path>src/ng/directive/ngRepeat.js <ide> * <ide> * # Tracking and Duplicates <ide> * <del> * When the contents of the collection change, `ngRepeat` makes the corresponding changes to the DOM: <add> * `ngRepeat` uses {@link $rootScope.Scope#$watchCollection $watchCollection} to detect changes in <add> * the collection. When a change happens, ngRepeat then makes the corresponding changes to the DOM: <ide> * <ide> * * When an item is added, a new instance of the template is added to the DOM. <ide> * * When an item is removed, its template instance is removed from the DOM. <ide> * * When items are reordered, their respective templates are reordered in the DOM. <ide> * <del> * By default, `ngRepeat` does not allow duplicate items in arrays. This is because when <del> * there are duplicates, it is not possible to maintain a one-to-one mapping between collection <del> * items and DOM elements. <add> * To minimize creation of DOM elements, `ngRepeat` uses a function <add> * to "keep track" of all items in the collection and their corresponding DOM elements. <add> * For example, if an item is added to the collection, ngRepeat will know that all other items <add> * already have DOM elements, and will not re-render them. <add> * <add> * The default tracking function (which tracks items by their identity) does not allow <add> * duplicate items in arrays. This is because when there are duplicates, it is not possible <add> * to maintain a one-to-one mapping between collection items and DOM elements. <ide> * <ide> * If you do need to repeat duplicate items, you can substitute the default tracking behavior <ide> * with your own using the `track by` expression. <ide> * </div> <ide> * ``` <ide> * <del> * You may use arbitrary expressions in `track by`, including references to custom functions <add> * You may also use arbitrary expressions in `track by`, including references to custom functions <ide> * on the scope: <ide> * ```html <ide> * <div ng-repeat="n in [42, 42, 43, 43] track by myTrackingFunction(n)"> <ide> * {{n}} <ide> * </div> <ide> * ``` <ide> * <del> * If you are working with objects that have an identifier property, you can track <add> * <div class="alert alert-success"> <add> * If you are working with objects that have an identifier property, you should track <ide> * by the identifier instead of the whole object. Should you reload your data later, `ngRepeat` <ide> * will not have to rebuild the DOM elements for items it has already rendered, even if the <del> * JavaScript objects in the collection have been substituted for new ones: <add> * JavaScript objects in the collection have been substituted for new ones. For large collections, <add> * this signifincantly improves rendering performance. If you don't have a unique identifier, <add> * `track by $index` can also provide a performance boost. <add> * </div> <ide> * ```html <ide> * <div ng-repeat="model in collection track by model.id"> <ide> * {{model.name}}
1
Text
Text
fix grammatical error
6353ea47464b708faaef01a27531915625b93439
<ide><path>guides/source/getting_started.md <ide> If you refresh <http://localhost:3000/posts/new> now, you'll get a new error: <ide> <ide> This error indicates that Rails cannot find the `new` action inside the `PostsController` <ide> that you just generated. This is because when controllers are generated in Rails <del>they are empty by default, unless you tell it you wanted actions during the <add>they are empty by default, unless you tell it your wanted actions during the <ide> generation process. <ide> <ide> To manually define an action inside a controller, all you need to do is to
1
Text
Text
upload distilbart artwork
331d8d2936e7a140225cf60301ba6469930fd216
<ide><path>examples/seq2seq/README.md <add>## Sequence to Sequence <add> <ide> This directory contains examples for finetuning and evaluating transformers on summarization and translation tasks. <ide> Summarization support is more mature than translation support. <ide> Please tag @sshleifer with any issues/unexpected behaviors, or send a PR! <ide> python run_eval.py sshleifer/distilbart-cnn-12-6 $DATA_DIR/val.source dbart_val_ <ide> <ide> <ide> ### DistilBART <add>![DBART](https://huggingface.co/front/thumbnails/distilbart_large.png) <ide> <ide> For the CNN/DailyMail dataset, (relatively longer, more extractive summaries), we found a simple technique that works: <ide> you just copy alternating layers from `bart-large-cnn` and finetune more on the same data.
1
Ruby
Ruby
pass explicit sort to handle apfs
7b8ba77ed26f84aacc1648eeb78b6d9964adfda2
<ide><path>Library/Homebrew/cmd/missing.rb <ide> def missing <ide> return unless HOMEBREW_CELLAR.exist? <ide> <ide> ff = if ARGV.named.empty? <del> Formula.installed <add> Formula.installed.sort <ide> else <del> ARGV.resolved_formulae <add> ARGV.resolved_formulae.sort <ide> end <ide> <ide> ff.each do |f|
1
Javascript
Javascript
fix module cycle in ember-runtime
8e12a0cb2e19bb7bd7a03abf8385d3f3c454d5ff
<ide><path>packages/ember-runtime/index.js <ide> export { <ide> A, <ide> MutableArray, <ide> removeAt, <add> uniqBy, <add> isArray, <ide> } from './lib/mixins/array'; <ide> export { default as Comparable } from './lib/mixins/comparable'; <ide> export { default as Namespace } from './lib/system/namespace'; <ide> export { default as Evented } from './lib/mixins/evented'; <ide> export { default as PromiseProxyMixin } from './lib/mixins/promise_proxy'; <ide> <ide> export { default as RSVP, onerrorDefault } from './lib/ext/rsvp'; // just for side effect of extending Ember.RSVP <del>export { isArray, typeOf, uniqBy } from './lib/utils'; <add>export { typeOf } from './lib/type-of'; <ide> <ide> import './lib/ext/function'; // just for side effect of extending Function.prototype <ide><path>packages/ember-runtime/lib/compare.js <del>import { typeOf } from './utils'; <add>import { typeOf } from './type-of'; <ide> import Comparable from './mixins/comparable'; <ide> <ide> const TYPE_ORDER = { <ide><path>packages/ember-runtime/lib/mixins/array.js <ide> @module @ember/array <ide> */ <ide> <add>import { DEBUG } from '@glimmer/env'; <add>import { HAS_NATIVE_PROXY } from 'ember-utils'; <add>import { PROXY_CONTENT } from 'ember-metal'; <ide> import { symbol, toString } from 'ember-utils'; <ide> import { <ide> get, <ide> import Copyable from '../mixins/copyable'; <ide> import copy from '../copy'; <ide> import EmberError from '@ember/error'; <ide> import MutableEnumerable from './mutable_enumerable'; <del>import { uniqBy } from '../utils'; <add>import { typeOf } from '../type-of'; <ide> <ide> const EMPTY_ARRAY = Object.freeze([]); <ide> const EMBER_ARRAY = symbol('EMBER_ARRAY'); <ide> export function isEmberArray(obj) { <ide> return obj && obj[EMBER_ARRAY]; <ide> } <ide> <add>const identityFunction = item => item; <add> <add>export function uniqBy(array, key = identityFunction) { <add> assert(`first argument passed to \`uniqBy\` should be array`, isArray(array)); <add> <add> let ret = A(); <add> let seen = new Set(); <add> let getter = typeof key === 'function' ? key : item => get(item, key); <add> <add> array.forEach(item => { <add> let val = getter(item); <add> if (!seen.has(val)) { <add> seen.add(val); <add> ret.push(item); <add> } <add> }); <add> <add> return ret; <add>} <add> <ide> function iter(key, value) { <ide> let valueProvided = arguments.length === 2; <ide> return valueProvided ? item => value === get(item, key) : item => !!get(item, key); <ide> function indexOf(array, val, startAt = 0, withNaNCheck) { <ide> return findIndex(array, predicate, startAt); <ide> } <ide> <add>/** <add> Returns true if the passed object is an array or Array-like. <add> <add> Objects are considered Array-like if any of the following are true: <add> <add> - the object is a native Array <add> - the object has an objectAt property <add> - the object is an Object, and has a length property <add> <add> Unlike `typeOf` this method returns true even if the passed object is <add> not formally an array but appears to be array-like (i.e. implements `Array`) <add> <add> ```javascript <add> import { isArray } from '@ember/array'; <add> import ArrayProxy from '@ember/array/proxy'; <add> <add> isArray(); // false <add> isArray([]); // true <add> isArray(ArrayProxy.create({ content: [] })); // true <add> ``` <add> <add> @method isArray <add> @static <add> @for @ember/array <add> @param {Object} obj The object to test <add> @return {Boolean} true if the passed object is an array or Array-like <add> @public <add>*/ <add>export function isArray(_obj) { <add> let obj = _obj; <add> if (DEBUG && HAS_NATIVE_PROXY && typeof _obj === 'object' && _obj !== null) { <add> let possibleProxyContent = _obj[PROXY_CONTENT]; <add> if (possibleProxyContent !== undefined) { <add> obj = possibleProxyContent; <add> } <add> } <add> <add> if (!obj || obj.setInterval) { <add> return false; <add> } <add> if (Array.isArray(obj)) { <add> return true; <add> } <add> if (ArrayMixin.detect(obj)) { <add> return true; <add> } <add> <add> let type = typeOf(obj); <add> if ('array' === type) { <add> return true; <add> } <add> let length = obj.length; <add> if (typeof length === 'number' && length === length && 'object' === type) { <add> return true; <add> } <add> return false; <add>} <add> <ide> // .......................................................... <ide> // ARRAY <ide> // <ide><path>packages/ember-runtime/lib/system/array_proxy.js <ide> import { <ide> addArrayObserver, <ide> removeArrayObserver, <ide> } from 'ember-metal'; <del>import { isArray } from '../utils'; <ide> import EmberObject from './object'; <del>import { MutableArray } from '../mixins/array'; <add>import { isArray, MutableArray } from '../mixins/array'; <ide> import { assert } from '@ember/debug'; <ide> <ide> const ARRAY_OBSERVER_MAPPING = { <add><path>packages/ember-runtime/lib/type-of.js <del><path>packages/ember-runtime/lib/utils.js <del>import { DEBUG } from '@glimmer/env'; <del>import { PROXY_CONTENT, get } from 'ember-metal'; <del>import { HAS_NATIVE_PROXY } from 'ember-utils'; <del>import EmberArray, { A } from './mixins/array'; <ide> import EmberObject from './system/object'; <del>import { assert } from '@ember/debug'; <ide> <ide> // ........................................ <ide> // TYPING & ARRAY MESSAGING <ide> const TYPE_MAP = { <ide> }; <ide> <ide> const { toString } = Object.prototype; <del>/** <del> @module @ember/array <del>*/ <del>/** <del> Returns true if the passed object is an array or Array-like. <del> <del> Objects are considered Array-like if any of the following are true: <del> <del> - the object is a native Array <del> - the object has an objectAt property <del> - the object is an Object, and has a length property <del> <del> Unlike `typeOf` this method returns true even if the passed object is <del> not formally an array but appears to be array-like (i.e. implements `Array`) <del> <del> ```javascript <del> import { isArray } from '@ember/array'; <del> import ArrayProxy from '@ember/array/proxy'; <del> <del> isArray(); // false <del> isArray([]); // true <del> isArray(ArrayProxy.create({ content: [] })); // true <del> ``` <del> <del> @method isArray <del> @static <del> @for @ember/array <del> @param {Object} obj The object to test <del> @return {Boolean} true if the passed object is an array or Array-like <del> @public <del>*/ <del>export function isArray(_obj) { <del> let obj = _obj; <del> if (DEBUG && HAS_NATIVE_PROXY && typeof _obj === 'object' && _obj !== null) { <del> let possibleProxyContent = _obj[PROXY_CONTENT]; <del> if (possibleProxyContent !== undefined) { <del> obj = possibleProxyContent; <del> } <del> } <ide> <del> if (!obj || obj.setInterval) { <del> return false; <del> } <del> if (Array.isArray(obj)) { <del> return true; <del> } <del> if (EmberArray.detect(obj)) { <del> return true; <del> } <del> <del> let type = typeOf(obj); <del> if ('array' === type) { <del> return true; <del> } <del> let length = obj.length; <del> if (typeof length === 'number' && length === length && 'object' === type) { <del> return true; <del> } <del> return false; <del>} <ide> /** <ide> @module @ember/utils <ide> */ <ide> export function typeOf(item) { <ide> <ide> return ret; <ide> } <del> <del>const identityFunction = item => item; <del> <del>export function uniqBy(array, key = identityFunction) { <del> assert(`first argument passed to \`uniqBy\` should be array`, isArray(array)); <del> <del> let ret = A(); <del> let seen = new Set(); <del> let getter = typeof key === 'function' ? key : item => get(item, key); <del> <del> array.forEach(item => { <del> let val = getter(item); <del> if (!seen.has(val)) { <del> seen.add(val); <del> ret.push(item); <del> } <del> }); <del> <del> return ret; <del>} <ide><path>packages/ember-runtime/tests/core/compare_test.js <del>import { typeOf } from '../../lib/utils'; <add>import { typeOf } from '../../lib/type-of'; <ide> import EmberObject from '../../lib/system/object'; <ide> import compare from '../../lib/compare'; <ide> import Comparable from '../../lib/mixins/comparable'; <ide><path>packages/ember-runtime/tests/core/is_array_test.js <del>import { isArray } from '../../lib/utils'; <del>import { A as emberA } from '../../lib/mixins/array'; <add>import { A as emberA, isArray } from '../../lib/mixins/array'; <ide> import ArrayProxy from '../../lib/system/array_proxy'; <ide> import EmberObject from '../../lib/system/object'; <ide> import { window } from 'ember-browser-environment'; <ide><path>packages/ember-runtime/tests/core/type_of_test.js <del>import { typeOf } from '../../lib/utils'; <add>import { typeOf } from '../../lib/type-of'; <ide> import EmberObject from '../../lib/system/object'; <ide> import { window } from 'ember-browser-environment'; <ide> import { moduleFor, AbstractTestCase } from 'internal-test-helpers';
8
Text
Text
update literal translations in index.md
9bb4946fbece4a27319ca762724e3d349f67d8d8
<ide><path>guide/spanish/agile/technical-debt/index.md <ide> localeTitle: Deuda técnica <ide> --- <ide> ## Deuda técnica <ide> <del>A menudo, en el desarrollo ágil, si está produciendo software en la práctica "suficientemente buena", también aumentará su deuda técnica. Esta es la acumulación de atajos y soluciones. <add>A menudo, en el desarrollo ágil, si está produciendo software "suficientemente bueno", también aumentará su deuda técnica. Esta es la acumulación de atajos y soluciones. <ide> <del>Compáralo con el dinero. Cuando cobra algo en una tarjeta de crédito, se compromete a devolverlo más tarde. Cuando creas deuda técnica, tu equipo _debe_ comprometerse a abordar esos problemas en un calendario. <add>Compáralo con el dinero. Cuando cobra algo en una tarjeta de crédito, se compromete a devolverlo más tarde. Cuando creas deuda técnica, tu equipo _debe_ comprometerse a abordar esos problemas en un futuro. <ide> <del>Uno de los beneficios de trabajar iterativamente es mostrar con frecuencia sus incrementos y recopilar comentarios. Si su primer pase es "lo suficientemente bueno" y se requieren cambios como resultado de esa retroalimentación, es posible que haya evitado algún trabajo innecesario. Capture esto en su cartera de pedidos e incluya una parte en cada sprint para ser refactorizada o mejorada. <add>Uno de los beneficios de trabajar iterativamente es mostrar con frecuencia sus incrementos y recopilar comentarios. Si su primer pase es "lo suficientemente bueno" y se requieren cambios como resultado de esa retroalimentación, es posible que haya evitado algún trabajo innecesario. Capture esto en su backlog e incluya una parte en cada sprint para ser refactorizada o mejorada. <ide> <ide> #### Más información: <ide> <ide> * La alianza ágil sobre [deuda técnica](https://www.agilealliance.org/introduction-to-the-technical-debt-concept/) <del>* Alianza Scrum en [Gestión de Deuda Técnica](https://www.scrumalliance.org/community/articles/2013/july/managing-technical-debt) <ide>\ No newline at end of file <add>* Alianza Scrum en [Gestión de Deuda Técnica](https://www.scrumalliance.org/community/articles/2013/july/managing-technical-debt)
1
Ruby
Ruby
skip extra work if no text or phrase was provided
ca59ec354ee8ba264120783c9364927a97b90896
<ide><path>actionpack/lib/action_view/helpers/text_helper.rb <ide> def highlight(text, phrases, *args) <ide> # excerpt('This is an example', 'an', 5) # => ...s is an exam... <ide> # excerpt('This is also an example', 'an', 8, '<chop> ') # => <chop> is also an example <ide> def excerpt(text, phrase, *args) <add> return unless text && phrase <add> <ide> options = args.extract_options! <ide> unless args.empty? <ide> options[:radius] = args[0] || 100 <ide> options[:omission] = args[1] || "..." <ide> end <ide> options.reverse_merge!(:radius => 100, :omission => "...") <ide> <del> if text && phrase <del> phrase = Regexp.escape(phrase) <del> <del> if found_pos = text.mb_chars =~ /(#{phrase})/i <del> start_pos = [ found_pos - options[:radius], 0 ].max <del> end_pos = [ [ found_pos + phrase.mb_chars.length + options[:radius] - 1, 0].max, text.mb_chars.length ].min <add> phrase = Regexp.escape(phrase) <add> if found_pos = text.mb_chars =~ /(#{phrase})/i <add> start_pos = [ found_pos - options[:radius], 0 ].max <add> end_pos = [ [ found_pos + phrase.mb_chars.length + options[:radius] - 1, 0].max, text.mb_chars.length ].min <ide> <del> prefix = start_pos > 0 ? options[:omission] : "" <del> postfix = end_pos < text.mb_chars.length - 1 ? options[:omission] : "" <add> prefix = start_pos > 0 ? options[:omission] : "" <add> postfix = end_pos < text.mb_chars.length - 1 ? options[:omission] : "" <ide> <del> prefix + text.mb_chars[start_pos..end_pos].strip + postfix <del> else <del> nil <del> end <add> prefix + text.mb_chars[start_pos..end_pos].strip + postfix <add> else <add> nil <ide> end <ide> end <ide>
1
PHP
PHP
add abstract createapplication() method
5e88f616e8b75ce5a0e7bd034923d725bc0f5321
<ide><path>src/Illuminate/Foundation/Testing/TestCase.php <ide> protected function refreshApplication() <ide> $this->client = $this->createClient(); <ide> } <ide> <add> /** <add> * Creates the application. <add> * <add> * Needs to be implemented by subclasses. <add> * <add> * @return Symfony\Component\HttpKernel\HttpKernelInterface <add> */ <add> abstract protected function createApplication(); <add> <ide> /** <ide> * Call the given URI and return the Response. <ide> *
1
Javascript
Javascript
improve path tests
5a54e4554ae0ff9788812c88ae05dfdd6088ffe1
<ide><path>test/parallel/test-path-parse-format.js <ide> const unixPaths = [ <ide> './file', <ide> 'C:\\foo', <ide> '/', <del> '' <add> '', <add> '.', <add> '..', <add> '/foo', <add> '/foo.', <add> '/foo.bar', <add> '/.', <add> '/.foo', <add> '/.foo.bar', <add> '/foo/bar.baz', <ide> ]; <ide> <ide> const unixSpecialCaseFormatTests = [ <ide> checkErrors(path.posix); <ide> checkFormat(path.win32, winSpecialCaseFormatTests); <ide> checkFormat(path.posix, unixSpecialCaseFormatTests); <ide> <add>// Test removal of trailing path separators <add>const trailingTests = [ <add> [ path.win32.parse, <add> [['.\\', { root: '', dir: '', base: '.', ext: '', name: '.' }], <add> ['\\\\', { root: '\\', dir: '\\', base: '', ext: '', name: '' }], <add> ['\\\\', { root: '\\', dir: '\\', base: '', ext: '', name: '' }], <add> ['c:\\foo\\\\\\', <add> { root: 'c:\\', dir: 'c:\\', base: 'foo', ext: '', name: 'foo' }], <add> ['D:\\foo\\\\\\bar.baz', <add> { root: 'D:\\', <add> dir: 'D:\\foo\\\\', <add> base: 'bar.baz', <add> ext: '.baz', <add> name: 'bar' <add> } <add> ] <add> ] <add> ], <add> [ path.posix.parse, <add> [['./', { root: '', dir: '', base: '.', ext: '', name: '.' }], <add> ['//', { root: '/', dir: '/', base: '', ext: '', name: '' }], <add> ['///', { root: '/', dir: '/', base: '', ext: '', name: '' }], <add> ['/foo///', { root: '/', dir: '/', base: 'foo', ext: '', name: 'foo' }], <add> ['/foo///bar.baz', <add> { root: '/', dir: '/foo//', base: 'bar.baz', ext: '.baz', name: 'bar' } <add> ] <add> ] <add> ] <add>]; <add>const failures = []; <add>trailingTests.forEach(function(test) { <add> const parse = test[0]; <add> test[1].forEach(function(test) { <add> const actual = parse(test[0]); <add> const expected = test[1]; <add> const fn = 'path.' + <add> (parse === path.win32.parse ? 'win32' : 'posix') + <add> '.parse('; <add> const message = fn + <add> JSON.stringify(test[0]) + <add> ')' + <add> '\n expect=' + JSON.stringify(expected) + <add> '\n actual=' + JSON.stringify(actual); <add> const actualKeys = Object.keys(actual); <add> const expectedKeys = Object.keys(expected); <add> let failed = (actualKeys.length !== expectedKeys.length); <add> if (!failed) { <add> for (let i = 0; i < actualKeys.length; ++i) { <add> const key = actualKeys[i]; <add> if (expectedKeys.indexOf(key) === -1 || actual[key] !== expected[key]) { <add> failed = true; <add> break; <add> } <add> } <add> } <add> if (failed) <add> failures.push('\n' + message); <add> }); <add>}); <add>assert.equal(failures.length, 0, failures.join('')); <add> <ide> function checkErrors(path) { <ide> errors.forEach(function(errorCase) { <ide> try { <ide><path>test/parallel/test-path-zero-length-strings.js <ide> const pwd = process.cwd(); <ide> <ide> // join will internally ignore all the zero-length strings and it will return <ide> // '.' if the joined string is a zero-length string. <del>assert.equal(path.join(''), '.'); <del>assert.equal(path.join('', ''), '.'); <add>assert.equal(path.posix.join(''), '.'); <add>assert.equal(path.posix.join('', ''), '.'); <add>assert.equal(path.win32.join(''), '.'); <add>assert.equal(path.win32.join('', ''), '.'); <ide> assert.equal(path.join(pwd), pwd); <ide> assert.equal(path.join(pwd, ''), pwd); <ide> <ide> // normalize will return '.' if the input is a zero-length string <del>assert.equal(path.normalize(''), '.'); <add>assert.equal(path.posix.normalize(''), '.'); <add>assert.equal(path.win32.normalize(''), '.'); <ide> assert.equal(path.normalize(pwd), pwd); <ide> <ide> // Since '' is not a valid path in any of the common environments, return false <del>assert.equal(path.isAbsolute(''), false); <add>assert.equal(path.posix.isAbsolute(''), false); <add>assert.equal(path.win32.isAbsolute(''), false); <ide> <ide> // resolve, internally ignores all the zero-length strings and returns the <ide> // current working directory <ide><path>test/parallel/test-path.js <ide> 'use strict'; <del>var common = require('../common'); <del>var assert = require('assert'); <add>const common = require('../common'); <add>const assert = require('assert'); <add>const path = require('path'); <ide> <del>var path = require('path'); <del> <del>var f = __filename; <add>const f = __filename; <add>const failures = []; <ide> <add>// path.basename tests <ide> assert.equal(path.basename(f), 'test-path.js'); <ide> assert.equal(path.basename(f, '.js'), 'test-path'); <ide> assert.equal(path.basename(''), ''); <ide> assert.equal(path.posix.basename('basename.ext\\\\'), 'basename.ext\\\\'); <ide> <ide> // POSIX filenames may include control characters <ide> // c.f. http://www.dwheeler.com/essays/fixing-unix-linux-filenames.html <del>if (!common.isWindows) { <del> var controlCharFilename = 'Icon' + String.fromCharCode(13); <del> assert.equal(path.basename('/a/b/' + controlCharFilename), <del> controlCharFilename); <del>} <add>const controlCharFilename = 'Icon' + String.fromCharCode(13); <add>assert.equal(path.posix.basename('/a/b/' + controlCharFilename), <add> controlCharFilename); <ide> <del>assert.equal(path.extname(f), '.js'); <ide> <add>// path.dirname tests <ide> assert.equal(path.dirname(f).substr(-13), <ide> common.isWindows ? 'test\\parallel' : 'test/parallel'); <del>assert.equal(path.dirname('/a/b/'), '/a'); <del>assert.equal(path.dirname('/a/b'), '/a'); <del>assert.equal(path.dirname('/a'), '/'); <del>assert.equal(path.dirname(''), '.'); <del>assert.equal(path.dirname('/'), '/'); <del>assert.equal(path.dirname('////'), '/'); <add> <add>assert.equal(path.posix.dirname('/a/b/'), '/a'); <add>assert.equal(path.posix.dirname('/a/b'), '/a'); <add>assert.equal(path.posix.dirname('/a'), '/'); <add>assert.equal(path.posix.dirname(''), '.'); <add>assert.equal(path.posix.dirname('/'), '/'); <add>assert.equal(path.posix.dirname('////'), '/'); <ide> <ide> assert.equal(path.win32.dirname('c:\\'), 'c:\\'); <ide> assert.equal(path.win32.dirname('c:\\foo'), 'c:\\'); <ide> assert.equal(path.win32.dirname('\\\\unc\\share\\foo\\bar\\'), <ide> '\\\\unc\\share\\foo'); <ide> assert.equal(path.win32.dirname('\\\\unc\\share\\foo\\bar\\baz'), <ide> '\\\\unc\\share\\foo\\bar'); <add>assert.equal(path.win32.dirname('/a/b/'), '/a'); <add>assert.equal(path.win32.dirname('/a/b'), '/a'); <add>assert.equal(path.win32.dirname('/a'), '/'); <add>assert.equal(path.win32.dirname(''), '.'); <add>assert.equal(path.win32.dirname('/'), '/'); <add>assert.equal(path.win32.dirname('////'), '/'); <add> <add> <add>// path.extname tests <add>[ <add> [f, '.js'], <add> ['', ''], <add> ['/path/to/file', ''], <add> ['/path/to/file.ext', '.ext'], <add> ['/path.to/file.ext', '.ext'], <add> ['/path.to/file', ''], <add> ['/path.to/.file', ''], <add> ['/path.to/.file.ext', '.ext'], <add> ['/path/to/f.ext', '.ext'], <add> ['/path/to/..ext', '.ext'], <add> ['/path/to/..', ''], <add> ['file', ''], <add> ['file.ext', '.ext'], <add> ['.file', ''], <add> ['.file.ext', '.ext'], <add> ['/file', ''], <add> ['/file.ext', '.ext'], <add> ['/.file', ''], <add> ['/.file.ext', '.ext'], <add> ['.path/file.ext', '.ext'], <add> ['file.ext.ext', '.ext'], <add> ['file.', '.'], <add> ['.', ''], <add> ['./', ''], <add> ['.file.ext', '.ext'], <add> ['.file', ''], <add> ['.file.', '.'], <add> ['.file..', '.'], <add> ['..', ''], <add> ['../', ''], <add> ['..file.ext', '.ext'], <add> ['..file', '.file'], <add> ['..file.', '.'], <add> ['..file..', '.'], <add> ['...', '.'], <add> ['...ext', '.ext'], <add> ['....', '.'], <add> ['file.ext/', '.ext'], <add> ['file.ext//', '.ext'], <add> ['file/', ''], <add> ['file//', ''], <add> ['file./', '.'], <add> ['file.//', '.'], <add>].forEach(function(test) { <add> [path.posix.extname, path.win32.extname].forEach(function(extname) { <add> let input = test[0]; <add> if (extname === path.win32.extname) <add> input = input.replace(/\//g, '\\'); <add> const actual = extname(input); <add> const expected = test[1]; <add> const fn = 'path.' + <add> (extname === path.win32.extname ? 'win32' : 'posix') + <add> '.extname('; <add> const message = fn + JSON.stringify(input) + ')' + <add> '\n expect=' + JSON.stringify(expected) + <add> '\n actual=' + JSON.stringify(actual); <add> if (actual !== expected) <add> failures.push('\n' + message); <add> }); <add>}); <add>assert.equal(failures.length, 0, failures.join('')); <ide> <del> <del>assert.equal(path.extname(''), ''); <del>assert.equal(path.extname('/path/to/file'), ''); <del>assert.equal(path.extname('/path/to/file.ext'), '.ext'); <del>assert.equal(path.extname('/path.to/file.ext'), '.ext'); <del>assert.equal(path.extname('/path.to/file'), ''); <del>assert.equal(path.extname('/path.to/.file'), ''); <del>assert.equal(path.extname('/path.to/.file.ext'), '.ext'); <del>assert.equal(path.extname('/path/to/f.ext'), '.ext'); <del>assert.equal(path.extname('/path/to/..ext'), '.ext'); <del>assert.equal(path.extname('file'), ''); <del>assert.equal(path.extname('file.ext'), '.ext'); <del>assert.equal(path.extname('.file'), ''); <del>assert.equal(path.extname('.file.ext'), '.ext'); <del>assert.equal(path.extname('/file'), ''); <del>assert.equal(path.extname('/file.ext'), '.ext'); <del>assert.equal(path.extname('/.file'), ''); <del>assert.equal(path.extname('/.file.ext'), '.ext'); <del>assert.equal(path.extname('.path/file.ext'), '.ext'); <del>assert.equal(path.extname('file.ext.ext'), '.ext'); <del>assert.equal(path.extname('file.'), '.'); <del>assert.equal(path.extname('.'), ''); <del>assert.equal(path.extname('./'), ''); <del>assert.equal(path.extname('.file.ext'), '.ext'); <del>assert.equal(path.extname('.file'), ''); <del>assert.equal(path.extname('.file.'), '.'); <del>assert.equal(path.extname('.file..'), '.'); <del>assert.equal(path.extname('..'), ''); <del>assert.equal(path.extname('../'), ''); <del>assert.equal(path.extname('..file.ext'), '.ext'); <del>assert.equal(path.extname('..file'), '.file'); <del>assert.equal(path.extname('..file.'), '.'); <del>assert.equal(path.extname('..file..'), '.'); <del>assert.equal(path.extname('...'), '.'); <del>assert.equal(path.extname('...ext'), '.ext'); <del>assert.equal(path.extname('....'), '.'); <del>assert.equal(path.extname('file.ext/'), '.ext'); <del>assert.equal(path.extname('file.ext//'), '.ext'); <del>assert.equal(path.extname('file/'), ''); <del>assert.equal(path.extname('file//'), ''); <del>assert.equal(path.extname('file./'), '.'); <del>assert.equal(path.extname('file.//'), '.'); <del> <del>// On windows, backspace is a path separator. <add>// On Windows, backslash is a path separator. <ide> assert.equal(path.win32.extname('.\\'), ''); <ide> assert.equal(path.win32.extname('..\\'), ''); <ide> assert.equal(path.win32.extname('file.ext\\'), '.ext'); <ide> assert.equal(path.win32.extname('file\\\\'), ''); <ide> assert.equal(path.win32.extname('file.\\'), '.'); <ide> assert.equal(path.win32.extname('file.\\\\'), '.'); <ide> <del>// On unix, backspace is a valid name component like any other character. <add>// On *nix, backslash is a valid name component like any other character. <ide> assert.equal(path.posix.extname('.\\'), ''); <ide> assert.equal(path.posix.extname('..\\'), '.\\'); <ide> assert.equal(path.posix.extname('file.ext\\'), '.ext\\'); <ide> assert.equal(path.posix.extname('file\\\\'), ''); <ide> assert.equal(path.posix.extname('file.\\'), '.\\'); <ide> assert.equal(path.posix.extname('file.\\\\'), '.\\\\'); <ide> <add> <ide> // path.join tests <del>var failures = []; <del>var joinTests = <add>const joinTests = [ <add> [ [path.posix.join, path.win32.join], <ide> // arguments result <ide> [[['.', 'x/b', '..', '/b/c.js'], 'x/b/c.js'], <ide> [['/.', 'x/b', '..', '/b/c.js'], '/x/b/c.js'], <ide> var joinTests = <ide> [['/', '', '/foo'], '/foo'], <ide> [['', '/', 'foo'], '/foo'], <ide> [['', '/', '/foo'], '/foo'] <del> ]; <add> ] <add> ] <add>]; <ide> <ide> // Windows-specific join tests <del>if (common.isWindows) { <del> joinTests = joinTests.concat( <del> [// UNC path expected <del> [['//foo/bar'], '//foo/bar/'], <del> [['\\/foo/bar'], '//foo/bar/'], <del> [['\\\\foo/bar'], '//foo/bar/'], <add>joinTests.push([ <add> path.win32.join, <add> joinTests[0][1].slice(0).concat( <add> [// arguments result <add> // UNC path expected <add> [['//foo/bar'], '\\\\foo\\bar\\'], <add> [['\\/foo/bar'], '\\\\foo\\bar\\'], <add> [['\\\\foo/bar'], '\\\\foo\\bar\\'], <ide> // UNC path expected - server and share separate <del> [['//foo', 'bar'], '//foo/bar/'], <del> [['//foo/', 'bar'], '//foo/bar/'], <del> [['//foo', '/bar'], '//foo/bar/'], <add> [['//foo', 'bar'], '\\\\foo\\bar\\'], <add> [['//foo/', 'bar'], '\\\\foo\\bar\\'], <add> [['//foo', '/bar'], '\\\\foo\\bar\\'], <ide> // UNC path expected - questionable <del> [['//foo', '', 'bar'], '//foo/bar/'], <del> [['//foo/', '', 'bar'], '//foo/bar/'], <del> [['//foo/', '', '/bar'], '//foo/bar/'], <add> [['//foo', '', 'bar'], '\\\\foo\\bar\\'], <add> [['//foo/', '', 'bar'], '\\\\foo\\bar\\'], <add> [['//foo/', '', '/bar'], '\\\\foo\\bar\\'], <ide> // UNC path expected - even more questionable <del> [['', '//foo', 'bar'], '//foo/bar/'], <del> [['', '//foo/', 'bar'], '//foo/bar/'], <del> [['', '//foo/', '/bar'], '//foo/bar/'], <add> [['', '//foo', 'bar'], '\\\\foo\\bar\\'], <add> [['', '//foo/', 'bar'], '\\\\foo\\bar\\'], <add> [['', '//foo/', '/bar'], '\\\\foo\\bar\\'], <ide> // No UNC path expected (no double slash in first component) <del> [['\\', 'foo/bar'], '/foo/bar'], <del> [['\\', '/foo/bar'], '/foo/bar'], <del> [['', '/', '/foo/bar'], '/foo/bar'], <del> // No UNC path expected (no non-slashes in first component - questionable) <del> [['//', 'foo/bar'], '/foo/bar'], <del> [['//', '/foo/bar'], '/foo/bar'], <del> [['\\\\', '/', '/foo/bar'], '/foo/bar'], <add> [['\\', 'foo/bar'], '\\foo\\bar'], <add> [['\\', '/foo/bar'], '\\foo\\bar'], <add> [['', '/', '/foo/bar'], '\\foo\\bar'], <add> // No UNC path expected (no non-slashes in first component - <add> // questionable) <add> [['//', 'foo/bar'], '\\foo\\bar'], <add> [['//', '/foo/bar'], '\\foo\\bar'], <add> [['\\\\', '/', '/foo/bar'], '\\foo\\bar'], <ide> [['//'], '/'], <ide> // No UNC path expected (share name missing - questionable). <del> [['//foo'], '/foo'], <del> [['//foo/'], '/foo/'], <del> [['//foo', '/'], '/foo/'], <del> [['//foo', '', '/'], '/foo/'], <add> [['//foo'], '\\foo'], <add> [['//foo/'], '\\foo\\'], <add> [['//foo', '/'], '\\foo\\'], <add> [['//foo', '', '/'], '\\foo\\'], <ide> // No UNC path expected (too many leading slashes - questionable) <del> [['///foo/bar'], '/foo/bar'], <del> [['////foo', 'bar'], '/foo/bar'], <del> [['\\\\\\/foo/bar'], '/foo/bar'], <add> [['///foo/bar'], '\\foo\\bar'], <add> [['////foo', 'bar'], '\\foo\\bar'], <add> [['\\\\\\/foo/bar'], '\\foo\\bar'], <ide> // Drive-relative vs drive-absolute paths. This merely describes the <ide> // status quo, rather than being obviously right <ide> [['c:'], 'c:.'], <ide> [['c:.'], 'c:.'], <ide> [['c:', ''], 'c:.'], <ide> [['', 'c:'], 'c:.'], <del> [['c:.', '/'], 'c:./'], <add> [['c:.', '/'], 'c:.\\'], <ide> [['c:.', 'file'], 'c:file'], <del> [['c:', '/'], 'c:/'], <del> [['c:', 'file'], 'c:/file'] <del> ]); <del>} <del> <del>// Run the join tests. <add> [['c:', '/'], 'c:\\'], <add> [['c:', 'file'], 'c:\\file'] <add> ] <add> ) <add>]); <ide> joinTests.forEach(function(test) { <del> var actual = path.join.apply(path, test[0]); <del> var expected = common.isWindows ? test[1].replace(/\//g, '\\') : test[1]; <del> var message = 'path.join(' + test[0].map(JSON.stringify).join(',') + ')' + <del> '\n expect=' + JSON.stringify(expected) + <del> '\n actual=' + JSON.stringify(actual); <del> if (actual !== expected) failures.push('\n' + message); <del> // assert.equal(actual, expected, message); <add> if (!Array.isArray(test[0])) <add> test[0] = [test[0]]; <add> test[0].forEach(function(join) { <add> test[1].forEach(function(test) { <add> const actual = join.apply(null, test[0]); <add> const expected = test[1]; <add> let actualAlt; <add> // For non-Windows specific tests with the Windows join(), we need to try <add> // replacing the slashes since the non-Windows specific tests' `expected` <add> // use forward slashes <add> if (join === path.win32.join) <add> actualAlt = actual.replace(/\\/g, '/'); <add> const fn = 'path.' + <add> (join === path.win32.join ? 'win32' : 'posix') + <add> '.join('; <add> const message = fn + test[0].map(JSON.stringify).join(',') + ')' + <add> '\n expect=' + JSON.stringify(expected) + <add> '\n actual=' + JSON.stringify(actual); <add> if (actual !== expected && actualAlt !== expected) <add> failures.push('\n' + message); <add> }); <add> }); <ide> }); <ide> assert.equal(failures.length, 0, failures.join('')); <ide> <add> <ide> // Test thrown TypeErrors <ide> var typeErrorTests = [true, false, 7, null, {}, undefined, [], NaN]; <ide> <ide> typeErrorTests.forEach(function(test) { <ide> }); <ide> <ide> <del>// path normalize tests <add>// path.normalize tests <ide> assert.equal(path.win32.normalize('./fixtures///b/../b/c.js'), <ide> 'fixtures\\b\\c.js'); <ide> assert.equal(path.win32.normalize('/foo/../../../bar'), '\\bar'); <ide> assert.equal(path.posix.normalize('a//b//../b'), 'a/b'); <ide> assert.equal(path.posix.normalize('a//b//./c'), 'a/b/c'); <ide> assert.equal(path.posix.normalize('a//b//.'), 'a/b'); <ide> <add> <ide> // path.resolve tests <del>var resolveTests; <del>if (common.isWindows) { <del> // windows <del> resolveTests = <del> // arguments result <del> [[['c:/blah\\blah', 'd:/games', 'c:../a'], 'c:\\blah\\a'], <del> [['c:/ignore', 'd:\\a/b\\c/d', '\\e.exe'], 'd:\\e.exe'], <del> [['c:/ignore', 'c:/some/file'], 'c:\\some\\file'], <del> [['d:/ignore', 'd:some/dir//'], 'd:\\ignore\\some\\dir'], <del> [['.'], process.cwd()], <del> [['//server/share', '..', 'relative\\'], '\\\\server\\share\\relative'], <del> [['c:/', '//'], 'c:\\'], <del> [['c:/', '//dir'], 'c:\\dir'], <del> [['c:/', '//server/share'], '\\\\server\\share\\'], <del> [['c:/', '//server//share'], '\\\\server\\share\\'], <del> [['c:/', '///some//dir'], 'c:\\some\\dir'] <del> ]; <del>} else { <del> // Posix <del> resolveTests = <del> // arguments result <del> [[['/var/lib', '../', 'file/'], '/var/file'], <del> [['/var/lib', '/../', 'file/'], '/file'], <del> [['a/b/c/', '../../..'], process.cwd()], <del> [['.'], process.cwd()], <del> [['/some/dir', '.', '/absolute/'], '/absolute']]; <del>} <del>failures = []; <add>const resolveTests = [ <add> [ path.win32.resolve, <add> // arguments result <add> [[['c:/blah\\blah', 'd:/games', 'c:../a'], 'c:\\blah\\a'], <add> [['c:/ignore', 'd:\\a/b\\c/d', '\\e.exe'], 'd:\\e.exe'], <add> [['c:/ignore', 'c:/some/file'], 'c:\\some\\file'], <add> [['d:/ignore', 'd:some/dir//'], 'd:\\ignore\\some\\dir'], <add> [['.'], process.cwd()], <add> [['//server/share', '..', 'relative\\'], '\\\\server\\share\\relative'], <add> [['c:/', '//'], 'c:\\'], <add> [['c:/', '//dir'], 'c:\\dir'], <add> [['c:/', '//server/share'], '\\\\server\\share\\'], <add> [['c:/', '//server//share'], '\\\\server\\share\\'], <add> [['c:/', '///some//dir'], 'c:\\some\\dir'], <add> [['C:\\foo\\tmp.3\\', '..\\tmp.3\\cycles\\root.js'], <add> 'C:\\foo\\tmp.3\\cycles\\root.js'] <add> ] <add> ], <add> [ path.posix.resolve, <add> // arguments result <add> [[['/var/lib', '../', 'file/'], '/var/file'], <add> [['/var/lib', '/../', 'file/'], '/file'], <add> [['a/b/c/', '../../..'], process.cwd()], <add> [['.'], process.cwd()], <add> [['/some/dir', '.', '/absolute/'], '/absolute'], <add> [['/foo/tmp.3/', '../tmp.3/cycles/root.js'], '/foo/tmp.3/cycles/root.js'] <add> ] <add> ] <add>]; <ide> resolveTests.forEach(function(test) { <del> var actual = path.resolve.apply(path, test[0]); <del> var expected = test[1]; <del> var message = 'path.resolve(' + test[0].map(JSON.stringify).join(',') + ')' + <del> '\n expect=' + JSON.stringify(expected) + <del> '\n actual=' + JSON.stringify(actual); <del> if (actual !== expected) failures.push('\n' + message); <del> // assert.equal(actual, expected, message); <add> const resolve = test[0]; <add> test[1].forEach(function(test) { <add> const actual = resolve.apply(null, test[0]); <add> let actualAlt; <add> if (resolve === path.win32.resolve && !common.isWindows) <add> actualAlt = actual.replace(/\\/g, '/'); <add> else if (resolve !== path.win32.resolve && common.isWindows) <add> actualAlt = actual.replace(/\//g, '\\'); <add> const expected = test[1]; <add> const fn = 'path.' + <add> (resolve === path.win32.resolve ? 'win32' : 'posix') + <add> '.resolve('; <add> const message = fn + test[0].map(JSON.stringify).join(',') + ')' + <add> '\n expect=' + JSON.stringify(expected) + <add> '\n actual=' + JSON.stringify(actual); <add> if (actual !== expected && actualAlt !== expected) <add> failures.push('\n' + message); <add> }); <ide> }); <ide> assert.equal(failures.length, 0, failures.join('')); <ide> <add> <ide> // path.isAbsolute tests <ide> assert.equal(path.win32.isAbsolute('//server/file'), true); <ide> assert.equal(path.win32.isAbsolute('\\\\server\\file'), true); <ide> assert.equal(path.posix.isAbsolute('/home/foo/..'), true); <ide> assert.equal(path.posix.isAbsolute('bar/'), false); <ide> assert.equal(path.posix.isAbsolute('./baz'), false); <ide> <add> <ide> // path.relative tests <del>var relativeTests; <del>if (common.isWindows) { <del> // windows <del> relativeTests = <del> // arguments result <del> [['c:/blah\\blah', 'd:/games', 'd:\\games'], <del> ['c:/aaaa/bbbb', 'c:/aaaa', '..'], <del> ['c:/aaaa/bbbb', 'c:/cccc', '..\\..\\cccc'], <del> ['c:/aaaa/bbbb', 'c:/aaaa/bbbb', ''], <del> ['c:/aaaa/bbbb', 'c:/aaaa/cccc', '..\\cccc'], <del> ['c:/aaaa/', 'c:/aaaa/cccc', 'cccc'], <del> ['c:/', 'c:\\aaaa\\bbbb', 'aaaa\\bbbb'], <del> ['c:/aaaa/bbbb', 'd:\\', 'd:\\']]; <del>} else { <del> // posix <del> relativeTests = <del> // arguments result <del> [['/var/lib', '/var', '..'], <del> ['/var/lib', '/bin', '../../bin'], <del> ['/var/lib', '/var/lib', ''], <del> ['/var/lib', '/var/apache', '../apache'], <del> ['/var/', '/var/lib', 'lib'], <del> ['/', '/var/lib', 'var/lib']]; <del>} <del>failures = []; <add>const relativeTests = [ <add> [ path.win32.relative, <add> // arguments result <add> [['c:/blah\\blah', 'd:/games', 'd:\\games'], <add> ['c:/aaaa/bbbb', 'c:/aaaa', '..'], <add> ['c:/aaaa/bbbb', 'c:/cccc', '..\\..\\cccc'], <add> ['c:/aaaa/bbbb', 'c:/aaaa/bbbb', ''], <add> ['c:/aaaa/bbbb', 'c:/aaaa/cccc', '..\\cccc'], <add> ['c:/aaaa/', 'c:/aaaa/cccc', 'cccc'], <add> ['c:/', 'c:\\aaaa\\bbbb', 'aaaa\\bbbb'], <add> ['c:/aaaa/bbbb', 'd:\\', 'd:\\'], <add> ['c:/AaAa/bbbb', 'c:/aaaa/bbbb', ''], <add> ['c:/aaaaa/', 'c:/aaaa/cccc', '..\\aaaa\\cccc'], <add> ['C:\\foo\\bar\\baz\\quux', 'C:\\', '..\\..\\..\\..'], <add> ['C:\\foo\\test', 'C:\\foo\\test\\bar\\package.json', 'bar\\package.json'] <add> ] <add> ], <add> [ path.posix.relative, <add> // arguments result <add> [['/var/lib', '/var', '..'], <add> ['/var/lib', '/bin', '../../bin'], <add> ['/var/lib', '/var/lib', ''], <add> ['/var/lib', '/var/apache', '../apache'], <add> ['/var/', '/var/lib', 'lib'], <add> ['/', '/var/lib', 'var/lib'], <add> ['/foo/test', '/foo/test/bar/package.json', 'bar/package.json'] <add> ] <add> ] <add>]; <ide> relativeTests.forEach(function(test) { <del> var actual = path.relative(test[0], test[1]); <del> var expected = test[2]; <del> var message = 'path.relative(' + <del> test.slice(0, 2).map(JSON.stringify).join(',') + <del> ')' + <del> '\n expect=' + JSON.stringify(expected) + <del> '\n actual=' + JSON.stringify(actual); <del> if (actual !== expected) failures.push('\n' + message); <add> const relative = test[0]; <add> test[1].forEach(function(test) { <add> const actual = relative(test[0], test[1]); <add> const expected = test[2]; <add> const fn = 'path.' + <add> (relative === path.win32.relative ? 'win32' : 'posix') + <add> '.relative('; <add> const message = fn + <add> test.slice(0, 2).map(JSON.stringify).join(',') + <add> ')' + <add> '\n expect=' + JSON.stringify(expected) + <add> '\n actual=' + JSON.stringify(actual); <add> if (actual !== expected) <add> failures.push('\n' + message); <add> }); <ide> }); <ide> assert.equal(failures.length, 0, failures.join('')); <ide> <add> <add>// path.sep tests <ide> // windows <ide> assert.equal(path.win32.sep, '\\'); <ide> // posix <ide> assert.equal(path.posix.sep, '/'); <ide> // path.delimiter tests <ide> // windows <ide> assert.equal(path.win32.delimiter, ';'); <del> <ide> // posix <ide> assert.equal(path.posix.delimiter, ':'); <ide> <ide> <add>// path._makeLong tests <add>assert.equal(path.posix._makeLong('/foo/bar'), '/foo/bar'); <add>assert.equal(path.posix._makeLong('foo/bar'), 'foo/bar'); <add>if (common.isWindows) { <add> // These tests cause resolve() to insert the cwd, so we cannot test them from <add> // non-Windows platforms (easily) <add> assert.equal(path.win32._makeLong('foo\\bar').toLowerCase(), <add> '\\\\?\\' + process.cwd().toLowerCase() + '\\foo\\bar'); <add> assert.equal(path.win32._makeLong('foo/bar').toLowerCase(), <add> '\\\\?\\' + process.cwd().toLowerCase() + '\\foo\\bar'); <add> assert.equal(path.win32._makeLong('C:').toLowerCase(), <add> '\\\\?\\' + process.cwd().toLowerCase()); <add> assert.equal(path.win32._makeLong('C').toLowerCase(), <add> '\\\\?\\' + process.cwd().toLowerCase() + '\\c'); <add>} <add>assert.equal(path.win32._makeLong('C:\\foo'), '\\\\?\\C:\\foo'); <add>assert.equal(path.win32._makeLong('C:/foo'), '\\\\?\\C:\\foo'); <add>assert.equal(path.win32._makeLong('\\\\foo\\bar'), '\\\\?\\UNC\\foo\\bar\\'); <add>assert.equal(path.win32._makeLong('//foo//bar'), '\\\\?\\UNC\\foo\\bar\\'); <add>assert.equal(path.win32._makeLong('\\\\?\\foo'), '\\\\?\\foo'); <add> <add> <ide> if (common.isWindows) <ide> assert.deepEqual(path, path.win32, 'should be win32 path module'); <ide> else
3
Java
Java
fix removal of virtual nodes in fabricreconciler
c0d27de37eec7b6860387e35dae4dfc455d4b6e2
<ide><path>ReactAndroid/src/main/java/com/facebook/react/fabric/FabricReconciler.java <ide> private void manageChildren( <ide> // If a View is not re-ordered, then the ReactTag is deleted (ReactShadowNode and native View <ide> // are released from memory) <ide> List<Integer> tagsToDelete = new LinkedList<>(); <del> int[] indicesToRemove = new int[prevList.size() - firstRemovedOrAddedViewIndex]; <del> int indicesToRemoveIndex = 0; <del> for (int j = firstRemovedOrAddedViewIndex; j < prevList.size(); j++) { <add> List<Integer> indicesToRemove = new LinkedList<>(); <add> for (int j = prevList.size() - 1; j >= firstRemovedOrAddedViewIndex; j--) { <ide> ReactShadowNode nodeToRemove = prevList.get(j); <ide> if (nodeToRemove.isVirtual()) continue; <del> indicesToRemove[indicesToRemoveIndex++] = j; <add> indicesToRemove.add(0, j); <ide> if (!addedTags.contains(nodeToRemove.getReactTag())) { <ide> tagsToDelete.add(nodeToRemove.getReactTag()); <ide> // TODO: T26729293 since we are not cloning ReactShadowNode's we need to "manually" remove <ide> private void manageChildren( <ide> } <ide> } <ide> <del> int[] tagsToDeleteArray = ArrayUtils.copyListToArray(tagsToDelete); <del> ViewAtIndex[] viewsToAddArray = viewsToAdd.toArray(new ViewAtIndex[viewsToAdd.size()]); <del> <ide> // TODO (t27180994): Mutate views synchronously on main thread <del> if (indicesToRemove.length > 0 || viewsToAddArray.length > 0 || tagsToDeleteArray.length > 0) { <add> if (!(indicesToRemove.isEmpty() && viewsToAdd.isEmpty() && tagsToDelete.isEmpty())) { <add> int[] indicesToRemoveArray = ArrayUtils.copyListToArray(indicesToRemove); <add> ViewAtIndex[] viewsToAddArray = viewsToAdd.toArray(new ViewAtIndex[viewsToAdd.size()]); <add> int[] tagsToDeleteArray = ArrayUtils.copyListToArray(tagsToDelete); <ide> if (DEBUG) { <ide> Log.d( <ide> TAG, <ide> "manageChildren.enqueueManageChildren parent: " + parent.getReactTag() + <del> "\n\tIndices2Remove: " + Arrays.toString(indicesToRemove) + <add> "\n\tIndices2Remove: " + Arrays.toString(indicesToRemoveArray) + <ide> "\n\tViews2Add: " + Arrays.toString(viewsToAddArray) + <ide> "\n\tTags2Delete: " + Arrays.toString(tagsToDeleteArray)); <ide> } <ide> uiViewOperationQueue.enqueueManageChildren( <del> parent.getReactTag(), indicesToRemove, viewsToAddArray, tagsToDeleteArray); <add> parent.getReactTag(), indicesToRemoveArray, viewsToAddArray, tagsToDeleteArray); <ide> } <ide> } <ide> <ide><path>ReactAndroid/src/main/java/com/facebook/react/uimanager/ViewAtIndex.java <ide> public ViewAtIndex(int tag, int index) { <ide> mIndex = index; <ide> } <ide> <add> @Override <add> public boolean equals(Object obj) { <add> if (obj == null || obj.getClass() != getClass()) { <add> return false; <add> } <add> ViewAtIndex other = (ViewAtIndex) obj; <add> return mIndex == other.mIndex && mTag == other.mTag; <add> } <add> <ide> @Override <ide> public String toString() { <del> return "[" + mIndex + ", " + mTag + "]"; <add> return "[" + mTag + ", " + mIndex + "]"; <ide> } <ide> }
2
Javascript
Javascript
build latest output files for new version
3e1b120cbeff4caa90ff15880a9e0075e70b50f2
<ide><path>Chart.js <ide> yMin; <ide> helpers.each(this.datasets, function(dataset){ <ide> dataCollection = dataset.points || dataset.bars || dataset.segments; <del> Elements.push(dataCollection[dataIndex]); <add> if (dataCollection[dataIndex]){ <add> Elements.push(dataCollection[dataIndex]); <add> } <ide> }); <ide> <ide> helpers.each(Elements, function(element) { <ide> datasetObject.bars.push(new this.BarClass({ <ide> value : dataPoint, <ide> label : data.labels[index], <add> datasetLabel: dataset.label, <ide> strokeColor : dataset.strokeColor, <ide> fillColor : dataset.fillColor, <ide> highlightFill : dataset.highlightFill || dataset.fillColor, <ide> datasetObject.points.push(new this.PointClass({ <ide> value : dataPoint, <ide> label : data.labels[index], <del> // x: this.scale.calculateX(index), <del> // y: this.scale.endPoint, <add> datasetLabel: dataset.label, <ide> strokeColor : dataset.pointStrokeColor, <ide> fillColor : dataset.pointColor, <ide> highlightFill : dataset.pointHighlightFill || dataset.pointColor, <ide> datasetObject.points.push(new this.PointClass({ <ide> value : dataPoint, <ide> label : data.labels[index], <add> datasetLabel: dataset.label, <ide> x: (this.options.animation) ? this.scale.xCenter : pointPosition.x, <ide> y: (this.options.animation) ? this.scale.yCenter : pointPosition.y, <ide> strokeColor : dataset.pointStrokeColor, <ide> this.eachPoints(function(point){ <ide> point.save(); <ide> }); <add> this.reflow(); <ide> this.render(); <ide> }, <ide> reflow: function(){ <ide><path>Chart.min.js <ide> * Released under the MIT license <ide> * https://github.com/nnnick/Chart.js/blob/master/LICENSE.md <ide> */ <del>(function(){"use strict";var t=this,i=t.Chart,e=function(t){this.canvas=t.canvas,this.ctx=t;this.width=t.canvas.width,this.height=t.canvas.height;return this.aspectRatio=this.width/this.height,s.retinaScale(this),this};e.defaults={global:{animation:!0,animationSteps:60,animationEasing:"easeOutQuart",showScale:!0,scaleOverride:!1,scaleSteps:null,scaleStepWidth:null,scaleStartValue:null,scaleLineColor:"rgba(0,0,0,.1)",scaleLineWidth:1,scaleShowLabels:!0,scaleLabel:"<%=value%>",scaleIntegersOnly:!0,scaleBeginAtZero:!1,scaleFontFamily:"'Helvetica Neue', 'Helvetica', 'Arial', sans-serif",scaleFontSize:12,scaleFontStyle:"normal",scaleFontColor:"#666",responsive:!1,showTooltips:!0,tooltipEvents:["mousemove","touchstart","touchmove","mouseout"],tooltipFillColor:"rgba(0,0,0,0.8)",tooltipFontFamily:"'Helvetica Neue', 'Helvetica', 'Arial', sans-serif",tooltipFontSize:14,tooltipFontStyle:"normal",tooltipFontColor:"#fff",tooltipTitleFontFamily:"'Helvetica Neue', 'Helvetica', 'Arial', sans-serif",tooltipTitleFontSize:14,tooltipTitleFontStyle:"bold",tooltipTitleFontColor:"#fff",tooltipYPadding:6,tooltipXPadding:6,tooltipCaretSize:8,tooltipCornerRadius:6,tooltipXOffset:10,tooltipTemplate:"<%if (label){%><%=label%>: <%}%><%= value %>",multiTooltipTemplate:"<%= value %>",multiTooltipKeyBackground:"#fff",onAnimationProgress:function(){},onAnimationComplete:function(){}}},e.types={};var s=e.helpers={},n=s.each=function(t,i,e){var s=Array.prototype.slice.call(arguments,3);if(t)if(t.length===+t.length){var n;for(n=0;n<t.length;n++)i.apply(e,[t[n],n].concat(s))}else for(var o in t)i.apply(e,[t[o],o].concat(s))},o=s.clone=function(t){var i={};return n(t,function(e,s){t.hasOwnProperty(s)&&(i[s]=e)}),i},a=s.extend=function(t){return n(Array.prototype.slice.call(arguments,1),function(i){n(i,function(e,s){i.hasOwnProperty(s)&&(t[s]=e)})}),t},h=s.merge=function(){var t=Array.prototype.slice.call(arguments,0);return t.unshift({}),a.apply(null,t)},l=s.indexOf=function(t,i){if(Array.prototype.indexOf)return t.indexOf(i);for(var e=0;e<t.length;e++)if(t[e]===i)return e;return-1},r=s.inherits=function(t){var i=this,e=t&&t.hasOwnProperty("constructor")?t.constructor:function(){return i.apply(this,arguments)},s=function(){this.constructor=e};return s.prototype=i.prototype,e.prototype=new s,e.extend=r,t&&a(e.prototype,t),e.__super__=i.prototype,e},c=s.noop=function(){},u=s.uid=function(){var t=0;return function(){return"chart-"+t++}}(),d=s.warn=function(t){window.console&&"function"==typeof window.console.warn&&console.warn(t)},p=s.amd="function"==typeof t.define&&t.define.amd,f=s.isNumber=function(t){return!isNaN(parseFloat(t))&&isFinite(t)},g=s.max=function(t){return Math.max.apply(Math,t)},m=s.min=function(t){return Math.min.apply(Math,t)},v=(s.cap=function(t,i,e){if(f(i)){if(t>i)return i}else if(f(e)&&e>t)return e;return t},s.getDecimalPlaces=function(t){return t%1!==0&&f(t)?t.toString().split(".")[1].length:0}),S=s.radians=function(t){return t*(Math.PI/180)},x=(s.getAngleFromPoint=function(t,i){var e=i.x-t.x,s=i.y-t.y,n=Math.sqrt(e*e+s*s),o=2*Math.PI+Math.atan2(s,e);return 0>e&&0>s&&(o+=2*Math.PI),{angle:o,distance:n}},s.aliasPixel=function(t){return t%2===0?0:.5}),C=(s.splineCurve=function(t,i,e,s){var n=Math.sqrt(Math.pow(i.x-t.x,2)+Math.pow(i.y-t.y,2)),o=Math.sqrt(Math.pow(e.x-i.x,2)+Math.pow(e.y-i.y,2)),a=s*n/(n+o),h=s*o/(n+o);return{inner:{x:i.x-a*(e.x-t.x),y:i.y-a*(e.y-t.y)},outer:{x:i.x+h*(e.x-t.x),y:i.y+h*(e.y-t.y)}}},s.calculateOrderOfMagnitude=function(t){return Math.floor(Math.log(t)/Math.LN10)}),y=(s.calculateScaleRange=function(t,i,e,s,n){var o=2,a=Math.floor(i/(1.5*e)),h=o>=a,l=g(t),r=m(t);l===r&&(l+=.5,r>=.5&&!s?r-=.5:l+=.5);for(var c=Math.abs(l-r),u=C(c),d=Math.ceil(l/(1*Math.pow(10,u)))*Math.pow(10,u),p=s?0:Math.floor(r/(1*Math.pow(10,u)))*Math.pow(10,u),f=d-p,v=Math.pow(10,u),S=Math.round(f/v);(S>a||a>2*S)&&!h;)if(S>a)v*=2,S=Math.round(f/v),S%1!==0&&(h=!0);else if(n&&u>=0){if(v/2%1!==0)break;v/=2,S=Math.round(f/v)}else v/=2,S=Math.round(f/v);return h&&(S=o,v=f/S),{steps:S,stepValue:v,min:p,max:p+S*v}},s.template=function(t,i){function e(t,i){var e=/\W/.test(t)?new Function("obj","var p=[],print=function(){p.push.apply(p,arguments);};with(obj){p.push('"+t.replace(/[\r\t\n]/g," ").split("<%").join(" ").replace(/((^|%>)[^\t]*)'/g,"$1\r").replace(/\t=(.*?)%>/g,"',$1,'").split(" ").join("');").split("%>").join("p.push('").split("\r").join("\\'")+"');}return p.join('');"):s[t]=s[t];return i?e(i):e}var s={};return e(t,i)}),b=(s.generateLabels=function(t,i,e,s){var o=new Array(i);return labelTemplateString&&n(o,function(i,n){o[n]=y(t,{value:e+s*(n+1)})}),o},s.easingEffects={linear:function(t){return t},easeInQuad:function(t){return t*t},easeOutQuad:function(t){return-1*t*(t-2)},easeInOutQuad:function(t){return(t/=.5)<1?.5*t*t:-0.5*(--t*(t-2)-1)},easeInCubic:function(t){return t*t*t},easeOutCubic:function(t){return 1*((t=t/1-1)*t*t+1)},easeInOutCubic:function(t){return(t/=.5)<1?.5*t*t*t:.5*((t-=2)*t*t+2)},easeInQuart:function(t){return t*t*t*t},easeOutQuart:function(t){return-1*((t=t/1-1)*t*t*t-1)},easeInOutQuart:function(t){return(t/=.5)<1?.5*t*t*t*t:-0.5*((t-=2)*t*t*t-2)},easeInQuint:function(t){return 1*(t/=1)*t*t*t*t},easeOutQuint:function(t){return 1*((t=t/1-1)*t*t*t*t+1)},easeInOutQuint:function(t){return(t/=.5)<1?.5*t*t*t*t*t:.5*((t-=2)*t*t*t*t+2)},easeInSine:function(t){return-1*Math.cos(t/1*(Math.PI/2))+1},easeOutSine:function(t){return 1*Math.sin(t/1*(Math.PI/2))},easeInOutSine:function(t){return-0.5*(Math.cos(Math.PI*t/1)-1)},easeInExpo:function(t){return 0===t?1:1*Math.pow(2,10*(t/1-1))},easeOutExpo:function(t){return 1===t?1:1*(-Math.pow(2,-10*t/1)+1)},easeInOutExpo:function(t){return 0===t?0:1===t?1:(t/=.5)<1?.5*Math.pow(2,10*(t-1)):.5*(-Math.pow(2,-10*--t)+2)},easeInCirc:function(t){return t>=1?t:-1*(Math.sqrt(1-(t/=1)*t)-1)},easeOutCirc:function(t){return 1*Math.sqrt(1-(t=t/1-1)*t)},easeInOutCirc:function(t){return(t/=.5)<1?-0.5*(Math.sqrt(1-t*t)-1):.5*(Math.sqrt(1-(t-=2)*t)+1)},easeInElastic:function(t){var i=1.70158,e=0,s=1;return 0===t?0:1==(t/=1)?1:(e||(e=.3),s<Math.abs(1)?(s=1,i=e/4):i=e/(2*Math.PI)*Math.asin(1/s),-(s*Math.pow(2,10*(t-=1))*Math.sin(2*(1*t-i)*Math.PI/e)))},easeOutElastic:function(t){var i=1.70158,e=0,s=1;return 0===t?0:1==(t/=1)?1:(e||(e=.3),s<Math.abs(1)?(s=1,i=e/4):i=e/(2*Math.PI)*Math.asin(1/s),s*Math.pow(2,-10*t)*Math.sin(2*(1*t-i)*Math.PI/e)+1)},easeInOutElastic:function(t){var i=1.70158,e=0,s=1;return 0===t?0:2==(t/=.5)?1:(e||(e=.3*1.5),s<Math.abs(1)?(s=1,i=e/4):i=e/(2*Math.PI)*Math.asin(1/s),1>t?-.5*s*Math.pow(2,10*(t-=1))*Math.sin(2*(1*t-i)*Math.PI/e):s*Math.pow(2,-10*(t-=1))*Math.sin(2*(1*t-i)*Math.PI/e)*.5+1)},easeInBack:function(t){var i=1.70158;return 1*(t/=1)*t*((i+1)*t-i)},easeOutBack:function(t){var i=1.70158;return 1*((t=t/1-1)*t*((i+1)*t+i)+1)},easeInOutBack:function(t){var i=1.70158;return(t/=.5)<1?.5*t*t*(((i*=1.525)+1)*t-i):.5*((t-=2)*t*(((i*=1.525)+1)*t+i)+2)},easeInBounce:function(t){return 1-b.easeOutBounce(1-t)},easeOutBounce:function(t){return(t/=1)<1/2.75?7.5625*t*t:2/2.75>t?1*(7.5625*(t-=1.5/2.75)*t+.75):2.5/2.75>t?1*(7.5625*(t-=2.25/2.75)*t+.9375):1*(7.5625*(t-=2.625/2.75)*t+.984375)},easeInOutBounce:function(t){return.5>t?.5*b.easeInBounce(2*t):.5*b.easeOutBounce(2*t-1)+.5}}),w=s.requestAnimFrame=function(){return window.requestAnimationFrame||window.webkitRequestAnimationFrame||window.mozRequestAnimationFrame||window.oRequestAnimationFrame||window.msRequestAnimationFrame||function(t){return window.setTimeout(t,1e3/60)}}(),P=(s.cancelAnimFrame=function(){return window.cancelAnimationFrame||window.webkitCancelAnimationFrame||window.mozCancelAnimationFrame||window.oCancelAnimationFrame||window.msCancelAnimationFrame||function(t){return window.clearTimeout(t,1e3/60)}}(),s.animationLoop=function(t,i,e,s,n,o){var a=0,h=b[e]||b.linear,l=function(){a++;var e=a/i,r=h(e);t.call(o,r,e,a),s.call(o,r,e),i>a?o.animationFrame=w(l):n.apply(o)};w(l)},s.getRelativePosition=function(t){var i,e,s=t.originalEvent||t,n=t.currentTarget||t.srcElement,o=n.getBoundingClientRect();return s.touches?(i=s.touches[0].clientX-o.left,e=s.touches[0].clientY-o.top):(i=s.clientX-o.left,e=s.clientY-o.top),{x:i,y:e}},s.addEvent=function(t,i,e){t.addEventListener?t.addEventListener(i,e):t.attachEvent?t.attachEvent("on"+i,e):t["on"+i]=e}),L=s.removeEvent=function(t,i,e){t.removeEventListener?t.removeEventListener(i,e,!1):t.detachEvent?t.detachEvent("on"+i,e):t["on"+i]=c},k=(s.bindEvents=function(t,i,e){t.events||(t.events={}),n(i,function(i){t.events[i]=function(){e.apply(t,arguments)},P(t.chart.canvas,i,t.events[i])})},s.unbindEvents=function(t,i){n(i,function(i,e){L(t.chart.canvas,e,i)})}),F=s.getMaximumSize=function(t){var i=t.parentNode;return i.clientWidth},R=s.retinaScale=function(t){var i=t.ctx,e=t.canvas.width,s=t.canvas.height;window.devicePixelRatio&&(i.canvas.style.width=e+"px",i.canvas.style.height=s+"px",i.canvas.height=s*window.devicePixelRatio,i.canvas.width=e*window.devicePixelRatio,i.scale(window.devicePixelRatio,window.devicePixelRatio))},A=s.clear=function(t){t.ctx.clearRect(0,0,t.width,t.height)},T=s.fontString=function(t,i,e){return i+" "+t+"px "+e},M=s.longestText=function(t,i,e){t.font=i;var s=0;return n(e,function(i){var e=t.measureText(i).width;s=e>s?e:s}),s},W=s.drawRoundedRectangle=function(t,i,e,s,n,o){t.beginPath(),t.moveTo(i+o,e),t.lineTo(i+s-o,e),t.quadraticCurveTo(i+s,e,i+s,e+o),t.lineTo(i+s,e+n-o),t.quadraticCurveTo(i+s,e+n,i+s-o,e+n),t.lineTo(i+o,e+n),t.quadraticCurveTo(i,e+n,i,e+n-o),t.lineTo(i,e+o),t.quadraticCurveTo(i,e,i+o,e),t.closePath()};e.instances={},e.Type=function(t,i,s){this.options=i,this.chart=s,this.id=u(),e.instances[this.id]=this,i.responsive&&this.resize(),this.initialize.call(this,t)},a(e.Type.prototype,{initialize:function(){return this},clear:function(){return A(this.chart),this},stop:function(){return s.cancelAnimFrame.call(t,this.animationFrame),this},resize:function(t){this.stop();var i=this.chart.canvas,e=F(this.chart.canvas),s=e/this.chart.aspectRatio;return i.width=this.chart.width=e,i.height=this.chart.height=s,R(this.chart),"function"==typeof t&&t.apply(this,Array.prototype.slice.call(arguments,1)),this},reflow:c,render:function(t){return t&&this.reflow(),this.options.animation&&!t?s.animationLoop(this.draw,this.options.animationSteps,this.options.animationEasing,this.options.onAnimationProgress,this.options.onAnimationComplete,this):(this.draw(),this.options.onAnimationComplete.call(this)),this},generateLegend:function(){return y(this.options.legendTemplate,this)},destroy:function(){this.clear(),k(this,this.events),delete e.instances[this.id]},showTooltip:function(t,i){"undefined"==typeof this.activeElements&&(this.activeElements=[]);var o=function(t){var i=!1;return t.length!==this.activeElements.length?i=!0:(n(t,function(t,e){t!==this.activeElements[e]&&(i=!0)},this),i)}.call(this,t);if(o||i){if(this.activeElements=t,this.draw(),t.length>0)if(this.datasets&&this.datasets.length>1){for(var a,h,r=this.datasets.length-1;r>=0&&(a=this.datasets[r].points||this.datasets[r].bars||this.datasets[r].segments,h=l(a,t[0]),-1===h);r--);var c=[],u=[],d=function(){var t,i,e,n,o,a=[],l=[],r=[];return s.each(this.datasets,function(i){t=i.points||i.bars||i.segments,a.push(t[h])}),s.each(a,function(t){l.push(t.x),r.push(t.y),c.push(s.template(this.options.multiTooltipTemplate,t)),u.push({fill:t._saved.fillColor||t.fillColor,stroke:t._saved.strokeColor||t.strokeColor})},this),o=m(r),e=g(r),n=m(l),i=g(l),{x:n>this.chart.width/2?n:i,y:(o+e)/2}}.call(this,h);new e.MultiTooltip({x:d.x,y:d.y,xPadding:this.options.tooltipXPadding,yPadding:this.options.tooltipYPadding,xOffset:this.options.tooltipXOffset,fillColor:this.options.tooltipFillColor,textColor:this.options.tooltipFontColor,fontFamily:this.options.tooltipFontFamily,fontStyle:this.options.tooltipFontStyle,fontSize:this.options.tooltipFontSize,titleTextColor:this.options.tooltipTitleFontColor,titleFontFamily:this.options.tooltipTitleFontFamily,titleFontStyle:this.options.tooltipTitleFontStyle,titleFontSize:this.options.tooltipTitleFontSize,cornerRadius:this.options.tooltipCornerRadius,labels:c,legendColors:u,legendColorBackground:this.options.multiTooltipKeyBackground,title:t[0].label,chart:this.chart,ctx:this.chart.ctx}).draw()}else n(t,function(t){var i=t.tooltipPosition();new e.Tooltip({x:Math.round(i.x),y:Math.round(i.y),xPadding:this.options.tooltipXPadding,yPadding:this.options.tooltipYPadding,fillColor:this.options.tooltipFillColor,textColor:this.options.tooltipFontColor,fontFamily:this.options.tooltipFontFamily,fontStyle:this.options.tooltipFontStyle,fontSize:this.options.tooltipFontSize,caretHeight:this.options.tooltipCaretSize,cornerRadius:this.options.tooltipCornerRadius,text:y(this.options.tooltipTemplate,t),chart:this.chart}).draw()},this);return this}},toBase64Image:function(){return this.chart.canvas.toDataURL.apply(this.chart.canvas,arguments)}}),e.Type.extend=function(t){var i=this,s=function(){return i.apply(this,arguments)};if(s.prototype=o(i.prototype),a(s.prototype,t),s.extend=e.Type.extend,t.name||i.prototype.name){var n=t.name||i.prototype.name,l=e.defaults[i.prototype.name]?o(e.defaults[i.prototype.name]):{};e.defaults[n]=a(l,t.defaults),e.types[n]=s,e.prototype[n]=function(t,i){var o=h(e.defaults.global,e.defaults[n],i||{});return new s(t,o,this)}}else d("Name not provided for this chart, so it hasn't been registered");return i},e.Element=function(t){a(this,t),this.initialize.apply(this,arguments),this.save()},a(e.Element.prototype,{initialize:function(){},restore:function(t){return t?n(t,function(t){this[t]=this._saved[t]},this):a(this,this._saved),this},save:function(){return this._saved=o(this),delete this._saved._saved,this},update:function(t){return n(t,function(t,i){this._saved[i]=this[i],this[i]=t},this),this},transition:function(t,i){return n(t,function(t,e){this[e]=(t-this._saved[e])*i+this._saved[e]},this),this},tooltipPosition:function(){return{x:this.x,y:this.y}}}),e.Element.extend=r,e.Point=e.Element.extend({display:!0,inRange:function(t,i){var e=this.hitDetectionRadius+this.radius;return Math.pow(t-this.x,2)+Math.pow(i-this.y,2)<Math.pow(e,2)},draw:function(){if(this.display){var t=this.ctx;t.beginPath(),t.arc(this.x,this.y,this.radius,0,2*Math.PI),t.closePath(),t.strokeStyle=this.strokeColor,t.lineWidth=this.strokeWidth,t.fillStyle=this.fillColor,t.fill(),t.stroke()}}}),e.Arc=e.Element.extend({inRange:function(t,i){var e=s.getAngleFromPoint(this,{x:t,y:i}),n=e.angle>=this.startAngle&&e.angle<=this.endAngle,o=e.distance>=this.innerRadius&&e.distance<=this.outerRadius;return n&&o},tooltipPosition:function(){var t=this.startAngle+(this.endAngle-this.startAngle)/2,i=(this.outerRadius-this.innerRadius)/2+this.innerRadius;return{x:this.x+Math.cos(t)*i,y:this.y+Math.sin(t)*i}},draw:function(t){var i=this.ctx;i.beginPath(),i.arc(this.x,this.y,this.outerRadius,this.startAngle,this.endAngle),i.arc(this.x,this.y,this.innerRadius,this.endAngle,this.startAngle,!0),i.closePath(),i.strokeStyle=this.strokeColor,i.lineWidth=this.strokeWidth,i.fillStyle=this.fillColor,i.fill(),i.lineJoin="bevel",this.showStroke&&i.stroke()}}),e.Rectangle=e.Element.extend({draw:function(){var t=this.ctx,i=this.width/2,e=this.x-i,s=this.x+i,n=this.base-(this.base-this.y),o=this.strokeWidth/2;this.showStroke&&(e+=o,s-=o,n+=o),t.beginPath(),t.fillStyle=this.fillColor,t.strokeStyle=this.strokeColor,t.lineWidth=this.strokeWidth,t.moveTo(e,this.base),t.lineTo(e,n),t.lineTo(s,n),t.lineTo(s,this.base),t.fill(),this.showStroke&&t.stroke()},height:function(){return this.base-this.y},inRange:function(t,i){return t>=this.x-this.width/2&&t<=this.x+this.width/2&&i>=this.y&&i<=this.base}}),e.Tooltip=e.Element.extend({draw:function(){var t=this.chart.ctx;t.font=T(this.fontSize,this.fontStyle,this.fontFamily),this.xAlign="center",this.yAlign="above";var i=2,e=t.measureText(this.text).width+2*this.xPadding,s=this.fontSize+2*this.yPadding,n=s+this.caretHeight+i;this.x+e/2>this.chart.width?this.xAlign="left":this.x-e/2<0&&(this.xAlign="right"),this.y-n<0&&(this.yAlign="below");var o=this.x-e/2,a=this.y-n;switch(t.fillStyle=this.fillColor,this.yAlign){case"above":t.beginPath(),t.moveTo(this.x,this.y-i),t.lineTo(this.x+this.caretHeight,this.y-(i+this.caretHeight)),t.lineTo(this.x-this.caretHeight,this.y-(i+this.caretHeight)),t.closePath(),t.fill();break;case"below":a=this.y+i+this.caretHeight,t.beginPath(),t.moveTo(this.x,this.y+i),t.lineTo(this.x+this.caretHeight,this.y+i+this.caretHeight),t.lineTo(this.x-this.caretHeight,this.y+i+this.caretHeight),t.closePath(),t.fill()}switch(this.xAlign){case"left":o=this.x-e+(this.cornerRadius+this.caretHeight);break;case"right":o=this.x-(this.cornerRadius+this.caretHeight)}W(t,o,a,e,s,this.cornerRadius),t.fill(),t.fillStyle=this.textColor,t.textAlign="center",t.textBaseline="middle",t.fillText(this.text,o+e/2,a+s/2)}}),e.MultiTooltip=e.Element.extend({initialize:function(){this.font=T(this.fontSize,this.fontStyle,this.fontFamily),this.titleFont=T(this.titleFontSize,this.titleFontStyle,this.titleFontFamily),this.height=this.labels.length*this.fontSize+(this.labels.length-1)*(this.fontSize/2)+2*this.yPadding+1.5*this.titleFontSize,this.ctx.font=this.titleFont;var t=this.ctx.measureText(this.title).width,i=M(this.ctx,this.font,this.labels)+this.fontSize+3,e=g([i,t]);this.width=e+2*this.xPadding;var s=this.height/2;this.y-s<0?this.y=s:this.y+s>this.chart.height&&(this.y=this.chart.height-s),this.x>this.chart.width/2?this.x-=this.xOffset+this.width:this.x+=this.xOffset},getLineHeight:function(t){var i=this.y-this.height/2+this.yPadding,e=t-1;return 0===t?i+this.titleFontSize/2:i+(1.5*this.fontSize*e+this.fontSize/2)+1.5*this.titleFontSize},draw:function(){W(this.ctx,this.x,this.y-this.height/2,this.width,this.height,this.cornerRadius);var t=this.ctx;t.fillStyle=this.fillColor,t.fill(),t.closePath(),t.textAlign="left",t.textBaseline="middle",t.fillStyle=this.titleTextColor,t.font=this.titleFont,t.fillText(this.title,this.x+this.xPadding,this.getLineHeight(0)),t.font=this.font,s.each(this.labels,function(i,e){t.fillStyle=this.textColor,t.fillText(i,this.x+this.xPadding+this.fontSize+3,this.getLineHeight(e+1)),t.fillStyle=this.legendColorBackground,t.fillRect(this.x+this.xPadding,this.getLineHeight(e+1)-this.fontSize/2,this.fontSize,this.fontSize),t.fillStyle=this.legendColors[e].fill,t.fillRect(this.x+this.xPadding,this.getLineHeight(e+1)-this.fontSize/2,this.fontSize,this.fontSize)},this)}}),e.Scale=e.Element.extend({initialize:function(){this.fit()},buildYLabels:function(){this.yLabels=[];for(var t=v(this.stepValue),i=0;i<=this.steps;i++)this.yLabels.push(y(this.templateString,{value:(this.min+i*this.stepValue).toFixed(t)}));this.yLabelWidth=this.display&&this.showLabels?M(this.ctx,this.font,this.yLabels):0},addXLabel:function(t){this.xLabels.push(t),this.valuesCount++,this.fit()},removeXLabel:function(){this.xLabels.shift(),this.valuesCount--,this.fit()},fit:function(){this.startPoint=this.display?this.fontSize:0,this.endPoint=this.display?this.height-1.5*this.fontSize-5:this.height,this.startPoint+=this.padding,this.endPoint-=this.padding;var t,i=this.endPoint-this.startPoint;for(this.calculateYRange(i),this.buildYLabels(),this.calculateXLabelRotation();i>this.endPoint-this.startPoint;)i=this.endPoint-this.startPoint,t=this.yLabelWidth,this.calculateYRange(i),this.buildYLabels(),t<this.yLabelWidth&&this.calculateXLabelRotation()},calculateXLabelRotation:function(){this.ctx.font=this.font;var t,i,e=this.ctx.measureText(this.xLabels[0]).width,s=this.ctx.measureText(this.xLabels[this.xLabels.length-1]).width;if(this.xScalePaddingRight=s/2+3,this.xScalePaddingLeft=e/2>this.yLabelWidth+10?e/2:this.yLabelWidth+10,this.xLabelRotation=0,this.display){var n,o=M(this.ctx,this.font,this.xLabels);this.xLabelWidth=o;for(var a=Math.floor(this.calculateX(1)-this.calculateX(0))-6;this.xLabelWidth>a&&0===this.xLabelRotation||this.xLabelWidth>a&&this.xLabelRotation<=90&&this.xLabelRotation>0;)n=Math.cos(S(this.xLabelRotation)),t=n*e,i=n*s,t+this.fontSize/2>this.yLabelWidth+8&&(this.xScalePaddingLeft=t+this.fontSize/2),this.xScalePaddingRight=this.fontSize/2,this.xLabelRotation++,this.xLabelWidth=n*o;this.xLabelRotation>0&&(this.endPoint-=Math.sin(S(this.xLabelRotation))*o+3)}else this.xLabelWidth=0,this.xScalePaddingRight=this.padding,this.xScalePaddingLeft=this.padding},calculateYRange:c,drawingArea:function(){return this.startPoint-this.endPoint},calculateY:function(t){var i=this.drawingArea()/(this.min-this.max);return this.endPoint-i*(t-this.min)},calculateX:function(t){var i=(this.xLabelRotation>0,this.width-(this.xScalePaddingLeft+this.xScalePaddingRight)),e=i/(this.valuesCount-(this.offsetGridLines?0:1)),s=e*t+this.xScalePaddingLeft;return this.offsetGridLines&&(s+=e/2),Math.round(s)},update:function(t){s.extend(this,t),this.fit()},draw:function(){var t=this.ctx,i=(this.endPoint-this.startPoint)/this.steps,e=Math.round(this.xScalePaddingLeft);this.display&&(t.fillStyle=this.textColor,t.font=this.font,n(this.yLabels,function(n,o){var a=this.endPoint-i*o,h=Math.round(a);t.textAlign="right",t.textBaseline="middle",this.showLabels&&t.fillText(n,e-10,a),t.beginPath(),o>0?(t.lineWidth=this.gridLineWidth,t.strokeStyle=this.gridLineColor):(t.lineWidth=this.lineWidth,t.strokeStyle=this.lineColor),h+=s.aliasPixel(t.lineWidth),t.moveTo(e,h),t.lineTo(this.width,h),t.stroke(),t.closePath(),t.lineWidth=this.lineWidth,t.strokeStyle=this.lineColor,t.beginPath(),t.moveTo(e-5,h),t.lineTo(e,h),t.stroke(),t.closePath()},this),n(this.xLabels,function(i,e){var s=this.calculateX(e)+x(this.lineWidth),n=this.calculateX(e-(this.offsetGridLines?.5:0))+x(this.lineWidth),o=this.xLabelRotation>0;t.beginPath(),e>0?(t.lineWidth=this.gridLineWidth,t.strokeStyle=this.gridLineColor):(t.lineWidth=this.lineWidth,t.strokeStyle=this.lineColor),t.moveTo(n,this.endPoint),t.lineTo(n,this.startPoint-3),t.stroke(),t.closePath(),t.lineWidth=this.lineWidth,t.strokeStyle=this.lineColor,t.beginPath(),t.moveTo(n,this.endPoint),t.lineTo(n,this.endPoint+5),t.stroke(),t.closePath(),t.save(),t.translate(s,o?this.endPoint+12:this.endPoint+8),t.rotate(-1*S(this.xLabelRotation)),t.font=this.font,t.textAlign=o?"right":"center",t.textBaseline=o?"middle":"top",t.fillText(i,0,0),t.restore()},this))}}),e.RadialScale=e.Element.extend({initialize:function(){this.size=m([this.height,this.width]),this.drawingArea=this.display?this.size/2-(this.fontSize/2+this.backdropPaddingY):this.size/2},calculateCenterOffset:function(t){var i=this.drawingArea/(this.max-this.min);return(t-this.min)*i},update:function(){this.lineArc?this.drawingArea=this.display?this.size/2-(this.fontSize/2+this.backdropPaddingY):this.size/2:this.setScaleSize(),this.buildYLabels()},buildYLabels:function(){this.yLabels=[];for(var t=v(this.stepValue),i=0;i<=this.steps;i++)this.yLabels.push(y(this.templateString,{value:(this.min+i*this.stepValue).toFixed(t)}))},getCircumference:function(){return 2*Math.PI/this.valuesCount},setScaleSize:function(){var t,i,e,s,n,o,a,h,l,r,c,u,d=m([this.height/2-this.pointLabelFontSize-5,this.width/2]),p=this.width,g=0;for(this.ctx.font=T(this.pointLabelFontSize,this.pointLabelFontStyle,this.pointLabelFontFamily),i=0;i<this.valuesCount;i++)t=this.getPointPosition(i,d),e=this.ctx.measureText(y(this.templateString,{value:this.labels[i]})).width+5,0===i||i===this.valuesCount/2?(s=e/2,t.x+s>p&&(p=t.x+s,n=i),t.x-s<g&&(g=t.x-s,a=i)):i<this.valuesCount/2?t.x+e>p&&(p=t.x+e,n=i):i>this.valuesCount/2&&t.x-e<g&&(g=t.x-e,a=i);l=g,r=Math.ceil(p-this.width),o=this.getIndexAngle(n),h=this.getIndexAngle(a),c=r/Math.sin(o+Math.PI/2),u=l/Math.sin(h+Math.PI/2),c=f(c)?c:0,u=f(u)?u:0,this.drawingArea=d-(u+c)/2,this.setCenterPoint(u,c)},setCenterPoint:function(t,i){var e=this.width-i-this.drawingArea,s=t+this.drawingArea;this.xCenter=(s+e)/2,this.yCenter=this.height/2},getIndexAngle:function(t){var i=2*Math.PI/this.valuesCount;return t*i-Math.PI/2},getPointPosition:function(t,i){var e=this.getIndexAngle(t);return{x:Math.cos(e)*i+this.xCenter,y:Math.sin(e)*i+this.yCenter}},draw:function(){if(this.display){var t=this.ctx;if(n(this.yLabels,function(i,e){if(e>0){var s,n=e*(this.drawingArea/this.steps),o=this.yCenter-n;if(this.lineWidth>0)if(t.strokeStyle=this.lineColor,t.lineWidth=this.lineWidth,this.lineArc)t.beginPath(),t.arc(this.xCenter,this.yCenter,n,0,2*Math.PI),t.closePath(),t.stroke();else{t.beginPath();for(var a=0;a<this.valuesCount;a++)s=this.getPointPosition(a,this.calculateCenterOffset(this.min+e*this.stepValue)),0===a?t.moveTo(s.x,s.y):t.lineTo(s.x,s.y);t.closePath(),t.stroke()}if(this.showLabels){if(t.font=T(this.fontSize,this.fontStyle,this.fontFamily),this.showLabelBackdrop){var h=t.measureText(i).width;t.fillStyle=this.backdropColor,t.fillRect(this.xCenter-h/2-this.backdropPaddingX,o-this.fontSize/2-this.backdropPaddingY,h+2*this.backdropPaddingX,this.fontSize+2*this.backdropPaddingY)}t.textAlign="center",t.textBaseline="middle",t.fillStyle=this.fontColor,t.fillText(i,this.xCenter,o)}}},this),!this.lineArc){t.lineWidth=this.angleLineWidth,t.strokeStyle=this.angleLineColor;for(var i=this.valuesCount-1;i>=0;i--){if(this.angleLineWidth>0){var e=this.getPointPosition(i,this.calculateCenterOffset(this.max));t.beginPath(),t.moveTo(this.xCenter,this.yCenter),t.lineTo(e.x,e.y),t.stroke(),t.closePath()}var s=this.getPointPosition(i,this.calculateCenterOffset(this.max)+5);t.font=T(this.pointLabelFontSize,this.pointLabelFontStyle,this.pointLabelFontFamily),t.fillStyle=this.pointLabelFontColor;var o=this.labels.length,a=this.labels.length/2,h=a/2,l=h>i||i>o-h,r=i===h||i===o-h;t.textAlign=0===i?"center":i===a?"center":a>i?"left":"right",t.textBaseline=r?"middle":l?"bottom":"top",t.fillText(this.labels[i],s.x,s.y)}}}}}),s.addEvent(window,"resize",function(){var t;return function(){clearTimeout(t),t=setTimeout(function(){n(e.instances,function(t){t.options.responsive&&t.resize(t.render,!0)})},50)}}()),p?define(function(){return e}):"object"==typeof module&&module.exports&&(module.exports=e),t.Chart=e,e.noConflict=function(){return t.Chart=i,e}}).call(this),function(){"use strict";var t=this,i=t.Chart,e=i.helpers,s={scaleBeginAtZero:!0,scaleShowGridLines:!0,scaleGridLineColor:"rgba(0,0,0,.05)",scaleGridLineWidth:1,barShowStroke:!0,barStrokeWidth:2,barValueSpacing:5,barDatasetSpacing:1,legendTemplate:'<ul class="<%=name.toLowerCase()%>-legend"><% for (var i=0; i<datasets.length; i++){%><li><span style="background-color:<%=datasets[i].fillColor%>"></span><%if(datasets[i].label){%><%=datasets[i].label%><%}%></li><%}%></ul>'};i.Type.extend({name:"Bar",defaults:s,initialize:function(t){var s=this.options;this.ScaleClass=i.Scale.extend({offsetGridLines:!0,calculateBarX:function(t,i,e){var n=this.calculateBaseWidth(),o=this.calculateX(e)-n/2,a=this.calculateBarWidth(t);return o+a*i+i*s.barDatasetSpacing+a/2},calculateBaseWidth:function(){return this.calculateX(1)-this.calculateX(0)-2*s.barValueSpacing},calculateBarWidth:function(t){var i=this.calculateBaseWidth()-(t-1)*s.barDatasetSpacing;return i/t}}),this.datasets=[],this.options.showTooltips&&e.bindEvents(this,this.options.tooltipEvents,function(t){var i="mouseout"!==t.type?this.getBarsAtEvent(t):[];this.eachBars(function(t){t.restore(["fillColor","strokeColor"])}),e.each(i,function(t){t.fillColor=t.highlightFill,t.strokeColor=t.highlightStroke}),this.showTooltip(i)}),this.BarClass=i.Rectangle.extend({strokeWidth:this.options.barStrokeWidth,showStroke:this.options.barShowStroke,ctx:this.chart.ctx}),e.each(t.datasets,function(i){var s={label:i.label||null,fillColor:i.fillColor,strokeColor:i.strokeColor,bars:[]};this.datasets.push(s),e.each(i.data,function(n,o){e.isNumber(n)&&s.bars.push(new this.BarClass({value:n,label:t.labels[o],strokeColor:i.strokeColor,fillColor:i.fillColor,highlightFill:i.highlightFill||i.fillColor,highlightStroke:i.highlightStroke||i.strokeColor}))},this)},this),this.buildScale(t.labels),this.BarClass.prototype.base=this.scale.endPoint,this.eachBars(function(t,i,s){e.extend(t,{width:this.scale.calculateBarWidth(this.datasets.length),x:this.scale.calculateBarX(this.datasets.length,s,i),y:this.scale.endPoint}),t.save()},this),this.render()},update:function(){this.scale.update(),e.each(this.activeElements,function(t){t.restore(["fillColor","strokeColor"])}),this.eachBars(function(t){t.save()}),this.render()},eachBars:function(t){e.each(this.datasets,function(i,s){e.each(i.bars,t,this,s)},this)},getBarsAtEvent:function(t){for(var i,s=[],n=e.getRelativePosition(t),o=function(t){s.push(t.bars[i])},a=0;a<this.datasets.length;a++)for(i=0;i<this.datasets[a].bars.length;i++)if(this.datasets[a].bars[i].inRange(n.x,n.y))return e.each(this.datasets,o),s;return s},buildScale:function(t){var i=this,s=function(){var t=[];return i.eachBars(function(i){t.push(i.value)}),t},n={templateString:this.options.scaleLabel,height:this.chart.height,width:this.chart.width,ctx:this.chart.ctx,textColor:this.options.scaleFontColor,fontSize:this.options.scaleFontSize,fontStyle:this.options.scaleFontStyle,fontFamily:this.options.scaleFontFamily,valuesCount:t.length,beginAtZero:this.options.scaleBeginAtZero,integersOnly:this.options.scaleIntegersOnly,calculateYRange:function(t){var i=e.calculateScaleRange(s(),t,this.fontSize,this.beginAtZero,this.integersOnly);e.extend(this,i)},xLabels:t,font:e.fontString(this.options.scaleFontSize,this.options.scaleFontStyle,this.options.scaleFontFamily),lineWidth:this.options.scaleLineWidth,lineColor:this.options.scaleLineColor,gridLineWidth:this.options.scaleShowGridLines?this.options.scaleGridLineWidth:0,gridLineColor:this.options.scaleShowGridLines?this.options.scaleGridLineColor:"rgba(0,0,0,0)",padding:this.options.showScale?0:this.options.barShowStroke?this.options.barStrokeWidth:0,showLabels:this.options.scaleShowLabels,display:this.options.showScale};this.options.scaleOverride&&e.extend(n,{calculateYRange:e.noop,steps:this.options.scaleSteps,stepValue:this.options.scaleStepWidth,min:this.options.scaleStartValue,max:this.options.scaleStartValue+this.options.scaleSteps*this.options.scaleStepWidth}),this.scale=new this.ScaleClass(n)},addData:function(t,i){e.each(t,function(t,s){e.isNumber(t)&&this.datasets[s].bars.push(new this.BarClass({value:t,label:i,x:this.scale.calculateBarX(this.datasets.length,s,this.scale.valuesCount+1),y:this.scale.endPoint,width:this.scale.calculateBarWidth(this.datasets.length),base:this.scale.endPoint,strokeColor:this.datasets[s].strokeColor,fillColor:this.datasets[s].fillColor}))},this),this.scale.addXLabel(i),this.update()},removeData:function(){this.scale.removeXLabel(),e.each(this.datasets,function(t){t.bars.shift()},this),this.update()},reflow:function(){e.extend(this.BarClass.prototype,{y:this.scale.endPoint,base:this.scale.endPoint});var t=e.extend({height:this.chart.height,width:this.chart.width});this.scale.update(t)},draw:function(t){var i=t||1;this.clear();this.chart.ctx;this.scale.draw(i),e.each(this.datasets,function(t,s){e.each(t.bars,function(t,e){t.base=this.scale.endPoint,t.transition({x:this.scale.calculateBarX(this.datasets.length,s,e),y:this.scale.calculateY(t.value),width:this.scale.calculateBarWidth(this.datasets.length)},i).draw()},this)},this)}})}.call(this),function(){"use strict";var t=this,i=t.Chart,e=i.helpers,s={segmentShowStroke:!0,segmentStrokeColor:"#fff",segmentStrokeWidth:2,percentageInnerCutout:50,animationSteps:100,animationEasing:"easeOutBounce",animateRotate:!0,animateScale:!1,legendTemplate:'<ul class="<%=name.toLowerCase()%>-legend"><% for (var i=0; i<segments.length; i++){%><li><span style="background-color:<%=segments[i].fillColor%>"></span><%if(segments[i].label){%><%=segments[i].label%><%}%></li><%}%></ul>'};i.Type.extend({name:"Doughnut",defaults:s,initialize:function(t){this.segments=[],this.outerRadius=(e.min([this.chart.width,this.chart.height])-this.options.segmentStrokeWidth/2)/2,this.SegmentArc=i.Arc.extend({ctx:this.chart.ctx,x:this.chart.width/2,y:this.chart.height/2}),this.options.showTooltips&&e.bindEvents(this,this.options.tooltipEvents,function(t){var i="mouseout"!==t.type?this.getSegmentsAtEvent(t):[]; <del>e.each(this.segments,function(t){t.restore(["fillColor"])}),e.each(i,function(t){t.fillColor=t.highlightColor}),this.showTooltip(i)}),this.calculateTotal(t),e.each(t,function(t,i){this.addData(t,i,!0)},this),this.render()},getSegmentsAtEvent:function(t){var i=[],s=e.getRelativePosition(t);return e.each(this.segments,function(t){t.inRange(s.x,s.y)&&i.push(t)},this),i},addData:function(t,i,e){var s=i||this.segments.length;this.segments.splice(s,0,new this.SegmentArc({value:t.value,outerRadius:this.options.animateScale?0:this.outerRadius,innerRadius:this.options.animateScale?0:this.outerRadius/100*this.options.percentageInnerCutout,fillColor:t.color,highlightColor:t.highlight||t.color,showStroke:this.options.segmentShowStroke,strokeWidth:this.options.segmentStrokeWidth,strokeColor:this.options.segmentStrokeColor,startAngle:1.5*Math.PI,circumference:this.options.animateRotate?0:this.calculateCircumference(t.value),label:t.label})),e||(this.reflow(),this.update())},calculateCircumference:function(t){return 2*Math.PI*(t/this.total)},calculateTotal:function(t){this.total=0,e.each(t,function(t){this.total+=t.value},this)},update:function(){this.calculateTotal(this.segments),e.each(this.activeElements,function(t){t.restore(["fillColor"])}),e.each(this.segments,function(t){t.save()}),this.render()},removeData:function(t){var i=e.isNumber(t)?t:this.segments.length-1;this.segments.splice(i,1),this.reflow(),this.update()},reflow:function(){e.extend(this.SegmentArc.prototype,{x:this.chart.width/2,y:this.chart.height/2}),this.outerRadius=(e.min([this.chart.width,this.chart.height])-this.options.segmentStrokeWidth/2)/2,e.each(this.segments,function(t){t.update({outerRadius:this.outerRadius,innerRadius:this.outerRadius/100*this.options.percentageInnerCutout})},this)},draw:function(t){var i=t?t:1;this.clear(),e.each(this.segments,function(t,e){t.transition({circumference:this.calculateCircumference(t.value),outerRadius:this.outerRadius,innerRadius:this.outerRadius/100*this.options.percentageInnerCutout},i),t.endAngle=t.startAngle+t.circumference,t.draw(),0===e&&(t.startAngle=1.5*Math.PI),e<this.segments.length-1&&(this.segments[e+1].startAngle=t.endAngle)},this)}}),i.types.Doughnut.extend({name:"Pie",defaults:e.merge(s,{percentageInnerCutout:0})})}.call(this),function(){"use strict";var t=this,i=t.Chart,e=i.helpers,s={scaleShowGridLines:!0,scaleGridLineColor:"rgba(0,0,0,.05)",scaleGridLineWidth:1,bezierCurve:!0,bezierCurveTension:.4,pointDot:!0,pointDotRadius:4,pointDotStrokeWidth:1,pointHitDetectionRadius:20,datasetStroke:!0,datasetStrokeWidth:2,datasetFill:!0,legendTemplate:'<ul class="<%=name.toLowerCase()%>-legend"><% for (var i=0; i<datasets.length; i++){%><li><span style="background-color:<%=datasets[i].strokeColor%>"></span><%if(datasets[i].label){%><%=datasets[i].label%><%}%></li><%}%></ul>'};i.Type.extend({name:"Line",defaults:s,initialize:function(t){this.PointClass=i.Point.extend({strokeWidth:this.options.pointDotStrokeWidth,radius:this.options.pointDotRadius,display:this.options.pointDot,hitDetectionRadius:this.options.pointHitDetectionRadius,ctx:this.chart.ctx,inRange:function(t){return Math.pow(t-this.x,2)<Math.pow(this.radius+this.hitDetectionRadius,2)}}),this.datasets=[],this.options.showTooltips&&e.bindEvents(this,this.options.tooltipEvents,function(t){var i="mouseout"!==t.type?this.getPointsAtEvent(t):[];this.eachPoints(function(t){t.restore(["fillColor","strokeColor"])}),e.each(i,function(t){t.fillColor=t.highlightFill,t.strokeColor=t.highlightStroke}),this.showTooltip(i)}),e.each(t.datasets,function(i){var s={label:i.label||null,fillColor:i.fillColor,strokeColor:i.strokeColor,pointColor:i.pointColor,pointStrokeColor:i.pointStrokeColor,points:[]};this.datasets.push(s),e.each(i.data,function(n,o){e.isNumber(n)&&s.points.push(new this.PointClass({value:n,label:t.labels[o],strokeColor:i.pointStrokeColor,fillColor:i.pointColor,highlightFill:i.pointHighlightFill||i.pointColor,highlightStroke:i.pointHighlightStroke||i.pointStrokeColor}))},this),this.buildScale(t.labels),this.eachPoints(function(t,i){e.extend(t,{x:this.scale.calculateX(i),y:this.scale.endPoint}),t.save()},this)},this),this.render()},update:function(){this.scale.update(),e.each(this.activeElements,function(t){t.restore(["fillColor","strokeColor"])}),this.eachPoints(function(t){t.save()}),this.render()},eachPoints:function(t){e.each(this.datasets,function(i){e.each(i.points,t,this)},this)},getPointsAtEvent:function(t){var i=[],s=e.getRelativePosition(t);return e.each(this.datasets,function(t){e.each(t.points,function(t){t.inRange(s.x,s.y)&&i.push(t)})},this),i},buildScale:function(t){var s=this,n=function(){var t=[];return s.eachPoints(function(i){t.push(i.value)}),t},o={templateString:this.options.scaleLabel,height:this.chart.height,width:this.chart.width,ctx:this.chart.ctx,textColor:this.options.scaleFontColor,fontSize:this.options.scaleFontSize,fontStyle:this.options.scaleFontStyle,fontFamily:this.options.scaleFontFamily,valuesCount:t.length,beginAtZero:this.options.scaleBeginAtZero,integersOnly:this.options.scaleIntegersOnly,calculateYRange:function(t){var i=e.calculateScaleRange(n(),t,this.fontSize,this.beginAtZero,this.integersOnly);e.extend(this,i)},xLabels:t,font:e.fontString(this.options.scaleFontSize,this.options.scaleFontStyle,this.options.scaleFontFamily),lineWidth:this.options.scaleLineWidth,lineColor:this.options.scaleLineColor,gridLineWidth:this.options.scaleShowGridLines?this.options.scaleGridLineWidth:0,gridLineColor:this.options.scaleShowGridLines?this.options.scaleGridLineColor:"rgba(0,0,0,0)",padding:this.options.showScale?0:this.options.pointDotRadius+this.options.pointDotStrokeWidth,showLabels:this.options.scaleShowLabels,display:this.options.showScale};this.options.scaleOverride&&e.extend(o,{calculateYRange:e.noop,steps:this.options.scaleSteps,stepValue:this.options.scaleStepWidth,min:this.options.scaleStartValue,max:this.options.scaleStartValue+this.options.scaleSteps*this.options.scaleStepWidth}),this.scale=new i.Scale(o)},addData:function(t,i){e.each(t,function(t,s){e.isNumber(t)&&this.datasets[s].points.push(new this.PointClass({value:t,label:i,x:this.scale.calculateX(this.scale.valuesCount+1),y:this.scale.endPoint,strokeColor:this.datasets[s].pointStrokeColor,fillColor:this.datasets[s].pointColor}))},this),this.scale.addXLabel(i),this.update()},removeData:function(){this.scale.removeXLabel(),e.each(this.datasets,function(t){t.points.shift()},this),this.update()},reflow:function(){var t=e.extend({height:this.chart.height,width:this.chart.width});this.scale.update(t)},draw:function(t){var i=t||1;this.clear();var s=this.chart.ctx;this.scale.draw(i),e.each(this.datasets,function(t){e.each(t.points,function(t,e){t.transition({y:this.scale.calculateY(t.value),x:this.scale.calculateX(e)},i)},this),this.options.bezierCurve&&e.each(t.points,function(i,s){i.controlPoints=0===s?e.splineCurve(i,i,t.points[s+1],0):s>=t.points.length-1?e.splineCurve(t.points[s-1],i,i,0):e.splineCurve(t.points[s-1],i,t.points[s+1],this.options.bezierCurveTension)},this),s.lineWidth=this.options.datasetStrokeWidth,s.strokeStyle=t.strokeColor,s.beginPath(),e.each(t.points,function(i,e){e>0?this.options.bezierCurve?s.bezierCurveTo(t.points[e-1].controlPoints.outer.x,t.points[e-1].controlPoints.outer.y,i.controlPoints.inner.x,i.controlPoints.inner.y,i.x,i.y):s.lineTo(i.x,i.y):s.moveTo(i.x,i.y)},this),s.stroke(),this.options.datasetFill&&(s.lineTo(t.points[t.points.length-1].x,this.scale.endPoint),s.lineTo(this.scale.calculateX(0),this.scale.endPoint),s.fillStyle=t.fillColor,s.closePath(),s.fill()),e.each(t.points,function(t){t.draw()})},this)}})}.call(this),function(){"use strict";var t=this,i=t.Chart,e=i.helpers,s={scaleShowLabelBackdrop:!0,scaleBackdropColor:"rgba(255,255,255,0.75)",scaleBeginAtZero:!0,scaleBackdropPaddingY:2,scaleBackdropPaddingX:2,scaleShowLine:!0,segmentShowStroke:!0,segmentStrokeColor:"#fff",segmentStrokeWidth:2,animationSteps:100,animationEasing:"easeOutBounce",animateRotate:!0,animateScale:!1,legendTemplate:'<ul class="<%=name.toLowerCase()%>-legend"><% for (var i=0; i<segments.length; i++){%><li><span style="background-color:<%=segments[i].fillColor%>"></span><%if(segments[i].label){%><%=segments[i].label%><%}%></li><%}%></ul>'};i.Type.extend({name:"PolarArea",defaults:s,initialize:function(t){this.segments=[],this.SegmentArc=i.Arc.extend({showStroke:this.options.segmentShowStroke,strokeWidth:this.options.segmentStrokeWidth,strokeColor:this.options.segmentStrokeColor,ctx:this.chart.ctx,innerRadius:0,x:this.chart.width/2,y:this.chart.height/2}),this.scale=new i.RadialScale({display:this.options.showScale,fontStyle:this.options.scaleFontStyle,fontSize:this.options.scaleFontSize,fontFamily:this.options.scaleFontFamily,fontColor:this.options.scaleFontColor,showLabels:this.options.scaleShowLabels,showLabelBackdrop:this.options.scaleShowLabelBackdrop,backdropColor:this.options.scaleBackdropColor,backdropPaddingY:this.options.scaleBackdropPaddingY,backdropPaddingX:this.options.scaleBackdropPaddingX,lineWidth:this.options.scaleShowLine?this.options.scaleLineWidth:0,lineColor:this.options.scaleLineColor,lineArc:!0,width:this.chart.width,height:this.chart.height,xCenter:this.chart.width/2,yCenter:this.chart.height/2,ctx:this.chart.ctx,templateString:this.options.scaleLabel,valuesCount:t.length}),this.updateScaleRange(t),this.scale.update(),e.each(t,function(t,i){this.addData(t,i,!0)},this),this.options.showTooltips&&e.bindEvents(this,this.options.tooltipEvents,function(t){var i="mouseout"!==t.type?this.getSegmentsAtEvent(t):[];e.each(this.segments,function(t){t.restore(["fillColor"])}),e.each(i,function(t){t.fillColor=t.highlightColor}),this.showTooltip(i)}),this.render()},getSegmentsAtEvent:function(t){var i=[],s=e.getRelativePosition(t);return e.each(this.segments,function(t){t.inRange(s.x,s.y)&&i.push(t)},this),i},addData:function(t,i,e){var s=i||this.segments.length;this.segments.splice(s,0,new this.SegmentArc({fillColor:t.color,highlightColor:t.highlight||t.color,label:t.label,value:t.value,outerRadius:this.options.animateScale?0:this.scale.calculateCenterOffset(t.value),circumference:this.options.animateRotate?0:this.scale.getCircumference(),startAngle:1.5*Math.PI})),e||(this.reflow(),this.update())},removeData:function(t){var i=e.isNumber(t)?t:this.segments.length-1;this.segments.splice(i,1),this.reflow(),this.update()},calculateTotal:function(t){this.total=0,e.each(t,function(t){this.total+=t.value},this),this.scale.valuesCount=this.segments.length},updateScaleRange:function(t){var i=[];e.each(t,function(t){i.push(t.value)});var s=this.options.scaleOverride?{steps:this.options.scaleSteps,stepValue:this.options.scaleStepWidth,min:this.options.scaleStartValue,max:this.options.scaleStartValue+this.options.scaleSteps*this.options.scaleStepWidth}:e.calculateScaleRange(i,e.min([this.chart.width,this.chart.height])/2,this.options.scaleFontSize,this.options.scaleBeginAtZero,this.options.scaleIntegersOnly);e.extend(this.scale,s,{size:e.min([this.chart.width,this.chart.height]),xCenter:this.chart.width/2,yCenter:this.chart.height/2})},update:function(){this.calculateTotal(this.segments),e.each(this.segments,function(t){t.save()}),this.render()},reflow:function(){e.extend(this.SegmentArc.prototype,{x:this.chart.width/2,y:this.chart.height/2}),this.updateScaleRange(this.segments),this.scale.update(),e.extend(this.scale,{xCenter:this.chart.width/2,yCenter:this.chart.height/2}),e.each(this.segments,function(t){t.update({outerRadius:this.scale.calculateCenterOffset(t.value)})},this)},draw:function(t){var i=t||1;this.clear(),e.each(this.segments,function(t,e){t.transition({circumference:this.scale.getCircumference(),outerRadius:this.scale.calculateCenterOffset(t.value)},i),t.endAngle=t.startAngle+t.circumference,0===e&&(t.startAngle=1.5*Math.PI),e<this.segments.length-1&&(this.segments[e+1].startAngle=t.endAngle),t.draw()},this),this.scale.draw()}})}.call(this),function(){"use strict";var t=this,i=t.Chart,e=i.helpers;i.Type.extend({name:"Radar",defaults:{scaleShowLine:!0,angleShowLineOut:!0,scaleShowLabels:!1,scaleBeginAtZero:!0,angleLineColor:"rgba(0,0,0,.1)",angleLineWidth:1,pointLabelFontFamily:"'Arial'",pointLabelFontStyle:"normal",pointLabelFontSize:10,pointLabelFontColor:"#666",pointDot:!0,pointDotRadius:3,pointDotStrokeWidth:1,pointHitDetectionRadius:20,datasetStroke:!0,datasetStrokeWidth:2,datasetFill:!0,legendTemplate:'<ul class="<%=name.toLowerCase()%>-legend"><% for (var i=0; i<datasets.length; i++){%><li><span style="background-color:<%=datasets[i].strokeColor%>"></span><%if(datasets[i].label){%><%=datasets[i].label%><%}%></li><%}%></ul>'},initialize:function(t){this.PointClass=i.Point.extend({strokeWidth:this.options.pointDotStrokeWidth,radius:this.options.pointDotRadius,display:this.options.pointDot,hitDetectionRadius:this.options.pointHitDetectionRadius,ctx:this.chart.ctx}),this.datasets=[],this.buildScale(t),this.options.showTooltips&&e.bindEvents(this,this.options.tooltipEvents,function(t){var i="mouseout"!==t.type?this.getPointsAtEvent(t):[];this.eachPoints(function(t){t.restore(["fillColor","strokeColor"])}),e.each(i,function(t){t.fillColor=t.highlightFill,t.strokeColor=t.highlightStroke}),this.showTooltip(i)}),e.each(t.datasets,function(i){var s={label:i.label||null,fillColor:i.fillColor,strokeColor:i.strokeColor,pointColor:i.pointColor,pointStrokeColor:i.pointStrokeColor,points:[]};this.datasets.push(s),e.each(i.data,function(n,o){if(e.isNumber(n)){var a;this.scale.animation||(a=this.scale.getPointPosition(o,this.scale.calculateCenterOffset(n))),s.points.push(new this.PointClass({value:n,label:t.labels[o],x:this.options.animation?this.scale.xCenter:a.x,y:this.options.animation?this.scale.yCenter:a.y,strokeColor:i.pointStrokeColor,fillColor:i.pointColor,highlightFill:i.pointHighlightFill||i.pointColor,highlightStroke:i.pointHighlightStroke||i.pointStrokeColor}))}},this)},this),this.render()},eachPoints:function(t){e.each(this.datasets,function(i){e.each(i.points,t,this)},this)},getPointsAtEvent:function(t){var i=e.getRelativePosition(t),s=e.getAngleFromPoint({x:this.scale.xCenter,y:this.scale.yCenter},i),n=2*Math.PI/this.scale.valuesCount,o=Math.round((s.angle-1.5*Math.PI)/n),a=[];return(o>=this.scale.valuesCount||0>o)&&(o=0),s.distance<=this.scale.drawingArea&&e.each(this.datasets,function(t){a.push(t.points[o])}),a},buildScale:function(t){this.scale=new i.RadialScale({display:this.options.showScale,fontStyle:this.options.scaleFontStyle,fontSize:this.options.scaleFontSize,fontFamily:this.options.scaleFontFamily,fontColor:this.options.scaleFontColor,showLabels:this.options.scaleShowLabels,showLabelBackdrop:this.options.scaleShowLabelBackdrop,backdropColor:this.options.scaleBackdropColor,backdropPaddingY:this.options.scaleBackdropPaddingY,backdropPaddingX:this.options.scaleBackdropPaddingX,lineWidth:this.options.scaleShowLine?this.options.scaleLineWidth:0,lineColor:this.options.scaleLineColor,angleLineColor:this.options.angleLineColor,angleLineWidth:this.options.angleShowLineOut?this.options.angleLineWidth:0,pointLabelFontColor:this.options.pointLabelFontColor,pointLabelFontSize:this.options.pointLabelFontSize,pointLabelFontFamily:this.options.pointLabelFontFamily,pointLabelFontStyle:this.options.pointLabelFontStyle,height:this.chart.height,width:this.chart.width,xCenter:this.chart.width/2,yCenter:this.chart.height/2,ctx:this.chart.ctx,templateString:this.options.scaleLabel,labels:t.labels,valuesCount:t.datasets[0].data.length}),this.scale.setScaleSize(),this.updateScaleRange(t.datasets),this.scale.buildYLabels()},updateScaleRange:function(t){var i=function(){var i=[];return e.each(t,function(t){t.data?i=i.concat(t.data):e.each(t.points,function(t){i.push(t.value)})}),i}(),s=this.options.scaleOverride?{steps:this.options.scaleSteps,stepValue:this.options.scaleStepWidth,min:this.options.scaleStartValue,max:this.options.scaleStartValue+this.options.scaleSteps*this.options.scaleStepWidth}:e.calculateScaleRange(i,e.min([this.chart.width,this.chart.height])/2,this.options.scaleFontSize,this.options.scaleBeginAtZero,this.options.scaleIntegersOnly);e.extend(this.scale,s)},addData:function(t,i){this.scale.valuesCount++,e.each(t,function(t,s){if(e.isNumber(t)){var n=this.scale.getPointPosition(this.scale.valuesCount,this.scale.calculateCenterOffset(t));this.datasets[s].points.push(new this.PointClass({value:t,label:i,x:n.x,y:n.y,strokeColor:this.datasets[s].pointStrokeColor,fillColor:this.datasets[s].pointColor}))}},this),this.scale.labels.push(i),this.reflow(),this.update()},removeData:function(){this.scale.valuesCount--,this.scale.labels.shift(),e.each(this.datasets,function(t){t.points.shift()},this),this.reflow(),this.update()},update:function(){this.eachPoints(function(t){t.save()}),this.render()},reflow:function(){e.extend(this.scale,{width:this.chart.width,height:this.chart.height,size:e.min([this.chart.width,this.chart.height]),xCenter:this.chart.width/2,yCenter:this.chart.height/2}),this.updateScaleRange(this.datasets),this.scale.setScaleSize(),this.scale.buildYLabels()},draw:function(t){var i=t||1,s=this.chart.ctx;this.clear(),this.scale.draw(),e.each(this.datasets,function(t){e.each(t.points,function(t,e){t.transition(this.scale.getPointPosition(e,this.scale.calculateCenterOffset(t.value)),i)},this),s.lineWidth=this.options.datasetStrokeWidth,s.strokeStyle=t.strokeColor,s.beginPath(),e.each(t.points,function(t,i){0===i?s.moveTo(t.x,t.y):s.lineTo(t.x,t.y)},this),s.closePath(),s.stroke(),s.fillStyle=t.fillColor,s.fill(),e.each(t.points,function(t){t.draw()})},this)}})}.call(this); <ide>\ No newline at end of file <add>(function(){"use strict";var t=this,i=t.Chart,e=function(t){this.canvas=t.canvas,this.ctx=t;this.width=t.canvas.width,this.height=t.canvas.height;return this.aspectRatio=this.width/this.height,s.retinaScale(this),this};e.defaults={global:{animation:!0,animationSteps:60,animationEasing:"easeOutQuart",showScale:!0,scaleOverride:!1,scaleSteps:null,scaleStepWidth:null,scaleStartValue:null,scaleLineColor:"rgba(0,0,0,.1)",scaleLineWidth:1,scaleShowLabels:!0,scaleLabel:"<%=value%>",scaleIntegersOnly:!0,scaleBeginAtZero:!1,scaleFontFamily:"'Helvetica Neue', 'Helvetica', 'Arial', sans-serif",scaleFontSize:12,scaleFontStyle:"normal",scaleFontColor:"#666",responsive:!1,showTooltips:!0,tooltipEvents:["mousemove","touchstart","touchmove","mouseout"],tooltipFillColor:"rgba(0,0,0,0.8)",tooltipFontFamily:"'Helvetica Neue', 'Helvetica', 'Arial', sans-serif",tooltipFontSize:14,tooltipFontStyle:"normal",tooltipFontColor:"#fff",tooltipTitleFontFamily:"'Helvetica Neue', 'Helvetica', 'Arial', sans-serif",tooltipTitleFontSize:14,tooltipTitleFontStyle:"bold",tooltipTitleFontColor:"#fff",tooltipYPadding:6,tooltipXPadding:6,tooltipCaretSize:8,tooltipCornerRadius:6,tooltipXOffset:10,tooltipTemplate:"<%if (label){%><%=label%>: <%}%><%= value %>",multiTooltipTemplate:"<%= value %>",multiTooltipKeyBackground:"#fff",onAnimationProgress:function(){},onAnimationComplete:function(){}}},e.types={};var s=e.helpers={},n=s.each=function(t,i,e){var s=Array.prototype.slice.call(arguments,3);if(t)if(t.length===+t.length){var n;for(n=0;n<t.length;n++)i.apply(e,[t[n],n].concat(s))}else for(var o in t)i.apply(e,[t[o],o].concat(s))},o=s.clone=function(t){var i={};return n(t,function(e,s){t.hasOwnProperty(s)&&(i[s]=e)}),i},a=s.extend=function(t){return n(Array.prototype.slice.call(arguments,1),function(i){n(i,function(e,s){i.hasOwnProperty(s)&&(t[s]=e)})}),t},h=s.merge=function(){var t=Array.prototype.slice.call(arguments,0);return t.unshift({}),a.apply(null,t)},l=s.indexOf=function(t,i){if(Array.prototype.indexOf)return t.indexOf(i);for(var e=0;e<t.length;e++)if(t[e]===i)return e;return-1},r=s.inherits=function(t){var i=this,e=t&&t.hasOwnProperty("constructor")?t.constructor:function(){return i.apply(this,arguments)},s=function(){this.constructor=e};return s.prototype=i.prototype,e.prototype=new s,e.extend=r,t&&a(e.prototype,t),e.__super__=i.prototype,e},c=s.noop=function(){},u=s.uid=function(){var t=0;return function(){return"chart-"+t++}}(),d=s.warn=function(t){window.console&&"function"==typeof window.console.warn&&console.warn(t)},p=s.amd="function"==typeof t.define&&t.define.amd,f=s.isNumber=function(t){return!isNaN(parseFloat(t))&&isFinite(t)},g=s.max=function(t){return Math.max.apply(Math,t)},m=s.min=function(t){return Math.min.apply(Math,t)},v=(s.cap=function(t,i,e){if(f(i)){if(t>i)return i}else if(f(e)&&e>t)return e;return t},s.getDecimalPlaces=function(t){return t%1!==0&&f(t)?t.toString().split(".")[1].length:0}),S=s.radians=function(t){return t*(Math.PI/180)},x=(s.getAngleFromPoint=function(t,i){var e=i.x-t.x,s=i.y-t.y,n=Math.sqrt(e*e+s*s),o=2*Math.PI+Math.atan2(s,e);return 0>e&&0>s&&(o+=2*Math.PI),{angle:o,distance:n}},s.aliasPixel=function(t){return t%2===0?0:.5}),C=(s.splineCurve=function(t,i,e,s){var n=Math.sqrt(Math.pow(i.x-t.x,2)+Math.pow(i.y-t.y,2)),o=Math.sqrt(Math.pow(e.x-i.x,2)+Math.pow(e.y-i.y,2)),a=s*n/(n+o),h=s*o/(n+o);return{inner:{x:i.x-a*(e.x-t.x),y:i.y-a*(e.y-t.y)},outer:{x:i.x+h*(e.x-t.x),y:i.y+h*(e.y-t.y)}}},s.calculateOrderOfMagnitude=function(t){return Math.floor(Math.log(t)/Math.LN10)}),y=(s.calculateScaleRange=function(t,i,e,s,n){var o=2,a=Math.floor(i/(1.5*e)),h=o>=a,l=g(t),r=m(t);l===r&&(l+=.5,r>=.5&&!s?r-=.5:l+=.5);for(var c=Math.abs(l-r),u=C(c),d=Math.ceil(l/(1*Math.pow(10,u)))*Math.pow(10,u),p=s?0:Math.floor(r/(1*Math.pow(10,u)))*Math.pow(10,u),f=d-p,v=Math.pow(10,u),S=Math.round(f/v);(S>a||a>2*S)&&!h;)if(S>a)v*=2,S=Math.round(f/v),S%1!==0&&(h=!0);else if(n&&u>=0){if(v/2%1!==0)break;v/=2,S=Math.round(f/v)}else v/=2,S=Math.round(f/v);return h&&(S=o,v=f/S),{steps:S,stepValue:v,min:p,max:p+S*v}},s.template=function(t,i){function e(t,i){var e=/\W/.test(t)?new Function("obj","var p=[],print=function(){p.push.apply(p,arguments);};with(obj){p.push('"+t.replace(/[\r\t\n]/g," ").split("<%").join(" ").replace(/((^|%>)[^\t]*)'/g,"$1\r").replace(/\t=(.*?)%>/g,"',$1,'").split(" ").join("');").split("%>").join("p.push('").split("\r").join("\\'")+"');}return p.join('');"):s[t]=s[t];return i?e(i):e}var s={};return e(t,i)}),b=(s.generateLabels=function(t,i,e,s){var o=new Array(i);return labelTemplateString&&n(o,function(i,n){o[n]=y(t,{value:e+s*(n+1)})}),o},s.easingEffects={linear:function(t){return t},easeInQuad:function(t){return t*t},easeOutQuad:function(t){return-1*t*(t-2)},easeInOutQuad:function(t){return(t/=.5)<1?.5*t*t:-0.5*(--t*(t-2)-1)},easeInCubic:function(t){return t*t*t},easeOutCubic:function(t){return 1*((t=t/1-1)*t*t+1)},easeInOutCubic:function(t){return(t/=.5)<1?.5*t*t*t:.5*((t-=2)*t*t+2)},easeInQuart:function(t){return t*t*t*t},easeOutQuart:function(t){return-1*((t=t/1-1)*t*t*t-1)},easeInOutQuart:function(t){return(t/=.5)<1?.5*t*t*t*t:-0.5*((t-=2)*t*t*t-2)},easeInQuint:function(t){return 1*(t/=1)*t*t*t*t},easeOutQuint:function(t){return 1*((t=t/1-1)*t*t*t*t+1)},easeInOutQuint:function(t){return(t/=.5)<1?.5*t*t*t*t*t:.5*((t-=2)*t*t*t*t+2)},easeInSine:function(t){return-1*Math.cos(t/1*(Math.PI/2))+1},easeOutSine:function(t){return 1*Math.sin(t/1*(Math.PI/2))},easeInOutSine:function(t){return-0.5*(Math.cos(Math.PI*t/1)-1)},easeInExpo:function(t){return 0===t?1:1*Math.pow(2,10*(t/1-1))},easeOutExpo:function(t){return 1===t?1:1*(-Math.pow(2,-10*t/1)+1)},easeInOutExpo:function(t){return 0===t?0:1===t?1:(t/=.5)<1?.5*Math.pow(2,10*(t-1)):.5*(-Math.pow(2,-10*--t)+2)},easeInCirc:function(t){return t>=1?t:-1*(Math.sqrt(1-(t/=1)*t)-1)},easeOutCirc:function(t){return 1*Math.sqrt(1-(t=t/1-1)*t)},easeInOutCirc:function(t){return(t/=.5)<1?-0.5*(Math.sqrt(1-t*t)-1):.5*(Math.sqrt(1-(t-=2)*t)+1)},easeInElastic:function(t){var i=1.70158,e=0,s=1;return 0===t?0:1==(t/=1)?1:(e||(e=.3),s<Math.abs(1)?(s=1,i=e/4):i=e/(2*Math.PI)*Math.asin(1/s),-(s*Math.pow(2,10*(t-=1))*Math.sin(2*(1*t-i)*Math.PI/e)))},easeOutElastic:function(t){var i=1.70158,e=0,s=1;return 0===t?0:1==(t/=1)?1:(e||(e=.3),s<Math.abs(1)?(s=1,i=e/4):i=e/(2*Math.PI)*Math.asin(1/s),s*Math.pow(2,-10*t)*Math.sin(2*(1*t-i)*Math.PI/e)+1)},easeInOutElastic:function(t){var i=1.70158,e=0,s=1;return 0===t?0:2==(t/=.5)?1:(e||(e=.3*1.5),s<Math.abs(1)?(s=1,i=e/4):i=e/(2*Math.PI)*Math.asin(1/s),1>t?-.5*s*Math.pow(2,10*(t-=1))*Math.sin(2*(1*t-i)*Math.PI/e):s*Math.pow(2,-10*(t-=1))*Math.sin(2*(1*t-i)*Math.PI/e)*.5+1)},easeInBack:function(t){var i=1.70158;return 1*(t/=1)*t*((i+1)*t-i)},easeOutBack:function(t){var i=1.70158;return 1*((t=t/1-1)*t*((i+1)*t+i)+1)},easeInOutBack:function(t){var i=1.70158;return(t/=.5)<1?.5*t*t*(((i*=1.525)+1)*t-i):.5*((t-=2)*t*(((i*=1.525)+1)*t+i)+2)},easeInBounce:function(t){return 1-b.easeOutBounce(1-t)},easeOutBounce:function(t){return(t/=1)<1/2.75?7.5625*t*t:2/2.75>t?1*(7.5625*(t-=1.5/2.75)*t+.75):2.5/2.75>t?1*(7.5625*(t-=2.25/2.75)*t+.9375):1*(7.5625*(t-=2.625/2.75)*t+.984375)},easeInOutBounce:function(t){return.5>t?.5*b.easeInBounce(2*t):.5*b.easeOutBounce(2*t-1)+.5}}),w=s.requestAnimFrame=function(){return window.requestAnimationFrame||window.webkitRequestAnimationFrame||window.mozRequestAnimationFrame||window.oRequestAnimationFrame||window.msRequestAnimationFrame||function(t){return window.setTimeout(t,1e3/60)}}(),P=(s.cancelAnimFrame=function(){return window.cancelAnimationFrame||window.webkitCancelAnimationFrame||window.mozCancelAnimationFrame||window.oCancelAnimationFrame||window.msCancelAnimationFrame||function(t){return window.clearTimeout(t,1e3/60)}}(),s.animationLoop=function(t,i,e,s,n,o){var a=0,h=b[e]||b.linear,l=function(){a++;var e=a/i,r=h(e);t.call(o,r,e,a),s.call(o,r,e),i>a?o.animationFrame=w(l):n.apply(o)};w(l)},s.getRelativePosition=function(t){var i,e,s=t.originalEvent||t,n=t.currentTarget||t.srcElement,o=n.getBoundingClientRect();return s.touches?(i=s.touches[0].clientX-o.left,e=s.touches[0].clientY-o.top):(i=s.clientX-o.left,e=s.clientY-o.top),{x:i,y:e}},s.addEvent=function(t,i,e){t.addEventListener?t.addEventListener(i,e):t.attachEvent?t.attachEvent("on"+i,e):t["on"+i]=e}),L=s.removeEvent=function(t,i,e){t.removeEventListener?t.removeEventListener(i,e,!1):t.detachEvent?t.detachEvent("on"+i,e):t["on"+i]=c},k=(s.bindEvents=function(t,i,e){t.events||(t.events={}),n(i,function(i){t.events[i]=function(){e.apply(t,arguments)},P(t.chart.canvas,i,t.events[i])})},s.unbindEvents=function(t,i){n(i,function(i,e){L(t.chart.canvas,e,i)})}),F=s.getMaximumSize=function(t){var i=t.parentNode;return i.clientWidth},R=s.retinaScale=function(t){var i=t.ctx,e=t.canvas.width,s=t.canvas.height;window.devicePixelRatio&&(i.canvas.style.width=e+"px",i.canvas.style.height=s+"px",i.canvas.height=s*window.devicePixelRatio,i.canvas.width=e*window.devicePixelRatio,i.scale(window.devicePixelRatio,window.devicePixelRatio))},A=s.clear=function(t){t.ctx.clearRect(0,0,t.width,t.height)},T=s.fontString=function(t,i,e){return i+" "+t+"px "+e},M=s.longestText=function(t,i,e){t.font=i;var s=0;return n(e,function(i){var e=t.measureText(i).width;s=e>s?e:s}),s},W=s.drawRoundedRectangle=function(t,i,e,s,n,o){t.beginPath(),t.moveTo(i+o,e),t.lineTo(i+s-o,e),t.quadraticCurveTo(i+s,e,i+s,e+o),t.lineTo(i+s,e+n-o),t.quadraticCurveTo(i+s,e+n,i+s-o,e+n),t.lineTo(i+o,e+n),t.quadraticCurveTo(i,e+n,i,e+n-o),t.lineTo(i,e+o),t.quadraticCurveTo(i,e,i+o,e),t.closePath()};e.instances={},e.Type=function(t,i,s){this.options=i,this.chart=s,this.id=u(),e.instances[this.id]=this,i.responsive&&this.resize(),this.initialize.call(this,t)},a(e.Type.prototype,{initialize:function(){return this},clear:function(){return A(this.chart),this},stop:function(){return s.cancelAnimFrame.call(t,this.animationFrame),this},resize:function(t){this.stop();var i=this.chart.canvas,e=F(this.chart.canvas),s=e/this.chart.aspectRatio;return i.width=this.chart.width=e,i.height=this.chart.height=s,R(this.chart),"function"==typeof t&&t.apply(this,Array.prototype.slice.call(arguments,1)),this},reflow:c,render:function(t){return t&&this.reflow(),this.options.animation&&!t?s.animationLoop(this.draw,this.options.animationSteps,this.options.animationEasing,this.options.onAnimationProgress,this.options.onAnimationComplete,this):(this.draw(),this.options.onAnimationComplete.call(this)),this},generateLegend:function(){return y(this.options.legendTemplate,this)},destroy:function(){this.clear(),k(this,this.events),delete e.instances[this.id]},showTooltip:function(t,i){"undefined"==typeof this.activeElements&&(this.activeElements=[]);var o=function(t){var i=!1;return t.length!==this.activeElements.length?i=!0:(n(t,function(t,e){t!==this.activeElements[e]&&(i=!0)},this),i)}.call(this,t);if(o||i){if(this.activeElements=t,this.draw(),t.length>0)if(this.datasets&&this.datasets.length>1){for(var a,h,r=this.datasets.length-1;r>=0&&(a=this.datasets[r].points||this.datasets[r].bars||this.datasets[r].segments,h=l(a,t[0]),-1===h);r--);var c=[],u=[],d=function(){var t,i,e,n,o,a=[],l=[],r=[];return s.each(this.datasets,function(i){t=i.points||i.bars||i.segments,t[h]&&a.push(t[h])}),s.each(a,function(t){l.push(t.x),r.push(t.y),c.push(s.template(this.options.multiTooltipTemplate,t)),u.push({fill:t._saved.fillColor||t.fillColor,stroke:t._saved.strokeColor||t.strokeColor})},this),o=m(r),e=g(r),n=m(l),i=g(l),{x:n>this.chart.width/2?n:i,y:(o+e)/2}}.call(this,h);new e.MultiTooltip({x:d.x,y:d.y,xPadding:this.options.tooltipXPadding,yPadding:this.options.tooltipYPadding,xOffset:this.options.tooltipXOffset,fillColor:this.options.tooltipFillColor,textColor:this.options.tooltipFontColor,fontFamily:this.options.tooltipFontFamily,fontStyle:this.options.tooltipFontStyle,fontSize:this.options.tooltipFontSize,titleTextColor:this.options.tooltipTitleFontColor,titleFontFamily:this.options.tooltipTitleFontFamily,titleFontStyle:this.options.tooltipTitleFontStyle,titleFontSize:this.options.tooltipTitleFontSize,cornerRadius:this.options.tooltipCornerRadius,labels:c,legendColors:u,legendColorBackground:this.options.multiTooltipKeyBackground,title:t[0].label,chart:this.chart,ctx:this.chart.ctx}).draw()}else n(t,function(t){var i=t.tooltipPosition();new e.Tooltip({x:Math.round(i.x),y:Math.round(i.y),xPadding:this.options.tooltipXPadding,yPadding:this.options.tooltipYPadding,fillColor:this.options.tooltipFillColor,textColor:this.options.tooltipFontColor,fontFamily:this.options.tooltipFontFamily,fontStyle:this.options.tooltipFontStyle,fontSize:this.options.tooltipFontSize,caretHeight:this.options.tooltipCaretSize,cornerRadius:this.options.tooltipCornerRadius,text:y(this.options.tooltipTemplate,t),chart:this.chart}).draw()},this);return this}},toBase64Image:function(){return this.chart.canvas.toDataURL.apply(this.chart.canvas,arguments)}}),e.Type.extend=function(t){var i=this,s=function(){return i.apply(this,arguments)};if(s.prototype=o(i.prototype),a(s.prototype,t),s.extend=e.Type.extend,t.name||i.prototype.name){var n=t.name||i.prototype.name,l=e.defaults[i.prototype.name]?o(e.defaults[i.prototype.name]):{};e.defaults[n]=a(l,t.defaults),e.types[n]=s,e.prototype[n]=function(t,i){var o=h(e.defaults.global,e.defaults[n],i||{});return new s(t,o,this)}}else d("Name not provided for this chart, so it hasn't been registered");return i},e.Element=function(t){a(this,t),this.initialize.apply(this,arguments),this.save()},a(e.Element.prototype,{initialize:function(){},restore:function(t){return t?n(t,function(t){this[t]=this._saved[t]},this):a(this,this._saved),this},save:function(){return this._saved=o(this),delete this._saved._saved,this},update:function(t){return n(t,function(t,i){this._saved[i]=this[i],this[i]=t},this),this},transition:function(t,i){return n(t,function(t,e){this[e]=(t-this._saved[e])*i+this._saved[e]},this),this},tooltipPosition:function(){return{x:this.x,y:this.y}}}),e.Element.extend=r,e.Point=e.Element.extend({display:!0,inRange:function(t,i){var e=this.hitDetectionRadius+this.radius;return Math.pow(t-this.x,2)+Math.pow(i-this.y,2)<Math.pow(e,2)},draw:function(){if(this.display){var t=this.ctx;t.beginPath(),t.arc(this.x,this.y,this.radius,0,2*Math.PI),t.closePath(),t.strokeStyle=this.strokeColor,t.lineWidth=this.strokeWidth,t.fillStyle=this.fillColor,t.fill(),t.stroke()}}}),e.Arc=e.Element.extend({inRange:function(t,i){var e=s.getAngleFromPoint(this,{x:t,y:i}),n=e.angle>=this.startAngle&&e.angle<=this.endAngle,o=e.distance>=this.innerRadius&&e.distance<=this.outerRadius;return n&&o},tooltipPosition:function(){var t=this.startAngle+(this.endAngle-this.startAngle)/2,i=(this.outerRadius-this.innerRadius)/2+this.innerRadius;return{x:this.x+Math.cos(t)*i,y:this.y+Math.sin(t)*i}},draw:function(t){var i=this.ctx;i.beginPath(),i.arc(this.x,this.y,this.outerRadius,this.startAngle,this.endAngle),i.arc(this.x,this.y,this.innerRadius,this.endAngle,this.startAngle,!0),i.closePath(),i.strokeStyle=this.strokeColor,i.lineWidth=this.strokeWidth,i.fillStyle=this.fillColor,i.fill(),i.lineJoin="bevel",this.showStroke&&i.stroke()}}),e.Rectangle=e.Element.extend({draw:function(){var t=this.ctx,i=this.width/2,e=this.x-i,s=this.x+i,n=this.base-(this.base-this.y),o=this.strokeWidth/2;this.showStroke&&(e+=o,s-=o,n+=o),t.beginPath(),t.fillStyle=this.fillColor,t.strokeStyle=this.strokeColor,t.lineWidth=this.strokeWidth,t.moveTo(e,this.base),t.lineTo(e,n),t.lineTo(s,n),t.lineTo(s,this.base),t.fill(),this.showStroke&&t.stroke()},height:function(){return this.base-this.y},inRange:function(t,i){return t>=this.x-this.width/2&&t<=this.x+this.width/2&&i>=this.y&&i<=this.base}}),e.Tooltip=e.Element.extend({draw:function(){var t=this.chart.ctx;t.font=T(this.fontSize,this.fontStyle,this.fontFamily),this.xAlign="center",this.yAlign="above";var i=2,e=t.measureText(this.text).width+2*this.xPadding,s=this.fontSize+2*this.yPadding,n=s+this.caretHeight+i;this.x+e/2>this.chart.width?this.xAlign="left":this.x-e/2<0&&(this.xAlign="right"),this.y-n<0&&(this.yAlign="below");var o=this.x-e/2,a=this.y-n;switch(t.fillStyle=this.fillColor,this.yAlign){case"above":t.beginPath(),t.moveTo(this.x,this.y-i),t.lineTo(this.x+this.caretHeight,this.y-(i+this.caretHeight)),t.lineTo(this.x-this.caretHeight,this.y-(i+this.caretHeight)),t.closePath(),t.fill();break;case"below":a=this.y+i+this.caretHeight,t.beginPath(),t.moveTo(this.x,this.y+i),t.lineTo(this.x+this.caretHeight,this.y+i+this.caretHeight),t.lineTo(this.x-this.caretHeight,this.y+i+this.caretHeight),t.closePath(),t.fill()}switch(this.xAlign){case"left":o=this.x-e+(this.cornerRadius+this.caretHeight);break;case"right":o=this.x-(this.cornerRadius+this.caretHeight)}W(t,o,a,e,s,this.cornerRadius),t.fill(),t.fillStyle=this.textColor,t.textAlign="center",t.textBaseline="middle",t.fillText(this.text,o+e/2,a+s/2)}}),e.MultiTooltip=e.Element.extend({initialize:function(){this.font=T(this.fontSize,this.fontStyle,this.fontFamily),this.titleFont=T(this.titleFontSize,this.titleFontStyle,this.titleFontFamily),this.height=this.labels.length*this.fontSize+(this.labels.length-1)*(this.fontSize/2)+2*this.yPadding+1.5*this.titleFontSize,this.ctx.font=this.titleFont;var t=this.ctx.measureText(this.title).width,i=M(this.ctx,this.font,this.labels)+this.fontSize+3,e=g([i,t]);this.width=e+2*this.xPadding;var s=this.height/2;this.y-s<0?this.y=s:this.y+s>this.chart.height&&(this.y=this.chart.height-s),this.x>this.chart.width/2?this.x-=this.xOffset+this.width:this.x+=this.xOffset},getLineHeight:function(t){var i=this.y-this.height/2+this.yPadding,e=t-1;return 0===t?i+this.titleFontSize/2:i+(1.5*this.fontSize*e+this.fontSize/2)+1.5*this.titleFontSize},draw:function(){W(this.ctx,this.x,this.y-this.height/2,this.width,this.height,this.cornerRadius);var t=this.ctx;t.fillStyle=this.fillColor,t.fill(),t.closePath(),t.textAlign="left",t.textBaseline="middle",t.fillStyle=this.titleTextColor,t.font=this.titleFont,t.fillText(this.title,this.x+this.xPadding,this.getLineHeight(0)),t.font=this.font,s.each(this.labels,function(i,e){t.fillStyle=this.textColor,t.fillText(i,this.x+this.xPadding+this.fontSize+3,this.getLineHeight(e+1)),t.fillStyle=this.legendColorBackground,t.fillRect(this.x+this.xPadding,this.getLineHeight(e+1)-this.fontSize/2,this.fontSize,this.fontSize),t.fillStyle=this.legendColors[e].fill,t.fillRect(this.x+this.xPadding,this.getLineHeight(e+1)-this.fontSize/2,this.fontSize,this.fontSize)},this)}}),e.Scale=e.Element.extend({initialize:function(){this.fit()},buildYLabels:function(){this.yLabels=[];for(var t=v(this.stepValue),i=0;i<=this.steps;i++)this.yLabels.push(y(this.templateString,{value:(this.min+i*this.stepValue).toFixed(t)}));this.yLabelWidth=this.display&&this.showLabels?M(this.ctx,this.font,this.yLabels):0},addXLabel:function(t){this.xLabels.push(t),this.valuesCount++,this.fit()},removeXLabel:function(){this.xLabels.shift(),this.valuesCount--,this.fit()},fit:function(){this.startPoint=this.display?this.fontSize:0,this.endPoint=this.display?this.height-1.5*this.fontSize-5:this.height,this.startPoint+=this.padding,this.endPoint-=this.padding;var t,i=this.endPoint-this.startPoint;for(this.calculateYRange(i),this.buildYLabels(),this.calculateXLabelRotation();i>this.endPoint-this.startPoint;)i=this.endPoint-this.startPoint,t=this.yLabelWidth,this.calculateYRange(i),this.buildYLabels(),t<this.yLabelWidth&&this.calculateXLabelRotation()},calculateXLabelRotation:function(){this.ctx.font=this.font;var t,i,e=this.ctx.measureText(this.xLabels[0]).width,s=this.ctx.measureText(this.xLabels[this.xLabels.length-1]).width;if(this.xScalePaddingRight=s/2+3,this.xScalePaddingLeft=e/2>this.yLabelWidth+10?e/2:this.yLabelWidth+10,this.xLabelRotation=0,this.display){var n,o=M(this.ctx,this.font,this.xLabels);this.xLabelWidth=o;for(var a=Math.floor(this.calculateX(1)-this.calculateX(0))-6;this.xLabelWidth>a&&0===this.xLabelRotation||this.xLabelWidth>a&&this.xLabelRotation<=90&&this.xLabelRotation>0;)n=Math.cos(S(this.xLabelRotation)),t=n*e,i=n*s,t+this.fontSize/2>this.yLabelWidth+8&&(this.xScalePaddingLeft=t+this.fontSize/2),this.xScalePaddingRight=this.fontSize/2,this.xLabelRotation++,this.xLabelWidth=n*o;this.xLabelRotation>0&&(this.endPoint-=Math.sin(S(this.xLabelRotation))*o+3)}else this.xLabelWidth=0,this.xScalePaddingRight=this.padding,this.xScalePaddingLeft=this.padding},calculateYRange:c,drawingArea:function(){return this.startPoint-this.endPoint},calculateY:function(t){var i=this.drawingArea()/(this.min-this.max);return this.endPoint-i*(t-this.min)},calculateX:function(t){var i=(this.xLabelRotation>0,this.width-(this.xScalePaddingLeft+this.xScalePaddingRight)),e=i/(this.valuesCount-(this.offsetGridLines?0:1)),s=e*t+this.xScalePaddingLeft;return this.offsetGridLines&&(s+=e/2),Math.round(s)},update:function(t){s.extend(this,t),this.fit()},draw:function(){var t=this.ctx,i=(this.endPoint-this.startPoint)/this.steps,e=Math.round(this.xScalePaddingLeft);this.display&&(t.fillStyle=this.textColor,t.font=this.font,n(this.yLabels,function(n,o){var a=this.endPoint-i*o,h=Math.round(a);t.textAlign="right",t.textBaseline="middle",this.showLabels&&t.fillText(n,e-10,a),t.beginPath(),o>0?(t.lineWidth=this.gridLineWidth,t.strokeStyle=this.gridLineColor):(t.lineWidth=this.lineWidth,t.strokeStyle=this.lineColor),h+=s.aliasPixel(t.lineWidth),t.moveTo(e,h),t.lineTo(this.width,h),t.stroke(),t.closePath(),t.lineWidth=this.lineWidth,t.strokeStyle=this.lineColor,t.beginPath(),t.moveTo(e-5,h),t.lineTo(e,h),t.stroke(),t.closePath()},this),n(this.xLabels,function(i,e){var s=this.calculateX(e)+x(this.lineWidth),n=this.calculateX(e-(this.offsetGridLines?.5:0))+x(this.lineWidth),o=this.xLabelRotation>0;t.beginPath(),e>0?(t.lineWidth=this.gridLineWidth,t.strokeStyle=this.gridLineColor):(t.lineWidth=this.lineWidth,t.strokeStyle=this.lineColor),t.moveTo(n,this.endPoint),t.lineTo(n,this.startPoint-3),t.stroke(),t.closePath(),t.lineWidth=this.lineWidth,t.strokeStyle=this.lineColor,t.beginPath(),t.moveTo(n,this.endPoint),t.lineTo(n,this.endPoint+5),t.stroke(),t.closePath(),t.save(),t.translate(s,o?this.endPoint+12:this.endPoint+8),t.rotate(-1*S(this.xLabelRotation)),t.font=this.font,t.textAlign=o?"right":"center",t.textBaseline=o?"middle":"top",t.fillText(i,0,0),t.restore()},this))}}),e.RadialScale=e.Element.extend({initialize:function(){this.size=m([this.height,this.width]),this.drawingArea=this.display?this.size/2-(this.fontSize/2+this.backdropPaddingY):this.size/2},calculateCenterOffset:function(t){var i=this.drawingArea/(this.max-this.min);return(t-this.min)*i},update:function(){this.lineArc?this.drawingArea=this.display?this.size/2-(this.fontSize/2+this.backdropPaddingY):this.size/2:this.setScaleSize(),this.buildYLabels()},buildYLabels:function(){this.yLabels=[];for(var t=v(this.stepValue),i=0;i<=this.steps;i++)this.yLabels.push(y(this.templateString,{value:(this.min+i*this.stepValue).toFixed(t)}))},getCircumference:function(){return 2*Math.PI/this.valuesCount},setScaleSize:function(){var t,i,e,s,n,o,a,h,l,r,c,u,d=m([this.height/2-this.pointLabelFontSize-5,this.width/2]),p=this.width,g=0;for(this.ctx.font=T(this.pointLabelFontSize,this.pointLabelFontStyle,this.pointLabelFontFamily),i=0;i<this.valuesCount;i++)t=this.getPointPosition(i,d),e=this.ctx.measureText(y(this.templateString,{value:this.labels[i]})).width+5,0===i||i===this.valuesCount/2?(s=e/2,t.x+s>p&&(p=t.x+s,n=i),t.x-s<g&&(g=t.x-s,a=i)):i<this.valuesCount/2?t.x+e>p&&(p=t.x+e,n=i):i>this.valuesCount/2&&t.x-e<g&&(g=t.x-e,a=i);l=g,r=Math.ceil(p-this.width),o=this.getIndexAngle(n),h=this.getIndexAngle(a),c=r/Math.sin(o+Math.PI/2),u=l/Math.sin(h+Math.PI/2),c=f(c)?c:0,u=f(u)?u:0,this.drawingArea=d-(u+c)/2,this.setCenterPoint(u,c)},setCenterPoint:function(t,i){var e=this.width-i-this.drawingArea,s=t+this.drawingArea;this.xCenter=(s+e)/2,this.yCenter=this.height/2},getIndexAngle:function(t){var i=2*Math.PI/this.valuesCount;return t*i-Math.PI/2},getPointPosition:function(t,i){var e=this.getIndexAngle(t);return{x:Math.cos(e)*i+this.xCenter,y:Math.sin(e)*i+this.yCenter}},draw:function(){if(this.display){var t=this.ctx;if(n(this.yLabels,function(i,e){if(e>0){var s,n=e*(this.drawingArea/this.steps),o=this.yCenter-n;if(this.lineWidth>0)if(t.strokeStyle=this.lineColor,t.lineWidth=this.lineWidth,this.lineArc)t.beginPath(),t.arc(this.xCenter,this.yCenter,n,0,2*Math.PI),t.closePath(),t.stroke();else{t.beginPath();for(var a=0;a<this.valuesCount;a++)s=this.getPointPosition(a,this.calculateCenterOffset(this.min+e*this.stepValue)),0===a?t.moveTo(s.x,s.y):t.lineTo(s.x,s.y);t.closePath(),t.stroke()}if(this.showLabels){if(t.font=T(this.fontSize,this.fontStyle,this.fontFamily),this.showLabelBackdrop){var h=t.measureText(i).width;t.fillStyle=this.backdropColor,t.fillRect(this.xCenter-h/2-this.backdropPaddingX,o-this.fontSize/2-this.backdropPaddingY,h+2*this.backdropPaddingX,this.fontSize+2*this.backdropPaddingY)}t.textAlign="center",t.textBaseline="middle",t.fillStyle=this.fontColor,t.fillText(i,this.xCenter,o)}}},this),!this.lineArc){t.lineWidth=this.angleLineWidth,t.strokeStyle=this.angleLineColor;for(var i=this.valuesCount-1;i>=0;i--){if(this.angleLineWidth>0){var e=this.getPointPosition(i,this.calculateCenterOffset(this.max));t.beginPath(),t.moveTo(this.xCenter,this.yCenter),t.lineTo(e.x,e.y),t.stroke(),t.closePath()}var s=this.getPointPosition(i,this.calculateCenterOffset(this.max)+5);t.font=T(this.pointLabelFontSize,this.pointLabelFontStyle,this.pointLabelFontFamily),t.fillStyle=this.pointLabelFontColor;var o=this.labels.length,a=this.labels.length/2,h=a/2,l=h>i||i>o-h,r=i===h||i===o-h;t.textAlign=0===i?"center":i===a?"center":a>i?"left":"right",t.textBaseline=r?"middle":l?"bottom":"top",t.fillText(this.labels[i],s.x,s.y)}}}}}),s.addEvent(window,"resize",function(){var t;return function(){clearTimeout(t),t=setTimeout(function(){n(e.instances,function(t){t.options.responsive&&t.resize(t.render,!0)})},50)}}()),p?define(function(){return e}):"object"==typeof module&&module.exports&&(module.exports=e),t.Chart=e,e.noConflict=function(){return t.Chart=i,e}}).call(this),function(){"use strict";var t=this,i=t.Chart,e=i.helpers,s={scaleBeginAtZero:!0,scaleShowGridLines:!0,scaleGridLineColor:"rgba(0,0,0,.05)",scaleGridLineWidth:1,barShowStroke:!0,barStrokeWidth:2,barValueSpacing:5,barDatasetSpacing:1,legendTemplate:'<ul class="<%=name.toLowerCase()%>-legend"><% for (var i=0; i<datasets.length; i++){%><li><span style="background-color:<%=datasets[i].fillColor%>"></span><%if(datasets[i].label){%><%=datasets[i].label%><%}%></li><%}%></ul>'};i.Type.extend({name:"Bar",defaults:s,initialize:function(t){var s=this.options;this.ScaleClass=i.Scale.extend({offsetGridLines:!0,calculateBarX:function(t,i,e){var n=this.calculateBaseWidth(),o=this.calculateX(e)-n/2,a=this.calculateBarWidth(t);return o+a*i+i*s.barDatasetSpacing+a/2},calculateBaseWidth:function(){return this.calculateX(1)-this.calculateX(0)-2*s.barValueSpacing},calculateBarWidth:function(t){var i=this.calculateBaseWidth()-(t-1)*s.barDatasetSpacing;return i/t}}),this.datasets=[],this.options.showTooltips&&e.bindEvents(this,this.options.tooltipEvents,function(t){var i="mouseout"!==t.type?this.getBarsAtEvent(t):[];this.eachBars(function(t){t.restore(["fillColor","strokeColor"])}),e.each(i,function(t){t.fillColor=t.highlightFill,t.strokeColor=t.highlightStroke}),this.showTooltip(i)}),this.BarClass=i.Rectangle.extend({strokeWidth:this.options.barStrokeWidth,showStroke:this.options.barShowStroke,ctx:this.chart.ctx}),e.each(t.datasets,function(i){var s={label:i.label||null,fillColor:i.fillColor,strokeColor:i.strokeColor,bars:[]};this.datasets.push(s),e.each(i.data,function(n,o){e.isNumber(n)&&s.bars.push(new this.BarClass({value:n,label:t.labels[o],datasetLabel:i.label,strokeColor:i.strokeColor,fillColor:i.fillColor,highlightFill:i.highlightFill||i.fillColor,highlightStroke:i.highlightStroke||i.strokeColor}))},this)},this),this.buildScale(t.labels),this.BarClass.prototype.base=this.scale.endPoint,this.eachBars(function(t,i,s){e.extend(t,{width:this.scale.calculateBarWidth(this.datasets.length),x:this.scale.calculateBarX(this.datasets.length,s,i),y:this.scale.endPoint}),t.save()},this),this.render()},update:function(){this.scale.update(),e.each(this.activeElements,function(t){t.restore(["fillColor","strokeColor"])}),this.eachBars(function(t){t.save()}),this.render()},eachBars:function(t){e.each(this.datasets,function(i,s){e.each(i.bars,t,this,s)},this)},getBarsAtEvent:function(t){for(var i,s=[],n=e.getRelativePosition(t),o=function(t){s.push(t.bars[i])},a=0;a<this.datasets.length;a++)for(i=0;i<this.datasets[a].bars.length;i++)if(this.datasets[a].bars[i].inRange(n.x,n.y))return e.each(this.datasets,o),s;return s},buildScale:function(t){var i=this,s=function(){var t=[];return i.eachBars(function(i){t.push(i.value)}),t},n={templateString:this.options.scaleLabel,height:this.chart.height,width:this.chart.width,ctx:this.chart.ctx,textColor:this.options.scaleFontColor,fontSize:this.options.scaleFontSize,fontStyle:this.options.scaleFontStyle,fontFamily:this.options.scaleFontFamily,valuesCount:t.length,beginAtZero:this.options.scaleBeginAtZero,integersOnly:this.options.scaleIntegersOnly,calculateYRange:function(t){var i=e.calculateScaleRange(s(),t,this.fontSize,this.beginAtZero,this.integersOnly);e.extend(this,i)},xLabels:t,font:e.fontString(this.options.scaleFontSize,this.options.scaleFontStyle,this.options.scaleFontFamily),lineWidth:this.options.scaleLineWidth,lineColor:this.options.scaleLineColor,gridLineWidth:this.options.scaleShowGridLines?this.options.scaleGridLineWidth:0,gridLineColor:this.options.scaleShowGridLines?this.options.scaleGridLineColor:"rgba(0,0,0,0)",padding:this.options.showScale?0:this.options.barShowStroke?this.options.barStrokeWidth:0,showLabels:this.options.scaleShowLabels,display:this.options.showScale};this.options.scaleOverride&&e.extend(n,{calculateYRange:e.noop,steps:this.options.scaleSteps,stepValue:this.options.scaleStepWidth,min:this.options.scaleStartValue,max:this.options.scaleStartValue+this.options.scaleSteps*this.options.scaleStepWidth}),this.scale=new this.ScaleClass(n)},addData:function(t,i){e.each(t,function(t,s){e.isNumber(t)&&this.datasets[s].bars.push(new this.BarClass({value:t,label:i,x:this.scale.calculateBarX(this.datasets.length,s,this.scale.valuesCount+1),y:this.scale.endPoint,width:this.scale.calculateBarWidth(this.datasets.length),base:this.scale.endPoint,strokeColor:this.datasets[s].strokeColor,fillColor:this.datasets[s].fillColor}))},this),this.scale.addXLabel(i),this.update()},removeData:function(){this.scale.removeXLabel(),e.each(this.datasets,function(t){t.bars.shift()},this),this.update()},reflow:function(){e.extend(this.BarClass.prototype,{y:this.scale.endPoint,base:this.scale.endPoint});var t=e.extend({height:this.chart.height,width:this.chart.width});this.scale.update(t)},draw:function(t){var i=t||1;this.clear();this.chart.ctx;this.scale.draw(i),e.each(this.datasets,function(t,s){e.each(t.bars,function(t,e){t.base=this.scale.endPoint,t.transition({x:this.scale.calculateBarX(this.datasets.length,s,e),y:this.scale.calculateY(t.value),width:this.scale.calculateBarWidth(this.datasets.length)},i).draw()},this)},this)}})}.call(this),function(){"use strict";var t=this,i=t.Chart,e=i.helpers,s={segmentShowStroke:!0,segmentStrokeColor:"#fff",segmentStrokeWidth:2,percentageInnerCutout:50,animationSteps:100,animationEasing:"easeOutBounce",animateRotate:!0,animateScale:!1,legendTemplate:'<ul class="<%=name.toLowerCase()%>-legend"><% for (var i=0; i<segments.length; i++){%><li><span style="background-color:<%=segments[i].fillColor%>"></span><%if(segments[i].label){%><%=segments[i].label%><%}%></li><%}%></ul>'};i.Type.extend({name:"Doughnut",defaults:s,initialize:function(t){this.segments=[],this.outerRadius=(e.min([this.chart.width,this.chart.height])-this.options.segmentStrokeWidth/2)/2,this.SegmentArc=i.Arc.extend({ctx:this.chart.ctx,x:this.chart.width/2,y:this.chart.height/2}),this.options.showTooltips&&e.bindEvents(this,this.options.tooltipEvents,function(t){var i="mouseout"!==t.type?this.getSegmentsAtEvent(t):[]; <add>e.each(this.segments,function(t){t.restore(["fillColor"])}),e.each(i,function(t){t.fillColor=t.highlightColor}),this.showTooltip(i)}),this.calculateTotal(t),e.each(t,function(t,i){this.addData(t,i,!0)},this),this.render()},getSegmentsAtEvent:function(t){var i=[],s=e.getRelativePosition(t);return e.each(this.segments,function(t){t.inRange(s.x,s.y)&&i.push(t)},this),i},addData:function(t,i,e){var s=i||this.segments.length;this.segments.splice(s,0,new this.SegmentArc({value:t.value,outerRadius:this.options.animateScale?0:this.outerRadius,innerRadius:this.options.animateScale?0:this.outerRadius/100*this.options.percentageInnerCutout,fillColor:t.color,highlightColor:t.highlight||t.color,showStroke:this.options.segmentShowStroke,strokeWidth:this.options.segmentStrokeWidth,strokeColor:this.options.segmentStrokeColor,startAngle:1.5*Math.PI,circumference:this.options.animateRotate?0:this.calculateCircumference(t.value),label:t.label})),e||(this.reflow(),this.update())},calculateCircumference:function(t){return 2*Math.PI*(t/this.total)},calculateTotal:function(t){this.total=0,e.each(t,function(t){this.total+=t.value},this)},update:function(){this.calculateTotal(this.segments),e.each(this.activeElements,function(t){t.restore(["fillColor"])}),e.each(this.segments,function(t){t.save()}),this.render()},removeData:function(t){var i=e.isNumber(t)?t:this.segments.length-1;this.segments.splice(i,1),this.reflow(),this.update()},reflow:function(){e.extend(this.SegmentArc.prototype,{x:this.chart.width/2,y:this.chart.height/2}),this.outerRadius=(e.min([this.chart.width,this.chart.height])-this.options.segmentStrokeWidth/2)/2,e.each(this.segments,function(t){t.update({outerRadius:this.outerRadius,innerRadius:this.outerRadius/100*this.options.percentageInnerCutout})},this)},draw:function(t){var i=t?t:1;this.clear(),e.each(this.segments,function(t,e){t.transition({circumference:this.calculateCircumference(t.value),outerRadius:this.outerRadius,innerRadius:this.outerRadius/100*this.options.percentageInnerCutout},i),t.endAngle=t.startAngle+t.circumference,t.draw(),0===e&&(t.startAngle=1.5*Math.PI),e<this.segments.length-1&&(this.segments[e+1].startAngle=t.endAngle)},this)}}),i.types.Doughnut.extend({name:"Pie",defaults:e.merge(s,{percentageInnerCutout:0})})}.call(this),function(){"use strict";var t=this,i=t.Chart,e=i.helpers,s={scaleShowGridLines:!0,scaleGridLineColor:"rgba(0,0,0,.05)",scaleGridLineWidth:1,bezierCurve:!0,bezierCurveTension:.4,pointDot:!0,pointDotRadius:4,pointDotStrokeWidth:1,pointHitDetectionRadius:20,datasetStroke:!0,datasetStrokeWidth:2,datasetFill:!0,legendTemplate:'<ul class="<%=name.toLowerCase()%>-legend"><% for (var i=0; i<datasets.length; i++){%><li><span style="background-color:<%=datasets[i].strokeColor%>"></span><%if(datasets[i].label){%><%=datasets[i].label%><%}%></li><%}%></ul>'};i.Type.extend({name:"Line",defaults:s,initialize:function(t){this.PointClass=i.Point.extend({strokeWidth:this.options.pointDotStrokeWidth,radius:this.options.pointDotRadius,display:this.options.pointDot,hitDetectionRadius:this.options.pointHitDetectionRadius,ctx:this.chart.ctx,inRange:function(t){return Math.pow(t-this.x,2)<Math.pow(this.radius+this.hitDetectionRadius,2)}}),this.datasets=[],this.options.showTooltips&&e.bindEvents(this,this.options.tooltipEvents,function(t){var i="mouseout"!==t.type?this.getPointsAtEvent(t):[];this.eachPoints(function(t){t.restore(["fillColor","strokeColor"])}),e.each(i,function(t){t.fillColor=t.highlightFill,t.strokeColor=t.highlightStroke}),this.showTooltip(i)}),e.each(t.datasets,function(i){var s={label:i.label||null,fillColor:i.fillColor,strokeColor:i.strokeColor,pointColor:i.pointColor,pointStrokeColor:i.pointStrokeColor,points:[]};this.datasets.push(s),e.each(i.data,function(n,o){e.isNumber(n)&&s.points.push(new this.PointClass({value:n,label:t.labels[o],datasetLabel:i.label,strokeColor:i.pointStrokeColor,fillColor:i.pointColor,highlightFill:i.pointHighlightFill||i.pointColor,highlightStroke:i.pointHighlightStroke||i.pointStrokeColor}))},this),this.buildScale(t.labels),this.eachPoints(function(t,i){e.extend(t,{x:this.scale.calculateX(i),y:this.scale.endPoint}),t.save()},this)},this),this.render()},update:function(){this.scale.update(),e.each(this.activeElements,function(t){t.restore(["fillColor","strokeColor"])}),this.eachPoints(function(t){t.save()}),this.render()},eachPoints:function(t){e.each(this.datasets,function(i){e.each(i.points,t,this)},this)},getPointsAtEvent:function(t){var i=[],s=e.getRelativePosition(t);return e.each(this.datasets,function(t){e.each(t.points,function(t){t.inRange(s.x,s.y)&&i.push(t)})},this),i},buildScale:function(t){var s=this,n=function(){var t=[];return s.eachPoints(function(i){t.push(i.value)}),t},o={templateString:this.options.scaleLabel,height:this.chart.height,width:this.chart.width,ctx:this.chart.ctx,textColor:this.options.scaleFontColor,fontSize:this.options.scaleFontSize,fontStyle:this.options.scaleFontStyle,fontFamily:this.options.scaleFontFamily,valuesCount:t.length,beginAtZero:this.options.scaleBeginAtZero,integersOnly:this.options.scaleIntegersOnly,calculateYRange:function(t){var i=e.calculateScaleRange(n(),t,this.fontSize,this.beginAtZero,this.integersOnly);e.extend(this,i)},xLabels:t,font:e.fontString(this.options.scaleFontSize,this.options.scaleFontStyle,this.options.scaleFontFamily),lineWidth:this.options.scaleLineWidth,lineColor:this.options.scaleLineColor,gridLineWidth:this.options.scaleShowGridLines?this.options.scaleGridLineWidth:0,gridLineColor:this.options.scaleShowGridLines?this.options.scaleGridLineColor:"rgba(0,0,0,0)",padding:this.options.showScale?0:this.options.pointDotRadius+this.options.pointDotStrokeWidth,showLabels:this.options.scaleShowLabels,display:this.options.showScale};this.options.scaleOverride&&e.extend(o,{calculateYRange:e.noop,steps:this.options.scaleSteps,stepValue:this.options.scaleStepWidth,min:this.options.scaleStartValue,max:this.options.scaleStartValue+this.options.scaleSteps*this.options.scaleStepWidth}),this.scale=new i.Scale(o)},addData:function(t,i){e.each(t,function(t,s){e.isNumber(t)&&this.datasets[s].points.push(new this.PointClass({value:t,label:i,x:this.scale.calculateX(this.scale.valuesCount+1),y:this.scale.endPoint,strokeColor:this.datasets[s].pointStrokeColor,fillColor:this.datasets[s].pointColor}))},this),this.scale.addXLabel(i),this.update()},removeData:function(){this.scale.removeXLabel(),e.each(this.datasets,function(t){t.points.shift()},this),this.update()},reflow:function(){var t=e.extend({height:this.chart.height,width:this.chart.width});this.scale.update(t)},draw:function(t){var i=t||1;this.clear();var s=this.chart.ctx;this.scale.draw(i),e.each(this.datasets,function(t){e.each(t.points,function(t,e){t.transition({y:this.scale.calculateY(t.value),x:this.scale.calculateX(e)},i)},this),this.options.bezierCurve&&e.each(t.points,function(i,s){i.controlPoints=0===s?e.splineCurve(i,i,t.points[s+1],0):s>=t.points.length-1?e.splineCurve(t.points[s-1],i,i,0):e.splineCurve(t.points[s-1],i,t.points[s+1],this.options.bezierCurveTension)},this),s.lineWidth=this.options.datasetStrokeWidth,s.strokeStyle=t.strokeColor,s.beginPath(),e.each(t.points,function(i,e){e>0?this.options.bezierCurve?s.bezierCurveTo(t.points[e-1].controlPoints.outer.x,t.points[e-1].controlPoints.outer.y,i.controlPoints.inner.x,i.controlPoints.inner.y,i.x,i.y):s.lineTo(i.x,i.y):s.moveTo(i.x,i.y)},this),s.stroke(),this.options.datasetFill&&(s.lineTo(t.points[t.points.length-1].x,this.scale.endPoint),s.lineTo(this.scale.calculateX(0),this.scale.endPoint),s.fillStyle=t.fillColor,s.closePath(),s.fill()),e.each(t.points,function(t){t.draw()})},this)}})}.call(this),function(){"use strict";var t=this,i=t.Chart,e=i.helpers,s={scaleShowLabelBackdrop:!0,scaleBackdropColor:"rgba(255,255,255,0.75)",scaleBeginAtZero:!0,scaleBackdropPaddingY:2,scaleBackdropPaddingX:2,scaleShowLine:!0,segmentShowStroke:!0,segmentStrokeColor:"#fff",segmentStrokeWidth:2,animationSteps:100,animationEasing:"easeOutBounce",animateRotate:!0,animateScale:!1,legendTemplate:'<ul class="<%=name.toLowerCase()%>-legend"><% for (var i=0; i<segments.length; i++){%><li><span style="background-color:<%=segments[i].fillColor%>"></span><%if(segments[i].label){%><%=segments[i].label%><%}%></li><%}%></ul>'};i.Type.extend({name:"PolarArea",defaults:s,initialize:function(t){this.segments=[],this.SegmentArc=i.Arc.extend({showStroke:this.options.segmentShowStroke,strokeWidth:this.options.segmentStrokeWidth,strokeColor:this.options.segmentStrokeColor,ctx:this.chart.ctx,innerRadius:0,x:this.chart.width/2,y:this.chart.height/2}),this.scale=new i.RadialScale({display:this.options.showScale,fontStyle:this.options.scaleFontStyle,fontSize:this.options.scaleFontSize,fontFamily:this.options.scaleFontFamily,fontColor:this.options.scaleFontColor,showLabels:this.options.scaleShowLabels,showLabelBackdrop:this.options.scaleShowLabelBackdrop,backdropColor:this.options.scaleBackdropColor,backdropPaddingY:this.options.scaleBackdropPaddingY,backdropPaddingX:this.options.scaleBackdropPaddingX,lineWidth:this.options.scaleShowLine?this.options.scaleLineWidth:0,lineColor:this.options.scaleLineColor,lineArc:!0,width:this.chart.width,height:this.chart.height,xCenter:this.chart.width/2,yCenter:this.chart.height/2,ctx:this.chart.ctx,templateString:this.options.scaleLabel,valuesCount:t.length}),this.updateScaleRange(t),this.scale.update(),e.each(t,function(t,i){this.addData(t,i,!0)},this),this.options.showTooltips&&e.bindEvents(this,this.options.tooltipEvents,function(t){var i="mouseout"!==t.type?this.getSegmentsAtEvent(t):[];e.each(this.segments,function(t){t.restore(["fillColor"])}),e.each(i,function(t){t.fillColor=t.highlightColor}),this.showTooltip(i)}),this.render()},getSegmentsAtEvent:function(t){var i=[],s=e.getRelativePosition(t);return e.each(this.segments,function(t){t.inRange(s.x,s.y)&&i.push(t)},this),i},addData:function(t,i,e){var s=i||this.segments.length;this.segments.splice(s,0,new this.SegmentArc({fillColor:t.color,highlightColor:t.highlight||t.color,label:t.label,value:t.value,outerRadius:this.options.animateScale?0:this.scale.calculateCenterOffset(t.value),circumference:this.options.animateRotate?0:this.scale.getCircumference(),startAngle:1.5*Math.PI})),e||(this.reflow(),this.update())},removeData:function(t){var i=e.isNumber(t)?t:this.segments.length-1;this.segments.splice(i,1),this.reflow(),this.update()},calculateTotal:function(t){this.total=0,e.each(t,function(t){this.total+=t.value},this),this.scale.valuesCount=this.segments.length},updateScaleRange:function(t){var i=[];e.each(t,function(t){i.push(t.value)});var s=this.options.scaleOverride?{steps:this.options.scaleSteps,stepValue:this.options.scaleStepWidth,min:this.options.scaleStartValue,max:this.options.scaleStartValue+this.options.scaleSteps*this.options.scaleStepWidth}:e.calculateScaleRange(i,e.min([this.chart.width,this.chart.height])/2,this.options.scaleFontSize,this.options.scaleBeginAtZero,this.options.scaleIntegersOnly);e.extend(this.scale,s,{size:e.min([this.chart.width,this.chart.height]),xCenter:this.chart.width/2,yCenter:this.chart.height/2})},update:function(){this.calculateTotal(this.segments),e.each(this.segments,function(t){t.save()}),this.render()},reflow:function(){e.extend(this.SegmentArc.prototype,{x:this.chart.width/2,y:this.chart.height/2}),this.updateScaleRange(this.segments),this.scale.update(),e.extend(this.scale,{xCenter:this.chart.width/2,yCenter:this.chart.height/2}),e.each(this.segments,function(t){t.update({outerRadius:this.scale.calculateCenterOffset(t.value)})},this)},draw:function(t){var i=t||1;this.clear(),e.each(this.segments,function(t,e){t.transition({circumference:this.scale.getCircumference(),outerRadius:this.scale.calculateCenterOffset(t.value)},i),t.endAngle=t.startAngle+t.circumference,0===e&&(t.startAngle=1.5*Math.PI),e<this.segments.length-1&&(this.segments[e+1].startAngle=t.endAngle),t.draw()},this),this.scale.draw()}})}.call(this),function(){"use strict";var t=this,i=t.Chart,e=i.helpers;i.Type.extend({name:"Radar",defaults:{scaleShowLine:!0,angleShowLineOut:!0,scaleShowLabels:!1,scaleBeginAtZero:!0,angleLineColor:"rgba(0,0,0,.1)",angleLineWidth:1,pointLabelFontFamily:"'Arial'",pointLabelFontStyle:"normal",pointLabelFontSize:10,pointLabelFontColor:"#666",pointDot:!0,pointDotRadius:3,pointDotStrokeWidth:1,pointHitDetectionRadius:20,datasetStroke:!0,datasetStrokeWidth:2,datasetFill:!0,legendTemplate:'<ul class="<%=name.toLowerCase()%>-legend"><% for (var i=0; i<datasets.length; i++){%><li><span style="background-color:<%=datasets[i].strokeColor%>"></span><%if(datasets[i].label){%><%=datasets[i].label%><%}%></li><%}%></ul>'},initialize:function(t){this.PointClass=i.Point.extend({strokeWidth:this.options.pointDotStrokeWidth,radius:this.options.pointDotRadius,display:this.options.pointDot,hitDetectionRadius:this.options.pointHitDetectionRadius,ctx:this.chart.ctx}),this.datasets=[],this.buildScale(t),this.options.showTooltips&&e.bindEvents(this,this.options.tooltipEvents,function(t){var i="mouseout"!==t.type?this.getPointsAtEvent(t):[];this.eachPoints(function(t){t.restore(["fillColor","strokeColor"])}),e.each(i,function(t){t.fillColor=t.highlightFill,t.strokeColor=t.highlightStroke}),this.showTooltip(i)}),e.each(t.datasets,function(i){var s={label:i.label||null,fillColor:i.fillColor,strokeColor:i.strokeColor,pointColor:i.pointColor,pointStrokeColor:i.pointStrokeColor,points:[]};this.datasets.push(s),e.each(i.data,function(n,o){if(e.isNumber(n)){var a;this.scale.animation||(a=this.scale.getPointPosition(o,this.scale.calculateCenterOffset(n))),s.points.push(new this.PointClass({value:n,label:t.labels[o],datasetLabel:i.label,x:this.options.animation?this.scale.xCenter:a.x,y:this.options.animation?this.scale.yCenter:a.y,strokeColor:i.pointStrokeColor,fillColor:i.pointColor,highlightFill:i.pointHighlightFill||i.pointColor,highlightStroke:i.pointHighlightStroke||i.pointStrokeColor}))}},this)},this),this.render()},eachPoints:function(t){e.each(this.datasets,function(i){e.each(i.points,t,this)},this)},getPointsAtEvent:function(t){var i=e.getRelativePosition(t),s=e.getAngleFromPoint({x:this.scale.xCenter,y:this.scale.yCenter},i),n=2*Math.PI/this.scale.valuesCount,o=Math.round((s.angle-1.5*Math.PI)/n),a=[];return(o>=this.scale.valuesCount||0>o)&&(o=0),s.distance<=this.scale.drawingArea&&e.each(this.datasets,function(t){a.push(t.points[o])}),a},buildScale:function(t){this.scale=new i.RadialScale({display:this.options.showScale,fontStyle:this.options.scaleFontStyle,fontSize:this.options.scaleFontSize,fontFamily:this.options.scaleFontFamily,fontColor:this.options.scaleFontColor,showLabels:this.options.scaleShowLabels,showLabelBackdrop:this.options.scaleShowLabelBackdrop,backdropColor:this.options.scaleBackdropColor,backdropPaddingY:this.options.scaleBackdropPaddingY,backdropPaddingX:this.options.scaleBackdropPaddingX,lineWidth:this.options.scaleShowLine?this.options.scaleLineWidth:0,lineColor:this.options.scaleLineColor,angleLineColor:this.options.angleLineColor,angleLineWidth:this.options.angleShowLineOut?this.options.angleLineWidth:0,pointLabelFontColor:this.options.pointLabelFontColor,pointLabelFontSize:this.options.pointLabelFontSize,pointLabelFontFamily:this.options.pointLabelFontFamily,pointLabelFontStyle:this.options.pointLabelFontStyle,height:this.chart.height,width:this.chart.width,xCenter:this.chart.width/2,yCenter:this.chart.height/2,ctx:this.chart.ctx,templateString:this.options.scaleLabel,labels:t.labels,valuesCount:t.datasets[0].data.length}),this.scale.setScaleSize(),this.updateScaleRange(t.datasets),this.scale.buildYLabels()},updateScaleRange:function(t){var i=function(){var i=[];return e.each(t,function(t){t.data?i=i.concat(t.data):e.each(t.points,function(t){i.push(t.value)})}),i}(),s=this.options.scaleOverride?{steps:this.options.scaleSteps,stepValue:this.options.scaleStepWidth,min:this.options.scaleStartValue,max:this.options.scaleStartValue+this.options.scaleSteps*this.options.scaleStepWidth}:e.calculateScaleRange(i,e.min([this.chart.width,this.chart.height])/2,this.options.scaleFontSize,this.options.scaleBeginAtZero,this.options.scaleIntegersOnly);e.extend(this.scale,s)},addData:function(t,i){this.scale.valuesCount++,e.each(t,function(t,s){if(e.isNumber(t)){var n=this.scale.getPointPosition(this.scale.valuesCount,this.scale.calculateCenterOffset(t));this.datasets[s].points.push(new this.PointClass({value:t,label:i,x:n.x,y:n.y,strokeColor:this.datasets[s].pointStrokeColor,fillColor:this.datasets[s].pointColor}))}},this),this.scale.labels.push(i),this.reflow(),this.update()},removeData:function(){this.scale.valuesCount--,this.scale.labels.shift(),e.each(this.datasets,function(t){t.points.shift()},this),this.reflow(),this.update()},update:function(){this.eachPoints(function(t){t.save()}),this.reflow(),this.render()},reflow:function(){e.extend(this.scale,{width:this.chart.width,height:this.chart.height,size:e.min([this.chart.width,this.chart.height]),xCenter:this.chart.width/2,yCenter:this.chart.height/2}),this.updateScaleRange(this.datasets),this.scale.setScaleSize(),this.scale.buildYLabels()},draw:function(t){var i=t||1,s=this.chart.ctx;this.clear(),this.scale.draw(),e.each(this.datasets,function(t){e.each(t.points,function(t,e){t.transition(this.scale.getPointPosition(e,this.scale.calculateCenterOffset(t.value)),i)},this),s.lineWidth=this.options.datasetStrokeWidth,s.strokeStyle=t.strokeColor,s.beginPath(),e.each(t.points,function(t,i){0===i?s.moveTo(t.x,t.y):s.lineTo(t.x,t.y)},this),s.closePath(),s.stroke(),s.fillStyle=t.fillColor,s.fill(),e.each(t.points,function(t){t.draw()})},this)}})}.call(this); <ide>\ No newline at end of file
2
Javascript
Javascript
consolidate triggerreport() tests
cae7232e7aa82ad57c81b55b0f8852ea3e70c5b3
<ide><path>test/node-report/test-api-nohooks.js <ide> const common = require('../common'); <ide> common.skipIfReportDisabled(); <ide> const assert = require('assert'); <add>const fs = require('fs'); <add>const path = require('path'); <ide> const helper = require('../common/report'); <ide> const tmpdir = require('../common/tmpdir'); <ide> <ide> common.expectWarning('ExperimentalWarning', <ide> 'change at any time'); <ide> tmpdir.refresh(); <ide> process.report.setOptions({ path: tmpdir.path }); <del>process.report.triggerReport(); <del>const reports = helper.findReports(process.pid, tmpdir.path); <del>assert.strictEqual(reports.length, 1); <del>helper.validate(reports[0]); <add> <add>function validate() { <add> const reports = helper.findReports(process.pid, tmpdir.path); <add> assert.strictEqual(reports.length, 1); <add> helper.validate(reports[0]); <add> fs.unlinkSync(reports[0]); <add> return reports[0]; <add>} <add> <add>{ <add> // Test with no arguments. <add> process.report.triggerReport(); <add> validate(); <add>} <add> <add>{ <add> // Test with an error argument. <add> process.report.triggerReport(new Error('test error')); <add> validate(); <add>} <add> <add>{ <add> // Test with a file argument. <add> const file = process.report.triggerReport('custom-name-1.json'); <add> const absolutePath = path.join(tmpdir.path, file); <add> assert.strictEqual(helper.findReports(process.pid, tmpdir.path).length, 0); <add> assert.strictEqual(file, 'custom-name-1.json'); <add> helper.validate(absolutePath); <add> fs.unlinkSync(absolutePath); <add>} <add> <add>{ <add> // Test with file and error arguments. <add> const file = process.report.triggerReport('custom-name-2.json', <add> new Error('test error')); <add> const absolutePath = path.join(tmpdir.path, file); <add> assert.strictEqual(helper.findReports(process.pid, tmpdir.path).length, 0); <add> assert.strictEqual(file, 'custom-name-2.json'); <add> helper.validate(absolutePath); <add> fs.unlinkSync(absolutePath); <add>} <add> <add>{ <add> // Test with a filename option. <add> const filename = path.join(tmpdir.path, 'custom-name-3.json'); <add> process.report.setOptions({ filename }); <add> const file = process.report.triggerReport(); <add> assert.strictEqual(helper.findReports(process.pid, tmpdir.path).length, 0); <add> assert.strictEqual(file, filename); <add> helper.validate(filename); <add> fs.unlinkSync(filename); <add>} <ide><path>test/node-report/test-api-pass-error.js <del>'use strict'; <del> <del>// Testcase for passing an error object to the API call. <del>const common = require('../common'); <del>common.skipIfReportDisabled(); <del>const assert = require('assert'); <del>if (process.argv[2] === 'child') { <del> try { <del> throw new Error('Testing error handling'); <del> } catch (err) { <del> process.report.triggerReport(err); <del> } <del>} else { <del> const helper = require('../common/report.js'); <del> const spawn = require('child_process').spawn; <del> const tmpdir = require('../common/tmpdir'); <del> tmpdir.refresh(); <del> const child = spawn(process.execPath, ['--experimental-report', <del> __filename, 'child'], <del> { cwd: tmpdir.path }); <del> child.on('exit', common.mustCall((code) => { <del> const report_msg = 'No reports found'; <del> const process_msg = 'Process exited unexpectedly'; <del> assert.strictEqual(code, 0, process_msg); <del> const reports = helper.findReports(child.pid, tmpdir.path); <del> assert.strictEqual(reports.length, 1, report_msg); <del> const report = reports[0]; <del> helper.validate(report); <del> })); <del>} <ide><path>test/node-report/test-api-trigger-with-filename.js <del>'use strict'; <del> <del>// Tests when a report is triggered with a given filename. <del>const common = require('../common'); <del>common.skipIfReportDisabled(); <del>const filename = 'myreport.json'; <del>if (process.argv[2] === 'child') { <del> process.report.triggerReport(filename); <del>} else { <del> const helper = require('../common/report.js'); <del> const spawn = require('child_process').spawn; <del> const assert = require('assert'); <del> const { join } = require('path'); <del> const tmpdir = require('../common/tmpdir'); <del> tmpdir.refresh(); <del> <del> const child = spawn(process.execPath, <del> ['--experimental-report', __filename, 'child'], <del> { cwd: tmpdir.path }); <del> child.on('exit', common.mustCall((code) => { <del> const process_msg = 'Process exited unexpectedly'; <del> assert.strictEqual(code, 0, process_msg + ':' + code); <del> const reports = helper.findReports(child.pid, tmpdir.path); <del> assert.strictEqual(reports.length, 0, <del> `Found unexpected report ${reports[0]}`); <del> const report = join(tmpdir.path, filename); <del> helper.validate(report); <del> })); <del>} <ide><path>test/node-report/test-api-trigger-with-options.js <del>'use strict'; <del> <del>// Tests when a report is triggered with options set. <del>const common = require('../common'); <del>common.skipIfReportDisabled(); <del>const filename = 'myreport.json'; <del>if (process.argv[2] === 'child') { <del> process.report.setOptions({ filename: filename }); <del> process.report.triggerReport(); <del>} else { <del> const helper = require('../common/report.js'); <del> const spawn = require('child_process').spawn; <del> const assert = require('assert'); <del> const { join } = require('path'); <del> const tmpdir = require('../common/tmpdir'); <del> tmpdir.refresh(); <del> <del> const child = spawn(process.execPath, <del> ['--experimental-report', __filename, 'child'], <del> { cwd: tmpdir.path }); <del> child.on('exit', common.mustCall((code) => { <del> const process_msg = 'Process exited unexpectedly'; <del> assert.strictEqual(code, 0, process_msg + ':' + code); <del> const reports = helper.findReports(child.pid, tmpdir.path); <del> assert.strictEqual(reports.length, 0, <del> `Found unexpected report ${reports[0]}`); <del> const report = join(tmpdir.path, filename); <del> helper.validate(report); <del> })); <del>}
4
Text
Text
add short description of models (#359)
b5bceea1b7edfd078c57037ebd84aac3c9b5ce07
<ide><path>README.md <ide> This repository contains machine learning models implemented in <ide> respective authors. <ide> <ide> To propose a model for inclusion please submit a pull request. <add> <add> <add>## Models <add>- [autoencoder](autoencoders) -- various autoencoders <add>- [inception](inception) -- deep convolutional networks for computer vision <add>- [namignizer](namignizer) -- recognize and generate names <add>- [neural_gpu](neural_gpu) -- highly parallel neural computer <add>- [privacy](privacy) -- privacy-preserving student models from multiple teachers <add>- [resnet](resnet) -- deep and wide residual networks <add>- [slim](slim) -- image classification models in TF-Slim <add>- [swivel](swivel) -- TensorFlow implementation of the Swivel algorithm for generating word embeddings <add>- [syntaxnet](syntaxnet) -- neural models of natural language syntax <add>- [textsum](textsum) -- sequence-to-sequence with attention model for text summarization. <add>- [transformer](transformer) -- spatial transformer network, which allows the spatial manipulation of data within the network
1
Javascript
Javascript
improve style and clarify wording
fd45d590ef924c25903832086a63172f98ea189c
<ide><path>src/ng/window.js <ide> * it is a global variable. In angular we always refer to it through the <ide> * `$window` service, so it may be overridden, removed or mocked for testing. <ide> * <del> * All expressions are evaluated with respect to current scope so they don't <del> * suffer from window globality. <add> * Expressions, like the one defined for the `ngClick` directive in the example <add> * below, are evaluated with respect to the current scope. Therefore, there is <add> * no risk of inadvertently coding in a dependency on a global value in such an <add> * expression. <ide> * <ide> * @example <ide> <doc:example>
1
Ruby
Ruby
add tests for unreadable formulae/casks
6e0bf05fb5ce233b97ba6023676073d33cc277e4
<ide><path>Library/Homebrew/test/cli/named_args_spec.rb <ide> <ide> require "cli/named_args" <ide> <add>def setup_unredable_formula(name) <add> error = FormulaUnreadableError.new(name, "testing") <add> allow(Formulary).to receive(:factory).with(name, force_bottle: false, flags: []).and_raise(error) <add>end <add> <add>def setup_unredable_cask(name) <add> error = Cask::CaskUnreadableError.new(name, "testing") <add> allow(Cask::CaskLoader).to receive(:load).with(name).and_raise(error) <add> <add> config = instance_double(Cask::Config) <add> allow(Cask::Config).to receive(:from_args).and_return(config) <add> allow(Cask::CaskLoader).to receive(:load).with(name, config: config).and_raise(error) <add>end <add> <ide> describe Homebrew::CLI::NamedArgs do <ide> let(:foo) do <ide> formula "foo" do <ide> RUBY <ide> end <ide> <add> let(:foo_cask) do <add> Cask::CaskLoader.load(+<<~RUBY) <add> cask "foo" do <add> version "1.0" <add> end <add> RUBY <add> end <add> <ide> describe "#to_formulae" do <ide> it "returns formulae" do <ide> stub_formula_loader foo, call_original: true <ide> <ide> expect(described_class.new("foo", "baz").to_formulae_and_casks).to eq [foo, baz] <ide> end <add> <add> context "when both formula and cask are present" do <add> before do <add> stub_formula_loader foo <add> stub_cask_loader foo_cask <add> end <add> <add> it "returns formula by default" do <add> expect(described_class.new("foo").to_formulae_and_casks).to eq [foo] <add> end <add> <add> it "returns formula if loading formula only" do <add> expect(described_class.new("foo").to_formulae_and_casks(only: :formula)).to eq [foo] <add> end <add> <add> it "returns cask if loading cask only" do <add> expect(described_class.new("foo").to_formulae_and_casks(only: :cask)).to eq [foo_cask] <add> end <add> end <add> <add> context "when both formula and cask are unreadable" do <add> before do <add> setup_unredable_formula "foo" <add> setup_unredable_cask "foo" <add> end <add> <add> it "raises an error" do <add> expect { described_class.new("foo").to_formulae_and_casks }.to raise_error(FormulaOrCaskUnavailableError) <add> end <add> <add> it "raises an error if loading formula only" do <add> expect { described_class.new("foo").to_formulae_and_casks(only: :formula) } <add> .to raise_error(FormulaUnreadableError) <add> end <add> <add> it "raises an error if loading cask only" do <add> expect { described_class.new("foo").to_formulae_and_casks(only: :cask) } <add> .to raise_error(Cask::CaskUnreadableError) <add> end <add> end <add> <add> it "raises an error when neither formula nor cask is present" do <add> expect { described_class.new("foo").to_formulae_and_casks }.to raise_error(FormulaOrCaskUnavailableError) <add> end <add> <add> it "returns formula when formula is present and cask is unreadable" do <add> stub_formula_loader foo <add> setup_unredable_cask "foo" <add> <add> expect(described_class.new("foo").to_formulae_and_casks).to eq [foo] <add> end <add> <add> it "returns cask when formula is unreadable and cask is present" do <add> setup_unredable_formula "foo" <add> stub_cask_loader foo_cask <add> <add> expect(described_class.new("foo").to_formulae_and_casks).to eq [foo_cask] <add> end <add> <add> it "raises an error when formula is absent and cask is unreadable" do <add> setup_unredable_cask "foo" <add> <add> expect { described_class.new("foo").to_formulae_and_casks }.to raise_error(Cask::CaskUnreadableError) <add> end <add> <add> it "raises an error when formula is unreadable and cask is absent" do <add> setup_unredable_formula "foo" <add> <add> expect { described_class.new("foo").to_formulae_and_casks }.to raise_error(FormulaUnreadableError) <add> end <ide> end <ide> <ide> describe "#to_resolved_formulae" do
1
Javascript
Javascript
fix documentation for the config class
e546190b1e98261c71753fdd4bc15caa53d0fc2d
<ide><path>src/config.js <ide> const Color = require('./color') <ide> const ScopedPropertyStore = require('scoped-property-store') <ide> const ScopeDescriptor = require('./scope-descriptor') <ide> <add>const schemaEnforcers = {} <add> <ide> // Essential: Used to access all of Atom's configuration details. <ide> // <ide> // An instance of this class is always available as the `atom.config` global. <ide> const ScopeDescriptor = require('./scope-descriptor') <ide> // <ide> // * Don't depend on (or write to) configuration keys outside of your keypath. <ide> // <del>const schemaEnforcers = {} <del> <ide> class Config { <ide> static addSchemaEnforcer (typeName, enforcerFunction) { <ide> if (schemaEnforcers[typeName] == null) { schemaEnforcers[typeName] = [] }
1
Python
Python
allow unicode yaml dump with unicodeyamlrenderer
7ae8409370635ccec7d3c160ea87281f21c9ae11
<ide><path>rest_framework/renderers.py <ide> class YAMLRenderer(BaseRenderer): <ide> format = 'yaml' <ide> encoder = encoders.SafeDumper <ide> charset = 'utf-8' <add> ensure_ascii = True <ide> <ide> def render(self, data, accepted_media_type=None, renderer_context=None): <ide> """ <ide> def render(self, data, accepted_media_type=None, renderer_context=None): <ide> if data is None: <ide> return '' <ide> <del> return yaml.dump(data, stream=None, encoding=self.charset, Dumper=self.encoder) <add> return yaml.dump(data, stream=None, encoding=self.charset, Dumper=self.encoder, allow_unicode=not self.ensure_ascii) <add> <add> <add>class UnicodeYAMLRenderer(YAMLRenderer): <add> """ <add> Renderer which serializes to YAML. <add> Does *not* apply character escaping for non-ascii characters. <add> """ <add> ensure_ascii = False <ide> <ide> <ide> class TemplateHTMLRenderer(BaseRenderer):
1
Python
Python
remove use of attr module in ud_train
2cab4d651732bad2520ab8aa566a6a91cb3c7bda
<ide><path>spacy/cli/ud_train.py <ide> from __future__ import unicode_literals <ide> import plac <ide> import tqdm <del>import attr <ide> from pathlib import Path <ide> import re <ide> import sys <ide> def initialize_pipeline(nlp, docs, golds, config): <ide> # Command line helpers # <ide> ######################## <ide> <del>@attr.s <ide> class Config(object): <del> vectors = attr.ib(default=None) <del> max_doc_length = attr.ib(default=10) <del> multitask_tag = attr.ib(default=True) <del> multitask_sent = attr.ib(default=True) <del> nr_epoch = attr.ib(default=30) <del> batch_size = attr.ib(default=1000) <del> dropout = attr.ib(default=0.2) <add> def __init__(self, vectors=None, max_doc_length=10, multitask_tag=True, <add> multitask_sent=True, nr_epoch=30, batch_size=1000, dropout=0.2): <add> for key, value in locals(): <add> setattr(self, key, value) <ide> <ide> @classmethod <ide> def load(cls, loc):
1
Ruby
Ruby
collapse logsubscriber into logging
fd372e66f0934617bef3b840cd0ea75429a24544
<ide><path>lib/active_job/log_subscriber.rb <del>require 'active_support/core_ext/string/filters' <del> <del>module ActiveJob <del> class LogSubscriber < ActiveSupport::LogSubscriber <del> def enqueue(event) <del> info "Enqueued #{event.payload[:job].name} to #{queue_name(event)}" + args_info(event) <del> end <del> <del> def enqueue_at(event) <del> info "Enqueued #{event.payload[:job].name} to #{queue_name(event)} at #{event.payload[:timestamp]}" + args_info(event) <del> end <del> <del> private <del> def queue_name(event) <del> event.payload[:adapter].name.demodulize.remove('Adapter') <del> end <del> <del> def args_info(event) <del> event.payload[:args].any? ? ": #{event.payload[:args].inspect}" : "" <del> end <del> <del> def logger <del> ActiveJob::Base.logger <del> end <del> end <del>end <del> <del>ActiveJob::LogSubscriber.attach_to :active_job <ide><path>lib/active_job/logging.rb <del>require 'active_job/log_subscriber' <add>require 'active_support/core_ext/string/filters' <ide> <ide> module ActiveJob <ide> module Logging <ide> mattr_accessor(:logger) { ActiveSupport::Logger.new(STDOUT) } <add> <add> class LogSubscriber < ActiveSupport::LogSubscriber <add> def enqueue(event) <add> info "Enqueued #{event.payload[:job].name} to #{queue_name(event)}" + args_info(event) <add> end <add> <add> def enqueue_at(event) <add> info "Enqueued #{event.payload[:job].name} to #{queue_name(event)} at #{event.payload[:timestamp]}" + args_info(event) <add> end <add> <add> private <add> def queue_name(event) <add> event.payload[:adapter].name.demodulize.remove('Adapter') <add> end <add> <add> def args_info(event) <add> event.payload[:args].any? ? ": #{event.payload[:args].inspect}" : "" <add> end <add> <add> def logger <add> ActiveJob::Base.logger <add> end <add> end <ide> end <ide> end <add> <add>ActiveJob::Logging::LogSubscriber.attach_to :active_job
2
Text
Text
update converting view section
3bb62b6651a8b91bec5a87ea04382e7f9d868fdc
<ide><path>docs/upgrading/upgrading-your-package.md <ide> To use the new views, you need to specify the `atom-space-pen-views` module in y <ide> <ide> ### Converting your views <ide> <del>Sometimes it is as simple as converting the requires at the top of each view page. In the case of our above example, you can just convert them to the following: <add>Sometimes it is as simple as converting the requires at the top of each view page. I assume you read the 'TL;DR' section and have updated all of your requires. <add> <add>### Upgrading classes extending any space-pen View <add> <add>The `afterAttach` and `beforeRemove` hooks have been replaced with <add>`attached` and `detached` and their semantics have been altered. `attached` will only be called when all parents of the View are attached to the DOM. <ide> <ide> ```coffee <del>{$, View} = require 'space-pen' <del>{TextEditorView} = require 'atom-space-pen-views' <add># Old way <add>{View} = require 'atom' <add>class MyView extends View <add> afterAttach: (onDom) -> <add> #... <add> <add> beforeRemove: -> <add> #... <ide> ``` <ide> <del>If you are using the lifecycle hooks, you will need to update code as well. <add>```coffee <add># New way <add>{View} = require 'atom-space-pen-views' <add>class MyView extends View <add> attached: -> <add> # Always called with the equivalent of @afterAttach(true)! <add> #... <add> <add> removed: -> <add> #... <add>``` <ide> <del>### Upgrading to space-pen's TextEditorView <add>### Upgrading to the new TextEditorView <ide> <ide> You should not need to change anything to use the new `TextEditorView`! See the [docs][TextEditorView] for more info. <ide> <del>### Upgrading to space-pen's ScrollView <add>### Upgrading to classes extending ScrollView <add> <add>The `ScrollView` has very minor changes. <add> <add>You can no longer use `@off` to remove default behavior for `core:move-up`, `core:move-down`, etc. <add> <add>```coffee <add># Old way to turn off default behavior <add>class ResultsView extends ScrollView <add> initialize: (@model) -> <add> super <add> # turn off default scrolling behavior from ScrollView <add> @off 'core:move-up' <add> @off 'core:move-down' <add> @off 'core:move-left' <add> @off 'core:move-right' <add>``` <add> <add>```coffee <add># New way to turn off default behavior <add>class ResultsView extends ScrollView <add> initialize: (@model) -> <add> disposable = super() <add> # turn off default scrolling behavior from ScrollView <add> disposable.dispose() <add>``` <ide> <del>See the [docs][ScrollView] for all the options. <add>* Check out [an example](https://github.com/atom/find-and-replace/pull/311/files#diff-9) from find-and-replace. <add>* See the [docs][ScrollView] for all the options. <ide> <del>### Upgrading to space-pen's SelectListView <add>### Upgrading to classes extending SelectListView <ide> <ide> Your SelectListView might look something like this: <ide> <ide> class CommandPaletteView extends SelectListView <ide> @panel?.hide() <ide> ``` <ide> <del>See the [SelectListView docs][SelectListView] for all the options. And check out the [conversion of CommandPaletteView][selectlistview-example] as a real-world example. <add>* And check out the [conversion of CommandPaletteView][selectlistview-example] as a real-world example. <add>* See the [SelectListView docs][SelectListView] for all options. <ide> <ide> ## Specs <ide>
1
Ruby
Ruby
add change_rpath method
a8cbc14ca34c55a9dfc3de865bb0cb420deb3adb
<ide><path>Library/Homebrew/os/mac/keg.rb <ide> def change_install_name(old, new, file) <ide> raise <ide> end <ide> <add> def change_rpath(old, new, file) <add> return if old == new <add> <add> @require_relocation = true <add> odebug "Changing rpath in #{file}\n from #{old}\n to #{new}" <add> MachO::Tools.change_rpath(file, old, new, strict: false) <add> apply_ad_hoc_signature(file) <add> rescue MachO::MachOError <add> onoe <<~EOS <add> Failed changing rpath in #{file} <add> from #{old} <add> to #{new} <add> EOS <add> raise <add> end <add> <ide> def apply_ad_hoc_signature(file) <ide> return if MacOS.version < :big_sur <ide> return unless Hardware::CPU.arm?
1
Ruby
Ruby
add debug output
47a8a312e3a82c5390e0c921ee314b2af3775cf1
<ide><path>Library/Homebrew/cmd/versions.rb <ide> def version_for_sha sha <ide> begin <ide> Object.send(:remove_const, Formula.class_s(name)) <ide> nostdout { Formula.factory(path).version } <del> rescue SyntaxError, TypeError, NameError, ArgumentError <add> rescue SyntaxError, TypeError, NameError, ArgumentError => e <ide> # We rescue these so that we can skip bad versions and <ide> # continue walking the history <del> nil <add> ohai "#{e} in #{name} at revision #{sha}", e.backtrace if ARGV.debug? <ide> end <ide> end <ide> end
1
Ruby
Ruby
update outdated test
6c5f1692eea160f6f967d71eaca478ccfef19df8
<ide><path>actionpack/test/dispatch/request_test.rb <ide> class RequestMethod < BaseRequestTest <ide> end <ide> end <ide> <del> test "allow method hacking on post" do <del> %w(GET OPTIONS PATCH PUT POST DELETE).each do |method| <del> request = stub_request 'REQUEST_METHOD' => method.to_s.upcase <del> <del> assert_equal(method == "HEAD" ? "GET" : method, request.method) <del> end <add> test "method returns original value of environment request method on POST" do <add> request = stub_request('rack.methodoverride.original_method' => 'POST') <add> assert_equal 'POST', request.method <ide> end <ide> <ide> test "invalid method hacking on post raises exception" do
1
Go
Go
enable secret inspect and rm by secret name
e0e65b9a3baab6bb3f35eddb6ed3d52654184029
<ide><path>cli/command/secret/inspect.go <ide> func runSecretInspect(dockerCli *command.DockerCli, opts inspectOptions) error { <ide> client := dockerCli.Client() <ide> ctx := context.Background() <ide> <add> // attempt to lookup secret by name <add> secrets, err := getSecrets(client, ctx, []string{opts.name}) <add> if err != nil { <add> return err <add> } <add> <add> id := opts.name <add> for _, s := range secrets { <add> if s.Spec.Annotations.Name == opts.name { <add> id = s.ID <add> break <add> } <add> } <add> <ide> getRef := func(name string) (interface{}, []byte, error) { <del> return client.SecretInspectWithRaw(ctx, name) <add> return client.SecretInspectWithRaw(ctx, id) <ide> } <ide> <del> return inspect.Inspect(dockerCli.Out(), []string{opts.name}, opts.format, getRef) <add> return inspect.Inspect(dockerCli.Out(), []string{id}, opts.format, getRef) <ide> } <ide><path>cli/command/secret/remove.go <ide> func runSecretRemove(dockerCli *command.DockerCli, opts removeOptions) error { <ide> client := dockerCli.Client() <ide> ctx := context.Background() <ide> <del> for _, id := range opts.ids { <add> // attempt to lookup secret by name <add> secrets, err := getSecrets(client, ctx, opts.ids) <add> if err != nil { <add> return err <add> } <add> <add> ids := opts.ids <add> <add> names := make(map[string]int) <add> for _, id := range ids { <add> names[id] = 1 <add> } <add> <add> if len(secrets) > 0 { <add> ids = []string{} <add> <add> for _, s := range secrets { <add> if _, ok := names[s.Spec.Annotations.Name]; ok { <add> ids = append(ids, s.ID) <add> } <add> } <add> } <add> <add> for _, id := range ids { <ide> if err := client.SecretRemove(ctx, id); err != nil { <ide> return err <ide> } <ide><path>cli/command/secret/utils.go <add>package secret <add> <add>import ( <add> "context" <add> <add> "github.com/docker/docker/api/types" <add> "github.com/docker/docker/api/types/filters" <add> "github.com/docker/docker/api/types/swarm" <add> "github.com/docker/docker/client" <add>) <add> <add>func getSecrets(client client.APIClient, ctx context.Context, names []string) ([]swarm.Secret, error) { <add> args := filters.NewArgs() <add> for _, n := range names { <add> args.Add("names", n) <add> } <add> <add> return client.SecretList(ctx, types.SecretListOptions{ <add> Filter: args, <add> }) <add>}
3
Java
Java
fix docleanupaftercompletion invocation
9cff07ce35dcca7c1028885492d246b3f4735dfb
<ide><path>spring-tx/src/main/java/org/springframework/transaction/reactive/AbstractReactiveTransactionManager.java <ide> private Mono<Void> cleanupAfterCompletion(TransactionSynchronizationManager sync <ide> if (status.isNewSynchronization()) { <ide> synchronizationManager.clear(); <ide> } <add> Mono<Void> cleanup = Mono.empty(); <ide> if (status.isNewTransaction()) { <del> doCleanupAfterCompletion(synchronizationManager, status.getTransaction()); <add> cleanup = doCleanupAfterCompletion(synchronizationManager, status.getTransaction()); <ide> } <ide> if (status.getSuspendedResources() != null) { <ide> if (status.isDebug()) { <ide> logger.debug("Resuming suspended transaction after completion of inner transaction"); <ide> } <ide> Object transaction = (status.hasTransaction() ? status.getTransaction() : null); <del> return resume(synchronizationManager, transaction, (SuspendedResourcesHolder) status.getSuspendedResources()); <add> return cleanup.then(resume(synchronizationManager, transaction, (SuspendedResourcesHolder) status.getSuspendedResources())); <ide> } <del> return Mono.empty(); <add> return cleanup; <ide> }); <ide> } <ide> <ide><path>spring-tx/src/test/java/org/springframework/transaction/reactive/ReactiveTestTransactionManager.java <ide> class ReactiveTestTransactionManager extends AbstractReactiveTransactionManager <ide> <ide> protected boolean rollbackOnly = false; <ide> <add> protected boolean cleanup = false; <add> <ide> <ide> ReactiveTestTransactionManager(boolean existingTransaction, boolean canCreateTransaction) { <ide> this.existingTransaction = existingTransaction; <ide> protected Mono<Void> doSetRollbackOnly(TransactionSynchronizationManager synchro <ide> return Mono.fromRunnable(() -> this.rollbackOnly = true); <ide> } <ide> <add> @Override <add> protected Mono<Void> doCleanupAfterCompletion(TransactionSynchronizationManager synchronizationManager, Object transaction) { <add> return Mono.fromRunnable(() -> this.cleanup = true); <add> } <ide> } <ide><path>spring-tx/src/test/java/org/springframework/transaction/reactive/ReactiveTransactionSupportTests.java <ide> public void commitWithoutExistingTransaction() { <ide> assertHasCommitted(tm); <ide> assertHasNoRollback(tm); <ide> assertHasNotSetRollbackOnly(tm); <add> assertHasCleanedUp(tm); <ide> } <ide> <ide> @Test <ide> public void rollbackWithoutExistingTransaction() { <ide> assertHasNotCommitted(tm); <ide> assertHasRolledBack(tm); <ide> assertHasNotSetRollbackOnly(tm); <add> assertHasCleanedUp(tm); <ide> } <ide> <ide> @Test <ide> public void rollbackOnlyWithoutExistingTransaction() { <ide> assertHasNotCommitted(tm); <ide> assertHasRolledBack(tm); <ide> assertHasNotSetRollbackOnly(tm); <add> assertHasCleanedUp(tm); <ide> } <ide> <ide> @Test <ide> public void commitWithExistingTransaction() { <ide> assertHasNotCommitted(tm); <ide> assertHasNoRollback(tm); <ide> assertHasNotSetRollbackOnly(tm); <add> assertHasNotCleanedUp(tm); <ide> } <ide> <ide> @Test <ide> public void rollbackWithExistingTransaction() { <ide> assertHasNotCommitted(tm); <ide> assertHasNoRollback(tm); <ide> assertHasSetRollbackOnly(tm); <add> assertHasNotCleanedUp(tm); <ide> } <ide> <ide> @Test <ide> public void rollbackOnlyWithExistingTransaction() { <ide> assertHasNotCommitted(tm); <ide> assertHasNoRollback(tm); <ide> assertHasSetRollbackOnly(tm); <add> assertHasNotCleanedUp(tm); <ide> } <ide> <ide> @Test <ide> public void transactionTemplate() { <ide> assertHasCommitted(tm); <ide> assertHasNoRollback(tm); <ide> assertHasNotSetRollbackOnly(tm); <add> assertHasCleanedUp(tm); <ide> } <ide> <ide> @Test <ide> public void transactionTemplateWithException() { <ide> assertHasNotCommitted(tm); <ide> assertHasRolledBack(tm); <ide> assertHasNotSetRollbackOnly(tm); <add> assertHasCleanedUp(tm); <ide> } <ide> <ide> private void assertHasBegan(ReactiveTestTransactionManager actual) { <ide> private void assertHasNotSetRollbackOnly(ReactiveTestTransactionManager actual) <ide> assertFalse("Expected to not call <ReactiveTransactionManager.setRollbackOnly()> but was <setRollbackOnly()> was called", actual.rollbackOnly); <ide> } <ide> <add> private void assertHasCleanedUp(ReactiveTestTransactionManager actual) { <add> assertTrue("Expected <ReactiveTransactionManager.doCleanupAfterCompletion()> but was <doCleanupAfterCompletion()> was not invoked", actual.cleanup); <add> } <add> <add> private void assertHasNotCleanedUp(ReactiveTestTransactionManager actual) { <add> assertFalse("Expected to not call <ReactiveTransactionManager.doCleanupAfterCompletion()> but was <doCleanupAfterCompletion()> was called", actual.cleanup); <add> } <add> <ide> }
3
Javascript
Javascript
replace assertpath() with validator
f962f97cc450cdd9ee58d914608801e5eed1058f
<ide><path>lib/path.js <ide> const { <ide> CHAR_COLON, <ide> CHAR_QUESTION_MARK, <ide> } = require('internal/constants'); <del> <del>function assertPath(path) { <del> if (typeof path !== 'string') { <del> throw new ERR_INVALID_ARG_TYPE('path', 'string', path); <del> } <del>} <add>const { validateString } = require('internal/validators'); <ide> <ide> function isPathSeparator(code) { <ide> return code === CHAR_FORWARD_SLASH || code === CHAR_BACKWARD_SLASH; <ide> const win32 = { <ide> } <ide> } <ide> <del> assertPath(path); <add> validateString(path, 'path'); <ide> <ide> // Skip empty entries <ide> if (path.length === 0) { <ide> const win32 = { <ide> }, <ide> <ide> normalize: function normalize(path) { <del> assertPath(path); <add> validateString(path, 'path'); <ide> const len = path.length; <ide> if (len === 0) <ide> return '.'; <ide> const win32 = { <ide> <ide> <ide> isAbsolute: function isAbsolute(path) { <del> assertPath(path); <add> validateString(path, 'path'); <ide> const len = path.length; <ide> if (len === 0) <ide> return false; <ide> const win32 = { <ide> var firstPart; <ide> for (var i = 0; i < arguments.length; ++i) { <ide> var arg = arguments[i]; <del> assertPath(arg); <add> validateString(arg, 'path'); <ide> if (arg.length > 0) { <ide> if (joined === undefined) <ide> joined = firstPart = arg; <ide> const win32 = { <ide> // to = 'C:\\orandea\\impl\\bbb' <ide> // The output of the function should be: '..\\..\\impl\\bbb' <ide> relative: function relative(from, to) { <del> assertPath(from); <del> assertPath(to); <add> validateString(from, 'from'); <add> validateString(to, 'to'); <ide> <ide> if (from === to) <ide> return ''; <ide> const win32 = { <ide> }, <ide> <ide> dirname: function dirname(path) { <del> assertPath(path); <add> validateString(path, 'path'); <ide> const len = path.length; <ide> if (len === 0) <ide> return '.'; <ide> const win32 = { <ide> <ide> <ide> basename: function basename(path, ext) { <del> if (ext !== undefined && typeof ext !== 'string') <del> throw new ERR_INVALID_ARG_TYPE('ext', 'string', ext); <del> assertPath(path); <add> if (ext !== undefined) <add> validateString(ext, 'ext'); <add> validateString(path, 'path'); <ide> var start = 0; <ide> var end = -1; <ide> var matchedSlash = true; <ide> const win32 = { <ide> <ide> <ide> extname: function extname(path) { <del> assertPath(path); <add> validateString(path, 'path'); <ide> var start = 0; <ide> var startDot = -1; <ide> var startPart = 0; <ide> const win32 = { <ide> <ide> <ide> parse: function parse(path) { <del> assertPath(path); <add> validateString(path, 'path'); <ide> <ide> var ret = { root: '', dir: '', base: '', ext: '', name: '' }; <ide> if (path.length === 0) <ide> const posix = { <ide> path = process.cwd(); <ide> } <ide> <del> assertPath(path); <add> validateString(path, 'path'); <ide> <ide> // Skip empty entries <ide> if (path.length === 0) { <ide> const posix = { <ide> <ide> <ide> normalize: function normalize(path) { <del> assertPath(path); <add> validateString(path, 'path'); <ide> <ide> if (path.length === 0) <ide> return '.'; <ide> const posix = { <ide> <ide> <ide> isAbsolute: function isAbsolute(path) { <del> assertPath(path); <add> validateString(path, 'path'); <ide> return path.length > 0 && path.charCodeAt(0) === CHAR_FORWARD_SLASH; <ide> }, <ide> <ide> const posix = { <ide> var joined; <ide> for (var i = 0; i < arguments.length; ++i) { <ide> var arg = arguments[i]; <del> assertPath(arg); <add> validateString(arg, 'path'); <ide> if (arg.length > 0) { <ide> if (joined === undefined) <ide> joined = arg; <ide> const posix = { <ide> <ide> <ide> relative: function relative(from, to) { <del> assertPath(from); <del> assertPath(to); <add> validateString(from, 'from'); <add> validateString(to, 'to'); <ide> <ide> if (from === to) <ide> return ''; <ide> const posix = { <ide> }, <ide> <ide> dirname: function dirname(path) { <del> assertPath(path); <add> validateString(path, 'path'); <ide> if (path.length === 0) <ide> return '.'; <ide> const hasRoot = path.charCodeAt(0) === CHAR_FORWARD_SLASH; <ide> const posix = { <ide> <ide> <ide> basename: function basename(path, ext) { <del> if (ext !== undefined && typeof ext !== 'string') <del> throw new ERR_INVALID_ARG_TYPE('ext', 'string', ext); <del> assertPath(path); <add> if (ext !== undefined) <add> validateString(ext, 'ext'); <add> validateString(path, 'path'); <ide> <ide> var start = 0; <ide> var end = -1; <ide> const posix = { <ide> <ide> <ide> extname: function extname(path) { <del> assertPath(path); <add> validateString(path, 'path'); <ide> var startDot = -1; <ide> var startPart = 0; <ide> var end = -1; <ide> const posix = { <ide> <ide> <ide> parse: function parse(path) { <del> assertPath(path); <add> validateString(path, 'path'); <ide> <ide> var ret = { root: '', dir: '', base: '', ext: '', name: '' }; <ide> if (path.length === 0)
1
Go
Go
protect concurrent map access
1ac0a66a64a906911d0708cd0e5fa397a2f0b595
<ide><path>daemon/graphdriver/quota/projectquota.go <ide> func NewControl(basePath string) (*Control, error) { <ide> // SetQuota - assign a unique project id to directory and set the quota limits <ide> // for that project id <ide> func (q *Control) SetQuota(targetPath string, quota Quota) error { <del> <add> q.RLock() <ide> projectID, ok := q.quotas[targetPath] <add> q.RUnlock() <ide> if !ok { <add> q.Lock() <ide> projectID = q.nextProjectID <ide> <ide> // <ide> // assign project id to new container directory <ide> // <ide> err := setProjectID(targetPath, projectID) <ide> if err != nil { <add> q.Unlock() <ide> return err <ide> } <del> <ide> q.quotas[targetPath] = projectID <ide> q.nextProjectID++ <add> q.Unlock() <ide> } <ide> <ide> // <ide> func setProjectQuota(backingFsBlockDev string, projectID uint32, quota Quota) er <ide> <ide> // GetQuota - get the quota limits of a directory that was configured with SetQuota <ide> func (q *Control) GetQuota(targetPath string, quota *Quota) error { <del> <add> q.RLock() <ide> projectID, ok := q.quotas[targetPath] <add> q.RUnlock() <ide> if !ok { <ide> return errors.Errorf("quota not found for path: %s", targetPath) <ide> } <ide> func setProjectID(targetPath string, projectID uint32) error { <ide> // findNextProjectID - find the next project id to be used for containers <ide> // by scanning driver home directory to find used project ids <ide> func (q *Control) findNextProjectID(home string) error { <add> q.Lock() <add> defer q.Unlock() <ide> files, err := ioutil.ReadDir(home) <ide> if err != nil { <ide> return errors.Errorf("read directory failed: %s", home) <ide><path>daemon/graphdriver/quota/types.go <ide> <ide> package quota // import "github.com/docker/docker/daemon/graphdriver/quota" <ide> <add>import "sync" <add> <ide> // Quota limit params - currently we only control blocks hard limit <ide> type Quota struct { <ide> Size uint64 <ide> type Quota struct { <ide> // who wants to apply project quotas to container dirs <ide> type Control struct { <ide> backingFsBlockDev string <add> sync.RWMutex // protect nextProjectID and quotas map <ide> nextProjectID uint32 <ide> quotas map[string]uint32 <ide> }
2
Java
Java
improve async support in spring mvc test
3bb515bec72b1984ae422f7a9da12e412978f61c
<ide><path>spring-test-mvc/src/main/java/org/springframework/test/web/servlet/DefaultMvcResult.java <ide> */ <ide> package org.springframework.test.web.servlet; <ide> <add>import java.util.concurrent.CountDownLatch; <add>import java.util.concurrent.TimeUnit; <add> <add>import javax.servlet.http.HttpServletRequest; <add> <ide> import org.springframework.mock.web.MockHttpServletRequest; <ide> import org.springframework.mock.web.MockHttpServletResponse; <add>import org.springframework.web.context.request.async.WebAsyncManager; <add>import org.springframework.web.context.request.async.WebAsyncUtils; <ide> import org.springframework.web.servlet.FlashMap; <ide> import org.springframework.web.servlet.HandlerInterceptor; <ide> import org.springframework.web.servlet.ModelAndView; <ide> class DefaultMvcResult implements MvcResult { <ide> <ide> private Exception resolvedException; <ide> <add> private CountDownLatch asyncResultLatch; <add> <ide> <ide> /** <ide> * Create a new instance with the given request and response. <ide> public FlashMap getFlashMap() { <ide> return RequestContextUtils.getOutputFlashMap(mockRequest); <ide> } <ide> <add> public void setAsyncResultLatch(CountDownLatch asyncResultLatch) { <add> this.asyncResultLatch = asyncResultLatch; <add> } <add> <add> public Object getAsyncResult() { <add> WebAsyncManager asyncManager = WebAsyncUtils.getAsyncManager(this.mockRequest); <add> if (asyncManager.isConcurrentHandlingStarted()) { <add> if (!awaitAsyncResult()) { <add> throw new IllegalStateException( <add> "Gave up waiting on async result from [" + this.handler + "] to complete"); <add> } <add> if (asyncManager.hasConcurrentResult()) { <add> return asyncManager.getConcurrentResult(); <add> } <add> } <add> <add> return null; <add> } <add> <add> private boolean awaitAsyncResult() { <add> if (this.asyncResultLatch == null) { <add> return true; <add> } <add> long timeout = ((HttpServletRequest) this.mockRequest).getAsyncContext().getTimeout(); <add> try { <add> return this.asyncResultLatch.await(timeout, TimeUnit.MILLISECONDS); <add> } <add> catch (InterruptedException e) { <add> return false; <add> } <add> } <add> <ide> } <ide><path>spring-test-mvc/src/main/java/org/springframework/test/web/servlet/MvcResult.java <ide> public interface MvcResult { <ide> */ <ide> FlashMap getFlashMap(); <ide> <add> /** <add> * Get the result of asynchronous execution or {@code null} if concurrent <add> * handling did not start. This method will hold and await the completion <add> * of concurrent handling. <add> * <add> * @throws IllegalStateException if concurrent handling does not complete <add> * within the allocated async timeout value. <add> */ <add> Object getAsyncResult(); <add> <ide> } <ide><path>spring-test-mvc/src/main/java/org/springframework/test/web/servlet/TestDispatcherServlet.java <ide> import java.io.IOException; <ide> import java.util.concurrent.Callable; <ide> import java.util.concurrent.CountDownLatch; <del>import java.util.concurrent.TimeUnit; <ide> <ide> import javax.servlet.ServletException; <ide> import javax.servlet.ServletRequest; <ide> public TestDispatcherServlet(WebApplicationContext webApplicationContext) { <ide> super(webApplicationContext); <ide> } <ide> <del> protected DefaultMvcResult getMvcResult(ServletRequest request) { <del> return (DefaultMvcResult) request.getAttribute(MockMvc.MVC_RESULT_ATTRIBUTE); <del> } <del> <ide> @Override <ide> protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { <ide> <del> WebAsyncManager asyncManager = WebAsyncUtils.getAsyncManager(request); <add> CountDownLatch latch = registerAsyncInterceptors(request); <add> getMvcResult(request).setAsyncResultLatch(latch); <ide> <del> TestCallableInterceptor callableInterceptor = new TestCallableInterceptor(); <del> asyncManager.registerCallableInterceptor("mock-mvc", callableInterceptor); <add> super.service(request, response); <add> } <ide> <del> TestDeferredResultInterceptor deferredResultInterceptor = new TestDeferredResultInterceptor(); <del> asyncManager.registerDeferredResultInterceptor("mock-mvc", deferredResultInterceptor); <add> private CountDownLatch registerAsyncInterceptors(HttpServletRequest request) { <ide> <del> super.service(request, response); <add> final CountDownLatch asyncResultLatch = new CountDownLatch(1); <add> <add> WebAsyncManager asyncManager = WebAsyncUtils.getAsyncManager(request); <ide> <del> // TODO: add CountDownLatch to DeferredResultInterceptor and wait in request().asyncResult(..) <add> asyncManager.registerCallableInterceptor("mockmvc", new CallableProcessingInterceptor() { <add> public void preProcess(NativeWebRequest request, Callable<?> task) throws Exception { } <add> public void postProcess(NativeWebRequest request, Callable<?> task, Object value) throws Exception { <add> asyncResultLatch.countDown(); <add> } <add> }); <ide> <del> Object handler = getMvcResult(request).getHandler(); <del> if (asyncManager.isConcurrentHandlingStarted() && !deferredResultInterceptor.wasInvoked) { <del> if (!callableInterceptor.await()) { <del> throw new ServletException( <del> "Gave up waiting on Callable from [" + handler.getClass().getName() + "] to complete"); <add> asyncManager.registerDeferredResultInterceptor("mockmvc", new DeferredResultProcessingInterceptor() { <add> public void preProcess(NativeWebRequest request, DeferredResult<?> result) throws Exception { } <add> public void postProcess(NativeWebRequest request, DeferredResult<?> result, Object value) throws Exception { <add> asyncResultLatch.countDown(); <ide> } <del> } <add> public void afterExpiration(NativeWebRequest request, DeferredResult<?> result) throws Exception { } <add> }); <add> <add> return asyncResultLatch; <add> } <add> <add> protected DefaultMvcResult getMvcResult(ServletRequest request) { <add> return (DefaultMvcResult) request.getAttribute(MockMvc.MVC_RESULT_ATTRIBUTE); <ide> } <ide> <ide> @Override <ide> protected ModelAndView processHandlerException(HttpServletRequest request, HttpS <ide> return mav; <ide> } <ide> <del> <del> private final class TestCallableInterceptor implements CallableProcessingInterceptor { <del> <del> private final CountDownLatch latch = new CountDownLatch(1); <del> <del> private boolean await() { <del> try { <del> return this.latch.await(5, TimeUnit.SECONDS); <del> } <del> catch (InterruptedException e) { <del> return false; <del> } <del> } <del> <del> public void preProcess(NativeWebRequest request, Callable<?> task) { } <del> <del> public void postProcess(NativeWebRequest request, Callable<?> task, Object concurrentResult) { <del> this.latch.countDown(); <del> } <del> } <del> <del> private final class TestDeferredResultInterceptor implements DeferredResultProcessingInterceptor { <del> <del> private boolean wasInvoked; <del> <del> public void preProcess(NativeWebRequest request, DeferredResult<?> deferredResult) { <del> this.wasInvoked = true; <del> } <del> <del> public void postProcess(NativeWebRequest request, DeferredResult<?> deferredResult, Object concurrentResult) { } <del> <del> public void afterExpiration(NativeWebRequest request, DeferredResult<?> deferredResult) { } <del> } <del> <ide> } <ide><path>spring-test-mvc/src/main/java/org/springframework/test/web/servlet/request/MockAsyncContext.java <ide> class MockAsyncContext implements AsyncContext { <ide> <ide> private String dispatchedPath; <ide> <del> private long timeout = 10 * 60 * 1000L; // 10 seconds is Tomcat's default <add> private long timeout = 10 * 1000L; // 10 seconds is Tomcat's default <ide> <ide> <ide> public MockAsyncContext(ServletRequest request, ServletResponse response) { <ide><path>spring-test-mvc/src/main/java/org/springframework/test/web/servlet/result/RequestResultMatchers.java <ide> import org.springframework.test.web.servlet.ResultMatcher; <ide> import org.springframework.web.context.request.async.AsyncTask; <ide> import org.springframework.web.context.request.async.DeferredResult; <del>import org.springframework.web.context.request.async.WebAsyncManager; <del>import org.springframework.web.context.request.async.WebAsyncUtils; <ide> <ide> /** <ide> * Factory for assertions on the request. An instance of this class is <ide> public <T> ResultMatcher asyncResult(final Matcher<T> matcher) { <ide> @SuppressWarnings("unchecked") <ide> public void match(MvcResult result) { <ide> HttpServletRequest request = result.getRequest(); <del> WebAsyncManager asyncManager = WebAsyncUtils.getAsyncManager(request); <ide> MatcherAssert.assertThat("Async started", request.isAsyncStarted(), equalTo(true)); <del> MatcherAssert.assertThat("Async result", (T) asyncManager.getConcurrentResult(), matcher); <add> MatcherAssert.assertThat("Async result", (T) result.getAsyncResult(), matcher); <ide> } <ide> }; <ide> } <ide><path>spring-test-mvc/src/test/java/org/springframework/test/web/servlet/StubMvcResult.java <ide> public void setResponse(MockHttpServletResponse response) { <ide> this.response = response; <ide> } <ide> <add> public Object getAsyncResult() { <add> return null; <add> } <add> <ide> }
6
Python
Python
avoid global variables in resnet construction
7a2575852af0f2a6c9e806d50d83bb6188ae8f8f
<ide><path>official/vision/image_classification/resnet/resnet_model.py <ide> from tensorflow.python.keras import regularizers <ide> from official.vision.image_classification.resnet import imagenet_preprocessing <ide> <del>L2_WEIGHT_DECAY = 1e-4 <del>BATCH_NORM_DECAY = 0.9 <del>BATCH_NORM_EPSILON = 1e-5 <del> <ide> layers = tf.keras.layers <ide> <ide> <del>def _gen_l2_regularizer(use_l2_regularizer=True): <del> return regularizers.l2(L2_WEIGHT_DECAY) if use_l2_regularizer else None <add>def _gen_l2_regularizer(use_l2_regularizer=True, l2_weight_decay=1e-4): <add> return regularizers.l2(l2_weight_decay) if use_l2_regularizer else None <ide> <ide> <ide> def identity_block(input_tensor, <ide> kernel_size, <ide> filters, <ide> stage, <ide> block, <del> use_l2_regularizer=True): <add> use_l2_regularizer=True, <add> batch_norm_decay=0.9, <add> batch_norm_epsilon=1e-5): <ide> """The identity block is the block that has no conv layer at shortcut. <ide> <ide> Args: <ide> def identity_block(input_tensor, <ide> stage: integer, current stage label, used for generating layer names <ide> block: 'a','b'..., current block label, used for generating layer names <ide> use_l2_regularizer: whether to use L2 regularizer on Conv layer. <add> batch_norm_decay: Moment of batch norm layers. <add> batch_norm_epsilon: Epsilon of batch borm layers. <ide> <ide> Returns: <ide> Output tensor for the block. <ide> def identity_block(input_tensor, <ide> input_tensor) <ide> x = layers.BatchNormalization( <ide> axis=bn_axis, <del> momentum=BATCH_NORM_DECAY, <del> epsilon=BATCH_NORM_EPSILON, <add> momentum=batch_norm_decay, <add> epsilon=batch_norm_epsilon, <ide> name=bn_name_base + '2a')( <ide> x) <ide> x = layers.Activation('relu')(x) <ide> def identity_block(input_tensor, <ide> x) <ide> x = layers.BatchNormalization( <ide> axis=bn_axis, <del> momentum=BATCH_NORM_DECAY, <del> epsilon=BATCH_NORM_EPSILON, <add> momentum=batch_norm_decay, <add> epsilon=batch_norm_epsilon, <ide> name=bn_name_base + '2b')( <ide> x) <ide> x = layers.Activation('relu')(x) <ide> def identity_block(input_tensor, <ide> x) <ide> x = layers.BatchNormalization( <ide> axis=bn_axis, <del> momentum=BATCH_NORM_DECAY, <del> epsilon=BATCH_NORM_EPSILON, <add> momentum=batch_norm_decay, <add> epsilon=batch_norm_epsilon, <ide> name=bn_name_base + '2c')( <ide> x) <ide> <ide> def conv_block(input_tensor, <ide> stage, <ide> block, <ide> strides=(2, 2), <del> use_l2_regularizer=True): <add> use_l2_regularizer=True, <add> batch_norm_decay=0.9, <add> batch_norm_epsilon=1e-5): <ide> """A block that has a conv layer at shortcut. <ide> <ide> Note that from stage 3, <ide> def conv_block(input_tensor, <ide> block: 'a','b'..., current block label, used for generating layer names <ide> strides: Strides for the second conv layer in the block. <ide> use_l2_regularizer: whether to use L2 regularizer on Conv layer. <add> batch_norm_decay: Moment of batch norm layers. <add> batch_norm_epsilon: Epsilon of batch borm layers. <ide> <ide> Returns: <ide> Output tensor for the block. <ide> def conv_block(input_tensor, <ide> input_tensor) <ide> x = layers.BatchNormalization( <ide> axis=bn_axis, <del> momentum=BATCH_NORM_DECAY, <del> epsilon=BATCH_NORM_EPSILON, <add> momentum=batch_norm_decay, <add> epsilon=batch_norm_epsilon, <ide> name=bn_name_base + '2a')( <ide> x) <ide> x = layers.Activation('relu')(x) <ide> def conv_block(input_tensor, <ide> x) <ide> x = layers.BatchNormalization( <ide> axis=bn_axis, <del> momentum=BATCH_NORM_DECAY, <del> epsilon=BATCH_NORM_EPSILON, <add> momentum=batch_norm_decay, <add> epsilon=batch_norm_epsilon, <ide> name=bn_name_base + '2b')( <ide> x) <ide> x = layers.Activation('relu')(x) <ide> def conv_block(input_tensor, <ide> x) <ide> x = layers.BatchNormalization( <ide> axis=bn_axis, <del> momentum=BATCH_NORM_DECAY, <del> epsilon=BATCH_NORM_EPSILON, <add> momentum=batch_norm_decay, <add> epsilon=batch_norm_epsilon, <ide> name=bn_name_base + '2c')( <ide> x) <ide> <ide> def conv_block(input_tensor, <ide> input_tensor) <ide> shortcut = layers.BatchNormalization( <ide> axis=bn_axis, <del> momentum=BATCH_NORM_DECAY, <del> epsilon=BATCH_NORM_EPSILON, <add> momentum=batch_norm_decay, <add> epsilon=batch_norm_epsilon, <ide> name=bn_name_base + '1')( <ide> shortcut) <ide> <ide> def conv_block(input_tensor, <ide> def resnet50(num_classes, <ide> batch_size=None, <ide> use_l2_regularizer=True, <del> rescale_inputs=False): <add> rescale_inputs=False, <add> batch_norm_decay=0.9, <add> batch_norm_epsilon=1e-5): <ide> """Instantiates the ResNet50 architecture. <ide> <ide> Args: <ide> num_classes: `int` number of classes for image classification. <ide> batch_size: Size of the batches for each step. <ide> use_l2_regularizer: whether to use L2 regularizer on Conv/Dense layer. <ide> rescale_inputs: whether to rescale inputs from 0 to 1. <add> batch_norm_decay: Moment of batch norm layers. <add> batch_norm_epsilon: Epsilon of batch borm layers. <ide> <ide> Returns: <ide> A Keras model instance. <ide> def resnet50(num_classes, <ide> else: # channels_last <ide> bn_axis = 3 <ide> <add> block_config = dict( <add> use_l2_regularizer=use_l2_regularizer, <add> batch_norm_decay=batch_norm_decay, <add> batch_norm_epsilon=batch_norm_epsilon) <ide> x = layers.ZeroPadding2D(padding=(3, 3), name='conv1_pad')(x) <ide> x = layers.Conv2D( <ide> 64, (7, 7), <ide> def resnet50(num_classes, <ide> x) <ide> x = layers.BatchNormalization( <ide> axis=bn_axis, <del> momentum=BATCH_NORM_DECAY, <del> epsilon=BATCH_NORM_EPSILON, <add> momentum=batch_norm_decay, <add> epsilon=batch_norm_epsilon, <ide> name='bn_conv1')( <ide> x) <ide> x = layers.Activation('relu')(x) <ide> x = layers.MaxPooling2D((3, 3), strides=(2, 2), padding='same')(x) <ide> <ide> x = conv_block( <del> x, <del> 3, [64, 64, 256], <del> stage=2, <del> block='a', <del> strides=(1, 1), <del> use_l2_regularizer=use_l2_regularizer) <del> x = identity_block( <del> x, <del> 3, [64, 64, 256], <del> stage=2, <del> block='b', <del> use_l2_regularizer=use_l2_regularizer) <del> x = identity_block( <del> x, <del> 3, [64, 64, 256], <del> stage=2, <del> block='c', <del> use_l2_regularizer=use_l2_regularizer) <del> <del> x = conv_block( <del> x, <del> 3, [128, 128, 512], <del> stage=3, <del> block='a', <del> use_l2_regularizer=use_l2_regularizer) <del> x = identity_block( <del> x, <del> 3, [128, 128, 512], <del> stage=3, <del> block='b', <del> use_l2_regularizer=use_l2_regularizer) <del> x = identity_block( <del> x, <del> 3, [128, 128, 512], <del> stage=3, <del> block='c', <del> use_l2_regularizer=use_l2_regularizer) <del> x = identity_block( <del> x, <del> 3, [128, 128, 512], <del> stage=3, <del> block='d', <del> use_l2_regularizer=use_l2_regularizer) <del> <del> x = conv_block( <del> x, <del> 3, [256, 256, 1024], <del> stage=4, <del> block='a', <del> use_l2_regularizer=use_l2_regularizer) <del> x = identity_block( <del> x, <del> 3, [256, 256, 1024], <del> stage=4, <del> block='b', <del> use_l2_regularizer=use_l2_regularizer) <del> x = identity_block( <del> x, <del> 3, [256, 256, 1024], <del> stage=4, <del> block='c', <del> use_l2_regularizer=use_l2_regularizer) <del> x = identity_block( <del> x, <del> 3, [256, 256, 1024], <del> stage=4, <del> block='d', <del> use_l2_regularizer=use_l2_regularizer) <del> x = identity_block( <del> x, <del> 3, [256, 256, 1024], <del> stage=4, <del> block='e', <del> use_l2_regularizer=use_l2_regularizer) <del> x = identity_block( <del> x, <del> 3, [256, 256, 1024], <del> stage=4, <del> block='f', <del> use_l2_regularizer=use_l2_regularizer) <del> <del> x = conv_block( <del> x, <del> 3, [512, 512, 2048], <del> stage=5, <del> block='a', <del> use_l2_regularizer=use_l2_regularizer) <del> x = identity_block( <del> x, <del> 3, [512, 512, 2048], <del> stage=5, <del> block='b', <del> use_l2_regularizer=use_l2_regularizer) <del> x = identity_block( <del> x, <del> 3, [512, 512, 2048], <del> stage=5, <del> block='c', <del> use_l2_regularizer=use_l2_regularizer) <add> x, 3, [64, 64, 256], stage=2, block='a', strides=(1, 1), **block_config) <add> x = identity_block(x, 3, [64, 64, 256], stage=2, block='b', **block_config) <add> x = identity_block(x, 3, [64, 64, 256], stage=2, block='c', **block_config) <add> <add> x = conv_block(x, 3, [128, 128, 512], stage=3, block='a', **block_config) <add> x = identity_block(x, 3, [128, 128, 512], stage=3, block='b', **block_config) <add> x = identity_block(x, 3, [128, 128, 512], stage=3, block='c', **block_config) <add> x = identity_block(x, 3, [128, 128, 512], stage=3, block='d', **block_config) <add> <add> x = conv_block(x, 3, [256, 256, 1024], stage=4, block='a', **block_config) <add> x = identity_block(x, 3, [256, 256, 1024], stage=4, block='b', **block_config) <add> x = identity_block(x, 3, [256, 256, 1024], stage=4, block='c', **block_config) <add> x = identity_block(x, 3, [256, 256, 1024], stage=4, block='d', **block_config) <add> x = identity_block(x, 3, [256, 256, 1024], stage=4, block='e', **block_config) <add> x = identity_block(x, 3, [256, 256, 1024], stage=4, block='f', **block_config) <add> <add> x = conv_block(x, 3, [512, 512, 2048], stage=5, block='a', **block_config) <add> x = identity_block(x, 3, [512, 512, 2048], stage=5, block='b', **block_config) <add> x = identity_block(x, 3, [512, 512, 2048], stage=5, block='c', **block_config) <ide> <ide> x = layers.GlobalAveragePooling2D()(x) <ide> x = layers.Dense( <ide><path>official/vision/image_classification/resnet/resnet_runnable.py <ide> def step_fn(inputs): <ide> loss = tf.reduce_sum(prediction_loss) * (1.0 / <ide> self.flags_obj.batch_size) <ide> num_replicas = self.strategy.num_replicas_in_sync <del> <add> l2_weight_decay = 1e-4 <ide> if self.flags_obj.single_l2_loss_op: <del> l2_loss = resnet_model.L2_WEIGHT_DECAY * 2 * tf.add_n([ <add> l2_loss = l2_weight_decay * 2 * tf.add_n([ <ide> tf.nn.l2_loss(v) <ide> for v in self.model.trainable_variables <ide> if 'bn' not in v.name
2
Javascript
Javascript
handle submit events
9dcb6813beeb1092b80dca7d83d36e274acd79a4
<ide><path>packages/sproutcore-views/lib/system/event_dispatcher.js <ide> SC.EventDispatcher = SC.Object.extend( <ide> focusout : 'focusOut', <ide> mouseenter : 'mouseEnter', <ide> mouseleave : 'mouseLeave', <add> submit : 'submit', <ide> change : 'change' <ide> }; <ide>
1
Python
Python
fix more formatting tests on win32
733feabcdba9aae2dbc1d71ec17c9b7483e68a1f
<ide><path>numpy/core/tests/test_print.py <ide> '(inf+1j)', complex(np.nan, 1): '(nan+1j)', complex(-np.inf, 1): <ide> '(-inf+1j)'} <ide> <add>if sys.platform == 'win32' and sys.version_info[0] <= 2 and sys.version_info[1] <= 5: <add> _REF[np.float32(1e10)] = '1e+010' <add>else: <add> _REF[np.float32(1e10)] = '1e+10' <add> <ide> def check_float_type(tp): <ide> for x in [0, 1,-1, 1e20] : <ide> assert_equal(str(tp(x)), str(float(x)), <ide> def check_float_type(tp): <ide> assert_equal(str(tp(1e10)), str(float('1e10')), <ide> err_msg='Failed str formatting for type %s' % tp) <ide> else: <del> if sys.platform == 'win32' and sys.version_info[0] <= 2 and sys.version_info[1] <= 5: <del> ref = '1e+010' <del> else: <del> ref = '1e+10' <del> assert_equal(str(tp(1e10)), ref, <add> assert_equal(str(tp(1e10)), _REF[tp(1e10)], <ide> err_msg='Failed str formatting for type %s' % tp) <ide> <ide> def test_float_types(): <ide> def check_complex_type(tp): <ide> assert_equal(str(tp(1e10)), str(complex(1e10)), <ide> err_msg='Failed str formatting for type %s' % tp) <ide> else: <del> if sys.platform == 'win32' and sys.version_info[0] <= 2 and sys.version_info[1] <= 5: <del> ref = '(1e+010+0j)' <del> else: <del> ref = '(1e+10+0j)' <del> assert_equal(str(tp(1e10)), ref, <add> assert_equal(str(tp(1e10)), _REF[tp(1e10)], <ide> err_msg='Failed str formatting for type %s' % tp) <ide> <ide> def test_complex_types():
1
PHP
PHP
add hal+json, hal+xml, and ld+json
b195583b5106fc1d9f5b52ae51fc0853862f1fca
<ide><path>src/Http/Response.php <ide> class Response implements ResponseInterface <ide> 'gz' => 'application/x-gzip', <ide> 'bz2' => 'application/x-bzip', <ide> '7z' => 'application/x-7z-compressed', <add> 'hal+json' => ['application/hal+json', 'application/vnd.hal+json'], <add> 'hal+xml' => ['application/hal+xml', 'application/vnd.hal+xml'], <ide> 'hdf' => 'application/x-hdf', <ide> 'hqx' => 'application/mac-binhex40', <ide> 'ico' => 'image/x-icon', <ide> class Response implements ResponseInterface <ide> 'js' => 'application/javascript', <ide> 'jsonapi' => 'application/vnd.api+json', <ide> 'latex' => 'application/x-latex', <add> 'ld+json' => 'application/ld+json', <ide> 'lha' => 'application/octet-stream', <ide> 'lsp' => 'application/x-lisp', <ide> 'lzh' => 'application/octet-stream',
1
Ruby
Ruby
add arm detection from linuxbrew
569c80323b7b28028552e21759790b83f5b305b3
<ide><path>Library/Homebrew/hardware.rb <ide> def ppc? <ide> type == :ppc <ide> end <ide> <add> def arm? <add> type == :arm <add> end <add> <ide> def features <ide> [] <ide> end
1
Python
Python
fix add_special_tokens on fast tokenizers
5e737018e1fcb22c8b76052058279552a8d6c806
<ide><path>src/transformers/tokenization_utils.py <ide> def add_tokens(self, new_tokens: List[Union[str, AddedTokenFast]]) -> int: <ide> <ide> def add_special_tokens(self, special_tokens_dict: dict) -> int: <ide> # Map special tokens to class attributes (self.pad_token...) <del> num_added_tokens = super().add_special_tokens(special_tokens_dict) <add> super().add_special_tokens(special_tokens_dict) <ide> <ide> # If the backend tokenizer the only specificities of special tokens are that <ide> # - they will never be processed by the model, and <ide> # - they will be removed while decoding. <ide> # But they are not mapped to special attributes in the backend so we can just <ide> # send a list. <del> tokens = flatten(special_tokens_dict.values()) <del> self._tokenizer.add_special_tokens(tokens) <add> tokens = [] <add> for token in special_tokens_dict.values(): <add> if isinstance(token, list): <add> tokens += token <add> else: <add> tokens += [token] <add> num_added_tokens = self._tokenizer.add_special_tokens(tokens) <ide> <ide> return num_added_tokens <ide> <ide><path>tests/test_tokenization_fast.py <ide> def assert_add_tokens(self, tokenizer_r): <ide> self.assertEqual(len(tokenizer_r), vocab_size + 3) <ide> <ide> self.assertEqual(tokenizer_r.add_special_tokens({}), 0) <add> self.assertEqual(tokenizer_r.add_special_tokens({"bos_token": "[BOS]", "eos_token": "[EOS]"}), 2) <ide> self.assertRaises( <ide> AssertionError, tokenizer_r.add_special_tokens, {"additional_special_tokens": "<testtoken1>"} <ide> ) <ide> self.assertEqual(tokenizer_r.add_special_tokens({"additional_special_tokens": ["<testtoken2>"]}), 1) <ide> self.assertEqual( <ide> tokenizer_r.add_special_tokens({"additional_special_tokens": ["<testtoken3>", "<testtoken4>"]}), 2 <ide> ) <del> self.assertEqual(len(tokenizer_r), vocab_size + 6) <add> self.assertEqual(len(tokenizer_r), vocab_size + 8) <ide> <ide> def assert_offsets_mapping(self, tokenizer_r): <ide> text = "Wonderful no inspiration example with subtoken"
2
Ruby
Ruby
fix collectionassociation docs
3ef1f9448332d8e73676ceb15e94d5482c75f1d3
<ide><path>activerecord/lib/active_record/associations/collection_association.rb <ide> module Associations <ide> # <ide> # CollectionAssociation class provides common methods to the collections <ide> # defined by +has_and_belongs_to_many+, +has_many+ or +has_many+ with <del> # +:through+ association option. <add> # +:through association+ option. <ide> # <ide> # You need to be careful with assumptions regarding the target: The proxy <ide> # does not fetch records from the database until it needs them, but new
1
Javascript
Javascript
improve non-padded strict tokens
95aeb62816dd970bb323106544c96522905eb1d7
<ide><path>moment.js <ide> parseTokenTwoDigits = /\d\d/, // 00 - 99 <ide> parseTokenThreeDigits = /\d{3}/, // 000 - 999 <ide> parseTokenFourDigits = /\d{4}/, // 0000 - 9999 <del> parseTokenSixDigits = /[+\-]?\d{6}/, // -999,999 - 999,999 <add> parseTokenSixDigits = /[+-]?\d{6}/, // -999,999 - 999,999 <add> parseTokenSignedNumber = /[+-]?\d+/, // -inf - inf <ide> <ide> // iso 8601 regex <ide> // 0000-00-00 0000-W00 or 0000-W00-0 + T + 00 or 00:00 or 00:00:00 or 00:00:00.000 + +00:00 or +0000 or +00) <ide> case 'GGGG': <ide> case 'gggg': <ide> return strict ? parseTokenFourDigits : parseTokenOneToFourDigits; <add> case 'Y': <add> case 'G': <add> case 'g': <add> return parseTokenSignedNumber; <ide> case 'YYYYYY': <ide> case 'YYYYY': <ide> case 'GGGGG': <ide> if (strict) { return parseTokenTwoDigits; } <ide> /* falls through */ <ide> case 'SSS': <add> if (strict) { return parseTokenThreeDigits; } <add> /* falls through */ <ide> case 'DDD': <del> return strict ? parseTokenThreeDigits : parseTokenOneToThreeDigits; <add> return parseTokenOneToThreeDigits; <ide> case 'MMM': <ide> case 'MMMM': <ide> case 'dd': <ide> case 'W': <ide> case 'e': <ide> case 'E': <del> return strict ? parseTokenOneDigit : parseTokenOneOrTwoDigits; <add> return parseTokenOneOrTwoDigits; <ide> default : <ide> a = new RegExp(regexpEscape(unescapeFormat(token.replace('\\', '')), "i")); <ide> return a; <ide><path>test/moment/create.js <ide> exports.create = { <ide> test.equal(moment(".*2010.*", ".*YYYY.*", true).year(), 2010, "valid format with regex chars on both sides"); <ide> <ide> //strict tokens <add> test.equal(moment("-5-05-25", 'YYYY-MM-DD', true).isValid(), false, "invalid negative year"); <ide> test.equal(moment("2-05-25", 'YYYY-MM-DD', true).isValid(), false, "invalid one-digit year"); <ide> test.equal(moment("20-05-25", 'YYYY-MM-DD', true).isValid(), false, "invalid two-digit year"); <ide> test.equal(moment("201-05-25", 'YYYY-MM-DD', true).isValid(), false, "invalid three-digit year"); <add> test.equal(moment("2010-05-25", 'YYYY-MM-DD', true).isValid(), true, "valid four-digit year"); <add> test.equal(moment("22010-05-25", 'YYYY-MM-DD', true).isValid(), false, "invalid five-digit year"); <ide> <ide> test.equal(moment("12-05-25", 'YY-MM-DD', true).isValid(), true, "valid two-digit year"); <ide> test.equal(moment("2012-05-25", 'YY-MM-DD', true).isValid(), false, "invalid four-digit year"); <ide> <add> test.equal(moment("-5-05-25", 'Y-MM-DD', true).isValid(), true, "valid negative year"); <add> test.equal(moment("2-05-25", 'Y-MM-DD', true).isValid(), true, "valid one-digit year"); <add> test.equal(moment("20-05-25", 'Y-MM-DD', true).isValid(), true, "valid two-digit year"); <add> test.equal(moment("201-05-25", 'Y-MM-DD', true).isValid(), true, "valid three-digit year"); <add> <add> test.equal(moment("2012-5-25", 'YYYY-M-DD', true).isValid(), true, "valid one-digit month"); <ide> test.equal(moment("2012-5-25", 'YYYY-MM-DD', true).isValid(), false, "invalid one-digit month"); <add> test.equal(moment("2012-05-25", 'YYYY-M-DD', true).isValid(), true, "valid one-digit month"); <add> test.equal(moment("2012-05-25", 'YYYY-MM-DD', true).isValid(), true, "valid one-digit month"); <ide> <add> test.equal(moment("2012-05-2", 'YYYY-MM-D', true).isValid(), true, "valid one-digit day"); <ide> test.equal(moment("2012-05-2", 'YYYY-MM-DD', true).isValid(), false, "invalid one-digit day"); <add> test.equal(moment("2012-05-02", 'YYYY-MM-D', true).isValid(), true, "valid two-digit day"); <add> test.equal(moment("2012-05-02", 'YYYY-MM-DD', true).isValid(), true, "valid two-digit day"); <ide> <ide> test.equal(moment("+002012-05-25", 'YYYYY-MM-DD', true).isValid(), true, "valid six-digit year"); <ide> test.equal(moment("+2012-05-25", 'YYYYY-MM-DD', true).isValid(), false, "invalid four-digit year");
2
Javascript
Javascript
add visibility flag for hiding/unhiding trees
eb3181e7722905933da3b53ebff05339f12a3ba6
<ide><path>packages/react-reconciler/src/ReactFiberCompleteWork.new.js <ide> import { <ide> NoFlags, <ide> DidCapture, <ide> Snapshot, <add> Visibility, <ide> MutationMask, <ide> LayoutMask, <ide> PassiveMask, <ide> function completeWork( <ide> // TODO: Only schedule updates if not prevDidTimeout. <ide> if (nextDidTimeout) { <ide> // If this boundary just timed out, schedule an effect to attach a <del> // retry listener to the promise. This flag is also used to hide the <del> // primary children. <add> // retry listener to the promise. <add> // TODO: Move to passive phase <ide> workInProgress.flags |= Update; <ide> } <ide> } <ide> function completeWork( <ide> // primary children. In mutation mode, we also need the flag to <ide> // *unhide* children that were previously hidden, so check if this <ide> // is currently timed out, too. <del> workInProgress.flags |= Update; <add> workInProgress.flags |= Update | Visibility; <ide> } <ide> } <ide> if ( <ide> function completeWork( <ide> workInProgress.memoizedProps.suspenseCallback != null <ide> ) { <ide> // Always notify the callback <add> // TODO: Move to passive phase <ide> workInProgress.flags |= Update; <ide> } <ide> bubbleProperties(workInProgress); <ide> function completeWork( <ide> prevIsHidden !== nextIsHidden && <ide> newProps.mode !== 'unstable-defer-without-hiding' <ide> ) { <del> workInProgress.flags |= Update; <add> workInProgress.flags |= Update | Visibility; <ide> } <ide> } <ide> <ide><path>packages/react-reconciler/src/ReactFiberFlags.js <ide> * @flow <ide> */ <ide> <add>import {enableCreateEventHandleAPI} from 'shared/ReactFeatureFlags'; <add> <ide> export type Flags = number; <ide> <ide> // Don't change these two values. They're used by React Dev Tools. <del>export const NoFlags = /* */ 0b000000000000000000; <del>export const PerformedWork = /* */ 0b000000000000000001; <add>export const NoFlags = /* */ 0b0000000000000000000; <add>export const PerformedWork = /* */ 0b0000000000000000001; <ide> <ide> // You can change the rest (and add more). <del>export const Placement = /* */ 0b000000000000000010; <del>export const Update = /* */ 0b000000000000000100; <del>export const PlacementAndUpdate = /* */ 0b000000000000000110; <del>export const Deletion = /* */ 0b000000000000001000; <del>export const ContentReset = /* */ 0b000000000000010000; <del>export const Callback = /* */ 0b000000000000100000; <del>export const DidCapture = /* */ 0b000000000001000000; <del>export const Ref = /* */ 0b000000000010000000; <del>export const Snapshot = /* */ 0b000000000100000000; <del>export const Passive = /* */ 0b000000001000000000; <del>// TODO (effects) Remove this bit once the new reconciler is synced to the old. <del>export const PassiveUnmountPendingDev = /* */ 0b000010000000000000; <del>export const Hydrating = /* */ 0b000000010000000000; <del>export const HydratingAndUpdate = /* */ 0b000000010000000100; <add>export const Placement = /* */ 0b0000000000000000010; <add>export const Update = /* */ 0b0000000000000000100; <add>export const PlacementAndUpdate = /* */ 0b0000000000000000110; <add>export const Deletion = /* */ 0b0000000000000001000; <add>export const ContentReset = /* */ 0b0000000000000010000; <add>export const Callback = /* */ 0b0000000000000100000; <add>export const DidCapture = /* */ 0b0000000000001000000; <add>export const Ref = /* */ 0b0000000000010000000; <add>export const Snapshot = /* */ 0b0000000000100000000; <add>export const Passive = /* */ 0b0000000001000000000; <add>export const Hydrating = /* */ 0b0000000010000000000; <add>export const HydratingAndUpdate = /* */ 0b0000000010000000100; <add>export const Visibility = /* */ 0b0000000100000000000; <ide> <ide> // Passive & Update & Callback & Ref & Snapshot <del>export const LifecycleEffectMask = /* */ 0b000000001110100100; <add>export const LifecycleEffectMask = /* */ 0b0000000001110100100; <ide> <ide> // Union of all host effects <del>export const HostEffectMask = /* */ 0b000000011111111111; <add>export const HostEffectMask = /* */ 0b0000000111111111111; <ide> <ide> // These are not really side effects, but we still reuse this field. <del>export const Incomplete = /* */ 0b000000100000000000; <del>export const ShouldCapture = /* */ 0b000001000000000000; <del>export const ForceUpdateForLegacySuspense = /* */ 0b000100000000000000; <add>export const Incomplete = /* */ 0b0000001000000000000; <add>export const ShouldCapture = /* */ 0b0000010000000000000; <add>// TODO (effects) Remove this bit once the new reconciler is synced to the old. <add>export const PassiveUnmountPendingDev = /* */ 0b0000100000000000000; <add>export const ForceUpdateForLegacySuspense = /* */ 0b0001000000000000000; <ide> <ide> // Static tags describe aspects of a fiber that are not specific to a render, <ide> // e.g. a fiber uses a passive effect (even if there are no updates on this particular render). <ide> // This enables us to defer more work in the unmount case, <ide> // since we can defer traversing the tree during layout to look for Passive effects, <ide> // and instead rely on the static flag as a signal that there may be cleanup work. <del>export const PassiveStatic = /* */ 0b001000000000000000; <add>export const PassiveStatic = /* */ 0b0010000000000000000; <ide> <ide> // Union of side effect groupings as pertains to subtreeFlags <del>// TODO: Don't need to visit Placement during BeforeMutation phase <del>// TODO: Only need to visit Deletions during BeforeMutation phase if an element <del>// is focused. <del>export const BeforeMutationMask = /* */ 0b000000000100001010; <del>export const MutationMask = /* */ 0b000000010010011110; <del>export const LayoutMask = /* */ 0b000000000010100100; <del>export const PassiveMask = /* */ 0b000000001000001000; <add> <add>export const BeforeMutationMask = <add> Snapshot | <add> (enableCreateEventHandleAPI <add> ? // createEventHandle needs to visit deleted and hidden trees to <add> // fire beforeblur <add> // TODO: Only need to visit Deletions during BeforeMutation phase if an <add> // element is focused. <add> Deletion | Visibility <add> : 0); <add> <add>export const MutationMask = /* */ 0b0000000110010011110; <add>export const LayoutMask = /* */ 0b0000000000010100100; <add>export const PassiveMask = /* */ 0b0000000001000001000; <ide> <ide> // Union of tags that don't get reset on clones. <ide> // This allows certain concepts to persist without recalculting them, <ide> // e.g. whether a subtree contains passive effects or portals. <del>export const StaticMask = /* */ 0b001000000000000000; <add>export const StaticMask = /* */ 0b0010000000000000000; <ide> <ide> // These flags allow us to traverse to fibers that have effects on mount <ide> // without traversing the entire tree after every commit for <ide> // double invoking <del>export const MountLayoutDev = /* */ 0b010000000000000000; <del>export const MountPassiveDev = /* */ 0b100000000000000000; <add>export const MountLayoutDev = /* */ 0b0100000000000000000; <add>export const MountPassiveDev = /* */ 0b1000000000000000000; <ide><path>packages/react-reconciler/src/ReactFiberWorkLoop.new.js <ide> import { <ide> HostEffectMask, <ide> Hydrating, <ide> HydratingAndUpdate, <add> Visibility, <ide> BeforeMutationMask, <ide> MutationMask, <ide> LayoutMask, <ide> function commitBeforeMutationEffectsImpl(fiber: Fiber) { <ide> <ide> if (!shouldFireAfterActiveInstanceBlur && focusedInstanceHandle !== null) { <ide> // Check to see if the focused element was inside of a hidden (Suspense) subtree. <del> // TODO: Move this out of the hot path using a dedicated effect tag. <ide> if ( <add> // TODO: Can optimize this further with separate Hide and Show flags. We <add> // only care about Hide here. <add> (flags & Visibility) !== NoFlags && <ide> fiber.tag === SuspenseComponent && <ide> isSuspenseBoundaryBeingHidden(current, fiber) && <ide> doesFiberContain(fiber, focusedInstanceHandle)
3
Ruby
Ruby
fix inheritance in exceptions
b7f093925e7a751914f131aaecd8c080d3441c16
<ide><path>Library/Homebrew/exceptions.rb <del>class UsageError <RuntimeError; end <del>class FormulaUnspecifiedError <UsageError; end <del>class KegUnspecifiedError <UsageError; end <add>class UsageError < RuntimeError; end <add>class FormulaUnspecifiedError < UsageError; end <add>class KegUnspecifiedError < UsageError; end <ide> <del>class MultipleVersionsInstalledError <RuntimeError <add>class MultipleVersionsInstalledError < RuntimeError <ide> attr :name <ide> <ide> def initialize name <ide> def initialize name <ide> <ide> class NotAKegError < RuntimeError; end <ide> <del>class NoSuchKegError <RuntimeError <add>class NoSuchKegError < RuntimeError <ide> attr :name <ide> <ide> def initialize name
1
Python
Python
remove dummy inputs in layers
f3f19146f9c248b9d600c5767d1ad60dc9aa20da
<ide><path>keras/layers/convolutional.py <ide> def __init__(self, nb_filter, filter_length, <ide> self.input_length = input_length <ide> if self.input_dim: <ide> kwargs['input_shape'] = (self.input_length, self.input_dim) <del> self.input = K.placeholder(ndim=3) <ide> super(Convolution1D, self).__init__(**kwargs) <ide> <ide> def build(self): <ide> def __init__(self, nb_filter, nb_row, nb_col, <ide> self.constraints = [self.W_constraint, self.b_constraint] <ide> <ide> self.initial_weights = weights <del> self.input = K.placeholder(ndim=4) <ide> super(Convolution2D, self).__init__(**kwargs) <ide> <ide> def build(self): <ide> def __init__(self, nb_filter, kernel_dim1, kernel_dim2, kernel_dim3, <ide> self.constraints = [self.W_constraint, self.b_constraint] <ide> <ide> self.initial_weights = weights <del> self.input = K.placeholder(ndim=5) <ide> super(Convolution3D, self).__init__(**kwargs) <ide> <ide> def build(self): <ide> def __init__(self, pool_length=2, stride=None, <ide> self.pool_length = pool_length <ide> self.stride = stride <ide> self.st = (self.stride, 1) <del> self.input = K.placeholder(ndim=3) <ide> self.pool_size = (pool_length, 1) <ide> assert border_mode in {'valid', 'same'}, 'border_mode must be in {valid, same}' <ide> self.border_mode = border_mode <ide> class _Pooling2D(Layer): <ide> def __init__(self, pool_size=(2, 2), strides=None, border_mode='valid', <ide> dim_ordering='th', **kwargs): <ide> super(_Pooling2D, self).__init__(**kwargs) <del> self.input = K.placeholder(ndim=4) <ide> self.pool_size = tuple(pool_size) <ide> if strides is None: <ide> strides = self.pool_size <ide> class _Pooling3D(Layer): <ide> def __init__(self, pool_size=(2, 2, 2), strides=None, border_mode='valid', <ide> dim_ordering='th', **kwargs): <ide> super(_Pooling3D, self).__init__(**kwargs) <del> self.input = K.placeholder(ndim=5) <ide> self.pool_size = tuple(pool_size) <ide> if strides is None: <ide> strides = self.pool_size <ide> class UpSampling1D(Layer): <ide> def __init__(self, length=2, **kwargs): <ide> super(UpSampling1D, self).__init__(**kwargs) <ide> self.length = length <del> self.input = K.placeholder(ndim=3) <ide> <ide> @property <ide> def output_shape(self): <ide> class UpSampling2D(Layer): <ide> <ide> def __init__(self, size=(2, 2), dim_ordering='th', **kwargs): <ide> super(UpSampling2D, self).__init__(**kwargs) <del> self.input = K.placeholder(ndim=4) <ide> self.size = tuple(size) <ide> assert dim_ordering in {'tf', 'th'}, 'dim_ordering must be in {tf, th}' <ide> self.dim_ordering = dim_ordering <ide> def __init__(self, size=(2, 2, 2), dim_ordering='th', **kwargs): <ide> raise Exception(self.__class__.__name__ + <ide> ' is currently only working with Theano backend.') <ide> super(UpSampling3D, self).__init__(**kwargs) <del> self.input = K.placeholder(ndim=5) <ide> self.size = tuple(size) <ide> assert dim_ordering in {'tf', 'th'}, 'dim_ordering must be in {tf, th}' <ide> self.dim_ordering = dim_ordering <ide> class ZeroPadding1D(Layer): <ide> def __init__(self, padding=1, **kwargs): <ide> super(ZeroPadding1D, self).__init__(**kwargs) <ide> self.padding = padding <del> self.input = K.placeholder(ndim=3) <ide> <ide> @property <ide> def output_shape(self): <ide> class ZeroPadding2D(Layer): <ide> def __init__(self, padding=(1, 1), dim_ordering='th', **kwargs): <ide> super(ZeroPadding2D, self).__init__(**kwargs) <ide> self.padding = tuple(padding) <del> self.input = K.placeholder(ndim=4) <ide> assert dim_ordering in {'tf', 'th'}, 'dim_ordering must be in {tf, th}' <ide> self.dim_ordering = dim_ordering <ide> <ide> def __init__(self, padding=(1, 1, 1), dim_ordering='th', **kwargs): <ide> ' is currently only working with Theano backend.') <ide> super(ZeroPadding3D, self).__init__(**kwargs) <ide> self.padding = tuple(padding) <del> self.input = K.placeholder(ndim=5) <ide> assert dim_ordering in {'tf', 'th'}, 'dim_ordering must be in {tf, th}' <ide> self.dim_ordering = dim_ordering <ide> <ide><path>keras/layers/core.py <ide> class Masking(MaskedLayer): <ide> def __init__(self, mask_value=0., **kwargs): <ide> super(Masking, self).__init__(**kwargs) <ide> self.mask_value = mask_value <del> if (not hasattr(self, 'input')): <del> self.input = K.placeholder(ndim=3) <ide> <ide> def get_output_mask(self, train=False): <ide> X = self.get_input(train) <ide> def __init__(self, output_dim, init='glorot_uniform', activation='linear', weigh <ide> self.input_dim = input_dim <ide> if self.input_dim: <ide> kwargs['input_shape'] = (self.input_dim,) <del> self.input = K.placeholder(ndim=2) <ide> super(Dense, self).__init__(**kwargs) <ide> <ide> def build(self): <ide> def __init__(self, output_dim, <ide> self.input_length = input_length <ide> if self.input_dim: <ide> kwargs['input_shape'] = (self.input_length, self.input_dim) <del> self.input = K.placeholder(ndim=3) <ide> super(TimeDistributedDense, self).__init__(**kwargs) <ide> <ide> def build(self): <ide> def __init__(self, output_dim, nb_feature=4, <ide> self.input_dim = input_dim <ide> if self.input_dim: <ide> kwargs['input_shape'] = (self.input_dim,) <del> self.input = K.placeholder(ndim=2) <ide> super(MaxoutDense, self).__init__(**kwargs) <ide> <ide> def build(self): <ide> def __init__(self, init='glorot_uniform', transform_bias=-2, <ide> self.input_dim = input_dim <ide> if self.input_dim: <ide> kwargs['input_shape'] = (self.input_dim,) <del> self.input = K.placeholder(ndim=2) <ide> super(Highway, self).__init__(**kwargs) <ide> <ide> def build(self): <ide><path>keras/layers/recurrent.py <ide> def build(self): <ide> input_shape = self.input_shape <ide> input_dim = input_shape[2] <ide> self.input_dim = input_dim <del> self.input = K.placeholder(input_shape) <ide> <ide> self.W_z = self.init((input_dim, self.output_dim)) <ide> self.U_z = self.inner_init((self.output_dim, self.output_dim)) <ide> def build(self): <ide> input_shape = self.input_shape <ide> input_dim = input_shape[2] <ide> self.input_dim = input_dim <del> self.input = K.placeholder(input_shape) <ide> <ide> if self.stateful: <ide> self.reset_states()
3