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
Ruby
Ruby
use default_formula for bottles
a83baba8b50e29e680b89588ca19347ac0133608
<ide><path>Library/Homebrew/formula_installer.rb <ide> def check_requirements(req_map) <ide> raise UnsatisfiedRequirements, fatals <ide> end <ide> <del> def install_requirement_formula?(req, dependent, build) <del> req_dependency = req.to_dependency <add> def install_requirement_formula?(req_dependency, req, install_bottle_for_dependent) <ide> return false unless req_dependency <ide> return true unless req.satisfied? <ide> return false if req.run? <ide> return true if build_bottle? <ide> return true if req.satisfied_by_formula? <del> install_bottle_for?(dependent, build) <add> install_bottle_for_dependent <ide> end <ide> <ide> def runtime_requirements(formula) <ide> def expand_requirements <ide> runtime_requirements = runtime_requirements(f) <ide> f.recursive_requirements do |dependent, req| <ide> build = effective_build_options_for(dependent) <add> install_bottle_for_dependent = install_bottle_for?(dependent, build) <add> use_default_formula = install_bottle_for_dependent || build_bottle? <add> req_dependency = req.to_dependency(use_default_formula: use_default_formula) <ide> <ide> if (req.optional? || req.recommended?) && build.without?(req) <ide> Requirement.prune <del> elsif req.build? && install_bottle_for?(dependent, build) <add> elsif req.build? && install_bottle_for_dependent <ide> Requirement.prune <del> elsif install_requirement_formula?(req, dependent, build) <del> dep = req.to_dependency <del> deps.unshift(dep) <del> formulae.unshift(dep.to_formula) <add> elsif install_requirement_formula?(req_dependency, req, install_bottle_for_dependent) <add> deps.unshift(req_dependency) <add> formulae.unshift(req_dependency.to_formula) <ide> Requirement.prune <ide> elsif req.satisfied? <ide> Requirement.prune <del> elsif !runtime_requirements.include?(req) && install_bottle_for?(dependent, build) <add> elsif !runtime_requirements.include?(req) && install_bottle_for_dependent <ide> Requirement.prune <ide> else <ide> unsatisfied_reqs[dependent] << req <ide><path>Library/Homebrew/requirement.rb <ide> def satisfied_by_formula? <ide> !@formula.nil? <ide> end <ide> <del> def to_dependency <del> if formula =~ HOMEBREW_TAP_FORMULA_REGEX <add> def to_dependency(use_default_formula: false) <add> if use_default_formula && default_formula? <add> Dependency.new(self.class.default_formula, tags, method(:modify_build_environment), name) <add> elsif formula =~ HOMEBREW_TAP_FORMULA_REGEX <ide> TapDependency.new(formula, tags, method(:modify_build_environment), name) <ide> elsif formula <ide> Dependency.new(formula, tags, method(:modify_build_environment), name) <ide><path>Library/Homebrew/test/formula_installer_spec.rb <ide> class #{Formulary.class_s(dep_name)} < Formula <ide> }.to raise_error(CannotInstallFormulaError) <ide> end <ide> <del> describe "#install_requirement_formula?" do <add> describe "#install_requirement_formula?", :focus do <ide> before do <ide> @requirement = Python3Requirement.new <add> @requirement_dependency = @requirement.to_dependency <add> @install_bottle_for_dependent = false <ide> allow(@requirement).to receive(:satisfied?).and_return(satisfied?) <ide> allow(@requirement).to receive(:satisfied_by_formula?).and_return(satisfied_by_formula?) <del> allow_any_instance_of(Dependency).to receive(:installed?).and_return(installed?) <ide> @dependent = formula do <ide> url "foo" <ide> version "0.1" <ide> depends_on :python3 <ide> end <del> @build = BuildOptions.new [], [] <ide> @fi = FormulaInstaller.new(@dependent) <ide> end <ide> <del> subject { @fi.install_requirement_formula?(@requirement, @dependent, @build) } <add> subject { @fi.install_requirement_formula?(@requirement_dependency, @requirement, @install_bottle_for_dependent) } <ide> <ide> context "it returns false when requirement is satisfied" do <ide> let(:satisfied?) { true }
3
Ruby
Ruby
fix merge conflicts for
4c42c89b0482f8ccde625e4d4699cd14f5f20afc
<ide><path>activerecord/lib/active_record/connection_adapters/abstract_mysql_adapter.rb <ide> def collation <ide> show_variable 'collation_database' <ide> end <ide> <del> def tables(name = nil) # :nodoc: <del> select_values("SHOW FULL TABLES", 'SCHEMA') <add> def tables(name = nil, database = nil, like = nil) #:nodoc: <add> database ||= current_database <add> <add> sql = "SELECT table_name FROM information_schema.tables " <add> sql << "WHERE table_schema = #{quote(database)}" <add> sql << " AND table_name = #{quote(like)}" if like <add> <add> execute_and_free(sql, 'SCHEMA') do |result| <add> result.collect(&:first) <add> end <ide> end <ide> alias data_sources tables <ide> <ide><path>activerecord/test/cases/test_case.rb <ide> def clear_log; self.log = []; self.log_all = []; end <ide> # ignored SQL, or better yet, use a different notification for the queries <ide> # instead examining the SQL content. <ide> oracle_ignored = [/^select .*nextval/i, /^SAVEPOINT/, /^ROLLBACK TO/, /^\s*select .* from all_triggers/im, /^\s*select .* from all_constraints/im, /^\s*select .* from all_tab_cols/im] <del> mysql_ignored = [/^SHOW FULL TABLES/i, /^SHOW FULL FIELDS/, /^SHOW CREATE TABLE /i, /^SHOW VARIABLES /, /^\s*SELECT (?:column_name|table_name)\b.*\bFROM information_schema\.(?:key_column_usage|tables)\b/im] <add> mysql_ignored = [/^SHOW FULL TABLES/i, /^SHOW FULL FIELDS/, /^SHOW CREATE TABLE /i, /^SHOW VARIABLES /, /^SELECT DATABASE\(\) as db$/, /^SELECT table_name FROM information_schema\.tables/] <ide> postgresql_ignored = [/^\s*select\b.*\bfrom\b.*pg_namespace\b/im, /^\s*select tablename\b.*from pg_tables\b/im, /^\s*select\b.*\battname\b.*\bfrom\b.*\bpg_attribute\b/im, /^SHOW search_path/i] <ide> sqlite3_ignored = [/^\s*SELECT name\b.*\bFROM sqlite_master/im, /^\s*SELECT sql\b.*\bFROM sqlite_master/im] <ide>
2
Text
Text
update docs on object-level permissions
73019f91fe55f2ac16ce179917f686bf1a931597
<ide><path>docs/api-guide/permissions.md <ide> If any permission check fails an `exceptions.PermissionDenied` exception will be <ide> <ide> REST framework permissions also support object-level permissioning. Object level permissions are used to determine if a user should be allowed to act on a particular object, which will typically be a model instance. <ide> <del>Object level permissions are run by REST framework's generic views when `.get_object()` is called. As with view level permissions, an `exceptions.PermissionDenied` exception will be raised if the user is not allowed to act on the given object. <add>Object level permissions are run by REST framework's generic views when `.get_object()` is called. <add>As with view level permissions, an `exceptions.PermissionDenied` exception will be raised if the user is not allowed to act on the given object. <add> <add>If you're writing your own views and want to enforce object level permissions, <add>you'll need to explicitly call the `.check_object_permissions(request, obj)` method on the view at the point at which you've retrieved the object. <add>This will either raise a `PermissionDenied` or `NotAuthenticated` exception, or simply return if the view has the appropraite permissions. <ide> <ide> ## Setting the permission policy <ide>
1
Ruby
Ruby
remove useless parens
0eefd8dc4884217e70ed99fb7d8ae272c7ce2d12
<ide><path>railties/test/railties/shared_tests.rb <ide> class CreateYaffles < ActiveRecord::Migration <ide> bukkits_migration_order = output.index(output.detect{|o| /NOTE: Migration 3_create_sessions.rb from bukkits has been skipped/ =~ o }) <ide> assert_not_nil yaffle_migration_order, "Expected migration to be copied" <ide> assert_not_nil bukkits_migration_order, "Expected migration to be skipped" <del> assert_equal((railties.index('acts_as_yaffle') > railties.index('bukkits')) , (yaffle_migration_order > bukkits_migration_order)) <add> assert_equal(railties.index('acts_as_yaffle') > railties.index('bukkits'), yaffle_migration_order > bukkits_migration_order) <ide> <ide> migrations_count = Dir["#{app_path}/db/migrate/*.rb"].length <ide> output = `bundle exec rake railties:install:migrations`
1
Javascript
Javascript
make better use of the built-in stability check
a0e85833a7438279ccd1a99dea3e8d6f78440d06
<ide><path>packages/ember-htmlbars/lib/keywords/component.js <ide> export default { <del> setupState: function(state, env, scope, params, hash) { <del> state.lastComponentPath = state.componentPath; <del> state.componentPath = env.hooks.getValue(params[0]); <del> }, <del> <del> isStable: function(state, env, scope, params, hash) { <del> return state.componentPath === state.lastComponentPath; <add> setupState: function(lastState, env, scope, params, hash) { <add> return { <add> componentPath: env.hooks.getValue(params[0]), <add> componentNode: lastState && lastState.componentNode <add> }; <ide> }, <ide> <ide> render: function(morph, env, scope, params, hash, template, inverse, visitor) { <ide><path>packages/ember-htmlbars/lib/keywords/outlet.js <ide> export default { <ide> toRender.template = topLevelViewTemplate; <ide> } <ide> <del> state.lastOutletState = state.outletState; <del> state.outletState = selectedOutletState; <add> return { outletState: selectedOutletState }; <ide> }, <ide> <ide> updateEnv: function(state, env) { <ide><path>packages/ember-htmlbars/lib/keywords/partial.js <ide> import { internal } from "htmlbars-runtime"; <ide> <ide> export default { <ide> setupState: function(state, env, scope, params, hash) { <del> state.lastPartialName = state.partialName; <del> state.partialName = env.hooks.getValue(params[0]); <del> }, <del> <del> isStable: function(state, env) { <del> return state.lastPartialName === state.partialName; <add> return { partialName: env.hooks.getValue(params[0]) }; <ide> }, <ide> <ide> render: function(renderNode, env, scope, params, hash, template, inverse, visitor) { <ide><path>packages/ember-htmlbars/lib/keywords/view.js <ide> import ComponentNode from "ember-htmlbars/system/component-node"; <ide> export default { <ide> setupState: function(state, env, scope, params, hash) { <ide> var read = env.hooks.getValue; <del> state.parentView = read(scope.locals.view); <ide> <del> state.lastViewClassOrInstance = state.viewClassOrInstance; <del> state.viewClassOrInstance = getView(read(params[0]), env.container); <del> }, <del> <del> isStable: function(state, env, scope, params, hash) { <del> return state.lastViewClassOrInstance === state.viewClassOrInstance; <add> return { <add> parentView: read(scope.locals.view), <add> viewClassOrInstance: getView(read(params[0]), env.container) <add> }; <ide> }, <ide> <ide> rerender: function(morph, env, scope, params, hash, template, inverse, visitor) { <ide><path>packages/ember-htmlbars/lib/keywords/with.js <ide> export default { <ide> }); <ide> <ide> params[0] = controllerInstance; <del> state.controller = controllerInstance; <add> return { controller: controllerInstance }; <ide> } <add> <add> return { controller: null }; <ide> }, <ide> <ide> isStable: function() {
5
Javascript
Javascript
add mocks for packages to resolution responses
5ca519de299e6f0d34f795d314d2aa6fc6199ac4
<ide><path>packager/react-packager/src/DependencyResolver/DependencyGraph/ResolutionRequest.js <ide> class ResolutionRequest { <ide> ).then((dependencies) => [depNames, dependencies]) <ide> ).then(([depNames, dependencies]) => { <ide> if (allMocks) { <del> return mod.getName().then(name => { <del> if (allMocks[name]) { <del> const mockModule = <del> this._moduleCache.getModule(allMocks[name]); <del> depNames.push(name); <del> dependencies.push(mockModule); <del> mocks[name] = allMocks[name]; <del> } <add> const list = [mod.getName()]; <add> const pkg = mod.getPackage(); <add> if (pkg) { <add> list.push(pkg.getName()); <add> } <add> return Promise.all(list).then(names => { <add> names.forEach(name => { <add> if (allMocks[name] && !mocks[name]) { <add> const mockModule = <add> this._moduleCache.getModule(allMocks[name]); <add> depNames.push(name); <add> dependencies.push(mockModule); <add> mocks[name] = allMocks[name]; <add> } <add> }); <ide> return [depNames, dependencies]; <ide> }); <ide> } <ide> class ResolutionRequest { <ide> // module backing them. If a dependency cannot be found but there <ide> // exists a mock with the desired ID, resolve it and add it as <ide> // a dependency. <del> if (allMocks && allMocks[name]) { <add> if (allMocks && allMocks[name] && !mocks[name]) { <ide> const mockModule = this._moduleCache.getModule(allMocks[name]); <ide> mocks[name] = allMocks[name]; <ide> return filteredPairs.push([name, mockModule]);
1
Javascript
Javascript
fix alphabetical order of loader examples
fd5934e6577ff6153bd33d746cf359f45a779764
<ide><path>examples/files.js <ide> var files = { <ide> "webgl_loader_mmd_pose", <ide> "webgl_loader_mmd_audio", <ide> "webgl_loader_nodes", <add> "webgl_loader_nrrd", <ide> "webgl_loader_obj", <ide> "webgl_loader_obj_mtl", <ide> "webgl_loader_obj2", <ide> "webgl_loader_obj2_meshspray", <ide> "webgl_loader_obj2_options", <ide> "webgl_loader_obj2_run_director", <del> "webgl_loader_nrrd", <ide> "webgl_loader_pcd", <ide> "webgl_loader_pdb", <ide> "webgl_loader_playcanvas",
1
Javascript
Javascript
remove reactdomnodecache and getdomnodeid
1d65f81b1617e339f36fad285bc45f805bb899f2
<ide><path>src/core/ReactDOMNodeCache.js <del>/** <del> * Copyright 2013 Facebook, Inc. <del> * <del> * Licensed under the Apache License, Version 2.0 (the "License"); <del> * you may not use this file except in compliance with the License. <del> * You may obtain a copy of the License at <del> * <del> * http://www.apache.org/licenses/LICENSE-2.0 <del> * <del> * Unless required by applicable law or agreed to in writing, software <del> * distributed under the License is distributed on an "AS IS" BASIS, <del> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <del> * See the License for the specific language governing permissions and <del> * limitations under the License. <del> * <del> * @providesModule ReactDOMNodeCache <del> * @typechecks <del> */ <del> <del>"use strict"; <del> <del>var ReactID = require('ReactID'); <del> <del>exports.getNodeByID = ReactID.getNode; <del>exports.purgeID = ReactID.purgeID; <del>exports.purgeEntireCache = ReactID.purgeEntireCache; <ide><path>src/dom/getDOMNodeID.js <del>/** <del> * Copyright 2013 Facebook, Inc. <del> * <del> * Licensed under the Apache License, Version 2.0 (the "License"); <del> * you may not use this file except in compliance with the License. <del> * You may obtain a copy of the License at <del> * <del> * http://www.apache.org/licenses/LICENSE-2.0 <del> * <del> * Unless required by applicable law or agreed to in writing, software <del> * distributed under the License is distributed on an "AS IS" BASIS, <del> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <del> * See the License for the specific language governing permissions and <del> * limitations under the License. <del> * <del> * @providesModule getDOMNodeID <del> * @typechecks <del> */ <del> <del>"use strict"; <del> <del>var ReactID = require('ReactID'); <del> <del>function getDOMNodeID(domNode) { <del> return ReactID.getID(domNode); <del>} <del>module.exports = getDOMNodeID;
2
Python
Python
increase timeout for benchmark tests
cbcf86f23d266434e803d89353307580116380b1
<ide><path>tools/test.py <ide> def GetVm(self, arch, mode): <ide> <ide> def GetTimeout(self, mode, section=''): <ide> timeout = self.timeout * TIMEOUT_SCALEFACTOR[ARCH_GUESS or 'ia32'][mode] <del> if section == 'pummel': <add> if section == 'pummel' or section == 'benchmark': <ide> timeout = timeout * 4 <ide> return timeout <ide>
1
Javascript
Javascript
add descriptors to eachcomputedproperty
78b790f08c9c4a7797d595314d4226803f3d1e4b
<ide><path>packages/ember-runtime/lib/system/core_object.js <ide> var ClassMixinProps = { <ide> for (var name in proto) { <ide> property = proto[name]; <ide> <del> if (property instanceof ComputedProperty) { <add> if (property && property.isDescriptor) { <ide> properties.push({ <ide> name: name, <ide> meta: property._meta <ide><path>packages/ember-runtime/tests/system/object/computed_test.js <add>import alias from 'ember-metal/alias'; <ide> import { computed } from 'ember-metal/computed'; <ide> import { get as emberGet } from 'ember-metal/property_get'; <ide> import { observer } from 'ember-metal/mixin'; <ide> QUnit.test('can iterate over a list of computed properties for a class', functio <ide> <ide> fooDidChange: observer('foo', function() {}), <ide> <del> bar: computed(function() {}) <add> bar: computed(function() {}), <add> <add> qux: alias('foo') <ide> }); <ide> <ide> var SubClass = MyClass.extend({ <ide> QUnit.test('can iterate over a list of computed properties for a class', functio <ide> list.push(name); <ide> }); <ide> <del> deepEqual(list.sort(), ['bar', 'foo'], 'watched and unwatched computed properties are iterated'); <add> deepEqual(list.sort(), ['bar', 'foo', 'qux'], 'watched and unwatched computed properties are iterated'); <ide> <ide> list = []; <ide> <ide> QUnit.test('can iterate over a list of computed properties for a class', functio <ide> } <ide> }); <ide> <del> deepEqual(list.sort(), ['bar', 'bat', 'baz', 'foo'], 'all inherited properties are included'); <add> deepEqual(list.sort(), ['bar', 'bat', 'baz', 'foo', 'qux'], 'all inherited properties are included'); <ide> }); <ide> <ide> QUnit.test('list of properties updates when an additional property is added (such cache busting)', function() {
2
Ruby
Ruby
remove email support
11a421948d43210451a536fb40b8c10b838ff8c6
<ide><path>Library/Homebrew/cmd/test-bot.rb <ide> # --skip-setup: Don't check the local system is setup correctly. <ide> # --skip-homebrew: Don't check Homebrew's files and tests are all valid. <ide> # --junit: Generate a JUnit XML test results file. <del># --email: Generate an email subject file. <ide> # --keep-old: Run brew bottle --keep-old to build new bottles for a single platform. <ide> # --HEAD: Run brew install with --HEAD <ide> # --local: Ask Homebrew to write verbose logs under ./logs/ and set HOME to ./home/ <ide> require "cmd/tap" <ide> <ide> module Homebrew <del> EMAIL_SUBJECT_FILE = "brew-test-bot.#{MacOS.cat}.email.txt" <ide> BYTES_IN_1_MEGABYTE = 1024*1024 <ide> <ide> def resolve_test_tap <ide> def brew_update <ide> raise "Cannot set @name: invalid command-line arguments!" <ide> end <ide> <del> if ENV["TRAVIS"] <del> puts "name: #{@name}" <del> puts "url: #{@url}" <del> puts "hash: #{@hash}" <del> puts "diff_start_sha1: #{diff_start_sha1}" <del> puts "diff_end_sha1: #{diff_end_sha1}" <del> end <del> <ide> @log_root = @brewbot_root + @name <ide> FileUtils.mkdir_p @log_root <ide> <ide> def sanitize_ARGV_and_ENV <ide> ARGV << "--junit" << "--local" <ide> end <ide> if ARGV.include? "--ci-master" <del> ARGV << "--email" << "--fast" <add> ARGV << "--fast" <ide> end <ide> <ide> if ARGV.include? "--local" <ide> ENV["HOMEBREW_HOME"] = ENV["HOME"] = "#{Dir.pwd}/home" <ide> mkdir_p ENV["HOME"] <ide> ENV["HOMEBREW_LOGS"] = "#{Dir.pwd}/logs" <ide> end <del> <del> if ARGV.include? "--email" <del> File.open EMAIL_SUBJECT_FILE, "w" do |file| <del> # The file should be written at the end but in case we don't get to that <del> # point ensure that we have something valid. <del> file.write "#{MacOS.version}: internal error." <del> end <del> end <ide> end <ide> <ide> def test_bot <ide> def test_bot <ide> xml_document.write(xml_file, pretty_print_indent) <ide> end <ide> end <del> <del> if ARGV.include? "--email" <del> failed_steps = [] <del> tests.each do |test| <del> test.steps.each do |step| <del> next if step.passed? <del> failed_steps << step.command_short <del> end <del> end <del> <del> if failed_steps.empty? <del> email_subject = "" <del> else <del> email_subject = "#{MacOS.version}: #{failed_steps.join ", "}." <del> end <del> <del> File.open EMAIL_SUBJECT_FILE, "w" do |file| <del> file.write email_subject <del> end <del> end <ide> ensure <ide> if ARGV.include? "--clean-cache" <ide> HOMEBREW_CACHE.children.each(&:rmtree)
1
Java
Java
construct moduleholder from reactmoduleinfo
54d8d10a6bb6267c0677d37e6b28c6428720536b
<ide><path>ReactAndroid/src/main/java/com/facebook/react/NativeModuleRegistryBuilder.java <ide> public void processPackage(ReactPackage reactPackage) { <ide> ReactMarker.logMarker(ReactMarkerConstants.CREATE_MODULE_END); <ide> moduleHolder = new ModuleHolder(module); <ide> } else { <del> moduleHolder = new ModuleHolder( <del> reactModuleInfo.name(), <del> reactModuleInfo.canOverrideExistingModule(), <del> reactModuleInfo.supportsWebWorkers(), <del> reactModuleInfo.needsEagerInit(), <del> reactModuleInfo.hasConstants(), <del> moduleSpec.getProvider()); <add> moduleHolder = new ModuleHolder(reactModuleInfo, moduleSpec.getProvider()); <ide> } <ide> <ide> String name = moduleHolder.getName(); <ide><path>ReactAndroid/src/main/java/com/facebook/react/cxxbridge/ModuleHolder.java <ide> import com.facebook.react.bridge.NativeModule; <ide> import com.facebook.react.bridge.ReactMarker; <ide> import com.facebook.react.bridge.ReactMarkerConstants; <add>import com.facebook.react.module.model.ReactModuleInfo; <ide> import com.facebook.systrace.Systrace; <ide> import com.facebook.systrace.SystraceMessage; <ide> <ide> public class ModuleHolder { <ide> private @Nullable NativeModule mModule; <ide> private boolean mInitializeNeeded; <ide> <del> public ModuleHolder( <del> String name, <del> boolean canOverrideExistingModule, <del> boolean supportsWebWorkers, <del> boolean needsEagerInit, <del> boolean hasConstants, <del> Provider<? extends NativeModule> provider) { <del> mName = name; <del> mCanOverrideExistingModule = canOverrideExistingModule; <del> mSupportsWebWorkers = supportsWebWorkers; <del> mHasConstants = hasConstants; <add> public ModuleHolder(ReactModuleInfo moduleInfo, Provider<? extends NativeModule> provider) { <add> mName = moduleInfo.name(); <add> mCanOverrideExistingModule = moduleInfo.canOverrideExistingModule(); <add> mSupportsWebWorkers = moduleInfo.supportsWebWorkers(); <add> mHasConstants = moduleInfo.hasConstants(); <ide> mProvider = provider; <del> if (needsEagerInit) { <add> if (moduleInfo.needsEagerInit()) { <ide> mModule = create(); <ide> } <ide> } <ide><path>ReactAndroid/src/test/java/com/facebook/react/cxxbridge/BaseJavaModuleTest.java <ide> public class BaseJavaModuleTest { <ide> <ide> @Before <ide> public void setup() { <del> ModuleHolder moduleHolder = new ModuleHolder("MethodsModule", <del> false, <del> false, <del> false, <del> false, <del> new Provider<MethodsModule>() { <del> MethodsModule mModule; <del> @Override <del> public MethodsModule get() { <del> mModule = new MethodsModule(); <del> return mModule; <del> } <del> }); <add> ModuleHolder moduleHolder = new ModuleHolder(new MethodsModule()); <ide> mWrapper = new JavaModuleWrapper(null, MethodsModule.class, moduleHolder); <ide> mMethods = mWrapper.getMethodDescriptors(); <ide> PowerMockito.mockStatic(SoLoader.class);
3
Javascript
Javascript
prevent crash when backtrace doesn't come back
1f041fe73e73e69b0253deb0df58e856f3b650e1
<ide><path>lib/_debugger.js <ide> Client.prototype.reqEval = function(expression, cb) { <ide> <ide> // Otherwise we need to get the current frame to see which scopes it has. <ide> this.reqBacktrace(function(bt) { <add> if (!bt.frames) { <add> // ?? <add> cb({}); <add> return; <add> } <add> <ide> var frame = bt.frames[self.currentFrame]; <ide> <ide> var evalFrames = frame.scopes.map(function(s) {
1
PHP
PHP
add space after question
ff579f49370a568f8b8ad948798bd76309e85753
<ide><path>src/Illuminate/Console/Command.php <ide> public function confirm($question, $default = true) <ide> { <ide> $dialog = $this->getHelperSet()->get('dialog'); <ide> <del> return $dialog->askConfirmation($this->output, "<question>$question</question>", $default); <add> return $dialog->askConfirmation($this->output, "<question>$question</question> ", $default); <ide> } <ide> <ide> /**
1
Mixed
Python
allow required false and default
cf5d401a0e60948ed0b3ad384c3f76fc30c3e222
<ide><path>docs/api-guide/fields.md <ide> The `default` is not applied during partial update operations. In the partial up <ide> <ide> May be set to a function or other callable, in which case the value will be evaluated each time it is used. When called, it will receive no arguments. If the callable has a `set_context` method, that will be called each time before getting the value with the field instance as only argument. This works the same way as for [validators](validators.md#using-set_context). <ide> <add>When serializing the instance, default will be used if the the object attribute or dictionary key is not present in the instance. <add> <ide> Note that setting a `default` value implies that the field is not required. Including both the `default` and `required` keyword arguments is invalid and will raise an error. <ide> <ide> ### `source` <ide><path>rest_framework/fields.py <ide> def get_attribute(self, instance): <ide> try: <ide> return get_attribute(instance, self.source_attrs) <ide> except (KeyError, AttributeError) as exc: <del> if not self.required and self.default is empty: <add> if self.default is not empty: <add> return self.get_default() <add> if not self.required: <ide> raise SkipField() <ide> msg = ( <ide> 'Got {exc_type} when attempting to get a value for field ' <ide><path>tests/test_serializer.py <ide> def create(self, validated_data): <ide> serializer.save() <ide> assert serializer.data == {'included': 'abc'} <ide> <del> def test_default_required_output_for_dict(self): <del> """ <del> 'default="something"' should require dictionary key. <ide> <del> We need to handle this as the field will have an implicit <del> 'required=False', but it should still have a value. <del> """ <add>class TestDefaultOutput: <add> def setup(self): <ide> class ExampleSerializer(serializers.Serializer): <del> omitted = serializers.CharField(default='abc') <del> included = serializers.CharField() <add> has_default = serializers.CharField(default='x') <add> has_default_callable = serializers.CharField(default=lambda: 'y') <add> no_default = serializers.CharField() <add> self.Serializer = ExampleSerializer <ide> <del> serializer = ExampleSerializer({'included': 'abc'}) <del> with pytest.raises(KeyError): <del> serializer.data <add> def test_default_used_for_dict(self): <add> """ <add> 'default="something"' should be used if dictionary key is missing from input. <add> """ <add> serializer = self.Serializer({'no_default': 'abc'}) <add> assert serializer.data == {'has_default': 'x', 'has_default_callable': 'y', 'no_default': 'abc'} <ide> <del> def test_default_required_output_for_object(self): <add> def test_default_used_for_object(self): <ide> """ <del> 'default="something"' should require object attribute. <add> 'default="something"' should be used if object attribute is missing from input. <add> """ <add> instance = MockObject(no_default='abc') <add> serializer = self.Serializer(instance) <add> assert serializer.data == {'has_default': 'x', 'has_default_callable': 'y', 'no_default': 'abc'} <ide> <del> We need to handle this as the field will have an implicit <del> 'required=False', but it should still have a value. <add> def test_default_not_used_when_in_dict(self): <ide> """ <del> class ExampleSerializer(serializers.Serializer): <del> omitted = serializers.CharField(default='abc') <del> included = serializers.CharField() <add> 'default="something"' should not be used if dictionary key is present in input. <add> """ <add> serializer = self.Serializer({'has_default': 'def', 'has_default_callable': 'ghi', 'no_default': 'abc'}) <add> assert serializer.data == {'has_default': 'def', 'has_default_callable': 'ghi', 'no_default': 'abc'} <ide> <del> instance = MockObject(included='abc') <del> serializer = ExampleSerializer(instance) <del> with pytest.raises(AttributeError): <del> serializer.data <add> def test_default_not_used_when_in_object(self): <add> """ <add> 'default="something"' should not be used if object attribute is present in input. <add> """ <add> instance = MockObject(has_default='def', has_default_callable='ghi', no_default='abc') <add> serializer = self.Serializer(instance) <add> assert serializer.data == {'has_default': 'def', 'has_default_callable': 'ghi', 'no_default': 'abc'} <ide> <ide> <ide> class TestCacheSerializerData:
3
Ruby
Ruby
add a user_agent to testrequest
fe31f0e066ef8969366e692d21127a60a246d5a0
<ide><path>actionpack/lib/action_controller/test_process.rb <ide> def process_with_test(*args) <ide> class TestRequest < AbstractRequest #:nodoc: <ide> attr_accessor :cookies, :session_options <ide> attr_accessor :query_parameters, :request_parameters, :path, :session, :env <del> attr_accessor :host <add> attr_accessor :host, :user_agent <ide> <ide> def initialize(query_parameters = nil, request_parameters = nil, session = nil) <ide> @query_parameters = query_parameters || {} <ide> def initialize_containers <ide> def initialize_default_values <ide> @host = "test.host" <ide> @request_uri = "/" <add> @user_agent = "Rails Testing" <ide> self.remote_addr = "0.0.0.0" <ide> @env["SERVER_PORT"] = 80 <ide> @env['REQUEST_METHOD'] = "GET" <ide><path>actionpack/test/controller/request_test.rb <ide> def test_content_type_with_charset <ide> @request.env["CONTENT_TYPE"] = "application/xml; charset=UTF-8" <ide> assert_equal Mime::XML, @request.content_type <ide> end <add> <add> def test_user_agent <add> assert_not_nil @request.user_agent <add> end <ide> <ide> protected <ide> def set_request_method_to(method)
2
Ruby
Ruby
display full upgrade version
c309ed8d44f69ed211abd2a170f45935c3357f73
<ide><path>Library/Homebrew/formula_installer.rb <ide> def install <ide> EOS <ide> message += if formula.outdated? && !formula.head? <ide> <<-EOS.undent <del> To upgrade to #{formula.version}, run `brew upgrade #{formula.name}` <add> To upgrade to #{formula.pkg_version}, run `brew upgrade #{formula.name}` <ide> EOS <ide> else <ide> # some other version is already installed *and* linked <ide> <<-EOS.undent <del> To install #{formula.version}, first run `brew unlink #{formula.name}` <add> To install #{formula.pkg_version}, first run `brew unlink #{formula.name}` <ide> EOS <ide> end <ide> raise CannotInstallFormulaError, message
1
Text
Text
add review suggestions to require()
51cd9719b5fde5da973dcdbb196402b49f885c63
<ide><path>doc/api/modules.md <ide> added: v0.1.13 <ide> <ide> * {Function} <ide> <del>To require modules. <add>Used to import modules, `JSON`, and local files. Modules can be imported <add>from `node_modules`. Local modules and JSON files can be imported using <add>a relative path (e.g. `./`, `./foo`, `./bar/baz`, `../foo`) that will be <add>resolved against the directory named by [`__dirname`][] (if defined) or <add>the current working directory. <add> <add>```js <add>// Importing a local module: <add>const myLocalModule = require('./path/myLocalModule'); <add> <add>// Importing a JSON file: <add>const jsonData = require('./path/filename.json'); <add> <add>// Importing a module from node_modules or Node.js built-in module: <add>const crypto = require('crypto'); <add>``` <ide> <ide> #### require.cache <ide> <!-- YAML
1
Go
Go
add integration test for unix sock cleanup
16309bef6395a50ee2871780b81caed8bc6c498e
<ide><path>api/server/server.go <ide> func ServeApi(job *engine.Job) engine.Status { <ide> } <ide> job.Eng.OnShutdown(func() { <ide> if err := srv.Close(); err != nil { <del> log.Errorf("%s", err.Error()) <add> log.Error(err) <ide> } <ide> }) <del> chErrors <- srv.Serve() <add> if err = srv.Serve(); err != nil && strings.Contains(err.Error(), "use of closed network connection") { <add> err = nil <add> } <add> chErrors <- err <ide> }() <ide> } <ide> <ide><path>api/server/server_linux.go <ide> import ( <ide> <ide> "github.com/docker/docker/engine" <ide> "github.com/docker/docker/pkg/systemd" <del> "net" <ide> ) <ide> <del>type UnixHttpServer struct { <del> srv *http.Server <del> l net.Listener <del>} <del> <del>func (s *UnixHttpServer) Serve() error { <del> return s.srv.Serve(s.l) <del>} <del>func (s *UnixHttpServer) Close() error { <del> if err := s.l.Close(); err != nil { <del> return err <del> } <del> if _, err := os.Stat(s.srv.Addr); err != nil { <del> return fmt.Errorf("Error removing unix socket %s: %s", s.srv.Addr, err.Error()) <del> } <del> if err := os.Remove(s.srv.Addr); err != nil { <del> return fmt.Errorf("Error removing unix socket %s: %s", s.srv.Addr, err.Error()) <del> } <del> return nil <del>} <del> <ide> // NewServer sets up the required Server and does protocol specific checking. <ide> func NewServer(proto, addr string, job *engine.Job) (Server, error) { <ide> // Basic error and sanity checking <ide> func NewServer(proto, addr string, job *engine.Job) (Server, error) { <ide> } <ide> } <ide> <del>func setupUnixHttp(addr string, job *engine.Job) (*UnixHttpServer, error) { <add>func setupUnixHttp(addr string, job *engine.Job) (*HttpServer, error) { <ide> r := createRouter(job.Eng, job.GetenvBool("Logging"), job.GetenvBool("EnableCors"), job.Getenv("CorsHeaders"), job.Getenv("Version")) <ide> <ide> if err := syscall.Unlink(addr); err != nil && !os.IsNotExist(err) { <ide> func setupUnixHttp(addr string, job *engine.Job) (*UnixHttpServer, error) { <ide> return nil, err <ide> } <ide> <del> return &UnixHttpServer{&http.Server{Addr: addr, Handler: r}, l}, nil <add> return &HttpServer{&http.Server{Addr: addr, Handler: r}, l}, nil <ide> } <ide> <ide> // serveFd creates an http.Server and sets it up to serve given a socket activated <ide><path>docker/daemon.go <ide> func mainDaemon() { <ide> errAPI := <-serveAPIWait <ide> // If we have an error here it is unique to API (as daemonErr would have <ide> // exited the daemon process above) <add> eng.Shutdown() <ide> if errAPI != nil { <del> log.Errorf("Shutting down due to ServeAPI error: %v", errAPI) <add> log.Fatalf("Shutting down due to ServeAPI error: %v", errAPI) <ide> } <del> eng.Shutdown() <add> <ide> } <ide><path>engine/engine.go <ide> func unregister(name string) { <ide> // It acts as a store for *containers*, and allows manipulation of these <ide> // containers by executing *jobs*. <ide> type Engine struct { <del> handlers map[string]Handler <del> catchall Handler <del> hack Hack // data for temporary hackery (see hack.go) <del> id string <del> Stdout io.Writer <del> Stderr io.Writer <del> Stdin io.Reader <del> Logging bool <del> tasks sync.WaitGroup <del> l sync.RWMutex // lock for shutdown <del> shutdown bool <del> onShutdown []func() // shutdown handlers <add> handlers map[string]Handler <add> catchall Handler <add> hack Hack // data for temporary hackery (see hack.go) <add> id string <add> Stdout io.Writer <add> Stderr io.Writer <add> Stdin io.Reader <add> Logging bool <add> tasks sync.WaitGroup <add> l sync.RWMutex // lock for shutdown <add> shutdownWait sync.WaitGroup <add> shutdown bool <add> onShutdown []func() // shutdown handlers <ide> } <ide> <ide> func (eng *Engine) Register(name string, handler Handler) error { <ide> func (eng *Engine) Job(name string, args ...string) *Job { <ide> func (eng *Engine) OnShutdown(h func()) { <ide> eng.l.Lock() <ide> eng.onShutdown = append(eng.onShutdown, h) <add> eng.shutdownWait.Add(1) <ide> eng.l.Unlock() <ide> } <ide> <ide> func (eng *Engine) Shutdown() { <ide> eng.l.Lock() <ide> if eng.shutdown { <ide> eng.l.Unlock() <add> eng.shutdownWait.Wait() <ide> return <ide> } <ide> eng.shutdown = true <ide> func (eng *Engine) Shutdown() { <ide> <ide> // Call shutdown handlers, if any. <ide> // Timeout after 10 seconds. <del> var wg sync.WaitGroup <ide> for _, h := range eng.onShutdown { <del> wg.Add(1) <ide> go func(h func()) { <del> defer wg.Done() <ide> h() <add> eng.shutdownWait.Done() <ide> }(h) <ide> } <ide> done := make(chan struct{}) <ide> go func() { <del> wg.Wait() <add> eng.shutdownWait.Wait() <ide> close(done) <ide> }() <ide> select { <ide><path>integration-cli/docker_cli_daemon_test.go <ide> func TestDaemonDots(t *testing.T) { <ide> <ide> logDone("daemon - test dots on INFO") <ide> } <add> <add>func TestDaemonUnixSockCleanedUp(t *testing.T) { <add> d := NewDaemon(t) <add> dir, err := ioutil.TempDir("", "socket-cleanup-test") <add> if err != nil { <add> t.Fatal(err) <add> } <add> defer os.RemoveAll(dir) <add> <add> sockPath := filepath.Join(dir, "docker.sock") <add> if err := d.Start("--host", "unix://"+sockPath); err != nil { <add> t.Fatal(err) <add> } <add> <add> if _, err := os.Stat(sockPath); err != nil { <add> t.Fatal("socket does not exist") <add> } <add> <add> if err := d.Stop(); err != nil { <add> t.Fatal(err) <add> } <add> <add> if _, err := os.Stat(sockPath); err == nil || !os.IsNotExist(err) { <add> t.Fatal("unix socket is not cleaned up") <add> } <add> <add> logDone("daemon - unix socket is cleaned up") <add>}
5
Javascript
Javascript
remove deregisternotifier feature for $watch
ce378f2582d3b73571b3db3eabfe89f596d48bea
<ide><path>src/ng/interpolate.js <ide> function $InterpolateProvider() { <ide> exp: text, //just for compatibility with regular watchers created via $watch <ide> separators: separators, <ide> expressions: expressions, <del> $$watchDelegate: function (scope, listener, objectEquality) { <add> $$watchDelegate: function (scope, listener, objectEquality, deregisterNotifier) { <ide> var lastValue; <ide> return scope.$watchGroup(parseFns, function interpolateFnWatcher(values, oldValues) { <ide> var currValue = compute(values); <ide> if (isFunction(listener)) { <ide> listener.call(this, currValue, values !== oldValues ? lastValue : currValue, scope); <ide> } <ide> lastValue = currValue; <del> }, objectEquality); <add> }, objectEquality, deregisterNotifier); <ide> } <ide> }); <ide> } <ide><path>src/ng/parse.js <ide> function $ParseProvider() { <ide> } <ide> }; <ide> <del> function oneTimeWatch(scope, listener, objectEquality, parsedExpression) { <add> function oneTimeWatch(scope, listener, objectEquality, deregisterNotifier, parsedExpression) { <ide> var unwatch, lastValue; <ide> return unwatch = scope.$watch(function oneTimeWatch(scope) { <ide> return parsedExpression(scope); <ide> function $ParseProvider() { <ide> } <ide> }); <ide> } <del> }, objectEquality); <add> }, objectEquality, deregisterNotifier); <ide> } <ide> <ide> function oneTimeLiteralWatch(scope, listener, objectEquality, parsedExpression) { <ide> function $ParseProvider() { <ide> } <ide> } <ide> <del> function constantWatch(scope, listener, objectEquality, parsedExpression) { <add> function constantWatch(scope, listener, objectEquality, deregisterNotifier, parsedExpression) { <ide> var unwatch; <ide> return unwatch = scope.$watch(function constantWatch(scope) { <ide> return parsedExpression(scope); <ide> function $ParseProvider() { <ide> listener.apply(this, arguments); <ide> } <ide> unwatch(); <del> }, objectEquality); <add> }, objectEquality, deregisterNotifier); <ide> } <ide> <ide> function addInterceptor(parsedExpression, interceptorFn) { <ide><path>src/ng/rootScope.js <ide> function $RootScopeProvider(){ <ide> * - `scope` refers to the current scope <ide> * @param {boolean=} objectEquality Compare for object equality using {@link angular.equals} instead of <ide> * comparing for reference equality. <add> * @param {function()=} deregisterNotifier Function to call when the deregistration function <add> * get called. <ide> * @returns {function()} Returns a deregistration function for this listener. <ide> */ <del> $watch: function(watchExp, listener, objectEquality) { <add> $watch: function(watchExp, listener, objectEquality, deregisterNotifier) { <ide> var get = compileToFn(watchExp, 'watch'); <ide> <ide> if (get.$$watchDelegate) { <del> return get.$$watchDelegate(this, listener, objectEquality, get); <add> return get.$$watchDelegate(this, listener, objectEquality, deregisterNotifier, get); <ide> } <ide> var scope = this, <ide> array = scope.$$watchers, <ide> function $RootScopeProvider(){ <ide> return function deregisterWatch() { <ide> arrayRemove(array, watcher); <ide> lastDirtyWatch = null; <add> if (isFunction(deregisterNotifier)) { <add> deregisterNotifier(); <add> } <ide> }; <ide> }, <ide> <ide><path>test/ng/rootScopeSpec.js <ide> describe('Scope', function() { <ide> expect(log).toEqual(['watch1', 'watchAction1', 'watch2', 'watchAction2', 'watch3', 'watchAction3', <ide> 'watch2', 'watch3']); <ide> })); <add> <add> describe('deregisterNotifier', function () { <add> it('should call the deregisterNotifier when the watch is deregistered', inject( <add> function($rootScope) { <add> var notifier = jasmine.createSpy('deregisterNotifier'); <add> var listenerRemove = $rootScope.$watch('noop', noop, false, notifier); <add> <add> expect(notifier).not.toHaveBeenCalled(); <add> <add> listenerRemove(); <add> expect(notifier).toHaveBeenCalledOnce(); <add> })); <add> <add> <add> it('should call the deregisterNotifier when a one-time expression is stable', inject( <add> function($rootScope) { <add> var notifier = jasmine.createSpy('deregisterNotifier'); <add> $rootScope.$watch('::foo', noop, false, notifier); <add> <add> expect(notifier).not.toHaveBeenCalledOnce(); <add> $rootScope.$digest(); <add> expect(notifier).not.toHaveBeenCalledOnce(); <add> <add> $rootScope.foo = 'foo'; <add> $rootScope.$digest(); <add> expect(notifier).toHaveBeenCalledOnce(); <add> })); <add> }); <ide> }); <ide> <ide>
4
Java
Java
reduce log level for @exceptionhandler failure
cdfcc23b6f1424f04e8273b3aa69fe185fb73dde
<ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/ExceptionHandlerExceptionResolver.java <ide> protected ModelAndView doResolveHandlerMethodException(HttpServletRequest reques <ide> exceptionHandlerMethod.invokeAndHandle(webRequest, mavContainer, exception, handlerMethod); <ide> } <ide> catch (Exception invocationEx) { <del> if (logger.isErrorEnabled()) { <del> logger.error("Failed to invoke @ExceptionHandler method: " + exceptionHandlerMethod, invocationEx); <add> if (logger.isDebugEnabled()) { <add> logger.debug("Failed to invoke @ExceptionHandler method: " + exceptionHandlerMethod, invocationEx); <ide> } <ide> return null; <ide> }
1
Javascript
Javascript
use async/await in tokenizedbuffer test
15a57287510521c26a597ff2e1b2a46a340fc659
<ide><path>spec/tokenized-buffer-spec.js <ide> const TokenizedBuffer = require('../src/tokenized-buffer') <ide> const TextBuffer = require('text-buffer') <ide> const {Point} = TextBuffer <ide> const _ = require('underscore-plus') <add>const {it, fit, ffit, fffit, beforeEach, afterEach} = require('./async-spec-helpers') <ide> <ide> describe('TokenizedBuffer', () => { <ide> let tokenizedBuffer, buffer <ide> <del> beforeEach(() => { <add> beforeEach(async () => { <ide> // enable async tokenization <ide> TokenizedBuffer.prototype.chunkSize = 5 <ide> jasmine.unspy(TokenizedBuffer.prototype, 'tokenizeInBackground') <ide> <del> waitsForPromise(() => atom.packages.activatePackage('language-javascript')) <add> await atom.packages.activatePackage('language-javascript') <ide> }) <ide> <ide> afterEach(() => tokenizedBuffer && tokenizedBuffer.destroy()) <ide> describe('TokenizedBuffer', () => { <ide> <ide> describe('serialization', () => { <ide> describe('when the underlying buffer has a path', () => { <del> beforeEach(() => { <add> beforeEach(async () => { <ide> buffer = atom.project.bufferForPathSync('sample.js') <del> <del> waitsForPromise(() => atom.packages.activatePackage('language-coffee-script')) <add> await atom.packages.activatePackage('language-coffee-script') <ide> }) <ide> <ide> it('deserializes it searching among the buffers in the current project', () => { <ide> describe('TokenizedBuffer', () => { <ide> }) <ide> ) <ide> <del> it('does not break out soft tabs across a scope boundary', () => { <del> waitsForPromise(() => atom.packages.activatePackage('language-gfm')) <add> it('does not break out soft tabs across a scope boundary', async () => { <add> await atom.packages.activatePackage('language-gfm') <ide> <del> runs(() => { <del> tokenizedBuffer.setTabLength(4) <del> tokenizedBuffer.setGrammar(atom.grammars.selectGrammar('.md')) <del> buffer.setText(' <![]()\n ') <del> fullyTokenize(tokenizedBuffer) <add> tokenizedBuffer.setTabLength(4) <add> tokenizedBuffer.setGrammar(atom.grammars.selectGrammar('.md')) <add> buffer.setText(' <![]()\n ') <add> fullyTokenize(tokenizedBuffer) <ide> <del> let length = 0 <del> for (let tag of tokenizedBuffer.tokenizedLines[1].tags) { <del> if (tag > 0) { length += tag } <del> } <add> let length = 0 <add> for (let tag of tokenizedBuffer.tokenizedLines[1].tags) { <add> if (tag > 0) length += tag <add> } <ide> <del> expect(length).toBe(4) <del> }) <add> expect(length).toBe(4) <ide> }) <ide> }) <ide> }) <ide> <ide> describe('when the buffer contains hard-tabs', () => { <del> beforeEach(() => { <del> waitsForPromise(() => atom.packages.activatePackage('language-coffee-script')) <add> beforeEach(async () => { <add> atom.packages.activatePackage('language-coffee-script') <ide> <del> runs(() => { <del> buffer = atom.project.bufferForPathSync('sample-with-tabs.coffee') <del> tokenizedBuffer = new TokenizedBuffer({buffer, grammar: atom.grammars.grammarForScopeName('source.coffee'), tabLength: 2}) <del> startTokenizing(tokenizedBuffer) <del> }) <add> buffer = atom.project.bufferForPathSync('sample-with-tabs.coffee') <add> tokenizedBuffer = new TokenizedBuffer({buffer, grammar: atom.grammars.grammarForScopeName('source.coffee'), tabLength: 2}) <add> startTokenizing(tokenizedBuffer) <ide> }) <ide> <ide> afterEach(() => { <ide> describe('TokenizedBuffer', () => { <ide> }) <ide> <ide> describe('when the grammar is tokenized', () => { <del> it('emits the `tokenized` event', () => { <del> let editor = null <del> const tokenizedHandler = jasmine.createSpy('tokenized handler') <add> it('emits the `tokenized` event', async () => { <add> const editor = await atom.workspace.open('sample.js') <ide> <del> waitsForPromise(() => atom.workspace.open('sample.js').then(o => editor = o)) <del> <del> runs(() => { <del> ({ tokenizedBuffer } = editor) <del> tokenizedBuffer.onDidTokenize(tokenizedHandler) <del> fullyTokenize(tokenizedBuffer) <del> expect(tokenizedHandler.callCount).toBe(1) <del> }) <del> }) <del> <del> it("doesn't re-emit the `tokenized` event when it is re-tokenized", () => { <del> let editor = null <ide> const tokenizedHandler = jasmine.createSpy('tokenized handler') <add> editor.tokenizedBuffer.onDidTokenize(tokenizedHandler) <add> fullyTokenize(editor.tokenizedBuffer) <add> expect(tokenizedHandler.callCount).toBe(1) <add> }) <ide> <del> waitsForPromise(() => atom.workspace.open('sample.js').then(o => editor = o)) <del> <del> runs(() => { <del> ({ tokenizedBuffer } = editor) <del> fullyTokenize(tokenizedBuffer) <add> it("doesn't re-emit the `tokenized` event when it is re-tokenized", async () => { <add> const editor = await atom.workspace.open('sample.js') <add> fullyTokenize(editor.tokenizedBuffer) <ide> <del> tokenizedBuffer.onDidTokenize(tokenizedHandler) <del> editor.getBuffer().insert([0, 0], "'") <del> fullyTokenize(tokenizedBuffer) <del> expect(tokenizedHandler).not.toHaveBeenCalled() <del> }) <add> const tokenizedHandler = jasmine.createSpy('tokenized handler') <add> editor.tokenizedBuffer.onDidTokenize(tokenizedHandler) <add> editor.getBuffer().insert([0, 0], "'") <add> fullyTokenize(editor.tokenizedBuffer) <add> expect(tokenizedHandler).not.toHaveBeenCalled() <ide> }) <ide> }) <ide> <del> describe('when the grammar is updated because a grammar it includes is activated', () => { <del> it('re-emits the `tokenized` event', () => { <del> let editor = null <del> tokenizedBuffer = null <del> const tokenizedHandler = jasmine.createSpy('tokenized handler') <del> <del> waitsForPromise(() => atom.workspace.open('coffee.coffee').then(o => editor = o)) <del> <del> runs(() => { <del> ({ tokenizedBuffer } = editor) <del> tokenizedBuffer.onDidTokenize(tokenizedHandler) <del> fullyTokenize(tokenizedBuffer) <del> tokenizedHandler.reset() <del> }) <add> describe('when the grammar is updated because a grammar it includes is activated', async () => { <add> it('re-emits the `tokenized` event', async () => { <add> const editor = await atom.workspace.open('coffee.coffee') <ide> <del> waitsForPromise(() => atom.packages.activatePackage('language-coffee-script')) <add> const tokenizedHandler = jasmine.createSpy('tokenized handler') <add> editor.tokenizedBuffer.onDidTokenize(tokenizedHandler) <add> fullyTokenize(editor.tokenizedBuffer) <add> tokenizedHandler.reset() <ide> <del> runs(() => { <del> fullyTokenize(tokenizedBuffer) <del> expect(tokenizedHandler.callCount).toBe(1) <del> }) <add> await atom.packages.activatePackage('language-coffee-script') <add> fullyTokenize(editor.tokenizedBuffer) <add> expect(tokenizedHandler.callCount).toBe(1) <ide> }) <ide> <del> it('retokenizes the buffer', () => { <del> waitsForPromise(() => atom.packages.activatePackage('language-ruby-on-rails')) <add> it('retokenizes the buffer', async () => { <add> await atom.packages.activatePackage('language-ruby-on-rails') <add> await atom.packages.activatePackage('language-ruby') <ide> <del> waitsForPromise(() => atom.packages.activatePackage('language-ruby')) <add> buffer = atom.project.bufferForPathSync() <add> buffer.setText("<div class='name'><%= User.find(2).full_name %></div>") <ide> <del> runs(() => { <del> buffer = atom.project.bufferForPathSync() <del> buffer.setText("<div class='name'><%= User.find(2).full_name %></div>") <del> tokenizedBuffer = new TokenizedBuffer({buffer, grammar: atom.grammars.selectGrammar('test.erb'), tabLength: 2}) <del> fullyTokenize(tokenizedBuffer) <del> <del> const {tokens} = tokenizedBuffer.tokenizedLines[0] <del> expect(tokens[0]).toEqual({value: "<div class='name'>", scopes: ['text.html.ruby']}) <add> tokenizedBuffer = new TokenizedBuffer({buffer, grammar: atom.grammars.selectGrammar('test.erb'), tabLength: 2}) <add> fullyTokenize(tokenizedBuffer) <add> expect(tokenizedBuffer.tokenizedLines[0].tokens[0]).toEqual({ <add> value: "<div class='name'>", <add> scopes: ['text.html.ruby'] <ide> }) <ide> <del> waitsForPromise(() => atom.packages.activatePackage('language-html')) <del> <del> runs(() => { <del> fullyTokenize(tokenizedBuffer) <del> const {tokens} = tokenizedBuffer.tokenizedLines[0] <del> expect(tokens[0]).toEqual({value: '<', scopes: ['text.html.ruby', 'meta.tag.block.any.html', 'punctuation.definition.tag.begin.html']}) <add> await atom.packages.activatePackage('language-html') <add> fullyTokenize(tokenizedBuffer) <add> expect(tokenizedBuffer.tokenizedLines[0].tokens[0]).toEqual({ <add> value: '<', <add> scopes: ['text.html.ruby', 'meta.tag.block.any.html', 'punctuation.definition.tag.begin.html'] <ide> }) <ide> }) <ide> }) <ide> describe('TokenizedBuffer', () => { <ide> iterator.moveToSuccessor() <ide> }) // ensure we don't infinitely loop (regression test) <ide> <del> it('does not report columns beyond the length of the line', () => { <del> waitsForPromise(() => atom.packages.activatePackage('language-coffee-script')) <add> it('does not report columns beyond the length of the line', async () => { <add> await atom.packages.activatePackage('language-coffee-script') <ide> <del> runs(() => { <del> buffer = new TextBuffer({text: '# hello\n# world'}) <del> tokenizedBuffer = new TokenizedBuffer({buffer, grammar: atom.grammars.grammarForScopeName('source.coffee'), tabLength: 2}) <del> fullyTokenize(tokenizedBuffer) <add> buffer = new TextBuffer({text: '# hello\n# world'}) <add> tokenizedBuffer = new TokenizedBuffer({buffer, grammar: atom.grammars.grammarForScopeName('source.coffee'), tabLength: 2}) <add> fullyTokenize(tokenizedBuffer) <ide> <del> const iterator = tokenizedBuffer.buildIterator() <del> iterator.seek(Point(0, 0)) <del> iterator.moveToSuccessor() <del> iterator.moveToSuccessor() <del> expect(iterator.getPosition().column).toBe(7) <add> const iterator = tokenizedBuffer.buildIterator() <add> iterator.seek(Point(0, 0)) <add> iterator.moveToSuccessor() <add> iterator.moveToSuccessor() <add> expect(iterator.getPosition().column).toBe(7) <ide> <del> iterator.moveToSuccessor() <del> expect(iterator.getPosition().column).toBe(0) <add> iterator.moveToSuccessor() <add> expect(iterator.getPosition().column).toBe(0) <ide> <del> iterator.seek(Point(0, 7)) <del> expect(iterator.getPosition().column).toBe(7) <add> iterator.seek(Point(0, 7)) <add> expect(iterator.getPosition().column).toBe(7) <ide> <del> iterator.seek(Point(0, 8)) <del> expect(iterator.getPosition().column).toBe(7) <del> }) <add> iterator.seek(Point(0, 8)) <add> expect(iterator.getPosition().column).toBe(7) <ide> }) <ide> <ide> it('correctly terminates scopes at the beginning of the line (regression)', () => {
1
Javascript
Javascript
add common links to formvalidators regex
b2ec1a3ef48c49a774a7baa906bbd4691bf1d351
<ide><path>client/src/components/formHelpers/FormFields.js <ide> import { Field } from 'react-final-form'; <ide> import { <ide> editorValidator, <ide> localhostValidator, <del> composeValidators <add> composeValidators, <add> fCCValidator <ide> } from './FormValidators'; <ide> <ide> const propTypes = { <ide> function FormFields(props) { <ide> } <ide> const validationWarning = composeValidators( <ide> name === 'githubLink' || isEditorLinkAllowed ? null : editorValidator, <add> fCCValidator, <ide> localhostValidator <ide> )(value); <ide> const message = error || validationError || validationWarning; <ide><path>client/src/components/formHelpers/FormValidators.js <ide> // Matches editor links for: Repl.it, Glitch, CodeSandbox, GitHub <del>const editorRegex = /repl\.it\/@|glitch\.com\/edit\/#!|codesandbox\.io\/s\/|github\.com/; <add>const editorRegex = /repl\.it\/(@|join\/)|glitch\.com\/edit\/#!|codesandbox\.io\/s\/|github\.com/; <add>const fCCRegex = /codepen\.io\/freecodecamp|freecodecamp\.rocks|github\.com\/freecodecamp/i; <ide> const localhostRegex = /localhost:/; <ide> <ide> export const editorValidator = value => <ide> editorRegex.test(value) ? 'Remember to submit the Live App URL.' : null; <ide> <add>export const fCCValidator = value => <add> fCCRegex.test(value) ? 'Remember to submit your own work.' : null; <add> <ide> export const localhostValidator = value => <ide> localhostRegex.test(value) <ide> ? 'Remember to submit a publicly visible app URL.' <ide><path>client/src/components/formHelpers/index.js <ide> import normalizeUrl from 'normalize-url'; <ide> import { <ide> localhostValidator, <ide> editorValidator, <del> composeValidators <add> composeValidators, <add> fCCValidator <ide> } from './FormValidators'; <ide> <ide> export { default as BlockSaveButton } from './BlockSaveButton.js'; <ide> export function formatUrlValues(values, options) { <ide> const urlValues = Object.keys(values).reduce((result, key) => { <ide> let value = values[key]; <ide> const nullOrWarning = composeValidators( <add> fCCValidator, <ide> localhostValidator, <ide> key === 'githubLink' || isEditorLinkAllowed ? null : editorValidator <ide> )(value);
3
PHP
PHP
update routingmiddleware tests
94ed2de21e93cd6454a69d94605c37c473a67d8f
<ide><path>tests/TestCase/Routing/Middleware/RoutingMiddlewareTest.php <ide> public function testInvokeScopedMiddleware() <ide> 'REQUEST_URI' => '/api/ping', <ide> ]); <ide> $response = new Response(); <del> $next = function ($req, $res) { <add> $next = function ($req, $res, $next) { <ide> $this->log[] = 'last'; <ide> <del> return $res; <add> return $next($req, $res); <ide> }; <ide> $middleware = new RoutingMiddleware($this->app()); <ide> $result = $middleware($request, $response, $next); <del> $this->assertSame($response, $result, 'Should return result'); <ide> $this->assertSame(['second', 'first', 'last'], $this->log); <ide> } <ide> <ide> public function testInvokeScopedMiddlewareReturnResponse() <ide> $middleware = new RoutingMiddleware($this->app()); <ide> $result = $middleware($request, $response, $next); <ide> <del> $this->assertSame($response, $result, 'Should return result'); <ide> $this->assertSame(['first', 'second'], $this->log); <ide> } <ide> <ide> public function testInvokeScopedMiddlewareReturnResponseMainScope() <ide> $middleware = new RoutingMiddleware($this->app()); <ide> $result = $middleware($request, $response, $next); <ide> <del> $this->assertSame($response, $result, 'Should return result'); <ide> $this->assertSame(['first'], $this->log); <ide> } <ide> <ide> public function testInvokeScopedMiddlewareIsolatedScopes($url, $expected) <ide> }; <ide> $middleware = new RoutingMiddleware($this->app()); <ide> $result = $middleware($request, $response, $next); <del> $this->assertSame($response, $result, 'Should return result'); <ide> $this->assertSame($expected, $this->log); <ide> } <ide>
1
Text
Text
add docs for service create based on plugins
62d399e8112caacad93829d8faa1c15dfc4f694c
<ide><path>docs/extend/index.md <ide> remove it, use the `docker plugin remove` command. For other available <ide> commands and options, see the <ide> [command line reference](../reference/commandline/index.md). <ide> <add>## Service creation using plugins <add> <add>In swarm mode, it is possible to create a service that allows for attaching <add>to networks or mounting volumes. Swarm schedules services based on plugin availability <add>on a node. In this example, a volume plugin is installed on a swarm worker and a volume <add>is created using the plugin. In the manager, a service is created with the relevant <add>mount options. It can be observed that the service is scheduled to run on the worker <add>node with the said volume plugin and volume. <add> <add>In the following example, node1 is the manager and node2 is the worker. <add> <add>1. Prepare manager. In node 1: <add> <add> ```bash <add> $ docker swarm init <add> Swarm initialized: current node (dxn1zf6l61qsb1josjja83ngz) is now a manager. <add> ``` <add> <add>2. Join swarm, install plugin and create volume on worker. In node 2: <add> <add> ```bash <add> $ docker swarm join \ <add> --token SWMTKN-1-49nj1cmql0jkz5s954yi3oex3nedyz0fb0xx14ie39trti4wxv-8vxv8rssmk743ojnwacrr2e7c \ <add> 192.168.99.100:2377 <add> ``` <add> <add> ```bash <add> $ docker plugin install tiborvass/sample-volume-plugin <add> latest: Pulling from tiborvass/sample-volume-plugin <add> eb9c16fbdc53: Download complete <add> Digest: sha256:00b42de88f3a3e0342e7b35fa62394b0a9ceb54d37f4c50be5d3167899994639 <add> Status: Downloaded newer image for tiborvass/sample-volume-plugin:latest <add> Installed plugin tiborvass/sample-volume-plugin <add> ``` <add> <add> ```bash <add> $ docker volume create -d tiborvass/sample-volume-plugin --name pluginVol <add> ``` <add> <add>3. Create a service using the plugin and volume. In node1: <add> <add> ```bash <add> $ docker service create --name my-service --mount type=volume,volume-driver=tiborvass/sample-volume-plugin,source=pluginVol,destination=/tmp busybox top <add> <add> $ docker service ls <add> z1sj8bb8jnfn my-service replicated 1/1 busybox:latest <add> ``` <add> docker service ls shows service 1 instance of service running. <add> <add>4. Observe the task getting scheduled in node 2: <add> <add> ```bash <add> $ docker ps --format '{{.ID}}\t {{.Status}} {{.Names}} {{.Command}}' <add> 83fc1e842599 Up 2 days my-service.1.9jn59qzn7nbc3m0zt1hij12xs "top" <add> ``` <add> <ide> ## Developing a plugin <ide> <ide> #### The rootfs directory
1
Javascript
Javascript
avoid expensive work for filtered cached modules
b3e8245ce64aebbb688344a7f793e48a98072ef0
<ide><path>lib/stats/DefaultStatsFactoryPlugin.js <ide> const { makePathsRelative, parseResource } = require("../util/identifier"); <ide> * @property {ExtractorsByOption<ExtendedAsset>} asset <ide> * @property {ExtractorsByOption<{ name: string, chunkGroup: ChunkGroup }>} chunkGroup <ide> * @property {ExtractorsByOption<Module>} module <add> * @property {ExtractorsByOption<Module>} module$visible <ide> * @property {ExtractorsByOption<Module>} moduleIssuer <ide> * @property {ExtractorsByOption<ModuleProfile>} profile <ide> * @property {ExtractorsByOption<ModuleGraphConnection>} moduleReason <ide> const SIMPLE_EXTRACTORS = { <ide> } <ide> }, <ide> module: { <add> _: (object, module, context, options, factory) => { <add> const { compilation, type } = context; <add> const built = compilation.builtModules.has(module); <add> const codeGenerated = compilation.codeGeneratedModules.has(module); <add> const sizes = {}; <add> for (const sourceType of module.getSourceTypes()) { <add> sizes[sourceType] = module.size(sourceType); <add> } <add> Object.assign(object, { <add> type: "module", <add> moduleType: module.type, <add> size: module.size(), <add> sizes, <add> built, <add> codeGenerated, <add> cached: !built && !codeGenerated <add> }); <add> if (built || codeGenerated || options.cachedModules) { <add> Object.assign( <add> object, <add> factory.create(`${type}$visible`, module, context) <add> ); <add> } <add> } <add> }, <add> module$visible: { <ide> _: (object, module, context, { requestShortener }, factory) => { <ide> const { compilation, type, rootModules } = context; <ide> const { moduleGraph } = compilation; <ide> const SIMPLE_EXTRACTORS = { <ide> for (const sourceType of module.getSourceTypes()) { <ide> sizes[sourceType] = module.size(sourceType); <ide> } <del> const built = compilation.builtModules.has(module); <del> const codeGenerated = compilation.codeGeneratedModules.has(module); <ide> Object.assign(object, { <del> type: "module", <del> moduleType: module.type, <ide> identifier: module.identifier(), <ide> name: module.readableIdentifier(requestShortener), <ide> nameForCondition: module.nameForCondition(), <ide> index: moduleGraph.getPreOrderIndex(module), <ide> preOrderIndex: moduleGraph.getPreOrderIndex(module), <ide> index2: moduleGraph.getPostOrderIndex(module), <ide> postOrderIndex: moduleGraph.getPostOrderIndex(module), <del> size: module.size(), <del> sizes, <ide> cacheable: module.buildInfo.cacheable, <del> built, <del> codeGenerated, <del> cached: !built && !codeGenerated, <ide> optional: module.isOptional(moduleGraph), <ide> orphan: <del> !type.endsWith("module.modules[].module") && <add> !type.endsWith("module.modules[].module$visible") && <ide> compilation.chunkGraph.getNumberOfModuleChunks(module) === 0, <ide> dependent: rootModules ? !rootModules.has(module) : undefined, <ide> issuer: issuer && issuer.identifier(), <ide> issuerName: issuer && issuer.readableIdentifier(requestShortener), <ide> issuerPath: <del> issuer && factory.create(`${type}.issuerPath`, path, context), <add> issuer && <add> factory.create(`${type.slice(0, -8)}.issuerPath`, path, context), <ide> failed: errorsCount > 0, <ide> errors: errorsCount, <ide> warnings: warningsCount <ide> }); <ide> if (profile) { <del> object.profile = factory.create(`${type}.profile`, profile, context); <add> object.profile = factory.create( <add> `${type.slice(0, -8)}.profile`, <add> profile, <add> context <add> ); <ide> } <ide> }, <ide> ids: (object, module, { compilation: { chunkGraph, moduleGraph } }) => { <ide> const SIMPLE_EXTRACTORS = { <ide> compilation: { moduleGraph } <ide> } = context; <ide> object.reasons = factory.create( <del> `${type}.reasons`, <add> `${type.slice(0, -8)}.reasons`, <ide> Array.from(moduleGraph.getIncomingConnections(module)), <ide> context <ide> ); <ide> const SIMPLE_EXTRACTORS = { <ide> if (module instanceof ConcatenatedModule) { <ide> const modules = module.modules; <ide> const groupedModules = factory.create( <del> `${type}.modules`, <add> `${type.slice(0, -8)}.modules`, <ide> modules, <ide> context <ide> ); <ide> const MODULES_GROUPERS = type => ({ <ide> if (groupModulesByType || !options.runtimeModules) { <ide> groupConfigs.push({ <ide> getKeys: module => { <add> if (!module.moduleType) return; <ide> if (groupModulesByType) { <ide> return [module.moduleType.split("/", 1)[0]]; <ide> } else if (module.moduleType === "runtime") { <ide> const MODULES_GROUPERS = type => ({ <ide> if (groupModulesByPath || groupModulesByExtension) { <ide> groupConfigs.push({ <ide> getKeys: module => { <add> if (!module.name) return; <ide> const resource = parseResource(module.name.split("!").pop()).path; <ide> const extensionMatch = <ide> groupModulesByExtension && /(\.[^.]+)(?:\?.*|$)/.exec(resource);
1
Python
Python
improve docs for searchsorted
317ff845c7fc92bcab9e713e38f24cc898223f70
<ide><path>numpy/core/fromnumeric.py <ide> def searchsorted(a, v, side='left', sorter=None): <ide> corresponding elements in `v` were inserted before the indices, the <ide> order of `a` would be preserved. <ide> <add> Assuming that `a` is sorted: <add> <add> ====== ============================ <add> `side` returned index `i` satisfies <add> ====== ============================ <add> left ``a[i-1] < v <= a[i]`` <add> right ``a[i-1] <= v < a[i]`` <add> ====== ============================ <add> <ide> Parameters <ide> ---------- <ide> a : 1-D array_like <ide> def searchsorted(a, v, side='left', sorter=None): <ide> As of NumPy 1.4.0 `searchsorted` works with real/complex arrays containing <ide> `nan` values. The enhanced sort order is documented in `sort`. <ide> <add> This function is a faster version of the builtin python `bisect.bisect_left` <add> (``side='left'``) and `bisect.bisect_right` (``side='right'``) functions, <add> which is also vectorized in the `v` argument. <add> <ide> Examples <ide> -------- <ide> >>> np.searchsorted([1,2,3,4,5], 3)
1
Python
Python
update expected slices for pillow > 9
ec4e421b7ded2f6b1baa63c19f2c0b2c11a36d92
<ide><path>tests/beit/test_modeling_beit.py <ide> import unittest <ide> <ide> from datasets import load_dataset <add>from packaging import version <ide> <ide> from transformers import BeitConfig <ide> from transformers.file_utils import cached_property, is_torch_available, is_vision_available <ide> <ide> <ide> if is_vision_available(): <add> import PIL <ide> from PIL import Image <ide> <ide> from transformers import BeitFeatureExtractor <ide> def test_inference_semantic_segmentation(self): <ide> expected_shape = torch.Size((1, 150, 160, 160)) <ide> self.assertEqual(logits.shape, expected_shape) <ide> <del> expected_slice = torch.tensor( <del> [ <del> [[-4.9225, -2.3954, -3.0522], [-2.8822, -1.0046, -1.7561], [-2.9549, -1.3228, -2.1347]], <del> [[-5.8168, -3.4129, -4.0778], [-3.8651, -2.2214, -3.0277], [-3.8356, -2.4643, -3.3535]], <del> [[-0.0078, 3.9952, 4.0754], [2.9856, 4.6944, 5.0035], [3.2413, 4.7813, 4.9969]], <del> ] <del> ).to(torch_device) <add> is_pillow_less_than_9 = version.parse(PIL.__version__) < version.parse("9.0.0") <add> <add> if is_pillow_less_than_9: <add> expected_slice = torch.tensor( <add> [ <add> [[-4.9225, -2.3954, -3.0522], [-2.8822, -1.0046, -1.7561], [-2.9549, -1.3228, -2.1347]], <add> [[-5.8168, -3.4129, -4.0778], [-3.8651, -2.2214, -3.0277], [-3.8356, -2.4643, -3.3535]], <add> [[-0.0078, 3.9952, 4.0754], [2.9856, 4.6944, 5.0035], [3.2413, 4.7813, 4.9969]], <add> ], <add> device=torch_device, <add> ) <add> else: <add> expected_slice = torch.tensor( <add> [ <add> [[-4.8960, -2.3688, -3.0355], [-2.8478, -0.9836, -1.7418], [-2.9449, -1.3332, -2.1456]], <add> [[-5.8081, -3.4124, -4.1006], [-3.8561, -2.2081, -3.0323], [-3.8365, -2.4601, -3.3669]], <add> [[-0.0309, 3.9868, 4.0540], [2.9640, 4.6877, 4.9976], [3.2081, 4.7690, 4.9942]], <add> ], <add> device=torch_device, <add> ) <ide> <ide> self.assertTrue(torch.allclose(logits[0, :3, :3, :3], expected_slice, atol=1e-4)) <ide><path>tests/vilt/test_modeling_vilt.py <ide> import unittest <ide> <ide> from datasets import load_dataset <add>from packaging import version <ide> <ide> from transformers import ViltConfig, is_torch_available, is_vision_available <ide> from transformers.file_utils import cached_property <ide> from transformers.models.vilt.modeling_vilt import VILT_PRETRAINED_MODEL_ARCHIVE_LIST <ide> <ide> if is_vision_available(): <add> import PIL <ide> from PIL import Image <ide> <ide> from transformers import ViltProcessor <ide> def test_inference_natural_language_visual_reasoning(self): <ide> expected_shape = torch.Size([1, 2]) <ide> self.assertEqual(outputs.logits.shape, expected_shape) <ide> <del> expected_slice = torch.tensor([-2.4013, 2.9342]).to(torch_device) <add> is_pillow_less_than_9 = version.parse(PIL.__version__) < version.parse("9.0.0") <add> <add> if is_pillow_less_than_9: <add> expected_slice = torch.tensor( <add> [-2.4013, 2.9342], <add> device=torch_device, <add> ) <add> else: <add> expected_slice = torch.tensor( <add> [-2.3713, 2.9168], <add> device=torch_device, <add> ) <add> <ide> self.assertTrue(torch.allclose(outputs.logits[0, :3], expected_slice, atol=1e-4)) <ide><path>tests/vision_encoder_decoder/test_modeling_vision_encoder_decoder.py <ide> import unittest <ide> <ide> from datasets import load_dataset <add>from packaging import version <ide> <ide> from transformers.file_utils import cached_property, is_torch_available, is_vision_available <ide> from transformers.testing_utils import require_torch, require_vision, slow, torch_device <ide> <ide> <ide> if is_vision_available(): <add> import PIL <ide> from PIL import Image <ide> <ide> from transformers import TrOCRProcessor, ViTFeatureExtractor <ide> def test_inference_printed(self): <ide> expected_shape = torch.Size((1, 1, model.decoder.config.vocab_size)) <ide> self.assertEqual(outputs.logits.shape, expected_shape) <ide> <del> expected_slice = torch.tensor( <del> [-5.6816, -5.8388, 1.1398, -6.9034, 6.8505, -2.4393, 1.2284, -1.0232, -1.9661, -3.9210] <del> ).to(torch_device) <add> is_pillow_less_than_9 = version.parse(PIL.__version__) < version.parse("9.0.0") <add> <add> if is_pillow_less_than_9: <add> expected_slice = torch.tensor( <add> [-5.6816, -5.8388, 1.1398, -6.9034, 6.8505, -2.4393, 1.2284, -1.0232, -1.9661, -3.9210], <add> device=torch_device, <add> ) <add> else: <add> expected_slice = torch.tensor( <add> [-5.6844, -5.8372, 1.1518, -6.8984, 6.8587, -2.4453, 1.2347, -1.0241, -1.9649, -3.9109], <add> device=torch_device, <add> ) <ide> <ide> self.assertTrue(torch.allclose(logits[0, 0, :10], expected_slice, atol=1e-4)) <ide>
3
Text
Text
update changelog for 2.29.4
536ad0c348f2f99009755698f491080757a48221
<ide><path>CHANGELOG.md <ide> Changelog <ide> ========= <ide> <add>### 2.29.4 <add> <add>* Release Jul 6, 2022 <add> * [#6015](https://github.com/moment/moment/pull/6015) [bugfix] Fix ReDoS in preprocessRFC2822 regex <add> <ide> ### 2.29.3 [Full changelog](https://gist.github.com/ichernev/edebd440f49adcaec72e5e77b791d8be) <ide> <ide> * Release Apr 17, 2022
1
Ruby
Ruby
fix schema for members
8da6ba9cae21beae1ee3c379db7b7113d2731c9b
<ide><path>activerecord/test/schema/schema.rb <ide> t.integer :children_count, default: 0 <ide> t.integer :parent_id <ide> t.references :author, polymorphic: true <del> t.string :resource_id <add> t.integer :resource_id <ide> t.string :resource_type <ide> t.integer :developer_id <ide> t.datetime :updated_at
1
Javascript
Javascript
fix webcrypto jwk ec and okp import crv check
4420d5218cbedadd9045f886003df7b506112cc7
<ide><path>lib/internal/crypto/cfrg.js <ide> async function cfrgImportKey( <ide> throw lazyDOMException('Invalid JWK keyData', 'DataError'); <ide> if (keyData.kty !== 'OKP') <ide> throw lazyDOMException('Invalid key type', 'DataError'); <add> if (keyData.crv !== name) <add> throw lazyDOMException('Subtype mismatch', 'DataError'); <ide> const isPublic = keyData.d === undefined; <ide> <ide> if (usagesSet.size > 0 && keyData.use !== undefined) { <ide><path>lib/internal/crypto/ec.js <ide> async function ecImportKey( <ide> break; <ide> } <ide> case 'jwk': { <del> let curve; <ide> if (keyData == null || typeof keyData !== 'object') <ide> throw lazyDOMException('Invalid JWK keyData', 'DataError'); <ide> if (keyData.kty !== 'EC') <ide> throw lazyDOMException('Invalid key type', 'DataError'); <add> if (keyData.crv !== namedCurve) <add> throw lazyDOMException('Named curve mismatch', 'DataError'); <ide> <ide> if (keyData.d !== undefined) { <ide> verifyAcceptableEcKeyUse(name, 'private', usagesSet); <ide> async function ecImportKey( <ide> if (algorithm.name === 'ECDSA' && keyData.alg !== undefined) { <ide> if (typeof keyData.alg !== 'string') <ide> throw lazyDOMException('Invalid alg', 'DataError'); <add> let algNamedCurve; <ide> switch (keyData.alg) { <del> case 'ES256': curve = 'P-256'; break; <del> case 'ES384': curve = 'P-384'; break; <del> case 'ES512': curve = 'P-521'; break; <add> case 'ES256': algNamedCurve = 'P-256'; break; <add> case 'ES384': algNamedCurve = 'P-384'; break; <add> case 'ES512': algNamedCurve = 'P-521'; break; <ide> } <del> if (curve !== namedCurve) <add> if (algNamedCurve !== namedCurve) <ide> throw lazyDOMException('Named curve mismatch', 'DataError'); <ide> } <ide> <ide><path>test/parallel/test-webcrypto-export-import-cfrg.js <ide> async function testImportJwk({ name, publicUsages, privateUsages }, extractable) <ide> message: /key is not extractable/ <ide> }); <ide> } <add> <add> for (const crv of [undefined, name === 'Ed25519' ? 'Ed448' : 'Ed25519']) { <add> await assert.rejects( <add> subtle.importKey( <add> 'jwk', <add> { kty: jwk.kty, x: jwk.x, y: jwk.y, crv }, <add> { name }, <add> extractable, <add> publicUsages), <add> { message: /Subtype mismatch/ }); <add> <add> await assert.rejects( <add> subtle.importKey( <add> 'jwk', <add> { kty: jwk.kty, d: jwk.d, x: jwk.x, y: jwk.y, crv }, <add> { name }, <add> extractable, <add> publicUsages), <add> { message: /Subtype mismatch/ }); <add> } <ide> } <ide> <ide> (async function() { <ide><path>test/parallel/test-webcrypto-export-import-ec.js <ide> async function testImportJwk( <ide> message: /key is not extractable/ <ide> }); <ide> } <add> <add> for (const crv of [undefined, namedCurve === 'P-256' ? 'P-384' : 'P-256']) { <add> await assert.rejects( <add> subtle.importKey( <add> 'jwk', <add> { kty: jwk.kty, x: jwk.x, y: jwk.y, crv }, <add> { name, namedCurve }, <add> extractable, <add> publicUsages), <add> { message: /Named curve mismatch/ }); <add> <add> await assert.rejects( <add> subtle.importKey( <add> 'jwk', <add> { kty: jwk.kty, d: jwk.d, x: jwk.x, y: jwk.y, crv }, <add> { name, namedCurve }, <add> extractable, <add> publicUsages), <add> { message: /Named curve mismatch/ }); <add> } <ide> } <ide> <ide> (async function() {
4
Python
Python
remove redundant respects_app_option check
938b0b8b978292d5a5d1be383be2776b4c49f254
<ide><path>celery/bin/base.py <ide> def setup_app_from_commandline(self, argv): <ide> if config: <ide> os.environ['CELERY_CONFIG_MODULE'] = config <ide> if self.respects_app_option: <del> if app and self.respects_app_option: <add> if app: <ide> self.app = self.find_app(app) <ide> elif self.app is None: <ide> self.app = self.get_app(loader=loader)
1
Go
Go
handle capabilities in tar files
3b9953903b12eaca76655311bd44533768f6f3da
<ide><path>archive/archive.go <ide> func addTarFile(path, name string, tw *tar.Writer) error { <ide> hdr.Devmajor = int64(major(uint64(stat.Rdev))) <ide> hdr.Devminor = int64(minor(uint64(stat.Rdev))) <ide> } <add> <add> } <add> <add> capability, _ := Lgetxattr(path, "security.capability") <add> if capability != nil { <add> hdr.Xattrs = make(map[string]string) <add> hdr.Xattrs["security.capability"] = string(capability) <ide> } <ide> <ide> if err := tw.WriteHeader(hdr); err != nil {
1
Javascript
Javascript
fix refresh for expired timers
1fab8a92974ce555adca39baada1d199b4952fd7
<ide><path>lib/internal/timers.js <ide> Timeout.prototype.refresh = function() { <ide> Timeout.prototype.unref = function() { <ide> if (this[kRefed]) { <ide> this[kRefed] = false; <del> decRefCount(); <add> if (!this._destroyed) <add> decRefCount(); <ide> } <ide> return this; <ide> }; <ide> <ide> Timeout.prototype.ref = function() { <del> if (this[kRefed] === false) { <add> if (!this[kRefed]) { <ide> this[kRefed] = true; <del> incRefCount(); <add> if (!this._destroyed) <add> incRefCount(); <ide> } <ide> return this; <ide> }; <ide> <ide> Timeout.prototype.hasRef = function() { <del> return !!this[kRefed]; <add> return this[kRefed]; <ide> }; <ide> <ide> function TimersList(expiry, msecs) { <ide> function insertGuarded(item, refed, start) { <ide> <ide> insert(item, msecs, start); <ide> <del> if (!item[async_id_symbol] || item._destroyed) { <add> const isDestroyed = item._destroyed; <add> if (isDestroyed || !item[async_id_symbol]) { <ide> item._destroyed = false; <ide> initAsyncResource(item, 'Timeout'); <ide> } <ide> <del> if (refed === !item[kRefed]) { <add> if (isDestroyed) { <add> if (refed) <add> incRefCount(); <add> } else if (refed === !item[kRefed]) { <ide> if (refed) <ide> incRefCount(); <ide> else <ide> function getTimerCallbacks(runNextTicks) { <ide> const asyncId = timer[async_id_symbol]; <ide> <ide> if (!timer._onTimeout) { <del> if (timer[kRefed]) <del> refCount--; <del> timer[kRefed] = null; <del> <del> if (destroyHooksExist() && !timer._destroyed) { <del> emitDestroy(asyncId); <add> if (!timer._destroyed) { <ide> timer._destroyed = true; <add> <add> if (timer[kRefed]) <add> refCount--; <add> <add> if (destroyHooksExist()) <add> emitDestroy(asyncId); <ide> } <ide> continue; <ide> } <ide> function getTimerCallbacks(runNextTicks) { <ide> if (timer._repeat && timer._idleTimeout !== -1) { <ide> timer._idleTimeout = timer._repeat; <ide> insert(timer, timer._idleTimeout, start); <del> } else if (!timer._idleNext && !timer._idlePrev) { <add> } else if (!timer._idleNext && !timer._idlePrev && !timer._destroyed) { <add> timer._destroyed = true; <add> <ide> if (timer[kRefed]) <ide> refCount--; <del> timer[kRefed] = null; <ide> <del> if (destroyHooksExist() && !timer._destroyed) { <add> if (destroyHooksExist()) <ide> emitDestroy(asyncId); <del> } <del> timer._destroyed = true; <ide> } <ide> } <ide> <ide><path>lib/timers.js <ide> const { <ide> <ide> // Remove a timer. Cancels the timeout and resets the relevant timer properties. <ide> function unenroll(item) { <add> if (item._destroyed) <add> return; <add> <add> item._destroyed = true; <add> <ide> // Fewer checks may be possible, but these cover everything. <del> if (destroyHooksExist() && <del> item[async_id_symbol] !== undefined && <del> !item._destroyed) { <add> if (destroyHooksExist() && item[async_id_symbol] !== undefined) <ide> emitDestroy(item[async_id_symbol]); <del> } <del> item._destroyed = true; <ide> <ide> L.remove(item); <ide> <ide> function unenroll(item) { <ide> <ide> decRefCount(); <ide> } <del> item[kRefed] = null; <ide> <ide> // If active is called later, then we want to make sure not to insert again <ide> item._idleTimeout = -1; <ide><path>test/parallel/test-timers-refresh.js <ide> const { inspect } = require('util'); <ide> strictEqual(timer.refresh(), timer); <ide> } <ide> <add>// regular timer <add>{ <add> let called = false; <add> const timer = setTimeout(common.mustCall(() => { <add> if (!called) { <add> called = true; <add> process.nextTick(common.mustCall(() => { <add> timer.refresh(); <add> strictEqual(timer.hasRef(), true); <add> })); <add> } <add> }, 2), 1); <add>} <add> <ide> // interval <ide> { <ide> let called = 0;
3
PHP
PHP
avoid fail due to postgres ordering
36a51bdad5e7d21177b8fdbb3470399f9a73367c
<ide><path>lib/Cake/Test/Case/Controller/Component/PaginatorComponentTest.php <ide> public function testOutOfRangePageNumberGetsClamped() { <ide> <ide> /** <ide> * Test that a really REALLY large page number gets clamped to the max page size. <del> * <add> * <ide> * <ide> * @expectedException NotFoundException <ide> * @return void <ide> public function testPaginateOrderVirtualFieldSharedWithRealField() { <ide> ); <ide> $Controller->passedArgs = array('sort' => 'PaginatorControllerPost.title', 'dir' => 'asc'); <ide> $result = $Controller->paginate('PaginatorControllerComment'); <del> $this->assertEquals(array(1, 2, 3, 4, 5, 6), Hash::extract($result, '{n}.PaginatorControllerComment.id')); <add> $result = Hash::extract($result, '{n}.PaginatorControllerComment.id'); <add> sort($result); <add> $this->assertEquals(array(1, 2, 3, 4, 5, 6), $result); <ide> } <ide> <ide> /**
1
Javascript
Javascript
use module.exports = {}
9318f82937d08462c87750946b919b8991c827e2
<ide><path>lib/readline.js <ide> const isFullWidthCodePoint = internalReadline.isFullWidthCodePoint; <ide> const stripVTControlCharacters = internalReadline.stripVTControlCharacters; <ide> <ide> <del>exports.createInterface = function(input, output, completer, terminal) { <add>function createInterface(input, output, completer, terminal) { <ide> return new Interface(input, output, completer, terminal); <ide> }; <ide> <ide> Interface.prototype._refreshLine = function() { <ide> // first move to the bottom of the current line, based on cursor pos <ide> var prevRows = this.prevRows || 0; <ide> if (prevRows > 0) { <del> exports.moveCursor(this.output, 0, -prevRows); <add> moveCursor(this.output, 0, -prevRows); <ide> } <ide> <ide> // Cursor to left edge. <del> exports.cursorTo(this.output, 0); <add> cursorTo(this.output, 0); <ide> // erase data <del> exports.clearScreenDown(this.output); <add> clearScreenDown(this.output); <ide> <ide> // Write the prompt and the current buffer content. <ide> this._writeToOutput(line); <ide> Interface.prototype._refreshLine = function() { <ide> } <ide> <ide> // Move cursor to original position. <del> exports.cursorTo(this.output, cursorPos.cols); <add> cursorTo(this.output, cursorPos.cols); <ide> <ide> var diff = lineRows - cursorPos.rows; <ide> if (diff > 0) { <del> exports.moveCursor(this.output, 0, -diff); <add> moveCursor(this.output, 0, -diff); <ide> } <ide> <ide> this.prevRows = cursorPos.rows; <ide> Interface.prototype._moveCursor = function(dx) { <ide> this.line.substring(this.cursor, oldcursor) <ide> ); <ide> } <del> exports.moveCursor(this.output, diffWidth, 0); <add> moveCursor(this.output, diffWidth, 0); <ide> this.prevRows = newPos.rows; <ide> } else { <ide> this._refreshLine(); <ide> Interface.prototype._ttyWrite = function(s, key) { <ide> break; <ide> <ide> case 'l': // clear the whole screen <del> exports.cursorTo(this.output, 0, 0); <del> exports.clearScreenDown(this.output); <add> cursorTo(this.output, 0, 0); <add> clearScreenDown(this.output); <ide> this._refreshLine(); <ide> break; <ide> <ide> Interface.prototype._ttyWrite = function(s, key) { <ide> } <ide> }; <ide> <del> <del>exports.Interface = Interface; <del> <del> <ide> /** <ide> * accepts a readable Stream instance and makes it emit "keypress" events <ide> */ <ide> function emitKeypressEvents(stream, iface) { <ide> stream.on('newListener', onNewListener); <ide> } <ide> } <del>exports.emitKeypressEvents = emitKeypressEvents; <del> <ide> <ide> /** <ide> * moves the cursor to the x and y coordinate on the given stream <ide> function cursorTo(stream, x, y) { <ide> stream.write('\x1b[' + (y + 1) + ';' + (x + 1) + 'H'); <ide> } <ide> } <del>exports.cursorTo = cursorTo; <del> <ide> <ide> /** <ide> * moves the cursor relative to its current location <ide> function moveCursor(stream, dx, dy) { <ide> stream.write('\x1b[' + dy + 'B'); <ide> } <ide> } <del>exports.moveCursor = moveCursor; <del> <ide> <ide> /** <ide> * clears the current line the cursor is on: <ide> function clearLine(stream, dir) { <ide> stream.write('\x1b[2K'); <ide> } <ide> } <del>exports.clearLine = clearLine; <del> <ide> <ide> /** <ide> * clears the screen from the current position of the cursor down <ide> function clearScreenDown(stream) { <ide> <ide> stream.write('\x1b[0J'); <ide> } <del>exports.clearScreenDown = clearScreenDown; <add> <add>module.exports = { <add> Interface, <add> clearLine, <add> clearScreenDown, <add> createInterface, <add> cursorTo, <add> emitKeypressEvents, <add> moveCursor <add>};
1
Ruby
Ruby
add missing test case for quoting behavior
a8afc6395b9ccbbe62c6deaa01294b4bd3aac758
<ide><path>activerecord/test/cases/base_test.rb <ide> def test_find_by_slug <ide> assert_equal Topic.find('1-meowmeow'), Topic.find(1) <ide> end <ide> <add> def test_find_by_slug_with_array <add> assert_equal Topic.find(['1-meowmeow', '2-hello']), Topic.find([1, 2]) <add> end <add> <ide> def test_equality_of_new_records <ide> assert_not_equal Topic.new, Topic.new <ide> assert_equal false, Topic.new == Topic.new <ide><path>activerecord/test/cases/relations_test.rb <ide> def test_find_all_with_multiple_should_use_and <ide> assert_equal [], relation.to_a <ide> end <ide> <add> def test_typecasting_where_with_array <add> ids = Author.pluck(:id) <add> slugs = ids.map { |id| "#{id}-as-a-slug" } <add> <add> assert_equal Author.all.to_a, Author.where(id: slugs).to_a <add> end <add> <ide> def test_find_all_using_where_with_relation <ide> david = authors(:david) <ide> # switching the lines below would succeed in current rails
2
Ruby
Ruby
use current version in new_framework_defaults_*.rb
b2c5199d5107129ff81c2e6f44e7f6bb87a3b94a
<ide><path>railties/lib/rails/generators/rails/app/app_generator.rb <ide> def delete_api_initializers <ide> <ide> def delete_new_framework_defaults <ide> unless options[:update] <del> remove_file "config/initializers/new_framework_defaults_7_0.rb" <add> remove_file "config/initializers/new_framework_defaults_#{Rails::VERSION::MAJOR}_#{Rails::VERSION::MINOR}.rb" <ide> end <ide> end <ide> <ide><path>railties/test/generators/app_generator_test.rb <ide> def test_new_application_not_include_api_initializers <ide> <ide> def test_new_application_doesnt_need_defaults <ide> run_generator <del> assert_no_file "config/initializers/new_framework_defaults_7_0.rb" <add> assert_empty Dir.glob("config/initializers/new_framework_defaults_*.rb", base: destination_root) <ide> end <ide> <ide> def test_new_application_load_defaults <ide> def test_new_application_load_defaults <ide> end <ide> <ide> def test_app_update_create_new_framework_defaults <del> app_root = File.join(destination_root, "myapp") <del> run_generator [app_root] <add> run_generator <add> defaults_path = "config/initializers/new_framework_defaults_#{Rails::VERSION::MAJOR}_#{Rails::VERSION::MINOR}.rb" <ide> <del> assert_no_file "#{app_root}/config/initializers/new_framework_defaults_7_0.rb" <add> assert_no_file defaults_path <ide> <del> stub_rails_application(app_root) do <del> generator = Rails::Generators::AppGenerator.new ["rails"], { update: true }, { destination_root: app_root, shell: @shell } <add> stub_rails_application do <add> generator = Rails::Generators::AppGenerator.new ["rails"], { update: true }, { destination_root: destination_root, shell: @shell } <ide> generator.send(:app_const) <ide> quietly { generator.update_config_files } <ide> <del> assert_file "#{app_root}/config/initializers/new_framework_defaults_7_1.rb" <add> assert_file defaults_path <ide> end <ide> end <ide> <ide> def test_minimal_rails_app <ide> end <ide> <ide> private <del> def stub_rails_application(root, &block) <add> def stub_rails_application(root = destination_root, &block) <ide> Rails.application.config.root = root <ide> Rails.application.class.stub(:name, "Myapp", &block) <ide> end
2
Go
Go
fix possible segfault in config reload
7f3910c92e95d23b5f74a6abc1055ebae478080b
<ide><path>daemon/reload.go <ide> func (daemon *Daemon) reloadDebug(conf *config.Config, attributes map[string]str <ide> func (daemon *Daemon) reloadMaxConcurrentDownloadsAndUploads(conf *config.Config, attributes map[string]string) { <ide> // If no value is set for max-concurrent-downloads we assume it is the default value <ide> // We always "reset" as the cost is lightweight and easy to maintain. <add> maxConcurrentDownloads := config.DefaultMaxConcurrentDownloads <ide> if conf.IsValueSet("max-concurrent-downloads") && conf.MaxConcurrentDownloads != nil { <del> *daemon.configStore.MaxConcurrentDownloads = *conf.MaxConcurrentDownloads <del> } else { <del> maxConcurrentDownloads := config.DefaultMaxConcurrentDownloads <del> daemon.configStore.MaxConcurrentDownloads = &maxConcurrentDownloads <add> maxConcurrentDownloads = *conf.MaxConcurrentDownloads <ide> } <add> daemon.configStore.MaxConcurrentDownloads = &maxConcurrentDownloads <ide> logrus.Debugf("Reset Max Concurrent Downloads: %d", *daemon.configStore.MaxConcurrentDownloads) <ide> <ide> // If no value is set for max-concurrent-upload we assume it is the default value <ide> // We always "reset" as the cost is lightweight and easy to maintain. <add> maxConcurrentUploads := config.DefaultMaxConcurrentUploads <ide> if conf.IsValueSet("max-concurrent-uploads") && conf.MaxConcurrentUploads != nil { <del> *daemon.configStore.MaxConcurrentUploads = *conf.MaxConcurrentUploads <del> } else { <del> maxConcurrentUploads := config.DefaultMaxConcurrentUploads <del> daemon.configStore.MaxConcurrentUploads = &maxConcurrentUploads <add> maxConcurrentUploads = *conf.MaxConcurrentUploads <ide> } <add> daemon.configStore.MaxConcurrentUploads = &maxConcurrentUploads <ide> logrus.Debugf("Reset Max Concurrent Uploads: %d", *daemon.configStore.MaxConcurrentUploads) <ide> <del> daemon.imageService.UpdateConfig(conf.MaxConcurrentDownloads, conf.MaxConcurrentUploads) <add> if daemon.imageService != nil { <add> daemon.imageService.UpdateConfig(&maxConcurrentDownloads, &maxConcurrentUploads) <add> } <add> <ide> // prepare reload event attributes with updatable configurations <ide> attributes["max-concurrent-downloads"] = fmt.Sprintf("%d", *daemon.configStore.MaxConcurrentDownloads) <ide> // prepare reload event attributes with updatable configurations
1
Ruby
Ruby
add test for verbose brew outdated output
755d43d46dc20b9e646909e08de482141de83777
<ide><path>Library/Homebrew/test/cmd/outdated_spec.rb <ide> describe "brew outdated", :integration_test do <del> it "prints outdated Formulae" do <del> setup_test_formula "testball" <del> (HOMEBREW_CELLAR/"testball/0.0.1/foo").mkpath <add> context "quiet output" do <add> it "prints outdated Formulae" do <add> setup_test_formula "testball" <add> (HOMEBREW_CELLAR/"testball/0.0.1/foo").mkpath <ide> <del> expect { brew "outdated" } <del> .to output("testball\n").to_stdout <del> .and not_to_output.to_stderr <del> .and be_a_success <add> expect { brew "outdated" } <add> .to output("testball\n").to_stdout <add> .and not_to_output.to_stderr <add> .and be_a_success <add> end <add> end <add> <add> context "verbose output" do <add> it "prints out the installed and newer versions" do <add> setup_test_formula "testball" <add> (HOMEBREW_CELLAR/"testball/0.0.1/foo").mkpath <add> <add> expect { brew "outdated", "--verbose" } <add> .to output("testball (0.0.1) < 0.1\n").to_stdout <add> .and not_to_output.to_stderr <add> .and be_a_success <add> end <ide> end <ide> end
1
Ruby
Ruby
fix word order in documentation for with_lock
1489e4f20841b46ebca1ca065c60fb0f2e553e46
<ide><path>activerecord/lib/active_record/locking/pessimistic.rb <ide> def lock!(lock = true) <ide> end <ide> <ide> # Wraps the passed block in a transaction, locking the object <del> # before yielding. You pass can the SQL locking clause <add> # before yielding. You can pass the SQL locking clause <ide> # as argument (see <tt>lock!</tt>). <ide> def with_lock(lock = true) <ide> transaction do
1
Javascript
Javascript
remove email verification
78dac937f7bf7cc5484c9e7ff472cacb92bb2959
<ide><path>server/boot/user.js <ide> var _ = require('lodash'), <ide> secrets = require('../../config/secrets'); <ide> <ide> module.exports = function(app) { <add> // NOTE(berks): user email validation currently not needed but build in. This <add> // work around should let us sneak by <add> // see: <add> // https://github.com/strongloop/loopback/issues/1137#issuecomment-109200135 <add> delete app.models.User.validations.email; <add> <ide> var router = app.loopback.Router(); <ide> var User = app.models.User; <ide> var Story = app.models.Story;
1
Ruby
Ruby
fix inheritance in formula.rb
498ef3372c2ca43d359071701cff810f9d7139bc
<ide><path>Library/Homebrew/formula.rb <ide> def keg_only reason <ide> end <ide> <ide> # see ack.rb for an example usage <del>class ScriptFileFormula <Formula <add>class ScriptFileFormula < Formula <ide> def install <ide> bin.install Dir['*'] <ide> end <ide> end <ide> <ide> # see flac.rb for example usage <del>class GithubGistFormula <ScriptFileFormula <add>class GithubGistFormula < ScriptFileFormula <ide> def initialize name='__UNKNOWN__', path=nil <ide> super name <ide> @version=File.basename(File.dirname(url))[0,6]
1
Go
Go
remove random package
66cfe61f71252f528ddb458d554cd241e996d9f1
<ide><path>pkg/namesgenerator/names-generator.go <ide> package namesgenerator <ide> <ide> import ( <ide> "fmt" <del> <del> "github.com/docker/docker/pkg/random" <add> "math/rand" <ide> ) <ide> <ide> var ( <ide> var ( <ide> // formatted as "adjective_surname". For example 'focused_turing'. If retry is non-zero, a random <ide> // integer between 0 and 10 will be added to the end of the name, e.g `focused_turing3` <ide> func GetRandomName(retry int) string { <del> rnd := random.Rand <ide> begin: <del> name := fmt.Sprintf("%s_%s", left[rnd.Intn(len(left))], right[rnd.Intn(len(right))]) <add> name := fmt.Sprintf("%s_%s", left[rand.Intn(len(left))], right[rand.Intn(len(right))]) <ide> if name == "boring_wozniak" /* Steve Wozniak is not boring */ { <ide> goto begin <ide> } <ide> <ide> if retry > 0 { <del> name = fmt.Sprintf("%s%d", name, rnd.Intn(10)) <add> name = fmt.Sprintf("%s%d", name, rand.Intn(10)) <ide> } <ide> return name <ide> } <ide><path>pkg/random/random.go <del>package random <del> <del>import ( <del> cryptorand "crypto/rand" <del> "io" <del> "math" <del> "math/big" <del> "math/rand" <del> "sync" <del> "time" <del>) <del> <del>// Rand is a global *rand.Rand instance, which initialized with NewSource() source. <del>var Rand = rand.New(NewSource()) <del> <del>// Reader is a global, shared instance of a pseudorandom bytes generator. <del>// It doesn't consume entropy. <del>var Reader io.Reader = &reader{rnd: Rand} <del> <del>// copypaste from standard math/rand <del>type lockedSource struct { <del> lk sync.Mutex <del> src rand.Source <del>} <del> <del>func (r *lockedSource) Int63() (n int64) { <del> r.lk.Lock() <del> n = r.src.Int63() <del> r.lk.Unlock() <del> return <del>} <del> <del>func (r *lockedSource) Seed(seed int64) { <del> r.lk.Lock() <del> r.src.Seed(seed) <del> r.lk.Unlock() <del>} <del> <del>// NewSource returns math/rand.Source safe for concurrent use and initialized <del>// with current unix-nano timestamp <del>func NewSource() rand.Source { <del> var seed int64 <del> if cryptoseed, err := cryptorand.Int(cryptorand.Reader, big.NewInt(math.MaxInt64)); err != nil { <del> // This should not happen, but worst-case fallback to time-based seed. <del> seed = time.Now().UnixNano() <del> } else { <del> seed = cryptoseed.Int64() <del> } <del> return &lockedSource{ <del> src: rand.NewSource(seed), <del> } <del>} <del> <del>type reader struct { <del> rnd *rand.Rand <del>} <del> <del>func (r *reader) Read(b []byte) (int, error) { <del> i := 0 <del> for { <del> val := r.rnd.Int63() <del> for val > 0 { <del> b[i] = byte(val) <del> i++ <del> if i == len(b) { <del> return i, nil <del> } <del> val >>= 8 <del> } <del> } <del>} <ide><path>pkg/random/random_test.go <del>package random <del> <del>import ( <del> "math/rand" <del> "sync" <del> "testing" <del>) <del> <del>// for go test -v -race <del>func TestConcurrency(t *testing.T) { <del> rnd := rand.New(NewSource()) <del> var wg sync.WaitGroup <del> <del> for i := 0; i < 10; i++ { <del> wg.Add(1) <del> go func() { <del> rnd.Int63() <del> wg.Done() <del> }() <del> } <del> wg.Wait() <del>} <ide><path>pkg/stringid/stringid.go <ide> package stringid <ide> <ide> import ( <del> "crypto/rand" <add> cryptorand "crypto/rand" <ide> "encoding/hex" <ide> "fmt" <ide> "io" <add> "math" <add> "math/big" <add> "math/rand" <ide> "regexp" <ide> "strconv" <ide> "strings" <del> <del> "github.com/docker/docker/pkg/random" <add> "time" <ide> ) <ide> <ide> const shortLen = 12 <ide> func TruncateID(id string) string { <ide> return id <ide> } <ide> <del>func generateID(crypto bool) string { <add>func generateID(r io.Reader) string { <ide> b := make([]byte, 32) <del> r := random.Reader <del> if crypto { <del> r = rand.Reader <del> } <ide> for { <ide> if _, err := io.ReadFull(r, b); err != nil { <ide> panic(err) // This shouldn't happen <ide> func generateID(crypto bool) string { <ide> <ide> // GenerateRandomID returns a unique id. <ide> func GenerateRandomID() string { <del> return generateID(true) <add> return generateID(cryptorand.Reader) <ide> } <ide> <ide> // GenerateNonCryptoID generates unique id without using cryptographically <ide> // secure sources of random. <ide> // It helps you to save entropy. <ide> func GenerateNonCryptoID() string { <del> return generateID(false) <add> return generateID(readerFunc(rand.Read)) <ide> } <ide> <ide> // ValidateID checks whether an ID string is a valid image ID. <ide> func ValidateID(id string) error { <ide> } <ide> return nil <ide> } <add> <add>func init() { <add> // safely set the seed globally so we generate random ids. Tries to use a <add> // crypto seed before falling back to time. <add> var seed int64 <add> if cryptoseed, err := cryptorand.Int(cryptorand.Reader, big.NewInt(math.MaxInt64)); err != nil { <add> // This should not happen, but worst-case fallback to time-based seed. <add> seed = time.Now().UnixNano() <add> } else { <add> seed = cryptoseed.Int64() <add> } <add> <add> rand.Seed(seed) <add>} <add> <add>type readerFunc func(p []byte) (int, error) <add> <add>func (fn readerFunc) Read(p []byte) (int, error) { <add> return fn(p) <add>} <ide><path>pkg/stringutils/stringutils.go <ide> import ( <ide> "bytes" <ide> "math/rand" <ide> "strings" <del> <del> "github.com/docker/docker/pkg/random" <ide> ) <ide> <ide> // GenerateRandomAlphaOnlyString generates an alphabetical random string with length n. <ide> func GenerateRandomAlphaOnlyString(n int) string { <ide> letters := []byte("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ") <ide> b := make([]byte, n) <ide> for i := range b { <del> b[i] = letters[random.Rand.Intn(len(letters))] <add> b[i] = letters[rand.Intn(len(letters))] <ide> } <ide> return string(b) <ide> }
5
PHP
PHP
trigger deprecation warning
b1562ed4d8b789e223d0d1b0e2c59224feff1002
<ide><path>src/View/Helper/HtmlHelper.php <ide> public function addCrumb($name, $link = null, array $options = []) <ide> */ <ide> public function docType($type = 'html5') <ide> { <add> deprecationWarning('HtmlHelper::docType() is deprecated and will be removed in 4.0.0'); <add> <ide> if (isset($this->_docTypes[$type])) { <ide> return $this->_docTypes[$type]; <ide> } <ide><path>tests/TestCase/View/Helper/HtmlHelperTest.php <ide> public function tearDown() <ide> */ <ide> public function testDocType() <ide> { <del> $result = $this->Html->docType(); <del> $expected = '<!DOCTYPE html>'; <del> $this->assertEquals($expected, $result); <add> $this->deprecated(function () { <add> $result = $this->Html->docType(); <add> $expected = '<!DOCTYPE html>'; <add> $this->assertEquals($expected, $result); <ide> <del> $result = $this->Html->docType('html4-strict'); <del> $expected = '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">'; <del> $this->assertEquals($expected, $result); <add> $result = $this->Html->docType('html4-strict'); <add> $expected = '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">'; <add> $this->assertEquals($expected, $result); <ide> <del> $this->assertNull($this->Html->docType('non-existing-doctype')); <add> $this->assertNull($this->Html->docType('non-existing-doctype')); <add> }); <ide> } <ide> <ide> /**
2
Javascript
Javascript
remove excess indentation
0d22858d67f5f8f7959a55ceca23adafe12827d5
<ide><path>lib/_tls_legacy.js <ide> Object.defineProperty(CryptoStream.prototype, 'bytesWritten', { <ide> CryptoStream.prototype.getPeerCertificate = function(detailed) { <ide> if (this.pair.ssl) { <ide> return common.translatePeerCertificate( <del> this.pair.ssl.getPeerCertificate(detailed)); <add> this.pair.ssl.getPeerCertificate(detailed)); <ide> } <ide> <ide> return null; <ide><path>lib/_tls_wrap.js <ide> TLSSocket.prototype.setSession = function(session) { <ide> TLSSocket.prototype.getPeerCertificate = function(detailed) { <ide> if (this._handle) { <ide> return common.translatePeerCertificate( <del> this._handle.getPeerCertificate(detailed)); <add> this._handle.getPeerCertificate(detailed)); <ide> } <ide> <ide> return null; <ide><path>lib/async_hooks.js <ide> function fatalError(e) { <ide> Error.captureStackTrace(o, fatalError); <ide> process._rawDebug(o.stack); <ide> } <del> if (process.execArgv.some( <del> (e) => /^--abort[_-]on[_-]uncaught[_-]exception$/.test(e))) { <add> if (process.execArgv.some((e) => /^--abort[_-]on[_-]uncaught[_-]exception$/.test(e))) { <ide> process.abort(); <ide> } <ide> process.exit(1); <ide> function init(asyncId, type, triggerAsyncId, resource) { <ide> for (var i = 0; i < active_hooks_array.length; i++) { <ide> if (typeof active_hooks_array[i][init_symbol] === 'function') { <ide> active_hooks_array[i][init_symbol]( <del> asyncId, type, triggerAsyncId, <del> resource <add> asyncId, type, triggerAsyncId, <add> resource <ide> ); <ide> } <ide> } <ide><path>lib/buffer.js <ide> function slowIndexOf(buffer, val, byteOffset, encoding, dir) { <ide> case 'ascii': <ide> case 'hex': <ide> return binding.indexOfBuffer( <del> buffer, Buffer.from(val, encoding), byteOffset, encoding, dir); <add> buffer, Buffer.from(val, encoding), byteOffset, encoding, dir); <ide> <ide> default: <ide> if (loweredCase) { <ide><path>lib/child_process.js <ide> exports.fork = function(modulePath /*, args, options*/) { <ide> // Use a separate fd=3 for the IPC channel. Inherit stdin, stdout, <ide> // and stderr from the parent if silent isn't set. <ide> options.stdio = options.silent ? stdioStringToArray('pipe') : <del> stdioStringToArray('inherit'); <add> stdioStringToArray('inherit'); <ide> } else if (options.stdio.indexOf('ipc') === -1) { <ide> throw new TypeError('Forked processes must have an IPC channel'); <ide> } <ide> function spawnSync(/*file, args, options*/) { <ide> pipe.input = Buffer.from(input, options.encoding); <ide> } else { <ide> throw new TypeError(util.format( <del> 'stdio[%d] should be Buffer, Uint8Array or string not %s', <del> i, <del> typeof input)); <add> 'stdio[%d] should be Buffer, Uint8Array or string not %s', <add> i, <add> typeof input)); <ide> } <ide> } <ide> } <ide><path>lib/crypto.js <ide> function pbkdf2(password, salt, iterations, keylen, digest, callback) { <ide> <ide> if (digest === undefined) { <ide> throw new TypeError( <del> 'The "digest" argument is required and must not be undefined'); <add> 'The "digest" argument is required and must not be undefined'); <ide> } <ide> <ide> password = toBuf(password); <ide><path>lib/fs.js <ide> function isFd(path) { <ide> <ide> // Constructor for file stats. <ide> function Stats( <del> dev, <del> mode, <del> nlink, <del> uid, <del> gid, <del> rdev, <del> blksize, <del> ino, <del> size, <del> blocks, <del> atim_msec, <del> mtim_msec, <del> ctim_msec, <del> birthtim_msec) { <add> dev, <add> mode, <add> nlink, <add> uid, <add> gid, <add> rdev, <add> blksize, <add> ino, <add> size, <add> blocks, <add> atim_msec, <add> mtim_msec, <add> ctim_msec, <add> birthtim_msec <add>) { <ide> this.dev = dev; <ide> this.mode = mode; <ide> this.nlink = nlink; <ide> fs.writeFile = function(path, data, options, callback) { <ide> <ide> function writeFd(fd, isUserFd) { <ide> var buffer = isUint8Array(data) ? <del> data : Buffer.from('' + data, options.encoding || 'utf8'); <add> data : Buffer.from('' + data, options.encoding || 'utf8'); <ide> var position = /a/.test(flag) ? null : 0; <ide> <ide> writeAll(fd, isUserFd, buffer, 0, buffer.length, position, callback); <ide><path>lib/inspector.js <ide> class Session extends EventEmitter { <ide> post(method, params, callback) { <ide> if (typeof method !== 'string') { <ide> throw new TypeError( <del> `"method" must be a string, got ${typeof method} instead`); <add> `"method" must be a string, got ${typeof method} instead`); <ide> } <ide> if (!callback && util.isFunction(params)) { <ide> callback = params; <ide> params = null; <ide> } <ide> if (params && typeof params !== 'object') { <ide> throw new TypeError( <del> `"params" must be an object, got ${typeof params} instead`); <add> `"params" must be an object, got ${typeof params} instead`); <ide> } <ide> if (callback && typeof callback !== 'function') { <ide> throw new TypeError( <del> `"callback" must be a function, got ${typeof callback} instead`); <add> `"callback" must be a function, got ${typeof callback} instead`); <ide> } <ide> <ide> if (!this[connectionSymbol]) { <ide><path>lib/internal/bootstrap_node.js <ide> if (async_hook_fields[kAfter] > 0) { <ide> do { <ide> NativeModule.require('async_hooks').emitAfter( <del> async_uid_fields[kCurrentAsyncId]); <add> async_uid_fields[kCurrentAsyncId]); <ide> // popAsyncIds() returns true if there are more ids on the stack. <ide> } while (popAsyncIds(async_uid_fields[kCurrentAsyncId])); <ide> // Or completely empty the id stack. <ide><path>lib/internal/child_process.js <ide> ChildProcess.prototype.spawn = function(options) { <ide> // when i === 0 - we're dealing with stdin <ide> // (which is the only one writable pipe) <ide> stream.socket = createSocket(this.pid !== 0 ? <del> stream.handle : null, i > 0); <add> stream.handle : null, i > 0); <ide> <ide> if (i > 0 && this.pid !== 0) { <ide> this._closesNeeded++; <ide> ChildProcess.prototype.spawn = function(options) { <ide> } <ide> <ide> this.stdin = stdio.length >= 1 && stdio[0].socket !== undefined ? <del> stdio[0].socket : null; <add> stdio[0].socket : null; <ide> this.stdout = stdio.length >= 2 && stdio[1].socket !== undefined ? <del> stdio[1].socket : null; <add> stdio[1].socket : null; <ide> this.stderr = stdio.length >= 3 && stdio[2].socket !== undefined ? <del> stdio[2].socket : null; <add> stdio[2].socket : null; <ide> <ide> this.stdio = []; <ide> <ide><path>lib/internal/readline.js <ide> if (process.binding('config').hasIntl) { <ide> <ide> // Code points are derived from: <ide> // http://www.unicode.org/Public/UNIDATA/EastAsianWidth.txt <del> if (code >= 0x1100 && ( <add> if ( <add> code >= 0x1100 && ( <ide> code <= 0x115f || // Hangul Jamo <ide> 0x2329 === code || // LEFT-POINTING ANGLE BRACKET <ide> 0x232a === code || // RIGHT-POINTING ANGLE BRACKET <ide> if (process.binding('config').hasIntl) { <ide> // Enclosed Ideographic Supplement <ide> 0x1f200 <= code && code <= 0x1f251 || <ide> // CJK Unified Ideographs Extension B .. Tertiary Ideographic Plane <del> 0x20000 <= code && code <= 0x3fffd)) { <add> 0x20000 <= code && code <= 0x3fffd <add> ) <add> ) { <ide> return true; <ide> } <ide> <ide><path>lib/readline.js <ide> Interface.prototype._moveCursor = function(dx) { <ide> var diffWidth; <ide> if (diffCursor < 0) { <ide> diffWidth = -getStringWidth( <del> this.line.substring(this.cursor, oldcursor) <del> ); <add> this.line.substring(this.cursor, oldcursor) <add> ); <ide> } else if (diffCursor > 0) { <ide> diffWidth = getStringWidth( <del> this.line.substring(this.cursor, oldcursor) <del> ); <add> this.line.substring(this.cursor, oldcursor) <add> ); <ide> } <ide> moveCursor(this.output, diffWidth, 0); <ide> this.prevRows = newPos.rows; <ide><path>lib/timers.js <ide> function listOnTimeout() { <ide> function tryOnTimeout(timer, list) { <ide> timer._called = true; <ide> const timerAsyncId = (typeof timer[async_id_symbol] === 'number') ? <del> timer[async_id_symbol] : null; <add> timer[async_id_symbol] : null; <ide> var threw = true; <ide> if (timerAsyncId !== null) <ide> emitBefore(timerAsyncId, timer[trigger_id_symbol]); <ide><path>lib/tls.js <ide> exports.checkServerIdentity = function checkServerIdentity(host, cert) { <ide> <ide> if (!valid) { <ide> const err = new Error( <del> `Hostname/IP doesn't match certificate's altnames: "${reason}"`); <add> `Hostname/IP doesn't match certificate's altnames: "${reason}"`); <ide> err.reason = reason; <ide> err.host = host; <ide> err.cert = cert; <ide><path>lib/url.js <ide> Url.prototype.resolveObject = function resolveObject(relative) { <ide> <ide> var isSourceAbs = (result.pathname && result.pathname.charAt(0) === '/'); <ide> var isRelAbs = ( <del> relative.host || <del> relative.pathname && relative.pathname.charAt(0) === '/' <add> relative.host || relative.pathname && relative.pathname.charAt(0) === '/' <ide> ); <ide> var mustEndAbs = (isRelAbs || isSourceAbs || <ide> (result.host && relative.pathname)); <ide> Url.prototype.resolveObject = function resolveObject(relative) { <ide> // then it must NOT get a trailing slash. <ide> var last = srcPath.slice(-1)[0]; <ide> var hasTrailingSlash = ( <del> (result.host || relative.host || srcPath.length > 1) && <del> (last === '.' || last === '..') || last === ''); <add> (result.host || relative.host || srcPath.length > 1) && <add> (last === '.' || last === '..') || last === ''); <ide> <ide> // strip single dots, resolve double dots to parent dir <ide> // if the path tries to go above the root, `up` ends up > 0 <ide><path>lib/util.js <ide> function formatValue(ctx, value, recurseTimes) { <ide> if (typeof value === 'function') { <ide> const ctorName = constructor ? constructor.name : 'Function'; <ide> return ctx.stylize( <del> `[${ctorName}${value.name ? `: ${value.name}` : ''}]`, 'special'); <add> `[${ctorName}${value.name ? `: ${value.name}` : ''}]`, 'special'); <ide> } <ide> if (isRegExp(value)) { <ide> return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); <ide> function formatTypedArray(ctx, value, recurseTimes, visibleKeys, keys) { <ide> for (const key of keys) { <ide> if (typeof key === 'symbol' || !numbersOnlyRE.test(key)) { <ide> output.push( <del> formatProperty(ctx, value, recurseTimes, visibleKeys, key, true)); <add> formatProperty(ctx, value, recurseTimes, visibleKeys, key, true)); <ide> } <ide> } <ide> return output;
16
Text
Text
fix typo in readme
13ccf784986107a339218b3d43a7e4ce3bdfd919
<ide><path>readme.md <ide> Router.onAppUpdated = (nextUrl) => { <ide> </ul> <ide> </details></p> <ide> <del>Shallow routig allows you to change the URL without running `getInitialProps`. You'll receive the updated `pathname` and the `query` via the `url` prop of the same page that's loaded, without losing state. <add>Shallow routing allows you to change the URL without running `getInitialProps`. You'll receive the updated `pathname` and the `query` via the `url` prop of the same page that's loaded, without losing state. <ide> <ide> You can do this by invoking the eith `Router.push` or `Router.replace` with `shallow: true` option. Here's an example: <ide>
1
PHP
PHP
fix undefined variable error for id
0e33004fee1df5574bcc28ea95f2ada16f5ad8ae
<ide><path>src/Illuminate/Queue/Console/RetryBatchCommand.php <ide> class RetryBatchCommand extends Command <ide> */ <ide> public function handle() <ide> { <del> $batch = $this->laravel[BatchRepository::class]->find($this->argument('id')); <add> $batch = $this->laravel[BatchRepository::class]->find($id = $this->argument('id')); <ide> <ide> if (! $batch) { <ide> $this->error("Unable to find a batch with ID [{$id}].");
1
Ruby
Ruby
cache the formatter on the path object
c99ff6df0031a10d67d6185597085a6bcbeee114
<ide><path>actionpack/lib/action_dispatch/journey/path/pattern.rb <ide> def initialize(strexp) <ide> @required_names = nil <ide> @re = nil <ide> @offsets = nil <add> @format = Visitors::FormatBuilder.new.accept(spec) <add> end <add> <add> def format_path(path_options) <add> @format.evaluate path_options <ide> end <ide> <ide> def ast <ide><path>actionpack/lib/action_dispatch/journey/route.rb <ide> def format(path_options) <ide> value.to_s == defaults[key].to_s && !required_parts.include?(key) <ide> end <ide> <del> format = Visitors::FormatBuilder.new.accept(path.spec) <del> format.evaluate path_options <add> path.format_path path_options <ide> end <ide> <ide> def optimized_path
2
Ruby
Ruby
fix incorrect output
82aedbb96d2d6326a2700413ef16890499e11014
<ide><path>activemodel/lib/active_model/errors.rb <ide> def add_on_blank(attributes, options = {}) <ide> # <ide> # company = Company.create(:address => '123 First St.') <ide> # company.errors.full_messages # => <del> # ["Name is too short (minimum is 5 characters)", "Name can't be blank", "Address can't be blank"] <add> # ["Name is too short (minimum is 5 characters)", "Name can't be blank", "Email can't be blank"] <ide> def full_messages <ide> map { |attribute, message| <ide> if attribute == :base
1
Go
Go
add timeouts for volume plugin ops
b15f8d2d4f054a87052a7065c50441f7e8479fa9
<ide><path>pkg/plugins/client.go <ide> package plugins <ide> <ide> import ( <ide> "bytes" <add> "context" <ide> "encoding/json" <ide> "io" <ide> "io/ioutil" <ide> "net/http" <ide> "net/url" <ide> "time" <ide> <add> "github.com/docker/docker/pkg/ioutils" <ide> "github.com/docker/docker/pkg/plugins/transport" <ide> "github.com/docker/go-connections/sockets" <ide> "github.com/docker/go-connections/tlsconfig" <ide> type Client struct { <ide> requestFactory transport.RequestFactory <ide> } <ide> <add>// RequestOpts is the set of options that can be passed into a request <add>type RequestOpts struct { <add> Timeout time.Duration <add>} <add> <add>// WithRequestTimeout sets a timeout duration for plugin requests <add>func WithRequestTimeout(t time.Duration) func(*RequestOpts) { <add> return func(o *RequestOpts) { <add> o.Timeout = t <add> } <add>} <add> <ide> // Call calls the specified method with the specified arguments for the plugin. <ide> // It will retry for 30 seconds if a failure occurs when calling. <del>func (c *Client) Call(serviceMethod string, args interface{}, ret interface{}) error { <add>func (c *Client) Call(serviceMethod string, args, ret interface{}) error { <add> return c.CallWithOptions(serviceMethod, args, ret) <add>} <add> <add>// CallWithOptions is just like call except it takes options <add>func (c *Client) CallWithOptions(serviceMethod string, args interface{}, ret interface{}, opts ...func(*RequestOpts)) error { <ide> var buf bytes.Buffer <ide> if args != nil { <ide> if err := json.NewEncoder(&buf).Encode(args); err != nil { <ide> return err <ide> } <ide> } <del> body, err := c.callWithRetry(serviceMethod, &buf, true) <add> body, err := c.callWithRetry(serviceMethod, &buf, true, opts...) <ide> if err != nil { <ide> return err <ide> } <ide> func (c *Client) SendFile(serviceMethod string, data io.Reader, ret interface{}) <ide> return nil <ide> } <ide> <del>func (c *Client) callWithRetry(serviceMethod string, data io.Reader, retry bool) (io.ReadCloser, error) { <add>func (c *Client) callWithRetry(serviceMethod string, data io.Reader, retry bool, reqOpts ...func(*RequestOpts)) (io.ReadCloser, error) { <ide> var retries int <ide> start := time.Now() <ide> <add> var opts RequestOpts <add> for _, o := range reqOpts { <add> o(&opts) <add> } <add> <ide> for { <ide> req, err := c.requestFactory.NewRequest(serviceMethod, data) <ide> if err != nil { <ide> return nil, err <ide> } <ide> <add> cancelRequest := func() {} <add> if opts.Timeout > 0 { <add> var ctx context.Context <add> ctx, cancelRequest = context.WithTimeout(req.Context(), opts.Timeout) <add> req = req.WithContext(ctx) <add> } <add> <ide> resp, err := c.http.Do(req) <ide> if err != nil { <add> cancelRequest() <ide> if !retry { <ide> return nil, err <ide> } <ide> func (c *Client) callWithRetry(serviceMethod string, data io.Reader, retry bool) <ide> if resp.StatusCode != http.StatusOK { <ide> b, err := ioutil.ReadAll(resp.Body) <ide> resp.Body.Close() <add> cancelRequest() <ide> if err != nil { <ide> return nil, &statusError{resp.StatusCode, serviceMethod, err.Error()} <ide> } <ide> func (c *Client) callWithRetry(serviceMethod string, data io.Reader, retry bool) <ide> // old way... <ide> return nil, &statusError{resp.StatusCode, serviceMethod, string(b)} <ide> } <del> return resp.Body, nil <add> return ioutils.NewReadCloserWrapper(resp.Body, func() error { <add> err := resp.Body.Close() <add> cancelRequest() <add> return err <add> }), nil <ide> } <ide> } <ide> <ide><path>volume/drivers/proxy.go <ide> package volumedrivers <ide> <ide> import ( <ide> "errors" <add> "time" <ide> <add> "github.com/docker/docker/pkg/plugins" <ide> "github.com/docker/docker/volume" <ide> ) <ide> <add>const ( <add> longTimeout = 2 * time.Minute <add> shortTimeout = 1 * time.Minute <add>) <add> <ide> type client interface { <del> Call(string, interface{}, interface{}) error <add> CallWithOptions(string, interface{}, interface{}, ...func(*plugins.RequestOpts)) error <ide> } <ide> <ide> type volumeDriverProxy struct { <ide> func (pp *volumeDriverProxy) Create(name string, opts map[string]string) (err er <ide> <ide> req.Name = name <ide> req.Opts = opts <del> if err = pp.Call("VolumeDriver.Create", req, &ret); err != nil { <add> <add> if err = pp.CallWithOptions("VolumeDriver.Create", req, &ret, plugins.WithRequestTimeout(longTimeout)); err != nil { <ide> return <ide> } <ide> <ide> func (pp *volumeDriverProxy) Remove(name string) (err error) { <ide> ) <ide> <ide> req.Name = name <del> if err = pp.Call("VolumeDriver.Remove", req, &ret); err != nil { <add> <add> if err = pp.CallWithOptions("VolumeDriver.Remove", req, &ret, plugins.WithRequestTimeout(shortTimeout)); err != nil { <ide> return <ide> } <ide> <ide> func (pp *volumeDriverProxy) Path(name string) (mountpoint string, err error) { <ide> ) <ide> <ide> req.Name = name <del> if err = pp.Call("VolumeDriver.Path", req, &ret); err != nil { <add> <add> if err = pp.CallWithOptions("VolumeDriver.Path", req, &ret, plugins.WithRequestTimeout(shortTimeout)); err != nil { <ide> return <ide> } <ide> <ide> func (pp *volumeDriverProxy) Mount(name string, id string) (mountpoint string, e <ide> <ide> req.Name = name <ide> req.ID = id <del> if err = pp.Call("VolumeDriver.Mount", req, &ret); err != nil { <add> <add> if err = pp.CallWithOptions("VolumeDriver.Mount", req, &ret, plugins.WithRequestTimeout(longTimeout)); err != nil { <ide> return <ide> } <ide> <ide> func (pp *volumeDriverProxy) Unmount(name string, id string) (err error) { <ide> <ide> req.Name = name <ide> req.ID = id <del> if err = pp.Call("VolumeDriver.Unmount", req, &ret); err != nil { <add> <add> if err = pp.CallWithOptions("VolumeDriver.Unmount", req, &ret, plugins.WithRequestTimeout(shortTimeout)); err != nil { <ide> return <ide> } <ide> <ide> func (pp *volumeDriverProxy) List() (volumes []*proxyVolume, err error) { <ide> ret volumeDriverProxyListResponse <ide> ) <ide> <del> if err = pp.Call("VolumeDriver.List", req, &ret); err != nil { <add> if err = pp.CallWithOptions("VolumeDriver.List", req, &ret, plugins.WithRequestTimeout(shortTimeout)); err != nil { <ide> return <ide> } <ide> <ide> func (pp *volumeDriverProxy) Get(name string) (volume *proxyVolume, err error) { <ide> ) <ide> <ide> req.Name = name <del> if err = pp.Call("VolumeDriver.Get", req, &ret); err != nil { <add> <add> if err = pp.CallWithOptions("VolumeDriver.Get", req, &ret, plugins.WithRequestTimeout(shortTimeout)); err != nil { <ide> return <ide> } <ide> <ide> func (pp *volumeDriverProxy) Capabilities() (capabilities volume.Capability, err <ide> ret volumeDriverProxyCapabilitiesResponse <ide> ) <ide> <del> if err = pp.Call("VolumeDriver.Capabilities", req, &ret); err != nil { <add> if err = pp.CallWithOptions("VolumeDriver.Capabilities", req, &ret, plugins.WithRequestTimeout(shortTimeout)); err != nil { <ide> return <ide> } <ide>
2
Ruby
Ruby
fix select_tag generating tag when set to false
e0e9d5bd8600c01de6b73487bf66046d179c0ed7
<ide><path>actionview/lib/action_view/helpers/form_tag_helper.rb <ide> def select_tag(name, option_tags = nil, options = {}) <ide> include_blank = '' <ide> end <ide> <del> option_tags = content_tag(:option, include_blank, value: '').safe_concat(option_tags) <add> if include_blank <add> option_tags = content_tag(:option, include_blank, value: '').safe_concat(option_tags) <add> end <ide> end <ide> <ide> if prompt = options.delete(:prompt) <ide><path>actionview/test/template/form_tag_helper_test.rb <ide> def test_select_tag_with_include_blank <ide> assert_dom_equal expected, actual <ide> end <ide> <add> def test_select_tag_with_include_blank_false <add> actual = select_tag "places", "<option>Home</option><option>Work</option><option>Pub</option>".html_safe, include_blank: false <add> expected = %(<select id="places" name="places"><option>Home</option><option>Work</option><option>Pub</option></select>) <add> assert_dom_equal expected, actual <add> end <add> <ide> def test_select_tag_with_include_blank_string <ide> actual = select_tag "places", "<option>Home</option><option>Work</option><option>Pub</option>".html_safe, include_blank: 'Choose' <ide> expected = %(<select id="places" name="places"><option value="">Choose</option><option>Home</option><option>Work</option><option>Pub</option></select>)
2
Python
Python
fix bug in bellman_ford.py
82a11d7f31d06f781e3902984fa2902c0676816a
<ide><path>graphs/bellman_ford.py <ide> def BellmanFord(graph, V, E, src): <ide> mdist[src] = 0.0 <ide> <ide> for i in range(V - 1): <del> for j in range(V): <add> for j in range(E): <ide> u = graph[j]["src"] <ide> v = graph[j]["dst"] <ide> w = graph[j]["weight"] <ide> <ide> if mdist[u] != float("inf") and mdist[u] + w < mdist[v]: <ide> mdist[v] = mdist[u] + w <del> for j in range(V): <add> for j in range(E): <ide> u = graph[j]["src"] <ide> v = graph[j]["dst"] <ide> w = graph[j]["weight"]
1
Javascript
Javascript
improve fn description
e9a4de035df5708f7d96180d774b070495dbd045
<ide><path>src/ng/interval.js <ide> function $IntervalProvider() { <ide> * appropriate moment. See the example below for more details on how and when to do this. <ide> * </div> <ide> * <del> * @param {function()} fn A function that should be called repeatedly. <add> * @param {function()} fn A function that should be called repeatedly. If no additional arguments <add> * are passed (see below), the function is called with the current iteration count. <ide> * @param {number} delay Number of milliseconds between each function call. <ide> * @param {number=} [count=0] Number of times to repeat. If not set, or 0, will repeat <ide> * indefinitely.
1
Javascript
Javascript
remove .getnormalvector() from curve.js
e4c0c6878dc857ad19c8e9fde5f1615aa48e6883
<ide><path>src/extras/core/Curve.js <ide> /** <ide> * @author zz85 / http://www.lab4games.net/zz85/blog <ide> * Extensible curve object <del> * <add> * <ide> * Some common of Curve methods <ide> * .getPoint(t), getTangent(t) <ide> * .getPointAt(u), getTagentAt(u) <ide> THREE.Curve.prototype.getLengths = function ( divisions ) { <ide> <ide> if ( !divisions ) divisions = (this.__arcLengthDivisions) ? (this.__arcLengthDivisions): 200; <ide> <del> if ( this.cacheArcLengths <del> && ( this.cacheArcLengths.length == divisions + 1 ) <add> if ( this.cacheArcLengths <add> && ( this.cacheArcLengths.length == divisions + 1 ) <ide> && !this.needsUpdate) { <ide> <ide> //console.log( "cached", this.cacheArcLengths ); <ide> THREE.Curve.prototype.getUtoTmapping = function ( u, distance ) { <ide> <ide> }; <ide> <del> <del>// In 2D space, there are actually 2 normal vectors, <del>// and in 3D space, infinte <del>// TODO this should be depreciated. <del>THREE.Curve.prototype.getNormalVector = function( t ) { <del> <del> var vec = this.getTangent( t ); <del> <del> return new THREE.Vector2( -vec.y , vec.x ); <del> <del>}; <del> <ide> // Returns a unit vector tangent at t <del>// In case any sub curve does not implement its tangent / normal finding, <del>// we get 2 points with a small delta and find a gradient of the 2 points <del>// which seems to make a reasonable approximation <add>// In case any sub curve does not implement its tangent derivation, <add>// 2 points a small delta apart will be used to find its gradient <add>// which seems to give a reasonable approximation <ide> <ide> THREE.Curve.prototype.getTangent = function( t ) { <ide> <ide> THREE.Curve.prototype.getTangent = function( t ) { <ide> <ide> var pt1 = this.getPoint( t1 ); <ide> var pt2 = this.getPoint( t2 ); <del> <add> <ide> var vec = pt2.clone().subSelf(pt1); <ide> return vec.normalize(); <ide> <ide> THREE.SplineCurve3 = THREE.Curve.create( <ide> // v.z = THREE.Curve.Utils.tangentSpline( t, pt0.z, pt1.z, pt2.z, pt3.z ); <ide> <ide> // return v; <del> <add> <ide> // } <ide> <ide> /************************************************************** <ide> THREE.ClosedSplineCurve3 = THREE.Curve.create( <ide> <ide> intPoint = Math.floor( point ); <ide> weight = point - intPoint; <del> <add> <ide> intPoint += intPoint > 0 ? 0 : ( Math.floor( Math.abs( intPoint ) / points.length ) + 1 ) * points.length; <ide> c[ 0 ] = ( intPoint - 1 ) % points.length; <ide> c[ 1 ] = ( intPoint ) % points.length; <ide> THREE.ClosedSplineCurve3 = THREE.Curve.create( <ide> v.x = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].x, points[ c[ 1 ] ].x, points[ c[ 2 ] ].x, points[ c[ 3 ] ].x, weight ); <ide> v.y = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].y, points[ c[ 1 ] ].y, points[ c[ 2 ] ].y, points[ c[ 3 ] ].y, weight ); <ide> v.z = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].z, points[ c[ 1 ] ].z, points[ c[ 2 ] ].z, points[ c[ 3 ] ].z, weight ); <del> <add> <ide> return v; <ide> <ide> }
1
Java
Java
fix formatting errors
e7e843cae2d3303a0e2d09d8a64f14ebbf314c00
<ide><path>spring-core/src/test/java/org/springframework/aot/nativex/ReflectionHintsSerializerTests.java <ide> void two() throws JSONException { <ide> void queriedMethods() throws JSONException { <ide> ReflectionHints hints = new ReflectionHints(); <ide> hints.registerType(Integer.class, builder -> builder.withMethod("parseInt", List.of(TypeReference.of(String.class)), <del> (b) -> b.withMode(ExecutableMode.INTROSPECT))); <add> b -> b.withMode(ExecutableMode.INTROSPECT))); <ide> <ide> assertEquals(""" <ide> [ <del> { <del> "name": "java.lang.Integer", <del> "queriedMethods": [ <del> { <del> "name": "parseInt", <del> "parameterTypes": ["java.lang.String"] <del> } <del> ] <del> } <add> { <add> "name": "java.lang.Integer", <add> "queriedMethods": [ <add> { <add> "name": "parseInt", <add> "parameterTypes": ["java.lang.String"] <add> } <add> ] <add> } <ide> ] <ide> """, hints); <ide> } <ide> void queriedMethods() throws JSONException { <ide> void methods() throws JSONException { <ide> ReflectionHints hints = new ReflectionHints(); <ide> hints.registerType(Integer.class, builder -> builder.withMethod("parseInt", List.of(TypeReference.of(String.class)), <del> (b) -> b.withMode(ExecutableMode.INVOKE))); <add> b -> b.withMode(ExecutableMode.INVOKE))); <ide> <ide> assertEquals(""" <ide> [ <del> { <del> "name": "java.lang.Integer", <del> "methods": [ <del> { <del> "name": "parseInt", <del> "parameterTypes": ["java.lang.String"] <del> } <del> ] <del> } <add> { <add> "name": "java.lang.Integer", <add> "methods": [ <add> { <add> "name": "parseInt", <add> "parameterTypes": ["java.lang.String"] <add> } <add> ] <add> } <ide> ] <ide> """, hints); <ide> } <ide> @Test <ide> void methodAndQueriedMethods() throws JSONException { <ide> ReflectionHints hints = new ReflectionHints(); <ide> hints.registerType(Integer.class, builder -> builder.withMethod("parseInt", List.of(TypeReference.of(String.class)), <del> (b) -> b.withMode(ExecutableMode.INVOKE))); <add> b -> b.withMode(ExecutableMode.INVOKE))); <ide> hints.registerType(Integer.class, builder -> builder.withMethod("parseInt", List.of(TypeReference.of(String.class)), <del> (b) -> b.withMode(ExecutableMode.INTROSPECT))); <add> b -> b.withMode(ExecutableMode.INTROSPECT))); <ide> <ide> assertEquals(""" <ide> [ <del> { <del> "name": "java.lang.Integer", <del> "queriedMethods": [ <del> { <del> "name": "parseInt", <del> "parameterTypes": ["java.lang.String"] <del> } <del> ], <del> "methods": [ <del> { <del> "name": "parseInt", <del> "parameterTypes": ["java.lang.String"] <del> } <del> ] <del> } <add> { <add> "name": "java.lang.Integer", <add> "queriedMethods": [ <add> { <add> "name": "parseInt", <add> "parameterTypes": ["java.lang.String"] <add> } <add> ], <add> "methods": [ <add> { <add> "name": "parseInt", <add> "parameterTypes": ["java.lang.String"] <add> } <add> ] <add> } <ide> ] <ide> """, hints); <ide> }
1
Text
Text
update the readme to reflect build changes
dd22f449538a2a56c09e91e390874ac6da2e4847
<ide><path>README.md <ide> You can also view all the test pdf files on the right side serving <ide> <ide> + http://localhost:8888/test/pdfs/?frame <ide> <del>### Building pdf.js <add>### Building pdf.js. <ide> <del>In order to bundle all `src/` files into a final `pdf.js`, issue: <add>In order to bundle all `src/` files into a final `pdf.js` and build the generic viewer, issue: <ide> <del> $ node make bundle <add> $ node make generic <ide> <del>This will generate the file `build/pdf.js` that can be included in your final project. (WARNING: That's a large file! Consider minifying it). <add>This will generate the file `build/generic/build/pdf.js` that can be included in your final project. The pdf.js file is large and should be minified for production. Also, if you would like to support more browsers than firefox you'll also need to include `compatibility.js` from `build/generic/web/`. <ide> <ide> <ide> # Learning
1
Ruby
Ruby
permit attaching files to new records
e05e2ae44f1ecf8e9bb5949f531305c15bc3c665
<ide><path>activestorage/lib/active_storage/attached/many.rb <ide> def attachments <ide> # document.images.attach([ first_blob, second_blob ]) <ide> def attach(*attachables) <ide> attachables.flatten.collect do |attachable| <del> attachments.create!(name: name, blob: create_blob_from(attachable)) <add> if record.new_record? <add> attachments.build(record: record, blob: create_blob_from(attachable)) <add> else <add> attachments.create!(record: record, blob: create_blob_from(attachable)) <add> end <ide> end <ide> end <ide> <ide><path>activestorage/lib/active_storage/attached/one.rb <ide> def attach(attachable) <ide> if attached? && dependent == :purge_later <ide> replace attachable <ide> else <del> write_attachment create_attachment_from(attachable) <add> write_attachment build_attachment_from(attachable) <ide> end <ide> end <ide> <ide> def replace(attachable) <ide> blob.tap do <ide> transaction do <ide> detach <del> write_attachment create_attachment_from(attachable) <add> write_attachment build_attachment_from(attachable) <ide> end <ide> end.purge_later <ide> end <ide> <del> def create_attachment_from(attachable) <del> ActiveStorage::Attachment.create!(record: record, name: name, blob: create_blob_from(attachable)) <add> def build_attachment_from(attachable) <add> ActiveStorage::Attachment.new(record: record, name: name, blob: create_blob_from(attachable)) <ide> end <ide> <ide> def write_attachment(attachment) <ide><path>activestorage/test/models/attachments_test.rb <ide> class ActiveStorage::AttachmentsTest < ActiveSupport::TestCase <ide> assert ActiveStorage::Blob.service.exist?(@user.avatar.key) <ide> end <ide> <add> test "attach blob to new record" do <add> user = User.new(name: "Jason") <add> <add> assert_no_changes -> { user.new_record? } do <add> assert_no_difference -> { ActiveStorage::Attachment.count } do <add> user.avatar.attach create_blob(filename: "funky.jpg") <add> end <add> end <add> <add> assert user.avatar.attached? <add> assert_equal "funky.jpg", user.avatar.filename.to_s <add> <add> assert_difference -> { ActiveStorage::Attachment.count }, +1 do <add> user.save! <add> end <add> <add> assert user.reload.avatar.attached? <add> assert_equal "funky.jpg", user.avatar.filename.to_s <add> end <add> <ide> test "access underlying associations of new blob" do <ide> @user.avatar.attach create_blob(filename: "funky.jpg") <ide> assert_equal @user, @user.avatar_attachment.record <ide> class ActiveStorage::AttachmentsTest < ActiveSupport::TestCase <ide> assert_equal "country.jpg", @user.highlights.second.filename.to_s <ide> end <ide> <add> test "attach blobs to new record" do <add> user = User.new(name: "Jason") <add> <add> assert_no_changes -> { user.new_record? } do <add> assert_no_difference -> { ActiveStorage::Attachment.count } do <add> user.highlights.attach( <add> { io: StringIO.new("STUFF"), filename: "town.jpg", content_type: "image/jpg" }, <add> { io: StringIO.new("IT"), filename: "country.jpg", content_type: "image/jpg" }) <add> end <add> end <add> <add> assert user.highlights.attached? <add> assert_equal "town.jpg", user.highlights.first.filename.to_s <add> assert_equal "country.jpg", user.highlights.second.filename.to_s <add> <add> assert_difference -> { ActiveStorage::Attachment.count }, +2 do <add> user.save! <add> end <add> <add> assert user.reload.highlights.attached? <add> assert_equal "town.jpg", user.highlights.first.filename.to_s <add> assert_equal "country.jpg", user.highlights.second.filename.to_s <add> end <add> <ide> test "find attached blobs" do <ide> @user.highlights.attach( <ide> { io: StringIO.new("STUFF"), filename: "town.jpg", content_type: "image/jpg" },
3
Go
Go
convert testgetcontainersbyname into a unit test
c44c98edec6822edf17cc969038e21be6ccdbd93
<ide><path>api/server/server_unit_test.go <ide> func TestGetInfo(t *testing.T) { <ide> } <ide> } <ide> <add>func TestGetContainersByName(t *testing.T) { <add> eng := engine.New() <add> name := "container_name" <add> var called bool <add> eng.Register("container_inspect", func(job *engine.Job) engine.Status { <add> called = true <add> if job.Args[0] != name { <add> t.Fatalf("name != '%s': %#v", name, job.Args[0]) <add> } <add> if api.APIVERSION.LessThan("1.12") && !job.GetenvBool("dirty") { <add> t.Fatal("dirty env variable not set") <add> } else if api.APIVERSION.GreaterThanOrEqualTo("1.12") && job.GetenvBool("dirty") { <add> t.Fatal("dirty env variable set when it shouldn't") <add> } <add> v := &engine.Env{} <add> v.SetBool("dirty", true) <add> if _, err := v.WriteTo(job.Stdout); err != nil { <add> return job.Error(err) <add> } <add> return engine.StatusOK <add> }) <add> r := serveRequest("GET", "/containers/"+name+"/json", nil, eng, t) <add> if !called { <add> t.Fatal("handler was not called") <add> } <add> if r.HeaderMap.Get("Content-Type") != "application/json" { <add> t.Fatalf("%#v\n", r) <add> } <add> var stdoutJson interface{} <add> if err := json.Unmarshal(r.Body.Bytes(), &stdoutJson); err != nil { <add> t.Fatalf("%#v", err) <add> } <add> if stdoutJson.(map[string]interface{})["dirty"].(float64) != 1 { <add> t.Fatalf("%#v", stdoutJson) <add> } <add>} <add> <ide> func serveRequest(method, target string, body io.Reader, eng *engine.Engine, t *testing.T) *httptest.ResponseRecorder { <ide> r := httptest.NewRecorder() <ide> req, err := http.NewRequest(method, target, body) <ide><path>integration/api_test.go <ide> import ( <ide> <ide> "github.com/dotcloud/docker/api" <ide> "github.com/dotcloud/docker/api/server" <del> "github.com/dotcloud/docker/daemon" <ide> "github.com/dotcloud/docker/engine" <ide> "github.com/dotcloud/docker/image" <ide> "github.com/dotcloud/docker/runconfig" <ide> func TestGetContainersTop(t *testing.T) { <ide> } <ide> } <ide> <del>func TestGetContainersByName(t *testing.T) { <del> eng := NewTestEngine(t) <del> defer mkDaemonFromEngine(eng, t).Nuke() <del> <del> // Create a container and remove a file <del> containerID := createTestContainer(eng, <del> &runconfig.Config{ <del> Image: unitTestImageID, <del> Cmd: []string{"echo", "test"}, <del> }, <del> t, <del> ) <del> <del> r := httptest.NewRecorder() <del> req, err := http.NewRequest("GET", "/containers/"+containerID+"/json", nil) <del> if err != nil { <del> t.Fatal(err) <del> } <del> if err := server.ServeRequest(eng, api.APIVERSION, r, req); err != nil { <del> t.Fatal(err) <del> } <del> assertHttpNotError(r, t) <del> outContainer := &daemon.Container{} <del> if err := json.Unmarshal(r.Body.Bytes(), outContainer); err != nil { <del> t.Fatal(err) <del> } <del> if outContainer.ID != containerID { <del> t.Fatalf("Wrong containers retrieved. Expected %s, received %s", containerID, outContainer.ID) <del> } <del>} <del> <ide> func TestPostCommit(t *testing.T) { <ide> eng := NewTestEngine(t) <ide> defer mkDaemonFromEngine(eng, t).Nuke()
2
PHP
PHP
fix code style
70698d2257f7b868a71983a6674a7c25f261ff8e
<ide><path>src/Illuminate/Container/BoundMethod.php <ide> protected static function addDependencyForCallParameter($container, $parameter, <ide> $dependencies[] = $container->make($parameter->getClass()->name); <ide> } elseif ($parameter->isDefaultValueAvailable()) { <ide> $dependencies[] = $parameter->getDefaultValue(); <del> } elseif(! $parameter->isOptional() && ! array_key_exists($parameter->name, $parameters)) { <add> } elseif (! $parameter->isOptional() && ! array_key_exists($parameter->name, $parameters)) { <ide> $message = "Unresolvable dependency resolving [$parameter] in class {$parameter->getDeclaringClass()->getName()}"; <ide> <ide> throw new BindingResolutionException($message);
1
Javascript
Javascript
add fractionsize as optional parameter
20685ffe11036d4d604d13f0d792ca46497af4a1
<ide><path>src/ng/filter/filters.js <ide> * <ide> * @param {number} amount Input to filter. <ide> * @param {string=} symbol Currency symbol or identifier to be displayed. <add> * @param {number=} fractionSize Number of decimal places to round the amount to. <ide> * @returns {string} Formatted number. <ide> * <ide> * <ide> <input type="number" ng-model="amount"> <br> <ide> default currency symbol ($): <span id="currency-default">{{amount | currency}}</span><br> <ide> custom currency identifier (USD$): <span>{{amount | currency:"USD$"}}</span> <add> no fractions (0): <span>{{amount | currency:"USD$":0}}</span> <ide> </div> <ide> </file> <ide> <file name="protractor.js" type="protractor"> <ide> it('should init with 1234.56', function() { <ide> expect(element(by.id('currency-default')).getText()).toBe('$1,234.56'); <ide> expect(element(by.binding('amount | currency:"USD$"')).getText()).toBe('USD$1,234.56'); <add> expect(element(by.binding('amount | currency:"USD$":0')).getText()).toBe('USD$1,235'); <ide> }); <ide> it('should update', function() { <ide> if (browser.params.browser == 'safari') { <ide> element(by.model('amount')).sendKeys('-1234'); <ide> expect(element(by.id('currency-default')).getText()).toBe('($1,234.00)'); <ide> expect(element(by.binding('amount | currency:"USD$"')).getText()).toBe('(USD$1,234.00)'); <add> expect(element(by.binding('amount | currency:"USD$":0')).getText()).toBe('(USD$1,234)'); <ide> }); <ide> </file> <ide> </example> <ide> */ <ide> currencyFilter.$inject = ['$locale']; <ide> function currencyFilter($locale) { <ide> var formats = $locale.NUMBER_FORMATS; <del> return function(amount, currencySymbol){ <del> if (isUndefined(currencySymbol)) currencySymbol = formats.CURRENCY_SYM; <add> return function(amount, currencySymbol, fractionSize){ <add> if (isUndefined(currencySymbol)) { <add> currencySymbol = formats.CURRENCY_SYM; <add> } <add> <add> if (isUndefined(fractionSize)) { <add> // TODO: read the default value from the locale file <add> fractionSize = 2; <add> } <ide> <ide> // if null or undefined pass it through <ide> return (amount == null) <ide> ? amount <del> : formatNumber(amount, formats.PATTERNS[1], formats.GROUP_SEP, formats.DECIMAL_SEP, 2). <add> : formatNumber(amount, formats.PATTERNS[1], formats.GROUP_SEP, formats.DECIMAL_SEP, fractionSize). <ide> replace(/\u00A4/g, currencySymbol); <ide> }; <ide> } <ide><path>test/ng/filter/filtersSpec.js <ide> describe('filters', function() { <ide> expect(currency(0)).toEqual('$0.00'); <ide> expect(currency(-999)).toEqual('($999.00)'); <ide> expect(currency(1234.5678, "USD$")).toEqual('USD$1,234.57'); <add> expect(currency(1234.5678, "USD$", 0)).toEqual('USD$1,235'); <ide> }); <ide> <ide> it('should pass through null and undefined to be compatible with one-time binding', function() {
2
Javascript
Javascript
expose http.clientrequest and http.serverresponse
60131fc88c165b3b556a16bc25f244c6d63a0482
<ide><path>lib/http.js <ide> function ServerResponse () { <ide> this.use_chunked_encoding_by_default = true; <ide> } <ide> process.inherits(ServerResponse, OutgoingMessage); <add>exports.ServerResponse = ServerResponse; <ide> <ide> ServerResponse.prototype.sendHeader = function (statusCode, headers) { <ide> var reason = STATUS_CODES[statusCode] || "unknown"; <ide> function ClientRequest (method, uri, headers) { <ide> this.sendHeaderLines(method + " " + uri + " HTTP/1.0\r\n", headers); <ide> } <ide> process.inherits(ClientRequest, OutgoingMessage); <add>exports.ClientRequest = ClientRequest; <ide> <ide> ClientRequest.prototype.finish = function (responseListener) { <ide> this.addListener("response", responseListener);
1
Text
Text
fix typo in ref-08-reconciliation.md
d3e315193a0cf189cb5f9734ad6d73f132911660
<ide><path>docs/docs/ref-08-reconciliation.md <ide> React's key design decision is to make the API seem like it re-renders the whole <ide> <ide> Generating the minimum number of operations to transform one tree into another is a complex and well-studied problem. The [state of the art algorithms](http://grfia.dlsi.ua.es/ml/algorithms/references/editsurvey_bille.pdf) have a complexity in the order of O(n<sup>3</sup>) where n is the number of nodes in the tree. <ide> <del>This means that displaying 1000 nodes would require in the order of one billion comparisons. This is far too expensive for our use case. To put this number in perspective, CPUs nowadays execute roughly 3 billion instruction per second. So even with the most performant implementation, we wouldn't be able to compute that diff in less than a second. <add>This means that displaying 1000 nodes would require in the order of one billion comparisons. This is far too expensive for our use case. To put this number in perspective, CPUs nowadays execute roughly 3 billion instructions per second. So even with the most performant implementation, we wouldn't be able to compute that diff in less than a second. <ide> <ide> Since an optimal algorithm is not tractable, we implement a non-optimal O(n) algorithm using heuristics based on two assumptions: <ide>
1
PHP
PHP
fix docblock typo
673b35051892debc514fe752dc965e5a3d2bf6ae
<ide><path>src/Illuminate/Queue/Middleware/PreventOverlappingJobs.php <ide> class PreventOverlappingJobs <ide> * @param string $key <ide> * @param string $prefix <ide> * @param int $expiresAt <del> * @param string $prefix <ide> * <ide> * @return void <ide> */
1
Text
Text
update neural_gpu documentation
b1ad92b8a69a885ae7049d54e8219d66e0b429e3
<ide><path>neural_gpu/README.md <ide> Requirements: <ide> * TensorFlow (see tensorflow.org for how to install) <ide> * Matplotlib for Python (sudo apt-get install python-matplotlib) <ide> <del>Run: python neural_gpu_trainer.py --task=rev <add>The model can be trained on the following algorithmic tasks: <add> <add>* `sort` - Sort a decimal list <add>* `kvsort` - Sort decimal keys in dictionary <add>* `id` - Return the same decimal list <add>* `rev` - Reverse a decimal list <add>* `rev2` - Reverse a decimal dictionary by key <add>* `incr` - Add one to a decimal <add>* `add` - Long decimal addition <add>* `left` - First decimal in list <add>* `right` - Last decimal in list <add>* `left-shift` - Left shift a decimal list <add>* `right-shift` - Right shift a decimal list <add>* `bmul` - Long binary multiplication <add>* `mul` - Long decimal multiplication <add>* `dup` - Duplicate a decimal list with padding <add>* `badd` - Long binary addition <add>* `qadd` - Long quaternary addition <add>* `search` - Search for decimal key in dictionary <add> <add>To train the model on the reverse task run: <add> <add>``` <add>python neural_gpu_trainer.py --task=rev <add>``` <add> <add>While training, interim / checkpoint model parameters will be <add>written to `/tmp/neural_gpu/`. <add> <add>Once the amount of error gets down to what you're comfortable <add>with, hit `Ctrl-C` to stop the training process. The latest <add>model parameters will be in `/tmp/neural_gpu/neural_gpu.ckpt-<step>` <add>and used on any subsequent run. <add> <add>To test a trained model on how well it decodes run: <add> <add>``` <add>python neural_gpu_trainer.py --task=rev --mode=1 <add>``` <add> <add>To produce an animation of the result run: <add> <add>``` <add>python neural_gpu_trainer.py --task=rev --mode=1 --animate=True <add>``` <ide> <ide> Maintained by Lukasz Kaiser (lukaszkaiser)
1
Javascript
Javascript
add regression test for legend layout issue
3ea93a09f2047b727891f9e13dbd3fb7ebe44adf
<ide><path>test/specs/plugin.legend.tests.js <ide> describe('Legend block tests', function() { <ide> }); <ide> }); <ide> <add> it('should not draw legend items outside of the chart bounds', function() { <add> var chart = window.acquireChart( <add> { <add> type: 'line', <add> data: { <add> datasets: [1, 2, 3].map(function(n) { <add> return { <add> label: 'dataset' + n, <add> data: [] <add> }; <add> }), <add> labels: [] <add> }, <add> options: { <add> legend: { <add> position: 'right' <add> } <add> } <add> }, <add> { <add> canvas: { <add> width: 512, <add> height: 105 <add> } <add> } <add> ); <add> <add> // Check some basic assertions about the test setup <add> expect(chart.width).toBe(512); <add> expect(chart.legend.legendHitBoxes.length).toBe(3); <add> <add> // Check whether any legend items reach outside the established bounds <add> chart.legend.legendHitBoxes.forEach(function(item) { <add> expect(item.left + item.width).toBeLessThanOrEqual(chart.width); <add> }); <add> }); <add> <ide> describe('config update', function() { <ide> it ('should update the options', function() { <ide> var chart = acquireChart({
1
Ruby
Ruby
remove the sqlite3 binary subclass
c9cc1f47adbfe6bcdca37fb1d1338999219c7b74
<ide><path>activerecord/lib/active_record/connection_adapters/sqlite3_adapter.rb <ide> def sqlite3_connection(config) <ide> end <ide> <ide> module ConnectionAdapters #:nodoc: <del> class SQLite3Binary < Type::Binary # :nodoc: <del> def cast_value(value) <del> if value.encoding != Encoding::ASCII_8BIT <del> value = value.force_encoding(Encoding::ASCII_8BIT) <del> end <del> value <del> end <del> end <del> <ide> # The SQLite3 adapter works SQLite 3.6.16 or newer <ide> # with the sqlite3-ruby drivers (available as gem from https://rubygems.org/gems/sqlite3). <ide> # <ide> def _type_cast(value) # :nodoc: <ide> end <ide> end <ide> <del> def type_classes_with_standard_constructor <del> super.merge(binary: SQLite3Binary) <del> end <del> <ide> def quote_string(s) #:nodoc: <ide> @connection.class.quote(s) <ide> end <ide> def rename_column(table_name, column_name, new_column_name) #:nodoc: <ide> <ide> protected <ide> <del> def initialize_type_map(m) <del> super <del> m.register_type(/binary/i, SQLite3Binary.new) <del> end <del> <ide> def table_structure(table_name) <ide> structure = exec_query("PRAGMA table_info(#{quote_table_name(table_name)})", 'SCHEMA').to_hash <ide> raise(ActiveRecord::StatementInvalid, "Could not find table '#{table_name}'") if structure.empty? <ide><path>activerecord/test/cases/types_test.rb <ide> def test_type_equality <ide> assert_not_equal Type::Value.new(precision: 1), Type::Value.new(precision: 2) <ide> end <ide> <del> if current_adapter?(:SQLite3Adapter) <del> def test_binary_encoding <del> type = SQLite3Binary.new <del> utf8_string = "a string".encode(Encoding::UTF_8) <del> type_cast = type.type_cast_from_user(utf8_string) <del> <del> assert_equal Encoding::ASCII_8BIT, type_cast.encoding <del> end <del> end <del> <ide> def test_attributes_which_are_invalid_for_database_can_still_be_reassigned <ide> type_which_cannot_go_to_the_database = Type::Value.new <ide> def type_which_cannot_go_to_the_database.type_cast_for_database(*)
2
Python
Python
fix minor docstring typos.
711d901c49bbc896f508920b70bfd8a83f11e5da
<ide><path>src/transformers/modeling_flax_utils.py <ide> def from_pretrained( <ide> from_pt (:obj:`bool`, `optional`, defaults to :obj:`False`): <ide> Load the model weights from a PyTorch checkpoint save file (see docstring of <ide> ``pretrained_model_name_or_path`` argument). <del> ignore_mismatched_size (:obj:`bool`, `optional`, defaults to :obj:`False`): <add> ignore_mismatched_sizes (:obj:`bool`, `optional`, defaults to :obj:`False`): <ide> Whether or not to raise an error if some of the weights from the checkpoint do not have the same size <ide> as the weights of the model (if for instance, you are instantiating a model with 10 labels from a <ide> checkpoint with 3 labels). <ide><path>src/transformers/modeling_tf_utils.py <ide> def from_pretrained(cls, pretrained_model_name_or_path, *model_args, **kwargs): <ide> from_pt: (:obj:`bool`, `optional`, defaults to :obj:`False`): <ide> Load the model weights from a PyTorch state_dict save file (see docstring of <ide> ``pretrained_model_name_or_path`` argument). <del> ignore_mismatched_size (:obj:`bool`, `optional`, defaults to :obj:`False`): <add> ignore_mismatched_sizes (:obj:`bool`, `optional`, defaults to :obj:`False`): <ide> Whether or not to raise an error if some of the weights from the checkpoint do not have the same size <ide> as the weights of the model (if for instance, you are instantiating a model with 10 labels from a <ide> checkpoint with 3 labels). <ide><path>src/transformers/modeling_utils.py <ide> def from_pretrained(cls, pretrained_model_name_or_path: Optional[Union[str, os.P <ide> from_flax (:obj:`bool`, `optional`, defaults to :obj:`False`): <ide> Load the model weights from a Flax checkpoint save file (see docstring of <ide> ``pretrained_model_name_or_path`` argument). <del> ignore_mismatched_size (:obj:`bool`, `optional`, defaults to :obj:`False`): <add> ignore_mismatched_sizes (:obj:`bool`, `optional`, defaults to :obj:`False`): <ide> Whether or not to raise an error if some of the weights from the checkpoint do not have the same size <ide> as the weights of the model (if for instance, you are instantiating a model with 10 labels from a <ide> checkpoint with 3 labels).
3
Python
Python
fix pipeline ner
a241011057245211975b4730170815536527d79d
<ide><path>transformers/pipelines.py <ide> class NerPipeline(Pipeline): <ide> def __init__(self, model, tokenizer: PreTrainedTokenizer = None, <ide> modelcard: ModelCard = None, framework: Optional[str] = None, <ide> args_parser: ArgumentHandler = None, device: int = -1, <del> binary_output: bool = False): <add> binary_output: bool = False, ignore_labels=['O']): <ide> super().__init__(model=model, <ide> tokenizer=tokenizer, <ide> modelcard=modelcard, <ide> def __init__(self, model, tokenizer: PreTrainedTokenizer = None, <ide> binary_output=binary_output) <ide> <ide> self._basic_tokenizer = BasicTokenizer(do_lower_case=False) <add> self.ignore_labels = ignore_labels <ide> <ide> def __call__(self, *texts, **kwargs): <ide> inputs, answers = self._args_parser(*texts, **kwargs), [] <ide> for sentence in inputs: <ide> <del> # Ugly token to word idx mapping (for now) <del> token_to_word, words = [], self._basic_tokenizer.tokenize(sentence) <del> for i, w in enumerate(words): <del> tokens = self.tokenizer.tokenize(w) <del> token_to_word += [i] * len(tokens) <del> <ide> # Manage correct placement of the tensors <ide> with self.device_placement(): <ide> <ide> def __call__(self, *texts, **kwargs): <ide> with torch.no_grad(): <ide> entities = self.model(**tokens)[0][0].cpu().numpy() <ide> <del> # Normalize scores <del> answer, token_start = [], 1 <del> for idx, word in groupby(token_to_word): <del> <del> # Sum log prob over token, then normalize across labels <del> score = np.exp(entities[token_start]) / np.exp(entities[token_start]).sum(-1, keepdims=True) <del> label_idx = score.argmax() <add> score = np.exp(entities) / np.exp(entities).sum(-1, keepdims=True) <add> labels_idx = score.argmax(axis=-1) <ide> <del> if label_idx > 0: <add> answer = [] <add> for idx, label_idx in enumerate(labels_idx): <add> if self.model.config.id2label[label_idx] not in self.ignore_labels: <ide> answer += [{ <del> 'word': words[idx], <del> 'score': score[label_idx].item(), <add> 'word': self.tokenizer.decode(tokens['input_ids'][0][idx].cpu().tolist()), <add> 'score': score[idx][label_idx].item(), <ide> 'entity': self.model.config.id2label[label_idx] <ide> }] <ide> <del> # Update token start <del> token_start += len(list(word)) <del> <ide> # Append <ide> answers += [answer] <add> if len(answers) == 1: <add> return answers[0] <ide> return answers <ide> <ide>
1
Python
Python
add missing to_list to multi_gpu_utils
be28fd9e06cb16d28730c87f5c5a2b790c1abbcc
<ide><path>keras/utils/multi_gpu_utils.py <ide> from ..layers.core import Lambda <ide> from ..engine.training import Model <ide> from ..models import clone_model <add>from ..utils.generic_utils import to_list <ide> <ide> <ide> def _get_available_devices():
1
Python
Python
fix schema categories for custom list actions
01b498ec5109da22bf1b79d86efaecf45426ad51
<ide><path>rest_framework/schemas.py <ide> def is_api_view(callback): <ide> return (cls is not None) and issubclass(cls, APIView) <ide> <ide> <del>def insert_into(target, keys, item): <del> """ <del> Insert `item` into the nested dictionary `target`. <del> <del> For example: <del> <del> target = {} <del> insert_into(target, ('users', 'list'), Link(...)) <del> insert_into(target, ('users', 'detail'), Link(...)) <del> assert target == {'users': {'list': Link(...), 'detail': Link(...)}} <del> """ <del> for key in keys[:1]: <del> if key not in target: <del> target[key] = {} <del> target = target[key] <del> target[keys[-1]] = item <del> <del> <ide> class SchemaGenerator(object): <ide> default_mapping = { <ide> 'get': 'read', <ide> def get_schema(self, request=None): <ide> self.endpoints = self.get_api_endpoints(self.patterns) <ide> <ide> links = [] <del> for key, path, method, callback in self.endpoints: <add> for path, method, category, action, callback in self.endpoints: <ide> view = callback.cls() <ide> for attr, val in getattr(callback, 'initkwargs', {}).items(): <ide> setattr(view, attr, val) <ide> def get_schema(self, request=None): <ide> view.request = None <ide> <ide> link = self.get_link(path, method, callback, view) <del> links.append((key, link)) <add> links.append((category, action, link)) <ide> <del> if not link: <add> if not links: <ide> return None <ide> <del> # Generate the schema content structure, from the endpoints. <del> # ('users', 'list'), Link -> {'users': {'list': Link()}} <add> # Generate the schema content structure, eg: <add> # {'users': {'list': Link()}} <ide> content = {} <del> for key, link in links: <del> insert_into(content, key, link) <add> for category, action, link in links: <add> if category is None: <add> content[action] = link <add> elif category in content: <add> content[category][action] = link <add> else: <add> content[category] = {action: link} <ide> <ide> # Return the schema document. <ide> return coreapi.Document(title=self.title, content=content, url=self.url) <ide> def get_api_endpoints(self, patterns, prefix=''): <ide> callback = pattern.callback <ide> if self.should_include_endpoint(path, callback): <ide> for method in self.get_allowed_methods(callback): <del> key = self.get_key(path, method, callback) <del> endpoint = (key, path, method, callback) <add> action = self.get_action(path, method, callback) <add> endpoint = (path, method, action, callback) <ide> api_endpoints.append(endpoint) <ide> <ide> elif isinstance(pattern, RegexURLResolver): <ide> def get_api_endpoints(self, patterns, prefix=''): <ide> ) <ide> api_endpoints.extend(nested_endpoints) <ide> <del> return api_endpoints <add> return self.add_categories(api_endpoints) <add> <add> def add_categories(self, api_endpoints): <add> """ <add> (path, method, action, callback) -> (path, method, category, action, callback) <add> """ <add> # Determine the top level categories for the schema content, <add> # based on the URLs of the endpoints. Eg `set(['users', 'organisations'])` <add> paths = [endpoint[0] for endpoint in api_endpoints] <add> categories = self.get_categories(paths) <add> <add> return [ <add> (path, method, self.get_category(categories, path), action, callback) <add> for (path, method, action, callback) in api_endpoints <add> ] <ide> <ide> def get_path(self, path_regex): <ide> """ <ide> def get_allowed_methods(self, callback): <ide> callback.cls().allowed_methods if method not in ('OPTIONS', 'HEAD') <ide> ] <ide> <del> def get_key(self, path, method, callback): <add> def get_action(self, path, method, callback): <ide> """ <del> Return a tuple of strings, indicating the identity to use for a <del> given endpoint. eg. ('users', 'list'). <add> Return a description action string for the endpoint, eg. 'list'. <ide> """ <del> category = None <del> for item in path.strip('/').split('/'): <del> if '{' in item: <del> break <del> category = item <del> <ide> actions = getattr(callback, 'actions', self.default_mapping) <del> action = actions[method.lower()] <del> <del> if category: <del> return (category, action) <del> return (action,) <add> return actions[method.lower()] <add> <add> def get_categories(self, paths): <add> categories = set() <add> split_paths = set([ <add> tuple(path.split("{")[0].strip('/').split('/')) <add> for path in paths <add> ]) <add> <add> while split_paths: <add> for split_path in list(split_paths): <add> if len(split_path) == 0: <add> split_paths.remove(split_path) <add> elif len(split_path) == 1: <add> categories.add(split_path[0]) <add> split_paths.remove(split_path) <add> elif split_path[0] in categories: <add> split_paths.remove(split_path) <add> <add> return categories <add> <add> def get_category(self, categories, path): <add> path_components = path.split("{")[0].strip('/').split('/') <add> for path_component in path_components: <add> if path_component in categories: <add> return path_component <add> return None <ide> <ide> # Methods for generating each individual `Link` instance... <ide> <ide><path>tests/test_schemas.py <ide> <ide> from rest_framework import filters, pagination, permissions, serializers <ide> from rest_framework.compat import coreapi <del>from rest_framework.decorators import detail_route <add>from rest_framework.decorators import detail_route, list_route <ide> from rest_framework.response import Response <ide> from rest_framework.routers import DefaultRouter <ide> from rest_framework.schemas import SchemaGenerator <ide> class ExampleViewSet(ModelViewSet): <ide> def custom_action(self, request, pk): <ide> return super(ExampleSerializer, self).retrieve(self, request) <ide> <add> @list_route() <add> def custom_list_action(self, request): <add> return super(ExampleViewSet, self).list(self, request) <add> <ide> def get_serializer(self, *args, **kwargs): <ide> assert self.request <ide> return super(ExampleViewSet, self).get_serializer(*args, **kwargs) <ide> def test_anonymous_request(self): <ide> coreapi.Field('ordering', required=False, location='query') <ide> ] <ide> ), <add> 'custom_list_action': coreapi.Link( <add> url='/example/custom_list_action/', <add> action='get' <add> ), <ide> 'retrieve': coreapi.Link( <ide> url='/example/{pk}/', <ide> action='get', <ide> def test_authenticated_request(self): <ide> coreapi.Field('d', required=False, location='form'), <ide> ] <ide> ), <add> 'custom_list_action': coreapi.Link( <add> url='/example/custom_list_action/', <add> action='get' <add> ), <ide> 'update': coreapi.Link( <ide> url='/example/{pk}/', <ide> action='put',
2
Javascript
Javascript
remove the vertical bar next to the code frame
89be2d00eaf60d1d4384b764a834709f3542f689
<ide><path>Libraries/LogBox/UI/AnsiHighlight.js <ide> export default function Ansi({ <ide> remove_empty: true, <ide> use_classes: true, <ide> }).map((bundle, key) => { <add> // Remove the vertical bar after line numbers <add> const content = <add> key === 1 ? bundle.content.replace(/\| $/, ' ') : bundle.content; <ide> const textStyle = <ide> bundle.fg && COLORS[bundle.fg] <ide> ? { <ide> export default function Ansi({ <ide> }; <ide> return ( <ide> <Text style={[style, textStyle]} key={key}> <del> {bundle.content} <add> {content} <ide> </Text> <ide> ); <ide> })}
1
Text
Text
add issue assignment template
56a8e757994a2245a2a0f28c4cecf3ae0c0d7e93
<ide><path>docs/moderator-handbook.md <ide> Sometimes we may get more than one pull request. We typically accept the most qu <ide> <ide> Happy contributing. <ide> ``` <add> <add>### Requests for Assignment <add> <add>```md <add>We typically do not assign issues. Instead, we accept the first pull request that comprehensively solves the issue. <add> <add>Issues labelled with `help wanted` or `first timers only` are open for contributions. <add> <add>Please make sure you read [our guidelines for contributing](https://contribute.freecodecamp.org/#/). We prioritize contributors following the instructions in our guide. Join us in [our chat room](https://discord.gg/PRyKn3Vbay) or [the forum](https://forum.freecodecamp.org/c/contributors/3) if you need help contributing - our community will be happy to assist you. <add>```
1
Java
Java
refine contentnegotiationstrategy contract
f3994467c4e1094f5229d05c5679550f956cba8e
<ide><path>spring-web/src/main/java/org/springframework/web/accept/AbstractMappingContentNegotiationStrategy.java <ide> /* <del> * Copyright 2002-2017 the original author or authors. <add> * Copyright 2002-2018 the original author or authors. <ide> * <ide> * Licensed under the Apache License, Version 2.0 (the "License"); <ide> * you may not use this file except in compliance with the License. <ide> public List<MediaType> resolveMediaTypeKey(NativeWebRequest webRequest, @Nullabl <ide> return Collections.singletonList(mediaType); <ide> } <ide> } <del> return Collections.emptyList(); <add> return MEDIA_TYPE_ALL_LIST; <ide> } <ide> <ide> <ide><path>spring-web/src/main/java/org/springframework/web/accept/ContentNegotiationManager.java <ide> */ <ide> public class ContentNegotiationManager implements ContentNegotiationStrategy, MediaTypeFileExtensionResolver { <ide> <del> private static final List<MediaType> MEDIA_TYPE_ALL = Collections.singletonList(MediaType.ALL); <del> <del> <ide> private final List<ContentNegotiationStrategy> strategies = new ArrayList<>(); <ide> <ide> private final Set<MediaTypeFileExtensionResolver> resolvers = new LinkedHashSet<>(); <ide> public void addFileExtensionResolvers(MediaTypeFileExtensionResolver... resolver <ide> public List<MediaType> resolveMediaTypes(NativeWebRequest request) throws HttpMediaTypeNotAcceptableException { <ide> for (ContentNegotiationStrategy strategy : this.strategies) { <ide> List<MediaType> mediaTypes = strategy.resolveMediaTypes(request); <del> if (mediaTypes.isEmpty() || mediaTypes.equals(MEDIA_TYPE_ALL)) { <add> if (mediaTypes.equals(MEDIA_TYPE_ALL_LIST)) { <ide> continue; <ide> } <ide> return mediaTypes; <ide> } <del> return Collections.emptyList(); <add> return MEDIA_TYPE_ALL_LIST; <ide> } <ide> <ide> @Override <ide><path>spring-web/src/main/java/org/springframework/web/accept/ContentNegotiationStrategy.java <ide> /* <del> * Copyright 2002-2016 the original author or authors. <add> * Copyright 2002-2018 the original author or authors. <ide> * <ide> * Licensed under the Apache License, Version 2.0 (the "License"); <ide> * you may not use this file except in compliance with the License. <ide> <ide> package org.springframework.web.accept; <ide> <add>import java.util.Collections; <ide> import java.util.List; <ide> <ide> import org.springframework.http.MediaType; <ide> @FunctionalInterface <ide> public interface ContentNegotiationStrategy { <ide> <add> /** <add> * A singleton list with {@link MediaType#ALL} that is returned from <add> * {@link #resolveMediaTypes} when no specific media types are requested. <add> * @since 5.0.5 <add> */ <add> List<MediaType> MEDIA_TYPE_ALL_LIST = Collections.singletonList(MediaType.ALL); <add> <add> <ide> /** <ide> * Resolve the given request to a list of media types. The returned list is <ide> * ordered by specificity first and by quality parameter second. <ide> * @param webRequest the current request <del> * @return the requested media types or an empty list (never {@code null}) <add> * @return the requested media types, or {@link #MEDIA_TYPE_ALL_LIST} if none <add> * were requested. <ide> * @throws HttpMediaTypeNotAcceptableException if the requested media <ide> * types cannot be parsed <ide> */ <ide><path>spring-web/src/main/java/org/springframework/web/accept/HeaderContentNegotiationStrategy.java <ide> /* <del> * Copyright 2002-2016 the original author or authors. <add> * Copyright 2002-2018 the original author or authors. <ide> * <ide> * Licensed under the Apache License, Version 2.0 (the "License"); <ide> * you may not use this file except in compliance with the License. <ide> package org.springframework.web.accept; <ide> <ide> import java.util.Arrays; <del>import java.util.Collections; <ide> import java.util.List; <ide> <ide> import org.springframework.http.HttpHeaders; <ide> import org.springframework.http.InvalidMediaTypeException; <ide> import org.springframework.http.MediaType; <add>import org.springframework.util.CollectionUtils; <ide> import org.springframework.web.HttpMediaTypeNotAcceptableException; <ide> import org.springframework.web.context.request.NativeWebRequest; <ide> <ide> public List<MediaType> resolveMediaTypes(NativeWebRequest request) <ide> <ide> String[] headerValueArray = request.getHeaderValues(HttpHeaders.ACCEPT); <ide> if (headerValueArray == null) { <del> return Collections.emptyList(); <add> return MEDIA_TYPE_ALL_LIST; <ide> } <ide> <ide> List<String> headerValues = Arrays.asList(headerValueArray); <ide> try { <ide> List<MediaType> mediaTypes = MediaType.parseMediaTypes(headerValues); <ide> MediaType.sortBySpecificityAndQuality(mediaTypes); <del> return mediaTypes; <add> return !CollectionUtils.isEmpty(mediaTypes) ? mediaTypes : MEDIA_TYPE_ALL_LIST; <ide> } <ide> catch (InvalidMediaTypeException ex) { <ide> throw new HttpMediaTypeNotAcceptableException( <ide><path>spring-web/src/test/java/org/springframework/web/accept/ContentNegotiationManagerFactoryBeanTests.java <ide> /* <del> * Copyright 2002-2017 the original author or authors. <add> * Copyright 2002-2018 the original author or authors. <ide> * <ide> * Licensed under the Apache License, Version 2.0 (the "License"); <ide> * you may not use this file except in compliance with the License. <ide> <ide> import org.junit.Before; <ide> import org.junit.Test; <add> <ide> import org.springframework.http.MediaType; <ide> import org.springframework.mock.web.test.MockHttpServletRequest; <ide> import org.springframework.mock.web.test.MockServletContext; <ide> import org.springframework.web.context.request.NativeWebRequest; <ide> import org.springframework.web.context.request.ServletWebRequest; <ide> <del>import static org.junit.Assert.assertEquals; <add>import static org.junit.Assert.*; <ide> <ide> /** <ide> * Test fixture for {@link ContentNegotiationManagerFactoryBean} tests. <ide> public void defaultSettings() throws Exception { <ide> this.servletRequest.setRequestURI("/flower.foobarbaz"); <ide> <ide> assertEquals("Should ignore unknown extensions by default", <del> Collections.<MediaType>emptyList(), manager.resolveMediaTypes(this.webRequest)); <add> ContentNegotiationStrategy.MEDIA_TYPE_ALL_LIST, manager.resolveMediaTypes(this.webRequest)); <ide> <ide> this.servletRequest.setRequestURI("/flower"); <ide> this.servletRequest.setParameter("format", "gif"); <ide> <ide> assertEquals("Should not resolve request parameters by default", <del> Collections.<MediaType>emptyList(), manager.resolveMediaTypes(this.webRequest)); <add> ContentNegotiationStrategy.MEDIA_TYPE_ALL_LIST, manager.resolveMediaTypes(this.webRequest)); <ide> <ide> this.servletRequest.setRequestURI("/flower"); <ide> this.servletRequest.addHeader("Accept", MediaType.IMAGE_GIF_VALUE); <ide> public void ignoreAcceptHeader() throws Exception { <ide> this.servletRequest.setRequestURI("/flower"); <ide> this.servletRequest.addHeader("Accept", MediaType.IMAGE_GIF_VALUE); <ide> <del> assertEquals(Collections.<MediaType>emptyList(), manager.resolveMediaTypes(this.webRequest)); <add> assertEquals(ContentNegotiationStrategy.MEDIA_TYPE_ALL_LIST, manager.resolveMediaTypes(this.webRequest)); <ide> } <ide> <ide> @Test <ide><path>spring-web/src/test/java/org/springframework/web/accept/MappingContentNegotiationStrategyTests.java <ide> /* <del> * Copyright 2002-2014 the original author or authors. <add> * Copyright 2002-2018 the original author or authors. <ide> * <ide> * Licensed under the Apache License, Version 2.0 (the "License"); <ide> * you may not use this file except in compliance with the License. <ide> public void resolveMediaTypesNoMatch() throws Exception { <ide> <ide> List<MediaType> mediaTypes = strategy.resolveMediaTypes(null); <ide> <del> assertEquals(0, mediaTypes.size()); <add> assertEquals(ContentNegotiationStrategy.MEDIA_TYPE_ALL_LIST, mediaTypes); <ide> } <ide> <ide> @Test <ide> public void resolveMediaTypesNoKey() throws Exception { <ide> <ide> List<MediaType> mediaTypes = strategy.resolveMediaTypes(null); <ide> <del> assertEquals(0, mediaTypes.size()); <add> assertEquals(ContentNegotiationStrategy.MEDIA_TYPE_ALL_LIST, mediaTypes); <ide> } <ide> <ide> @Test <ide><path>spring-web/src/test/java/org/springframework/web/accept/PathExtensionContentNegotiationStrategyTests.java <ide> /* <del> * Copyright 2002-2017 the original author or authors. <add> * Copyright 2002-2018 the original author or authors. <ide> * <ide> * Licensed under the Apache License, Version 2.0 (the "License"); <ide> * you may not use this file except in compliance with the License. <ide> import org.springframework.web.context.request.NativeWebRequest; <ide> import org.springframework.web.context.request.ServletWebRequest; <ide> <del>import static org.junit.Assert.assertEquals; <del>import static org.junit.Assert.assertTrue; <add>import static org.junit.Assert.*; <ide> <ide> /** <ide> * A test fixture for PathExtensionContentNegotiationStrategy. <ide> public void getMediaTypeFilenameWithContextPath() throws Exception { <ide> <ide> this.servletRequest.setContextPath("/project-1.0.0.M3"); <ide> this.servletRequest.setRequestURI("/project-1.0.0.M3/"); <del> assertTrue("Context path should be excluded", strategy.resolveMediaTypes(webRequest).isEmpty()); <add> assertEquals("Context path should be excluded", ContentNegotiationStrategy.MEDIA_TYPE_ALL_LIST, <add> strategy.resolveMediaTypes(webRequest)); <ide> <ide> this.servletRequest.setRequestURI("/project-1.0.0.M3"); <del> assertTrue("Context path should be excluded", strategy.resolveMediaTypes(webRequest).isEmpty()); <add> assertEquals("Context path should be excluded", ContentNegotiationStrategy.MEDIA_TYPE_ALL_LIST, <add> strategy.resolveMediaTypes(webRequest)); <ide> } <ide> <ide> // SPR-9390 <ide> public void resolveMediaTypesIgnoreUnknownExtension() throws Exception { <ide> PathExtensionContentNegotiationStrategy strategy = new PathExtensionContentNegotiationStrategy(); <ide> List<MediaType> mediaTypes = strategy.resolveMediaTypes(this.webRequest); <ide> <del> assertEquals(Collections.<MediaType>emptyList(), mediaTypes); <add> assertEquals(ContentNegotiationStrategy.MEDIA_TYPE_ALL_LIST, mediaTypes); <ide> } <ide> <ide> @Test(expected = HttpMediaTypeNotAcceptableException.class) <ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/condition/ProducesRequestCondition.java <ide> public int compareTo(ProducesRequestCondition other, HttpServletRequest request) <ide> } <ide> <ide> private List<MediaType> getAcceptedMediaTypes(HttpServletRequest request) throws HttpMediaTypeNotAcceptableException { <del> List<MediaType> mediaTypes = this.contentNegotiationManager.resolveMediaTypes(new ServletWebRequest(request)); <del> return mediaTypes.isEmpty() ? Collections.singletonList(MediaType.ALL) : mediaTypes; <add> return this.contentNegotiationManager.resolveMediaTypes(new ServletWebRequest(request)); <ide> } <ide> <ide> private int indexOfEqualMediaType(MediaType mediaType) { <ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/AbstractMessageConverterMethodProcessor.java <ide> /* <del> * Copyright 2002-2017 the original author or authors. <add> * Copyright 2002-2018 the original author or authors. <ide> * <ide> * Licensed under the Apache License, Version 2.0 (the "License"); <ide> * you may not use this file except in compliance with the License. <ide> else if (converter.canWrite(valueClass, null)) { <ide> private List<MediaType> getAcceptableMediaTypes(HttpServletRequest request) <ide> throws HttpMediaTypeNotAcceptableException { <ide> <del> List<MediaType> types = this.contentNegotiationManager.resolveMediaTypes(new ServletWebRequest(request)); <del> return (types.isEmpty() ? Collections.singletonList(MediaType.ALL) : types); <add> return this.contentNegotiationManager.resolveMediaTypes(new ServletWebRequest(request)); <ide> } <ide> <ide> /** <ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/view/ContentNegotiatingViewResolver.java <ide> /* <del> * Copyright 2002-2017 the original author or authors. <add> * Copyright 2002-2018 the original author or authors. <ide> * <ide> * Licensed under the Apache License, Version 2.0 (the "License"); <ide> * you may not use this file except in compliance with the License. <ide> protected List<MediaType> getMediaTypes(HttpServletRequest request) { <ide> Assert.state(this.contentNegotiationManager != null, "No ContentNegotiationManager set"); <ide> try { <ide> ServletWebRequest webRequest = new ServletWebRequest(request); <del> <ide> List<MediaType> acceptableMediaTypes = this.contentNegotiationManager.resolveMediaTypes(webRequest); <del> acceptableMediaTypes = (!acceptableMediaTypes.isEmpty() ? acceptableMediaTypes : <del> Collections.singletonList(MediaType.ALL)); <del> <ide> List<MediaType> producibleMediaTypes = getProducibleMediaTypes(request); <ide> Set<MediaType> compatibleMediaTypes = new LinkedHashSet<>(); <ide> for (MediaType acceptable : acceptableMediaTypes) { <ide><path>spring-webmvc/src/test/java/org/springframework/web/servlet/config/annotation/ContentNegotiationConfigurerTests.java <ide> /* <del> * Copyright 2002-2017 the original author or authors. <add> * Copyright 2002-2018 the original author or authors. <ide> * <ide> * Licensed under the Apache License, Version 2.0 (the "License"); <ide> * you may not use this file except in compliance with the License. <ide> import org.springframework.http.MediaType; <ide> import org.springframework.mock.web.test.MockHttpServletRequest; <ide> import org.springframework.web.accept.ContentNegotiationManager; <add>import org.springframework.web.accept.ContentNegotiationStrategy; <ide> import org.springframework.web.accept.FixedContentNegotiationStrategy; <ide> import org.springframework.web.context.request.NativeWebRequest; <ide> import org.springframework.web.context.request.ServletWebRequest; <ide> public void defaultSettings() throws Exception { <ide> this.servletRequest.addParameter("format", "gif"); <ide> <ide> assertEquals("Should not resolve request parameters by default", <del> Collections.emptyList(), manager.resolveMediaTypes(this.webRequest)); <add> ContentNegotiationStrategy.MEDIA_TYPE_ALL_LIST, manager.resolveMediaTypes(this.webRequest)); <ide> <ide> this.servletRequest.setRequestURI("/flower"); <ide> this.servletRequest.addHeader("Accept", MediaType.IMAGE_GIF_VALUE); <ide> public void ignoreAcceptHeader() throws Exception { <ide> this.servletRequest.setRequestURI("/flower"); <ide> this.servletRequest.addHeader("Accept", MediaType.IMAGE_GIF_VALUE); <ide> <del> assertEquals(Collections.emptyList(), manager.resolveMediaTypes(this.webRequest)); <add> assertEquals(ContentNegotiationStrategy.MEDIA_TYPE_ALL_LIST, manager.resolveMediaTypes(this.webRequest)); <ide> } <ide> <ide> @Test
11
Javascript
Javascript
fix undefine style
9998b8dcbb2674ac680fd6598aea0840e69c0e1b
<ide><path>src/directives.js <ide> angularDirective("ng:hide", function(expression, element){ <ide> angularDirective("ng:style", function(expression, element){ <ide> return function(element){ <ide> this.$onEval(function(){ <del> element.css(this.$eval(expression)); <add> element.css(this.$eval(expression) || {}); <ide> }, element); <ide> }; <ide> }); <ide><path>test/directivesSpec.js <ide> describe("directives", function(){ <ide> expect(element.css('color')).toEqual('red'); <ide> }); <ide> <add> it('should silently ignore undefined ng:style', function() { <add> var scope = compile('<div ng:style="myStyle"></div>'); <add> scope.$eval(); <add> dump(sortedHtml(element)); <add> expect(element.hasClass('ng-exception')).toBeFalsy(); <add> }); <add> <ide> it('should ng:show', function(){ <ide> var scope = compile('<div ng:hide="hide"></div>'); <ide> scope.$eval();
2
PHP
PHP
fix filesystem tests failing in windows
cfed25302fd0ed945541cbffa409785c8a1e2c85
<ide><path>tests/Filesystem/FilesystemAdapterTest.php <ide> public function testPutWithStreamInterface() <ide> $spy = m::spy($this->filesystem); <ide> <ide> $filesystemAdapter = new FilesystemAdapter($spy); <del> $stream = new Stream(fopen($this->tempDir.'/foo.txt', 'r')); <del> $filesystemAdapter->put('bar.txt', $stream); <add> $stream = fopen($this->tempDir.'/foo.txt', 'r'); <add> $guzzleStream = new Stream($stream); <add> $filesystemAdapter->put('bar.txt', $guzzleStream); <add> fclose($stream); <ide> <ide> $spy->shouldHaveReceived('putStream'); <ide> $this->assertEquals('some-data', $filesystemAdapter->get('bar.txt')); <ide><path>tests/Filesystem/FilesystemTest.php <ide> public function testPutStoresFiles() <ide> $this->assertStringEqualsFile($this->tempDir.'/file.txt', 'Hello World'); <ide> } <ide> <del> public function testReplaceStoresFiles() <add> public function testReplaceCreatesFile() <ide> { <add> $tempFile = "{$this->tempDir}/file.txt"; <add> <add> $filesystem = new Filesystem; <add> <add> $filesystem->replace($tempFile, 'Hello World'); <add> $this->assertStringEqualsFile($tempFile, 'Hello World'); <add> } <add> <add> public function testReplaceWhenUnixSymlinkExists() <add> { <add> if (windows_os()) { <add> $this->markTestSkipped('Skipping since operating system is Windows'); <add> } <add> <ide> $tempFile = "{$this->tempDir}/file.txt"; <ide> $symlinkDir = "{$this->tempDir}/symlink_dir"; <ide> $symlink = "{$symlinkDir}/symlink.txt";
2
Javascript
Javascript
remove the `ipdfhistory` interface
ae90d9162be0da59fdeb748939c00173db6a7d01
<ide><path>web/interfaces.js <ide> class IPDFLinkService { <ide> isPageCached(pageNumber) {} <ide> } <ide> <del>/** <del> * @interface <del> */ <del>class IPDFHistory { <del> /** <del> * @param {Object} params <del> */ <del> initialize({ fingerprint, resetHistory = false, updateUrl = false }) {} <del> <del> reset() {} <del> <del> /** <del> * @param {Object} params <del> */ <del> push({ namedDest = null, explicitDest, pageNumber }) {} <del> <del> /** <del> * @param {number} pageNumber <del> */ <del> pushPage(pageNumber) {} <del> <del> pushCurrentPosition() {} <del> <del> back() {} <del> <del> forward() {} <del>} <del> <ide> /** <ide> * @interface <ide> */ <ide> class IL10n { <ide> export { <ide> IL10n, <ide> IPDFAnnotationLayerFactory, <del> IPDFHistory, <ide> IPDFLinkService, <ide> IPDFStructTreeLayerFactory, <ide> IPDFTextLayerFactory,
1
Ruby
Ruby
add destroy to engine's commands
0ac5c03f169b3e3055040e84ca088df134c2bfbb
<ide><path>railties/lib/rails/engine/commands.rb <ide> engine = ::Rails::Engine.find(ENGINE_ROOT) <ide> <ide> case command <del>when 'generate' <add>when 'generate', 'destroy' <ide> require 'rails/generators' <ide> engine.load_generators <del> require 'rails/commands/generate' <add> require "rails/commands/#{command}" <ide> <ide> when '--version', '-v' <ide> ARGV.unshift '--version' <ide> <ide> The common rails commands available for engines are: <ide> generate Generate new code (short-cut alias: "g") <add> destroy Undo code generated with "generate" <ide> <ide> All commands can be run with -h for more information. <ide> EOT
1
Javascript
Javascript
reduce context footprint
ff74aadbc01d1e08b297e19878ea3336a5db0d59
<ide><path>src/Container.js <ide> import identity from 'lodash/utility/identity'; <ide> <ide> export default class ReduxContainer extends Component { <ide> static contextTypes = { <del> wrapActionCreator: PropTypes.func.isRequired, <del> observeStores: PropTypes.func.isRequired <add> redux: PropTypes.object.isRequired <ide> }; <ide> <ide> static propTypes = { <ide> export default class ReduxContainer extends Component { <ide> } <ide> <ide> update(props) { <del> this.actions = mapValues(props.actions, this.context.wrapActionCreator); <add> this.actions = mapValues(props.actions, this.context.redux.wrapActionCreator); <ide> if (this.unsubscribe) { <ide> this.unsubscribe(); <ide> } <ide> export default class ReduxContainer extends Component { <ide> } <ide> <ide> this.mapState = mapState; <del> this.unsubscribe = this.context.observeStores(stores, this.handleChange); <add> this.unsubscribe = this.context.redux.observeStores(stores, this.handleChange); <ide> } <ide> <ide> handleChange(stateFromStores) { <ide><path>src/Root.js <ide> import createDispatcher from './createDispatcher'; <ide> export default function root(DecoratedComponent) { <ide> return class ReduxRoot extends Component { <ide> static childContextTypes = { <del> observeStores: PropTypes.func.isRequired, <del> wrapActionCreator: PropTypes.func.isRequired <add> redux: PropTypes.object.isRequired <ide> }; <ide> <ide> getChildContext() { <add> const { observeStores, wrapActionCreator } = this.dispatcher <ide> return { <del> observeStores: this.dispatcher.observeStores, <del> wrapActionCreator: this.dispatcher.wrapActionCreator <add> redux: { <add> observeStores, <add> wrapActionCreator <add> } <ide> }; <ide> } <ide>
2
Text
Text
add v3.8.0-beta.2 to changelog
919574fecb2a9a7d649cbe4d46692af193c6b57b
<ide><path>CHANGELOG.md <ide> # Ember Changelog <ide> <add>### v3.8.0-beta.2 (January 14, 2019) <add>- [#17467](https://github.com/emberjs/ember.js/pull/17467) [BUGFIX] Fix substate interactions with aborts <add> <ide> ### v3.8.0-beta.1 (January 7, 2019) <ide> <ide> - [#17143](https://github.com/emberjs/ember.js/pull/17143) / [#17375](https://github.com/emberjs/ember.js/pull/17375) [FEATURE] Implement Element Modifier Manager RFC (see [emberjs/rfcs#0373](https://github.com/emberjs/rfcs/blob/master/text/0373-Element-Modifier-Managers.md)).
1
Ruby
Ruby
make os x specific
536c42f7e6214087812413177d8bcebf3ab04f6e
<add><path>Library/Homebrew/test/test_os_mac_version.rb <del><path>Library/Homebrew/test/test_version_subclasses.rb <ide> require "version" <ide> require "os/mac/version" <ide> <del>class MacOSVersionTests < Homebrew::TestCase <add>class OSMacVersionTests < Homebrew::TestCase <ide> def setup <ide> @v = MacOS::Version.new("10.7") <ide> end
1
Python
Python
expose max_q_size and other generator_queue args
4f5f88b9bab58e363b95ddc1931f2036d13d14e6
<ide><path>keras/engine/training.py <ide> def standardize_weights(y, sample_weight=None, class_weight=None, <ide> def generator_queue(generator, max_q_size=10, <ide> wait_time=0.05, nb_worker=1): <ide> '''Builds a threading queue out of a data generator. <del> Used in `fit_generator`, `evaluate_generator`. <add> Used in `fit_generator`, `evaluate_generator`, `predict_generator`. <ide> ''' <ide> q = queue.Queue() <ide> _stop = threading.Event() <ide> def predict_on_batch(self, x): <ide> def fit_generator(self, generator, samples_per_epoch, nb_epoch, <ide> verbose=1, callbacks=[], <ide> validation_data=None, nb_val_samples=None, <del> class_weight={}): <add> class_weight={}, max_q_size=10): <ide> '''Fits the model on data generated batch-by-batch by <ide> a Python generator. <ide> The generator is run in parallel to the model, for efficiency. <ide> def fit_generator(self, generator, samples_per_epoch, nb_epoch, <ide> at the end of every epoch. <ide> class_weight: dictionary mapping class indices to a weight <ide> for the class. <add> max_q_size: maximum size for the generator queue <ide> <ide> # Returns <ide> A `History` object. <ide> def generate_arrays_from_file(path): <ide> self.validation_data = None <ide> <ide> # start generator thread storing batches into a queue <del> data_gen_queue, _stop = generator_queue(generator) <add> data_gen_queue, _stop = generator_queue(generator, max_q_size=max_q_size) <ide> <ide> callback_model.stop_training = False <ide> while epoch < nb_epoch: <ide> def generate_arrays_from_file(path): <ide> if samples_seen >= samples_per_epoch and do_validation: <ide> if val_gen: <ide> val_outs = self.evaluate_generator(validation_data, <del> nb_val_samples) <add> nb_val_samples, <add> max_q_size=max_q_size) <ide> else: <ide> # no need for try/except because <ide> # data has already been validated <ide> def generate_arrays_from_file(path): <ide> callbacks.on_train_end() <ide> return self.history <ide> <del> def evaluate_generator(self, generator, val_samples): <add> def evaluate_generator(self, generator, val_samples, max_q_size=10): <ide> '''Evaluates the model on a data generator. The generator should <ide> return the same kind of data as accepted by `test_on_batch`. <ide> <ide> def evaluate_generator(self, generator, val_samples): <ide> val_samples: <ide> total number of samples to generate from `generator` <ide> before returning. <add> max_q_size: maximum size for the generator queue <ide> <ide> # Returns <ide> Scalar test loss (if the model has a single output and no metrics) <ide> def evaluate_generator(self, generator, val_samples): <ide> wait_time = 0.01 <ide> all_outs = [] <ide> weights = [] <del> data_gen_queue, _stop = generator_queue(generator) <add> data_gen_queue, _stop = generator_queue(generator, max_q_size=max_q_size) <ide> <ide> while processed_samples < val_samples: <ide> generator_output = None <ide> def evaluate_generator(self, generator, val_samples): <ide> weights=weights)) <ide> return averages <ide> <del> def predict_generator(self, generator, val_samples): <add> def predict_generator(self, generator, val_samples, max_q_size=10): <ide> '''Generates predictions for the input samples from a data generator. <ide> The generator should return the same kind of data as accepted by <ide> `predict_on_batch`. <ide> def predict_generator(self, generator, val_samples): <ide> generator: generator yielding batches of input samples. <ide> val_samples: total number of samples to generate from `generator` <ide> before returning. <add> max_q_size: maximum size for the generator queue <ide> <ide> # Returns <ide> Numpy array(s) of predictions. <ide> def predict_generator(self, generator, val_samples): <ide> processed_samples = 0 <ide> wait_time = 0.01 <ide> all_outs = [] <del> data_gen_queue, _stop = generator_queue(generator) <add> data_gen_queue, _stop = generator_queue(generator, max_q_size=max_q_size) <ide> <ide> while processed_samples < val_samples: <ide> generator_output = None <ide><path>keras/models.py <ide> def predict_classes(self, x, batch_size=32, verbose=1): <ide> def fit_generator(self, generator, samples_per_epoch, nb_epoch, <ide> verbose=1, callbacks=[], <ide> validation_data=None, nb_val_samples=None, <del> class_weight=None, <del> **kwargs): <add> class_weight=None, max_q_size=10, **kwargs): <ide> '''Fits the model on data generated batch-by-batch by <ide> a Python generator. <ide> The generator is run in parallel to the model, for efficiency. <ide> def fit_generator(self, generator, samples_per_epoch, nb_epoch, <ide> at the end of every epoch. <ide> class_weight: dictionary mapping class indices to a weight <ide> for the class. <add> max_q_size: maximum size for the generator queue <ide> <ide> # Returns <ide> A `History` object. <ide> def generate_arrays_from_file(path): <ide> callbacks=callbacks, <ide> validation_data=validation_data, <ide> nb_val_samples=nb_val_samples, <del> class_weight=class_weight) <add> class_weight=class_weight, <add> max_q_size=max_q_size) <ide> <del> def evaluate_generator(self, generator, val_samples, <del> **kwargs): <add> def evaluate_generator(self, generator, val_samples, max_q_size=10, **kwargs): <ide> '''Evaluates the model on a data generator. The generator should <ide> return the same kind of data as accepted by `test_on_batch`. <ide> <ide> def evaluate_generator(self, generator, val_samples, <ide> val_samples: <ide> total number of samples to generate from `generator` <ide> before returning. <add> max_q_size: maximum size for the generator queue <ide> ''' <ide> if self.model is None: <ide> raise Exception('The model needs to be compiled before being used.') <ide> def evaluate_generator(self, generator, val_samples, <ide> raise Exception('Received unknown keyword arguments: ' + <ide> str(kwargs)) <ide> return self.model.evaluate_generator(generator, <del> val_samples) <add> val_samples, <add> max_q_size=max_q_size) <ide> <del> def predict_generator(self, generator, val_samples): <add> def predict_generator(self, generator, val_samples, max_q_size=10): <ide> '''Generates predictions for the input samples from a data generator. <ide> The generator should return the same kind of data as accepted by <ide> `predict_on_batch`. <ide> def predict_generator(self, generator, val_samples): <ide> generator: generator yielding batches of input samples. <ide> val_samples: total number of samples to generate from `generator` <ide> before returning. <add> max_q_size: maximum size for the generator queue <ide> <ide> # Returns <ide> A Numpy array of predictions. <ide> ''' <ide> if self.model is None: <ide> raise Exception('The model needs to be compiled before being used.') <del> return self.model.predict_generator(generator, val_samples) <add> return self.model.predict_generator(generator, val_samples, <add> max_q_size=max_q_size) <ide> <ide> def get_config(self): <ide> '''Returns the model configuration <ide><path>tests/keras/test_sequential_model.py <ide> def data_generator(train): <ide> model.fit_generator(data_generator(True), len(X_train), nb_epoch, validation_data=(X_test, y_test)) <ide> model.fit_generator(data_generator(True), len(X_train), nb_epoch, <ide> validation_data=data_generator(False), nb_val_samples=batch_size * 3) <add> model.fit_generator(data_generator(True), len(X_train), nb_epoch, max_q_size=2) <ide> <ide> loss = model.evaluate(X_train, y_train) <ide> <ide> def data_generator(x, y, batch_size=50): <ide> <ide> loss = model.evaluate(X_test, y_test) <ide> <del> prediction = model.predict_generator(data_generator(X_test, y_test), X_test.shape[0]) <del> gen_loss = model.evaluate_generator(data_generator(X_test, y_test, 50), X_test.shape[0]) <add> prediction = model.predict_generator(data_generator(X_test, y_test), X_test.shape[0], max_q_size=2) <add> gen_loss = model.evaluate_generator(data_generator(X_test, y_test, 50), X_test.shape[0], max_q_size=2) <ide> pred_loss = K.eval(K.mean(objectives.get(model.loss)(K.variable(y_test), K.variable(prediction)))) <ide> <ide> assert(np.isclose(pred_loss, loss))
3
Ruby
Ruby
update clang expectation for 10.11
46d45677cc06a479c39fc7a59d9077de9d84d842
<ide><path>Library/Homebrew/os/mac/xcode.rb <ide> def installed? <ide> <ide> def latest_version <ide> case MacOS.version <del> when "10.11" then "700.0.57.2" <add> when "10.11" then "700.0.59.1" <ide> when "10.10" then "602.0.53" <ide> when "10.9" then "600.0.57" <ide> when "10.8" then "503.0.40"
1
Text
Text
fix dead link on reload or open in new tab
de3596d4afbd3373d9fc0b6eeb7706e340ad2f1a
<ide><path>docs/axes/labelling.md <ide> The call to the method is scoped to the scale. `this` inside the method is the s <ide> If the callback returns `null` or `undefined` the associated grid line will be hidden. <ide> <ide> :::tip <del>The [category axis](../axes/cartesian/category), which is the default x-axis for line and bar charts, uses the `index` as internal data format. For accessing the label, use `this.getLabelForValue(value)`. [API: getLabelForValue](../api/classes/scale.html#getlabelforvalue) <add>The [category axis](../axes/cartesian/category), which is the default x-axis for line and bar charts, uses the `index` as internal data format. For accessing the label, use `this.getLabelForValue(value)`. [API: getLabelForValue](../api/classes/Scale.html#getlabelforvalue) <ide> ::: <ide> <ide> In the following example, every label of the Y-axis would be displayed with a dollar sign at the front.
1
Python
Python
update sample_weight documentation
399c00c7f87660f5a660df72fdf6fd1192c32be2
<ide><path>keras/models.py <ide> class accuracy in the logs to stdout at each epoch. <ide> used for scaling the loss function (during training only). <ide> sample_weight: list or numpy array with 1:1 mapping to <ide> the training samples, used for scaling the loss function <del> (during training only). For time-distributed data, <del> there is one weight per sample *per timestep*, <del> i.e. if your output data is shaped <del> `(nb_samples, timesteps, output_dim)`, <del> your mask should be of shape `(nb_samples, timesteps, 1)`. <del> This allows you to mask out or reweight individual <del> output timesteps, which is useful <del> in sequence to sequence learning. <add> (during training only). <ide> ''' <ide> if type(X) == list: <ide> if len(set([len(a) for a in X] + [len(y)])) != 1:
1
Mixed
Javascript
add gc tracking to common api
d37a47754d98ef82dfc5a15fb3accacbb5f09855
<ide><path>test/common/README.md <ide> otherwise. <ide> ### noWarnCode <ide> See `common.expectWarning()` for usage. <ide> <add>### onGC(target, listener) <add>* `target` [&lt;Object>] <add>* `listener` [&lt;Object>] <add> * `ongc` [&lt;Function>] <add> <add>Installs a GC listener for the collection of `target`. <add> <add>This uses `async_hooks` for GC tracking. This means that it enables <add>`async_hooks` tracking, which may affect the test functionality. It also <add>means that between a `global.gc()` call and the listener being invoked <add>a full `setImmediate()` invocation passes. <add> <add>`listener` is an object to make it easier to use a closure; the target object <add>should not be in scope when `listener.ongc()` is created. <add> <ide> ### opensslCli <ide> * [&lt;boolean>] <ide> <ide><path>test/common/index.js <ide> exports.isCPPSymbolsNotMapped = exports.isWindows || <ide> exports.isAIX || <ide> exports.isLinuxPPCBE || <ide> exports.isFreeBSD; <add> <add>const gcTrackerMap = new WeakMap(); <add>const gcTrackerTag = 'NODE_TEST_COMMON_GC_TRACKER'; <add> <add>exports.onGC = function(obj, gcListener) { <add> const async_hooks = require('async_hooks'); <add> <add> const onGcAsyncHook = async_hooks.createHook({ <add> init: exports.mustCallAtLeast(function(id, type, trigger, resource) { <add> if (this.trackedId === undefined) { <add> assert.strictEqual(type, gcTrackerTag); <add> this.trackedId = id; <add> } <add> }), <add> destroy(id) { <add> assert.notStrictEqual(this.trackedId, -1); <add> if (id === this.trackedId) { <add> this.gcListener.ongc(); <add> onGcAsyncHook.disable(); <add> } <add> } <add> }).enable(); <add> onGcAsyncHook.gcListener = gcListener; <add> <add> gcTrackerMap.set(obj, new async_hooks.AsyncResource(gcTrackerTag)); <add> obj = null; <add>}; <ide><path>test/parallel/test-common-gc.js <add>'use strict'; <add>// Flags: --expose-gc <add>const common = require('../common'); <add> <add>{ <add> const gcListener = { ongc: common.mustCall() }; <add> common.onGC({}, gcListener); <add> global.gc(); <add>} <add> <add>{ <add> const gcListener = { ongc: common.mustNotCall() }; <add> common.onGC(process, gcListener); <add> global.gc(); <add>}
3
Ruby
Ruby
use keyword argument in `transaction`
be9addb69bf1e22860be3d9b9210dada6e52d536
<ide><path>activerecord/lib/active_record/connection_adapters/abstract/database_statements.rb <ide> def supports_statement_cache? <ide> # isolation level. However, support is disabled for MySQL versions below 5, <ide> # because they are affected by a bug[http://bugs.mysql.com/bug.php?id=39170] <ide> # which means the isolation level gets persisted outside the transaction. <del> def transaction(options = {}) <del> options.assert_valid_keys :requires_new, :joinable, :isolation <del> <del> if !options[:requires_new] && current_transaction.joinable? <del> if options[:isolation] <add> def transaction(requires_new: nil, isolation: nil, joinable: true) <add> if !requires_new && current_transaction.joinable? <add> if isolation <ide> raise ActiveRecord::TransactionIsolationError, "cannot set isolation when joining a transaction" <ide> end <ide> yield <ide> else <del> transaction_manager.within_new_transaction(options) { yield } <add> transaction_manager.within_new_transaction(isolation: isolation, joinable: joinable) { yield } <ide> end <ide> rescue ActiveRecord::Rollback <ide> # rollbacks are silently swallowed
1
Python
Python
pass the matching trainer log level to deepspeed
e27707488911a4bae5936a1bdad0cfdb2018cebd
<ide><path>src/transformers/deepspeed.py <ide> def deepspeed_init(trainer, num_training_steps, resume_from_checkpoint=None): <ide> <ide> """ <ide> import deepspeed <add> from deepspeed.utils import logger as ds_logger <ide> <ide> model = trainer.model <add> args = trainer.args <ide> <del> hf_deepspeed_config = trainer.args.hf_deepspeed_config <del> hf_deepspeed_config.trainer_config_finalize(trainer.args, model, num_training_steps) <add> hf_deepspeed_config = args.hf_deepspeed_config <add> hf_deepspeed_config.trainer_config_finalize(args, model, num_training_steps) <ide> <ide> # resume config update - some bits like `model` and `num_training_steps` only become available during train <ide> config = hf_deepspeed_config.config <ide> def deepspeed_init(trainer, num_training_steps, resume_from_checkpoint=None): <ide> <ide> optimizer = None <ide> if "optimizer" in config: <del> if trainer.args.adafactor: <add> if args.adafactor: <ide> raise ValueError( <ide> "--adafactor was passed, but also found `optimizer` configured in the DeepSpeed config. " <ide> "Only one optimizer can be configured." <ide> def deepspeed_init(trainer, num_training_steps, resume_from_checkpoint=None): <ide> # keep for quick debug: <ide> # from pprint import pprint; pprint(config) <ide> <add> # set the Deepspeed log level consistent with the trainer <add> ds_logger.setLevel(args.get_process_log_level()) <add> <ide> model_parameters = filter(lambda p: p.requires_grad, model.parameters()) <ide> <ide> model, optimizer, _, lr_scheduler = deepspeed.initialize(
1
Text
Text
clarify documentation regarding the static folder
a806c16713332349cffbbe0e0ab98399e26fe955
<ide><path>readme.md <ide> So far, we get: <ide> - Automatic transpilation and bundling (with webpack and babel) <ide> - Hot code reloading <ide> - Server rendering and indexing of `./pages` <del>- Static file serving. `./static/` is mapped to `/static/` <add>- Static file serving. `./static/` is mapped to `/static/` (given you [create a `./static/` directory](#static-file-serving-eg-images) inside your project) <ide> <ide> To see how simple this is, check out the [sample app - nextgram](https://github.com/zeit/nextgram) <ide> <ide> Create a folder called `static` in your project root directory. From your code y <ide> export default () => <img src="/static/my-image.png" alt="my image" /> <ide> ``` <ide> <add>_Note: Don't name the `static` directory anything else. The name is required and is the only directory that Next.js uses for serving static assets._ <add> <ide> ### Populating `<head>` <ide> <ide> <p><details>
1
Javascript
Javascript
use getownpropertynames to check for empty object
d150dc7d026e89e042bc134b03fd69fd3e2023aa
<ide><path>src/lib/utils/is-object-empty.js <ide> export default function isObjectEmpty(obj) { <del> if (Object.keys) { <del> return (Object.keys(obj).length === 0); <add> if (Object.getOwnPropertyNames) { <add> return (Object.getOwnPropertyNames(obj).length === 0); <ide> } else { <ide> var k; <ide> for (k in obj) { <del> // even if its not own property I'd still call it non-empty <del> return false; <add> if (obj.hasOwnProperty(k)) { <add> return false; <add> } <ide> } <ide> return true; <ide> }
1
Ruby
Ruby
move gnunet to the boneyard
758608815f24a8823918c76e710a8f2fba890b0b
<ide><path>Library/Homebrew/tap_migrations.rb <ide> "drizzle" => "homebrew/boneyard", <ide> "drush" => "homebrew/php", <ide> "dsniff" => "homebrew/boneyard", <add> "gnunet" => "homebrew/boneyard", <ide> "grads" => "homebrew/binary", <ide> "gromacs" => "homebrew/science", <ide> "hllib" => "homebrew/boneyard",
1
Text
Text
remove vestigial onboarding section
7dca3297bce9c19a0451be1b130c8fcab564fe04
<ide><path>doc/onboarding-extras.md <ide> to update from nodejs/node: <ide> * `git checkout master` <ide> * `git remote update -p` OR `git fetch --all` <ide> * `git merge --ff-only upstream/master` (or `REMOTENAME/BRANCH`) <del> <del>## Best practices <del> <del>* When making PRs, spend time writing a thorough description.
1
Python
Python
remove print statement
6b7198e74e39c18317cd50dd077732beeae7b4bb
<ide><path>libcloud/storage/drivers/cloudfiles.py <ide> def _put_object(self, container, object_name, upload_func, <ide> <ide> response = result_dict['response'].response <ide> bytes_transferred = result_dict['bytes_transferred'] <del> print result_dict['data_hash'] <ide> server_hash = result_dict['response'].headers.get('etag', None) <ide> <ide> if response.status == httplib.EXPECTATION_FAILED:
1
Text
Text
fix typos in fog article
8be8bef50b28d98ee558b9f0da75041b6caaa32c
<ide><path>threejs/lessons/threejs-fog.md <ide> past that distance. <ide> </div> <ide> <ide> It's important to note that the fog is applied to *things that are rendered*. <del>It is part of the calculation of each pixel of the color of the object. <del>What that means is if you want your scene to fade to a certain color you <del>need to set the fog **and** the background color to the same color. <del>The background color is set using the <add>It is part of the calculation of each pixel of the color of the object. <add>What that means is if you want your scene to fade to a certain color you <add>need to set the fog **and** the background color to the same color. <add>The background color is set using the <ide> [`scene.background`](Scene.background) <ide> property. To pick a background color you attach a `THREE.Color` to it. For example <ide> <ide> will fade out right around their center. <ide> <ide> {{{example url="../threejs-fog.html" }}} <ide> <del>Let's add an interface so we can adjust the fog. Again we'll use <add>Let's add an interface so we can adjust the fog. Again we'll use <ide> [dat.GUI](https://github.com/dataarts/dat.gui). dat.GUI takes <ide> an object and a property and automagically makes an interface <ide> for that type of property. We could just simply let it manipulate <ide> We can then add it like this <ide> } <ide> ``` <ide> <del>The `near` and `far` parameter set the minimum and maximum values <add>The `near` and `far` parameters set the minimum and maximum values <ide> for adjusting the fog. They are set when we setup the camera. <ide> <ide> The `.listen()` at the end of the last 2 lines tells dat.GUI to *listen* <ide> mentioned above we need to keep both the fog color and the background <ide> color in sync. So, let's add another *virtual* property to our helper <ide> that will set both colors when dat.GUI manipulates it. <ide> <del>dat.GUI can manipulate colors in 4 ways, as a CSS 6 digit hex string (eg: `#112233`). As an hue, saturation, value, object (eg: `{h: 60, s: 1, v: }`). <add>dat.GUI can manipulate colors in 4 ways, as a CSS 6 digit hex string (eg: `#112233`). As an hue, saturation, value, object (eg: `{h: 60, s: 1, v: }`). <ide> As an RGB array (eg: `[255, 128, 64]`). Or, as an RGBA array (eg: `[127, 200, 75, 0.3]`). <ide> <ide> It's easiest for our purpose to use the hex string version since that way <ide> for most materials. As an example of why you might want <ide> to turn the fog off, imagine you're making a 3D vehicle <ide> simulator with a view from the driver's seat or cockpit. <ide> You probably want the fog off for everything inside the vehicle when <del>viewing from inside the vehicle. <add>viewing from inside the vehicle. <ide> <ide> A better example might be a house <ide> and thick fog outside house. Let's say the fog is set to start <ide> 2 meters away (near = 2) and completely fogged out at 4 meters (far = 4). <ide> Rooms are longer than 2 meters and the house is probably longer <ide> than 4 meters so you need to set the materials for the inside <ide> of the house to not apply fog otherwise when standing inside the <del>house looking outside the wall at the far end of the room will look <add>house looking outside the wall at the far end of the room will look <ide> like it's in the fog. <ide> <ide> <div class="spread"> <ide> like it's in the fog. <ide> </div> <ide> <ide> Notice the walls and ceiling at the far end of the room are getting fog applied. <del>By turing fog of on the materials for the house we can fix that issue. <add>By turning fog off on the materials for the house we can fix that issue. <ide> <ide> <div class="spread"> <ide> <div>
1
Java
Java
use httpmethod enums
55faf6e3205d26a4ba693f40c1ea1cef179f31cb
<ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/DispatcherServlet.java <ide> import org.springframework.core.io.ClassPathResource; <ide> import org.springframework.core.io.support.PropertiesLoaderUtils; <ide> import org.springframework.core.log.LogFormatUtils; <add>import org.springframework.http.HttpMethod; <ide> import org.springframework.http.server.RequestPath; <ide> import org.springframework.http.server.ServletServerHttpRequest; <ide> import org.springframework.lang.Nullable; <ide> protected void doDispatch(HttpServletRequest request, HttpServletResponse respon <ide> <ide> // Process last-modified header, if supported by the handler. <ide> String method = request.getMethod(); <del> boolean isGet = "GET".equals(method); <del> if (isGet || "HEAD".equals(method)) { <add> boolean isGet = HttpMethod.GET.matches(method); <add> if (isGet || HttpMethod.HEAD.matches(method)) { <ide> long lastModified = ha.getLastModified(request, mappedHandler.getHandler()); <ide> if (new ServletWebRequest(request, response).checkNotModified(lastModified) && isGet) { <ide> return;
1
Go
Go
update documentation for serviceupdate
77162b39dad0c11f1ea60c898f2855f7fbbecf47
<ide><path>client/service_update.go <ide> import ( <ide> "github.com/docker/docker/api/types/swarm" <ide> ) <ide> <del>// ServiceUpdate updates a Service. <add>// ServiceUpdate updates a Service. The version number is required to avoid conflicting writes. <add>// It should be the value as set *before* the update. You can find this value in the Meta field <add>// of swarm.Service, which can be found using ServiceInspectWithRaw. <ide> func (cli *Client) ServiceUpdate(ctx context.Context, serviceID string, version swarm.Version, service swarm.ServiceSpec, options types.ServiceUpdateOptions) (types.ServiceUpdateResponse, error) { <ide> var ( <ide> query = url.Values{}
1
Ruby
Ruby
ignore nameerror and argumenterror
8809c85cc3515736f5c7b85436d1020aa17cb6c4
<ide><path>Library/Homebrew/cmd/versions.rb <ide> def version_for_sha sha <ide> version = nostdout { Formula.factory(path).version } <ide> Object.send(:remove_const, Formula.class_s(name)) <ide> version <del> rescue SyntaxError, TypeError <add> rescue SyntaxError, TypeError, NameError, ArgumentError <ide> # We rescue these so that we can skip bad versions and <ide> # continue walking the history <ide> nil
1
PHP
PHP
define the expected exception
994cf4c422e59a7d2ee188bf7d5537f64f6c9e23
<ide><path>tests/Database/DatabaseConnectionTest.php <ide> public function testLogQueryFiresEventsIfSet() <ide> <ide> public function testBeforeExecutingHooksCanBeRegistered() <ide> { <add> $this->expectException(Exception::class); <ide> $this->expectExceptionMessage('The callback was fired'); <ide> <ide> $connection = $this->getMockConnection(); <ide><path>tests/Database/DatabaseSchemaBlueprintIntegrationTest.php <ide> <ide> namespace Illuminate\Tests\Database; <ide> <add>use BadMethodCallException; <ide> use Illuminate\Container\Container; <ide> use Illuminate\Database\Capsule\Manager as DB; <ide> use Illuminate\Database\Schema\Blueprint; <ide> public function testAddUniqueIndexWithNameWorks() <ide> <ide> public function testItEnsuresDroppingMultipleColumnsIsAvailable() <ide> { <add> $this->expectException(BadMethodCallException::class); <ide> $this->expectExceptionMessage("SQLite doesn't support multiple calls to dropColumn / renameColumn in a single modification."); <ide> <ide> $this->db->connection()->getSchemaBuilder()->table('users', function (Blueprint $table) { <ide> public function testItEnsuresDroppingMultipleColumnsIsAvailable() <ide> <ide> public function testItEnsuresRenamingMultipleColumnsIsAvailable() <ide> { <add> $this->expectException(BadMethodCallException::class); <ide> $this->expectExceptionMessage("SQLite doesn't support multiple calls to dropColumn / renameColumn in a single modification."); <ide> <ide> $this->db->connection()->getSchemaBuilder()->table('users', function (Blueprint $table) { <ide> public function testItEnsuresRenamingMultipleColumnsIsAvailable() <ide> <ide> public function testItEnsuresRenamingAndDroppingMultipleColumnsIsAvailable() <ide> { <add> $this->expectException(BadMethodCallException::class); <ide> $this->expectExceptionMessage("SQLite doesn't support multiple calls to dropColumn / renameColumn in a single modification."); <ide> <ide> $this->db->connection()->getSchemaBuilder()->table('users', function (Blueprint $table) { <ide> public function testItEnsuresRenamingAndDroppingMultipleColumnsIsAvailable() <ide> <ide> public function testItEnsuresDroppingForeignKeyIsAvailable() <ide> { <add> $this->expectException(BadMethodCallException::class); <ide> $this->expectExceptionMessage("SQLite doesn't support dropping foreign keys (you would need to re-create the table)."); <ide> <ide> $this->db->connection()->getSchemaBuilder()->table('users', function (Blueprint $table) { <ide><path>tests/Integration/Queue/JobEncryptionTest.php <ide> namespace Illuminate\Tests\Integration\Queue; <ide> <ide> use Illuminate\Bus\Queueable; <add>use Illuminate\Contracts\Encryption\DecryptException; <ide> use Illuminate\Contracts\Queue\ShouldBeEncrypted; <ide> use Illuminate\Contracts\Queue\ShouldQueue; <ide> use Illuminate\Database\Schema\Blueprint; <ide> public function testNonEncryptedJobPayloadIsStoredRaw() <ide> { <ide> Bus::dispatch(new JobEncryptionTestNonEncryptedJob); <ide> <add> $this->expectException(DecryptException::class); <ide> $this->expectExceptionMessage('The payload is invalid'); <ide> <ide> $this->assertInstanceOf(JobEncryptionTestNonEncryptedJob::class, <ide><path>tests/View/Blade/BladeEchoHandlerTest.php <ide> public function testWhitespaceIsPreservedCorrectly() <ide> */ <ide> public function testHandlerLogicWorksCorrectly($blade) <ide> { <add> $this->expectException(Exception::class); <ide> $this->expectExceptionMessage('The fluent object has been successfully handled!'); <ide> <ide> $this->compiler->stringable(Fluent::class, function ($object) {
4
Javascript
Javascript
extract the type checker into a separate module
db6ac5c01c4ad669db7ca264bc81ae5b3d6dfa01
<ide><path>src/isomorphic/classic/__tests__/ReactContextValidator-test.js <ide> var ReactTestUtils; <ide> var reactComponentExpect; <ide> <ide> describe('ReactContextValidator', function() { <add> function normalizeCodeLocInfo(str) { <add> return str.replace(/\(at .+?:\d+\)/g, '(at **)'); <add> } <add> <ide> beforeEach(function() { <ide> jest.resetModuleRegistry(); <ide> <ide> describe('ReactContextValidator', function() { <ide> ReactTestUtils.renderIntoDocument(<Component />); <ide> <ide> expect(console.error.argsForCall.length).toBe(1); <del> expect(console.error.argsForCall[0][0]).toBe( <del> 'Warning: Failed Context Types: ' + <del> 'Required context `foo` was not specified in `Component`.' <add> expect(normalizeCodeLocInfo(console.error.argsForCall[0][0])).toBe( <add> 'Warning: Failed context type: ' + <add> 'Required context `foo` was not specified in `Component`.\n' + <add> ' in Component (at **)' <ide> ); <ide> <ide> var ComponentInFooStringContext = React.createClass({ <ide> describe('ReactContextValidator', function() { <ide> ReactTestUtils.renderIntoDocument(<ComponentInFooNumberContext fooValue={123} />); <ide> <ide> expect(console.error.argsForCall.length).toBe(2); <del> expect(console.error.argsForCall[1][0]).toBe( <del> 'Warning: Failed Context Types: ' + <add> expect(normalizeCodeLocInfo(console.error.argsForCall[1][0])).toBe( <add> 'Warning: Failed context type: ' + <ide> 'Invalid context `foo` of type `number` supplied ' + <del> 'to `Component`, expected `string`.' + <del> ' Check the render method of `ComponentInFooNumberContext`.' <add> 'to `Component`, expected `string`.\n' + <add> ' in Component (at **)\n' + <add> ' in ComponentInFooNumberContext (at **)' <ide> ); <ide> }); <ide> <ide> describe('ReactContextValidator', function() { <ide> <ide> ReactTestUtils.renderIntoDocument(<Component testContext={{bar: 123}} />); <ide> expect(console.error.argsForCall.length).toBe(1); <del> expect(console.error.argsForCall[0][0]).toBe( <del> 'Warning: Failed Context Types: ' + <del> 'Required child context `foo` was not specified in `Component`.' <add> expect(normalizeCodeLocInfo(console.error.argsForCall[0][0])).toBe( <add> 'Warning: Failed childContext type: ' + <add> 'Required child context `foo` was not specified in `Component`.\n' + <add> ' in Component (at **)' <ide> ); <ide> <ide> ReactTestUtils.renderIntoDocument(<Component testContext={{foo: 123}} />); <ide> <ide> expect(console.error.argsForCall.length).toBe(2); <del> expect(console.error.argsForCall[1][0]).toBe( <del> 'Warning: Failed Context Types: ' + <add> expect(normalizeCodeLocInfo(console.error.argsForCall[1][0])).toBe( <add> 'Warning: Failed childContext type: ' + <ide> 'Invalid child context `foo` of type `number` ' + <del> 'supplied to `Component`, expected `string`.' <add> 'supplied to `Component`, expected `string`.\n' + <add> ' in Component (at **)' <ide> ); <ide> <ide> ReactTestUtils.renderIntoDocument( <ide><path>src/isomorphic/classic/element/ReactElementValidator.js <ide> var ReactCurrentOwner = require('ReactCurrentOwner'); <ide> var ReactComponentTreeDevtool = require('ReactComponentTreeDevtool'); <ide> var ReactElement = require('ReactElement'); <del>var ReactPropTypeLocationNames = require('ReactPropTypeLocationNames'); <ide> var ReactPropTypeLocations = require('ReactPropTypeLocations'); <ide> <add>var checkReactTypeSpec = require('checkReactTypeSpec'); <add> <ide> var canDefineProperty = require('canDefineProperty'); <ide> var getIteratorFn = require('getIteratorFn'); <del>var invariant = require('invariant'); <ide> var warning = require('warning'); <ide> <ide> function getDeclarationErrorAddendum() { <ide> function getDeclarationErrorAddendum() { <ide> */ <ide> var ownerHasKeyUseWarning = {}; <ide> <del>var loggedTypeFailures = {}; <del> <ide> function getCurrentComponentErrorInfo(parentType) { <ide> var info = getDeclarationErrorAddendum(); <ide> <ide> function validateChildKeys(node, parentType) { <ide> } <ide> } <ide> <del>/** <del> * Assert that the props are valid <del> * <del> * @param {object} element <del> * @param {string} componentName Name of the component for error messages. <del> * @param {object} propTypes Map of prop name to a ReactPropType <del> * @param {string} location e.g. "prop", "context", "child context" <del> * @private <del> */ <del>function checkPropTypes(element, componentName, propTypes, location) { <del> var props = element.props; <del> for (var propName in propTypes) { <del> if (propTypes.hasOwnProperty(propName)) { <del> var error; <del> // Prop type validation may throw. In case they do, we don't want to <del> // fail the render phase where it didn't fail before. So we log it. <del> // After these have been cleaned up, we'll let them throw. <del> try { <del> // This is intentionally an invariant that gets caught. It's the same <del> // behavior as without this statement except with a better message. <del> invariant( <del> typeof propTypes[propName] === 'function', <del> '%s: %s type `%s` is invalid; it must be a function, usually from ' + <del> 'React.PropTypes.', <del> componentName || 'React class', <del> ReactPropTypeLocationNames[location], <del> propName <del> ); <del> error = propTypes[propName](props, propName, componentName, location); <del> } catch (ex) { <del> error = ex; <del> } <del> warning( <del> !error || error instanceof Error, <del> '%s: type specification of %s `%s` is invalid; the type checker ' + <del> 'function must return `null` or an `Error` but returned a %s. ' + <del> 'You may have forgotten to pass an argument to the type checker ' + <del> 'creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and ' + <del> 'shape all require an argument).', <del> componentName || 'React class', <del> ReactPropTypeLocationNames[location], <del> propName, <del> typeof error <del> ); <del> if (error instanceof Error && !(error.message in loggedTypeFailures)) { <del> // Only monitor this failure once because there tends to be a lot of the <del> // same error. <del> loggedTypeFailures[error.message] = true; <del> <del> warning( <del> false, <del> 'Failed propType: %s%s', <del> error.message, <del> ReactComponentTreeDevtool.getCurrentStackAddendum(element) <del> ); <del> } <del> } <del> } <del>} <del> <ide> /** <ide> * Given an element, validate that its props follow the propTypes definition, <ide> * provided by the type. <ide> function validatePropTypes(element) { <ide> } <ide> var name = componentClass.displayName || componentClass.name; <ide> if (componentClass.propTypes) { <del> checkPropTypes( <del> element, <del> name, <add> checkReactTypeSpec( <ide> componentClass.propTypes, <del> ReactPropTypeLocations.prop <add> element.props, <add> ReactPropTypeLocations.prop, <add> name, <add> element, <add> null <ide> ); <ide> } <ide> if (typeof componentClass.getDefaultProps === 'function') { <ide><path>src/isomorphic/classic/element/__tests__/ReactElementClone-test.js <ide> describe('ReactElementClone', function() { <ide> ReactTestUtils.renderIntoDocument(React.createElement(GrandParent)); <ide> expect(console.error.argsForCall.length).toBe(1); <ide> expect(console.error.argsForCall[0][0]).toBe( <del> 'Warning: Failed propType: ' + <add> 'Warning: Failed prop type: ' + <ide> 'Invalid prop `color` of type `number` supplied to `Component`, ' + <ide> 'expected `string`.\n' + <ide> ' in Component (created by GrandParent)\n' + <ide><path>src/isomorphic/classic/element/__tests__/ReactElementValidator-test.js <ide> describe('ReactElementValidator', function() { <ide> }); <ide> ReactTestUtils.renderIntoDocument(React.createElement(ParentComp)); <ide> expect(console.error.argsForCall[0][0]).toBe( <del> 'Warning: Failed propType: ' + <add> 'Warning: Failed prop type: ' + <ide> 'Invalid prop `color` of type `number` supplied to `MyComp`, ' + <ide> 'expected `string`.\n' + <ide> ' in MyComp (created by ParentComp)\n' + <ide> describe('ReactElementValidator', function() { <ide> <ide> expect(console.error.calls.length).toBe(1); <ide> expect(console.error.argsForCall[0][0]).toBe( <del> 'Warning: Failed propType: ' + <add> 'Warning: Failed prop type: ' + <ide> 'Required prop `prop` was not specified in `Component`.\n' + <ide> ' in Component' <ide> ); <ide> describe('ReactElementValidator', function() { <ide> <ide> expect(console.error.calls.length).toBe(1); <ide> expect(console.error.argsForCall[0][0]).toBe( <del> 'Warning: Failed propType: ' + <add> 'Warning: Failed prop type: ' + <ide> 'Required prop `prop` was not specified in `Component`.\n' + <ide> ' in Component' <ide> ); <ide> describe('ReactElementValidator', function() { <ide> <ide> expect(console.error.calls.length).toBe(2); <ide> expect(console.error.argsForCall[0][0]).toBe( <del> 'Warning: Failed propType: ' + <add> 'Warning: Failed prop type: ' + <ide> 'Required prop `prop` was not specified in `Component`.\n' + <ide> ' in Component' <ide> ); <ide> <ide> expect(console.error.argsForCall[1][0]).toBe( <del> 'Warning: Failed propType: ' + <add> 'Warning: Failed prop type: ' + <ide> 'Invalid prop `prop` of type `number` supplied to ' + <ide> '`Component`, expected `string`.\n' + <ide> ' in Component' <ide><path>src/isomorphic/classic/types/__tests__/ReactPropTypes-test.js <ide> describe('ReactPropTypes', function() { <ide> instance = ReactTestUtils.renderIntoDocument(instance); <ide> <ide> expect(spy.argsForCall.length).toBe(1); <del> expect(spy.argsForCall[0][1]).toBe('num'); <add> expect(spy.argsForCall[0][1]).toBe('num'); <ide> }); <ide> <ide> it('should have received the validator\'s return value', function() { <ide> describe('ReactPropTypes', function() { <ide> expect( <ide> console.error.argsForCall[0][0].replace(/\(at .+?:\d+\)/g, '(at **)') <ide> ).toBe( <del> 'Warning: Failed propType: num must be 5!\n' + <add> 'Warning: Failed prop type: num must be 5!\n' + <ide> ' in Component (at **)' <ide> ); <ide> }); <ide><path>src/isomorphic/classic/types/checkReactTypeSpec.js <add>/** <add> * Copyright 2013-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> * @providesModule checkReactTypeSpec <add> */ <add> <add>'use strict'; <add> <add>var ReactComponentTreeDevtool = require('ReactComponentTreeDevtool'); <add>var ReactPropTypeLocationNames = require('ReactPropTypeLocationNames'); <add> <add>var invariant = require('invariant'); <add>var warning = require('warning'); <add> <add>var loggedTypeFailures = {}; <add> <add>/** <add> * Assert that the values match with the type specs. <add> * Error messages are memorized and will only be shown once. <add> * <add> * @param {object} typeSpecs Map of name to a ReactPropType <add> * @param {object} values Runtime values that need to be type-checked <add> * @param {string} location e.g. "prop", "context", "child context" <add> * @param {string} componentName Name of the component for error messages. <add> * @param {?object} element The React element that is being type-checked <add> * @param {?number} debugID The React component instance that is being type-checked <add> * @private <add> */ <add>function checkReactTypeSpec(typeSpecs, values, location, componentName, element, debugID) { <add> for (var typeSpecName in typeSpecs) { <add> if (typeSpecs.hasOwnProperty(typeSpecName)) { <add> var error; <add> // Prop type validation may throw. In case they do, we don't want to <add> // fail the render phase where it didn't fail before. So we log it. <add> // After these have been cleaned up, we'll let them throw. <add> try { <add> // This is intentionally an invariant that gets caught. It's the same <add> // behavior as without this statement except with a better message. <add> invariant( <add> typeof typeSpecs[typeSpecName] === 'function', <add> '%s: %s type `%s` is invalid; it must be a function, usually from ' + <add> 'React.PropTypes.', <add> componentName || 'React class', <add> ReactPropTypeLocationNames[location], <add> typeSpecName <add> ); <add> error = typeSpecs[typeSpecName](values, typeSpecName, componentName, location); <add> } catch (ex) { <add> error = ex; <add> } <add> warning( <add> !error || error instanceof Error, <add> '%s: type specification of %s `%s` is invalid; the type checker ' + <add> 'function must return `null` or an `Error` but returned a %s. ' + <add> 'You may have forgotten to pass an argument to the type checker ' + <add> 'creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and ' + <add> 'shape all require an argument).', <add> componentName || 'React class', <add> ReactPropTypeLocationNames[location], <add> typeSpecName, <add> typeof error <add> ); <add> if (error instanceof Error && !(error.message in loggedTypeFailures)) { <add> // Only monitor this failure once because there tends to be a lot of the <add> // same error. <add> loggedTypeFailures[error.message] = true; <add> <add> var componentStackInfo = ''; <add> <add> if (debugID !== null) { <add> componentStackInfo = ReactComponentTreeDevtool.getStackAddendumByID(debugID); <add> } else if (element !== null) { <add> componentStackInfo = ReactComponentTreeDevtool.getCurrentStackAddendum(element); <add> } <add> <add> warning( <add> false, <add> 'Failed %s type: %s%s', <add> location, <add> error.message, <add> componentStackInfo <add> ); <add> } <add> } <add> } <add>} <add> <add>module.exports = checkReactTypeSpec; <ide><path>src/isomorphic/modern/element/__tests__/ReactJSXElementValidator-test.js <ide> describe('ReactJSXElementValidator', function() { <ide> expect( <ide> console.error.argsForCall[0][0].replace(/\(at .+?:\d+\)/g, '(at **)') <ide> ).toBe( <del> 'Warning: Failed propType: ' + <add> 'Warning: Failed prop type: ' + <ide> 'Invalid prop `color` of type `number` supplied to `MyComp`, ' + <ide> 'expected `string`.\n' + <ide> ' in MyComp (at **)\n' + <ide> describe('ReactJSXElementValidator', function() { <ide> expect( <ide> console.error.argsForCall[0][0].replace(/\(at .+?:\d+\)/g, '(at **)') <ide> ).toBe( <del> 'Warning: Failed propType: ' + <add> 'Warning: Failed prop type: ' + <ide> 'Required prop `prop` was not specified in `RequiredPropComponent`.\n' + <ide> ' in RequiredPropComponent (at **)' <ide> ); <ide> describe('ReactJSXElementValidator', function() { <ide> expect( <ide> console.error.argsForCall[0][0].replace(/\(at .+?:\d+\)/g, '(at **)') <ide> ).toBe( <del> 'Warning: Failed propType: ' + <add> 'Warning: Failed prop type: ' + <ide> 'Required prop `prop` was not specified in `RequiredPropComponent`.\n' + <ide> ' in RequiredPropComponent (at **)' <ide> ); <ide> describe('ReactJSXElementValidator', function() { <ide> expect( <ide> console.error.argsForCall[0][0].replace(/\(at .+?:\d+\)/g, '(at **)') <ide> ).toBe( <del> 'Warning: Failed propType: ' + <add> 'Warning: Failed prop type: ' + <ide> 'Required prop `prop` was not specified in `RequiredPropComponent`.\n' + <ide> ' in RequiredPropComponent (at **)' <ide> ); <ide> <ide> expect( <ide> console.error.argsForCall[1][0].replace(/\(at .+?:\d+\)/g, '(at **)') <ide> ).toBe( <del> 'Warning: Failed propType: ' + <add> 'Warning: Failed prop type: ' + <ide> 'Invalid prop `prop` of type `number` supplied to ' + <ide> '`RequiredPropComponent`, expected `string`.\n' + <ide> ' in RequiredPropComponent (at **)' <ide><path>src/renderers/shared/stack/reconciler/ReactCompositeComponent.js <ide> var ReactInstanceMap = require('ReactInstanceMap'); <ide> var ReactInstrumentation = require('ReactInstrumentation'); <ide> var ReactNodeTypes = require('ReactNodeTypes'); <ide> var ReactPropTypeLocations = require('ReactPropTypeLocations'); <del>var ReactPropTypeLocationNames = require('ReactPropTypeLocationNames'); <ide> var ReactReconciler = require('ReactReconciler'); <ide> var ReactUpdateQueue = require('ReactUpdateQueue'); <ide> <add>var checkReactTypeSpec = require('checkReactTypeSpec'); <add> <ide> var emptyObject = require('emptyObject'); <ide> var invariant = require('invariant'); <ide> var shouldUpdateReactComponent = require('shouldUpdateReactComponent'); <ide> var warning = require('warning'); <ide> <del>function getDeclarationErrorAddendum(component) { <del> var owner = component._currentElement._owner || null; <del> if (owner) { <del> var name = owner.getName(); <del> if (name) { <del> return ' Check the render method of `' + name + '`.'; <del> } <del> } <del> return ''; <del>} <del> <ide> function StatelessComponent(Component) { <ide> } <ide> StatelessComponent.prototype.render = function() { <ide> var ReactCompositeComponentMixin = { <ide> /** <ide> * Assert that the context types are valid <ide> * <del> * @param {object} propTypes Map of context field to a ReactPropType <del> * @param {object} props <add> * @param {object} typeSpecs Map of context field to a ReactPropType <add> * @param {object} values Runtime values that need to be type-checked <ide> * @param {string} location e.g. "prop", "context", "child context" <ide> * @private <ide> */ <del> _checkContextTypes: function(propTypes, props, location) { <del> var componentName = this.getName(); <del> for (var propName in propTypes) { <del> if (propTypes.hasOwnProperty(propName)) { <del> var error; <del> try { <del> // This is intentionally an invariant that gets caught. It's the same <del> // behavior as without this statement except with a better message. <del> invariant( <del> typeof propTypes[propName] === 'function', <del> '%s: %s type `%s` is invalid; it must be a function, usually ' + <del> 'from React.PropTypes.', <del> componentName || 'React class', <del> ReactPropTypeLocationNames[location], <del> propName <del> ); <del> error = propTypes[propName](props, propName, componentName, location); <del> } catch (ex) { <del> error = ex; <del> } <del> if (error instanceof Error) { <del> // We may want to extend this logic for similar errors in <del> // top-level render calls, so I'm abstracting it away into <del> // a function to minimize refactoring in the future <del> var addendum = getDeclarationErrorAddendum(this); <del> warning( <del> false, <del> 'Failed Context Types: %s%s', <del> error.message, <del> addendum <del> ); <del> } <del> } <del> } <add> _checkContextTypes: function(typeSpecs, values, location) { <add> checkReactTypeSpec( <add> typeSpecs, <add> values, <add> location, <add> this.getName(), <add> null, <add> this._debugID <add> ); <ide> }, <ide> <ide> receiveComponent: function(nextElement, transaction, nextContext) { <ide><path>src/renderers/shared/stack/reconciler/__tests__/ReactStatelessComponent-test.js <ide> describe('ReactStatelessComponent', function() { <ide> expect( <ide> console.error.argsForCall[0][0].replace(/\(at .+?:\d+\)/g, '(at **)') <ide> ).toBe( <del> 'Warning: Failed propType: Invalid prop `test` of type `number` ' + <add> 'Warning: Failed prop type: Invalid prop `test` of type `number` ' + <ide> 'supplied to `Child`, expected `string`.\n' + <ide> ' in Child (at **)' <ide> );
9
Javascript
Javascript
add testconfig.timeout to configtestcases
f0ef3fd6ae6be6e2ade7a6565cc789fa26a15273
<ide><path>test/ConfigTestCases.test.js <ide> describe("ConfigTestCases", () => { <ide> testConfig = Object.assign(testConfig, require(path.join(testDirectory, "test.config.js"))); <ide> } catch(e) {} <ide> <del> // this.timeout(testConfig.timeout); <del> <ide> webpack(options, (err, stats) => { <ide> if(err) { <ide> const fakeStats = { <ide> describe("ConfigTestCases", () => { <ide> let exportedTests = []; <ide> <ide> function _it(title, fn) { <del> exportedTests.push(fit(title, fn)); <add> exportedTests.push(fit(title, fn, testConfig.timeout)); <ide> } <ide> <ide> const globalContext = {
1