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
Go
Go
fix flaky test testrunexitonstdinclose
f84cabd3b8a737e7539d71773b842daa8f0dc66b
<ide><path>integration-cli/docker_cli_run_test.go <ide> func (s *DockerSuite) TestRunExitOnStdinClose(c *check.C) { <ide> name := "testrunexitonstdinclose" <ide> <ide> meow := "/bin/cat" <del> delay := 1 <add> delay := 60 <ide> if daemonPlatform == "windows" { <ide> meow = "cat" <del> delay = 60 <ide> } <ide> runCmd := exec.Command(dockerBinary, "run", "--name", name, "-i", "busybox", meow) <ide>
1
Ruby
Ruby
use project-by tool to retrieve formula data
4fa01fc8b75d2d0530327e9c0f11aede26a150fa
<ide><path>Library/Homebrew/dev-cmd/bump.rb <ide> def bump <ide> repo["repo"] == "homebrew" <ide> end <ide> <del> next if homebrew_repo.blank? # TODO: check if/when this ever happens <add> next if homebrew_repo.blank? <ide> <ide> formula = begin <ide> Formula[homebrew_repo["srcname"]] <ide><path>Library/Homebrew/utils/repology.rb <ide> def query_api(last_package_in_response = "") <ide> end <ide> <ide> def single_package_query(name) <del> url = "https://repology.org/api/v1/project/#{name}" <del> <del> output, _errors, _status = curl_output(url.to_s) <del> data = JSON.parse(output) <del> <del> homebrew = data.select do |repo| <del> repo["repo"] == "homebrew" <add> url = %W[ <add> https://repology.org/tools/project-by?repo=homebrew& <add> name_type=srcname&target_page=api_v1_project&name=#{name} <add> ].join <add> <add> output, _errors, _status = curl_output("--location", url.to_s) <add> <add> begin <add> data = JSON.parse(output) <add> { name => data } <add> rescue <add> nil <ide> end <del> <del> homebrew.empty? ? nil : { name => data } <ide> end <ide> <ide> def parse_api_response(limit = nil) <ide> def parse_api_response(limit = nil) <ide> end <ide> <ide> def latest_version(repositories) <del> # TODO: explain unique <add> # The status is "unique" when the package is present only in Homebrew, so Repology <add> # has no way of knowing if the package is up-to-date. <ide> is_unique = repositories.find do |repo| <ide> repo["status"] == "unique" <ide> end.present? <ide> def latest_version(repositories) <ide> repo["status"] == "newest" <ide> end <ide> <del> # TODO: explain when latest can be blank <add> # Repology cannot identify "newest" versions for packages without a version scheme <ide> return "no latest version" if latest_version.blank? <ide> <ide> latest_version["version"]
2
Javascript
Javascript
remove unreachable code
ec7c27f4cb80c3f2600ec7e024276c2831273a47
<ide><path>lib/child_process.js <ide> var _deprecatedCustomFds = internalUtil.deprecate(function(options) { <ide> 'Use options.stdio instead.'); <ide> <ide> function _convertCustomFds(options) { <del> if (options && options.customFds && !options.stdio) { <add> if (options.customFds && !options.stdio) { <ide> _deprecatedCustomFds(options); <ide> } <ide> }
1
Javascript
Javascript
update fuzz tester to not use animation priority
9749a6ea6a7215507e2ff70627fe31ae31fbf0a2
<ide><path>src/renderers/shared/fiber/__tests__/ReactIncrementalTriangle-test.js <ide> describe('ReactIncrementalTriangle', () => { <ide> beforeEach(() => { <ide> jest.resetModules(); <ide> React = require('react'); <del> ReactNoop = require('ReactNoop'); <add> ReactNoop = require('ReactNoopEntry'); <ide> <ide> ReactFeatureFlags = require('ReactFeatureFlags'); <ide> ReactFeatureFlags.disableNewFiberFeatures = false; <ide> describe('ReactIncrementalTriangle', () => { <ide> if (this.props.depth !== 0) { <ide> throw new Error('Cannot activate non-leaf component'); <ide> } <del> ReactNoop.performAnimationWork(() => { <add> ReactNoop.syncUpdates(() => { <ide> this.setState({isActive: true}); <ide> }); <ide> } <ide> deactivate() { <ide> if (this.props.depth !== 0) { <ide> throw new Error('Cannot deactivate non-leaf component'); <ide> } <del> ReactNoop.performAnimationWork(() => { <add> ReactNoop.syncUpdates(() => { <ide> this.setState({isActive: false}); <ide> }); <ide> } <ide> describe('ReactIncrementalTriangle', () => { <ide> state = {counter: 0}; <ide> interrupt() { <ide> // Triggers a restart from the top. <del> ReactNoop.performAnimationWork(() => { <add> ReactNoop.syncUpdates(() => { <ide> this.forceUpdate(); <ide> }); <ide> } <ide> describe('ReactIncrementalTriangle', () => { <ide> let expectedCounterAtEnd = app.state.counter; <ide> <ide> let activeTriangle = null; <del> for (let i = 0; i < actions.length; i++) { <del> const action = actions[i]; <del> switch (action.type) { <del> case FLUSH: <del> ReactNoop.flushUnitsOfWork(action.unitsOfWork); <del> break; <del> case STEP: <del> app.setCounter(action.counter); <del> expectedCounterAtEnd = action.counter; <del> break; <del> case INTERRUPT: <del> app.interrupt(); <del> break; <del> case TOGGLE: <del> const targetTriangle = leafTriangles[action.childIndex]; <del> if (targetTriangle === undefined) { <del> throw new Error('Target index is out of bounds'); <del> } <del> if (targetTriangle === activeTriangle) { <del> activeTriangle = null; <del> targetTriangle.deactivate(); <del> } else { <del> if (activeTriangle !== null) { <del> activeTriangle.deactivate(); <add> ReactNoop.batchedUpdates(() => { <add> for (let i = 0; i < actions.length; i++) { <add> const action = actions[i]; <add> switch (action.type) { <add> case FLUSH: <add> ReactNoop.flushUnitsOfWork(action.unitsOfWork); <add> break; <add> case STEP: <add> app.setCounter(action.counter); <add> expectedCounterAtEnd = action.counter; <add> break; <add> case INTERRUPT: <add> app.interrupt(); <add> break; <add> case TOGGLE: <add> const targetTriangle = leafTriangles[action.childIndex]; <add> if (targetTriangle === undefined) { <add> throw new Error('Target index is out of bounds'); <ide> } <del> activeTriangle = targetTriangle; <del> targetTriangle.activate(); <del> } <del> ReactNoop.flushAnimationPri(); <del> break; <del> default: <del> break; <add> if (targetTriangle === activeTriangle) { <add> activeTriangle = null; <add> targetTriangle.deactivate(); <add> } else { <add> if (activeTriangle !== null) { <add> activeTriangle.deactivate(); <add> } <add> activeTriangle = targetTriangle; <add> targetTriangle.activate(); <add> } <add> break; <add> default: <add> break; <add> } <ide> } <del> } <add> }); <ide> // Flush remaining work <ide> ReactNoop.flush(); <ide> assertConsistentTree(activeTriangle, expectedCounterAtEnd);
1
PHP
PHP
implement viewvarstrait in other classes
41cd758d75f371036e746e23b9a300838eab70e6
<ide><path>lib/Cake/Console/Command/Task/TemplateTask.php <ide> use Cake\Console\Shell; <ide> use Cake\Core\App; <ide> use Cake\Utility\Folder; <add>use Cake\Utility\ViewVarsTrait; <ide> <ide> /** <ide> * Template Task can generate templated output Used in other Tasks. <ide> */ <ide> class TemplateTask extends Shell { <ide> <del>/** <del> * variables to add to template scope <del> * <del> * @var array <del> */ <del> public $templateVars = array(); <add> use ViewVarsTrait; <ide> <ide> /** <ide> * Paths to look for templates on. <ide> protected function _findThemes() { <ide> return $themes; <ide> } <ide> <del>/** <del> * Set variable values to the template scope <del> * <del> * @param string|array $one A string or an array of data. <del> * @param string|array $two Value in case $one is a string (which then works as the key). <del> * Unused if $one is an associative array, otherwise serves as the values to $one's keys. <del> * @return void <del> */ <del> public function set($one, $two = null) { <del> if (is_array($one)) { <del> if (is_array($two)) { <del> $data = array_combine($one, $two); <del> } else { <del> $data = $one; <del> } <del> } else { <del> $data = array($one => $two); <del> } <del> <del> if (!$data) { <del> return false; <del> } <del> $this->templateVars = $data + $this->templateVars; <del> } <del> <ide> /** <ide> * Runs the template <ide> * <ide> public function generate($directory, $filename, $vars = null) { <ide> $themePath = $this->getThemePath(); <ide> $templateFile = $this->_findTemplate($themePath, $directory, $filename); <ide> if ($templateFile) { <del> extract($this->templateVars); <add> extract($this->viewVars); <ide> ob_start(); <ide> ob_implicit_flush(0); <ide> include $templateFile; <ide><path>lib/Cake/View/View.php <ide> use Cake\Routing\Router; <ide> use Cake\Utility\Inflector; <ide> use Cake\Utility\ObjectCollection; <add>use Cake\Utility\ViewVarsTrait; <ide> <ide> /** <ide> * View, the V in the MVC triad. View interacts with Helpers and view variables passed <ide> class View extends Object { <ide> <ide> use RequestActionTrait; <add> use ViewVarsTrait; <ide> <ide> /** <ide> * Helpers collection <ide> public function uuid($object, $url) { <ide> return $hash; <ide> } <ide> <del>/** <del> * Allows a template or element to set a variable that will be available in <del> * a layout or other element. Analogous to Controller::set(). <del> * <del> * @param string|array $one A string or an array of data. <del> * @param string|array $two Value in case $one is a string (which then works as the key). <del> * Unused if $one is an associative array, otherwise serves as the values to $one's keys. <del> * @return void <del> */ <del> public function set($one, $two = null) { <del> $data = null; <del> if (is_array($one)) { <del> if (is_array($two)) { <del> $data = array_combine($one, $two); <del> } else { <del> $data = $one; <del> } <del> } else { <del> $data = array($one => $two); <del> } <del> if (!$data) { <del> return false; <del> } <del> $this->viewVars = $data + $this->viewVars; <del> } <del> <ide> /** <ide> * Magic accessor for helpers. <ide> *
2
Javascript
Javascript
add helpful assert for non-route controllers
c0cbf374940507c57af748fbc9015ef04ab70363
<ide><path>packages/ember-routing/lib/system/route.js <ide> Ember.Route = Ember.Object.extend({ <ide> <ide> if (!controller) { <ide> model = model || this.modelFor(name); <add> <add> Ember.assert("You are trying to look up a controller that you did not define, and for which Ember does not know the model.\n\nThis is not a controller for a route, so you must explicitly define the controller ("+this.router.namespace.toString() + "." + Ember.String.capitalize(Ember.String.camelize(name))+"Controller) or pass a model as the second parameter to `controllerFor`, so that Ember knows which type of controller to create for you.", model || this.container.lookup('route:' + name)); <add> <ide> controller = Ember.generateController(container, name, model); <ide> } <ide> <ide> Ember.Route = Ember.Object.extend({ <ide> @return {Object} the model object <ide> */ <ide> modelFor: function(name) { <del> return this.container.lookup('route:' + name).currentModel; <add> var route = this.container.lookup('route:' + name); <add> return route && route.currentModel; <ide> }, <ide> <ide> /** <ide><path>packages/ember/tests/routing/basic_test.js <ide> test("Parent route context change", function() { <ide> equal(editCount, 2, 'set up the edit route twice without failure'); <ide> deepEqual(editedPostIds, ['1', '2'], 'modelFor posts.post returns the right context'); <ide> }); <add> <add>test("Calling controllerFor for a non-route controller returns a controller", function() { <add> var controller; <add> <add> App.ApplicationRoute = Ember.Route.extend({ <add> setupController: function() { <add> controller = this.controllerFor('nonDefinedRoute', {}); <add> } <add> }); <add> <add> bootApplication(); <add> <add> ok(controller instanceof Ember.ObjectController, "controller was able to be retrieved"); <add>});
2
Ruby
Ruby
reject versions that aren't strings
f6536e9c8bae3c53a0b7c97b7bdddc0ce7beab83
<ide><path>Library/Homebrew/formula_support.rb <ide> def detect_version(val) <ide> when nil then Version.detect(url, specs) <ide> when String then Version.new(val) <ide> when Hash then Version.new_with_scheme(*val.shift) <add> else <add> raise TypeError, "version '#{val.inspect}' should be a string" <ide> end <ide> end <ide> <ide><path>Library/Homebrew/test/test_software_spec.rb <ide> def test_version_from_tag <ide> assert @spec.version.detected_from_url? <ide> end <ide> <add> def test_rejects_non_string_versions <add> assert_raises(TypeError) { @spec.version(1) } <add> assert_raises(TypeError) { @spec.version(2.0) } <add> assert_raises(TypeError) { @spec.version(Object.new) } <add> end <add> <ide> def test_mirrors <ide> assert_empty @spec.mirrors <ide> @spec.mirror('foo')
2
Javascript
Javascript
add tree-shaking to provideddependency
0aabe2a88446c2f8cae28ef50c93a525eb405df0
<ide><path>lib/dependencies/ProvidedDependency.js <ide> <ide> "use strict"; <ide> <add>const Dependency = require("../Dependency"); <ide> const InitFragment = require("../InitFragment"); <ide> const makeSerializable = require("../util/makeSerializable"); <ide> const ModuleDependency = require("./ModuleDependency"); <ide> <ide> /** @typedef {import("webpack-sources").ReplaceSource} ReplaceSource */ <ide> /** @typedef {import("../ChunkGraph")} ChunkGraph */ <del>/** @typedef {import("../Dependency")} Dependency */ <add>/** @typedef {import("../Dependency").ReferencedExport} ReferencedExport */ <ide> /** @typedef {import("../Dependency").UpdateHashContext} UpdateHashContext */ <ide> /** @typedef {import("../DependencyTemplate").DependencyTemplateContext} DependencyTemplateContext */ <ide> /** @typedef {import("../DependencyTemplates")} DependencyTemplates */ <ide> /** @typedef {import("../ModuleGraph")} ModuleGraph */ <ide> /** @typedef {import("../RuntimeTemplate")} RuntimeTemplate */ <ide> /** @typedef {import("../util/Hash")} Hash */ <add>/** @typedef {import("../util/runtime").RuntimeSpec} RuntimeSpec */ <add> <add>const idsSymbol = Symbol("ProvidedDependency.ids"); <ide> <ide> /** <ide> * @param {string[]|null} path the property path array <ide> const pathToString = path => <ide> : ""; <ide> <ide> class ProvidedDependency extends ModuleDependency { <del> constructor(request, identifier, path, range) { <add> /** <add> * @param {string} request request <add> * @param {string} identifier identifier <add> * @param {string[]} ids ids <add> * @param {[number, number]} range range <add> */ <add> constructor(request, identifier, ids, range) { <ide> super(request); <ide> this.identifier = identifier; <del> this.path = path; <add> this.ids = ids; <ide> this.range = range; <ide> this._hashUpdate = undefined; <ide> } <ide> class ProvidedDependency extends ModuleDependency { <ide> return "esm"; <ide> } <ide> <add> /** <add> * @param {ModuleGraph} moduleGraph the module graph <add> * @returns {string[]} the imported ids <add> */ <add> getIds(moduleGraph) { <add> const meta = moduleGraph.getMetaIfExisting(this); <add> if (meta === undefined) return this.ids; <add> const ids = meta[idsSymbol]; <add> return ids !== undefined ? ids : this.ids; <add> } <add> <add> /** <add> * @param {ModuleGraph} moduleGraph the module graph <add> * @param {string[]} ids the imported ids <add> * @returns {void} <add> */ <add> setIds(moduleGraph, ids) { <add> moduleGraph.getMeta(this)[idsSymbol] = ids; <add> } <add> <add> /** <add> * Returns list of exports referenced by this dependency <add> * @param {ModuleGraph} moduleGraph module graph <add> * @param {RuntimeSpec} runtime the runtime for which the module is analysed <add> * @returns {(string[] | ReferencedExport)[]} referenced exports <add> */ <add> getReferencedExports(moduleGraph, runtime) { <add> let ids = this.getIds(moduleGraph); <add> if (ids.length === 0) return Dependency.EXPORTS_OBJECT_REFERENCED; <add> return [ids]; <add> } <add> <ide> /** <ide> * Update the hash <ide> * @param {Hash} hash hash to be updated <ide> class ProvidedDependency extends ModuleDependency { <ide> updateHash(hash, context) { <ide> if (this._hashUpdate === undefined) { <ide> this._hashUpdate = <del> this.identifier + (this.path ? this.path.join(",") : "null"); <add> this.identifier + (this.ids ? this.ids.join(",") : "null"); <ide> } <ide> hash.update(this._hashUpdate); <ide> } <ide> <ide> serialize(context) { <ide> const { write } = context; <ide> write(this.identifier); <del> write(this.path); <add> write(this.ids); <ide> super.serialize(context); <ide> } <ide> <ide> deserialize(context) { <ide> const { read } = context; <ide> this.identifier = read(); <del> this.path = read(); <add> this.ids = read(); <ide> super.deserialize(context); <ide> } <ide> } <ide> class ProvidedDependencyTemplate extends ModuleDependency.Template { <ide> dependency, <ide> source, <ide> { <add> runtime, <ide> runtimeTemplate, <ide> moduleGraph, <ide> chunkGraph, <ide> class ProvidedDependencyTemplate extends ModuleDependency.Template { <ide> } <ide> ) { <ide> const dep = /** @type {ProvidedDependency} */ (dependency); <add> const connection = moduleGraph.getConnection(dep); <add> const exportsInfo = moduleGraph.getExportsInfo(connection.module); <add> const usedName = exportsInfo.getUsedName(dep.getIds(moduleGraph), runtime); <ide> initFragments.push( <ide> new InitFragment( <ide> `/* provided dependency */ var ${ <ide> class ProvidedDependencyTemplate extends ModuleDependency.Template { <ide> chunkGraph, <ide> request: dep.request, <ide> runtimeRequirements <del> })}${pathToString(dep.path)};\n`, <add> })}${pathToString(/** @type {string[]} */ (usedName))};\n`, <ide> InitFragment.STAGE_PROVIDES, <ide> 1, <ide> `provided ${dep.identifier}` <ide><path>test/configCases/plugins/provide-plugin/a.js <add>export * as c from "./b"; <add>export * as c2 from "./harmony2"; <ide><path>test/configCases/plugins/provide-plugin/b.js <add>export function square(x) { <add> return x * x; <add>} <add> <add>export function cube(x) { <add> return x * x * x; <add>} <ide><path>test/configCases/plugins/provide-plugin/harmony2.js <add>export const a = 1; <add>export const aUsed = __webpack_exports_info__.a.used; <ide><path>test/configCases/plugins/provide-plugin/index.js <ide> it("should provide a module for a property request", function() { <ide> expect(x).toBe("fff"); <ide> }); <ide> <add>it("should tree-shake unused exports", function() { <add> expect(aa1(2)).toBe(8); <add> expect(es2015_aUsed).toBe(false); <add>}); <add> <ide> it("should provide ES2015 modules", function() { <ide> expect((es2015.default)).toBe("ECMAScript 2015"); <ide> expect((es2015.alias)).toBe("ECMAScript Harmony"); <ide><path>test/configCases/plugins/provide-plugin/webpack.config.js <ide> module.exports = { <ide> aaa: "./aaa", <ide> "bbb.ccc": "./bbbccc", <ide> dddeeefff: ["./ddd", "eee", "3-f"], <add> aa1: ["./a", "c", "cube"], <add> es2015_aUsed: ["./harmony2", "aUsed"], <ide> "process.env.NODE_ENV": "./env", <ide> es2015: "./harmony", <ide> es2015_name: ["./harmony", "default"],
6
Text
Text
put content in data structures stub
fc4ae129b4bb7a6b09cfb9b15a57b407f9d52143
<ide><path>packages/learn/src/introductions/coding-interview-prep/data-structures/index.md <ide> superBlock: Coding Interview Prep <ide> --- <ide> ## Introduction to the Coding Interview Data Structure Questions <ide> <del>This introduction is a stub <del> <del>Help us make it real on [GitHub](https://github.com/freeCodeCamp/learn/tree/master/src/introductions). <ide>\ No newline at end of file <add>These excercises are meant to help you deal with large or complex data by using many different data types other than your standard objects or arrays.
1
PHP
PHP
fix missing prefix when reading table schema
9c4a9bbd06c2b88f9ab95678de455fc0a443ee41
<ide><path>lib/Cake/Model/CakeSchema.php <ide> public function read($options = array()) { <ide> $systemTables = array( <ide> 'aros', 'acos', 'aros_acos', Configure::read('Session.table'), 'i18n' <ide> ); <add> <add> $fulltable = $db->fullTableName($Object, false); <add> <ide> if (in_array($table, $systemTables)) { <ide> $tables[$Object->table] = $this->_columns($Object); <ide> $tables[$Object->table]['indexes'] = $db->index($Object); <del> $tables[$Object->table]['tableParameters'] = $db->readTableParameters($table); <add> $tables[$Object->table]['tableParameters'] = $db->readTableParameters($fulltable); <ide> } elseif ($models === false) { <ide> $tables[$table] = $this->_columns($Object); <ide> $tables[$table]['indexes'] = $db->index($Object); <del> $tables[$table]['tableParameters'] = $db->readTableParameters($table); <add> $tables[$table]['tableParameters'] = $db->readTableParameters($fulltable); <ide> } else { <ide> $tables['missing'][$table] = $this->_columns($Object); <ide> $tables['missing'][$table]['indexes'] = $db->index($Object); <del> $tables['missing'][$table]['tableParameters'] = $db->readTableParameters($table); <add> $tables['missing'][$table]['tableParameters'] = $db->readTableParameters($fulltable); <ide> } <ide> } <ide> }
1
PHP
PHP
fix request usage in auth tests
cff3aeb81edd59bf84fecfd2393917b9d1524b6f
<ide><path>tests/TestCase/Auth/BasicAuthenticateTest.php <ide> public function testAuthenticateUsernameZero() <ide> $User = TableRegistry::get('Users'); <ide> $User->updateAll(['username' => '0'], ['username' => 'mariano']); <ide> <del> $request = new ServerRequest('posts/index'); <del> $request->data = ['User' => [ <del> 'user' => '0', <del> 'password' => 'password' <del> ]]; <add> $request = new ServerRequest([ <add> 'url' => 'posts/index', <add> 'data' => [ <add> 'User' => [ <add> 'user' => '0', <add> 'password' => 'password' <add> ] <add> ] <add> ]); <ide> $_SERVER['PHP_AUTH_USER'] = '0'; <ide> $_SERVER['PHP_AUTH_PW'] = 'password'; <ide> <ide><path>tests/TestCase/Auth/FormAuthenticateTest.php <ide> public function testConstructor() <ide> */ <ide> public function testAuthenticateNoData() <ide> { <del> $request = new ServerRequest('posts/index'); <del> $request->data = []; <add> $request = new ServerRequest([ <add> 'url' => 'posts/index', <add> 'post' => [], <add> ]); <ide> $this->assertFalse($this->auth->authenticate($request, $this->response)); <ide> } <ide> <ide> public function testAuthenticateNoData() <ide> */ <ide> public function testAuthenticateNoUsername() <ide> { <del> $request = new ServerRequest('posts/index'); <del> $request->data = ['password' => 'foobar']; <add> $request = new ServerRequest([ <add> 'url' => 'posts/index', <add> 'post' => ['password' => 'foobar'], <add> ]); <ide> $this->assertFalse($this->auth->authenticate($request, $this->response)); <ide> } <ide> <ide> public function testAuthenticateNoUsername() <ide> */ <ide> public function testAuthenticateNoPassword() <ide> { <del> $request = new ServerRequest('posts/index'); <del> $request->data = ['username' => 'mariano']; <add> $request = new ServerRequest([ <add> 'url' => 'posts/index', <add> 'post' => ['username' => 'mariano'], <add> ]); <ide> $this->assertFalse($this->auth->authenticate($request, $this->response)); <ide> } <ide> <ide> public function testAuthenticateNoPassword() <ide> public function testAuthenticatePasswordIsFalse() <ide> { <ide> $request = new ServerRequest('posts/index', false); <del> $request->data = [ <del> 'username' => 'mariano', <del> 'password' => null <del> ]; <add> $request = new ServerRequest([ <add> 'url' => 'posts/index', <add> 'post' => [ <add> 'username' => 'mariano', <add> 'password' => null <add> ], <add> ]); <ide> $this->assertFalse($this->auth->authenticate($request, $this->response)); <ide> } <ide> <ide> public function testAuthenticatePasswordIsFalse() <ide> */ <ide> public function testAuthenticatePasswordIsEmptyString() <ide> { <del> $request = new ServerRequest('posts/index', false); <del> $request->data = [ <del> 'username' => 'mariano', <del> 'password' => '' <del> ]; <add> $request = new ServerRequest([ <add> 'url' => 'posts/index', <add> 'post' => [ <add> 'username' => 'mariano', <add> 'password' => '' <add> ], <add> ]); <ide> <ide> $this->auth = $this->getMockBuilder(FormAuthenticate::class) <ide> ->setMethods(['_checkFields']) <ide> public function testAuthenticatePasswordIsEmptyString() <ide> */ <ide> public function testAuthenticateFieldsAreNotString() <ide> { <del> $request = new ServerRequest('posts/index', false); <del> $request->data = [ <del> 'username' => ['mariano', 'phpnut'], <del> 'password' => 'my password' <del> ]; <add> $request = new ServerRequest([ <add> 'url' => 'posts/index', <add> 'post' => [ <add> 'username' => ['mariano', 'phpnut'], <add> 'password' => 'my password' <add> ], <add> ]); <ide> $this->assertFalse($this->auth->authenticate($request, $this->response)); <ide> <del> $request->data = [ <del> 'username' => 'mariano', <add> $request = new ServerRequest([ <add> 'url' => 'posts/index', <add> 'post' => [ <add> 'username' => 'mariano', <ide> 'password' => ['password1', 'password2'] <del> ]; <add> ], <add> ]); <ide> $this->assertFalse($this->auth->authenticate($request, $this->response)); <ide> } <ide> <ide> public function testAuthenticateFieldsAreNotString() <ide> */ <ide> public function testAuthenticateInjection() <ide> { <del> $request = new ServerRequest('posts/index'); <del> $request->data = [ <del> 'username' => '> 1', <del> 'password' => "' OR 1 = 1" <del> ]; <add> $request = new ServerRequest([ <add> 'url' => 'posts/index', <add> 'post' => [ <add> 'username' => '> 1', <add> 'password' => "' OR 1 = 1" <add> ], <add> ]); <ide> $this->assertFalse($this->auth->authenticate($request, $this->response)); <ide> } <ide> <ide> public function testAuthenticateInjection() <ide> */ <ide> public function testAuthenticateSuccess() <ide> { <del> $request = new ServerRequest('posts/index'); <del> $request->data = [ <del> 'username' => 'mariano', <del> 'password' => 'password' <del> ]; <add> $request = new ServerRequest([ <add> 'url' => 'posts/index', <add> 'post' => [ <add> 'username' => 'mariano', <add> 'password' => 'password' <add> ], <add> ]); <ide> $result = $this->auth->authenticate($request, $this->response); <ide> $expected = [ <ide> 'id' => 1, <ide> public function testAuthenticateIncludesVirtualFields() <ide> $users = TableRegistry::get('Users'); <ide> $users->setEntityClass('TestApp\Model\Entity\VirtualUser'); <ide> <del> $request = new ServerRequest('posts/index'); <del> $request->data = [ <del> 'username' => 'mariano', <del> 'password' => 'password' <del> ]; <add> $request = new ServerRequest([ <add> 'url' => 'posts/index', <add> 'post' => [ <add> 'username' => 'mariano', <add> 'password' => 'password' <add> ], <add> ]); <ide> $result = $this->auth->authenticate($request, $this->response); <ide> $expected = [ <ide> 'id' => 1, <ide> public function testPluginModel() <ide> <ide> $this->auth->setConfig('userModel', 'TestPlugin.AuthUsers'); <ide> <del> $request = new ServerRequest('posts/index'); <del> $request->data = [ <del> 'username' => 'gwoo', <del> 'password' => 'cake' <del> ]; <add> $request = new ServerRequest([ <add> 'url' => 'posts/index', <add> 'post' => [ <add> 'username' => 'gwoo', <add> 'password' => 'cake' <add> ], <add> ]); <ide> <ide> $result = $this->auth->authenticate($request, $this->response); <ide> $expected = [ <ide> public function testPluginModel() <ide> */ <ide> public function testFinder() <ide> { <del> $request = new ServerRequest('posts/index'); <del> $request->data = [ <del> 'username' => 'mariano', <del> 'password' => 'password' <del> ]; <add> $request = new ServerRequest([ <add> 'url' => 'posts/index', <add> 'post' => [ <add> 'username' => 'mariano', <add> 'password' => 'password' <add> ], <add> ]); <ide> <ide> $this->auth->setConfig([ <ide> 'userModel' => 'AuthUsers', <ide> public function testFinder() <ide> */ <ide> public function testFinderOptions() <ide> { <del> $request = new ServerRequest('posts/index'); <del> $request->data = [ <del> 'username' => 'mariano', <del> 'password' => 'password' <del> ]; <add> $request = new ServerRequest([ <add> 'url' => 'posts/index', <add> 'post' => [ <add> 'username' => 'mariano', <add> 'password' => 'password' <add> ], <add> ]); <ide> <ide> $this->auth->setConfig([ <ide> 'userModel' => 'AuthUsers', <ide> public function testPasswordHasherSettings() <ide> ['username' => 'mariano'] <ide> ); <ide> <del> $request = new ServerRequest('posts/index'); <del> $request->data = [ <del> 'username' => 'mariano', <del> 'password' => 'mypass' <del> ]; <add> $request = new ServerRequest([ <add> 'url' => 'posts/index', <add> 'post' => [ <add> 'username' => 'mariano', <add> 'password' => 'mypass' <add> ], <add> ]); <ide> <ide> $result = $this->auth->authenticate($request, $this->response); <ide> $expected = [ <ide> public function testPasswordHasherSettings() <ide> */ <ide> public function testAuthenticateNoRehash() <ide> { <del> $request = new ServerRequest('posts/index'); <del> $request->data = [ <del> 'username' => 'mariano', <del> 'password' => 'password' <del> ]; <add> $request = new ServerRequest([ <add> 'url' => 'posts/index', <add> 'post' => [ <add> 'username' => 'mariano', <add> 'password' => 'password' <add> ], <add> ]); <ide> $result = $this->auth->authenticate($request, $this->response); <ide> $this->assertNotEmpty($result); <ide> $this->assertFalse($this->auth->needsPasswordRehash()); <ide> public function testAuthenticateRehash() <ide> $password = $this->auth->passwordHasher()->hash('password'); <ide> TableRegistry::get('Users')->updateAll(['password' => $password], []); <ide> <del> $request = new ServerRequest('posts/index'); <del> $request->data = [ <del> 'username' => 'mariano', <del> 'password' => 'password' <del> ]; <add> $request = new ServerRequest([ <add> 'url' => 'posts/index', <add> 'post' => [ <add> 'username' => 'mariano', <add> 'password' => 'password' <add> ], <add> ]); <ide> $result = $this->auth->authenticate($request, $this->response); <ide> $this->assertNotEmpty($result); <ide> $this->assertTrue($this->auth->needsPasswordRehash());
2
Python
Python
fix #521. (browseable api exception on delete)
598ae3286ac6343a59e6d80fc93428539c5f836e
<ide><path>rest_framework/mixins.py <ide> class DestroyModelMixin(object): <ide> Should be mixed in with `SingleObjectBaseView`. <ide> """ <ide> def destroy(self, request, *args, **kwargs): <del> self.object = self.get_object() <del> self.object.delete() <add> obj = self.get_object() <add> obj.delete() <ide> return Response(status=status.HTTP_204_NO_CONTENT)
1
Go
Go
return image id in api when using buildkit
ca8022ec63a9d0e2f9660e2a3455d821abf8f517
<ide><path>api/server/backend/build/backend.go <ide> func (b *Backend) Build(ctx context.Context, config backend.BuildConfig) (string <ide> return "", err <ide> } <ide> if config.ProgressWriter.AuxFormatter != nil { <del> if err = config.ProgressWriter.AuxFormatter.Emit(types.BuildResult{ID: imageID}); err != nil { <add> if err = config.ProgressWriter.AuxFormatter.Emit("moby.image.id", types.BuildResult{ID: imageID}); err != nil { <ide> return "", err <ide> } <ide> } <ide><path>api/server/router/build/build_routes.go <ide> func (br *buildRouter) postBuild(ctx context.Context, w http.ResponseWriter, r * <ide> return errdefs.InvalidParameter(errors.New("squash is only supported with experimental mode")) <ide> } <ide> <add> if buildOptions.Version == types.BuilderBuildKit && !br.daemon.HasExperimental() { <add> return errdefs.InvalidParameter(errors.New("buildkit is only supported with experimental mode")) <add> } <add> <ide> out := io.Writer(output) <ide> if buildOptions.SuppressOutput { <ide> out = notVerboseBuffer <ide> func (br *buildRouter) postBuild(ctx context.Context, w http.ResponseWriter, r * <ide> return progress.NewProgressReader(in, progressOutput, r.ContentLength, "Downloading context", buildOptions.RemoteContext) <ide> } <ide> <del> if buildOptions.Version == types.BuilderBuildKit && !br.daemon.HasExperimental() { <del> return errdefs.InvalidParameter(errors.New("buildkit is only supported with experimental mode")) <del> } <del> <ide> wantAux := versions.GreaterThanOrEqualTo(version, "1.30") <ide> <ide> imgID, err := br.backend.Build(ctx, backend.BuildConfig{ <ide><path>builder/builder-next/builder.go <ide> package buildkit <ide> <ide> import ( <ide> "context" <del> "encoding/json" <ide> "io" <ide> "strings" <ide> "sync" <ide> import ( <ide> "github.com/docker/docker/api/types/backend" <ide> "github.com/docker/docker/builder" <ide> "github.com/docker/docker/daemon/images" <del> "github.com/docker/docker/pkg/jsonmessage" <add> "github.com/docker/docker/pkg/streamformatter" <ide> controlapi "github.com/moby/buildkit/api/services/control" <ide> "github.com/moby/buildkit/control" <ide> "github.com/moby/buildkit/identity" <ide> func (b *Builder) Build(ctx context.Context, opt backend.BuildConfig) (*builder. <ide> Session: opt.Options.SessionID, <ide> } <ide> <add> aux := streamformatter.AuxFormatter{opt.ProgressWriter.Output} <add> <ide> eg, ctx := errgroup.WithContext(ctx) <ide> <ide> eg.Go(func() error { <ide> func (b *Builder) Build(ctx context.Context, opt backend.BuildConfig) (*builder. <ide> return errors.Errorf("missing image id") <ide> } <ide> out.ImageID = id <del> return nil <add> return aux.Emit("moby.image.id", types.BuildResult{ID: id}) <ide> }) <ide> <ide> ch := make(chan *controlapi.StatusResponse) <ide> func (b *Builder) Build(ctx context.Context, opt backend.BuildConfig) (*builder. <ide> if err != nil { <ide> return err <ide> } <del> <del> auxJSONBytes, err := json.Marshal(dt) <del> if err != nil { <add> if err := aux.Emit("moby.buildkit.trace", dt); err != nil { <ide> return err <ide> } <del> auxJSON := new(json.RawMessage) <del> *auxJSON = auxJSONBytes <del> msgJSON, err := json.Marshal(&jsonmessage.JSONMessage{ID: "moby.buildkit.trace", Aux: auxJSON}) <del> if err != nil { <del> return err <del> } <del> msgJSON = append(msgJSON, []byte("\r\n")...) <del> n, err := opt.ProgressWriter.Output.Write(msgJSON) <del> if err != nil { <del> return err <del> } <del> if n != len(msgJSON) { <del> return io.ErrShortWrite <del> } <ide> } <ide> return nil <ide> }) <ide><path>builder/dockerfile/builder.go <ide> func emitImageID(aux *streamformatter.AuxFormatter, state *dispatchState) error <ide> if aux == nil || state.imageID == "" { <ide> return nil <ide> } <del> return aux.Emit(types.BuildResult{ID: state.imageID}) <add> return aux.Emit("", types.BuildResult{ID: state.imageID}) <ide> } <ide> <ide> func processMetaArg(meta instructions.ArgCommand, shlex *shell.Lex, args *BuildArgs) error { <ide><path>pkg/streamformatter/streamformatter.go <ide> type AuxFormatter struct { <ide> } <ide> <ide> // Emit emits the given interface as an aux progress message <del>func (sf *AuxFormatter) Emit(aux interface{}) error { <add>func (sf *AuxFormatter) Emit(id string, aux interface{}) error { <ide> auxJSONBytes, err := json.Marshal(aux) <ide> if err != nil { <ide> return err <ide> } <ide> auxJSON := new(json.RawMessage) <ide> *auxJSON = auxJSONBytes <del> msgJSON, err := json.Marshal(&jsonmessage.JSONMessage{Aux: auxJSON}) <add> msgJSON, err := json.Marshal(&jsonmessage.JSONMessage{ID: id, Aux: auxJSON}) <ide> if err != nil { <ide> return err <ide> } <ide><path>pkg/streamformatter/streamformatter_test.go <ide> func TestAuxFormatterEmit(t *testing.T) { <ide> sampleAux := &struct { <ide> Data string <ide> }{"Additional data"} <del> err := aux.Emit(sampleAux) <add> err := aux.Emit("", sampleAux) <ide> assert.NilError(t, err) <ide> assert.Check(t, is.Equal(`{"aux":{"Data":"Additional data"}}`+streamNewline, b.String())) <ide> }
6
Go
Go
fix various race conditions in loggerutils
3148a46657266738ef28cfa07b78088fea4eda07
<ide><path>daemon/logger/loggerutils/logfile_test.go <ide> import ( <ide> "os" <ide> "path/filepath" <ide> "strings" <add> "sync/atomic" <ide> "testing" <ide> "time" <ide> <ide> func TestTailFiles(t *testing.T) { <ide> <ide> files := []SizeReaderAt{s1, s2, s3} <ide> watcher := logger.NewLogWatcher() <add> defer watcher.ConsumerGone() <ide> <ide> tailReader := func(ctx context.Context, r SizeReaderAt, lines int) (io.Reader, int, error) { <ide> return tailfile.NewTailReader(ctx, r, lines) <ide> func (d *dummyWrapper) Decode() (*logger.Message, error) { <ide> <ide> func TestFollowLogsProducerGone(t *testing.T) { <ide> lw := logger.NewLogWatcher() <add> defer lw.ConsumerGone() <ide> <ide> f, err := ioutil.TempFile("", t.Name()) <ide> assert.NilError(t, err) <ide> defer os.Remove(f.Name()) <ide> <del> var sent, received, closed int <add> var sent, received, closed int32 <ide> dec := &dummyWrapper{fn: func() error { <del> switch closed { <add> switch atomic.LoadInt32(&closed) { <ide> case 0: <del> sent++ <add> atomic.AddInt32(&sent, 1) <ide> return nil <ide> case 1: <del> closed++ <add> atomic.AddInt32(&closed, 1) <ide> t.Logf("logDecode() closed after sending %d messages\n", sent) <ide> return io.EOF <ide> default: <ide> func TestFollowLogsProducerGone(t *testing.T) { <ide> } <ide> <ide> // "stop" the "container" <del> closed = 1 <add> atomic.StoreInt32(&closed, 1) <ide> lw.ProducerGone() <ide> <ide> // should receive all the messages sent <ide> func TestFollowLogsProducerGone(t *testing.T) { <ide> select { <ide> case <-lw.Msg: <ide> received++ <del> if received == sent { <add> if received == atomic.LoadInt32(&sent) { <ide> return <ide> } <ide> case err := <-lw.Err: <ide> func TestFollowLogsProducerGone(t *testing.T) { <ide> t.Fatalf("timeout waiting for log messages to be read (sent: %d, received: %d", sent, received) <ide> } <ide> <del> t.Logf("messages sent: %d, received: %d", sent, received) <add> t.Logf("messages sent: %d, received: %d", atomic.LoadInt32(&sent), received) <ide> <ide> // followLogs() should be done by now <ide> select { <ide> func checkFileExists(name string) poll.Check { <ide> case os.IsNotExist(err): <ide> return poll.Continue("waiting for %s to exist", name) <ide> default: <del> t.Logf("%s", dirStringer{filepath.Dir(name)}) <add> t.Logf("waiting for %s: %v: %s", name, err, dirStringer{filepath.Dir(name)}) <ide> return poll.Error(err) <ide> } <ide> }
1
Javascript
Javascript
replace occurances of gotostate with transitionto
03c94f8278d8cbdb6621051f2ac2e9f61e2eb36f
<ide><path>packages/ember-states/lib/state_manager.js <ide> require('ember-states/state'); <ide> <ide> <ide> Each state property may itself contain properties that are instances of Ember.State. <del> The StateManager can transition to specific sub-states in a series of goToState method calls or <add> The StateManager can transition to specific sub-states in a series of transitionTo method calls or <ide> via a single transitionTo with the full path to the specific state. The StateManager will also <ide> keep track of the full path to its currentState <ide> <ide><path>packages/ember-states/tests/routable_test.js <ide> test("it should have its updateRoute method called when it is entered", function <ide> location: locationStub, <ide> root: Ember.State.create({ <ide> ready: function(manager) { <del> manager.goToState('initial'); <add> manager.transitionTo('initial'); <ide> }, <ide> <ide> initial: state <ide> test("when you call `route` on the Router, it calls it on the current state", fu <ide> location: locationStub, <ide> root: Ember.State.create({ <ide> ready: function(manager) { <del> manager.goToState('initial'); <add> manager.transitionTo('initial'); <ide> }, <ide> <ide> initial: state <ide><path>packages/ember-states/tests/state_manager_test.js <ide> test("it discovers states that are properties of the state manager", function() <ide> test("it reports its current state", function() { <ide> ok(get(stateManager, 'currentState') === null, "currentState defaults to null if no state is specified"); <ide> <del> stateManager.goToState('loadingState'); <del> ok(get(stateManager, 'currentState') === loadingState, "currentState changes after goToState() is called"); <add> stateManager.transitionTo('loadingState'); <add> ok(get(stateManager, 'currentState') === loadingState, "currentState changes after transitionTo() is called"); <ide> <del> stateManager.goToState('loadedState'); <add> stateManager.transitionTo('loadedState'); <ide> ok(get(stateManager, 'currentState') === loadedState, "currentState can change to a sibling state"); <ide> }); <ide> <ide> test("it sends enter and exit events during state transitions", function() { <del> stateManager.goToState('loadingState'); <add> stateManager.transitionTo('loadingState'); <ide> <ide> equal(loadingState.entered, 1, "state should receive one enter event"); <ide> equal(loadingState.exited, 0, "state should not have received an exit event"); <ide> test("it sends enter and exit events during state transitions", function() { <ide> loadingState.reset(); <ide> loadedState.reset(); <ide> <del> stateManager.goToState('loadedState'); <add> stateManager.transitionTo('loadedState'); <ide> equal(loadingState.entered, 0, "state should not receive an enter event"); <ide> equal(loadingState.exited, 1, "state should receive one exit event"); <ide> equal(loadedState.entered, 1, "sibling state should receive one enter event"); <ide> test("it sends enter and exit events during state transitions", function() { <ide> loadingState.reset(); <ide> loadedState.reset(); <ide> <del> stateManager.goToState('loadingState'); <add> stateManager.transitionTo('loadingState'); <ide> <ide> equal(loadingState.entered, 1, "state should receive one enter event"); <ide> equal(loadingState.exited, 0, "state should not have received an exit event"); <ide> test("a transition can be asynchronous", function() { <ide> var stateManager = Ember.StateManager.create({ <ide> start: Ember.State.create({ <ide> finish: function(manager) { <del> manager.goToState('finished'); <add> manager.transitionTo('finished'); <ide> }, <ide> <ide> exit: function(manager, transition) { <ide> test("a transition can be asynchronous", function() { <ide> test("it accepts absolute paths when changing states", function() { <ide> var emptyState = loadedState.empty; <ide> <del> stateManager.goToState('loadingState'); <add> stateManager.transitionTo('loadingState'); <ide> <del> stateManager.goToState('loadedState.empty'); <add> stateManager.transitionTo('loadedState.empty'); <ide> <ide> equal(emptyState.entered, 1, "sends enter event to substate"); <ide> equal(emptyState.exited, 0, "does not send exit event to substate"); <ide> ok(stateManager.get('currentState') === emptyState, "updates currentState property to state at absolute path"); <ide> }); <ide> <del>test("it does not enter an infinite loop in goToState", function() { <add>test("it does not enter an infinite loop in transitionTo", function() { <ide> var emptyState = loadedState.empty; <ide> <del> stateManager.goToState('loadedState.empty'); <add> stateManager.transitionTo('loadedState.empty'); <ide> <del> stateManager.goToState(''); <del> ok(stateManager.get('currentState') === emptyState, "goToState does nothing when given empty name"); <add> stateManager.transitionTo(''); <add> ok(stateManager.get('currentState') === emptyState, "transitionTo does nothing when given empty name"); <ide> <del> stateManager.goToState('nonexistentState'); <del> ok(stateManager.get('currentState') === emptyState, "goToState does not infinite loop when given nonexistent State"); <add> stateManager.transitionTo('nonexistentState'); <add> ok(stateManager.get('currentState') === emptyState, "transitionTo does not infinite loop when given nonexistent State"); <ide> }); <ide> <ide> test("it automatically transitions to a default state", function() { <ide> test("it automatically transitions to a default state that is an instance", func <ide> } <ide> }); <ide> <del> stateManager.goToState('foo'); <add> stateManager.transitionTo('foo'); <ide> ok(get(stateManager, 'currentState').isStart, "automatically transitions to start state"); <ide> }); <ide> <ide> test("it sends exit events to nested states when changing to a top-level state", <ide> }) <ide> }); <ide> <del> stateManager.goToState('login'); <add> stateManager.transitionTo('login'); <ide> equal(stateManager.login.entered, 1, "precond - it enters the login state"); <ide> equal(stateManager.login.start.entered, 1, "automatically enters the start state"); <ide> ok(stateManager.get('currentState') === stateManager.login.start, "automatically sets currentState to start state"); <ide> <ide> stateManager.login.reset(); <ide> stateManager.login.start.reset(); <ide> <del> stateManager.goToState('redeem'); <add> stateManager.transitionTo('redeem'); <ide> <ide> equal(stateManager.login.exited, 1, "login state is exited once"); <ide> equal(stateManager.login.start.exited, 1, "start state is exited once"); <ide> test("it sends exit events in the correct order when changing to a top-level sta <ide> }) <ide> }); <ide> <del> stateManager.goToState('start.outer.inner'); <del> stateManager.goToState('start'); <add> stateManager.transitionTo('start.outer.inner'); <add> stateManager.transitionTo('start'); <ide> equal(exitOrder.length, 2, "precond - it calls both exits"); <ide> equal(exitOrder[0], 'exitedInner', "inner exit is called first"); <ide> equal(exitOrder[1], 'exitedOuter', "outer exit is called second"); <ide> test("it sends exit events in the correct order when changing to a state multipl <ide> }) <ide> }); <ide> <del> stateManager.goToState('start.outer.inner'); <del> stateManager.goToState('start'); <del> stateManager.goToState('start.outer.inner'); <add> stateManager.transitionTo('start.outer.inner'); <add> stateManager.transitionTo('start'); <add> stateManager.transitionTo('start.outer.inner'); <ide> exitOrder = []; <del> stateManager.goToState('start'); <add> stateManager.transitionTo('start'); <ide> equal(exitOrder.length, 2, "precond - it calls both exits"); <ide> equal(exitOrder[0], 'exitedInner', "inner exit is called first"); <ide> equal(exitOrder[1], 'exitedOuter', "outer exit is called second"); <ide> module("Ember.StateManager - Event Dispatching", { <ide> }) <ide> }); <ide> <del> stateManager.goToState('loading'); <add> stateManager.transitionTo('loading'); <ide> } <ide> }); <ide> <ide> test("it dispatches events to the current state", function() { <ide> }); <ide> <ide> test("it dispatches events to a parent state if the child state does not respond to it", function() { <del> stateManager.goToState('loaded.empty'); <add> stateManager.transitionTo('loaded.empty'); <ide> stateManager.send('anEvent'); <ide> <ide> equal(loadedEventCalled, 1, "parent state receives event"); <ide> }); <ide> <ide> test("it does not dispatch events to parents if the child responds to it", function() { <del> stateManager.goToState('loaded.empty'); <add> stateManager.transitionTo('loaded.empty'); <ide> stateManager.send('eventInChild'); <ide> <ide> equal(eventInChildCalled, 1, "does not dispatch event to parent"); <ide> module("Ember.Statemanager - Pivot states", { <ide> } <ide> }); <ide> <del>test("goToState triggers all enter states", function() { <del> stateManager.goToState('grandparent.parent.child'); <add>test("transitionTo triggers all enter states", function() { <add> stateManager.transitionTo('grandparent.parent.child'); <ide> equal(stateManager.grandparent.entered, 1, "the top level should be entered"); <ide> equal(stateManager.grandparent.parent.entered, 1, "intermediate states should be entered"); <ide> equal(stateManager.grandparent.parent.child.entered, 1, "the final state should be entered"); <ide> <del> stateManager.goToState('grandparent.parent.sibling'); <add> stateManager.transitionTo('grandparent.parent.sibling'); <ide> equal(stateManager.grandparent.entered, 1, "the top level should not be re-entered"); <ide> equal(stateManager.grandparent.parent.entered, 1, "intermediate states should not be re-entered"); <ide> equal(stateManager.grandparent.parent.child.entered, 1, "the final state should not be re-entered"); <ide> test("goToState triggers all enter states", function() { <ide> equal(stateManager.grandparent.parent.exited, 0, "intermediate states should not have exited"); <ide> }); <ide> <del>test("goToState with current state does not trigger enter or exit", function() { <del> stateManager.goToState('grandparent.parent.child'); <del> stateManager.goToState('grandparent.parent.child'); <add>test("transitionTo with current state does not trigger enter or exit", function() { <add> stateManager.transitionTo('grandparent.parent.child'); <add> stateManager.transitionTo('grandparent.parent.child'); <ide> equal(stateManager.grandparent.entered, 1, "the top level should only be entered once"); <ide> equal(stateManager.grandparent.parent.entered, 1, "intermediate states should only be entered once"); <ide> equal(stateManager.grandparent.parent.child.entered, 1, "the final state should only be entered once"); <ide> test("if a context is passed to a transition, the state's setup event is trigger <ide> stateManager = Ember.StateManager.create({ <ide> start: Ember.State.create({ <ide> goNext: function(manager, context) { <del> manager.goToState('next', context); <add> manager.transitionTo('next', context); <ide> } <ide> }), <ide> <ide> test("if a context is passed to a transition and the path is to the current stat <ide> start: Ember.State.create({ <ide> goNext: function(manager, context) { <ide> counter++; <del> manager.goToState('foo.next', counter); <add> manager.transitionTo('foo.next', counter); <ide> } <ide> }), <ide> <ide> foo: Ember.State.create({ <ide> next: Ember.State.create({ <ide> goNext: function(manager, context) { <ide> counter++; <del> manager.goToState('next', counter); <add> manager.transitionTo('next', counter); <ide> }, <ide> <ide> setup: function(manager, context) { <ide> test("multiple contexts can be provided in a single transitionTo", function() { <ide> stateManager = Ember.StateManager.create({ <ide> start: Ember.State.create({ <ide> goNuts: function(manager, context) { <del> manager.goToState('foo.next', context); <add> manager.transitionTo('foo.next', context); <ide> } <ide> }), <ide> <ide><path>packages/ember-states/tests/state_test.js <ide> test("states set up proper names on their children", function() { <ide> } <ide> }); <ide> <del> manager.goToState('first'); <add> manager.transitionTo('first'); <ide> equal(getPath(manager, 'currentState.path'), 'first'); <ide> <del> manager.goToState('first.insideFirst'); <add> manager.transitionTo('first.insideFirst'); <ide> equal(getPath(manager, 'currentState.path'), 'first.insideFirst'); <ide> }); <ide> <ide> test("states with child instances set up proper names on their children", functi <ide> } <ide> }); <ide> <del> manager.goToState('first'); <add> manager.transitionTo('first'); <ide> equal(getPath(manager, 'currentState.path'), 'first'); <ide> <del> manager.goToState('first.insideFirst'); <add> manager.transitionTo('first.insideFirst'); <ide> equal(getPath(manager, 'currentState.path'), 'first.insideFirst'); <ide> }); <ide> <ide><path>packages/ember-viewstates/lib/view_state.js <ide> var get = Ember.get, set = Ember.set; <ide> }) <ide> }) <ide> <del> viewStates.goToState('showingPeople') <add> viewStates.transitionTo('showingPeople') <ide> <ide> The above code will change the rendered HTML from <ide> <ide> var get = Ember.get, set = Ember.set; <ide> </div> <ide> </body> <ide> <del> Changing the current state via `goToState` from `showingPeople` to <add> Changing the current state via `transitionTo` from `showingPeople` to <ide> `showingPhotos` will remove the `showingPeople` view and add the `showingPhotos` view: <ide> <del> viewStates.goToState('showingPhotos') <add> viewStates.transitionTo('showingPhotos') <ide> <ide> will change the rendered HTML to <ide> <ide> var get = Ember.get, set = Ember.set; <ide> }) <ide> <ide> <del> viewStates.goToState('showingPeople.withEditingPanel') <add> viewStates.transitionTo('showingPeople.withEditingPanel') <ide> <ide> <ide> Will result in the following rendered HTML: <ide><path>packages/ember-viewstates/tests/view_state_test.js <ide> test("it appends and removes a view when it is entered and exited", function() { <ide> equal(Ember.$('#test-view').length, 1, "found view with custom id in DOM"); <ide> <ide> Ember.run(function() { <del> stateManager.goToState('other'); <add> stateManager.transitionTo('other'); <ide> }); <ide> <ide> equal(Ember.$('#test-view').length, 0, "can't find view with custom id in DOM"); <ide> test("it appends and removes a view to the element specified in its state manage <ide> equal(Ember.$("#test-view").parent().attr('id'), "my-container", "appends view to the correct element"); <ide> <ide> Ember.run(function() { <del> stateManager.goToState('other'); <add> stateManager.transitionTo('other'); <ide> }); <ide> <ide> equal(Ember.$('#test-view').length, 0, "can't find view with custom id in DOM"); <ide> test("it appends and removes a view to the view specified in the state manager's <ide> equal(get(rootView, 'childViews').objectAt(0), view, "the view added is the view state's view"); <ide> <ide> Ember.run(function() { <del> stateManager.goToState('other'); <add> stateManager.transitionTo('other'); <ide> }); <ide> <ide> equal(getPath(rootView, 'childViews.length'), 0, "transitioning to a state without a view should remove the previous view"); <ide> <ide> Ember.run(function() { <del> stateManager.goToState('otherWithView'); <add> stateManager.transitionTo('otherWithView'); <ide> }); <ide> <ide> equal(get(rootView, 'childViews').objectAt(0), otherView, "the view added is the otherView state's view"); <ide> <ide> Ember.run(function() { <del> stateManager.goToState('start'); <add> stateManager.transitionTo('start'); <ide> }); <ide> equal(getPath(rootView, 'childViews.length'), 1, "when transitioning into a view state, its view should be added as a child of the root view"); <ide> equal(get(rootView, 'childViews').objectAt(0), view, "the view added is the view state's view"); <ide> test("it reports the view associated with the current view state, if any", funct <ide> }); <ide> <ide> Ember.run(function(){ <del> stateManager.goToState('foo.bar'); <add> stateManager.transitionTo('foo.bar'); <ide> }); <ide> <ide> equal(get(stateManager, 'currentView'), view, "returns nearest parent view state's view");
6
Ruby
Ruby
fix undefined method null error
3364e519b5bebb136ad9606d6af42f4171691bfd
<ide><path>Library/Homebrew/dev-cmd/bump-formula-pr.rb <ide> def check_new_version(formula, tap_remote_repo, args:, version: nil, url: nil, t <ide> specs = {} <ide> specs[:tag] = tag if tag.present? <ide> version = Version.detect(url, **specs) <add> return if version.null? <ide> end <ide> <del> return if version.null? <del> <ide> check_throttle(formula, version) <ide> check_closed_pull_requests(formula, tap_remote_repo, args: args, version: version) <ide> end
1
Text
Text
add async_hooks migration note
80dcc068fb54d93b6a8d65fe5cf4f21e04aeb52c
<ide><path>doc/api/async_hooks.md <ide> <ide> <!--introduced_in=v8.1.0--> <ide> <del>> Stability: 1 - Experimental <add>> Stability: 1 - Experimental. Please migrate away from this API, if you can. <add>> We do not recommend using the [`createHook`][], [`AsyncHook`][], and <add>> [`executionAsyncResource`][] APIs as they have usability issues, safety risks, <add>> and performance implications. Async context tracking use cases are better <add>> served by the stable [`AsyncLocalStorage`][] API. If you have a use case for <add>> `createHook`, `AsyncHook`, or `executionAsyncResource` beyond the context <add>> tracking need solved by [`AsyncLocalStorage`][] or diagnostics data currently <add>> provided by [Diagnostics Channel][], please open an issue at <add>> <https://github.com/nodejs/node/issues> describing your use case so we can <add>> create a more purpose-focused API. <ide> <ide> <!-- source_link=lib/async_hooks.js --> <ide> <ide> The documentation for this class has moved [`AsyncResource`][]. <ide> The documentation for this class has moved [`AsyncLocalStorage`][]. <ide> <ide> [DEP0111]: deprecations.md#dep0111-processbinding <add>[Diagnostics Channel]: diagnostics_channel.md <ide> [Hook Callbacks]: #hook-callbacks <ide> [PromiseHooks]: https://docs.google.com/document/d/1rda3yKGHimKIhg5YeoAmCOtyURgsbTH_qaYR79FELlk/edit <add>[`AsyncHook`]: #class-asynchook <ide> [`AsyncLocalStorage`]: async_context.md#class-asynclocalstorage <ide> [`AsyncResource`]: async_context.md#class-asyncresource <ide> [`Worker`]: worker_threads.md#class-worker <ide> [`after` callback]: #afterasyncid <ide> [`before` callback]: #beforeasyncid <add>[`createHook`]: #async_hookscreatehookcallbacks <ide> [`destroy` callback]: #destroyasyncid <add>[`executionAsyncResource`]: #async_hooksexecutionasyncresource <ide> [`init` callback]: #initasyncid-type-triggerasyncid-resource <ide> [`process.getActiveResourcesInfo()`]: process.md#processgetactiveresourcesinfo <ide> [`promiseResolve` callback]: #promiseresolveasyncid
1
Javascript
Javascript
remove unused variable
d86253456eedebe238a07da1914b9e11b867e835
<ide><path>packages/ember-views/lib/views/view.js <ide> Ember.View = Ember.Object.extend(Ember.Evented, <ide> @test in createChildViews <ide> */ <ide> createChildView: function(view, attrs) { <del> var coreAttrs, templateData; <add> var coreAttrs; <ide> <ide> if (Ember.View.detect(view)) { <ide> coreAttrs = { _parentView: this, templateData: get(this, 'templateData') };
1
Go
Go
implement daemon suite for integration-cli
57464c32b99b36a2963fb37da86b9870c9a56145
<ide><path>integration-cli/check_test.go <ide> func (s *DockerRegistrySuite) TearDownTest(c *check.C) { <ide> s.reg.Close() <ide> s.ds.TearDownTest(c) <ide> } <add> <add>func init() { <add> check.Suite(&DockerDaemonSuite{ <add> ds: &DockerSuite{}, <add> }) <add>} <add> <add>type DockerDaemonSuite struct { <add> ds *DockerSuite <add> d *Daemon <add>} <add> <add>func (s *DockerDaemonSuite) SetUpTest(c *check.C) { <add> s.d = NewDaemon(c) <add> s.ds.SetUpTest(c) <add>} <add> <add>func (s *DockerDaemonSuite) TearDownTest(c *check.C) { <add> s.d.Stop() <add> s.ds.TearDownTest(c) <add>} <ide><path>integration-cli/docker_cli_daemon_test.go <ide> import ( <ide> "github.com/go-check/check" <ide> ) <ide> <del>func (s *DockerSuite) TestDaemonRestartWithRunningContainersPorts(c *check.C) { <del> d := NewDaemon(c) <del> if err := d.StartWithBusybox(); err != nil { <add>func (s *DockerDaemonSuite) TestDaemonRestartWithRunningContainersPorts(c *check.C) { <add> if err := s.d.StartWithBusybox(); err != nil { <ide> c.Fatalf("Could not start daemon with busybox: %v", err) <ide> } <del> defer d.Stop() <ide> <del> if out, err := d.Cmd("run", "-d", "--name", "top1", "-p", "1234:80", "--restart", "always", "busybox:latest", "top"); err != nil { <add> if out, err := s.d.Cmd("run", "-d", "--name", "top1", "-p", "1234:80", "--restart", "always", "busybox:latest", "top"); err != nil { <ide> c.Fatalf("Could not run top1: err=%v\n%s", err, out) <ide> } <ide> // --restart=no by default <del> if out, err := d.Cmd("run", "-d", "--name", "top2", "-p", "80", "busybox:latest", "top"); err != nil { <add> if out, err := s.d.Cmd("run", "-d", "--name", "top2", "-p", "80", "busybox:latest", "top"); err != nil { <ide> c.Fatalf("Could not run top2: err=%v\n%s", err, out) <ide> } <ide> <ide> testRun := func(m map[string]bool, prefix string) { <ide> var format string <ide> for cont, shouldRun := range m { <del> out, err := d.Cmd("ps") <add> out, err := s.d.Cmd("ps") <ide> if err != nil { <ide> c.Fatalf("Could not run ps: err=%v\n%q", err, out) <ide> } <ide> func (s *DockerSuite) TestDaemonRestartWithRunningContainersPorts(c *check.C) { <ide> <ide> testRun(map[string]bool{"top1": true, "top2": true}, "") <ide> <del> if err := d.Restart(); err != nil { <add> if err := s.d.Restart(); err != nil { <ide> c.Fatalf("Could not restart daemon: %v", err) <ide> } <del> <ide> testRun(map[string]bool{"top1": true, "top2": false}, "After daemon restart: ") <del> <ide> } <ide> <del>func (s *DockerSuite) TestDaemonRestartWithVolumesRefs(c *check.C) { <del> d := NewDaemon(c) <del> if err := d.StartWithBusybox(); err != nil { <add>func (s *DockerDaemonSuite) TestDaemonRestartWithVolumesRefs(c *check.C) { <add> if err := s.d.StartWithBusybox(); err != nil { <ide> c.Fatal(err) <ide> } <del> defer d.Stop() <ide> <del> if out, err := d.Cmd("run", "-d", "--name", "volrestarttest1", "-v", "/foo", "busybox"); err != nil { <add> if out, err := s.d.Cmd("run", "-d", "--name", "volrestarttest1", "-v", "/foo", "busybox"); err != nil { <ide> c.Fatal(err, out) <ide> } <del> if err := d.Restart(); err != nil { <add> if err := s.d.Restart(); err != nil { <ide> c.Fatal(err) <ide> } <del> if _, err := d.Cmd("run", "-d", "--volumes-from", "volrestarttest1", "--name", "volrestarttest2", "busybox", "top"); err != nil { <add> if _, err := s.d.Cmd("run", "-d", "--volumes-from", "volrestarttest1", "--name", "volrestarttest2", "busybox", "top"); err != nil { <ide> c.Fatal(err) <ide> } <del> if out, err := d.Cmd("rm", "-fv", "volrestarttest2"); err != nil { <add> if out, err := s.d.Cmd("rm", "-fv", "volrestarttest2"); err != nil { <ide> c.Fatal(err, out) <ide> } <del> v, err := d.Cmd("inspect", "--format", "{{ json .Volumes }}", "volrestarttest1") <add> v, err := s.d.Cmd("inspect", "--format", "{{ json .Volumes }}", "volrestarttest1") <ide> if err != nil { <ide> c.Fatal(err) <ide> } <ide> func (s *DockerSuite) TestDaemonRestartWithVolumesRefs(c *check.C) { <ide> if _, err := os.Stat(volumes["/foo"]); err != nil { <ide> c.Fatalf("Expected volume to exist: %s - %s", volumes["/foo"], err) <ide> } <del> <ide> } <ide> <del>func (s *DockerSuite) TestDaemonStartIptablesFalse(c *check.C) { <del> d := NewDaemon(c) <del> if err := d.Start("--iptables=false"); err != nil { <add>func (s *DockerDaemonSuite) TestDaemonStartIptablesFalse(c *check.C) { <add> if err := s.d.Start("--iptables=false"); err != nil { <ide> c.Fatalf("we should have been able to start the daemon with passing iptables=false: %v", err) <ide> } <del> d.Stop() <del> <ide> } <ide> <ide> // Issue #8444: If docker0 bridge is modified (intentionally or unintentionally) and <ide> // no longer has an IP associated, we should gracefully handle that case and associate <ide> // an IP with it rather than fail daemon start <del>func (s *DockerSuite) TestDaemonStartBridgeWithoutIPAssociation(c *check.C) { <del> d := NewDaemon(c) <add>func (s *DockerDaemonSuite) TestDaemonStartBridgeWithoutIPAssociation(c *check.C) { <ide> // rather than depending on brctl commands to verify docker0 is created and up <ide> // let's start the daemon and stop it, and then make a modification to run the <ide> // actual test <del> if err := d.Start(); err != nil { <add> if err := s.d.Start(); err != nil { <ide> c.Fatalf("Could not start daemon: %v", err) <ide> } <del> if err := d.Stop(); err != nil { <add> if err := s.d.Stop(); err != nil { <ide> c.Fatalf("Could not stop daemon: %v", err) <ide> } <ide> <ide> func (s *DockerSuite) TestDaemonStartBridgeWithoutIPAssociation(c *check.C) { <ide> c.Fatalf("failed to remove docker0 IP association: %v, stdout: %q, stderr: %q", err, stdout, stderr) <ide> } <ide> <del> if err := d.Start(); err != nil { <add> if err := s.d.Start(); err != nil { <ide> warning := "**WARNING: Docker bridge network in bad state--delete docker0 bridge interface to fix" <ide> c.Fatalf("Could not start daemon when docker0 has no IP address: %v\n%s", err, warning) <ide> } <del> <del> // cleanup - stop the daemon if test passed <del> if err := d.Stop(); err != nil { <del> c.Fatalf("Could not stop daemon: %v", err) <del> } <del> <ide> } <ide> <del>func (s *DockerSuite) TestDaemonIptablesClean(c *check.C) { <del> <del> d := NewDaemon(c) <del> if err := d.StartWithBusybox(); err != nil { <add>func (s *DockerDaemonSuite) TestDaemonIptablesClean(c *check.C) { <add> if err := s.d.StartWithBusybox(); err != nil { <ide> c.Fatalf("Could not start daemon with busybox: %v", err) <ide> } <del> defer d.Stop() <ide> <del> if out, err := d.Cmd("run", "-d", "--name", "top", "-p", "80", "busybox:latest", "top"); err != nil { <add> if out, err := s.d.Cmd("run", "-d", "--name", "top", "-p", "80", "busybox:latest", "top"); err != nil { <ide> c.Fatalf("Could not run top: %s, %v", out, err) <ide> } <ide> <ide> func (s *DockerSuite) TestDaemonIptablesClean(c *check.C) { <ide> c.Fatalf("iptables output should have contained %q, but was %q", ipTablesSearchString, out) <ide> } <ide> <del> if err := d.Stop(); err != nil { <add> if err := s.d.Stop(); err != nil { <ide> c.Fatalf("Could not stop daemon: %v", err) <ide> } <ide> <ide> func (s *DockerSuite) TestDaemonIptablesClean(c *check.C) { <ide> if strings.Contains(out, ipTablesSearchString) { <ide> c.Fatalf("iptables output should not have contained %q, but was %q", ipTablesSearchString, out) <ide> } <del> <ide> } <ide> <del>func (s *DockerSuite) TestDaemonIptablesCreate(c *check.C) { <del> <del> d := NewDaemon(c) <del> if err := d.StartWithBusybox(); err != nil { <add>func (s *DockerDaemonSuite) TestDaemonIptablesCreate(c *check.C) { <add> if err := s.d.StartWithBusybox(); err != nil { <ide> c.Fatalf("Could not start daemon with busybox: %v", err) <ide> } <del> defer d.Stop() <ide> <del> if out, err := d.Cmd("run", "-d", "--name", "top", "--restart=always", "-p", "80", "busybox:latest", "top"); err != nil { <add> if out, err := s.d.Cmd("run", "-d", "--name", "top", "--restart=always", "-p", "80", "busybox:latest", "top"); err != nil { <ide> c.Fatalf("Could not run top: %s, %v", out, err) <ide> } <ide> <ide> func (s *DockerSuite) TestDaemonIptablesCreate(c *check.C) { <ide> c.Fatalf("iptables output should have contained %q, but was %q", ipTablesSearchString, out) <ide> } <ide> <del> if err := d.Restart(); err != nil { <add> if err := s.d.Restart(); err != nil { <ide> c.Fatalf("Could not restart daemon: %v", err) <ide> } <ide> <ide> // make sure the container is not running <del> runningOut, err := d.Cmd("inspect", "--format='{{.State.Running}}'", "top") <add> runningOut, err := s.d.Cmd("inspect", "--format='{{.State.Running}}'", "top") <ide> if err != nil { <ide> c.Fatalf("Could not inspect on container: %s, %v", out, err) <ide> } <ide> func (s *DockerSuite) TestDaemonIptablesCreate(c *check.C) { <ide> if !strings.Contains(out, ipTablesSearchString) { <ide> c.Fatalf("iptables output after restart should have contained %q, but was %q", ipTablesSearchString, out) <ide> } <del> <ide> } <ide> <del>func (s *DockerSuite) TestDaemonLoggingLevel(c *check.C) { <del> d := NewDaemon(c) <del> <del> if err := d.Start("--log-level=bogus"); err == nil { <del> c.Fatal("Daemon should not have been able to start") <del> } <add>func (s *DockerDaemonSuite) TestDaemonLogLevelWrong(c *check.C) { <add> c.Assert(s.d.Start("--log-level=bogus"), check.NotNil, check.Commentf("Daemon shouldn't start with wrong log level")) <add>} <ide> <del> d = NewDaemon(c) <del> if err := d.Start("--log-level=debug"); err != nil { <add>func (s *DockerDaemonSuite) TestDaemonLogLevelDebug(c *check.C) { <add> if err := s.d.Start("--log-level=debug"); err != nil { <ide> c.Fatal(err) <ide> } <del> d.Stop() <del> content, _ := ioutil.ReadFile(d.logFile.Name()) <add> content, _ := ioutil.ReadFile(s.d.logFile.Name()) <ide> if !strings.Contains(string(content), `level=debug`) { <ide> c.Fatalf(`Missing level="debug" in log file:\n%s`, string(content)) <ide> } <add>} <ide> <del> d = NewDaemon(c) <del> if err := d.Start("--log-level=fatal"); err != nil { <add>func (s *DockerDaemonSuite) TestDaemonLogLevelFatal(c *check.C) { <add> // we creating new daemons to create new logFile <add> if err := s.d.Start("--log-level=fatal"); err != nil { <ide> c.Fatal(err) <ide> } <del> d.Stop() <del> content, _ = ioutil.ReadFile(d.logFile.Name()) <add> content, _ := ioutil.ReadFile(s.d.logFile.Name()) <ide> if strings.Contains(string(content), `level=debug`) { <ide> c.Fatalf(`Should not have level="debug" in log file:\n%s`, string(content)) <ide> } <add>} <ide> <del> d = NewDaemon(c) <del> if err := d.Start("-D"); err != nil { <add>func (s *DockerDaemonSuite) TestDaemonFlagD(c *check.C) { <add> if err := s.d.Start("-D"); err != nil { <ide> c.Fatal(err) <ide> } <del> d.Stop() <del> content, _ = ioutil.ReadFile(d.logFile.Name()) <add> content, _ := ioutil.ReadFile(s.d.logFile.Name()) <ide> if !strings.Contains(string(content), `level=debug`) { <ide> c.Fatalf(`Missing level="debug" in log file using -D:\n%s`, string(content)) <ide> } <add>} <ide> <del> d = NewDaemon(c) <del> if err := d.Start("--debug"); err != nil { <add>func (s *DockerDaemonSuite) TestDaemonFlagDebug(c *check.C) { <add> if err := s.d.Start("--debug"); err != nil { <ide> c.Fatal(err) <ide> } <del> d.Stop() <del> content, _ = ioutil.ReadFile(d.logFile.Name()) <add> content, _ := ioutil.ReadFile(s.d.logFile.Name()) <ide> if !strings.Contains(string(content), `level=debug`) { <ide> c.Fatalf(`Missing level="debug" in log file using --debug:\n%s`, string(content)) <ide> } <add>} <ide> <del> d = NewDaemon(c) <del> if err := d.Start("--debug", "--log-level=fatal"); err != nil { <add>func (s *DockerDaemonSuite) TestDaemonFlagDebugLogLevelFatal(c *check.C) { <add> if err := s.d.Start("--debug", "--log-level=fatal"); err != nil { <ide> c.Fatal(err) <ide> } <del> d.Stop() <del> content, _ = ioutil.ReadFile(d.logFile.Name()) <add> content, _ := ioutil.ReadFile(s.d.logFile.Name()) <ide> if !strings.Contains(string(content), `level=debug`) { <ide> c.Fatalf(`Missing level="debug" in log file when using both --debug and --log-level=fatal:\n%s`, string(content)) <ide> } <del> <ide> } <ide> <del>func (s *DockerSuite) TestDaemonAllocatesListeningPort(c *check.C) { <add>func (s *DockerDaemonSuite) TestDaemonAllocatesListeningPort(c *check.C) { <ide> listeningPorts := [][]string{ <ide> {"0.0.0.0", "0.0.0.0", "5678"}, <ide> {"127.0.0.1", "127.0.0.1", "1234"}, <ide> func (s *DockerSuite) TestDaemonAllocatesListeningPort(c *check.C) { <ide> cmdArgs = append(cmdArgs, "--host", fmt.Sprintf("tcp://%s:%s", hostDirective[0], hostDirective[2])) <ide> } <ide> <del> d := NewDaemon(c) <del> if err := d.StartWithBusybox(cmdArgs...); err != nil { <add> if err := s.d.StartWithBusybox(cmdArgs...); err != nil { <ide> c.Fatalf("Could not start daemon with busybox: %v", err) <ide> } <del> defer d.Stop() <ide> <ide> for _, hostDirective := range listeningPorts { <del> output, err := d.Cmd("run", "-p", fmt.Sprintf("%s:%s:80", hostDirective[1], hostDirective[2]), "busybox", "true") <add> output, err := s.d.Cmd("run", "-p", fmt.Sprintf("%s:%s:80", hostDirective[1], hostDirective[2]), "busybox", "true") <ide> if err == nil { <ide> c.Fatalf("Container should not start, expected port already allocated error: %q", output) <ide> } else if !strings.Contains(output, "port is already allocated") { <ide> c.Fatalf("Expected port is already allocated error: %q", output) <ide> } <ide> } <del> <ide> } <ide> <ide> // #9629 <del>func (s *DockerSuite) TestDaemonVolumesBindsRefs(c *check.C) { <del> d := NewDaemon(c) <del> <del> if err := d.StartWithBusybox(); err != nil { <add>func (s *DockerDaemonSuite) TestDaemonVolumesBindsRefs(c *check.C) { <add> if err := s.d.StartWithBusybox(); err != nil { <ide> c.Fatal(err) <ide> } <del> defer d.Stop() <ide> <ide> tmp, err := ioutil.TempDir(os.TempDir(), "") <ide> if err != nil { <ide> func (s *DockerSuite) TestDaemonVolumesBindsRefs(c *check.C) { <ide> c.Fatal(err) <ide> } <ide> <del> if out, err := d.Cmd("create", "-v", tmp+":/foo", "--name=voltest", "busybox"); err != nil { <add> if out, err := s.d.Cmd("create", "-v", tmp+":/foo", "--name=voltest", "busybox"); err != nil { <ide> c.Fatal(err, out) <ide> } <ide> <del> if err := d.Restart(); err != nil { <add> if err := s.d.Restart(); err != nil { <ide> c.Fatal(err) <ide> } <ide> <del> if out, err := d.Cmd("run", "--volumes-from=voltest", "--name=consumer", "busybox", "/bin/sh", "-c", "[ -f /foo/test ]"); err != nil { <add> if out, err := s.d.Cmd("run", "--volumes-from=voltest", "--name=consumer", "busybox", "/bin/sh", "-c", "[ -f /foo/test ]"); err != nil { <ide> c.Fatal(err, out) <ide> } <del> <ide> } <ide> <del>func (s *DockerSuite) TestDaemonKeyGeneration(c *check.C) { <add>func (s *DockerDaemonSuite) TestDaemonKeyGeneration(c *check.C) { <ide> // TODO: skip or update for Windows daemon <ide> os.Remove("/etc/docker/key.json") <del> d := NewDaemon(c) <del> if err := d.Start(); err != nil { <add> if err := s.d.Start(); err != nil { <ide> c.Fatalf("Could not start daemon: %v", err) <ide> } <del> d.Stop() <add> s.d.Stop() <ide> <ide> k, err := libtrust.LoadKeyFile("/etc/docker/key.json") <ide> if err != nil { <ide> func (s *DockerSuite) TestDaemonKeyGeneration(c *check.C) { <ide> if len(kid) != 59 { <ide> c.Fatalf("Bad key ID: %s", kid) <ide> } <del> <ide> } <ide> <del>func (s *DockerSuite) TestDaemonKeyMigration(c *check.C) { <add>func (s *DockerDaemonSuite) TestDaemonKeyMigration(c *check.C) { <ide> // TODO: skip or update for Windows daemon <ide> os.Remove("/etc/docker/key.json") <ide> k1, err := libtrust.GenerateECP256PrivateKey() <ide> func (s *DockerSuite) TestDaemonKeyMigration(c *check.C) { <ide> c.Fatalf("Error saving private key: %s", err) <ide> } <ide> <del> d := NewDaemon(c) <del> if err := d.Start(); err != nil { <add> if err := s.d.Start(); err != nil { <ide> c.Fatalf("Could not start daemon: %v", err) <ide> } <del> d.Stop() <add> s.d.Stop() <ide> <ide> k2, err := libtrust.LoadKeyFile("/etc/docker/key.json") <ide> if err != nil { <ide> func (s *DockerSuite) TestDaemonKeyMigration(c *check.C) { <ide> if k1.KeyID() != k2.KeyID() { <ide> c.Fatalf("Key not migrated") <ide> } <del> <ide> } <ide> <ide> // Simulate an older daemon (pre 1.3) coming up with volumes specified in containers <ide> // without corresponding volume json <del>func (s *DockerSuite) TestDaemonUpgradeWithVolumes(c *check.C) { <del> d := NewDaemon(c) <del> <add>func (s *DockerDaemonSuite) TestDaemonUpgradeWithVolumes(c *check.C) { <ide> graphDir := filepath.Join(os.TempDir(), "docker-test") <ide> defer os.RemoveAll(graphDir) <del> if err := d.StartWithBusybox("-g", graphDir); err != nil { <add> if err := s.d.StartWithBusybox("-g", graphDir); err != nil { <ide> c.Fatal(err) <ide> } <del> defer d.Stop() <ide> <ide> tmpDir := filepath.Join(os.TempDir(), "test") <ide> defer os.RemoveAll(tmpDir) <ide> <del> if out, err := d.Cmd("create", "-v", tmpDir+":/foo", "--name=test", "busybox"); err != nil { <add> if out, err := s.d.Cmd("create", "-v", tmpDir+":/foo", "--name=test", "busybox"); err != nil { <ide> c.Fatal(err, out) <ide> } <ide> <del> if err := d.Stop(); err != nil { <add> if err := s.d.Stop(); err != nil { <ide> c.Fatal(err) <ide> } <ide> <ide> func (s *DockerSuite) TestDaemonUpgradeWithVolumes(c *check.C) { <ide> c.Fatal(err) <ide> } <ide> <del> if err := d.Start("-g", graphDir); err != nil { <add> if err := s.d.Start("-g", graphDir); err != nil { <ide> c.Fatal(err) <ide> } <ide> <ide> func (s *DockerSuite) TestDaemonUpgradeWithVolumes(c *check.C) { <ide> } <ide> <ide> // Now with just removing the volume config and not the volume data <del> if err := d.Stop(); err != nil { <add> if err := s.d.Stop(); err != nil { <ide> c.Fatal(err) <ide> } <ide> <ide> if err := os.RemoveAll(configDir); err != nil { <ide> c.Fatal(err) <ide> } <ide> <del> if err := d.Start("-g", graphDir); err != nil { <add> if err := s.d.Start("-g", graphDir); err != nil { <ide> c.Fatal(err) <ide> } <ide> <ide> func (s *DockerSuite) TestDaemonUpgradeWithVolumes(c *check.C) { <ide> if len(dir) == 0 { <ide> c.Fatalf("expected volumes config dir to contain data for new volume") <ide> } <del> <ide> } <ide> <ide> // GH#11320 - verify that the daemon exits on failure properly <ide> // Note that this explicitly tests the conflict of {-b,--bridge} and {--bip} options as the means <ide> // to get a daemon init failure; no other tests for -b/--bip conflict are therefore required <del>func (s *DockerSuite) TestDaemonExitOnFailure(c *check.C) { <del> d := NewDaemon(c) <del> defer d.Stop() <del> <add>func (s *DockerDaemonSuite) TestDaemonExitOnFailure(c *check.C) { <ide> //attempt to start daemon with incorrect flags (we know -b and --bip conflict) <del> if err := d.Start("--bridge", "nosuchbridge", "--bip", "1.1.1.1"); err != nil { <add> if err := s.d.Start("--bridge", "nosuchbridge", "--bip", "1.1.1.1"); err != nil { <ide> //verify we got the right error <ide> if !strings.Contains(err.Error(), "Daemon exited and never started") { <ide> c.Fatalf("Expected daemon not to start, got %v", err) <ide> } <ide> // look in the log and make sure we got the message that daemon is shutting down <del> runCmd := exec.Command("grep", "Error starting daemon", d.LogfileName()) <add> runCmd := exec.Command("grep", "Error starting daemon", s.d.LogfileName()) <ide> if out, _, err := runCommandWithOutput(runCmd); err != nil { <ide> c.Fatalf("Expected 'Error starting daemon' message; but doesn't exist in log: %q, err: %v", out, err) <ide> } <ide> } else { <ide> //if we didn't get an error and the daemon is running, this is a failure <del> d.Stop() <ide> c.Fatal("Conflicting options should cause the daemon to error out with a failure") <ide> } <del> <ide> } <ide> <del>func (s *DockerSuite) TestDaemonUlimitDefaults(c *check.C) { <add>func (s *DockerDaemonSuite) TestDaemonUlimitDefaults(c *check.C) { <ide> testRequires(c, NativeExecDriver) <del> d := NewDaemon(c) <ide> <del> if err := d.StartWithBusybox("--default-ulimit", "nofile=42:42", "--default-ulimit", "nproc=1024:1024"); err != nil { <add> if err := s.d.StartWithBusybox("--default-ulimit", "nofile=42:42", "--default-ulimit", "nproc=1024:1024"); err != nil { <ide> c.Fatal(err) <ide> } <del> defer d.Stop() <ide> <del> out, err := d.Cmd("run", "--ulimit", "nproc=2048", "--name=test", "busybox", "/bin/sh", "-c", "echo $(ulimit -n); echo $(ulimit -p)") <add> out, err := s.d.Cmd("run", "--ulimit", "nproc=2048", "--name=test", "busybox", "/bin/sh", "-c", "echo $(ulimit -n); echo $(ulimit -p)") <ide> if err != nil { <ide> c.Fatal(out, err) <ide> } <ide> func (s *DockerSuite) TestDaemonUlimitDefaults(c *check.C) { <ide> } <ide> <ide> // Now restart daemon with a new default <del> if err := d.Restart("--default-ulimit", "nofile=43"); err != nil { <add> if err := s.d.Restart("--default-ulimit", "nofile=43"); err != nil { <ide> c.Fatal(err) <ide> } <ide> <del> out, err = d.Cmd("start", "-a", "test") <add> out, err = s.d.Cmd("start", "-a", "test") <ide> if err != nil { <ide> c.Fatal(err) <ide> } <ide> func (s *DockerSuite) TestDaemonUlimitDefaults(c *check.C) { <ide> if nproc != "2048" { <ide> c.Fatalf("exepcted `ulimit -p` to be 2048, got: %s", nproc) <ide> } <del> <ide> } <ide> <ide> // #11315 <del>func (s *DockerSuite) TestDaemonRestartRenameContainer(c *check.C) { <del> d := NewDaemon(c) <del> if err := d.StartWithBusybox(); err != nil { <add>func (s *DockerDaemonSuite) TestDaemonRestartRenameContainer(c *check.C) { <add> if err := s.d.StartWithBusybox(); err != nil { <ide> c.Fatal(err) <ide> } <del> defer d.Stop() <ide> <del> if out, err := d.Cmd("run", "--name=test", "busybox"); err != nil { <add> if out, err := s.d.Cmd("run", "--name=test", "busybox"); err != nil { <ide> c.Fatal(err, out) <ide> } <ide> <del> if out, err := d.Cmd("rename", "test", "test2"); err != nil { <add> if out, err := s.d.Cmd("rename", "test", "test2"); err != nil { <ide> c.Fatal(err, out) <ide> } <ide> <del> if err := d.Restart(); err != nil { <add> if err := s.d.Restart(); err != nil { <ide> c.Fatal(err) <ide> } <ide> <del> if out, err := d.Cmd("start", "test2"); err != nil { <add> if out, err := s.d.Cmd("start", "test2"); err != nil { <ide> c.Fatal(err, out) <ide> } <del> <ide> } <ide> <del>func (s *DockerSuite) TestDaemonLoggingDriverDefault(c *check.C) { <del> d := NewDaemon(c) <del> <del> if err := d.StartWithBusybox(); err != nil { <add>func (s *DockerDaemonSuite) TestDaemonLoggingDriverDefault(c *check.C) { <add> if err := s.d.StartWithBusybox(); err != nil { <ide> c.Fatal(err) <ide> } <del> defer d.Stop() <ide> <del> out, err := d.Cmd("run", "-d", "busybox", "echo", "testline") <add> out, err := s.d.Cmd("run", "-d", "busybox", "echo", "testline") <ide> if err != nil { <ide> c.Fatal(out, err) <ide> } <ide> id := strings.TrimSpace(out) <ide> <del> if out, err := d.Cmd("wait", id); err != nil { <add> if out, err := s.d.Cmd("wait", id); err != nil { <ide> c.Fatal(out, err) <ide> } <del> logPath := filepath.Join(d.folder, "graph", "containers", id, id+"-json.log") <add> logPath := filepath.Join(s.d.folder, "graph", "containers", id, id+"-json.log") <ide> <ide> if _, err := os.Stat(logPath); err != nil { <ide> c.Fatal(err) <ide> func (s *DockerSuite) TestDaemonLoggingDriverDefault(c *check.C) { <ide> } <ide> } <ide> <del>func (s *DockerSuite) TestDaemonLoggingDriverDefaultOverride(c *check.C) { <del> d := NewDaemon(c) <del> <del> if err := d.StartWithBusybox(); err != nil { <add>func (s *DockerDaemonSuite) TestDaemonLoggingDriverDefaultOverride(c *check.C) { <add> if err := s.d.StartWithBusybox(); err != nil { <ide> c.Fatal(err) <ide> } <del> defer d.Stop() <ide> <del> out, err := d.Cmd("run", "-d", "--log-driver=none", "busybox", "echo", "testline") <add> out, err := s.d.Cmd("run", "-d", "--log-driver=none", "busybox", "echo", "testline") <ide> if err != nil { <ide> c.Fatal(out, err) <ide> } <ide> id := strings.TrimSpace(out) <ide> <del> if out, err := d.Cmd("wait", id); err != nil { <add> if out, err := s.d.Cmd("wait", id); err != nil { <ide> c.Fatal(out, err) <ide> } <del> logPath := filepath.Join(d.folder, "graph", "containers", id, id+"-json.log") <add> logPath := filepath.Join(s.d.folder, "graph", "containers", id, id+"-json.log") <ide> <ide> if _, err := os.Stat(logPath); err == nil || !os.IsNotExist(err) { <ide> c.Fatalf("%s shouldn't exits, error on Stat: %s", logPath, err) <ide> } <ide> } <ide> <del>func (s *DockerSuite) TestDaemonLoggingDriverNone(c *check.C) { <del> d := NewDaemon(c) <del> <del> if err := d.StartWithBusybox("--log-driver=none"); err != nil { <add>func (s *DockerDaemonSuite) TestDaemonLoggingDriverNone(c *check.C) { <add> if err := s.d.StartWithBusybox("--log-driver=none"); err != nil { <ide> c.Fatal(err) <ide> } <del> defer d.Stop() <ide> <del> out, err := d.Cmd("run", "-d", "busybox", "echo", "testline") <add> out, err := s.d.Cmd("run", "-d", "busybox", "echo", "testline") <ide> if err != nil { <ide> c.Fatal(out, err) <ide> } <ide> id := strings.TrimSpace(out) <del> if out, err := d.Cmd("wait", id); err != nil { <add> if out, err := s.d.Cmd("wait", id); err != nil { <ide> c.Fatal(out, err) <ide> } <ide> <del> logPath := filepath.Join(d.folder, "graph", "containers", id, id+"-json.log") <add> logPath := filepath.Join(s.d.folder, "graph", "containers", id, id+"-json.log") <ide> <ide> if _, err := os.Stat(logPath); err == nil || !os.IsNotExist(err) { <ide> c.Fatalf("%s shouldn't exits, error on Stat: %s", logPath, err) <ide> } <ide> } <ide> <del>func (s *DockerSuite) TestDaemonLoggingDriverNoneOverride(c *check.C) { <del> d := NewDaemon(c) <del> <del> if err := d.StartWithBusybox("--log-driver=none"); err != nil { <add>func (s *DockerDaemonSuite) TestDaemonLoggingDriverNoneOverride(c *check.C) { <add> if err := s.d.StartWithBusybox("--log-driver=none"); err != nil { <ide> c.Fatal(err) <ide> } <del> defer d.Stop() <ide> <del> out, err := d.Cmd("run", "-d", "--log-driver=json-file", "busybox", "echo", "testline") <add> out, err := s.d.Cmd("run", "-d", "--log-driver=json-file", "busybox", "echo", "testline") <ide> if err != nil { <ide> c.Fatal(out, err) <ide> } <ide> id := strings.TrimSpace(out) <ide> <del> if out, err := d.Cmd("wait", id); err != nil { <add> if out, err := s.d.Cmd("wait", id); err != nil { <ide> c.Fatal(out, err) <ide> } <del> logPath := filepath.Join(d.folder, "graph", "containers", id, id+"-json.log") <add> logPath := filepath.Join(s.d.folder, "graph", "containers", id, id+"-json.log") <ide> <ide> if _, err := os.Stat(logPath); err != nil { <ide> c.Fatal(err) <ide> func (s *DockerSuite) TestDaemonLoggingDriverNoneOverride(c *check.C) { <ide> } <ide> } <ide> <del>func (s *DockerSuite) TestDaemonLoggingDriverNoneLogsError(c *check.C) { <del> d := NewDaemon(c) <del> <del> if err := d.StartWithBusybox("--log-driver=none"); err != nil { <add>func (s *DockerDaemonSuite) TestDaemonLoggingDriverNoneLogsError(c *check.C) { <add> if err := s.d.StartWithBusybox("--log-driver=none"); err != nil { <ide> c.Fatal(err) <ide> } <del> defer d.Stop() <ide> <del> out, err := d.Cmd("run", "-d", "busybox", "echo", "testline") <add> out, err := s.d.Cmd("run", "-d", "busybox", "echo", "testline") <ide> if err != nil { <ide> c.Fatal(out, err) <ide> } <ide> id := strings.TrimSpace(out) <del> out, err = d.Cmd("logs", id) <add> out, err = s.d.Cmd("logs", id) <ide> if err == nil { <ide> c.Fatalf("Logs should fail with \"none\" driver") <ide> } <ide> func (s *DockerSuite) TestDaemonLoggingDriverNoneLogsError(c *check.C) { <ide> } <ide> } <ide> <del>func (s *DockerSuite) TestDaemonDots(c *check.C) { <del> d := NewDaemon(c) <del> if err := d.StartWithBusybox(); err != nil { <add>func (s *DockerDaemonSuite) TestDaemonDots(c *check.C) { <add> if err := s.d.StartWithBusybox(); err != nil { <ide> c.Fatal(err) <ide> } <del> defer d.Stop() <ide> <ide> // Now create 4 containers <del> if _, err := d.Cmd("create", "busybox"); err != nil { <add> if _, err := s.d.Cmd("create", "busybox"); err != nil { <ide> c.Fatalf("Error creating container: %q", err) <ide> } <del> if _, err := d.Cmd("create", "busybox"); err != nil { <add> if _, err := s.d.Cmd("create", "busybox"); err != nil { <ide> c.Fatalf("Error creating container: %q", err) <ide> } <del> if _, err := d.Cmd("create", "busybox"); err != nil { <add> if _, err := s.d.Cmd("create", "busybox"); err != nil { <ide> c.Fatalf("Error creating container: %q", err) <ide> } <del> if _, err := d.Cmd("create", "busybox"); err != nil { <add> if _, err := s.d.Cmd("create", "busybox"); err != nil { <ide> c.Fatalf("Error creating container: %q", err) <ide> } <ide> <del> d.Stop() <add> s.d.Stop() <ide> <del> d.Start("--log-level=debug") <del> d.Stop() <del> content, _ := ioutil.ReadFile(d.logFile.Name()) <add> s.d.Start("--log-level=debug") <add> s.d.Stop() <add> content, _ := ioutil.ReadFile(s.d.logFile.Name()) <ide> if strings.Contains(string(content), "....") { <ide> c.Fatalf("Debug level should not have ....\n%s", string(content)) <ide> } <ide> <del> d.Start("--log-level=error") <del> d.Stop() <del> content, _ = ioutil.ReadFile(d.logFile.Name()) <add> s.d.Start("--log-level=error") <add> s.d.Stop() <add> content, _ = ioutil.ReadFile(s.d.logFile.Name()) <ide> if strings.Contains(string(content), "....") { <ide> c.Fatalf("Error level should not have ....\n%s", string(content)) <ide> } <ide> <del> d.Start("--log-level=info") <del> d.Stop() <del> content, _ = ioutil.ReadFile(d.logFile.Name()) <add> s.d.Start("--log-level=info") <add> s.d.Stop() <add> content, _ = ioutil.ReadFile(s.d.logFile.Name()) <ide> if !strings.Contains(string(content), "....") { <ide> c.Fatalf("Info level should have ....\n%s", string(content)) <ide> } <del> <ide> } <ide> <del>func (s *DockerSuite) TestDaemonUnixSockCleanedUp(c *check.C) { <del> d := NewDaemon(c) <add>func (s *DockerDaemonSuite) TestDaemonUnixSockCleanedUp(c *check.C) { <ide> dir, err := ioutil.TempDir("", "socket-cleanup-test") <ide> if err != nil { <ide> c.Fatal(err) <ide> } <ide> defer os.RemoveAll(dir) <ide> <ide> sockPath := filepath.Join(dir, "docker.sock") <del> if err := d.Start("--host", "unix://"+sockPath); err != nil { <add> if err := s.d.Start("--host", "unix://"+sockPath); err != nil { <ide> c.Fatal(err) <ide> } <del> defer d.Stop() <ide> <ide> if _, err := os.Stat(sockPath); err != nil { <ide> c.Fatal("socket does not exist") <ide> } <ide> <del> if err := d.Stop(); err != nil { <add> if err := s.d.Stop(); err != nil { <ide> c.Fatal(err) <ide> } <ide> <ide> if _, err := os.Stat(sockPath); err == nil || !os.IsNotExist(err) { <ide> c.Fatal("unix socket is not cleaned up") <ide> } <del> <ide> } <ide> <del>func (s *DockerSuite) TestDaemonwithwrongkey(c *check.C) { <add>func (s *DockerDaemonSuite) TestDaemonwithwrongkey(c *check.C) { <ide> type Config struct { <ide> Crv string `json:"crv"` <ide> D string `json:"d"` <ide> func (s *DockerSuite) TestDaemonwithwrongkey(c *check.C) { <ide> } <ide> <ide> os.Remove("/etc/docker/key.json") <del> d := NewDaemon(c) <del> if err := d.Start(); err != nil { <add> if err := s.d.Start(); err != nil { <ide> c.Fatalf("Failed to start daemon: %v", err) <ide> } <ide> <del> if err := d.Stop(); err != nil { <add> if err := s.d.Stop(); err != nil { <ide> c.Fatalf("Could not stop daemon: %v", err) <ide> } <ide> <ide> func (s *DockerSuite) TestDaemonwithwrongkey(c *check.C) { <ide> c.Fatalf("Error ioutil.WriteFile: %s", err) <ide> } <ide> <del> d1 := NewDaemon(c) <ide> defer os.Remove("/etc/docker/key.json") <ide> <del> if err := d1.Start(); err == nil { <del> d1.Stop() <add> if err := s.d.Start(); err == nil { <ide> c.Fatalf("It should not be successful to start daemon with wrong key: %v", err) <ide> } <ide> <del> content, _ := ioutil.ReadFile(d1.logFile.Name()) <add> content, _ := ioutil.ReadFile(s.d.logFile.Name()) <ide> <ide> if !strings.Contains(string(content), "Public Key ID does not match") { <ide> c.Fatal("Missing KeyID message from daemon logs") <ide> } <del> <ide> } <ide> <del>func (s *DockerSuite) TestDaemonRestartKillWait(c *check.C) { <del> d := NewDaemon(c) <del> if err := d.StartWithBusybox(); err != nil { <add>func (s *DockerDaemonSuite) TestDaemonRestartKillWait(c *check.C) { <add> if err := s.d.StartWithBusybox(); err != nil { <ide> c.Fatalf("Could not start daemon with busybox: %v", err) <ide> } <del> defer d.Stop() <ide> <del> out, err := d.Cmd("run", "-id", "busybox", "/bin/cat") <add> out, err := s.d.Cmd("run", "-id", "busybox", "/bin/cat") <ide> if err != nil { <ide> c.Fatalf("Could not run /bin/cat: err=%v\n%s", err, out) <ide> } <ide> containerID := strings.TrimSpace(out) <ide> <del> if out, err := d.Cmd("kill", containerID); err != nil { <add> if out, err := s.d.Cmd("kill", containerID); err != nil { <ide> c.Fatalf("Could not kill %s: err=%v\n%s", containerID, err, out) <ide> } <ide> <del> if err := d.Restart(); err != nil { <add> if err := s.d.Restart(); err != nil { <ide> c.Fatalf("Could not restart daemon: %v", err) <ide> } <ide> <ide> errchan := make(chan error) <ide> go func() { <del> if out, err := d.Cmd("wait", containerID); err != nil { <add> if out, err := s.d.Cmd("wait", containerID); err != nil { <ide> errchan <- fmt.Errorf("%v:\n%s", err, out) <ide> } <ide> close(errchan) <ide> func (s *DockerSuite) TestDaemonRestartKillWait(c *check.C) { <ide> c.Fatal(err) <ide> } <ide> } <del> <ide> } <ide> <ide> // TestHttpsInfo connects via two-way authenticated HTTPS to the info endpoint <del>func (s *DockerSuite) TestHttpsInfo(c *check.C) { <add>func (s *DockerDaemonSuite) TestHttpsInfo(c *check.C) { <ide> const ( <ide> testDaemonHttpsAddr = "localhost:4271" <ide> ) <ide> <del> d := NewDaemon(c) <del> if err := d.Start("--tlsverify", "--tlscacert", "fixtures/https/ca.pem", "--tlscert", "fixtures/https/server-cert.pem", <add> if err := s.d.Start("--tlsverify", "--tlscacert", "fixtures/https/ca.pem", "--tlscert", "fixtures/https/server-cert.pem", <ide> "--tlskey", "fixtures/https/server-key.pem", "-H", testDaemonHttpsAddr); err != nil { <ide> c.Fatalf("Could not start daemon with busybox: %v", err) <ide> } <del> defer d.Stop() <ide> <ide> //force tcp protocol <ide> host := fmt.Sprintf("tcp://%s", testDaemonHttpsAddr) <ide> daemonArgs := []string{"--host", host, "--tlsverify", "--tlscacert", "fixtures/https/ca.pem", "--tlscert", "fixtures/https/client-cert.pem", "--tlskey", "fixtures/https/client-key.pem"} <del> out, err := d.CmdWithArgs(daemonArgs, "info") <add> out, err := s.d.CmdWithArgs(daemonArgs, "info") <ide> if err != nil { <ide> c.Fatalf("Error Occurred: %s and output: %s", err, out) <ide> } <ide> } <ide> <ide> // TestHttpsInfoRogueCert connects via two-way authenticated HTTPS to the info endpoint <ide> // by using a rogue client certificate and checks that it fails with the expected error. <del>func (s *DockerSuite) TestHttpsInfoRogueCert(c *check.C) { <add>func (s *DockerDaemonSuite) TestHttpsInfoRogueCert(c *check.C) { <ide> const ( <ide> errBadCertificate = "remote error: bad certificate" <ide> testDaemonHttpsAddr = "localhost:4271" <ide> ) <del> d := NewDaemon(c) <del> if err := d.Start("--tlsverify", "--tlscacert", "fixtures/https/ca.pem", "--tlscert", "fixtures/https/server-cert.pem", <add> if err := s.d.Start("--tlsverify", "--tlscacert", "fixtures/https/ca.pem", "--tlscert", "fixtures/https/server-cert.pem", <ide> "--tlskey", "fixtures/https/server-key.pem", "-H", testDaemonHttpsAddr); err != nil { <ide> c.Fatalf("Could not start daemon with busybox: %v", err) <ide> } <del> defer d.Stop() <ide> <ide> //force tcp protocol <ide> host := fmt.Sprintf("tcp://%s", testDaemonHttpsAddr) <ide> daemonArgs := []string{"--host", host, "--tlsverify", "--tlscacert", "fixtures/https/ca.pem", "--tlscert", "fixtures/https/client-rogue-cert.pem", "--tlskey", "fixtures/https/client-rogue-key.pem"} <del> out, err := d.CmdWithArgs(daemonArgs, "info") <add> out, err := s.d.CmdWithArgs(daemonArgs, "info") <ide> if err == nil || !strings.Contains(out, errBadCertificate) { <ide> c.Fatalf("Expected err: %s, got instead: %s and output: %s", errBadCertificate, err, out) <ide> } <ide> } <ide> <ide> // TestHttpsInfoRogueServerCert connects via two-way authenticated HTTPS to the info endpoint <ide> // which provides a rogue server certificate and checks that it fails with the expected error <del>func (s *DockerSuite) TestHttpsInfoRogueServerCert(c *check.C) { <add>func (s *DockerDaemonSuite) TestHttpsInfoRogueServerCert(c *check.C) { <ide> const ( <ide> errCaUnknown = "x509: certificate signed by unknown authority" <ide> testDaemonRogueHttpsAddr = "localhost:4272" <ide> ) <del> d := NewDaemon(c) <del> if err := d.Start("--tlsverify", "--tlscacert", "fixtures/https/ca.pem", "--tlscert", "fixtures/https/server-rogue-cert.pem", <add> if err := s.d.Start("--tlsverify", "--tlscacert", "fixtures/https/ca.pem", "--tlscert", "fixtures/https/server-rogue-cert.pem", <ide> "--tlskey", "fixtures/https/server-rogue-key.pem", "-H", testDaemonRogueHttpsAddr); err != nil { <ide> c.Fatalf("Could not start daemon with busybox: %v", err) <ide> } <del> defer d.Stop() <ide> <ide> //force tcp protocol <ide> host := fmt.Sprintf("tcp://%s", testDaemonRogueHttpsAddr) <ide> daemonArgs := []string{"--host", host, "--tlsverify", "--tlscacert", "fixtures/https/ca.pem", "--tlscert", "fixtures/https/client-rogue-cert.pem", "--tlskey", "fixtures/https/client-rogue-key.pem"} <del> out, err := d.CmdWithArgs(daemonArgs, "info") <add> out, err := s.d.CmdWithArgs(daemonArgs, "info") <ide> if err == nil || !strings.Contains(out, errCaUnknown) { <ide> c.Fatalf("Expected err: %s, got instead: %s and output: %s", errCaUnknown, err, out) <ide> } <ide><path>integration-cli/docker_cli_exec_test.go <ide> func (s *DockerSuite) TestExecAfterContainerRestart(c *check.C) { <ide> <ide> } <ide> <del>func (s *DockerSuite) TestExecAfterDaemonRestart(c *check.C) { <add>func (s *DockerDaemonSuite) TestExecAfterDaemonRestart(c *check.C) { <ide> testRequires(c, SameHostDaemon) <ide> <del> d := NewDaemon(c) <del> if err := d.StartWithBusybox(); err != nil { <add> if err := s.d.StartWithBusybox(); err != nil { <ide> c.Fatalf("Could not start daemon with busybox: %v", err) <ide> } <del> defer d.Stop() <ide> <del> if out, err := d.Cmd("run", "-d", "--name", "top", "-p", "80", "busybox:latest", "top"); err != nil { <add> if out, err := s.d.Cmd("run", "-d", "--name", "top", "-p", "80", "busybox:latest", "top"); err != nil { <ide> c.Fatalf("Could not run top: err=%v\n%s", err, out) <ide> } <ide> <del> if err := d.Restart(); err != nil { <add> if err := s.d.Restart(); err != nil { <ide> c.Fatalf("Could not restart daemon: %v", err) <ide> } <ide> <del> if out, err := d.Cmd("start", "top"); err != nil { <add> if out, err := s.d.Cmd("start", "top"); err != nil { <ide> c.Fatalf("Could not start top after daemon restart: err=%v\n%s", err, out) <ide> } <ide> <del> out, err := d.Cmd("exec", "top", "echo", "hello") <add> out, err := s.d.Cmd("exec", "top", "echo", "hello") <ide> if err != nil { <ide> c.Fatalf("Could not exec on container top: err=%v\n%s", err, out) <ide> } <ide> func (s *DockerSuite) TestExecAfterDaemonRestart(c *check.C) { <ide> if outStr != "hello" { <ide> c.Errorf("container should've printed hello, instead printed %q", outStr) <ide> } <del> <ide> } <ide> <ide> // Regression test for #9155, #9044 <ide><path>integration-cli/docker_cli_proxy_test.go <ide> func (s *DockerSuite) TestCliProxyDisableProxyUnixSock(c *check.C) { <ide> <ide> // Can't use localhost here since go has a special case to not use proxy if connecting to localhost <ide> // See https://golang.org/pkg/net/http/#ProxyFromEnvironment <del>func (s *DockerSuite) TestCliProxyProxyTCPSock(c *check.C) { <add>func (s *DockerDaemonSuite) TestCliProxyProxyTCPSock(c *check.C) { <ide> testRequires(c, SameHostDaemon) <ide> // get the IP to use to connect since we can't use localhost <ide> addrs, err := net.InterfaceAddrs() <ide> func (s *DockerSuite) TestCliProxyProxyTCPSock(c *check.C) { <ide> c.Fatal("could not find ip to connect to") <ide> } <ide> <del> d := NewDaemon(c) <del> if err := d.Start("-H", "tcp://"+ip+":2375"); err != nil { <add> if err := s.d.Start("-H", "tcp://"+ip+":2375"); err != nil { <ide> c.Fatal(err) <ide> } <ide>
4
Ruby
Ruby
handle missing process
7eb4b92d309a2118881f78893271bc1c8e5d57b4
<ide><path>Library/Homebrew/cache_store.rb <ide> def db <ide> end <ide> rescue ErrorDuringExecution, Timeout::Error <ide> odebug "Failed to read #{dbm_file_path}!" <del> Process.kill(:KILL, dbm_test_read_cmd.pid) <add> begin <add> Process.kill(:KILL, dbm_test_read_cmd.pid) <add> rescue Errno::ESRCH <add> # Process has already terminated. <add> nil <add> end <ide> false <ide> end <ide> cache_path.delete unless dbm_test_read_success
1
Text
Text
add doc for setting the queue adapter
29c9dcc4aff563085e94ec89c148b6e779fd4e46
<ide><path>README.md <ide> switch between them without having to rewrite your jobs. <ide> <ide> ## Usage <ide> <add>Set the queue adapter for Active Job: <add> <add>``` ruby <add>ActiveJob::Base.queue_adapter = :inline # default queue adapter <add># Adapters currently supported: :resque, :sidekiq, :sucker_punch, :delayed_job <add>``` <add> <ide> Declare a job like so: <ide> <ide> ```ruby
1
PHP
PHP
apply fixes from styleci
ebbefd8723125d094a09c940ff27919b9ae9f2d1
<ide><path>tests/Integration/Database/EloquentPaginateTest.php <ide> public function test_pagination_on_top_of_columns() <ide> { <ide> for ($i = 1; $i <= 50; $i++) { <ide> Post::create([ <del> 'title' => 'Title ' . $i, <add> 'title' => 'Title '.$i, <ide> ]); <ide> } <ide>
1
Javascript
Javascript
add rfc232 variants
4fc1370b6eec39a0dd3b98ca1bb3e002b061500a
<ide><path>blueprints/initializer-test/qunit-rfc-232-files/tests/unit/initializers/__name__-test.js <add>import Application from '@ember/application'; <add>import { run } from '@ember/runloop'; <add> <add>import { initialize } from '<%= dasherizedModulePrefix %>/initializers/<%= dasherizedModuleName %>'; <add>import { module, test } from 'qunit'; <add>import { setupTest } from 'ember-qunit'; <add>import destroyApp from '../../helpers/destroy-app'; <add> <add>module('<%= friendlyTestName %>', function(hooks) { <add> setupTest(hooks); <add> <add> hooks.beforeEach(function() { <add> run(() => { <add> this.application = Application.create(); <add> this.application.deferReadiness(); <add> }); <add> }); <add> hooks.afterEach(function() { <add> destroyApp(this.application); <add> }); <add> <add> // Replace this with your real tests. <add> test('it works', function(assert) { <add> initialize(this.application); <add> <add> // you would normally confirm the results of the initializer here <add> assert.ok(true); <add> }); <add>}); <ide><path>node-tests/blueprints/initializer-test-test.js <ide> const modifyPackages = blueprintHelpers.modifyPackages; <ide> const chai = require('ember-cli-blueprint-test-helpers/chai'); <ide> const expect = chai.expect; <ide> <add>const generateFakePackageManifest = require('../helpers/generate-fake-package-manifest'); <ide> const fixture = require('../helpers/fixture'); <ide> <ide> describe('Blueprint: initializer-test', function() { <ide> describe('Blueprint: initializer-test', function() { <ide> }); <ide> }); <ide> <add> describe('with ember-cli-qunit@4.1.1', function() { <add> beforeEach(function() { <add> generateFakePackageManifest('ember-cli-qunit', '4.1.1'); <add> }); <add> <add> it('initializer-test foo', function() { <add> return emberGenerateDestroy(['initializer-test', 'foo'], _file => { <add> expect(_file('tests/unit/initializers/foo-test.js')) <add> .to.equal(fixture('initializer-test/rfc232.js')); <add> }); <add> }); <add> }); <add> <ide> describe('with ember-cli-mocha', function() { <ide> beforeEach(function() { <ide> modifyPackages([ <ide><path>node-tests/fixtures/initializer-test/rfc232.js <add>import Application from '@ember/application'; <add>import { run } from '@ember/runloop'; <add> <add>import { initialize } from 'my-app/initializers/foo'; <add>import { module, test } from 'qunit'; <add>import { setupTest } from 'ember-qunit'; <add>import destroyApp from '../../helpers/destroy-app'; <add> <add>module('Unit | Initializer | foo', function(hooks) { <add> setupTest(hooks); <add> <add> hooks.beforeEach(function() { <add> run(() => { <add> this.application = Application.create(); <add> this.application.deferReadiness(); <add> }); <add> }); <add> hooks.afterEach(function() { <add> destroyApp(this.application); <add> }); <add> <add> // Replace this with your real tests. <add> test('it works', function(assert) { <add> initialize(this.application); <add> <add> // you would normally confirm the results of the initializer here <add> assert.ok(true); <add> }); <add>});
3
Javascript
Javascript
add korean translation
3621529edaf7b6548fe81f83ec25151f6b292161
<ide><path>lang/kr.js <ide> longDateFormat : { <ide> L : "YYYY.MM.DD", <ide> LL : "YYYY년 MMMM D일", <del> LLL : "YYYY년 MMMM D일 HH시 mm분", <del> LLLL : "YYYY년 MMMM D일 dddd HH시 mm분" <add> LLL : "YYYY년 MMMM D일 A h시 mm분", <add> LLLL : "YYYY년 MMMM D일 dddd A h시 mm분" <ide> }, <add> meridiem : { <add> AM : '오전', <add> am : '오전', <add> PM : '오후', <add> pm : '오후' <add> }, <ide> relativeTime : { <ide> future : "%s 후", <ide> past : "%s 전", <del> s : "%d초", <add> s : "몇초", <add> ss : "%d초", <ide> m : "일분", <ide> mm : "%d분", <del> h : "한 시간", <add> h : "한시간", <ide> hh : "%d시간", <ide> d : "하루", <ide> dd : "%d일", <ide> yy : "%d년" <ide> }, <ide> ordinal : function (number) { <del> return '일'; <add> return '일'; <ide> } <ide> }; <ide> <ide><path>lang/test/kr.js <ide> module("lang:kr"); <ide> test("format", 18, function() { <ide> moment.lang('kr'); <ide> var a = [ <del> ['dddd, MMMM Do YYYY, h:mm:ss a', 'Sunday, February 14th 2010, 3:25:50 pm'], <del> ['ddd, hA', 'Sun, 3PM'], <del> ['M Mo MM MMMM MMM', '2 2nd 02 February Feb'], <add> ['YYYY년 MMMM Do dddd a h:mm:ss', '2010년 2월 14일 일요일 오후 3:25:50'], <add> ['ddd A h', '일 오후 3'], <add> ['M Mo MM MMMM MMM', '2 2일 02 2월 2월'], <ide> ['YYYY YY', '2010 10'], <del> ['D Do DD', '14 14th 14'], <del> ['d do dddd ddd', '0 0th Sunday Sun'], <del> ['DDD DDDo DDDD', '45 45th 045'], <del> ['w wo ww', '8 8th 08'], <add> ['D Do DD', '14 14일 14'], <add> ['d do dddd ddd', '0 0일 일요일 일'], <add> ['DDD DDDo DDDD', '45 45일 045'], <add> ['w wo ww', '8 8일 08'], <ide> ['h hh', '3 03'], <ide> ['H HH', '15 15'], <ide> ['m mm', '25 25'], <ide> ['s ss', '50 50'], <del> ['a A', 'pm PM'], <del> ['t\\he DDDo \\d\\ay of t\\he ye\\ar', 'the 45th day of the year'], <del> ['L', '02/14/2010'], <del> ['LL', 'February 14 2010'], <del> ['LLL', 'February 14 2010 3:25 PM'], <del> ['LLLL', 'Sunday, February 14 2010 3:25 PM'] <add> ['a A', '오후 오후'], <add> ['일년 중 DDDo째 되는 날', '일년 중 45일째 되는 날'], <add> ['L', '2010.02.14'], <add> ['LL', '2010년 2월 14일'], <add> ['LLL', '2010년 2월 14일 오후 3시 25분'], <add> ['LLLL', '2010년 2월 14일 일요일 오후 3시 25분'] <ide> ], <ide> b = moment(new Date(2010, 1, 14, 15, 25, 50, 125)), <ide> i; <ide> test("format week", 7, function() { <ide> }); <ide> <ide> test("from", 30, function() { <del> moment.lang('en'); <add> moment.lang('kr'); <ide> var start = moment([2007, 1, 28]); <del> equal(start.from(moment([2007, 1, 28]).add({s:44}), true), "a few seconds", "44 seconds = a few seconds"); <del> equal(start.from(moment([2007, 1, 28]).add({s:45}), true), "a minute", "45 seconds = a minute"); <del> equal(start.from(moment([2007, 1, 28]).add({s:89}), true), "a minute", "89 seconds = a minute"); <del> equal(start.from(moment([2007, 1, 28]).add({s:90}), true), "2 minutes", "90 seconds = 2 minutes"); <del> equal(start.from(moment([2007, 1, 28]).add({m:44}), true), "44 minutes", "44 minutes = 44 minutes"); <del> equal(start.from(moment([2007, 1, 28]).add({m:45}), true), "an hour", "45 minutes = an hour"); <del> equal(start.from(moment([2007, 1, 28]).add({m:89}), true), "an hour", "89 minutes = an hour"); <del> equal(start.from(moment([2007, 1, 28]).add({m:90}), true), "2 hours", "90 minutes = 2 hours"); <del> equal(start.from(moment([2007, 1, 28]).add({h:5}), true), "5 hours", "5 hours = 5 hours"); <del> equal(start.from(moment([2007, 1, 28]).add({h:21}), true), "21 hours", "21 hours = 21 hours"); <del> equal(start.from(moment([2007, 1, 28]).add({h:22}), true), "a day", "22 hours = a day"); <del> equal(start.from(moment([2007, 1, 28]).add({h:35}), true), "a day", "35 hours = a day"); <del> equal(start.from(moment([2007, 1, 28]).add({h:36}), true), "2 days", "36 hours = 2 days"); <del> equal(start.from(moment([2007, 1, 28]).add({d:1}), true), "a day", "1 day = a day"); <del> equal(start.from(moment([2007, 1, 28]).add({d:5}), true), "5 days", "5 days = 5 days"); <del> equal(start.from(moment([2007, 1, 28]).add({d:25}), true), "25 days", "25 days = 25 days"); <del> equal(start.from(moment([2007, 1, 28]).add({d:26}), true), "a month", "26 days = a month"); <del> equal(start.from(moment([2007, 1, 28]).add({d:30}), true), "a month", "30 days = a month"); <del> equal(start.from(moment([2007, 1, 28]).add({d:45}), true), "a month", "45 days = a month"); <del> equal(start.from(moment([2007, 1, 28]).add({d:46}), true), "2 months", "46 days = 2 months"); <del> equal(start.from(moment([2007, 1, 28]).add({d:74}), true), "2 months", "75 days = 2 months"); <del> equal(start.from(moment([2007, 1, 28]).add({d:76}), true), "3 months", "76 days = 3 months"); <del> equal(start.from(moment([2007, 1, 28]).add({M:1}), true), "a month", "1 month = a month"); <del> equal(start.from(moment([2007, 1, 28]).add({M:5}), true), "5 months", "5 months = 5 months"); <del> equal(start.from(moment([2007, 1, 28]).add({d:344}), true), "11 months", "344 days = 11 months"); <del> equal(start.from(moment([2007, 1, 28]).add({d:345}), true), "a year", "345 days = a year"); <del> equal(start.from(moment([2007, 1, 28]).add({d:547}), true), "a year", "547 days = a year"); <del> equal(start.from(moment([2007, 1, 28]).add({d:548}), true), "2 years", "548 days = 2 years"); <del> equal(start.from(moment([2007, 1, 28]).add({y:1}), true), "a year", "1 year = a year"); <del> equal(start.from(moment([2007, 1, 28]).add({y:5}), true), "5 years", "5 years = 5 years"); <add> equal(start.from(moment([2007, 1, 28]).add({s:44}), true), "몇초", "44초 = 몇초"); <add> equal(start.from(moment([2007, 1, 28]).add({s:45}), true), "일분", "45초 = 일분"); <add> equal(start.from(moment([2007, 1, 28]).add({s:89}), true), "일분", "89초 = 일분"); <add> equal(start.from(moment([2007, 1, 28]).add({s:90}), true), "2분", "90초 = 2분"); <add> equal(start.from(moment([2007, 1, 28]).add({m:44}), true), "44분", "44분 = 44분"); <add> equal(start.from(moment([2007, 1, 28]).add({m:45}), true), "한시간", "45분 = 한시간"); <add> equal(start.from(moment([2007, 1, 28]).add({m:89}), true), "한시간", "89분 = 한시간"); <add> equal(start.from(moment([2007, 1, 28]).add({m:90}), true), "2시간", "90분 = 2시간"); <add> equal(start.from(moment([2007, 1, 28]).add({h:5}), true), "5시간", "5시간 = 5시간"); <add> equal(start.from(moment([2007, 1, 28]).add({h:21}), true), "21시간", "21시간 = 21시간"); <add> equal(start.from(moment([2007, 1, 28]).add({h:22}), true), "하루", "22시간 = 하루"); <add> equal(start.from(moment([2007, 1, 28]).add({h:35}), true), "하루", "35시간 = 하루"); <add> equal(start.from(moment([2007, 1, 28]).add({h:36}), true), "2일", "36시간 = 2일"); <add> equal(start.from(moment([2007, 1, 28]).add({d:1}), true), "하루", "하루 = 하루"); <add> equal(start.from(moment([2007, 1, 28]).add({d:5}), true), "5일", "5일 = 5일"); <add> equal(start.from(moment([2007, 1, 28]).add({d:25}), true), "25일", "25일 = 25일"); <add> equal(start.from(moment([2007, 1, 28]).add({d:26}), true), "한달", "26일 = 한달"); <add> equal(start.from(moment([2007, 1, 28]).add({d:30}), true), "한달", "30일 = 한달"); <add> equal(start.from(moment([2007, 1, 28]).add({d:45}), true), "한달", "45일 = 한달"); <add> equal(start.from(moment([2007, 1, 28]).add({d:46}), true), "2달", "46일 = 2달"); <add> equal(start.from(moment([2007, 1, 28]).add({d:74}), true), "2달", "75일 = 2달"); <add> equal(start.from(moment([2007, 1, 28]).add({d:76}), true), "3달", "76일 = 3달"); <add> equal(start.from(moment([2007, 1, 28]).add({M:1}), true), "한달", "1달 = 한달"); <add> equal(start.from(moment([2007, 1, 28]).add({M:5}), true), "5달", "5달 = 5달"); <add> equal(start.from(moment([2007, 1, 28]).add({d:344}), true), "11달", "344일 = 11달"); <add> equal(start.from(moment([2007, 1, 28]).add({d:345}), true), "일년", "345일 = 일년"); <add> equal(start.from(moment([2007, 1, 28]).add({d:547}), true), "일년", "547일 = 일년"); <add> equal(start.from(moment([2007, 1, 28]).add({d:548}), true), "2년", "548일 = 2년"); <add> equal(start.from(moment([2007, 1, 28]).add({y:1}), true), "일년", "일년 = 일년"); <add> equal(start.from(moment([2007, 1, 28]).add({y:5}), true), "5년", "5년 = 5년"); <ide> }); <ide> <ide> test("suffix", 2, function() { <del> moment.lang('en'); <del> equal(moment(30000).from(0), "in a few seconds", "prefix"); <del> equal(moment(0).from(30000), "a few seconds ago", "suffix"); <add> moment.lang('kr'); <add> equal(moment(30000).from(0), "몇초 후", "prefix"); <add> equal(moment(0).from(30000), "몇초 전", "suffix"); <ide> }); <ide> <ide>
2
Javascript
Javascript
fix element creation for large dataset
505afa7f1323cf6e7975369eba30056977085eaa
<ide><path>src/core/core.datasetController.js <ide> export default class DatasetController { <ide> */ <ide> _insertElements(start, count, resetNewElements = true) { <ide> const me = this; <del> const elements = new Array(count); <ide> const meta = me._cachedMeta; <ide> const data = meta.data; <add> const end = start + count; <ide> let i; <ide> <del> for (i = 0; i < count; ++i) { <del> elements[i] = new me.dataElementType(); <add> const move = (arr) => { <add> arr.length += count; <add> for (i = arr.length - 1; i >= end; i--) { <add> arr[i] = arr[i - count]; <add> } <add> }; <add> move(data); <add> <add> for (i = start; i < end; ++i) { <add> data[i] = new me.dataElementType(); <ide> } <del> data.splice(start, 0, ...elements); <ide> <ide> if (me._parsing) { <del> meta._parsed.splice(start, 0, ...new Array(count)); <add> move(meta._parsed); <ide> } <ide> me.parse(start, count); <ide> <ide><path>test/specs/controller.line.tests.js <ide> describe('Chart.controllers.line', function() { <ide> expect(meta.data[2].options.borderWidth).toBe(3); <ide> expect(meta.data[3].options.borderWidth).toBe(4); <ide> }); <add> <add> it('should render a million points', function() { <add> var data = []; <add> for (let x = 0; x < 1e6; x++) { <add> data.push({x, y: Math.sin(x / 10000)}); <add> } <add> function createChart() { <add> window.acquireChart({ <add> type: 'line', <add> data: { <add> datasets: [{ <add> data, <add> borderWidth: 1, <add> radius: 0 <add> }], <add> }, <add> options: { <add> scales: { <add> x: {type: 'linear'}, <add> y: {type: 'linear'} <add> } <add> } <add> }); <add> } <add> expect(createChart).not.toThrow(); <add> }); <ide> });
2
Text
Text
add link to write with transformers to model card
a9ae27cd0fe80b32ea1d1b64a0832f94d150d66b
<ide><path>model_cards/gpt2-xl-README.md <add>Test the whole generation capabilities here: https://transformer.huggingface.co/doc/gpt2-large
1
Ruby
Ruby
add parser for hyphenated filenames
d4c15a6d9d2d0641491d652285cd1d628bc8d530
<ide><path>Library/Homebrew/test/version_spec.rb <ide> specify "version internal dash" do <ide> expect(described_class.create("1.1-2")) <ide> .to be_detected_from("https://brew.sh/foo-arse-1.1-2.tar.gz") <add> expect(described_class.create("3.3.04-1")) <add> .to be_detected_from("https://brew.sh/3.3.04-1.tar.gz") <add> expect(described_class.create("1.2-20200102")) <add> .to be_detected_from("https://brew.sh/v1.2-20200102.tar.gz") <add> expect(described_class.create("3.6.6-0.2")) <add> .to be_detected_from("https://brew.sh/v3.6.6-0.2.tar.gz") <ide> end <ide> <ide> specify "version single digit" do <ide><path>Library/Homebrew/version.rb <ide> def self._parse(spec, detected_from_url:) <ide> # e.g. ruby-1.9.1-p243 <ide> StemParser.new(/[_-](#{NUMERIC_WITH_DOTS}-(?:p|rc|RC)?\d+)#{CONTENT_SUFFIX}?$/), <ide> <add> # Hyphenated versions without software-name prefix (e.g. brew-) <add> # e.g. v0.0.8-12.tar.gz <add> # e.g. 3.3.04-1.tar.gz <add> # e.g. v2.1-20210510.tar.gz <add> # e.g. 2020.11.11-3.tar.gz <add> # e.g. v3.6.6-0.2 <add> StemParser.new(/^v?(#{NUMERIC_WITH_DOTS}(?:-#{NUMERIC_WITH_OPTIONAL_DOTS})+)/), <add> <ide> # URL with no extension <ide> # e.g. https://waf.io/waf-1.8.12 <ide> # e.g. https://codeload.github.com/gsamokovarov/jump/tar.gz/v0.7.1
2
PHP
PHP
add type hints in schemashell
1d529c1dd2ede04ed84e18dd970b63f3555e1133
<ide><path>lib/Cake/Console/Command/SchemaShell.php <ide> protected function _loadSchema() { <ide> * @param string $table <ide> * @return void <ide> */ <del> protected function _create($Schema, $table = null) { <add> protected function _create(CakeSchema $Schema, $table = null) { <ide> $db = ConnectionManager::getDataSource($this->Schema->connection); <ide> <ide> $drop = $create = array(); <ide> protected function _update(&$Schema, $table = null) { <ide> * @param CakeSchema $Schema <ide> * @return void <ide> */ <del> protected function _run($contents, $event, &$Schema) { <add> protected function _run($contents, $event, CakeSchema $Schema) { <ide> if (empty($contents)) { <ide> $this->err(__d('cake_console', 'Sql could not be run')); <ide> return; <ide><path>lib/Cake/Test/Case/Console/Command/SchemaShellTest.php <ide> public function testUpdateWithTable() { <ide> ); <ide> $this->Shell->args = array('SchemaShellTest', 'articles'); <ide> $this->Shell->startup(); <del> $this->Shell->expects($this->any())->method('in')->will($this->returnValue('y')); <del> $this->Shell->expects($this->once())->method('_run') <add> $this->Shell->expects($this->any()) <add> ->method('in') <add> ->will($this->returnValue('y')); <add> $this->Shell->expects($this->once()) <add> ->method('_run') <ide> ->with($this->arrayHasKey('articles'), 'update', $this->isInstanceOf('CakeSchema')); <ide> <ide> $this->Shell->update();
2
Ruby
Ruby
add 6.4 expectation
754c950e3eaa1f89c1030ec93d73b8e5a16fdb7d
<ide><path>Library/Homebrew/os/mac/xcode.rb <ide> def latest_version <ide> when "10.7" then "4.6.3" <ide> when "10.8" then "5.1.1" <ide> when "10.9" then "6.2" <del> when "10.10" then "6.3.2" <add> when "10.10" then "6.4" <ide> when "10.11" then "7.0" <ide> else <ide> # Default to newest known version of Xcode for unreleased OSX versions.
1
Javascript
Javascript
fix un-highlight when there is no query
53672af0f79c64a88eb4280063e9df7e55f7144a
<ide><path>web/viewer.js <ide> var PDFFindController = { <ide> <ide> this.active = true; <ide> <del> if (!this.state.query) { <del> this.updateUIState(FindStates.FIND_FOUND); <del> return; <del> } <ide> this.updateUIState(FindStates.FIND_PENDING); <ide> <ide> if (this.dirtyMatch) { <ide> var PDFFindController = { <ide> } <ide> this.updatePage(i, true); <ide> } <del> if (!firstMatch) { <add> if (!firstMatch || !this.state.query) { <ide> this.updateUIState(FindStates.FIND_FOUND); <ide> } else { <ide> this.updateUIState(FindStates.FIND_NOTFOUND);
1
Python
Python
set version to v2.1.0a7.dev4
1831e1423d2e4d365baca2eb8d7358efa706b0aa
<ide><path>spacy/about.py <ide> # fmt: off <ide> <ide> __title__ = "spacy-nightly" <del>__version__ = "2.1.0a7.dev3" <add>__version__ = "2.1.0a7.dev4" <ide> __summary__ = "Industrial-strength Natural Language Processing (NLP) with Python and Cython" <ide> __uri__ = "https://spacy.io" <ide> __author__ = "Explosion AI"
1
Javascript
Javascript
handle iteration over identical obj values
47a2a9829f0a847bbee61cd142c43000d73ea98b
<ide><path>src/ng/directive/ngRepeat.js <ide> var ngRepeatDirective = ['$parse', '$animator', function($parse, $animator) { <ide> var animate = $animator($scope, $attr); <ide> var expression = $attr.ngRepeat; <ide> var match = expression.match(/^\s*(.+)\s+in\s+(.*?)\s*(\s+track\s+by\s+(.+)\s*)?$/), <del> trackByExp, trackByExpGetter, trackByIdFn, lhs, rhs, valueIdentifier, keyIdentifier, <add> trackByExp, trackByExpGetter, trackByIdFn, trackByIdArrayFn, trackByIdObjFn, lhs, rhs, valueIdentifier, keyIdentifier, <ide> hashFnLocals = {$id: hashKey}; <ide> <ide> if (!match) { <ide> var ngRepeatDirective = ['$parse', '$animator', function($parse, $animator) { <ide> return trackByExpGetter($scope, hashFnLocals); <ide> }; <ide> } else { <del> trackByIdFn = function(key, value) { <add> trackByIdArrayFn = function(key, value) { <ide> return hashKey(value); <ide> } <add> trackByIdObjFn = function(key) { <add> return key; <add> } <ide> } <ide> <ide> match = lhs.match(/^(?:([\$\w]+)|\(([\$\w]+)\s*,\s*([\$\w]+)\))$/); <ide> var ngRepeatDirective = ['$parse', '$animator', function($parse, $animator) { <ide> <ide> if (isArrayLike(collection)) { <ide> collectionKeys = collection; <add> trackByIdFn = trackByIdFn || trackByIdArrayFn; <ide> } else { <add> trackByIdFn = trackByIdFn || trackByIdObjFn; <ide> // if object, extract keys, sort them and use to determine order of iteration over obj props <ide> collectionKeys = []; <ide> for (key in collection) { <ide><path>test/ng/directive/ngRepeatSpec.js <ide> describe('ngRepeat', function() { <ide> expect(element.text()).toEqual('misko:swe|shyam:set|'); <ide> }); <ide> <add> it('should iterate over an object/map with identical values', function() { <add> element = $compile( <add> '<ul>' + <add> '<li ng-repeat="(key, value) in items">{{key}}:{{value}}|</li>' + <add> '</ul>')(scope); <add> scope.items = {age:20, wealth:20, prodname: "Bingo", dogname: "Bingo", codename: "20"}; <add> scope.$digest(); <add> expect(element.text()).toEqual('age:20|codename:20|dogname:Bingo|prodname:Bingo|wealth:20|'); <add> }); <ide> <ide> describe('track by', function() { <ide> it('should track using expression function', function() {
2
Javascript
Javascript
fix saving of xfa checkboxes. (bug 1726381)
6d2193a8121252520407a33c633611189c711688
<ide><path>src/core/xfa/template.js <ide> class CheckButton extends XFAObject { <ide> field.items.children[0][$toHTML]().html) || <ide> []; <ide> const exportedValue = { <del> on: (items[0] || "on").toString(), <del> off: (items[1] || "off").toString(), <add> on: (items[0] !== undefined ? items[0] : "on").toString(), <add> off: (items[1] !== undefined ? items[1] : "off").toString(), <ide> }; <ide> <ide> const value = (field.value && field.value[$text]()) || "off"; <ide> class CheckButton extends XFAObject { <ide> type, <ide> checked, <ide> xfaOn: exportedValue.on, <add> xfaOff: exportedValue.off, <ide> "aria-label": ariaLabel(field), <ide> }, <ide> }; <ide><path>src/display/xfa_layer.js <ide> class XfaLayer { <ide> break; <ide> } <ide> html.addEventListener("change", event => { <del> storage.setValue(id, { value: event.target.getAttribute("xfaOn") }); <add> storage.setValue(id, { <add> value: event.target.checked <add> ? event.target.getAttribute("xfaOn") <add> : event.target.getAttribute("xfaOff"), <add> }); <ide> }); <ide> } else { <ide> if (storedData.value !== null) {
2
Ruby
Ruby
remove charset.alias directly
3a4a529453c49572be1e0738cb4e9fd8efa75581
<ide><path>Library/Homebrew/cleaner.rb <ide> def initialize f <ide> # Clean the keg of formula @f <ide> def clean <ide> ObserverPathnameExtension.reset_counts! <add> <add> # Many formulae include 'lib/charset.alias', but it is not strictly needed <add> # and will conflict if more than one formula provides it <add> alias_path = @f.lib/'charset.alias' <add> alias_path.extend(ObserverPathnameExtension).unlink if alias_path.exist? <add> <ide> [@f.bin, @f.sbin, @f.lib].select{ |d| d.exist? }.each{ |d| clean_dir d } <ide> <ide> # Get rid of any info 'dir' files, so they don't conflict at the link stage <ide> def clean <ide> def prune <ide> dirs = [] <ide> symlinks = [] <del> <ide> @f.prefix.find do |path| <ide> if @f.skip_clean? path <ide> Find.prune <ide> def clean_dir d <ide> next <ide> elsif path.extname == '.la' <ide> path.unlink <del> elsif path == @f.lib+'charset.alias' <del> # Many formulae symlink this file, but it is not strictly needed <del> path.unlink <ide> else <ide> clean_file_permissions(path) <ide> end
1
Text
Text
add @empty changelog line
134df8712b28fdee7f83d2793dafeb6950b79f39
<ide><path>CHANGELOG-5.4.md <ide> - Added support for attaching an image to Slack attachments `$attachment->image($url)`([#18664](https://github.com/laravel/framework/pull/18664)) <ide> - Added `Validator::extendDependent()` to allow adding custom rules that depend on other fields ([#18654](https://github.com/laravel/framework/pull/18654)) <ide> - Added support for `--parent` option on `make:controller` ([#18606](https://github.com/laravel/framework/pull/18606)) <add>- Added `@empty()` directive ([#18738](https://github.com/laravel/framework/pull/18738)) <ide> <ide> ### Fixed <ide> - Fixed an issue with `Collection::groupBy()` when the provided value is a boolean ([#18674](https://github.com/laravel/framework/pull/18674))
1
Python
Python
set version to v2.2.2.dev5
8b9954d1b7649cac351f87001f0283a52aef14e6
<ide><path>spacy/about.py <ide> # fmt: off <ide> __title__ = "spacy" <del>__version__ = "2.2.2.dev4" <add>__version__ = "2.2.2.dev5" <ide> __release__ = True <ide> __download_url__ = "https://github.com/explosion/spacy-models/releases/download" <ide> __compatibility__ = "https://raw.githubusercontent.com/explosion/spacy-models/master/compatibility.json"
1
Text
Text
remove usage of global grunt-cli
f876ab71913e17e9126baad19ab795f28b61bfe6
<ide><path>CONTRIBUTING.md <ide> Before you submit your pull request consider the following guidelines: <ide> * Run the AngularJS [unit][developers.tests-unit] and [E2E test][developers.tests-e2e] suites, and ensure that all tests <ide> pass. It is generally sufficient to run the tests only on Chrome, as our Travis integration will <ide> run the tests on all supported browsers. <del>* Run `grunt eslint` to check that you have followed the automatically enforced coding rules <add>* Run `yarn grunt eslint` to check that you have followed the automatically enforced coding rules <ide> * Commit your changes using a descriptive commit message that follows our <ide> [commit message conventions][developers.commits]. Adherence to the <ide> [commit message conventions][developers.commits] is required, because release notes are <ide> Before you submit your pull request consider the following guidelines: <ide> * Before creating the Pull Request, package and run all tests a last time: <ide> <ide> ```shell <del> grunt test <add> yarn grunt test <ide> ``` <ide> <ide> * Push your branch to GitHub: <ide><path>DEVELOPERS.md <ide> machine: <ide> to be installed and included in your <ide> [PATH](http://docs.oracle.com/javase/tutorial/essential/environment/paths.html) variable. <ide> <del>* [Grunt](http://gruntjs.com): We use Grunt as our build system. Install the grunt command-line tool <del> globally with: <del> <del> ```shell <del> yarn global add grunt-cli <del> ``` <add>* [Grunt](http://gruntjs.com): We use Grunt as our build system. We're using it as a local dependency, <add> but you can also add the grunt command-line tool globally (with `yarn global add grunt-cli`), which allows <add> you to leave out the `yarn` prefix for all our grunt commands. <ide> <ide> ### Forking AngularJS on Github <ide> <ide> git remote add upstream "https://github.com/angular/angular.js.git" <ide> yarn install <ide> <ide> # Build AngularJS (which will install `bower` dependencies automatically): <del>grunt package <add>yarn grunt package <ide> ``` <ide> <ide> **Note:** If you're using Windows, you must use an elevated command prompt (right click, run as <del>Administrator). This is because `grunt package` creates some symbolic links. <del> <del>**Note:** If you're using Linux, and `yarn install` fails with the message <del>'Please try running this command again as root/Administrator.', you may need to globally install <del>`grunt` and `bower`: <del> <del>```shell <del>sudo yarn global add grunt-cli <del>sudo yarn global add bower <del>``` <add>Administrator). This is because `yarn grunt package` creates some symbolic links. <ide> <ide> The build output is in the `build` directory. It consists of the following files and <ide> directories: <ide> HTTP server. For this purpose, we have made available a local web server based o <ide> <ide> 1. To start the web server, run: <ide> ```shell <del> grunt webserver <add> yarn grunt webserver <ide> ``` <ide> <ide> 2. To access the local server, enter the following URL into your web browser: <ide> We write unit and integration tests with Jasmine and execute them with Karma. To <ide> tests once on Chrome run: <ide> <ide> ```shell <del>grunt test:unit <add>yarn grunt test:unit <ide> ``` <ide> <ide> To run the tests on other browsers (Chrome, ChromeCanary, Firefox and Safari are pre-configured) use: <ide> <ide> ```shell <del>grunt test:unit --browsers=Chrome,Firefox <add>yarn grunt test:unit --browsers=Chrome,Firefox <ide> ``` <ide> <ide> **Note:** there should be _no spaces between browsers_. `Chrome, Firefox` is INVALID. <ide> For example, to run the whole unit test suite: <ide> <ide> ```shell <ide> # Browserstack <del>grunt test:unit --browsers=BS_Chrome,BS_Firefox,BS_Safari,BS_IE_9,BS_IE_10,BS_IE_11,BS_EDGE,BS_iOS_8,BS_iOS_9,BS_iOS_10 <add>yarn grunt test:unit --browsers=BS_Chrome,BS_Firefox,BS_Safari,BS_IE_9,BS_IE_10,BS_IE_11,BS_EDGE,BS_iOS_8,BS_iOS_9,BS_iOS_10 <ide> # Saucelabs <del>grunt test:unit --browsers=BS_Chrome,BS_Firefox,BS_Safari,BS_IE_9,BS_IE_10,BS_IE_11,BS_EDGE,BS_iOS_8,BS_iOS_9,BS_iOS_10 <add>yarn grunt test:unit --browsers=BS_Chrome,BS_Firefox,BS_Safari,BS_IE_9,BS_IE_10,BS_IE_11,BS_EDGE,BS_iOS_8,BS_iOS_9,BS_iOS_10 <ide> ``` <ide> <ide> Running these commands requires you to set up [Karma Browserstack][karma-browserstack] or <ide> source or test files change. To execute tests in this mode run: <ide> 1. To start the Karma server, capture Chrome browser and run unit tests, run: <ide> <ide> ```shell <del> grunt autotest <add> yarn grunt autotest <ide> ``` <ide> <ide> 2. To capture more browsers, open this URL in the desired browser (URL might be different if you <ide> source or test files change. To execute tests in this mode run: <ide> To learn more about all of the preconfigured Grunt tasks run: <ide> <ide> ```shell <del>grunt --help <add>yarn grunt --help <ide> ``` <ide> <ide> <ide> grunt --help <ide> AngularJS's end to end tests are run with Protractor. Simply run: <ide> <ide> ```shell <del>grunt test:e2e <add>yarn grunt test:e2e <ide> ``` <ide> <ide> This will start the webserver and run the tests on Chrome. <ide> documentation generation tool [Dgeni][dgeni]. <ide> The docs can be built from scratch using grunt: <ide> <ide> ```shell <del>grunt docs <add>yarn grunt docs <ide> ``` <ide> <ide> This defers the doc-building task to `gulp`. <ide> Note that the docs app is using the local build files to run. This means you mig <ide> the build: <ide> <ide> ```shell <del>grunt build <add>yarn grunt build <ide> ``` <ide> <ide> (This is also necessary if you are making changes to minErrors).
2
Python
Python
update tokenization docstrings for #328
ab49fafc047b13d215f1857b3b638cabf19c3fe8
<ide><path>pytorch_transformers/tokenization_bert.py <ide> class BertTokenizer(PreTrainedTokenizer): <ide> <ide> def __init__(self, vocab_file, do_lower_case=True, do_basic_tokenize=True, never_split=None, <ide> unk_token="[UNK]", sep_token="[SEP]", pad_token="[PAD]", cls_token="[CLS]", <del> mask_token="[MASK]", **kwargs): <add> mask_token="[MASK]", tokenize_chinese_chars=True, **kwargs): <ide> """Constructs a BertTokenizer. <ide> <ide> Args: <del> vocab_file: Path to a one-wordpiece-per-line vocabulary file <del> do_lower_case: Whether to lower case the input <del> Only has an effect when do_wordpiece_only=False <del> do_basic_tokenize: Whether to do basic tokenization before wordpiece. <del> never_split: List of tokens which will never be split during tokenization. <del> Only has an effect when do_wordpiece_only=False <add> **vocab_file**: Path to a one-wordpiece-per-line vocabulary file <add> **do_lower_case**: (`optional`) boolean (default True) <add> Whether to lower case the input <add> Only has an effect when do_basic_tokenize=True <add> **do_basic_tokenize**: (`optional`) boolean (default True) <add> Whether to do basic tokenization before wordpiece. <add> **never_split**: (`optional`) list of string <add> List of tokens which will never be split during tokenization. <add> Only has an effect when do_basic_tokenize=True <add> **tokenize_chinese_chars**: (`optional`) boolean (default True) <add> Whether to tokenize Chinese characters. <add> This should likely be desactivated for Japanese: <add> see: https://github.com/huggingface/pytorch-pretrained-BERT/issues/328 <ide> """ <ide> super(BertTokenizer, self).__init__(unk_token=unk_token, sep_token=sep_token, <ide> pad_token=pad_token, cls_token=cls_token, <ide> def __init__(self, vocab_file, do_lower_case=True, do_basic_tokenize=True, never <ide> [(ids, tok) for tok, ids in self.vocab.items()]) <ide> self.do_basic_tokenize = do_basic_tokenize <ide> if do_basic_tokenize: <del> self.basic_tokenizer = BasicTokenizer(do_lower_case=do_lower_case, <del> never_split=never_split) <add> self.basic_tokenizer = BasicTokenizer(do_lower_case=do_lower_case, <add> never_split=never_split, <add> tokenize_chinese_chars=tokenize_chinese_chars) <ide> self.wordpiece_tokenizer = WordpieceTokenizer(vocab=self.vocab, unk_token=self.unk_token) <ide> <ide> @property <ide> def from_pretrained(cls, pretrained_model_name_or_path, *inputs, **kwargs): <ide> class BasicTokenizer(object): <ide> """Runs basic tokenization (punctuation splitting, lower casing, etc.).""" <ide> <del> def __init__(self, <del> do_lower_case=True, <del> never_split=None): <del> """Constructs a BasicTokenizer. <add> def __init__(self, do_lower_case=True, never_split=None, tokenize_chinese_chars=True): <add> """ Constructs a BasicTokenizer. <ide> <ide> Args: <del> do_lower_case: Whether to lower case the input. <add> **do_lower_case**: Whether to lower case the input. <add> **never_split**: (`optional`) list of str <add> Kept for backward compatibility purposes. <add> Now implemented directly at the base class level (see :func:`PreTrainedTokenizer.tokenize`) <add> List of token not to split. <add> **tokenize_chinese_chars**: (`optional`) boolean (default True) <add> Whether to tokenize Chinese characters. <add> This should likely be desactivated for Japanese: <add> see: https://github.com/huggingface/pytorch-pretrained-BERT/issues/328 <ide> """ <ide> if never_split is None: <ide> never_split = [] <ide> self.do_lower_case = do_lower_case <ide> self.never_split = never_split <add> self.tokenize_chinese_chars = tokenize_chinese_chars <ide> <del> def tokenize(self, text, never_split=None, tokenize_chinese_chars=True): <del> """Tokenizes a piece of text.""" <add> def tokenize(self, text, never_split=None): <add> """ Basic Tokenization of a piece of text. <add> Split on "white spaces" only, for sub-word tokenization, see WordPieceTokenizer. <add> <add> Args: <add> **never_split**: (`optional`) list of str <add> Kept for backward compatibility purposes. <add> Now implemented directly at the base class level (see :func:`PreTrainedTokenizer.tokenize`) <add> List of token not to split. <add> """ <ide> never_split = self.never_split + (never_split if never_split is not None else []) <ide> text = self._clean_text(text) <ide> # This was added on November 1st, 2018 for the multilingual and Chinese <ide> def tokenize(self, text, never_split=None, tokenize_chinese_chars=True): <ide> # and generally don't have any Chinese data in them (there are Chinese <ide> # characters in the vocabulary because Wikipedia does have some Chinese <ide> # words in the English Wikipedia.). <del> if tokenize_chinese_chars: <add> if self.tokenize_chinese_chars: <ide> text = self._tokenize_chinese_chars(text) <ide> orig_tokens = whitespace_tokenize(text) <ide> split_tokens = []
1
Mixed
Go
create extpoint for graphdrivers
b78e4216a2a97704b664da34d526da1f7e080849
<ide><path>daemon/graphdriver/driver.go <ide> func GetDriver(name, home string, options []string) (Driver, error) { <ide> if initFunc, exists := drivers[name]; exists { <ide> return initFunc(filepath.Join(home, name), options) <ide> } <add> if pluginDriver, err := lookupPlugin(name, home, options); err == nil { <add> return pluginDriver, nil <add> } <ide> logrus.Errorf("Failed to GetDriver graph %s %s", name, home) <ide> return nil, ErrNotSupported <ide> } <ide><path>daemon/graphdriver/plugin.go <add>// +build experimental <add>// +build daemon <add> <add>package graphdriver <add> <add>import ( <add> "fmt" <add> "io" <add> <add> "github.com/docker/docker/pkg/plugins" <add>) <add> <add>type pluginClient interface { <add> // Call calls the specified method with the specified arguments for the plugin. <add> Call(string, interface{}, interface{}) error <add> // Stream calls the specified method with the specified arguments for the plugin and returns the response IO stream <add> Stream(string, interface{}) (io.ReadCloser, error) <add> // SendFile calls the specified method, and passes through the IO stream <add> SendFile(string, io.Reader, interface{}) error <add>} <add> <add>func lookupPlugin(name, home string, opts []string) (Driver, error) { <add> pl, err := plugins.Get(name, "GraphDriver") <add> if err != nil { <add> return nil, fmt.Errorf("Error looking up graphdriver plugin %s: %v", name, err) <add> } <add> return newPluginDriver(name, home, opts, pl.Client) <add>} <add> <add>func newPluginDriver(name, home string, opts []string, c pluginClient) (Driver, error) { <add> proxy := &graphDriverProxy{name, c} <add> return proxy, proxy.Init(home, opts) <add>} <ide><path>daemon/graphdriver/plugin_unsupported.go <add>// +build !experimental <add> <add>package graphdriver <add> <add>func lookupPlugin(name, home string, opts []string) (Driver, error) { <add> return nil, ErrNotSupported <add>} <ide><path>daemon/graphdriver/proxy.go <add>// +build experimental <add>// +build daemon <add> <add>package graphdriver <add> <add>import ( <add> "errors" <add> "fmt" <add> <add> "github.com/docker/docker/pkg/archive" <add>) <add> <add>type graphDriverProxy struct { <add> name string <add> client pluginClient <add>} <add> <add>type graphDriverRequest struct { <add> ID string `json:",omitempty"` <add> Parent string `json:",omitempty"` <add> MountLabel string `json:",omitempty"` <add>} <add> <add>type graphDriverResponse struct { <add> Err string `json:",omitempty"` <add> Dir string `json:",omitempty"` <add> Exists bool `json:",omitempty"` <add> Status [][2]string `json:",omitempty"` <add> Changes []archive.Change `json:",omitempty"` <add> Size int64 `json:",omitempty"` <add> Metadata map[string]string `json:",omitempty"` <add>} <add> <add>type graphDriverInitRequest struct { <add> Home string <add> Opts []string <add>} <add> <add>func (d *graphDriverProxy) Init(home string, opts []string) error { <add> args := &graphDriverInitRequest{ <add> Home: home, <add> Opts: opts, <add> } <add> var ret graphDriverResponse <add> if err := d.client.Call("GraphDriver.Init", args, &ret); err != nil { <add> return err <add> } <add> if ret.Err != "" { <add> return errors.New(ret.Err) <add> } <add> return nil <add>} <add> <add>func (d *graphDriverProxy) String() string { <add> return d.name <add>} <add> <add>func (d *graphDriverProxy) Create(id, parent string) error { <add> args := &graphDriverRequest{ <add> ID: id, <add> Parent: parent, <add> } <add> var ret graphDriverResponse <add> if err := d.client.Call("GraphDriver.Create", args, &ret); err != nil { <add> return err <add> } <add> if ret.Err != "" { <add> return errors.New(ret.Err) <add> } <add> return nil <add>} <add> <add>func (d *graphDriverProxy) Remove(id string) error { <add> args := &graphDriverRequest{ID: id} <add> var ret graphDriverResponse <add> if err := d.client.Call("GraphDriver.Remove", args, &ret); err != nil { <add> return err <add> } <add> if ret.Err != "" { <add> return errors.New(ret.Err) <add> } <add> return nil <add>} <add> <add>func (d *graphDriverProxy) Get(id, mountLabel string) (string, error) { <add> args := &graphDriverRequest{ <add> ID: id, <add> MountLabel: mountLabel, <add> } <add> var ret graphDriverResponse <add> if err := d.client.Call("GraphDriver.Get", args, &ret); err != nil { <add> return "", err <add> } <add> var err error <add> if ret.Err != "" { <add> err = errors.New(ret.Err) <add> } <add> return ret.Dir, err <add>} <add> <add>func (d *graphDriverProxy) Put(id string) error { <add> args := &graphDriverRequest{ID: id} <add> var ret graphDriverResponse <add> if err := d.client.Call("GraphDriver.Put", args, &ret); err != nil { <add> return err <add> } <add> if ret.Err != "" { <add> return errors.New(ret.Err) <add> } <add> return nil <add>} <add> <add>func (d *graphDriverProxy) Exists(id string) bool { <add> args := &graphDriverRequest{ID: id} <add> var ret graphDriverResponse <add> if err := d.client.Call("GraphDriver.Exists", args, &ret); err != nil { <add> return false <add> } <add> return ret.Exists <add>} <add> <add>func (d *graphDriverProxy) Status() [][2]string { <add> args := &graphDriverRequest{} <add> var ret graphDriverResponse <add> if err := d.client.Call("GraphDriver.Status", args, &ret); err != nil { <add> return nil <add> } <add> return ret.Status <add>} <add> <add>func (d *graphDriverProxy) GetMetadata(id string) (map[string]string, error) { <add> args := &graphDriverRequest{ <add> ID: id, <add> } <add> var ret graphDriverResponse <add> if err := d.client.Call("GraphDriver.GetMetadata", args, &ret); err != nil { <add> return nil, err <add> } <add> if ret.Err != "" { <add> return nil, errors.New(ret.Err) <add> } <add> return ret.Metadata, nil <add>} <add> <add>func (d *graphDriverProxy) Cleanup() error { <add> args := &graphDriverRequest{} <add> var ret graphDriverResponse <add> if err := d.client.Call("GraphDriver.Cleanup", args, &ret); err != nil { <add> return nil <add> } <add> if ret.Err != "" { <add> return errors.New(ret.Err) <add> } <add> return nil <add>} <add> <add>func (d *graphDriverProxy) Diff(id, parent string) (archive.Archive, error) { <add> args := &graphDriverRequest{ <add> ID: id, <add> Parent: parent, <add> } <add> body, err := d.client.Stream("GraphDriver.Diff", args) <add> if err != nil { <add> body.Close() <add> return nil, err <add> } <add> return archive.Archive(body), nil <add>} <add> <add>func (d *graphDriverProxy) Changes(id, parent string) ([]archive.Change, error) { <add> args := &graphDriverRequest{ <add> ID: id, <add> Parent: parent, <add> } <add> var ret graphDriverResponse <add> if err := d.client.Call("GraphDriver.Changes", args, &ret); err != nil { <add> return nil, err <add> } <add> if ret.Err != "" { <add> return nil, errors.New(ret.Err) <add> } <add> <add> return ret.Changes, nil <add>} <add> <add>func (d *graphDriverProxy) ApplyDiff(id, parent string, diff archive.Reader) (int64, error) { <add> var ret graphDriverResponse <add> if err := d.client.SendFile(fmt.Sprintf("GraphDriver.ApplyDiff?id=%s&parent=%s", id, parent), diff, &ret); err != nil { <add> return -1, err <add> } <add> if ret.Err != "" { <add> return -1, errors.New(ret.Err) <add> } <add> return ret.Size, nil <add>} <add> <add>func (d *graphDriverProxy) DiffSize(id, parent string) (int64, error) { <add> args := &graphDriverRequest{ <add> ID: id, <add> Parent: parent, <add> } <add> var ret graphDriverResponse <add> if err := d.client.Call("GraphDriver.DiffSize", args, &ret); err != nil { <add> return -1, err <add> } <add> if ret.Err != "" { <add> return -1, errors.New(ret.Err) <add> } <add> return ret.Size, nil <add>} <ide><path>experimental/plugins_graphdriver.md <add># Experimental: Docker graph driver plugins <add> <add>Docker graph driver plugins enable admins to use an external/out-of-process <add>graph driver for use with Docker engine. This is an alternative to using the <add>built-in storage drivers, such as aufs/overlay/devicemapper/btrfs. <add> <add>A graph driver plugin is used for image and container fs storage, as such <add>the plugin must be started and available for connections prior to Docker Engine <add>being started. <add> <add># Write a graph driver plugin <add> <add>See the [plugin documentation](/docs/extend/plugins.md) for detailed information <add>on the underlying plugin protocol. <add> <add> <add>## Graph Driver plugin protocol <add> <add>If a plugin registers itself as a `GraphDriver` when activated, then it is <add>expected to provide the rootfs for containers as well as image layer storage. <add> <add>### /GraphDriver.Init <add> <add>**Request**: <add>``` <add>{ <add> "Home": "/graph/home/path", <add> "Opts": [] <add>} <add>``` <add> <add>Initialize the graph driver plugin with a home directory and array of options. <add>Plugins are not required to accept these options as the Docker Engine does not <add>require that the plugin use this path or options, they are only being passed <add>through from the user. <add> <add>**Response**: <add>``` <add>{ <add> "Err": null <add>} <add>``` <add> <add>Respond with a string error if an error occurred. <add> <add> <add>### /GraphDriver.Create <add> <add>**Request**: <add>``` <add>{ <add> "ID": "46fe8644f2572fd1e505364f7581e0c9dbc7f14640bd1fb6ce97714fb6fc5187", <add> "Parent": "2cd9c322cb78a55e8212aa3ea8425a4180236d7106938ec921d0935a4b8ca142" <add>} <add>``` <add> <add>Create a new, empty, filesystem layer with the specified `ID` and `Parent`. <add>`Parent` may be an empty string, which would indicate that there is no parent <add>layer. <add> <add>**Response**: <add>``` <add>{ <add> "Err: null <add>} <add>``` <add> <add>Respond with a string error if an error occurred. <add> <add> <add>### /GraphDriver.Remove <add> <add>**Request**: <add>``` <add>{ <add> "ID": "46fe8644f2572fd1e505364f7581e0c9dbc7f14640bd1fb6ce97714fb6fc5187" <add>} <add>``` <add> <add>Remove the filesystem layer with this given `ID`. <add> <add>**Response**: <add>``` <add>{ <add> "Err: null <add>} <add>``` <add> <add>Respond with a string error if an error occurred. <add> <add>### /GraphDriver.Get <add> <add>**Request**: <add>``` <add>{ <add> "ID": "46fe8644f2572fd1e505364f7581e0c9dbc7f14640bd1fb6ce97714fb6fc5187" <add> "MountLabel": "" <add>} <add>``` <add> <add>Get the mountpoint for the layered filesystem referred to by the given `ID`. <add> <add>**Response**: <add>``` <add>{ <add> "Dir": "/var/mygraph/46fe8644f2572fd1e505364f7581e0c9dbc7f14640bd1fb6ce97714fb6fc5187", <add> "Err": "" <add>} <add>``` <add> <add>Respond with the absolute path to the mounted layered filesystem. <add>Respond with a string error if an error occurred. <add> <add>### /GraphDriver.Put <add> <add>**Request**: <add>``` <add>{ <add> "ID": "46fe8644f2572fd1e505364f7581e0c9dbc7f14640bd1fb6ce97714fb6fc5187" <add>} <add>``` <add> <add>Release the system resources for the specified `ID`, such as unmounting the <add>filesystem layer. <add> <add>**Response**: <add>``` <add>{ <add> "Err: null <add>} <add>``` <add> <add>Respond with a string error if an error occurred. <add> <add>### /GraphDriver.Exists <add> <add>**Request**: <add>``` <add>{ <add> "ID": "46fe8644f2572fd1e505364f7581e0c9dbc7f14640bd1fb6ce97714fb6fc5187" <add>} <add>``` <add> <add>Determine if a filesystem layer with the specified `ID` exists. <add> <add>**Response**: <add>``` <add>{ <add> "Exists": true <add>} <add>``` <add> <add>Respond with a boolean for whether or not the filesystem layer with the specified <add>`ID` exists. <add> <add>### /GraphDriver.Status <add> <add>**Request**: <add>``` <add>{} <add>``` <add> <add>Get low-level diagnostic information about the graph driver. <add> <add>**Response**: <add>``` <add>{ <add> "Status": [[]] <add>} <add>``` <add> <add>Respond with a 2-D array with key/value pairs for the underlying status <add>information. <add> <add> <add>### /GraphDriver.GetMetadata <add> <add>**Request**: <add>``` <add>{ <add> "ID": "46fe8644f2572fd1e505364f7581e0c9dbc7f14640bd1fb6ce97714fb6fc5187" <add>} <add>``` <add> <add>Get low-level diagnostic information about the layered filesystem with the <add>with the specified `ID` <add> <add>**Response**: <add>``` <add>{ <add> "Metadata": {}, <add> "Err": null <add>} <add>``` <add> <add>Respond with a set of key/value pairs containing the low-level diagnostic <add>information about the layered filesystem. <add>Respond with a string error if an error occurred. <add> <add>### /GraphDriver.Cleanup <add> <add>**Request**: <add>``` <add>{} <add>``` <add> <add>Perform neccessary tasks to release resources help by the plugin, for example <add>unmounting all the layered file systems. <add> <add>**Response**: <add>``` <add>{ <add> "Err: null <add>} <add>``` <add> <add>Respond with a string error if an error occurred. <add> <add> <add>### /GraphDriver.Diff <add> <add>**Request**: <add>``` <add>{ <add> "ID": "46fe8644f2572fd1e505364f7581e0c9dbc7f14640bd1fb6ce97714fb6fc5187", <add> "Parent": "2cd9c322cb78a55e8212aa3ea8425a4180236d7106938ec921d0935a4b8ca142" <add>} <add>``` <add> <add>Get an archive of the changes between the filesystem layers specified by the `ID` <add>and `Parent`. `Parent` may be an empty string, in which case there is no parent. <add> <add>**Response**: <add>``` <add>{{ TAR STREAM }} <add>``` <add> <add>### /GraphDriver.Changes <add> <add>**Request**: <add>``` <add>{ <add> "ID": "46fe8644f2572fd1e505364f7581e0c9dbc7f14640bd1fb6ce97714fb6fc5187", <add> "Parent": "2cd9c322cb78a55e8212aa3ea8425a4180236d7106938ec921d0935a4b8ca142" <add>} <add>``` <add> <add>Get a list of changes between the filesystem layers specified by the `ID` and <add>`Parent`. `Parent` may be an empty string, in which case there is no parent. <add> <add>**Response**: <add>``` <add>{ <add> "Changes": [{}], <add> "Err": null <add>} <add>``` <add> <add>Responds with a list of changes. The structure of a change is: <add>``` <add> "Path": "/some/path", <add> "Kind": 0, <add>``` <add> <add>Where teh `Path` is the filesystem path within the layered filesystem that is <add>changed and `Kind` is an integer specifying the type of change that occurred: <add> <add>- 0 - Modified <add>- 1 - Added <add>- 2 - Deleted <add> <add>Respond with a string error if an error occurred. <add> <add>### /GraphDriver.ApplyDiff <add> <add>**Request**: <add>``` <add>{{ TAR STREAM }} <add>``` <add> <add>Extract the changeset from the given diff into the layer with the specified `ID` <add>and `Parent` <add> <add>**Query Parameters**: <add> <add>- id (required)- the `ID` of the new filesystem layer to extract the diff to <add>- parent (required)- the `Parent` of the given `ID` <add> <add>**Response**: <add>``` <add>{ <add> "Size": 512366, <add> "Err": null <add>} <add>``` <add> <add>Respond with the size of the new layer in bytes. <add>Respond with a string error if an error occurred. <add> <add>### /GraphDriver.DiffSize <add> <add>**Request**: <add>``` <add>{ <add> "ID": "46fe8644f2572fd1e505364f7581e0c9dbc7f14640bd1fb6ce97714fb6fc5187", <add> "Parent": "2cd9c322cb78a55e8212aa3ea8425a4180236d7106938ec921d0935a4b8ca142" <add>} <add>``` <add> <add>Calculate the changes between the specified `ID` <add> <add>**Response**: <add>``` <add>{ <add> "Size": 512366, <add> "Err": null <add>} <add>``` <add> <add>Respond with the size changes between the specified `ID` and `Parent` <add>Respond with a string error if an error occurred. <ide><path>integration-cli/check_test.go <ide> package main <ide> <ide> import ( <add> "fmt" <ide> "testing" <ide> <add> "github.com/docker/docker/pkg/reexec" <ide> "github.com/go-check/check" <ide> ) <ide> <ide> func Test(t *testing.T) { <add> reexec.Init() // This is required for external graphdriver tests <add> <add> if !isLocalDaemon { <add> fmt.Println("INFO: Testing against a remote daemon") <add> } else { <add> fmt.Println("INFO: Testing against a local daemon") <add> } <add> <ide> check.TestingT(t) <ide> } <ide> <ide><path>integration-cli/docker_cli_external_graphdriver_unix_test.go <add>// +build experimental <add>// +build !windows <add> <add>package main <add> <add>import ( <add> "encoding/json" <add> "fmt" <add> "io" <add> "io/ioutil" <add> "net/http" <add> "net/http/httptest" <add> "os" <add> "strings" <add> <add> "github.com/docker/docker/daemon/graphdriver" <add> "github.com/docker/docker/daemon/graphdriver/vfs" <add> "github.com/docker/docker/pkg/archive" <add> "github.com/go-check/check" <add>) <add> <add>func init() { <add> check.Suite(&DockerExternalGraphdriverSuite{ <add> ds: &DockerSuite{}, <add> }) <add>} <add> <add>type DockerExternalGraphdriverSuite struct { <add> server *httptest.Server <add> ds *DockerSuite <add> d *Daemon <add> ec *graphEventsCounter <add>} <add> <add>type graphEventsCounter struct { <add> activations int <add> creations int <add> removals int <add> gets int <add> puts int <add> stats int <add> cleanups int <add> exists int <add> init int <add> metadata int <add> diff int <add> applydiff int <add> changes int <add> diffsize int <add>} <add> <add>func (s *DockerExternalGraphdriverSuite) SetUpTest(c *check.C) { <add> s.d = NewDaemon(c) <add> s.ec = &graphEventsCounter{} <add>} <add> <add>func (s *DockerExternalGraphdriverSuite) TearDownTest(c *check.C) { <add> s.d.Stop() <add> s.ds.TearDownTest(c) <add>} <add> <add>func (s *DockerExternalGraphdriverSuite) SetUpSuite(c *check.C) { <add> mux := http.NewServeMux() <add> s.server = httptest.NewServer(mux) <add> <add> type graphDriverRequest struct { <add> ID string `json:",omitempty"` <add> Parent string `json:",omitempty"` <add> MountLabel string `json:",omitempty"` <add> } <add> <add> type graphDriverResponse struct { <add> Err error `json:",omitempty"` <add> Dir string `json:",omitempty"` <add> Exists bool `json:",omitempty"` <add> Status [][2]string `json:",omitempty"` <add> Metadata map[string]string `json:",omitempty"` <add> Changes []archive.Change `json:",omitempty"` <add> Size int64 `json:",omitempty"` <add> } <add> <add> respond := func(w http.ResponseWriter, data interface{}) { <add> w.Header().Set("Content-Type", "appplication/vnd.docker.plugins.v1+json") <add> switch t := data.(type) { <add> case error: <add> fmt.Fprintln(w, fmt.Sprintf(`{"Err": %s}`, t.Error())) <add> case string: <add> fmt.Fprintln(w, t) <add> default: <add> json.NewEncoder(w).Encode(&data) <add> } <add> } <add> <add> base, err := ioutil.TempDir("", "external-graph-test") <add> c.Assert(err, check.IsNil) <add> vfsProto, err := vfs.Init(base, []string{}) <add> if err != nil { <add> c.Fatalf("error initializing graph driver: %v", err) <add> } <add> driver := graphdriver.NaiveDiffDriver(vfsProto) <add> <add> mux.HandleFunc("/Plugin.Activate", func(w http.ResponseWriter, r *http.Request) { <add> s.ec.activations++ <add> respond(w, `{"Implements": ["GraphDriver"]}`) <add> }) <add> <add> mux.HandleFunc("/GraphDriver.Init", func(w http.ResponseWriter, r *http.Request) { <add> s.ec.init++ <add> respond(w, "{}") <add> }) <add> <add> mux.HandleFunc("/GraphDriver.Create", func(w http.ResponseWriter, r *http.Request) { <add> s.ec.creations++ <add> <add> var req graphDriverRequest <add> if err := json.NewDecoder(r.Body).Decode(&req); err != nil { <add> http.Error(w, err.Error(), 500) <add> return <add> } <add> if err := driver.Create(req.ID, req.Parent); err != nil { <add> respond(w, err) <add> return <add> } <add> respond(w, "{}") <add> }) <add> <add> mux.HandleFunc("/GraphDriver.Remove", func(w http.ResponseWriter, r *http.Request) { <add> s.ec.removals++ <add> <add> var req graphDriverRequest <add> if err := json.NewDecoder(r.Body).Decode(&req); err != nil { <add> http.Error(w, err.Error(), 500) <add> return <add> } <add> <add> if err := driver.Remove(req.ID); err != nil { <add> respond(w, err) <add> return <add> } <add> respond(w, "{}") <add> }) <add> <add> mux.HandleFunc("/GraphDriver.Get", func(w http.ResponseWriter, r *http.Request) { <add> s.ec.gets++ <add> <add> var req graphDriverRequest <add> if err := json.NewDecoder(r.Body).Decode(&req); err != nil { <add> http.Error(w, err.Error(), 500) <add> } <add> <add> dir, err := driver.Get(req.ID, req.MountLabel) <add> if err != nil { <add> respond(w, err) <add> return <add> } <add> respond(w, &graphDriverResponse{Dir: dir}) <add> }) <add> <add> mux.HandleFunc("/GraphDriver.Put", func(w http.ResponseWriter, r *http.Request) { <add> s.ec.puts++ <add> <add> var req graphDriverRequest <add> if err := json.NewDecoder(r.Body).Decode(&req); err != nil { <add> http.Error(w, err.Error(), 500) <add> return <add> } <add> <add> if err := driver.Put(req.ID); err != nil { <add> respond(w, err) <add> return <add> } <add> respond(w, "{}") <add> }) <add> <add> mux.HandleFunc("/GraphDriver.Exists", func(w http.ResponseWriter, r *http.Request) { <add> s.ec.exists++ <add> <add> var req graphDriverRequest <add> if err := json.NewDecoder(r.Body).Decode(&req); err != nil { <add> http.Error(w, err.Error(), 500) <add> return <add> } <add> respond(w, &graphDriverResponse{Exists: driver.Exists(req.ID)}) <add> }) <add> <add> mux.HandleFunc("/GraphDriver.Status", func(w http.ResponseWriter, r *http.Request) { <add> s.ec.stats++ <add> respond(w, `{"Status":{}}`) <add> }) <add> <add> mux.HandleFunc("/GraphDriver.Cleanup", func(w http.ResponseWriter, r *http.Request) { <add> s.ec.cleanups++ <add> err := driver.Cleanup() <add> if err != nil { <add> respond(w, err) <add> return <add> } <add> respond(w, `{}`) <add> }) <add> <add> mux.HandleFunc("/GraphDriver.GetMetadata", func(w http.ResponseWriter, r *http.Request) { <add> s.ec.metadata++ <add> <add> var req graphDriverRequest <add> if err := json.NewDecoder(r.Body).Decode(&req); err != nil { <add> http.Error(w, err.Error(), 500) <add> return <add> } <add> <add> data, err := driver.GetMetadata(req.ID) <add> if err != nil { <add> respond(w, err) <add> return <add> } <add> respond(w, &graphDriverResponse{Metadata: data}) <add> }) <add> <add> mux.HandleFunc("/GraphDriver.Diff", func(w http.ResponseWriter, r *http.Request) { <add> s.ec.diff++ <add> <add> var req graphDriverRequest <add> if err := json.NewDecoder(r.Body).Decode(&req); err != nil { <add> http.Error(w, err.Error(), 500) <add> return <add> } <add> <add> diff, err := driver.Diff(req.ID, req.Parent) <add> if err != nil { <add> respond(w, err) <add> return <add> } <add> io.Copy(w, diff) <add> }) <add> <add> mux.HandleFunc("/GraphDriver.Changes", func(w http.ResponseWriter, r *http.Request) { <add> s.ec.changes++ <add> var req graphDriverRequest <add> if err := json.NewDecoder(r.Body).Decode(&req); err != nil { <add> http.Error(w, err.Error(), 500) <add> return <add> } <add> <add> changes, err := driver.Changes(req.ID, req.Parent) <add> if err != nil { <add> respond(w, err) <add> return <add> } <add> respond(w, &graphDriverResponse{Changes: changes}) <add> }) <add> <add> mux.HandleFunc("/GraphDriver.ApplyDiff", func(w http.ResponseWriter, r *http.Request) { <add> s.ec.applydiff++ <add> id := r.URL.Query().Get("id") <add> parent := r.URL.Query().Get("parent") <add> <add> size, err := driver.ApplyDiff(id, parent, r.Body) <add> if err != nil { <add> respond(w, err) <add> return <add> } <add> respond(w, &graphDriverResponse{Size: size}) <add> }) <add> <add> mux.HandleFunc("/GraphDriver.DiffSize", func(w http.ResponseWriter, r *http.Request) { <add> s.ec.diffsize++ <add> <add> var req graphDriverRequest <add> if err := json.NewDecoder(r.Body).Decode(&req); err != nil { <add> http.Error(w, err.Error(), 500) <add> return <add> } <add> <add> size, err := driver.DiffSize(req.ID, req.Parent) <add> if err != nil { <add> respond(w, err) <add> return <add> } <add> respond(w, &graphDriverResponse{Size: size}) <add> }) <add> <add> if err := os.MkdirAll("/etc/docker/plugins", 0755); err != nil { <add> c.Fatal(err) <add> } <add> <add> if err := ioutil.WriteFile("/etc/docker/plugins/test-external-graph-driver.spec", []byte(s.server.URL), 0644); err != nil { <add> c.Fatal(err) <add> } <add>} <add> <add>func (s *DockerExternalGraphdriverSuite) TearDownSuite(c *check.C) { <add> s.server.Close() <add> <add> if err := os.RemoveAll("/etc/docker/plugins"); err != nil { <add> c.Fatal(err) <add> } <add>} <add> <add>func (s *DockerExternalGraphdriverSuite) TestExternalGraphDriver(c *check.C) { <add> c.Assert(s.d.StartWithBusybox("-s", "test-external-graph-driver"), check.IsNil) <add> <add> out, err := s.d.Cmd("run", "-d", "--name=graphtest", "busybox", "sh", "-c", "echo hello > /hello") <add> c.Assert(err, check.IsNil, check.Commentf(out)) <add> <add> err = s.d.Restart("-s", "test-external-graph-driver") <add> <add> out, err = s.d.Cmd("inspect", "--format='{{.GraphDriver.Name}}'", "graphtest") <add> c.Assert(err, check.IsNil, check.Commentf(out)) <add> c.Assert(strings.TrimSpace(out), check.Equals, "test-external-graph-driver") <add> <add> out, err = s.d.Cmd("diff", "graphtest") <add> c.Assert(err, check.IsNil, check.Commentf(out)) <add> c.Assert(strings.Contains(out, "A /hello"), check.Equals, true) <add> <add> out, err = s.d.Cmd("rm", "-f", "graphtest") <add> c.Assert(err, check.IsNil, check.Commentf(out)) <add> <add> out, err = s.d.Cmd("info") <add> c.Assert(err, check.IsNil, check.Commentf(out)) <add> <add> err = s.d.Stop() <add> c.Assert(err, check.IsNil) <add> <add> c.Assert(s.ec.activations, check.Equals, 2) <add> c.Assert(s.ec.init, check.Equals, 2) <add> c.Assert(s.ec.creations >= 1, check.Equals, true) <add> c.Assert(s.ec.removals >= 1, check.Equals, true) <add> c.Assert(s.ec.gets >= 1, check.Equals, true) <add> c.Assert(s.ec.puts >= 1, check.Equals, true) <add> c.Assert(s.ec.stats, check.Equals, 1) <add> c.Assert(s.ec.cleanups, check.Equals, 2) <add> c.Assert(s.ec.exists >= 1, check.Equals, true) <add> c.Assert(s.ec.applydiff >= 1, check.Equals, true) <add> c.Assert(s.ec.changes, check.Equals, 1) <add> c.Assert(s.ec.diffsize, check.Equals, 0) <add> c.Assert(s.ec.diff, check.Equals, 0) <add> c.Assert(s.ec.metadata, check.Equals, 1) <add>} <add> <add>func (s *DockerExternalGraphdriverSuite) TestExternalGraphDriverPull(c *check.C) { <add> testRequires(c, Network) <add> c.Assert(s.d.Start(), check.IsNil) <add> <add> out, err := s.d.Cmd("pull", "busybox:latest") <add> c.Assert(err, check.IsNil, check.Commentf(out)) <add> <add> out, err = s.d.Cmd("run", "-d", "busybox", "top") <add> c.Assert(err, check.IsNil, check.Commentf(out)) <add>} <ide><path>integration-cli/docker_test_vars.go <ide> func init() { <ide> // Similarly, it will be perfectly valid to also run CLI tests from <ide> // a Linux CLI (built with the daemon tag) against a Windows daemon. <ide> if len(os.Getenv("DOCKER_REMOTE_DAEMON")) > 0 { <del> fmt.Println("INFO: Testing against a remote daemon") <ide> isLocalDaemon = false <ide> } else { <del> fmt.Println("INFO: Testing against a local daemon") <ide> isLocalDaemon = true <ide> } <del> <ide> } <ide><path>pkg/plugins/client.go <ide> import ( <ide> "bytes" <ide> "encoding/json" <ide> "fmt" <add> "io" <ide> "io/ioutil" <ide> "net/http" <ide> "strings" <ide> type Client struct { <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. <ide> func (c *Client) Call(serviceMethod string, args interface{}, ret interface{}) error { <del> return c.callWithRetry(serviceMethod, args, ret, true) <add> var buf bytes.Buffer <add> if err := json.NewEncoder(&buf).Encode(args); err != nil { <add> return err <add> } <add> body, err := c.callWithRetry(serviceMethod, &buf, true) <add> if err != nil { <add> return err <add> } <add> defer body.Close() <add> return json.NewDecoder(body).Decode(&ret) <ide> } <ide> <del>func (c *Client) callWithRetry(serviceMethod string, args interface{}, ret interface{}, retry bool) error { <add>// Stream calls the specified method with the specified arguments for the plugin and returns the response body <add>func (c *Client) Stream(serviceMethod string, args interface{}) (io.ReadCloser, error) { <ide> var buf bytes.Buffer <ide> if err := json.NewEncoder(&buf).Encode(args); err != nil { <del> return err <add> return nil, err <ide> } <add> return c.callWithRetry(serviceMethod, &buf, true) <add>} <ide> <del> req, err := http.NewRequest("POST", "/"+serviceMethod, &buf) <add>// SendFile calls the specified method, and passes through the IO stream <add>func (c *Client) SendFile(serviceMethod string, data io.Reader, ret interface{}) error { <add> body, err := c.callWithRetry(serviceMethod, data, true) <ide> if err != nil { <ide> return err <ide> } <add> return json.NewDecoder(body).Decode(&ret) <add>} <add> <add>func (c *Client) callWithRetry(serviceMethod string, data io.Reader, retry bool) (io.ReadCloser, error) { <add> req, err := http.NewRequest("POST", "/"+serviceMethod, data) <add> if err != nil { <add> return nil, err <add> } <ide> req.Header.Add("Accept", versionMimetype) <ide> req.URL.Scheme = "http" <ide> req.URL.Host = c.addr <ide> func (c *Client) callWithRetry(serviceMethod string, args interface{}, ret inter <ide> resp, err := c.http.Do(req) <ide> if err != nil { <ide> if !retry { <del> return err <add> return nil, err <ide> } <ide> <ide> timeOff := backoff(retries) <ide> if abort(start, timeOff) { <del> return err <add> return nil, err <ide> } <ide> retries++ <ide> logrus.Warnf("Unable to connect to plugin: %s, retrying in %v", c.addr, timeOff) <ide> time.Sleep(timeOff) <ide> continue <ide> } <ide> <del> defer resp.Body.Close() <ide> if resp.StatusCode != http.StatusOK { <ide> remoteErr, err := ioutil.ReadAll(resp.Body) <ide> if err != nil { <del> return &remoteError{err.Error(), serviceMethod} <add> return nil, &remoteError{err.Error(), serviceMethod} <ide> } <del> return &remoteError{string(remoteErr), serviceMethod} <add> return nil, &remoteError{string(remoteErr), serviceMethod} <ide> } <del> <del> return json.NewDecoder(resp.Body).Decode(&ret) <add> return resp.Body, nil <ide> } <ide> } <ide> <ide><path>pkg/plugins/client_test.go <ide> func teardownRemotePluginServer() { <ide> <ide> func TestFailedConnection(t *testing.T) { <ide> c, _ := NewClient("tcp://127.0.0.1:1", tlsconfig.Options{InsecureSkipVerify: true}) <del> err := c.callWithRetry("Service.Method", nil, nil, false) <add> _, err := c.callWithRetry("Service.Method", nil, false) <ide> if err == nil { <ide> t.Fatal("Unexpected successful connection") <ide> }
10
Ruby
Ruby
add tests for prior checkin
4584376a914f8a8cee059943d80ba73d2d4e2627
<ide><path>activesupport/test/dependencies/raises_exception.rb <ide> $raises_exception_load_count += 1 <del>raise 'Loading me failed, so do not add to loaded or history.' <add>raise Exception, 'Loading me failed, so do not add to loaded or history.' <ide> $raises_exception_load_count += 1 <ide><path>activesupport/test/dependencies_test.rb <ide> def test_dependency_which_raises_exception_isnt_added_to_loaded_set <ide> $raises_exception_load_count = 0 <ide> <ide> 5.times do |count| <del> assert_raises(RuntimeError) { require_dependency filename } <add> assert_raises(Exception) { require_dependency filename } <ide> assert_equal count + 1, $raises_exception_load_count <ide> <ide> assert !Dependencies.loaded.include?(filename) <ide> def test_removal_from_tree_should_be_detected <ide> end <ide> end <ide> <add> def test_nested_load_error_isnt_rescued <add> with_loading 'dependencies' do <add> assert_raises(MissingSourceFile) do <add> RequiresNonexistent1 <add> end <add> end <add> end <add> <ide> end
2
Text
Text
fix typos in docs
72de94a05d2038f2557d4c7a3b16cf20416fb123
<ide><path>docs/api-guide/caching.md <ide> # Caching <ide> <del>> A certain woman had a very sharp conciousness but almost no <add>> A certain woman had a very sharp consciousness but almost no <ide> > memory ... She remembered enough to work, and she worked hard. <ide> > - Lydia Davis <ide> <ide><path>docs/api-guide/fields.md <ide> A field that ensures the input is a valid UUID string. The `to_internal_value` m <ide> **Signature:** `UUIDField(format='hex_verbose')` <ide> <ide> - `format`: Determines the representation format of the uuid value <del> - `'hex_verbose'` - The cannoncical hex representation, including hyphens: `"5ce0e9a5-5ffa-654b-cee0-1238041fb31a"` <add> - `'hex_verbose'` - The canonical hex representation, including hyphens: `"5ce0e9a5-5ffa-654b-cee0-1238041fb31a"` <ide> - `'hex'` - The compact hex representation of the UUID, not including hyphens: `"5ce0e9a55ffa654bcee01238041fb31a"` <ide> - `'int'` - A 128 bit integer representation of the UUID: `"123456789012312313134124512351145145114"` <ide> - `'urn'` - RFC 4122 URN representation of the UUID: `"urn:uuid:5ce0e9a5-5ffa-654b-cee0-1238041fb31a"` <ide><path>docs/api-guide/settings.md <ide> This should be a function with the following signature: <ide> <ide> If the view instance inherits `ViewSet`, it may have been initialized with several optional arguments: <ide> <del>* `name`: A name expliticly provided to a view in the viewset. Typically, this value should be used as-is when provided. <add>* `name`: A name explicitly provided to a view in the viewset. Typically, this value should be used as-is when provided. <ide> * `suffix`: Text used when differentiating individual views in a viewset. This argument is mutually exclusive to `name`. <ide> * `detail`: Boolean that differentiates an individual view in a viewset as either being a 'list' or 'detail' view. <ide> <ide><path>docs/api-guide/throttling.md <ide> If you need to strictly identify unique client IP addresses, you'll need to firs <ide> <ide> It is important to understand that if you configure the `NUM_PROXIES` setting, then all clients behind a unique [NAT'd](https://en.wikipedia.org/wiki/Network_address_translation) gateway will be treated as a single client. <ide> <del>Further context on how the `X-Forwarded-For` header works, and identifying a remote client IP can be [found here][identifing-clients]. <add>Further context on how the `X-Forwarded-For` header works, and identifying a remote client IP can be [found here][identifying-clients]. <ide> <ide> ## Setting up the cache <ide> <ide> The following is an example of a rate throttle, that will randomly throttle 1 in <ide> <ide> [cite]: https://developer.twitter.com/en/docs/basics/rate-limiting <ide> [permissions]: permissions.md <del>[identifing-clients]: http://oxpedia.org/wiki/index.php?title=AppSuite:Grizzly#Multiple_Proxies_in_front_of_the_cluster <add>[identifying-clients]: http://oxpedia.org/wiki/index.php?title=AppSuite:Grizzly#Multiple_Proxies_in_front_of_the_cluster <ide> [cache-setting]: https://docs.djangoproject.com/en/stable/ref/settings/#caches <ide> [cache-docs]: https://docs.djangoproject.com/en/stable/topics/cache/#setting-up-the-cache <ide><path>docs/community/3.6-announcement.md <ide> REST framework's new API documentation supports a number of features: <ide> * Support for various authentication schemes. <ide> * Code snippets for the Python, JavaScript, and Command Line clients. <ide> <del>The `coreapi` library is required as a dependancy for the API docs. Make sure <add>The `coreapi` library is required as a dependency for the API docs. Make sure <ide> to install the latest version (2.3.0 or above). The `pygments` and `markdown` <ide> libraries are optional but recommended. <ide> <ide><path>docs/community/release-notes.md <ide> Be sure to upgrade to Python 3 before upgrading to Django REST Framework 3.10. <ide> Note: `AutoSchema.__init__` now ensures `manual_fields` is a list. <ide> Previously may have been stored internally as `None`. <ide> <del>* Remove ulrparse compatability shim; use six instead [#5579][gh5579] <add>* Remove ulrparse compatibility shim; use six instead [#5579][gh5579] <ide> * Drop compat wrapper for `TimeDelta.total_seconds()` [#5577][gh5577] <ide> * Clean up all whitespace throughout project [#5578][gh5578] <ide> * Compat cleanup [#5581][gh5581] <ide><path>docs/community/third-party-packages.md <ide> If you have an idea for a new feature please consider how it may be packaged as <ide> <ide> You can use [this cookiecutter template][cookiecutter] for creating reusable Django REST Framework packages quickly. Cookiecutter creates projects from project templates. While optional, this cookiecutter template includes best practices from Django REST framework and other packages, as well as a Travis CI configuration, Tox configuration, and a sane setup.py for easy PyPI registration/distribution. <ide> <del>Note: Let us know if you have an alternate cookiecuter package so we can also link to it. <add>Note: Let us know if you have an alternate cookiecutter package so we can also link to it. <ide> <ide> #### Running the initial cookiecutter command <ide>
7
Ruby
Ruby
remove cask’s `cli#debug?`
a44d4ce88b6fb3deea8dc41be662583941d5c96d
<ide><path>Library/Homebrew/cask/lib/hbc/cask.rb <ide> def to_s <ide> end <ide> <ide> def dumpcask <del> return unless CLI.debug? <del> <ide> odebug "Cask instance dumps in YAML:" <ide> odebug "Cask instance toplevel:", to_yaml <ide> [ <ide><path>Library/Homebrew/cask/lib/hbc/cli.rb <ide> class CLI <ide> <ide> FLAGS = { <ide> ["--[no-]binaries", :binaries] => true, <del> ["--debug", :debug] => false, <ide> ["--verbose", :verbose] => false, <ide> ["--outdated", :outdated] => false, <ide> ["--help", :help] => false, <ide> def self.process(arguments) <ide> run_command(command, *rest) <ide> rescue CaskError, CaskSha256MismatchError, ArgumentError => e <ide> msg = e.message <del> msg << e.backtrace.join("\n") if debug? <add> msg << e.backtrace.join("\n") if ARGV.debug? <ide> onoe msg <ide> exit 1 <ide> rescue StandardError, ScriptError, NoMemoryError => e <ide> def self.process_options(args) <ide> <ide> # for compat with Homebrew, not certain if this is desirable <ide> self.verbose = true if ARGV.verbose? <del> self.debug = true if ARGV.debug? <ide> <ide> remaining <ide> end <ide><path>Library/Homebrew/cask/lib/hbc/cli/internal_dump.rb <ide> def self.run(*arguments) <ide> end <ide> <ide> def self.dump_casks(*cask_tokens) <del> CLI.debug = true # Yuck. At the moment this is the only way to make dumps visible <ide> count = 0 <ide> cask_tokens.each do |cask_token| <ide> begin <ide><path>Library/Homebrew/cask/lib/hbc/system_command.rb <ide> def self._warn_plist_garbage(command, garbage) <ide> def self._parse_plist(command, output) <ide> raise CaskError, "Empty plist input" unless output =~ /\S/ <ide> output.sub!(/\A(.*?)(<\?\s*xml)/m, '\2') <del> _warn_plist_garbage(command, Regexp.last_match[1]) if CLI.debug? <add> _warn_plist_garbage(command, Regexp.last_match[1]) if ARGV.debug? <ide> output.sub!(%r{(<\s*/\s*plist\s*>)(.*?)\Z}m, '\1') <ide> _warn_plist_garbage(command, Regexp.last_match[2]) <ide> xml = Plist.parse_xml(output) <ide><path>Library/Homebrew/cask/lib/hbc/utils.rb <ide> def tty? <ide> # global methods <ide> <ide> def odebug(title, *sput) <del> return unless Hbc::CLI.debug? <add> return unless ARGV.debug? <ide> puts Formatter.headline(title, color: :magenta) <ide> puts sput unless sput.empty? <ide> end <ide><path>Library/Homebrew/test/cask/cli/options_spec.rb <ide> end <ide> end <ide> <del> describe "--debug" do <del> it "sets the Cask debug method to true" do <del> begin <del> Hbc::CLI.process_options %w[help --debug] <del> expect(Hbc::CLI.debug?).to be true <del> ensure <del> Hbc::CLI.debug = false <del> end <del> end <del> end <del> <ide> describe "--help" do <ide> it "sets the Cask help method to true" do <ide> begin
6
Javascript
Javascript
add test for unique challenge titles
5fa098ea0de6afe29af7020c5a868d80c05b64f8
<ide><path>challengeTitles.js <add>import _ from 'lodash'; <add> <add>class ChallengeTitles { <add> constructor() { <add> this.knownTitles = []; <add> } <add> check(title) { <add> if (typeof title !== 'string') { <add> throw new Error(`Expected a valid string for ${title}, got ${typeof title}`); <add> } else if (title.length === 0) { <add> throw new Error(`Expected a title length greater than 0`); <add> } <add> const titleToCheck = title.toLowerCase().replace(/\s+/g, ''); <add> const titleIndex = _.findIndex(this.knownTitles, existing => titleToCheck === existing); <add> if (titleIndex !== -1) { <add> throw new Error(` <add> All challenges must have a unique title. <add> <add> The title ${title} is already assigned <add> `); <add> } <add> this.knownTitles = [ ...this.knownTitles, titleToCheck ]; <add> } <add>} <add> <add>export default ChallengeTitles; <ide><path>test-challenges.js <ide> import tape from 'tape'; <ide> import getChallenges from './getChallenges'; <ide> import { modern } from '../common/app/utils/challengeTypes'; <ide> import MongoIds from './mongoIds'; <add>import ChallengeTitles from './challengeTitles'; <ide> import addAssertsToTapTest from './addAssertsToTapTest'; <ide> <ide> let mongoIds = new MongoIds(); <add>let challengeTitles = new ChallengeTitles(); <ide> <ide> function evaluateTest(solution, assert, <ide> react, redux, reactRedux, <ide> function createTest({ <ide> reactRedux = false <ide> }) { <ide> mongoIds.check(id, title); <add> challengeTitles.check(title); <ide> <ide> solutions = solutions.filter(solution => !!solution); <ide> tests = tests.filter(test => !!test);
2
Ruby
Ruby
fix the variable name
7768c2a7f3142b422c90dfea451f74643994be52
<ide><path>activerecord/lib/active_record/associations/builder/has_and_belongs_to_many.rb <ide> class JoinTableResolver <ide> KnownTable = Struct.new :join_table <ide> <ide> class KnownClass <del> def initialize(rhs_class, lhs_class_name) <del> @rhs_class = rhs_class <del> @lhs_class_name = lhs_class_name <add> def initialize(lhs_class, rhs_class_name) <add> @lhs_class = lhs_class <add> @rhs_class_name = rhs_class_name <ide> @join_table = nil <ide> end <ide> <ide> def join_table <del> @join_table ||= [@rhs_class.table_name, klass.table_name].sort.join("\0").gsub(/^(.*_)(.+)\0\1(.+)/, '\1\2_\3').gsub("\0", "_") <add> @join_table ||= [@lhs_class.table_name, klass.table_name].sort.join("\0").gsub(/^(.*_)(.+)\0\1(.+)/, '\1\2_\3').gsub("\0", "_") <ide> end <ide> <ide> private <del> def klass; @lhs_class_name.constantize; end <add> def klass; @rhs_class_name.constantize; end <ide> end <ide> <del> def self.build(rhs_class, name, options) <add> def self.build(lhs_class, name, options) <ide> if options[:join_table] <ide> KnownTable.new options[:join_table] <ide> else <ide> class_name = options.fetch(:class_name) { <ide> name.to_s.camelize.singularize <ide> } <del> KnownClass.new rhs_class, class_name <add> KnownClass.new lhs_class, class_name <ide> end <ide> end <ide> end
1
Javascript
Javascript
escape forward slash in email regexp
b775e2bca1093e9df62a269b5bda968555ea0ded
<ide><path>src/ng/directive/input.js <ide> */ <ide> <ide> var URL_REGEXP = /^(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?$/; <del>var EMAIL_REGEXP = /^[a-z0-9!#$%&'*+/=?^_`{|}~.-]+@[a-z0-9-]+(\.[a-z0-9-]+)*$/i; <add>var EMAIL_REGEXP = /^[a-z0-9!#$%&'*+\/=?^_`{|}~.-]+@[a-z0-9-]+(\.[a-z0-9-]+)*$/i; <ide> var NUMBER_REGEXP = /^\s*(\-|\+)?(\d+|(\d*(\.\d*)))\s*$/; <ide> var DATE_REGEXP = /^(\d{4})-(\d{2})-(\d{2})$/; <ide> var DATETIMELOCAL_REGEXP = /^(\d{4})-(\d\d)-(\d\d)T(\d\d):(\d\d)$/;
1
PHP
PHP
remove bonus inflection in _setmodelclass()
a2f3fc4012450cf51a3a660ee2a7a296a2efc14c
<ide><path>src/Console/Shell.php <ide> class Shell { <ide> protected $_io; <ide> <ide> /** <del> * Constructs this Shell instance. <add> * Constructs this Shell instance. <ide> * <ide> * @param \Cake\Console\ConsoleIo $io An io instance. <ide> * @link http://book.cakephp.org/3.0/en/console-and-shells.html#Shell <ide> public function __construct(ConsoleIo $io = null) { <ide> } <ide> $this->_io = $io ?: new ConsoleIo(); <ide> <del> $this->_setModelClass($this->name); <ide> $this->modelFactory('Table', ['Cake\ORM\TableRegistry', 'get']); <ide> $this->Tasks = new TaskRegistry($this); <ide> <ide> public function __construct(ConsoleIo $io = null) { <ide> ['tasks'], <ide> ['associative' => ['tasks']] <ide> ); <add> <add> if (isset($this->modelClass)) { <add> $this->loadModel(); <add> } <ide> } <ide> <ide> /** <ide> protected function _welcome() { <ide> $this->hr(); <ide> } <ide> <del>/** <del> * Lazy loads models using the loadModel() method if it matches modelClass <del> * <del> * @param string $name <del> * @return void <del> */ <del> public function __isset($name) { <del> if ($name === $this->modelClass) { <del> list($plugin, $class) = pluginSplit($name, true); <del> if (!$plugin) { <del> $plugin = $this->plugin ? $this->plugin . '.' : null; <del> } <del> return $this->loadModel($plugin . $this->modelClass); <del> } <del> } <del> <ide> /** <ide> * Loads tasks defined in public $tasks <ide> * <ide><path>src/Model/ModelAwareTrait.php <ide> namespace Cake\Model; <ide> <ide> use Cake\Error\Exception; <del>use Cake\Utility\Inflector; <ide> <ide> /** <ide> * Provides functionality for loading table classes <ide> trait ModelAwareTrait { <ide> <ide> /** <del> * This object's primary model class name, the Inflector::pluralized()'ed version of <del> * the object's $name property. <add> * This object's primary model class name. Should be a plural form. <add> * CakePHP will not inflect the name. <ide> * <ide> * Example: For a object named 'Comments', the modelClass would be 'Comments' <ide> * <ide> trait ModelAwareTrait { <ide> */ <ide> protected function _setModelClass($name) { <ide> if (empty($this->modelClass)) { <del> $this->modelClass = Inflector::pluralize($name); <add> $this->modelClass = $name; <ide> } <ide> } <ide> <ide><path>tests/TestCase/Console/ShellTest.php <ide> public function testInitialize() { <ide> Plugin::load('TestPlugin'); <ide> $this->Shell->tasks = array('DbConfig' => array('one', 'two')); <ide> $this->Shell->plugin = 'TestPlugin'; <del> $this->Shell->modelClass = 'TestPluginComments'; <add> $this->Shell->modelClass = 'TestPlugin.TestPluginComments'; <ide> $this->Shell->initialize(); <add> $this->Shell->loadModel(); <ide> <ide> $this->assertTrue(isset($this->Shell->TestPluginComments)); <ide> $this->assertInstanceOf(
3
Text
Text
use reserved domains for examples in url.md
0311fcc546e792c813f1c6644ff7e60e7a7b5158
<ide><path>doc/api/url.md <ide> backwards compatibility with existing applications. New application code <ide> should use the WHATWG API. <ide> <ide> A comparison between the WHATWG and Legacy APIs is provided below. Above the URL <del>`'http://user:pass@sub.host.com:8080/p/a/t/h?query=string#hash'`, properties of <del>an object returned by the legacy `url.parse()` are shown. Below it are <add>`'http://user:pass@sub.example.com:8080/p/a/t/h?query=string#hash'`, properties <add>of an object returned by the legacy `url.parse()` are shown. Below it are <ide> properties of a WHATWG `URL` object. <ide> <ide> WHATWG URL's `origin` property includes `protocol` and `host`, but not <ide> `username` or `password`. <ide> <ide> ```txt <del>┌─────────────────────────────────────────────────────────────────────────────────────────────┐ <del>│ href │ <del>├──────────┬──┬─────────────────────┬─────────────────────┬───────────────────────────┬───────┤ <del>│ protocol │ │ auth │ host │ path │ hash │ <del>│ │ │ ├──────────────┬──────┼──────────┬────────────────┤ │ <del>│ │ │ │ hostname │ port │ pathname │ search │ │ <del>│ │ │ │ │ │ ├─┬──────────────┤ │ <del>│ │ │ │ │ │ │ │ query │ │ <del>" https: // user : pass @ sub.host.com : 8080 /p/a/t/h ? query=string #hash " <del>│ │ │ │ │ hostname │ port │ │ │ │ <del>│ │ │ │ ├──────────────┴──────┤ │ │ │ <del>│ protocol │ │ username │ password │ host │ │ │ │ <del>├──────────┴──┼──────────┴──────────┼─────────────────────┤ │ │ │ <del>│ origin │ │ origin │ pathname │ search │ hash │ <del>├─────────────┴─────────────────────┴─────────────────────┴──────────┴────────────────┴───────┤ <del>│ href │ <del>└─────────────────────────────────────────────────────────────────────────────────────────────┘ <add>┌────────────────────────────────────────────────────────────────────────────────────────────────┐ <add>│ href │ <add>├──────────┬──┬─────────────────────┬────────────────────────┬───────────────────────────┬───────┤ <add>│ protocol │ │ auth │ host │ path │ hash │ <add>│ │ │ ├─────────────────┬──────┼──────────┬────────────────┤ │ <add>│ │ │ │ hostname │ port │ pathname │ search │ │ <add>│ │ │ │ │ │ ├─┬──────────────┤ │ <add>│ │ │ │ │ │ │ │ query │ │ <add>" https: // user : pass @ sub.example.com : 8080 /p/a/t/h ? query=string #hash " <add>│ │ │ │ │ hostname │ port │ │ │ │ <add>│ │ │ │ ├─────────────────┴──────┤ │ │ │ <add>│ protocol │ │ username │ password │ host │ │ │ │ <add>├──────────┴──┼──────────┴──────────┼────────────────────────┤ │ │ │ <add>│ origin │ │ origin │ pathname │ search │ hash │ <add>├─────────────┴─────────────────────┴────────────────────────┴──────────┴────────────────┴───────┤ <add>│ href │ <add>└────────────────────────────────────────────────────────────────────────────────────────────────┘ <ide> (all spaces in the "" line should be ignored — they are purely for formatting) <ide> ``` <ide> <ide> Parsing the URL string using the WHATWG API: <ide> <ide> ```js <ide> const myURL = <del> new URL('https://user:pass@sub.host.com:8080/p/a/t/h?query=string#hash'); <add> new URL('https://user:pass@sub.example.com:8080/p/a/t/h?query=string#hash'); <ide> ``` <ide> <ide> Parsing the URL string using the Legacy API: <ide> <ide> ```js <ide> const url = require('url'); <ide> const myURL = <del> url.parse('https://user:pass@sub.host.com:8080/p/a/t/h?query=string#hash'); <add> url.parse('https://user:pass@sub.example.com:8080/p/a/t/h?query=string#hash'); <ide> ``` <ide> <ide> ## The WHATWG URL API <ide> Unicode characters appearing within the hostname of `input` will be <ide> automatically converted to ASCII using the [Punycode][] algorithm. <ide> <ide> ```js <del>const myURL = new URL('https://你好你好'); <del>// https://xn--6qqa088eba/ <add>const myURL = new URL('https://測試'); <add>// https://xn--g6w251d/ <ide> ``` <ide> <ide> This feature is only available if the `node` executable was compiled with <ide> and a `base` is provided, it is advised to validate that the `origin` of <ide> the `URL` object is what is expected. <ide> <ide> ```js <del>let myURL = new URL('http://anotherExample.org/', 'https://example.org/'); <del>// http://anotherexample.org/ <add>let myURL = new URL('http://Example.com/', 'https://example.org/'); <add>// http://example.com/ <ide> <del>myURL = new URL('https://anotherExample.org/', 'https://example.org/'); <del>// https://anotherexample.org/ <add>myURL = new URL('https://Example.com/', 'https://example.org/'); <add>// https://example.com/ <ide> <del>myURL = new URL('foo://anotherExample.org/', 'https://example.org/'); <del>// foo://anotherExample.org/ <add>myURL = new URL('foo://Example.com/', 'https://example.org/'); <add>// foo://Example.com/ <ide> <del>myURL = new URL('http:anotherExample.org/', 'https://example.org/'); <del>// http://anotherexample.org/ <add>myURL = new URL('http:Example.com/', 'https://example.org/'); <add>// http://example.com/ <ide> <del>myURL = new URL('https:anotherExample.org/', 'https://example.org/'); <del>// https://example.org/anotherExample.org/ <add>myURL = new URL('https:Example.com/', 'https://example.org/'); <add>// https://example.org/Example.com/ <ide> <del>myURL = new URL('foo:anotherExample.org/', 'https://example.org/'); <del>// foo:anotherExample.org/ <add>myURL = new URL('foo:Example.com/', 'https://example.org/'); <add>// foo:Example.com/ <ide> ``` <ide> <ide> #### url.hash <ide> console.log(myURL.origin); <ide> ``` <ide> <ide> ```js <del>const idnURL = new URL('https://你好你好'); <add>const idnURL = new URL('https://測試'); <ide> console.log(idnURL.origin); <del>// Prints https://xn--6qqa088eba <add>// Prints https://xn--g6w251d <ide> <ide> console.log(idnURL.hostname); <del>// Prints xn--6qqa088eba <add>// Prints xn--g6w251d <ide> ``` <ide> <ide> #### url.password <ide> any way. The `url.format(URL[, options])` method allows for basic customization <ide> of the output. <ide> <ide> ```js <del>const myURL = new URL('https://a:b@你好你好?abc#foo'); <add>const myURL = new URL('https://a:b@測試?abc#foo'); <ide> <ide> console.log(myURL.href); <del>// Prints https://a:b@xn--6qqa088eba/?abc#foo <add>// Prints https://a:b@xn--g6w251d/?abc#foo <ide> <ide> console.log(myURL.toString()); <del>// Prints https://a:b@xn--6qqa088eba/?abc#foo <add>// Prints https://a:b@xn--g6w251d/?abc#foo <ide> <ide> console.log(url.format(myURL, { fragment: false, unicode: true, auth: false })); <del>// Prints 'https://你好你好/?abc' <add>// Prints 'https://測試/?abc' <ide> ``` <ide> <ide> ### url.pathToFileURL(path) <ide> For example: `'#hash'`. <ide> The `host` property is the full lower-cased host portion of the URL, including <ide> the `port` if specified. <ide> <del>For example: `'sub.host.com:8080'`. <add>For example: `'sub.example.com:8080'`. <ide> <ide> #### urlObject.hostname <ide> <ide> The `hostname` property is the lower-cased host name portion of the `host` <ide> component *without* the `port` included. <ide> <del>For example: `'sub.host.com'`. <add>For example: `'sub.example.com'`. <ide> <ide> #### urlObject.href <ide> <ide> The `href` property is the full URL string that was parsed with both the <ide> `protocol` and `host` components converted to lower-case. <ide> <del>For example: `'http://user:pass@sub.host.com:8080/p/a/t/h?query=string#hash'`. <add>For example: `'http://user:pass@sub.example.com:8080/p/a/t/h?query=string#hash'`. <ide> <ide> #### urlObject.path <ide> <ide> using the [Punycode][] algorithm. Note, however, that a hostname *may* contain <ide> *both* Punycode encoded and percent-encoded characters: <ide> <ide> ```js <del>const myURL = new URL('https://%CF%80.com/foo'); <add>const myURL = new URL('https://%CF%80.example.com/foo'); <ide> console.log(myURL.href); <del>// Prints https://xn--1xa.com/foo <add>// Prints https://xn--1xa.example.com/foo <ide> console.log(myURL.origin); <del>// Prints https://π.com <add>// Prints https://π.example.com <ide> ``` <ide> <ide> [`Error`]: errors.html#errors_class_error
1
Javascript
Javascript
drop `arraymap` for `map`.
11879537b9d17ae393920df699ad95ec67b55759
<ide><path>lib/ArrayMap.js <del>/* <del> MIT License http://www.opensource.org/licenses/mit-license.php <del> Author Tobias Koppers @sokra <del>*/ <del> <del>"use strict"; <del> <del>class ArrayMap { <del> constructor() { <del> this.keys = []; <del> this.values = []; <del> } <del> <del> get(key) { <del> for(let i = 0; i < this.keys.length; i++) { <del> if(this.keys[i] === key) { <del> return this.values[i]; <del> } <del> } <del> return; <del> } <del> <del> set(key, value) { <del> for(let i = 0; i < this.keys.length; i++) { <del> if(this.keys[i] === key) { <del> this.values[i] = value; <del> return this; <del> } <del> } <del> this.keys.push(key); <del> this.values.push(value); <del> return this; <del> } <del> <del> remove(key) { <del> for(let i = 0; i < this.keys.length; i++) { <del> if(this.keys[i] === key) { <del> this.keys.splice(i, 1); <del> this.values.splice(i, 1); <del> return true; <del> } <del> } <del> return false; <del> } <del> <del> clone() { <del> const newMap = new ArrayMap(); <del> <del> for(let i = 0; i < this.keys.length; i++) { <del> newMap.keys.push(this.keys[i]); <del> newMap.values.push(this.values[i]); <del> } <del> return newMap; <del> } <del>} <del> <del>module.exports = ArrayMap; <ide><path>lib/Compilation.js <ide> var EntryModuleNotFoundError = require("./EntryModuleNotFoundError"); <ide> var ModuleNotFoundError = require("./ModuleNotFoundError"); <ide> var ModuleDependencyWarning = require("./ModuleDependencyWarning"); <ide> var Module = require("./Module"); <del>var ArrayMap = require("./ArrayMap"); <ide> var Chunk = require("./Chunk"); <ide> var Entrypoint = require("./Entrypoint"); <ide> var Stats = require("./Stats"); <ide> function Compilation(compiler) { <ide> this.errors = []; <ide> this.warnings = []; <ide> this.children = []; <del> this.dependencyFactories = new ArrayMap(); <del> this.dependencyTemplates = new ArrayMap(); <add> this.dependencyFactories = new Map(); <add> this.dependencyTemplates = new Map(); <ide> } <ide> module.exports = Compilation; <ide> <ide><path>test/ArrayMap.test.js <del>var should = require("should"); <del>var ArrayMap = require("../lib/ArrayMap"); <del> <del>describe("ArrayMap", function() { <del> var myArrayMap; <del> <del> beforeEach(function() { <del> myArrayMap = new ArrayMap(); <del> }); <del> <del> describe('get', function() { <del> it('returns value for known key', function() { <del> myArrayMap.set('foo', 10); <del> myArrayMap.get('foo').should.be.exactly(10); <del> }); <del> <del> it('returns undefined for unknown key', function() { <del> should(myArrayMap.get('foo')).be.undefined(); <del> }); <del> }); <del> <del> describe('set', function() { <del> it('returns reference to array map instance', function() { <del> myArrayMap.set('foo', 10).should.be.exactly(myArrayMap); <del> }); <del> <del> it('sets value for new key', function() { <del> myArrayMap.set('foo', 10); <del> myArrayMap.get('foo').should.be.exactly(10); <del> }); <del> <del> it('overwrites value for existing key', function() { <del> myArrayMap.set('foo', 10).set('foo', 'hello'); <del> myArrayMap.get('foo').should.be.exactly('hello'); <del> }); <del> }); <del> <del> describe('remove', function() { <del> it('removes entry for existing data', function() { <del> myArrayMap.set('foo', 10); <del> myArrayMap.remove('foo').should.be.exactly(true); <del> should(myArrayMap.get('foo')).be.undefined(); <del> }); <del> <del> it('does nothing for non-existant data', function() { <del> myArrayMap.remove('foo').should.be.exactly(false); <del> should(myArrayMap.get('foo')).be.undefined(); <del> }); <del> }); <del> <del> describe('clone', function() { <del> it('creates a new instance of the array map', function() { <del> myArrayMap.clone().should.not.be.exactly(myArrayMap); <del> }); <del> <del> it('creates a new copy with no shared data', function() { <del> var myArrayMap2 = myArrayMap.set('foo', 10).clone(); <del> myArrayMap.set('foo', 'hello'); <del> myArrayMap2.set('bar', 20); <del> <del> myArrayMap.get('foo').should.be.exactly('hello'); <del> myArrayMap2.get('foo').should.be.exactly(10); <del> should(myArrayMap.get('bar')).be.undefined(); <del> myArrayMap2.get('bar').should.be.exactly(20); <del> }); <del> }); <del>});
3
Javascript
Javascript
fix nowork bug
9fca81213967210ea3f74daab7a0f64a454bd3b6
<ide><path>src/renderers/shared/fiber/ReactFiberBeginWork.js <ide> module.exports = function<T, P, I, C>(config : HostConfig<T, P, I, C>) { <ide> // it until the next tick. <ide> workInProgress.child = current.child; <ide> reuseChildren(workInProgress, workInProgress.child); <del> if (workInProgress.pendingWorkPriority <= priorityLevel) { <add> if (workInProgress.pendingWorkPriority !== NoWork && workInProgress.pendingWorkPriority <= priorityLevel) { <ide> // TODO: This passes the current node and reads the priority level and <ide> // pending props from that. We want it to read our priority level and <ide> // pending props from the work in progress. Needs restructuring. <ide> module.exports = function<T, P, I, C>(config : HostConfig<T, P, I, C>) { <ide> } <ide> <ide> if (!workInProgress.hasWorkInProgress && <del> workInProgress.pendingProps === workInProgress.memoizedProps && <del> workInProgress.pendingWorkPriority === NoWork) { <add> workInProgress.pendingProps === workInProgress.memoizedProps) { <ide> // If we started this work before, and finished it, or if we're in a <ide> // ping-pong update scenario, this version could already be what we're <ide> // looking for. In that case, we should be able to just bail out. <add> const priorityLevel = workInProgress.pendingWorkPriority; <ide> workInProgress.pendingProps = null; <del> // TODO: We should be able to bail out if there is remaining work at a lower <del> // priority too. However, I don't know if that is safe or even better since <del> // the other tree could've potentially finished that work. <add> workInProgress.pendingWorkPriority = NoWork; <add> if (workInProgress.child) { <add> // If we bail out but still has work with the current priority in this <add> // subtree, we need to go find it right now. If we don't, we won't flush <add> // it until the next tick. <add> reuseChildren(workInProgress, workInProgress.child); <add> if (workInProgress.pendingWorkPriority !== NoWork && workInProgress.pendingWorkPriority <= priorityLevel) { <add> // TODO: This passes the current node and reads the priority level and <add> // pending props from that. We want it to read our priority level and <add> // pending props from the work in progress. Needs restructuring. <add> return findNextUnitOfWorkAtPriority(workInProgress, priorityLevel); <add> } <add> } <ide> return null; <ide> } <ide> <ide><path>src/renderers/shared/fiber/ReactFiberPendingWork.js <ide> var { <ide> } = require('ReactPriorityLevel'); <ide> <ide> function cloneSiblings(current : Fiber, workInProgress : Fiber, returnFiber : Fiber) { <add> workInProgress.return = returnFiber; <ide> while (current.sibling) { <ide> current = current.sibling; <ide> workInProgress = workInProgress.sibling = cloneFiber( <ide> exports.findNextUnitOfWorkAtPriority = function(currentRoot : Fiber, priorityLev <ide> workInProgress.pendingProps = current.pendingProps; <ide> return workInProgress; <ide> } <add> <ide> // If we have a child let's see if any of our children has work to do. <ide> // Only bother doing this at all if the current priority level matches <ide> // because it is the highest priority for the whole subtree. <ide> exports.findNextUnitOfWorkAtPriority = function(currentRoot : Fiber, priorityLev <ide> throw new Error('Should have wip now'); <ide> } <ide> workInProgress.pendingWorkPriority = current.pendingWorkPriority; <del> workInProgress.child = cloneFiber(currentChild, NoWork); <del> workInProgress.child.return = workInProgress; <add> // TODO: The below priority used to be set to NoWork which would've <add> // dropped work. This is currently unobservable but will become <add> // observable when the first sibling has lower priority work remaining <add> // than the next sibling. At that point we should add tests that catches <add> // this. <add> workInProgress.child = cloneFiber( <add> currentChild, <add> currentChild.pendingWorkPriority <add> ); <ide> cloneSiblings(currentChild, workInProgress.child, workInProgress); <ide> current = current.child; <ide> continue;
2
Ruby
Ruby
move more command handling logic to commands.rb
8a9dcad2c708ce945695029c5af79b4b3965a4de
<ide><path>Library/Homebrew/brew.rb <ide> class MissingEnvironmentVariables < RuntimeError; end <ide> <ide> ENV["PATH"] = path <ide> <del> if cmd <del> internal_cmd = require? HOMEBREW_LIBRARY_PATH/"cmd"/cmd <add> require "commands" <ide> <del> unless internal_cmd <del> internal_dev_cmd = require? HOMEBREW_LIBRARY_PATH/"dev-cmd"/cmd <del> internal_cmd = internal_dev_cmd <add> if cmd <add> internal_cmd = Commands.valid_internal_cmd?(cmd) <add> internal_cmd ||= begin <add> internal_dev_cmd = Commands.valid_internal_dev_cmd?(cmd) <ide> if internal_dev_cmd && !ARGV.homebrew_developer? <ide> if (HOMEBREW_REPOSITORY/".git/config").exist? <ide> system "git", "config", "--file=#{HOMEBREW_REPOSITORY}/.git/config", <ide> "--replace-all", "homebrew.devcmdrun", "true" <ide> end <ide> ENV["HOMEBREW_DEV_CMD_RUN"] = "1" <ide> end <add> internal_dev_cmd <ide> end <ide> end <ide> <ide> class MissingEnvironmentVariables < RuntimeError; end <ide> # `Homebrew.help` never returns, except for unknown commands. <ide> end <ide> <del> if internal_cmd <del> Homebrew.send cmd.to_s.tr("-", "_").downcase <del> elsif which "brew-#{cmd}" <add> if internal_cmd || Commands.external_ruby_v2_cmd_path(cmd) <add> Homebrew.send Commands.method_name(cmd) <add> elsif (path = Commands.external_ruby_cmd_path(cmd)) <add> require?(path) <add> exit Homebrew.failed? ? 1 : 0 <add> elsif Commands.external_cmd_path(cmd) <ide> %w[CACHE LIBRARY_PATH].each do |env| <ide> ENV["HOMEBREW_#{env}"] = Object.const_get("HOMEBREW_#{env}").to_s <ide> end <ide> exec "brew-#{cmd}", *ARGV <del> elsif (path = which("brew-#{cmd}.rb")) && require?(path) <del> exit Homebrew.failed? ? 1 : 0 <ide> else <ide> possible_tap = OFFICIAL_CMD_TAPS.find { |_, cmds| cmds.include?(cmd) } <ide> possible_tap = Tap.fetch(possible_tap.first) if possible_tap <ide><path>Library/Homebrew/cli/parser.rb <ide> def self.parse(args = ARGV, &block) <ide> end <ide> <ide> def self.from_cmd_path(cmd_path) <del> cmd_method_prefix = cmd_path.basename(cmd_path.extname) <del> .to_s <del> .sub(/^brew-/, "") <del> .tr("-", "_") <del> cmd_args_method_name = "#{cmd_method_prefix}_args".to_sym <add> cmd_args_method_name = Commands.args_method_name(cmd_path) <ide> <ide> begin <ide> Homebrew.send(cmd_args_method_name) if require?(cmd_path) <ide><path>Library/Homebrew/cmd/command.rb <ide> def command <ide> <ide> raise UsageError, "This command requires a command argument" if args.remaining.empty? <ide> <del> args.remaining.each do |c| <del> cmd = HOMEBREW_INTERNAL_COMMAND_ALIASES.fetch(c, c) <add> args.remaining.each do |cmd| <ide> path = Commands.path(cmd) <del> cmd_paths = PATH.new(ENV["PATH"]).append(Tap.cmd_directories) unless path <del> path ||= which("brew-#{cmd}", cmd_paths) <del> path ||= which("brew-#{cmd}.rb", cmd_paths) <del> <ide> odie "Unknown command: #{cmd}" unless path <ide> puts path <ide> end <ide><path>Library/Homebrew/cmd/commands.rb <ide> def commands <ide> commands_args.parse <ide> <ide> if args.quiet? <del> cmds = internal_commands <del> cmds += external_commands <del> cmds += internal_developer_commands <del> cmds += HOMEBREW_INTERNAL_COMMAND_ALIASES.keys if args.include_aliases? <del> puts Formatter.columns(cmds.sort) <add> puts Formatter.columns(Commands.commands(aliases: args.include_aliases?)) <ide> return <ide> end <ide> <del> # Find commands in Homebrew/cmd <del> ohai "Built-in commands", Formatter.columns(internal_commands.sort) <del> <del> # Find commands in Homebrew/dev-cmd <add> ohai "Built-in commands", Formatter.columns(Commands.internal_commands) <ide> puts <del> ohai "Built-in developer commands", Formatter.columns(internal_developer_commands.sort) <add> ohai "Built-in developer commands", Formatter.columns(Commands.internal_developer_commands) <ide> <del> exts = external_commands <del> return if exts.empty? <add> external_commands = Commands.external_commands <add> return if external_commands.blank? <ide> <del> # Find commands in the PATH <ide> puts <del> ohai "External commands", Formatter.columns(exts) <del> end <del> <del> def internal_commands <del> find_internal_commands HOMEBREW_LIBRARY_PATH/"cmd" <del> end <del> <del> def internal_developer_commands <del> find_internal_commands HOMEBREW_LIBRARY_PATH/"dev-cmd" <del> end <del> <del> def external_commands <del> cmd_paths = PATH.new(ENV["PATH"]).append(Tap.cmd_directories) <del> cmd_paths.each_with_object([]) do |path, cmds| <del> Dir["#{path}/brew-*"].each do |file| <del> next unless File.executable?(file) <del> <del> cmd = File.basename(file, ".rb")[5..-1] <del> next if cmd.include?(".") <del> <del> cmds << cmd <del> end <del> end.sort <del> end <del> <del> def find_internal_commands(directory) <del> Pathname.glob(directory/"*") <del> .select(&:file?) <del> .map { |f| f.basename.to_s.sub(/\.(?:rb|sh)$/, "") } <add> ohai "External commands", Formatter.columns(external_commands) <ide> end <ide> end <ide><path>Library/Homebrew/commands.rb <ide> # frozen_string_literal: true <ide> <ide> module Commands <del> def self.path(cmd) <add> module_function <add> <add> HOMEBREW_CMD_PATH = (HOMEBREW_LIBRARY_PATH/"cmd").freeze <add> HOMEBREW_DEV_CMD_PATH = (HOMEBREW_LIBRARY_PATH/"dev-cmd").freeze <add> HOMEBREW_INTERNAL_COMMAND_ALIASES = { <add> "ls" => "list", <add> "homepage" => "home", <add> "-S" => "search", <add> "up" => "update", <add> "ln" => "link", <add> "instal" => "install", # gem does the same <add> "uninstal" => "uninstall", <add> "rm" => "uninstall", <add> "remove" => "uninstall", <add> "configure" => "diy", <add> "abv" => "info", <add> "dr" => "doctor", <add> "--repo" => "--repository", <add> "environment" => "--env", <add> "--config" => "config", <add> "-v" => "--version", <add> }.freeze <add> <add> def valid_internal_cmd?(cmd) <add> require?(HOMEBREW_CMD_PATH/cmd) <add> end <add> <add> def valid_internal_dev_cmd?(cmd) <add> require?(HOMEBREW_DEV_CMD_PATH/cmd) <add> end <add> <add> def method_name(cmd) <add> cmd.to_s <add> .tr("-", "_") <add> .downcase <add> .to_sym <add> end <add> <add> def args_method_name(cmd_path) <add> cmd_path_basename = basename_without_extension(cmd_path) <add> cmd_method_prefix = method_name(cmd_path_basename) <add> "#{cmd_method_prefix}_args".to_sym <add> end <add> <add> def internal_cmd_path(cmd) <ide> [ <del> HOMEBREW_LIBRARY_PATH/"cmd/#{cmd}.sh", <del> HOMEBREW_LIBRARY_PATH/"dev-cmd/#{cmd}.sh", <del> HOMEBREW_LIBRARY_PATH/"cmd/#{cmd}.rb", <del> HOMEBREW_LIBRARY_PATH/"dev-cmd/#{cmd}.rb", <add> HOMEBREW_CMD_PATH/"#{cmd}.rb", <add> HOMEBREW_CMD_PATH/"#{cmd}.sh", <ide> ].find(&:exist?) <ide> end <add> <add> def internal_dev_cmd_path(cmd) <add> [ <add> HOMEBREW_DEV_CMD_PATH/"#{cmd}.rb", <add> HOMEBREW_DEV_CMD_PATH/"#{cmd}.sh", <add> ].find(&:exist?) <add> end <add> <add> # Ruby commands which can be `require`d without being run. <add> def external_ruby_v2_cmd_path(cmd) <add> path = which("#{cmd}.rb", Tap.cmd_directories) <add> path if require?(path) <add> end <add> <add> # Ruby commands which are run by being `require`d. <add> def external_ruby_cmd_path(cmd) <add> which("brew-#{cmd}.rb", PATH.new(ENV["PATH"]).append(Tap.cmd_directories)) <add> end <add> <add> def external_cmd_path(cmd) <add> which("brew-#{cmd}", PATH.new(ENV["PATH"]).append(Tap.cmd_directories)) <add> end <add> <add> def path(cmd) <add> internal_cmd = HOMEBREW_INTERNAL_COMMAND_ALIASES.fetch(cmd, cmd) <add> path ||= internal_cmd_path(internal_cmd) <add> path ||= internal_dev_cmd_path(internal_cmd) <add> path ||= external_ruby_v2_cmd_path(cmd) <add> path ||= external_ruby_cmd_path(cmd) <add> path ||= external_cmd_path(cmd) <add> path <add> end <add> <add> def commands(aliases: false) <add> cmds = internal_commands <add> cmds += internal_developer_commands <add> cmds += external_commands <add> cmds += internal_commands_aliases if aliases <add> cmds.sort <add> end <add> <add> def internal_commands_paths <add> find_commands HOMEBREW_CMD_PATH <add> end <add> <add> def internal_developer_commands_paths <add> find_commands HOMEBREW_DEV_CMD_PATH <add> end <add> <add> def internal_commands <add> find_internal_commands(HOMEBREW_CMD_PATH).map(&:to_s) <add> end <add> <add> def internal_developer_commands <add> find_internal_commands(HOMEBREW_DEV_CMD_PATH).map(&:to_s) <add> end <add> <add> def internal_commands_aliases <add> HOMEBREW_INTERNAL_COMMAND_ALIASES.keys <add> end <add> <add> def find_internal_commands(path) <add> find_commands(path).map(&:basename) <add> .map(&method(:basename_without_extension)) <add> end <add> <add> def external_commands <add> Tap.cmd_directories.flat_map do |path| <add> find_commands(path).select(&:executable?) <add> .map(&method(:basename_without_extension)) <add> .map { |p| p.to_s.sub(/^brew(cask)?-/, '\1 ').strip } <add> end.map(&:to_s) <add> .sort <add> end <add> <add> def basename_without_extension(path) <add> path.basename(path.extname) <add> end <add> <add> def find_commands(path) <add> Pathname.glob("#{path}/*") <add> .select(&:file?) <add> .sort <add> end <ide> end <ide><path>Library/Homebrew/dev-cmd/man.rb <ide> def build_man_page <ide> template = (SOURCE_PATH/"brew.1.md.erb").read <ide> variables = OpenStruct.new <ide> <del> variables[:commands] = generate_cmd_manpages("#{HOMEBREW_LIBRARY_PATH}/cmd/*.{rb,sh}") <del> variables[:developer_commands] = generate_cmd_manpages("#{HOMEBREW_LIBRARY_PATH}/dev-cmd/{*.rb,sh}") <add> variables[:commands] = generate_cmd_manpages(Commands.internal_commands_paths) <add> variables[:developer_commands] = generate_cmd_manpages(Commands.internal_developer_commands_paths) <ide> variables[:global_options] = global_options_manpage <ide> <ide> readme = HOMEBREW_REPOSITORY/"README.md" <ide> def target_path_to_format(target) <ide> end <ide> end <ide> <del> def generate_cmd_manpages(glob) <del> cmd_paths = Pathname.glob(glob).sort <add> def generate_cmd_manpages(cmd_paths) <ide> man_page_lines = [] <ide> man_args = Homebrew.args <ide> # preserve existing manpage order <ide><path>Library/Homebrew/global.rb <ide> def auditing? <ide> nil <ide> end.compact.freeze <ide> <del>HOMEBREW_INTERNAL_COMMAND_ALIASES = { <del> "ls" => "list", <del> "homepage" => "home", <del> "-S" => "search", <del> "up" => "update", <del> "ln" => "link", <del> "instal" => "install", # gem does the same <del> "uninstal" => "uninstall", <del> "rm" => "uninstall", <del> "remove" => "uninstall", <del> "configure" => "diy", <del> "abv" => "info", <del> "dr" => "doctor", <del> "--repo" => "--repository", <del> "environment" => "--env", <del> "--config" => "config", <del> "-v" => "--version", <del>}.freeze <del> <ide> require "set" <ide> <ide> require "extend/pathname" <ide><path>Library/Homebrew/help.rb <ide> module Help <ide> <ide> def help(cmd = nil, flags = {}) <ide> # Resolve command aliases and find file containing the implementation. <del> if cmd <del> cmd = HOMEBREW_INTERNAL_COMMAND_ALIASES.fetch(cmd, cmd) <del> path = Commands.path(cmd) <del> path ||= which("brew-#{cmd}") <del> path ||= which("brew-#{cmd}.rb") <del> end <add> path = Commands.path(cmd) if cmd <ide> <ide> # Display command-specific (or generic) help in response to `UsageError`. <ide> if (error_message = flags[:usage_error]) <del> $stderr.puts path ? command_help(path) : HOMEBREW_HELP <add> $stderr.puts path ? command_help(cmd, path) : HOMEBREW_HELP <ide> $stderr.puts <ide> onoe error_message <ide> exit 1 <ide> def help(cmd = nil, flags = {}) <ide> # Resume execution in `brew.rb` for unknown commands. <ide> return if path.nil? <ide> <del> # Display help for commands (or generic help if undocumented). <del> puts command_help(path) <add> # Display help for internal command (or generic help if undocumented). <add> puts command_help(cmd, path) <ide> exit 0 <ide> end <ide> <del> def command_help(path) <del> # Let OptionParser generate help text for commands which have a parser <del> if cmd_parser = CLI::Parser.from_cmd_path(path) <del> return cmd_parser.generate_help_text <add> def command_help(cmd, path) <add> # Only some types of commands can have a parser. <add> output = if Commands.valid_internal_cmd?(cmd) || <add> Commands.valid_internal_dev_cmd?(cmd) || <add> Commands.external_ruby_v2_cmd_path(cmd) <add> parser_help(path) <ide> end <ide> <del> # Otherwise read #: lines from the file. <del> help_lines = command_help_lines(path) <del> if help_lines.blank? <add> output ||= comment_help(path) <add> <add> output ||= if output.blank? <ide> opoo "No help text in: #{path}" if ARGV.homebrew_developer? <del> return HOMEBREW_HELP <add> HOMEBREW_HELP <ide> end <ide> <add> output <add> end <add> <add> def parser_help(path) <add> # Let OptionParser generate help text for commands which have a parser. <add> cmd_parser = CLI::Parser.from_cmd_path(path) <add> return unless cmd_parser <add> <add> cmd_parser.generate_help_text <add> end <add> <add> def comment_help(path) <add> # Otherwise read #: lines from the file. <add> help_lines = command_help_lines(path) <add> return if help_lines.blank? <add> <ide> Formatter.wrap(help_lines.join.gsub(/^ /, ""), COMMAND_DESC_WIDTH) <ide> .sub("@hide_from_man_page ", "") <ide> .sub(/^\* /, "#{Tty.bold}Usage: brew#{Tty.reset} ") <ide><path>Library/Homebrew/test/cmd/commands_spec.rb <ide> # frozen_string_literal: true <ide> <del>require "cmd/command" <ide> require "cmd/commands" <ide> require "fileutils" <ide> <ide> .and be_a_success <ide> end <ide> end <del> <del>RSpec.shared_context "custom internal commands" do <del> let(:cmds) do <del> [ <del> # internal commands <del> HOMEBREW_LIBRARY_PATH/"cmd/rbcmd.rb", <del> HOMEBREW_LIBRARY_PATH/"cmd/shcmd.sh", <del> <del> # internal developer-commands <del> HOMEBREW_LIBRARY_PATH/"dev-cmd/rbdevcmd.rb", <del> HOMEBREW_LIBRARY_PATH/"dev-cmd/shdevcmd.sh", <del> ] <del> end <del> <del> around do |example| <del> cmds.each do |f| <del> FileUtils.touch f <del> end <del> <del> example.run <del> ensure <del> FileUtils.rm_f cmds <del> end <del>end <del> <del>describe Homebrew do <del> include_context "custom internal commands" <del> <del> specify "::internal_commands" do <del> cmds = described_class.internal_commands <del> expect(cmds).to include("rbcmd"), "Ruby commands files should be recognized" <del> expect(cmds).to include("shcmd"), "Shell commands files should be recognized" <del> expect(cmds).not_to include("rbdevcmd"), "Dev commands shouldn't be included" <del> end <del> <del> specify "::internal_developer_commands" do <del> cmds = described_class.internal_developer_commands <del> expect(cmds).to include("rbdevcmd"), "Ruby commands files should be recognized" <del> expect(cmds).to include("shdevcmd"), "Shell commands files should be recognized" <del> expect(cmds).not_to include("rbcmd"), "Non-dev commands shouldn't be included" <del> end <del> <del> specify "::external_commands" do <del> mktmpdir do |dir| <del> %w[brew-t1 brew-t2.rb brew-t3.py].each do |file| <del> path = "#{dir}/#{file}" <del> FileUtils.touch path <del> FileUtils.chmod 0755, path <del> end <del> <del> FileUtils.touch "#{dir}/brew-t4" <del> <del> ENV["PATH"] += "#{File::PATH_SEPARATOR}#{dir}" <del> cmds = described_class.external_commands <del> <del> expect(cmds).to include("t1"), "Executable files should be included" <del> expect(cmds).to include("t2"), "Executable Ruby files should be included" <del> expect(cmds).not_to include("t3"), "Executable files with a non Ruby extension shouldn't be included" <del> expect(cmds).not_to include("t4"), "Non-executable files shouldn't be included" <del> end <del> end <del>end <del> <del>describe Commands do <del> include_context "custom internal commands" <del> <del> describe "::path" do <del> specify "returns the path for an internal command" do <del> expect(described_class.path("rbcmd")).to eq(HOMEBREW_LIBRARY_PATH/"cmd/rbcmd.rb") <del> expect(described_class.path("shcmd")).to eq(HOMEBREW_LIBRARY_PATH/"cmd/shcmd.sh") <del> expect(described_class.path("idontexist1234")).to be nil <del> end <del> <del> specify "returns the path for an internal developer-command" do <del> expect(described_class.path("rbdevcmd")).to eq(HOMEBREW_LIBRARY_PATH/"dev-cmd/rbdevcmd.rb") <del> expect(described_class.path("shdevcmd")).to eq(HOMEBREW_LIBRARY_PATH/"dev-cmd/shdevcmd.sh") <del> end <del> end <del>end <ide><path>Library/Homebrew/test/commands_spec.rb <add># frozen_string_literal: true <add> <add>require "commands" <add> <add>RSpec.shared_context "custom internal commands" do <add> let(:cmds) do <add> [ <add> # internal commands <add> Commands::HOMEBREW_CMD_PATH/"rbcmd.rb", <add> Commands::HOMEBREW_CMD_PATH/"shcmd.sh", <add> <add> # internal developer-commands <add> Commands::HOMEBREW_DEV_CMD_PATH/"rbdevcmd.rb", <add> Commands::HOMEBREW_DEV_CMD_PATH/"shdevcmd.sh", <add> ] <add> end <add> <add> around do |example| <add> cmds.each do |f| <add> FileUtils.touch f <add> end <add> <add> example.run <add> ensure <add> FileUtils.rm_f cmds <add> end <add>end <add> <add>describe Commands do <add> include_context "custom internal commands" <add> <add> specify "::internal_commands" do <add> cmds = described_class.internal_commands <add> expect(cmds).to include("rbcmd"), "Ruby commands files should be recognized" <add> expect(cmds).to include("shcmd"), "Shell commands files should be recognized" <add> expect(cmds).not_to include("rbdevcmd"), "Dev commands shouldn't be included" <add> end <add> <add> specify "::internal_developer_commands" do <add> cmds = described_class.internal_developer_commands <add> expect(cmds).to include("rbdevcmd"), "Ruby commands files should be recognized" <add> expect(cmds).to include("shdevcmd"), "Shell commands files should be recognized" <add> expect(cmds).not_to include("rbcmd"), "Non-dev commands shouldn't be included" <add> end <add> <add> specify "::external_commands" do <add> mktmpdir do |dir| <add> %w[t0.rb brew-t1 brew-t2.rb brew-t3.py].each do |file| <add> path = "#{dir}/#{file}" <add> FileUtils.touch path <add> FileUtils.chmod 0755, path <add> end <add> <add> FileUtils.touch "#{dir}/brew-t4" <add> <add> allow(Tap).to receive(:cmd_directories).and_return([dir]) <add> <add> cmds = described_class.external_commands <add> <add> expect(cmds).to include("t0"), "Executable v2 Ruby files should be included" <add> expect(cmds).to include("t1"), "Executable files should be included" <add> expect(cmds).to include("t2"), "Executable Ruby files should be included" <add> expect(cmds).to include("t3"), "Executable files with a Ruby extension should be included" <add> expect(cmds).not_to include("t4"), "Non-executable files shouldn't be included" <add> end <add> end <add> <add> describe "::path" do <add> specify "returns the path for an internal command" do <add> expect(described_class.path("rbcmd")).to eq(HOMEBREW_LIBRARY_PATH/"cmd/rbcmd.rb") <add> expect(described_class.path("shcmd")).to eq(HOMEBREW_LIBRARY_PATH/"cmd/shcmd.sh") <add> expect(described_class.path("idontexist1234")).to be nil <add> end <add> <add> specify "returns the path for an internal developer-command" do <add> expect(described_class.path("rbdevcmd")).to eq(HOMEBREW_LIBRARY_PATH/"dev-cmd/rbdevcmd.rb") <add> expect(described_class.path("shdevcmd")).to eq(HOMEBREW_LIBRARY_PATH/"dev-cmd/shdevcmd.sh") <add> end <add> end <add>end
10
Javascript
Javascript
add specs for modalmanager
a3479c212a935468396872bf448777196784c880
<ide><path>Libraries/Modal/Modal.js <ide> const AppContainer = require('../ReactNative/AppContainer'); <ide> const I18nManager = require('../ReactNative/I18nManager'); <ide> const NativeEventEmitter = require('../EventEmitter/NativeEventEmitter'); <del>const NativeModules = require('../BatchedBridge/NativeModules'); <add>import NativeModalManager from './NativeModalManager'; <ide> const Platform = require('../Utilities/Platform'); <ide> const React = require('react'); <ide> const PropTypes = require('prop-types'); <ide> const StyleSheet = require('../StyleSheet/StyleSheet'); <ide> const View = require('../Components/View/View'); <ide> <ide> const RCTModalHostView = require('./RCTModalHostViewNativeComponent'); <del> <ide> const ModalEventEmitter = <del> Platform.OS === 'ios' && NativeModules.ModalManager <del> ? new NativeEventEmitter(NativeModules.ModalManager) <add> Platform.OS === 'ios' && NativeModalManager != null <add> ? new NativeEventEmitter(NativeModalManager) <ide> : null; <ide> <ide> import type EmitterSubscription from '../vendor/emitter/EmitterSubscription'; <ide><path>Libraries/Modal/NativeModalManager.js <add>/** <add> * Copyright (c) Facebook, Inc. and its affiliates. <add> * <add> * This source code is licensed under the MIT license found in the <add> * LICENSE file in the root directory of this source tree. <add> * <add> * @flow <add> * @format <add> */ <add> <add>'use strict'; <add> <add>import type {TurboModule} from 'RCTExport'; <add>import * as TurboModuleRegistry from 'TurboModuleRegistry'; <add> <add>export interface Spec extends TurboModule { <add> // RCTEventEmitter <add> +addListener: (eventName: string) => void; <add> +removeListeners: (count: number) => void; <add>} <add> <add>export default TurboModuleRegistry.get<Spec>('ModalManager');
2
Text
Text
remove helmet test instructions
3969f651b8694ac58da6ae181b4268932f8781bf
<ide><path>curriculum/challenges/english/06-quality-assurance/quality-assurance-projects/issue-tracker.english.md <ide> Start this project on Repl.it using <a href="https://repl.it/github/freeCodeCamp <ide> <ide> ```yml <ide> tests: <del> - text: Prevent cross site scripting (XSS) attacks. <del> testString: '' <ide> - text: I can POST /api/issues/{projectname} with form data containing required issue_title, issue_text, created_by, and optional assigned_to and status_text. <ide> testString: '' <ide> - text: The object saved (and returned) will include all of those fields (blank for optional no input) and also include created_on(date/time), updated_on(date/time), open(boolean, true for open, false for closed), and _id. <ide><path>curriculum/challenges/english/06-quality-assurance/quality-assurance-projects/metric-imperial-converter.english.md <ide> Start this project on Repl.it using <a href="https://repl.it/github/freeCodeCamp <ide> <ide> ```yml <ide> tests: <del> - text: I will prevent the client from trying to guess(sniff) the MIME type. <del> testString: '' <del> - text: I will prevent cross-site scripting (XSS) attacks. <del> testString: '' <ide> - text: 'I can GET /api/convert with a single parameter containing an accepted number and unit and have it converted. (Hint: Split the input by looking for the index of the first character which will mark the start of the unit)' <ide> testString: '' <ide> - text: I can convert <code>'gal'</code> to <code>'L'</code> and vice versa. (1 gal to 3.78541 L) <ide><path>curriculum/challenges/english/06-quality-assurance/quality-assurance-projects/personal-library.english.md <ide> Start this project on Repl.it using <a href="https://repl.it/github/freeCodeCamp <ide> <ide> ```yml <ide> tests: <del> - text: Nothing from my website will be cached in my client. <del> testString: '' <del> - text: The headers will say that the site is powered by 'PHP 4.2.0' even though it isn't (as a security measure). <del> testString: '' <ide> - text: I can post a title to /api/books to add a book and returned will be the object with the title and a unique _id. <ide> testString: '' <ide> - text: I can get /api/books to retrieve an array of all books containing title, _id, and commentcount.
3
Javascript
Javascript
remove eslint comments
8d1f15bf992a70eab3107986a4fc71afc16a9c99
<ide><path>test/parallel/test-whatwg-url-tojson.js <ide> const common = require('../common'); <ide> const URL = require('url').URL; <ide> const { test, assert_equals } = common.WPT; <ide> <del>/* eslint-disable */ <ide> /* WPT Refs: <ide> https://github.com/w3c/web-platform-tests/blob/02585db/url/url-tojson.html <ide> License: http://www.w3.org/Consortium/Legal/2008/04-testsuite-copyright.html <ide> */ <ide> test(() => { <del> const a = new URL("https://example.com/") <del> assert_equals(JSON.stringify(a), "\"https://example.com/\"") <del>}) <del>/* eslint-enable */ <add> const a = new URL('https://example.com/'); <add> assert_equals(JSON.stringify(a), '"https://example.com/"'); <add>});
1
Ruby
Ruby
reorganize clean_dir to avoid repeated conditional
095d83d10b6763ecc57f3967898113c98b920063
<ide><path>Library/Homebrew/cleaner.rb <ide> def clean_dir d <ide> d.find do |path| <ide> path.extend(NoisyPathname) if ARGV.verbose? <ide> <del> if path.directory? <del> # Stop cleaning this subtree if protected <del> Find.prune if @f.skip_clean? path <del> elsif not path.file? <del> # Sanity? <add> Find.prune if @f.skip_clean? path <add> <add> if path.symlink? or path.directory? <ide> next <ide> elsif path.extname == '.la' <del> # *.la files are stupid <del> path.unlink unless @f.skip_clean? path <add> path.unlink <ide> elsif path == @f.lib+'charset.alias' <ide> # Many formulae symlink this file, but it is not strictly needed <del> path.unlink unless @f.skip_clean? path <del> elsif not path.symlink? <del> # Fix permissions <del> clean_file_permissions(path) unless @f.skip_clean? path <add> path.unlink <add> else <add> clean_file_permissions(path) <ide> end <ide> end <ide> end
1
Mixed
Ruby
add support for postgresql `interval` datatype
e5a5cc483573f41fa396779057bd83ce389640d8
<ide><path>activerecord/CHANGELOG.md <add>* Add support for PostgreSQL `interval` data type with conversion to <add> `ActiveSupport::Duration` when loading records from database and <add> serialization to ISO 8601 formatted duration string on save. <add> Add support to define a column in migrations and get it in a schema dump. <add> Optional column precision is supported. <add> <add> To use this in 6.1, you need to place the next string to your model file: <add> <add> attribute :duration, :interval <add> <add> To keep old behavior until 6.2 is released: <add> <add> attribute :duration, :string <add> <add> Example: <add> <add> create_table :events do |t| <add> t.string :name <add> t.interval :duration <add> end <add> <add> class Event < ApplicationRecord <add> attribute :duration, :interval <add> end <add> <add> Event.create!(name: 'Rock Fest', duration: 2.days) <add> Event.last.duration # => 2 days <add> Event.last.duration.iso8601 # => "P2D" <add> Event.new(duration: 'P1DT12H3S').duration # => 1 day, 12 hours, and 3 seconds <add> Event.new(duration: '1 day') # Unknown value will be ignored and NULL will be written to database <add> <add> *Andrey Novikov* <add> <ide> * Allow associations supporting the `dependent:` key to take `dependent: :destroy_async`. <ide> <ide> ```ruby <ide><path>activerecord/lib/active_record/connection_adapters/postgresql/oid.rb <ide> require "active_record/connection_adapters/postgresql/oid/enum" <ide> require "active_record/connection_adapters/postgresql/oid/hstore" <ide> require "active_record/connection_adapters/postgresql/oid/inet" <add>require "active_record/connection_adapters/postgresql/oid/interval" <ide> require "active_record/connection_adapters/postgresql/oid/jsonb" <ide> require "active_record/connection_adapters/postgresql/oid/macaddr" <ide> require "active_record/connection_adapters/postgresql/oid/money" <ide><path>activerecord/lib/active_record/connection_adapters/postgresql/oid/interval.rb <add># frozen_string_literal: true <add> <add>require "active_support/duration" <add> <add>module ActiveRecord <add> module ConnectionAdapters <add> module PostgreSQL <add> module OID # :nodoc: <add> class Interval < Type::Value # :nodoc: <add> def type <add> :interval <add> end <add> <add> def cast_value(value) <add> case value <add> when ::ActiveSupport::Duration <add> value <add> when ::String <add> begin <add> ::ActiveSupport::Duration.parse(value) <add> rescue ::ActiveSupport::Duration::ISO8601Parser::ParsingError <add> nil <add> end <add> else <add> super <add> end <add> end <add> <add> def serialize(value) <add> case value <add> when ::ActiveSupport::Duration <add> value.iso8601(precision: self.precision) <add> when ::Numeric <add> # Sometimes operations on Times returns just float number of seconds so we need to handle that. <add> # Example: Time.current - (Time.current + 1.hour) # => -3600.000001776 (Float) <add> value.seconds.iso8601(precision: self.precision) <add> else <add> super <add> end <add> end <add> <add> def type_cast_for_schema(value) <add> serialize(value).inspect <add> end <add> end <add> end <add> end <add> end <add>end <ide><path>activerecord/lib/active_record/connection_adapters/postgresql/schema_statements.rb <ide> def type_to_sql(type, limit: nil, precision: nil, scale: nil, array: nil, **) # <ide> when 5..8; "bigint" <ide> else raise ArgumentError, "No integer type has byte size #{limit}. Use a numeric with scale 0 instead." <ide> end <add> when "interval" <add> case precision <add> when nil; "interval" <add> when 0..6; "interval(#{precision})" <add> else raise(ActiveRecordError, "No interval type has precision of #{precision}. The allowed range of precision is from 0 to 6") <add> end <ide> else <ide> super <ide> end <ide><path>activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb <ide> def initialize_type_map(m = type_map) <ide> m.register_type "polygon", OID::SpecializedString.new(:polygon) <ide> m.register_type "circle", OID::SpecializedString.new(:circle) <ide> <del> m.register_type "interval" do |_, _, sql_type| <del> precision = extract_precision(sql_type) <del> OID::SpecializedString.new(:interval, precision: precision) <del> end <del> <ide> register_class_with_precision m, "time", Type::Time <ide> register_class_with_precision m, "timestamp", OID::DateTime <ide> <ide> def initialize_type_map(m = type_map) <ide> end <ide> end <ide> <add> m.register_type "interval" do |*args, sql_type| <add> precision = extract_precision(sql_type) <add> OID::Interval.new(precision: precision) <add> end <add> <ide> load_additional_types <ide> end <ide> <ide> def configure_connection <ide> end <ide> end <ide> <add> # Set interval output format to ISO 8601 for ease of parsing by ActiveSupport::Duration.parse <add> execute("SET intervalstyle = iso_8601", "SCHEMA") <add> <ide> # SET statements from :variables config hash <ide> # https://www.postgresql.org/docs/current/static/sql-set.html <ide> variables.map do |k, v| <ide> def decode(value, tuple = nil, field = nil) <ide> ActiveRecord::Type.register(:enum, OID::Enum, adapter: :postgresql) <ide> ActiveRecord::Type.register(:hstore, OID::Hstore, adapter: :postgresql) <ide> ActiveRecord::Type.register(:inet, OID::Inet, adapter: :postgresql) <add> ActiveRecord::Type.register(:interval, OID::Interval, adapter: :postgresql) <ide> ActiveRecord::Type.register(:jsonb, OID::Jsonb, adapter: :postgresql) <ide> ActiveRecord::Type.register(:money, OID::Money, adapter: :postgresql) <ide> ActiveRecord::Type.register(:point, OID::Point, adapter: :postgresql) <ide><path>activerecord/lib/active_record/model_schema.rb <ide> def load_schema! <ide> @columns_hash.each do |name, column| <ide> type = connection.lookup_cast_type_from_column(column) <ide> type = _convert_type_from_options(type) <add> warn_if_deprecated_type(column) <ide> define_attribute( <ide> name, <ide> type, <ide> def _convert_type_from_options(type) <ide> type <ide> end <ide> end <add> <add> def warn_if_deprecated_type(column) <add> return if attributes_to_define_after_schema_loads.key?(column.name) <add> return unless column.respond_to?(:oid) <add> <add> if column.array? <add> array_arguments = ", array: true" <add> else <add> array_arguments = "" <add> end <add> <add> if column.sql_type.start_with?("interval") <add> precision_arguments = column.precision.presence && ", precision: #{column.precision}" <add> ActiveSupport::Deprecation.warn(<<~WARNING) <add> The behavior of the `:interval` type will be changing in Rails 6.2 <add> to return an `ActiveSupport::Duration` object. If you'd like to keep <add> the old behavior, you can add this line to #{self.name} model: <add> <add> attribute :#{column.name}, :string#{precision_arguments}#{array_arguments} <add> <add> If you'd like the new behavior today, you can add this line: <add> <add> attribute :#{column.name}, :interval#{precision_arguments}#{array_arguments} <add> WARNING <add> end <add> end <ide> end <ide> end <ide> end <ide><path>activerecord/test/cases/adapters/postgresql/datatype_test.rb <ide> require "support/ddl_helper" <ide> <ide> class PostgresqlTime < ActiveRecord::Base <add> # Declare attributes to get rid from deprecation warnings on ActiveRecord 6.1 <add> attribute :time_interval, :string <add> attribute :scaled_time_interval, :interval <ide> end <ide> <ide> class PostgresqlOid < ActiveRecord::Base <ide> def test_data_type_of_oid_types <ide> end <ide> <ide> def test_time_values <del> assert_equal "-1 years -2 days", @first_time.time_interval <del> assert_equal "-21 days", @first_time.scaled_time_interval <add> assert_equal "P-1Y-2D", @first_time.time_interval <add> assert_equal (-21.day), @first_time.scaled_time_interval <ide> end <ide> <ide> def test_oid_values <ide> assert_equal 1234, @first_oid.obj_id <ide> end <ide> <del> def test_update_time <del> @first_time.time_interval = "2 years 3 minutes" <del> assert @first_time.save <del> assert @first_time.reload <del> assert_equal "2 years 00:03:00", @first_time.time_interval <del> end <del> <ide> def test_update_oid <ide> new_value = 2147483648 <ide> @first_oid.obj_id = new_value <ide><path>activerecord/test/cases/adapters/postgresql/interval_test.rb <add># encoding: utf-8 <add># frozen_string_literal: true <add> <add>require "cases/helper" <add>require "support/schema_dumping_helper" <add> <add>class PostgresqlIntervalTest < ActiveRecord::TestCase <add> include SchemaDumpingHelper <add> <add> class IntervalDataType < ActiveRecord::Base <add> attribute :maximum_term, :interval <add> attribute :minimum_term, :interval, precision: 3 <add> attribute :default_term, :interval <add> attribute :all_terms, :interval, array: true <add> attribute :legacy_term, :string <add> end <add> <add> class DeprecatedIntervalDataType < ActiveRecord::Base; end <add> <add> def setup <add> @connection = ActiveRecord::Base.connection <add> begin <add> @connection.transaction do <add> @connection.create_table("interval_data_types") do |t| <add> t.interval "maximum_term" <add> t.interval "minimum_term", precision: 3 <add> t.interval "default_term", default: "P3Y" <add> t.interval "all_terms", array: true <add> t.interval "legacy_term" <add> end <add> @connection.create_table("deprecated_interval_data_types") do |t| <add> t.interval "duration" <add> end <add> end <add> end <add> @column_max = IntervalDataType.columns_hash["maximum_term"] <add> @column_min = IntervalDataType.columns_hash["minimum_term"] <add> assert(@column_max.is_a?(ActiveRecord::ConnectionAdapters::PostgreSQLColumn)) <add> assert(@column_min.is_a?(ActiveRecord::ConnectionAdapters::PostgreSQLColumn)) <add> assert_nil @column_max.precision <add> assert_equal 3, @column_min.precision <add> end <add> <add> teardown do <add> @connection.execute "DROP TABLE IF EXISTS interval_data_types" <add> @connection.execute "DROP TABLE IF EXISTS deprecated_interval_data_types" <add> end <add> <add> def test_column <add> assert_equal :interval, @column_max.type <add> assert_equal :interval, @column_min.type <add> assert_equal "interval", @column_max.sql_type <add> assert_equal "interval(3)", @column_min.sql_type <add> end <add> <add> def test_interval_type <add> IntervalDataType.create!( <add> maximum_term: 6.year + 5.month + 4.days + 3.hours + 2.minutes + 1.seconds, <add> minimum_term: 1.year + 2.month + 3.days + 4.hours + 5.minutes + (6.234567).seconds, <add> all_terms: [1.month, 1.year, 1.hour], <add> legacy_term: "33 years", <add> ) <add> i = IntervalDataType.last! <add> assert_equal "P6Y5M4DT3H2M1S", i.maximum_term.iso8601 <add> assert_equal "P1Y2M3DT4H5M6.235S", i.minimum_term.iso8601 <add> assert_equal "P3Y", i.default_term.iso8601 <add> assert_equal %w[ P1M P1Y PT1H ], i.all_terms.map(&:iso8601) <add> assert_equal "P33Y", i.legacy_term <add> end <add> <add> def test_interval_type_cast_from_invalid_string <add> i = IntervalDataType.create!(maximum_term: "1 year 2 minutes") <add> i.reload <add> assert_nil i.maximum_term <add> end <add> <add> def test_interval_type_cast_from_numeric <add> i = IntervalDataType.create!(minimum_term: 36000) <add> i.reload <add> assert_equal "PT10H", i.minimum_term.iso8601 <add> end <add> <add> def test_interval_type_cast_string_and_numeric_from_user <add> i = IntervalDataType.new(maximum_term: "P1YT2M", minimum_term: "PT10H", legacy_term: "P1DT1H") <add> assert i.maximum_term.is_a?(ActiveSupport::Duration) <add> assert i.legacy_term.is_a?(String) <add> assert_equal "P1YT2M", i.maximum_term.iso8601 <add> assert_equal "PT10H", i.minimum_term.iso8601 <add> assert_equal "P1DT1H", i.legacy_term <add> end <add> <add> def test_deprecated_legacy_type <add> assert_deprecated do <add> DeprecatedIntervalDataType.new <add> end <add> end <add> <add> def test_schema_dump_with_default_value <add> output = dump_table_schema "interval_data_types" <add> assert_match %r{t\.interval "default_term", default: "P3Y"}, output <add> end <add>end <ide><path>guides/source/active_record_postgresql.md <ide> macbook.address <ide> All geometric types, with the exception of `points` are mapped to normal text. <ide> A point is casted to an array containing `x` and `y` coordinates. <ide> <add>### Interval <add> <add>* [type definition](http://www.postgresql.org/docs/current/static/datatype-datetime.html#DATATYPE-INTERVAL-INPUT) <add>* [functions and operators](http://www.postgresql.org/docs/current/static/functions-datetime.html) <add> <add>This type is mapped to [`ActiveSupport::Duration`](http://api.rubyonrails.org/classes/ActiveSupport/Duration.html) objects. <add> <add>```ruby <add># db/migrate/20200120000000_create_events.rb <add>create_table :events do |t| <add> t.interval 'duration' <add>end <add> <add># app/models/event.rb <add>class Event < ApplicationRecord <add>end <add> <add># Usage <add>Event.create(duration: 2.days) <add> <add>event = Event.first <add>event.duration # => 2 days <add>``` <ide> <ide> UUID Primary Keys <ide> -----------------
9
Javascript
Javascript
use the `tothrowminerr()` matcher when possible
fbf30b28e0a3de717e3f8eb605a4920da080211b
<ide><path>test/AngularSpec.js <ide> describe('angular', function() { <ide> <ide> expect(function() { <ide> angularInit(appElement, angular.bootstrap); <del> }).toThrowError( <del> new RegExp('\\[\\$injector:modulerr] Failed to instantiate module doesntexist due to:\\n' + <add> }).toThrowMinErr('$injector', 'modulerr', <add> new RegExp('Failed to instantiate module doesntexist due to:\\n' + <ide> '.*\\[\\$injector:nomod] Module \'doesntexist\' is not available! You either ' + <ide> 'misspelled the module name or forgot to load it\\.') <ide> ); <ide> describe('angular', function() { <ide> <ide> expect(function() { <ide> angular.bootstrap(element); <del> }).toThrowError( <del> /\[ng:btstrpd\] App Already Bootstrapped with this Element '&lt;div class="?ng\-scope"?( ng[0-9]+="?[0-9]+"?)?&gt;'/i <del> ); <add> }).toThrowMinErr('ng', 'btstrpd', <add> /App Already Bootstrapped with this Element '&lt;div class="?ng-scope"?( ng\d+="?\d+"?)?&gt;'/i); <ide> <ide> dealoc(element); <ide> }); <ide> describe('angular', function() { <ide> angular.bootstrap(document.getElementsByTagName('html')[0]); <ide> expect(function() { <ide> angular.bootstrap(document); <del> }).toThrowError( <del> /\[ng:btstrpd\] App Already Bootstrapped with this Element 'document'/i <del> ); <add> }).toThrowMinErr('ng', 'btstrpd', /App Already Bootstrapped with this Element 'document'/i); <ide> <ide> dealoc(document); <ide> }); <ide> describe('angular', function() { <ide> <ide> expect(function() { <ide> angular.bootstrap(element, ['doesntexist']); <del> }).toThrowError( <del> new RegExp('\\[\\$injector:modulerr\\] Failed to instantiate module doesntexist due to:\\n' + <add> }).toThrowMinErr('$injector', 'modulerr', <add> new RegExp('Failed to instantiate module doesntexist due to:\\n' + <ide> '.*\\[\\$injector:nomod\\] Module \'doesntexist\' is not available! You either ' + <ide> 'misspelled the module name or forgot to load it\\.')); <ide> <ide><path>test/auto/injectorSpec.js <ide> describe('injector', function() { <ide> createInjector([function($provide) { <ide> $provide.value('name', 'angular'); <ide> }, instanceLookupInModule]); <del> }).toThrowError(/\[\$injector:unpr] Unknown provider: name/); <add> }).toThrowMinErr('$injector', 'modulerr', '[$injector:unpr] Unknown provider: name'); <ide> }); <ide> }); <ide> }); <ide><path>test/jqLiteSpec.js <ide> describe('jqLite', function() { <ide> aElem.on('click', noop); <ide> expect(function() { <ide> aElem.off('click', noop, '.test'); <del> }).toThrowError(/\[jqLite:offargs\]/); <add> }).toThrowMinErr('jqLite', 'offargs'); <ide> }); <ide> }); <ide> <ide><path>test/ng/directive/validatorsSpec.js <ide> describe('validators', function() { <ide> expect(function() { <ide> var inputElm = helper.compileInput('<input type="text" ng-model="foo" ng-pattern="fooRegexp" />'); <ide> $rootScope.$apply('foo = \'bar\''); <del> }).not.toThrowError(/^\[ngPattern:noregexp\] Expected fooRegexp to be a RegExp but was/); <add> }).not.toThrow(); <ide> }); <ide> <ide> <ide> describe('validators', function() { <ide> $rootScope.fooRegexp = {}; <ide> $rootScope.foo = 'bar'; <ide> }); <del> }).toThrowError(/^\[ngPattern:noregexp\] Expected fooRegexp to be a RegExp but was/); <add> }).toThrowMinErr('ngPattern', 'noregexp', 'Expected fooRegexp to be a RegExp but was'); <ide> }); <ide> <ide>
4
Ruby
Ruby
remove escape characters
88e5c4c333c72238e4e93116fdecf45194310539
<ide><path>Library/Contributions/cmd/brew-test-bot.rb <ide> def run <ide> testcase.attributes['time'] = step.time <ide> failure = testcase.add_element 'failure' if step.failed? <ide> if step.has_output? <del> # Remove null characters from step output. <del> output = REXML::CData.new step.output.delete("\000") <add> # Remove invalid XML CData characters from step output. <add> output = REXML::CData.new step.output.delete("\000\e") <ide> if step.passed? <ide> system_out = testcase.add_element 'system-out' <ide> system_out.text = output
1
Python
Python
fix python 3.2 test failure
d4a211a0f1905c3ef597d63440d04deb78659e96
<ide><path>libcloud/utils/iso8601.py <ide> from datetime import datetime, timedelta, tzinfo <ide> import re <ide> <add>from libcloud.utils.py3 import basestring <add> <ide> __all__ = ["parse_date", "ParseError"] <ide> <ide> # Adapted from http://delete.me.uk/2005/03/iso8601.html
1
Javascript
Javascript
remove unneeded comma at the end of spherical
780dbe8c5dda2149a682bf6687d0732bffaab3cd
<ide><path>src/math/Spherical.js <ide> Spherical.prototype = { <ide> <ide> return this; <ide> <del> }, <add> } <ide> <ide> }; <ide>
1
Javascript
Javascript
add documentation for navigationcardstack
d6003677159d1f68bfa6c91c64b6acc008b36834
<ide><path>Libraries/CustomComponents/NavigationExperimental/NavigationCardStack.js <ide> type DefaultProps = { <ide> /** <ide> * A controlled navigation view that renders a stack of cards. <ide> * <add> * ```html <ide> * +------------+ <ide> * +-| Header | <ide> * +-+ |------------| <ide> type DefaultProps = { <ide> * +-+ | | <ide> * +-+ | <ide> * +------------+ <add> * ``` <add> * <add> * ## Example <add> * <add> * ```js <add> * <add> * class App extends React.Component { <add> * constructor(props, context) { <add> * this.state = { <add> * navigation: { <add> * index: 0, <add> * routes: [ <add> * {key: 'page 1'}, <add> * }, <add> * }, <add> * }; <add> * } <add> * <add> * render() { <add> * return ( <add> * <NavigationCardStack <add> * navigationState={this.state.navigation} <add> * renderScene={this._renderScene} <add> * /> <add> * ); <add> * } <add> * <add> * _renderScene: (props) => { <add> * return ( <add> * <View> <add> * <Text>{props.scene.route.key}</Text> <add> * </View> <add> * ); <add> * }; <add> * ``` <ide> */ <ide> class NavigationCardStack extends React.Component<DefaultProps, Props, void> { <ide> _render : NavigationSceneRenderer; <ide> _renderScene : NavigationSceneRenderer; <ide> <ide> static propTypes = { <add> /** <add> * Custom style applied to the card. <add> */ <add> cardStyle: View.propTypes.style, <add> <add> /** <add> * Direction of the cards movement. Value could be `horizontal` or <add> * `vertical`. Default value is `horizontal`. <add> */ <ide> direction: PropTypes.oneOf([Directions.HORIZONTAL, Directions.VERTICAL]), <add> <add> /** <add> * The distance from the edge of the card which gesture response can start <add> * for. Defaults value is `30`. <add> */ <add> gestureResponseDistance: PropTypes.number, <add> <add> /** <add> * The controlled navigation state. Typically, the navigation state <add> * look like this: <add> * <add> * ```js <add> * const navigationState = { <add> * index: 0, // the index of the selected route. <add> * routes: [ // A list of routes. <add> * {key: 'page 1'}, // The 1st route. <add> * {key: 'page 2'}, // The second route. <add> * ], <add> * }; <add> * ``` <add> */ <ide> navigationState: NavigationPropTypes.navigationState.isRequired, <add> <add> /** <add> * Callback that is called when the "back" action is performed. <add> * This happens when the back button is pressed or the back gesture is <add> * performed. <add> */ <ide> onNavigateBack: PropTypes.func, <add> <add> /** <add> * Function that renders the header. <add> */ <ide> renderHeader: PropTypes.func, <add> <add> /** <add> * Function that renders the a scene for a route. <add> */ <ide> renderScene: PropTypes.func.isRequired, <del> cardStyle: View.propTypes.style, <del> gestureResponseDistance: PropTypes.number, <add> <add> /** <add> * Custom style applied to the cards stack. <add> */ <add> style: View.propTypes.style, <ide> }; <ide> <ide> static defaultProps: DefaultProps = {
1
Text
Text
wrap a couple of long lines
cf30b85eb1d3ecbf27c35ea344a5f68934c1bd2b
<ide><path>CONTRIBUTING.md <ide> # Contributing to Docker <ide> <del>Want to hack on Docker? Awesome! Here are instructions to get you started. They are probably not perfect, please let us know if anything feels <del>wrong or incomplete. <add>Want to hack on Docker? Awesome! Here are instructions to get you <add>started. They are probably not perfect, please let us know if anything <add>feels wrong or incomplete. <ide> <ide> ## Build Environment <ide> <del>For instructions on setting up your development environment, please see our dedicated [dev environment setup docs](http://docs.docker.io/en/latest/contributing/devenvironment/). <add>For instructions on setting up your development environment, please <add>see our dedicated [dev environment setup <add>docs](http://docs.docker.io/en/latest/contributing/devenvironment/). <ide> <ide> ## Contribution guidelines <ide>
1
Python
Python
remove a remaining instance of old naming
da20a4ccd2cf5d9033358b55589a2f75a83d1dea
<ide><path>keras/models.py <ide> def compile(self, optimizer, loss, class_mode="categorical", theano_mode=None): <ide> raise Exception("Invalid class mode:" + str(class_mode)) <ide> self.class_mode = class_mode <ide> <del> if hasattr(self, 'cost_updates'): <add> if hasattr(self, 'loss_update'): <ide> for u in self.loss_updates: <ide> train_loss = u.update_loss(train_loss) <ide> <ide> def load_weights(self, filepath): <ide> weights = [g['param_{}'.format(p)] for p in range(g.attrs['nb_params'])] <ide> self.layers[k].set_weights(weights) <ide> f.close() <del> <del> <del>class Autoencoder(Sequential): <del> <del> def __init__(self, encoder, decoder): <del> super(Autoencoder,self).__init__() <del> self.encoder = encoder <del> self.decoder = decoder <del> <del> self.add(Merge([self.encoder])) <del> self.add(Merge([self.decoder])) <del> <del> def train(self, X, **kwargs): <del> super(Autoencoder,self).train(X,X,**kwargs) <del> <del> def test(self, X, **kwargs): <del> super(Autoencoder,self).test(X,X,**kwargs) <del> <del> def fit(self, X, **kwargs): <del> super(Autoencoder,self).fit(X,X,**kwargs) <del> <del> def freeze_encoder(self): <del> class ZeroGrad(regularizers.Regularizer): <del> <del> def update_gradient(self, gradient, params): <del> return 0.*gradient <del> <del> zero_grad = ZeroGrad() <del> self.encoder.regularizers = [zero_grad for r in self.encoder.regularizers]
1
Javascript
Javascript
increase coverage for net/blocklist
ed3a4c8bca0b59a7c805e1db076d1654cf3a1ac4
<ide><path>test/parallel/test-blocklist.js <ide> require('../common'); <ide> <ide> const { BlockList } = require('net'); <ide> const assert = require('assert'); <add>const util = require('util'); <ide> <ide> { <ide> const blockList = new BlockList(); <ide> const assert = require('assert'); <ide> assert(blockList.check('8592:757c:efaf:1fff:ffff:ffff:ffff:ffff', 'ipv6')); <ide> assert(!blockList.check('8592:757c:efaf:2fff:ffff:ffff:ffff:ffff', 'ipv6')); <ide> } <add> <add>{ <add> assert.throws(() => new BlockList('NOT BLOCK LIST HANDLE'), /ERR_INVALID_ARG_TYPE/); <add>} <add> <add>{ <add> const blockList = new BlockList(); <add> assert.throws(() => blockList.addRange('1.1.1.2', '1.1.1.1'), /ERR_INVALID_ARG_VALUE/); <add>} <add> <add>{ <add> const blockList = new BlockList(); <add> assert.throws(() => blockList.addSubnet(1), /ERR_INVALID_ARG_TYPE/); <add> assert.throws(() => blockList.addSubnet('', ''), /ERR_INVALID_ARG_TYPE/); <add> assert.throws(() => blockList.addSubnet('', 1, 1), /ERR_INVALID_ARG_TYPE/); <add> assert.throws(() => blockList.addSubnet('', 1, ''), /ERR_INVALID_ARG_VALUE/); <add> <add> assert.throws(() => blockList.addSubnet('', -1, 'ipv4'), /ERR_OUT_OF_RANGE/); <add> assert.throws(() => blockList.addSubnet('', 33, 'ipv4'), /ERR_OUT_OF_RANGE/); <add> <add> assert.throws(() => blockList.addSubnet('', -1, 'ipv6'), /ERR_OUT_OF_RANGE/); <add> assert.throws(() => blockList.addSubnet('', 129, 'ipv6'), /ERR_OUT_OF_RANGE/); <add>} <add> <add>{ <add> const blockList = new BlockList(); <add> assert.throws(() => blockList.check(1), /ERR_INVALID_ARG_TYPE/); <add> assert.throws(() => blockList.check('', 1), /ERR_INVALID_ARG_TYPE/); <add> assert.throws(() => blockList.check('', ''), /ERR_INVALID_ARG_VALUE/); <add>} <add> <add>{ <add> const blockList = new BlockList(); <add> const ret = util.inspect(blockList, { depth: -1 }); <add> assert.strictEqual(ret, '[BlockList]'); <add>} <add> <add>{ <add> const blockList = new BlockList(); <add> const ret = util.inspect(blockList, { depth: null }); <add> assert(ret.includes('rules: []')); <add>}
1
Text
Text
update changelog.md for 1.4.0-beta.3
a29ee8b87dab1b13024ce5fc8d48d6ced1344f31
<ide><path>CHANGELOG.md <ide> # Ember Changelog <ide> <add>### Ember 1.4.0-beta.3 (January 20, 2014) <add> <add>* Document the send method on Ember.ActionHandler. <add>* Document Ember.Route #controllerName and #viewName properties. <add>* Allow jQuery version 1.11 and 2.1. <add> <ide> ### Ember 1.4.0-beta.2 (January 14, 2014) <ide> <ide> * [BUGFIX] Fix stripping trailing slashes for * routes.
1
Python
Python
run tests in alphabetical order
a6756a2c064c21b41fc0ab0379bd4e055feb8bc0
<ide><path>tools/test.py <ide> def ListTests(self, current_path, path, context, mode): <ide> if not name or name.match(test_name): <ide> full_path = current_path + [test_name] <ide> test.AddTestsToList(result, full_path, path, context, mode) <add> result.sort(cmp=lambda a, b: cmp(a.GetName(), b.GetName())) <ide> return result <ide> <ide> def GetTestStatus(self, context, sections, defs):
1
Python
Python
add test coverage for get_task_name() in pr
f51204f13a6efafd746ad4f61d0ec8ce4229b355
<ide><path>t/unit/tasks/test_trace.py <ide> from celery import group, uuid <ide> from celery import signals <ide> from celery import states <add>from celery.app.task import Context <ide> from celery.exceptions import Ignore, Retry, Reject <ide> from celery.app.trace import ( <ide> TraceInfo, <ide> build_tracer, <ide> get_log_policy, <add> get_task_name, <ide> log_policy_reject, <ide> log_policy_ignore, <ide> log_policy_internal, <ide> def test_get_log_policy(self): <ide> einfo2.internal = True <ide> assert (get_log_policy(self.add, einfo2, KeyError()) is <ide> log_policy_internal) <add> <add> def test_get_task_name(self): <add> assert get_task_name(Context({}), 'default') == 'default' <add> assert get_task_name(Context({'shadow': None}), 'default') == 'default' <add> assert get_task_name(Context({'shadow': ''}), 'default') == 'default' <add> assert get_task_name(Context({'shadow': 'test'}), 'default') == 'test' <ide> <ide> def test_trace_after_return(self): <ide>
1
Ruby
Ruby
use example.com as standard (closes ) [anna]
932622294194888cf7f9c5a10c082b75f0b7ab8d
<ide><path>actionpack/lib/action_controller/integration.rb <ide> def reset! <ide> @cookies = {} <ide> @controller = @request = @response = nil <ide> <del> self.host = "www.example.test" <add> self.host = "www.example.com" <ide> self.remote_addr = "127.0.0.1" <ide> self.accept = "text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5" <ide> <ide> def https? <ide> <ide> # Set the host name to use in the next request. <ide> # <del> # session.host! "www.example.test" <add> # session.host! "www.example.com" <ide> def host!(name) <ide> @host = name <ide> end <ide><path>railties/lib/console_app.rb <ide> def app(create=false) <ide> @app_integration_instance = nil if create <ide> @app_integration_instance ||= new_session do |sess| <del> sess.host! "www.example.test" <add> sess.host! "www.example.com" <ide> end <ide> end <ide>
2
Text
Text
add tobias to the tsc
7c211366ee498e4003a1fba6803e776168fbeef5
<ide><path>README.md <ide> For information about the governance of the Node.js project, see <ide> **Michaël Zasso** &lt;targos@protonmail.com&gt; (he/him) <ide> * [thefourtheye](https://github.com/thefourtheye) - <ide> **Sakthipriyan Vairamani** &lt;thechargingvolcano@gmail.com&gt; (he/him) <add>* [tniessen](https://github.com/tniessen) - <add>**Tobias Nießen** &lt;tniessen@tnie.de&gt; <ide> * [Trott](https://github.com/Trott) - <ide> **Rich Trott** &lt;rtrott@gmail.com&gt; (he/him) <ide>
1
PHP
PHP
remove failing assertions
f96433678711ab3c8f31ce223454af3f7e9e3fd1
<ide><path>tests/Support/SupportStrTest.php <ide> public function testStrContains() <ide> public function testStrContainsAll() <ide> { <ide> $this->assertTrue(Str::containsAll('taylor otwell', ['taylor', 'otwell'])); <del> $this->assertTrue(Str::containsAll('taylor otwell', 'taylor')); <ide> $this->assertTrue(Str::containsAll('taylor otwell', ['taylor'])); <del> $this->assertFalse(Str::containsAll('taylor otwell', 'xxx')); <ide> $this->assertFalse(Str::containsAll('taylor otwell', ['taylor', 'xxx'])); <ide> } <ide>
1
Javascript
Javascript
add failing test
464d9502d6221946864028a716d1c4f8b5fe35f9
<ide><path>packages/ember-metal/tests/watching/watch_test.js <ide> testBoth('watching a regular defined property', function(get, set) { <ide> set(obj, 'foo', 'bar'); <ide> equal(willCount, 1, 'should have invoked willCount'); <ide> equal(didCount, 1, 'should have invoked didCount'); <add> <add> equal(get(obj, 'foo'), 'bar', 'should get new value'); <add> equal(obj.foo, 'bar', 'property should be accessible on obj'); <add>}); <add> <add>testBoth('watching a regular undefined property', function(get, set) { <add> <add> var obj = { }; <add> <add> Ember.watch(obj, 'foo'); <add> <add> equal('foo' in obj, false, 'precond undefined'); <add> <add> set(obj, 'foo', 'bar'); <add> <add> equal(willCount, 1, 'should have invoked willCount'); <add> equal(didCount, 1, 'should have invoked didCount'); <add> <add> equal(get(obj, 'foo'), 'bar', 'should get new value'); <add> equal(obj.foo, 'bar', 'property should be accessible on obj'); <ide> }); <ide> <ide> testBoth('watches should inherit', function(get, set) {
1
PHP
PHP
apply fixes from styleci
294eac84b5d268fd39004a46037c0a2d2623ba97
<ide><path>src/Illuminate/Database/Query/Grammars/PostgresGrammar.php <ide> protected function compileLock(Builder $query, $value) <ide> } <ide> <ide> /** <del> * @inheritdoc <add> * {@inheritdoc} <ide> */ <ide> public function compileInsert(Builder $query, array $values) <ide> {
1
PHP
PHP
allow custom messages
86e0a082eb43beb93d8677742c3b3b4fe42bc338
<ide><path>src/Illuminate/Foundation/Http/FormRequest.php <ide> class FormRequest extends Request { <ide> public function validate(ValidationFactory $factory) <ide> { <ide> $instance = $factory->make( <del> $this->input(), $this->container->call([$this, 'rules']) <add> $this->input(), $this->container->call([$this, 'rules']), $this->container->call([$this, 'messages']) <ide> ); <ide> <ide> if ($instance->fails())
1
PHP
PHP
fix missing base path on generated urls
2f2237b1164a7539ba4bcd80352201a6bca0402c
<ide><path>lib/Cake/Routing/Router.php <ide> public static function url($url = null, $options = array()) { <ide> $hasLeadingSlash = isset($url[0]) ? $url[0] === '/' : false; <ide> } <ide> <add> $params = array( <add> 'plugin' => null, <add> 'controller' => null, <add> 'action' => 'index' <add> ); <add> $here = $base = $output = $frag = null; <add> <ide> $request = static::getRequest(true); <ide> if ($request) { <ide> $params = $request->params; <ide> $here = $request->here; <del> } else { <del> $params = array( <del> 'plugin' => null, <del> 'controller' => null, <del> 'action' => 'index' <del> ); <del> $here = null; <add> $base = $request->base; <ide> } <ide> <del> $output = $frag = null; <del> <ide> if (empty($url)) { <ide> $output = isset($here) ? $here : '/'; <ide> if ($full && defined('FULL_BASE_URL')) { <del> $output = FULL_BASE_URL . $output; <add> $output = FULL_BASE_URL . $base . $output; <ide> } <ide> return $output; <ide> } elseif ($urlType === 'array') { <ide> public static function url($url = null, $options = array()) { <ide> if ($hasColonSlash || $plainString) { <ide> return $url; <ide> } <del> if ($hasLeadingSlash) { <del> $output = substr($url, 1); <add> $output = $url; <add> if ($hasLeadingSlash && strlen($output) > 1) { <add> $output = substr($output, 1); <ide> } <add> $output = $base . $output; <ide> } <ide> $protocol = preg_match('#^[a-z][a-z0-9+-.]*\://#i', $output); <ide> if ($protocol === 0) { <ide><path>lib/Cake/Test/TestCase/Routing/RouterTest.php <ide> public function tearDown() { <ide> * @return void <ide> */ <ide> public function testFullBaseURL() { <del> $skip = PHP_SAPI == 'cli'; <del> if ($skip) { <del> $this->markTestSkipped('Cannot validate base urls in CLI'); <del> } <ide> $this->assertRegExp('/^http(s)?:\/\//', Router::url('/', true)); <ide> $this->assertRegExp('/^http(s)?:\/\//', Router::url(null, true)); <ide> $this->assertRegExp('/^http(s)?:\/\//', Router::url(array('_full' => true))); <del> $this->assertSame(FULL_BASE_URL . '/', Router::url(array('_full' => true))); <ide> } <ide> <ide> /** <ide> public function testUrlNormalization() { <ide> } <ide> <ide> /** <del> * test generation of basic urls. <del> * <del> * @return void <add> * Test generating urls with base paths. <ide> */ <del> public function testUrlGenerationBasic() { <del> extract(Router::getNamedExpressions()); <del> <add> public function testUrlGenerationWithBasePath() { <add> Router::connect('/:controller/:action/*'); <ide> $request = new Request(); <del> $request->addParams(array( <del> 'action' => 'index', 'plugin' => null, 'controller' => 'subscribe', 'admin' => true <del> )); <add> $request->addParams([ <add> 'action' => 'index', <add> 'plugin' => null, <add> 'controller' => 'subscribe', <add> ]); <ide> $request->base = '/magazine'; <del> $request->here = '/magazine'; <add> $request->here = '/magazine/'; <ide> $request->webroot = '/magazine/'; <del> Router::setRequestInfo($request); <add> Router::pushRequest($request); <ide> <ide> $result = Router::url(); <del> $this->assertEquals('/magazine', $result); <add> $this->assertEquals('/magazine/', $result); <add> <add> $result = Router::url('/'); <add> $this->assertEquals('/magazine/', $result); <add> <add> $result = Router::url(['controller' => 'articles', 'action' => 'view', 1]); <add> $this->assertEquals('/magazine/articles/view/1', $result); <add> } <add> <add>/** <add> * test generation of basic urls. <add> * <add> * @return void <add> */ <add> public function testUrlGenerationBasic() { <add> extract(Router::getNamedExpressions()); <ide> <del> Router::reload(); <ide> <ide> Router::connect('/', array('controller' => 'pages', 'action' => 'display', 'home')); <ide> $out = Router::url(array('controller' => 'pages', 'action' => 'display', 'home'));
2
Text
Text
fix typo in description of close event
b359096f2f9a1d36a7a0d32e50160d5af1802e21
<ide><path>doc/api/http.md <ide> passed as the second parameter to the [`'request'`][] event. <ide> added: v0.6.7 <ide> --> <ide> <del>Indicates that the the response is completed, or its underlying connection was <add>Indicates that the response is completed, or its underlying connection was <ide> terminated prematurely (before the response completion). <ide> <ide> ### Event: `'finish'`
1
Javascript
Javascript
improve description and example
29274e1d8d8b3c6a9100758da4a3c78222e77af1
<ide><path>src/Angular.js <ide> function encodeUriQuery(val, pctEncodeSpaces) { <ide> * <ide> * @description <ide> * <del> * Use this directive to auto-bootstrap an application. Only <del> * one ngApp directive can be used per HTML document. The directive <del> * designates the root of the application and is typically placed <del> * at the root of the page. <add> * Use this directive to **auto-bootstrap** an AngularJS application. The `ngApp` directive <add> * designates the **root element** of the application and is typically placed near the root element <add> * of the page - e.g. on the `<body>` or `<html>` tags. <ide> * <del> * The first ngApp found in the document will be auto-bootstrapped. To use multiple applications in <del> * an HTML document you must manually bootstrap them using {@link angular.bootstrap}. <del> * Applications cannot be nested. <add> * Only one AngularJS application can be auto-bootstrapped per HTML document. The first `ngApp` <add> * found in the document will be used to define the root element to auto-bootstrap as an <add> * application. To run multiple applications in an HTML document you must manually bootstrap them using <add> * {@link angular.bootstrap} instead. AngularJS applications cannot be nested within each other. <ide> * <del> * In the example below if the `ngApp` directive were not placed <del> * on the `html` element then the document would not be compiled <del> * and the `{{ 1+2 }}` would not be resolved to `3`. <add> * You can specify an **AngularJS module** to be used as the root module for the application. This <add> * module will be loaded into the {@link AUTO.$injector} when the application is bootstrapped and <add> * should contain the application code needed or have dependencies on other modules that will <add> * contain the code. See {@link angular.module} for more information. <ide> * <del> * `ngApp` is the easiest way to bootstrap an application. <add> * In the example below if the `ngApp` directive were not placed on the `html` element then the <add> * document would not be compiled, the `AppController` would not be instantiated and the `{{ a+b }}` <add> * would not be resolved to `3`. <ide> * <del> <doc:example> <del> <doc:source> <del> I can add: 1 + 2 = {{ 1+2 }} <del> </doc:source> <del> </doc:example> <add> * `ngApp` is the easiest, and most common, way to bootstrap an application. <add> * <add> <example module="ngAppDemo"> <add> <file name="index.html"> <add> <div ng-controller="ngAppDemoController"> <add> I can add: {{a}} + {{b}} = {{ a+b }} <add> </file> <add> <file name="script.js"> <add> angular.module('ngAppDemo', []).controller('ngAppDemoController', function($scope) { <add> $scope.a = 1; <add> $scope.b = 2; <add> }); <add> </file> <add> </example> <ide> * <ide> */ <ide> function angularInit(element, bootstrap) {
1
Text
Text
suggest use of the github gem when contributing
6ad2907000d927e055cacf389228ebdc01fcc0d7
<ide><path>README.md <ide> Contributing New Formulae <ide> ========================= <ide> Formulae are simple Ruby scripts. Generate a formula with most bits filled-in: <ide> <del> brew create http://foo.org/foobar-1.2.1.tar.bz2 <add> brew create http://example.com/foo-1.2.1.tar.bz2 <ide> <ide> Check it over and try to install it: <ide> <del> brew install foobar <add> brew install foo <ide> <ide> Check the [wiki][] for more detailed information and tips for contribution. <ide> <ide> If you want your formula to become part of this distribution, fork <ide> maintain your own distribution. Maybe you want to support Tiger? Or use <ide> special compile flags? Go ahead that's what git is all about! :) <ide> <add>The easiest way to fork is with the [github-gem][], so potentially this is <add>your workflow: <add> <add> brew create http://example.com/foo-1.2.1.tar.bz2 <add> git commit Library/Formula/foo.rb <add> github fork <add> git push myname master <add> github pull-request <add> <ide> <ide> Licensing <ide> ========= <ide> confirm. Individual formulae are licensed according to their authors' wishes. <ide> <ide> FAQ <ide> === <del>1. Are you excessively interested in beer? <del> Yes. <del> <del>2. Was Homebrew devised under the influence of alcohol? <del> Yes. <del> <del>3. Can Homebrew replace MacPorts? <add>1. Can Homebrew replace MacPorts? <ide> Maybe. But remember, Homebrew is still incomplete. Be forgiving in your <ide> approach and be willing to fork and contribute fixes. Thanks! <ide> <del>4. Is there an IRC channel? <add>2. Is there an IRC channel? <ide> Yes, <irc://irc.freenode.net#machomebrew>. <ide> <del>5. And it's on Twitter? <add>3. And it's on Twitter? <ide> Yes, <http://twitter.com/machomebrew>. <ide> <add> <ide> [wiki]: http://wiki.github.com/mxcl/homebrew <add>[github-gem]: http://github.com/defunkt/github-gem
1
Python
Python
add google cloud storage to bigquery operator
40834dbfe473b2fb8299fa005a7a86580f3c8917
<ide><path>airflow/contrib/hooks/bigquery_hook.py <ide> def __init__(self, service, project_id): <ide> self.service = service <ide> self.project_id = project_id <ide> <del> def run_query(self, bql, destination_dataset_table = False, write_disposition = 'WRITE_EMPTY'): <add> def run_query(self, bql, destination_dataset_table = False, write_disposition = 'WRITE_EMPTY', allow_large_results=False): <ide> """ <ide> Executes a BigQuery SQL query. Optionally persists results in a BigQuery <ide> table. See here: <ide> def run_query(self, bql, destination_dataset_table = False, write_disposition = <ide> BigQuery table to save the query results. <ide> :param write_disposition: What to do if the table already exists in <ide> BigQuery. <add> :param allow_large_results: Whether to allow large results. <add> :type allow_large_results: boolean <ide> """ <ide> configuration = { <ide> 'query': { <del> 'query': bql <add> 'query': bql, <ide> } <ide> } <ide> <ide> def run_query(self, bql, destination_dataset_table = False, write_disposition = <ide> 'Expected destination_dataset_table in the format of <dataset>.<table>. Got: {}'.format(destination_dataset_table) <ide> destination_dataset, destination_table = destination_dataset_table.split('.', 1) <ide> configuration['query'].update({ <add> 'allowLargeResults': allow_large_results, <ide> 'writeDisposition': write_disposition, <ide> 'destinationTable': { <ide> 'projectId': self.project_id, <ide> def run_extract(self, source_dataset_table, destination_cloud_storage_uris, comp <ide> :param compression: Type of compression to use. <ide> :type compression: string <ide> :param export_format: File format to export. <del> :type field_delimiter: string <add> :type export_format: string <ide> :param field_delimiter: The delimiter to use when extracting to a CSV. <ide> :type field_delimiter: string <ide> :param print_header: Whether to print a header for a CSV file extract. <ide> def run_copy(self, source_dataset_tables, destination_project_dataset_table, wri <ide> return self.run_with_configuration(configuration) <ide> <ide> def run_load(self, destination_dataset_table, schema_fields, source_uris, source_format='CSV', create_disposition='CREATE_IF_NEEDED', skip_leading_rows=0, write_disposition='WRITE_EMPTY', field_delimiter=','): <add> """ <add> Executes a BigQuery load command to load data from Google Cloud Storage <add> to BigQuery. See here: <add> <add> https://cloud.google.com/bigquery/docs/reference/v2/jobs <add> <add> For more details about these parameters. <add> <add> :param destination_dataset_table: The dotted <dataset>.<table> BigQuery table to load data into. <add> :type destination_dataset_table: string <add> :param schema_fields: The schema field list as defined here: <add> https://cloud.google.com/bigquery/docs/reference/v2/jobs#configuration.load <add> :type schema_fields: list <add> :param source_uris: The source Google Cloud <add> Storage URI (e.g. gs://some-bucket/some-file.txt). A single wild <add> per-object name can be used. <add> :type source_uris: list <add> :param source_format: File format to export. <add> :type source_format: string <add> :param create_disposition: The create disposition if the table doesn't exist. <add> :type create_disposition: string <add> :param skip_leading_rows: Number of rows to skip when loading from a CSV. <add> :type skip_leading_rows: int <add> :param write_disposition: The write disposition if the table already exists. <add> :type write_disposition: string <add> :param field_delimiter: The delimiter to use when loading from a CSV. <add> :type field_delimiter: string <add> """ <ide> assert '.' in destination_dataset_table, \ <ide> 'Expected destination_dataset_table in the format of <dataset>.<table>. Got: {}'.format(destination_dataset_table) <ide> <ide> def run_load(self, destination_dataset_table, schema_fields, source_uris, source <ide> 'sourceFormat': source_format, <ide> 'sourceUris': source_uris, <ide> 'writeDisposition': write_disposition, <add> } <ide> } <ide> <ide> if source_format == 'CSV': <ide><path>airflow/contrib/hooks/gcs_hook.py <ide> def download(self, bucket, object, filename=False): <ide> return downloaded_file_bytes <ide> <ide> def upload(self, bucket, object, filename, mime_type='application/octet-stream'): <add> """ <add> Uploads a local file to Google Cloud Storage. <add> <add> :param bucket: The bucket to upload to. <add> :type bucket: string <add> :param object: The object name to set when uploading the local file. <add> :type object: string <add> :param filename: The local file path to the file to be uploaded. <add> :type filename: string <add> :param mime_type: The MIME type to set when uploading the file. <add> :type mime_type: string <add> """ <ide> service = self.get_conn() <ide> media = MediaFileUpload(filename, mime_type) <ide> response = service \ <ide> .objects() \ <ide> .insert(bucket=bucket, name=object, media_body=media) \ <ide> .execute() <del> <ide><path>airflow/contrib/operators/bigquery_operator.py <ide> def __init__(self, <ide> bql, <ide> destination_dataset_table = False, <ide> write_disposition = 'WRITE_EMPTY', <add> allow_large_results=False, <ide> bigquery_conn_id='bigquery_default', <ide> delegate_to=None, <ide> *args, <ide> def __init__(self, <ide> self.bql = bql <ide> self.destination_dataset_table = destination_dataset_table <ide> self.write_disposition = write_disposition <add> self.allow_large_results = allow_large_results <ide> self.bigquery_conn_id = bigquery_conn_id <ide> self.delegate_to = delegate_to <ide> <ide> def execute(self, context): <ide> hook = BigQueryHook(bigquery_conn_id=self.bigquery_conn_id, delegate_to=self.delegate_to) <ide> conn = hook.get_conn() <ide> cursor = conn.cursor() <del> cursor.run_query(self.bql, self.destination_dataset_table, self.write_disposition) <add> cursor.run_query(self.bql, self.destination_dataset_table, self.write_disposition, self.allow_large_results) <ide><path>airflow/contrib/operators/gcs_to_bq.py <add>import json <add>import logging <add> <add>from airflow.contrib.hooks.gcs_hook import GoogleCloudStorageHook <add>from airflow.contrib.hooks.bigquery_hook import BigQueryHook <add>from airflow.models import BaseOperator <add>from airflow.utils import apply_defaults <add> <add>class GoogleCloudStorageToBigQueryOperator(BaseOperator): <add> """ <add> Loads files from Google cloud storage into BigQuery. <add> """ <add> template_fields = ('bucket','source_objects','schema_object','destination_dataset_table') <add> template_ext = ('.sql',) <add> ui_color = '#f0eee4' <add> <add> @apply_defaults <add> def __init__( <add> self, <add> bucket, <add> source_objects, <add> destination_dataset_table, <add> schema_fields=False, <add> schema_object=False, <add> source_format='CSV', <add> create_disposition='CREATE_IF_NEEDED', <add> skip_leading_rows=0, <add> write_disposition='WRITE_EMPTY', <add> field_delimiter=',', <add> max_id_key=False, <add> bigquery_conn_id='bigquery_default', <add> google_cloud_storage_conn_id='google_cloud_storage_default', <add> delegate_to=None, <add> *args, <add> **kwargs): <add> """ <add> The schema to be used for the BigQuery table may be specified in one of <add> two ways. You may either directly pass the schema fields in, or you may <add> point the operator to a Google cloud storage object name. The object in <add> Google cloud storage must be a JSON file with the schema fields in it. <add> <add> :param bucket: The bucket to load from. <add> :type bucket: string <add> :param source_objects: List of Google cloud storage URIs to load from. <add> :type object: list <add> :param destination_dataset_table: The dotted <dataset>.<table> BigQuery table to load data into. <add> :type destination_dataset_table: string <add> :param schema_fields: If set, the schema field list as defined here: <add> https://cloud.google.com/bigquery/docs/reference/v2/jobs#configuration.load <add> :type schema_fields: list <add> :param schema_object: If set, a GCS object path pointing to a .json file that contains the schema for the table. <add> :param schema_object: string <add> :param source_format: File format to export. <add> :type source_format: string <add> :param create_disposition: The create disposition if the table doesn't exist. <add> :type create_disposition: string <add> :param skip_leading_rows: Number of rows to skip when loading from a CSV. <add> :type skip_leading_rows: int <add> :param write_disposition: The write disposition if the table already exists. <add> :type write_disposition: string <add> :param field_delimiter: The delimiter to use when loading from a CSV. <add> :type field_delimiter: string <add> :param max_id_key: If set, the name of a column in the BigQuery table <add> that's to be loaded. Thsi will be used to select the MAX value from <add> BigQuery after the load occurs. The results will be returned by the <add> execute() command, which in turn gets stored in XCom for future <add> operators to use. This can be helpful with incremental loads--during <add> future executions, you can pick up from the max ID. <add> :type max_id_key: string <add> :param bigquery_conn_id: Reference to a specific BigQuery hook. <add> :type bigquery_conn_id: string <add> :param google_cloud_storage_conn_id: Reference to a specific Google <add> cloud storage hook. <add> :type google_cloud_storage_conn_id: string <add> :param delegate_to: The account to impersonate, if any. For this to <add> work, the service account making the request must have domain-wide <add> delegation enabled. <add> :type delegate_to: string <add> """ <add> super(GoogleCloudStorageToBigQueryOperator, self).__init__(*args, **kwargs) <add> <add> # GCS config <add> self.bucket = bucket <add> self.source_objects = source_objects <add> self.schema_object = schema_object <add> <add> # BQ config <add> self.destination_dataset_table = destination_dataset_table <add> self.schema_fields = schema_fields <add> self.source_format = source_format <add> self.create_disposition = create_disposition <add> self.skip_leading_rows = skip_leading_rows <add> self.write_disposition = write_disposition <add> self.field_delimiter = field_delimiter <add> <add> self.max_id_key = max_id_key <add> self.bigquery_conn_id = bigquery_conn_id <add> self.google_cloud_storage_conn_id = google_cloud_storage_conn_id <add> self.delegate_to = delegate_to <add> <add> def execute(self, context): <add> gcs_hook = GoogleCloudStorageHook(google_cloud_storage_conn_id=self.google_cloud_storage_conn_id, <add> delegate_to=self.delegate_to) <add> bq_hook = BigQueryHook(bigquery_conn_id=self.bigquery_conn_id, <add> delegate_to=self.delegate_to) <add> <add> schema_fields = self.schema_fields if self.schema_fields else json.loads(gcs_hook.download(self.bucket, self.schema_object)) <add> source_uris = map(lambda schema_object: 'gs://{}/{}'.format(self.bucket, schema_object), self.source_objects) <add> conn = bq_hook.get_conn() <add> cursor = conn.cursor() <add> cursor.run_load( <add> destination_dataset_table=self.destination_dataset_table, <add> schema_fields=schema_fields, <add> source_uris=source_uris, <add> source_format=self.source_format, <add> create_disposition=self.create_disposition, <add> skip_leading_rows=self.skip_leading_rows, <add> write_disposition=self.write_disposition, <add> field_delimiter=self.field_delimiter) <add> <add> if self.max_id_key: <add> cursor.execute('SELECT MAX({}) FROM {}'.format(self.max_id_key, self.destination_dataset_table)) <add> row = cursor.fetchone() <add> logging.info('Loaded BQ data with max {}.{}={}'.format(self.destination_dataset_table, self.max_id_key, row[0])) <add> return row[0] <ide><path>airflow/contrib/operators/mysql_to_gcs.py <ide> from tempfile import NamedTemporaryFile <ide> <ide> class MySqlToGoogleCloudStorageOperator(BaseOperator): <add> """ <add> Copy data from MySQL to Google cloud storage in JSON format. <add> """ <ide> template_fields = ('sql', 'bucket', 'filename', 'schema_filename') <ide> template_ext = ('.sql',) <ide> ui_color = '#a0e08c' <ide> def __init__(self, <ide> bucket, <ide> filename, <ide> schema_filename=None, <del> approx_max_file_size_bytes=3900000000L, <add> approx_max_file_size_bytes=1900000000L, <ide> mysql_conn_id='mysql_default', <ide> google_cloud_storage_conn_id='google_cloud_storage_default', <ide> delegate_to=None, <ide> *args, <ide> **kwargs): <add> """ <add> :param sql: The SQL to execute on the MySQL table. <add> :type sql: string <add> :param bucket: The bucket to upload to. <add> :type bucket: string <add> :param filename: The filename to use as the object name when uploading <add> to Google cloud storage. A {} should be specified in the filename <add> to allow the operator to inject file numbers in cases where the <add> file is split due to size. <add> :type filename: string <add> :param schema_filename: If set, the filename to use as the object name <add> when uploading a .json file containing the BigQuery schema fields <add> for the table that was dumped from MySQL. <add> :type schema_filename: string <add> :param approx_max_file_size_bytes: This operator supports the ability <add> to split large table dumps into multiple files (see notes in the <add> filenamed param docs above). Google cloud storage allows for files <add> to be a maximum of 4GB. This param allows developers to specify the <add> file size of the splits. <add> :type approx_max_file_size_bytes: long <add> :param mysql_conn_id: Reference to a specific MySQL hook. <add> :type mysql_conn_id: string <add> :param google_cloud_storage_conn_id: Reference to a specific Google <add> cloud storage hook. <add> :type google_cloud_storage_conn_id: string <add> :param delegate_to: The account to impersonate, if any. For this to <add> work, the service account making the request must have domain-wide <add> delegation enabled. <add> """ <ide> super(MySqlToGoogleCloudStorageOperator, self).__init__(*args, **kwargs) <ide> self.sql = sql; <ide> self.bucket = bucket <ide> def execute(self, context): <ide> file_handle.close() <ide> <ide> def _query_mysql(self): <add> """ <add> Queries mysql and returns a cursor to the results. <add> """ <ide> mysql = MySqlHook(mysql_conn_id=self.mysql_conn_id) <ide> conn = mysql.get_conn() <ide> cursor = conn.cursor() <ide> cursor.execute(self.sql) <ide> return cursor <ide> <ide> def _write_local_data_files(self, cursor): <add> """ <add> Takes a cursor, and writes results to a local file. <add> <add> :return: A dictionary where keys are filenames to be used as object <add> names in GCS, and values are file handles to local files that <add> contain the data for the GCS objects. <add> """ <ide> schema = map(lambda schema_tuple: schema_tuple[0], cursor.description) <ide> file_no = 0 <ide> tmp_file_handle = NamedTemporaryFile(delete=True) <ide> def _write_local_data_files(self, cursor): <ide> return tmp_file_handles <ide> <ide> def _write_local_schema_file(self, cursor): <add> """ <add> Takes a cursor, and writes the BigQuery schema for the results to a <add> local file system. <add> <add> :return: A dictionary where key is a filename to be used as an object <add> name in GCS, and values are file handles to local files that <add> contains the BigQuery schema fields in .json format. <add> """ <ide> schema = [] <ide> for field in cursor.description: <ide> # See PEP 249 for details about the description tuple. <ide> def _write_local_schema_file(self, cursor): <ide> 'mode': field_mode, <ide> }) <ide> <del> print('Using schema for {}: {}', self.schema_filename, str(schema)) <add> logging.info('Using schema for %s: %s', self.schema_filename, schema) <ide> tmp_schema_file_handle = NamedTemporaryFile(delete=True) <ide> json.dump(schema, tmp_schema_file_handle) <ide> return {self.schema_filename: tmp_schema_file_handle} <ide> <ide> def _upload_to_gcs(self, files_to_upload): <add> """ <add> Upload all of the file splits (and optionally the schema .json file) to <add> Google cloud storage. <add> """ <ide> hook = GoogleCloudStorageHook(google_cloud_storage_conn_id=self.google_cloud_storage_conn_id, <ide> delegate_to=self.delegate_to) <ide> for object, tmp_file_handle in files_to_upload.items(): <ide> hook.upload(self.bucket, object, tmp_file_handle.name, 'application/json') <ide> <ide> @classmethod <ide> def type_map(cls, mysql_type): <add> """ <add> Helper function that maps from MySQL fields to BigQuery fields. Used <add> when a schema_filename is set. <add> """ <ide> d = { <ide> FIELD_TYPE.BIT: 'INTEGER', <ide> FIELD_TYPE.DATETIME: 'TIMESTAMP',
5
Mixed
Javascript
add new options to `net.socket` and `net.server`
45b5ca810a16074e639157825c1aa2e90d60e9f6
<ide><path>doc/api/http.md <ide> changes: <ide> [`--max-http-header-size`][] for requests received by this server, i.e. <ide> the maximum length of request headers in bytes. <ide> **Default:** 16384 (16 KB). <add> * `noDelay` {boolean} If set to `true`, it disables the use of Nagle's <add> algorithm immediately after a new incoming connection is received. <add> **Default:** `false`. <add> * `keepAlive` {boolean} If set to `true`, it enables keep-alive functionality <add> on the socket immediately after a new incoming connection is received, <add> similarly on what is done in \[`socket.setKeepAlive([enable][, initialDelay])`]\[`socket.setKeepAlive(enable, initialDelay)`]. <add> **Default:** `false`. <add> * `keepAliveInitialDelay` {number} If set to a positive number, it sets the <add> initial delay before the first keepalive probe is sent on an idle socket. <add> **Default:** `0`. <ide> <ide> * `requestListener` {Function} <ide> <ide> changes: <ide> * `callback` {Function} <ide> * Returns: {http.ClientRequest} <ide> <add>`options` in [`socket.connect()`][] are also supported. <add> <ide> Node.js maintains several connections per server to make HTTP requests. <ide> This function allows one to transparently issue requests. <ide> <ide><path>doc/api/net.md <ide> For TCP connections, available `options` are: <ide> `0` indicates that both IPv4 and IPv6 addresses are allowed. **Default:** `0`. <ide> * `hints` {number} Optional [`dns.lookup()` hints][]. <ide> * `lookup` {Function} Custom lookup function. **Default:** [`dns.lookup()`][]. <add>* `noDelay` {boolean} If set to `true`, it disables the use of Nagle's algorithm immediately <add> after the socket is established. **Default:** `false`. <add>* `keepAlive` {boolean} If set to `true`, it enables keep-alive functionality on the socket <add> immediately after the connection is established, similarly on what is done in <add> [`socket.setKeepAlive([enable][, initialDelay])`][`socket.setKeepAlive(enable, initialDelay)`]. <add> **Default:** `false`. <add>* `keepAliveInitialDelay` {number} If set to a positive number, it sets the initial delay before <add> the first keepalive probe is sent on an idle socket.**Default:** `0`. <ide> <ide> For [IPC][] connections, available `options` are: <ide> <ide> added: v0.5.0 <ide> **Default:** `false`. <ide> * `pauseOnConnect` {boolean} Indicates whether the socket should be <ide> paused on incoming connections. **Default:** `false`. <add> * `noDelay` {boolean} If set to `true`, it disables the use of Nagle's algorithm immediately <add> after a new incoming connection is received. **Default:** `false`. <add> * `keepAlive` {boolean} If set to `true`, it enables keep-alive functionality on the socket <add> immediately after a new incoming connection is received, similarly on what is done in <add> [`socket.setKeepAlive([enable][, initialDelay])`][`socket.setKeepAlive(enable, initialDelay)`]. <add> **Default:** `false`. <add> * `keepAliveInitialDelay` {number} If set to a positive number, it sets the initial delay before <add> the first keepalive probe is sent on an idle socket.**Default:** `0`. <add> <ide> * `connectionListener` {Function} Automatically set as a listener for the <ide> [`'connection'`][] event. <add> <ide> * Returns: {net.Server} <ide> <ide> Creates a new TCP or [IPC][] server. <ide> net.isIPv6('fhqwhgads'); // returns false <ide> [`socket.pause()`]: #socketpause <ide> [`socket.resume()`]: #socketresume <ide> [`socket.setEncoding()`]: #socketsetencodingencoding <add>[`socket.setKeepAlive(enable, initialDelay)`]: #socketsetkeepaliveenable-initialdelay <ide> [`socket.setTimeout()`]: #socketsettimeouttimeout-callback <ide> [`socket.setTimeout(timeout)`]: #socketsettimeouttimeout-callback <ide> [`writable.destroy()`]: stream.md#writabledestroyerror <ide><path>lib/_http_server.js <ide> function Server(options, requestListener) { <ide> } <ide> <ide> storeHTTPOptions.call(this, options); <del> net.Server.call(this, { allowHalfOpen: true }); <add> net.Server.call( <add> this, <add> { allowHalfOpen: true, noDelay: options.noDelay, <add> keepAlive: options.keepAlive, <add> keepAliveInitialDelay: options.keepAliveInitialDelay }); <ide> <ide> if (requestListener) { <ide> this.on('request', requestListener); <ide><path>lib/net.js <ide> function initSocketHandle(self) { <ide> const kBytesRead = Symbol('kBytesRead'); <ide> const kBytesWritten = Symbol('kBytesWritten'); <ide> const kSetNoDelay = Symbol('kSetNoDelay'); <add>const kSetKeepAlive = Symbol('kSetKeepAlive'); <add>const kSetKeepAliveInitialDelay = Symbol('kSetKeepAliveInitialDelay'); <ide> <ide> function Socket(options) { <ide> if (!(this instanceof Socket)) return new Socket(options); <ide> function Socket(options) { <ide> 'is not supported' <ide> ); <ide> } <add> if (typeof options?.keepAliveInitialDelay !== 'undefined') { <add> validateNumber( <add> options?.keepAliveInitialDelay, 'options.keepAliveInitialDelay' <add> ); <add> <add> if (options.keepAliveInitialDelay < 0) { <add> options.keepAliveInitialDelay = 0; <add> } <add> } <ide> <ide> this.connecting = false; <ide> // Problem with this is that users can supply their own handle, that may not <ide> function Socket(options) { <ide> this[kHandle] = null; <ide> this._parent = null; <ide> this._host = null; <del> this[kSetNoDelay] = false; <ide> this[kLastWriteQueueSize] = 0; <ide> this[kTimeout] = null; <ide> this[kBuffer] = null; <ide> function Socket(options) { <ide> this[kBufferCb] = onread.callback; <ide> } <ide> <add> this[kSetNoDelay] = Boolean(options.noDelay); <add> this[kSetKeepAlive] = Boolean(options.keepAlive); <add> this[kSetKeepAliveInitialDelay] = ~~(options.keepAliveInitialDelay / 1000); <add> <ide> // Shut down the socket when we're finished with it. <ide> this.on('end', onReadableStreamEnd); <ide> <ide> Socket.prototype._onTimeout = function() { <ide> <ide> <ide> Socket.prototype.setNoDelay = function(enable) { <add> // Backwards compatibility: assume true when `enable` is omitted <add> enable = Boolean(enable === undefined ? true : enable); <add> <ide> if (!this._handle) { <del> this.once('connect', <del> enable ? this.setNoDelay : () => this.setNoDelay(enable)); <add> this[kSetNoDelay] = enable; <ide> return this; <ide> } <ide> <del> // Backwards compatibility: assume true when `enable` is omitted <del> const newValue = enable === undefined ? true : !!enable; <del> if (this._handle.setNoDelay && newValue !== this[kSetNoDelay]) { <del> this[kSetNoDelay] = newValue; <del> this._handle.setNoDelay(newValue); <add> if (this._handle.setNoDelay && enable !== this[kSetNoDelay]) { <add> this[kSetNoDelay] = enable; <add> this._handle.setNoDelay(enable); <ide> } <ide> <ide> return this; <ide> }; <ide> <ide> <del>Socket.prototype.setKeepAlive = function(setting, msecs) { <add>Socket.prototype.setKeepAlive = function(enable, initialDelayMsecs) { <add> enable = Boolean(enable); <add> const initialDelay = ~~(initialDelayMsecs / 1000); <add> <ide> if (!this._handle) { <del> this.once('connect', () => this.setKeepAlive(setting, msecs)); <add> this[kSetKeepAlive] = enable; <add> this[kSetKeepAliveInitialDelay] = initialDelay; <ide> return this; <ide> } <ide> <del> if (this._handle.setKeepAlive) <del> this._handle.setKeepAlive(setting, ~~(msecs / 1000)); <add> if (this._handle.setKeepAlive && enable !== this[kSetKeepAlive]) { <add> this[kSetKeepAlive] = enable; <add> this[kSetKeepAliveInitialDelay] = initialDelay; <add> this._handle.setKeepAlive(enable, initialDelay); <add> } <ide> <ide> return this; <ide> }; <ide> function afterConnect(status, handle, req, readable, writable) { <ide> } <ide> self._unrefTimer(); <ide> <add> if (self[kSetNoDelay] && self._handle.setNoDelay) { <add> self._handle.setNoDelay(true); <add> } <add> <add> if (self[kSetKeepAlive] && self._handle.setKeepAlive) { <add> self._handle.setKeepAlive(true, self[kSetKeepAliveInitialDelay]); <add> } <add> <ide> self.emit('connect'); <ide> self.emit('ready'); <ide> <ide> function Server(options, connectionListener) { <ide> } else { <ide> throw new ERR_INVALID_ARG_TYPE('options', 'Object', options); <ide> } <add> if (typeof options.keepAliveInitialDelay !== 'undefined') { <add> validateNumber( <add> options.keepAliveInitialDelay, 'options.keepAliveInitialDelay' <add> ); <add> <add> if (options.keepAliveInitialDelay < 0) { <add> options.keepAliveInitialDelay = 0; <add> } <add> } <ide> <ide> this._connections = 0; <ide> <ide> function Server(options, connectionListener) { <ide> <ide> this.allowHalfOpen = options.allowHalfOpen || false; <ide> this.pauseOnConnect = !!options.pauseOnConnect; <add> this.noDelay = Boolean(options.noDelay); <add> this.keepAlive = Boolean(options.keepAlive); <add> this.keepAliveInitialDelay = ~~(options.keepAliveInitialDelay / 1000); <ide> } <ide> ObjectSetPrototypeOf(Server.prototype, EventEmitter.prototype); <ide> ObjectSetPrototypeOf(Server, EventEmitter); <ide> function onconnection(err, clientHandle) { <ide> writable: true <ide> }); <ide> <add> if (self.noDelay && handle.setNoDelay) { <add> handle.setNoDelay(true); <add> } <add> <add> if (self.keepAlive && self.setKeepAlive) { <add> handle.setKeepAlive(true, handle.keepAliveInitialDelay); <add> } <add> <ide> self._connections++; <ide> socket.server = self; <ide> socket._server = self; <ide><path>test/parallel/test-net-connect-keepalive.js <add>'use strict'; <add> <add>const common = require('../common'); <add>const assert = require('assert'); <add>const net = require('net'); <add> <add>const truthyValues = [true, 1, 'true', {}, []]; <add>const delays = [[123, 0], [456123, 456], [-123000, 0], [undefined, 0]]; <add>const falseyValues = [false, 0, '']; <add> <add>const genSetKeepAlive = (desiredEnable, desiredDelay) => (enable, delay) => { <add> assert.strictEqual(enable, desiredEnable); <add> assert.strictEqual(delay, desiredDelay); <add>}; <add> <add>for (const value of truthyValues) { <add> for (const delay of delays) { <add> const server = net.createServer(); <add> <add> server.listen(0, common.mustCall(function() { <add> const port = server.address().port; <add> <add> const client = net.connect( <add> { port, keepAlive: value, keepAliveInitialDelay: delay[0] }, <add> common.mustCall(() => client.end()) <add> ); <add> <add> client._handle.setKeepAlive = common.mustCall( <add> genSetKeepAlive(true, delay[1]) <add> ); <add> <add> client.on('end', common.mustCall(function() { <add> server.close(); <add> })); <add> })); <add> } <add>} <add> <add>for (const value of falseyValues) { <add> const server = net.createServer(); <add> <add> server.listen(0, common.mustCall(function() { <add> const port = server.address().port; <add> <add> const client = net.connect( <add> { port, keepAlive: value }, <add> common.mustCall(() => client.end()) <add> ); <add> <add> client._handle.setKeepAlive = common.mustNotCall(); <add> <add> client.on('end', common.mustCall(function() { <add> server.close(); <add> })); <add> })); <add>} <ide><path>test/parallel/test-net-connect-nodelay.js <add>'use strict'; <add> <add>const common = require('../common'); <add>const assert = require('assert'); <add>const net = require('net'); <add> <add>const truthyValues = [true, 1, 'true', {}, []]; <add>const falseyValues = [false, 0, '']; <add>const genSetNoDelay = (desiredArg) => (enable) => { <add> assert.strictEqual(enable, desiredArg); <add>}; <add> <add>for (const value of truthyValues) { <add> const server = net.createServer(); <add> <add> server.listen(0, common.mustCall(function() { <add> const port = server.address().port; <add> <add> const client = net.connect( <add> { port, noDelay: value }, <add> common.mustCall(() => client.end()) <add> ); <add> <add> client._handle.setNoDelay = common.mustCall(genSetNoDelay(true)); <add> <add> client.on('end', common.mustCall(function() { <add> server.close(); <add> })); <add> })); <add>} <add> <add>for (const value of falseyValues) { <add> const server = net.createServer(); <add> <add> server.listen(0, common.mustCall(function() { <add> const port = server.address().port; <add> <add> const client = net.connect( <add> { port, noDelay: value }, <add> common.mustCall(() => client.end()) <add> ); <add> <add> client._handle.setNoDelay = common.mustNotCall(); <add> <add> client.on('end', common.mustCall(function() { <add> server.close(); <add> })); <add> })); <add>}
6
Javascript
Javascript
use xxhash64 for future defaults
da8e93af330739c332670ed7d040a648431703b4
<ide><path>lib/config/defaults.js <ide> const applyWebpackOptionsDefaults = options => { <ide> outputModule: options.experiments.outputModule, <ide> development, <ide> entry: options.entry, <del> module: options.module <add> module: options.module, <add> futureDefaults: options.experiments.futureDefaults <ide> }); <ide> <ide> applyExternalsPresetsDefaults(options.externalsPresets, { <ide> const applyModuleDefaults = ( <ide> * @param {boolean} options.development is development mode <ide> * @param {Entry} options.entry entry option <ide> * @param {ModuleOptions} options.module module option <add> * @param {boolean} options.futureDefaults is future defaults enabled <ide> * @returns {void} <ide> */ <ide> const applyOutputDefaults = ( <ide> const applyOutputDefaults = ( <ide> outputModule, <ide> development, <ide> entry, <del> module <add> module, <add> futureDefaults <ide> } <ide> ) => { <ide> /** <ide> const applyOutputDefaults = ( <ide> : "" <ide> ); <ide> D(output, "chunkLoadTimeout", 120000); <del> D(output, "hashFunction", "md4"); <add> D(output, "hashFunction", futureDefaults ? "xxhash64" : "md4"); <ide> D(output, "hashDigest", "hex"); <ide> D(output, "hashDigestLength", 20); <ide> D(output, "strictModuleExceptionHandling", false); <ide><path>test/Defaults.unittest.js <ide> Object { <ide> }, <ide> e => <ide> e.toMatchInlineSnapshot(` <del> - Expected <del> + Received <add>- Expected <add>+ Received <ide> <del> <del> - "futureDefaults": false, <del> + "futureDefaults": true, <del> <del> - "__dirname": "mock", <del> - "__filename": "mock", <del> - "global": true, <del> + "__dirname": "warn-mock", <del> + "__filename": "warn-mock", <del> + "global": "warn", <del> `) <add> <add>- "futureDefaults": false, <add>+ "futureDefaults": true, <add> <add>- "__dirname": "mock", <add>- "__filename": "mock", <add>- "global": true, <add>+ "__dirname": "warn-mock", <add>+ "__filename": "warn-mock", <add>+ "global": "warn", <add> <add>- "hashFunction": "md4", <add>+ "hashFunction": "xxhash64", <add>`) <ide> ); <ide> });
2
Python
Python
avoid crash when unicode in title
3fc3b7a13af2e15d8cb0cc90860d7861d3ad7ddf
<ide><path>spacy/cli/project/run.py <ide> from typing import Optional, List, Dict, Sequence, Any, Iterable <ide> from pathlib import Path <ide> from wasabi import msg <add>from wasabi.util import locale_escape <ide> import sys <ide> import srsly <ide> import typer <ide> def print_run_help(project_dir: Path, subcommand: Optional[str] = None) -> None: <ide> print("") <ide> title = config.get("title") <ide> if title: <del> print(f"{title}\n") <add> print(f"{locale_escape(title)}\n") <ide> if config_commands: <ide> print(f"Available commands in {PROJECT_FILE}") <ide> print(f"Usage: {COMMAND} project run [COMMAND] {project_loc}")
1
PHP
PHP
fix more failing tests
ffd6ad1cc3faf682b68a3ce39b61f8f02b202783
<ide><path>src/Controller/Controller.php <ide> */ <ide> namespace Cake\Controller; <ide> <del>use Cake\Controller\Exception\MissingActionException; <ide> use Cake\Controller\ComponentRegistry; <add>use Cake\Controller\Exception\MissingActionException; <ide> use Cake\Datasource\ModelAwareTrait; <ide> use Cake\Event\EventDispatcherInterface; <ide> use Cake\Event\EventDispatcherTrait; <ide><path>src/Controller/ErrorController.php <ide> namespace Cake\Controller; <ide> <ide> use Cake\Event\EventInterface; <add>use Cake\Http\Response; <ide> <ide> /** <ide> * Error Handling Controller <ide> public function initialize(): void <ide> * beforeRender callback. <ide> * <ide> * @param \Cake\Event\EventInterface $event Event. <del> * @return void <add> * @return \Cake\Http\Response|null <ide> */ <del> public function beforeRender(EventInterface $event): void <add> public function beforeRender(EventInterface $event): ?Response <ide> { <ide> $this->viewBuilder()->setTemplatePath('Error'); <add> <add> return null; <ide> } <ide> } <ide><path>tests/TestCase/Error/ExceptionRendererTest.php <ide> <?php <add>declare(strict_types=1); <ide> /** <ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org) <ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) <ide> use Cake\Http\Exception\InternalErrorException; <ide> use Cake\Http\Exception\MethodNotAllowedException; <ide> use Cake\Http\Exception\NotFoundException; <add>use Cake\Http\Response; <ide> use Cake\Http\ServerRequest; <ide> use Cake\Mailer\Exception\MissingActionException as MissingMailerActionException; <ide> use Cake\Network\Exception\SocketException; <ide> class BlueberryComponent extends Component <ide> * @param array $config <ide> * @return void <ide> */ <del> public function initialize(array $config) <add> public function initialize(array $config): void <ide> { <ide> $this->testName = 'BlueberryComponent'; <ide> } <ide> class TestErrorController extends Controller <ide> /** <ide> * beforeRender method <ide> * <del> * @return void <add> * @return \Cake\Http\Response|null <ide> */ <del> public function beforeRender(EventInterface $event) <add> public function beforeRender(EventInterface $event): ?Response <ide> { <ide> echo $this->Blueberry->testName; <add> <add> return null; <ide> } <ide> <ide> /** <ide><path>tests/test_app/TestApp/Controller/CakesController.php <ide> namespace TestApp\Controller; <ide> <ide> use Cake\Controller\Controller; <add>use Cake\Http\Response; <ide> <ide> /** <ide> * CakesController class <ide> public function invalid() <ide> } <ide> <ide> /** <del> * startup process. <add> * Startup process <add> * <add> * \Cake\Http\Response|null <ide> */ <del> public function startupProcess() <add> public function startupProcess(): ?Response <ide> { <ide> parent::startupProcess(); <ide> if ($this->request->getParam('stop') === 'startup') { <ide> return $this->response->withStringBody('startup stop'); <ide> } <add> <add> return null; <ide> } <ide> <ide> /** <del> * shutdown process. <add> * Shutdown process <add> * <add> * \Cake\Http\Response|null <ide> */ <del> public function shutdownProcess() <add> public function shutdownProcess(): ?Response <ide> { <ide> parent::shutdownProcess(); <ide> if ($this->request->getParam('stop') === 'shutdown') { <ide> return $this->response->withStringBody('shutdown stop'); <ide> } <add> <add> return null; <ide> } <ide> } <ide><path>tests/test_app/TestApp/Controller/PostsController.php <ide> public function beforeFilter(EventInterface $event): ?Response <ide> if ($this->request->getParam('action') !== 'securePost') { <ide> $this->getEventManager()->off($this->Security); <ide> } <add> <add> return null; <ide> } <ide> <ide> /**
5
Java
Java
increase idle timeout for react app tests
c1c2a5bce57604f26f98bce17d3a6854ad809257
<ide><path>ReactAndroid/src/androidTest/java/com/facebook/react/testing/ReactAppTestActivity.java <ide> public class ReactAppTestActivity extends FragmentActivity <ide> private static final String DEFAULT_BUNDLE_NAME = "AndroidTestBundle.js"; <ide> private static final int ROOT_VIEW_ID = 8675309; <ide> // we need a bigger timeout for CI builds because they run on a slow emulator <del> private static final long IDLE_TIMEOUT_MS = 120000; <add> private static final long IDLE_TIMEOUT_MS = 240000; <ide> private final CountDownLatch mDestroyCountDownLatch = new CountDownLatch(1); <ide> private CountDownLatch mLayoutEvent = new CountDownLatch(1); <ide> private @Nullable ReactBridgeIdleSignaler mBridgeIdleSignaler;
1
Javascript
Javascript
fix accidental global. thanks, @fponticelli!
674ededfa15481f7a398c42ed695e304237a191c
<ide><path>d3.behavior.js <ide> d3.behavior.zoom = function() { <ide> }; <ide> <ide> function transform(scale, o) { <del> var domain = scale.__domain || (scale.__domain = scale.domain()); <add> var domain = scale.__domain || (scale.__domain = scale.domain()), <ide> range = scale.range().map(function(v) { return (v - o) / k; }); <ide> scale.domain(domain).domain(range.map(scale.invert)); <ide> } <ide><path>d3.behavior.min.js <del>(function(){d3.behavior={},d3.behavior.zoom=function(){function m(a,b){function i(a,b){var c=a.__domain||(a.__domain=a.domain());range=a.range().map(function(a){return(a-b)/h}),a.domain(c).domain(range.map(a.invert))}var g=d3.event,h=Math.pow(2,e);d3.event={scale:h,translate:[c,d],transform:function(a,b){a&&i(a,c),b&&i(b,d)}};try{for(var j=0,k=f.length;j<k;j++)f[j].call(this,a,b)}finally{d3.event=g}}function l(f,g){var i=d3.event;if(!h){var j=d3.svg.mouse(this.nearestViewportElement||this);h={x0:c,y0:d,z0:e,x1:c-j[0],y1:d-j[1]}}if(i.type=="dblclick")e=i.shiftKey?Math.ceil(e-1):Math.floor(e+1);else{var k=(i.wheelDelta/120||-i.detail)*.1;if(a<0){var l=Date.now(),n=l-b;n>9&&Math.abs(i.wheelDelta)/n>=50&&(a=1),b=l}a==1&&(k*=.03),e+=k}var o=Math.pow(2,e-h.z0)-1;c=h.x0+h.x1*o,d=h.y0+h.y1*o,m.call(this,f,g)}function k(){g&&(j(),g=null)}function j(){h=null,g&&(c=d3.event.clientX+g.x0,d=d3.event.clientY+g.y0,m.call(g.target,g.data,g.index))}function i(a,b){g={x0:c-d3.event.clientX,y0:d-d3.event.clientY,target:this,data:a,index:b},d3.event.preventDefault(),window.focus()}function h(){var a=this.on("mousedown",i).on("mousewheel",l).on("DOMMouseScroll",l).on("dblclick",l);d3.select(window).on("mousemove",j).on("mouseup",k)}var a=/WebKit\/533/.test(navigator.userAgent)?-1:0,b=0,c=0,d=0,e=0,f=[],g,h;h.on=function(a,b){a=="zoom"&&f.push(b);return h};return h}})() <ide>\ No newline at end of file <add>(function(){d3.behavior={},d3.behavior.zoom=function(){function m(a,b){function i(a,b){var c=a.__domain||(a.__domain=a.domain()),d=a.range().map(function(a){return(a-b)/h});a.domain(c).domain(d.map(a.invert))}var g=d3.event,h=Math.pow(2,e);d3.event={scale:h,translate:[c,d],transform:function(a,b){a&&i(a,c),b&&i(b,d)}};try{for(var j=0,k=f.length;j<k;j++)f[j].call(this,a,b)}finally{d3.event=g}}function l(f,g){var i=d3.event;if(!h){var j=d3.svg.mouse(this.nearestViewportElement||this);h={x0:c,y0:d,z0:e,x1:c-j[0],y1:d-j[1]}}if(i.type=="dblclick")e=i.shiftKey?Math.ceil(e-1):Math.floor(e+1);else{var k=(i.wheelDelta/120||-i.detail)*.1;if(a<0){var l=Date.now(),n=l-b;n>9&&Math.abs(i.wheelDelta)/n>=50&&(a=1),b=l}a==1&&(k*=.03),e+=k}var o=Math.pow(2,e-h.z0)-1;c=h.x0+h.x1*o,d=h.y0+h.y1*o,m.call(this,f,g)}function k(){g&&(j(),g=null)}function j(){h=null,g&&(c=d3.event.clientX+g.x0,d=d3.event.clientY+g.y0,m.call(g.target,g.data,g.index))}function i(a,b){g={x0:c-d3.event.clientX,y0:d-d3.event.clientY,target:this,data:a,index:b},d3.event.preventDefault(),window.focus()}function h(){var a=this.on("mousedown",i).on("mousewheel",l).on("DOMMouseScroll",l).on("dblclick",l);d3.select(window).on("mousemove",j).on("mouseup",k)}var a=/WebKit\/533/.test(navigator.userAgent)?-1:0,b=0,c=0,d=0,e=0,f=[],g,h;h.on=function(a,b){a=="zoom"&&f.push(b);return h};return h}})() <ide>\ No newline at end of file <ide><path>src/behavior/zoom.js <ide> d3.behavior.zoom = function() { <ide> }; <ide> <ide> function transform(scale, o) { <del> var domain = scale.__domain || (scale.__domain = scale.domain()); <add> var domain = scale.__domain || (scale.__domain = scale.domain()), <ide> range = scale.range().map(function(v) { return (v - o) / k; }); <ide> scale.domain(domain).domain(range.map(scale.invert)); <ide> }
3
PHP
PHP
add test covering correct use for
edfb0c6bb1af2045cb6adc36f037fcd7350569f6
<ide><path>tests/TestCase/ORM/QueryRegressionTest.php <ide> public function testEagerLoadingFromEmptyResults() <ide> $this->assertEmpty($results); <ide> } <ide> <add> /** <add> * Tests that eagerloading associations with aliased fields works. <add> * <add> * @return void <add> */ <add> public function testEagerLoadingAliasedAssociationFields() <add> { <add> $this->loadFixtures('Articles', 'Authors'); <add> $table = TableRegistry::get('Articles'); <add> $table->belongsTo('Authors', [ <add> 'foreignKey' => 'author_id' <add> ]); <add> $result = $table->find() <add> ->contain(['Authors' => [ <add> 'fields' => [ <add> 'id', <add> 'Authors__aliased_name' => 'name' <add> ] <add> ]]) <add> ->where(['Articles.id' => 1]) <add> ->first(); <add> $this->assertInstanceOf(EntityInterface::class, $result); <add> $this->assertInstanceOf(EntityInterface::class, $result->author); <add> $this->assertSame('mariano', $result->author->aliased_name); <add> } <add> <ide> /** <ide> * Tests that eagerloading and hydration works for associations that have <ide> * different aliases in the association and targetTable
1
Ruby
Ruby
generate an api dummy application for api plugins
ce32c9da962a9dd7a894c9a4457db9dd5f5a5a1f
<ide><path>railties/lib/rails/generators/rails/plugin/plugin_generator.rb <ide> def generate_test_dummy(force = false) <ide> opts = (options || {}).slice(*PASSTHROUGH_OPTIONS) <ide> opts[:force] = force <ide> opts[:skip_bundle] = true <add> opts[:api] = options.api? <ide> <ide> invoke Rails::Generators::AppGenerator, <ide> [ File.expand_path(dummy_path, destination_root) ], opts <ide><path>railties/test/generators/plugin_generator_test.rb <ide> def test_application_controller_parent_for_mountable_api_plugins <ide> end <ide> end <ide> <add> def test_dummy_api_application_for_api_plugins <add> run_generator [destination_root, '--api'] <add> <add> assert_file "test/dummy/config/application.rb" do |content| <add> assert_match "config.api_only = true", content <add> end <add> end <add> <ide> protected <ide> def action(*args, &block) <ide> silence(:stdout){ generator.send(*args, &block) }
2
Javascript
Javascript
remove error messages in test-buffer-alloc
e021de346909474dc8d2154942606199f75d6118
<ide><path>test/parallel/test-buffer-alloc.js <ide> assert.strictEqual('TWFu', (Buffer.from('Man')).toString('base64')); <ide> assert.strictEqual(quote, b.toString('ascii', 0, quote.length)); <ide> <ide> // check that the base64 decoder ignores whitespace <del> const expectedWhite = expected.slice(0, 60) + ' \n' + <del> expected.slice(60, 120) + ' \n' + <del> expected.slice(120, 180) + ' \n' + <del> expected.slice(180, 240) + ' \n' + <del> expected.slice(240, 300) + '\n' + <del> expected.slice(300, 360) + '\n'; <add> const expectedWhite = `${expected.slice(0, 60)} \n` + <add> `${expected.slice(60, 120)} \n` + <add> `${expected.slice(120, 180)} \n` + <add> `${expected.slice(180, 240)} \n` + <add> `${expected.slice(240, 300)}\n` + <add> `${expected.slice(300, 360)}\n`; <ide> b = Buffer.allocUnsafe(1024); <ide> bytesWritten = b.write(expectedWhite, 0, 'base64'); <ide> assert.strictEqual(quote.length, bytesWritten);
1
Text
Text
add example for chmod in fs.md
41fad84035daa37baf07a888322b2f17dd1d563c
<ide><path>doc/api/fs.md <ide> possible exception are given to the completion callback. <ide> <ide> See also: chmod(2). <ide> <add>```js <add>fs.chmod('my_file.txt', 0o775, (err) => { <add> if (err) throw err; <add> console.log('The permissions for file "my_file.txt" have been changed!'); <add>}); <add>``` <add> <ide> ### File modes <ide> <ide> The `mode` argument used in both the `fs.chmod()` and `fs.chmodSync()`
1
PHP
PHP
use $format as own first argument
2ccd38010f1dfd4fba4d6beb27fc213962a22a97
<ide><path>src/View/Helper/PaginatorHelper.php <ide> public function defaultModel($model = null) <ide> } <ide> <ide> /** <del> * Returns a counter string for the paged result set <add> * Returns a counter string for the paged result set. <ide> * <ide> * ### Options <ide> * <ide> * - `model` The model to use, defaults to PaginatorHelper::defaultModel(); <del> * - `format` The format string you want to use, defaults to 'pages' Which generates output like '1 of 5' <add> * <add> * @param string $format The format string you want to use, defaults to 'pages' Which generates output like '1 of 5' <ide> * set to 'range' to generate output like '1 - 3 of 13'. Can also be set to a custom string, containing <ide> * the following placeholders `{{page}}`, `{{pages}}`, `{{current}}`, `{{count}}`, `{{model}}`, `{{start}}`, `{{end}}` and any <ide> * custom content you would like. <del> * <ide> * @param array $options Options for the counter string. See #options for list of keys. <ide> * If string it will be used as format. <ide> * @return string Counter string. <ide> * @link https://book.cakephp.org/3.0/en/views/helpers/paginator.html#creating-a-page-counter <ide> */ <del> public function counter(array $options = []) <add> public function counter($format, array $options = []) <ide> { <ide> $options += [ <ide> 'model' => $this->defaultModel(), <del> 'format' => 'pages', <ide> ]; <ide> <ide> $paging = $this->params($options['model']); <ide> if (!$paging['pageCount']) { <ide> $paging['pageCount'] = 1; <ide> } <ide> <del> switch ($options['format']) { <add> switch ($format) { <ide> case 'range': <ide> case 'pages': <del> $template = 'counter' . ucfirst($options['format']); <add> $template = 'counter' . ucfirst($format); <ide> break; <ide> default: <ide> $template = 'counterCustom'; <del> $this->templater()->add([$template => $options['format']]); <add> $this->templater()->add([$template => $format]); <ide> } <ide> $map = array_map([$this->Number, 'format'], [ <ide> 'page' => $paging['page'], <ide><path>tests/TestCase/View/Helper/PaginatorHelperTest.php <ide> public function testCounter() <ide> <ide> $expected = 'Page 1 of 5, showing 3 records out of 13 total, starting on record 1, '; <ide> $expected .= 'ending on 3'; <del> $result = $this->Paginator->counter(['format' => $input]); <add> $result = $this->Paginator->counter($input); <ide> $this->assertEquals($expected, $result); <ide> <del> $result = $this->Paginator->counter(['format' => 'pages']); <add> $result = $this->Paginator->counter('pages'); <ide> $expected = '1 of 5'; <ide> $this->assertEquals($expected, $result); <ide> <del> $result = $this->Paginator->counter(['format' => 'range']); <add> $result = $this->Paginator->counter('range'); <ide> $expected = '1 - 3 of 13'; <ide> $this->assertEquals($expected, $result); <ide> <del> $result = $this->Paginator->counter(['format' => 'Showing {{page}} of {{pages}} {{model}}']); <add> $result = $this->Paginator->counter('Showing {{page}} of {{pages}} {{model}}'); <ide> $this->assertEquals('Showing 1 of 5 clients', $result); <ide> } <ide> <ide> public function testCounterBigNumbers() <ide> <ide> $expected = 'Page 1,523 of 1,600, showing 3,000 records out of 4,800,001 total, '; <ide> $expected .= 'starting on record 4,566,001, ending on 4,569,001'; <del> $result = $this->Paginator->counter(['format' => $input]); <add> $result = $this->Paginator->counter($input); <ide> $this->assertEquals($expected, $result); <ide> <ide> I18n::setLocale('de-DE'); <ide> $expected = 'Page 1.523 of 1.600, showing 3.000 records out of 4.800.001 total, '; <ide> $expected .= 'starting on record 4.566.001, ending on 4.569.001'; <del> $result = $this->Paginator->counter(['format' => $input]); <add> $result = $this->Paginator->counter($input); <ide> $this->assertEquals($expected, $result); <ide> } <ide> <ide> public function testWithZeroPages() <ide> ] <ide> ])); <ide> <del> $result = $this->Paginator->counter(['format' => 'pages']); <add> $result = $this->Paginator->counter('pages'); <ide> $expected = '0 of 1'; <ide> $this->assertEquals($expected, $result); <ide> }
2
PHP
PHP
ensure consistent order for loaded function
d63b4df10c8974f4c3dcc60397d91d5ed2fcd381
<ide><path>lib/Cake/Core/CakePlugin.php <ide> class CakePlugin { <ide> * parameters (plugin name, plugin configuration) <ide> * <ide> * It is also possible to load multiple plugins at once. Examples: <del> * <add> * <ide> * `CakePlugin::load(array('DebugKit', 'ApiGenerator'))` will load the DebugKit and ApiGenerator plugins <ide> * `CakePlugin::load(array('DebugKit', 'ApiGenerator'), array('bootstrap' => true))` will load bootstrap file for both plugins <del> * <add> * <ide> * {{{ <ide> * CakePlugin::load(array( <ide> * 'DebugKit' => array('routes' => true), <ide> * 'ApiGenerator' <ide> * ), array('bootstrap' => true)) <ide> * }}} <del> * <add> * <ide> * Will only load the bootstrap for ApiGenerator and only the routes for DebugKit <del> * <add> * <ide> * @param mixed $plugin name of the plugin to be loaded in CamelCase format or array or plugins to load <ide> * @param array $config configuration options for the plugin <ide> * @throws MissingPluginException if the folder for the plugin to be loaded is not found <ide> public static function load($plugin, $config = array()) { <ide> * The above example will load the bootstrap file for all plugins, but for DebugKit it will only load the routes file <ide> * and will not look for any bootstrap script. <ide> * <del> * @param array $options <add> * @param array $options <ide> * @return void <ide> */ <ide> public function loadAll($options = array()) { <ide> public static function loaded($plugin = null) { <ide> if ($plugin) { <ide> return isset(self::$_plugins[$plugin]); <ide> } <del> return array_keys(self::$_plugins); <add> $return = array_keys(self::$_plugins); <add> sort($return); <add> return $return; <ide> } <ide> <ide> /** <ide> public static function unload($plugin = null) { <ide> unset(self::$_plugins[$plugin]); <ide> } <ide> } <del>} <ide>\ No newline at end of file <add>}
1
Javascript
Javascript
remove unused variable
4b887fe1c205a6a9d16cc9b77f96e640df6c8b60
<ide><path>web/debugger.js <ide> var StepperManager = (function StepperManagerClosure() { <ide> this.selectStepper(pageNumber, false); <ide> return stepper; <ide> }, <del> selectStepper: function selectStepper(pageNumber, selectPanel, change) { <add> selectStepper: function selectStepper(pageNumber, selectPanel) { <ide> if (selectPanel) <ide> this.manager.selectPanel(1); <ide> for (var i = 0; i < steppers.length; ++i) {
1
Python
Python
set version to v3.4.0
bffe54d02b840a73f8dec4d8cd50056507695853
<ide><path>spacy/about.py <ide> # fmt: off <ide> __title__ = "spacy" <del>__version__ = "3.3.0" <add>__version__ = "3.4.0" <ide> __download_url__ = "https://github.com/explosion/spacy-models/releases/download" <ide> __compatibility__ = "https://raw.githubusercontent.com/explosion/spacy-models/master/compatibility.json" <ide> __projects__ = "https://github.com/explosion/projects"
1
PHP
PHP
fix url option in first() and last()
0f911778dc5beb24c173fd1ec6b3f3c92adcd7af
<ide><path>src/View/Helper/PaginatorHelper.php <ide> public function first($first = '<< first', array $options = []): string <ide> } elseif ($params['page'] > 1 && is_string($first)) { <ide> $first = $options['escape'] ? h($first) : $first; <ide> $out .= $this->templater()->format('first', [ <del> 'url' => $this->generateUrl(['page' => 1], $options['model']), <add> 'url' => $this->generateUrl(['page' => 1], $options['model'], $options['url']), <ide> 'text' => $first, <ide> ]); <ide> } <ide> public function last($last = 'last >>', array $options = []): string <ide> } elseif ($params['page'] < $params['pageCount'] && is_string($last)) { <ide> $last = $options['escape'] ? h($last) : $last; <ide> $out .= $this->templater()->format('last', [ <del> 'url' => $this->generateUrl(['page' => $params['pageCount']], $options['model']), <add> 'url' => $this->generateUrl(['page' => $params['pageCount']], $options['model'], $options['url']), <ide> 'text' => $last, <ide> ]); <ide> } <ide><path>tests/TestCase/View/Helper/PaginatorHelperTest.php <ide> public function testFirstAndLastTag() <ide> '/li', <ide> ]; <ide> $this->assertHtml($expected, $result); <add> <add> $result = $this->Paginator->first('first', ['url' => ['action' => 'paged']]); <add> $expected = [ <add> 'li' => ['class' => 'first'], <add> 'a' => ['href' => '/paged'], <add> 'first', <add> '/a', <add> '/li', <add> ]; <add> $this->assertHtml($expected, $result); <ide> } <ide> <ide> /** <ide> public function testLast() <ide> <ide> $result = $this->Paginator->last(3); <ide> $this->assertSame('', $result, 'When inside the last links range, no links should be made'); <add> <add> <add> $result = $this->Paginator->last('lastest', ['url' => ['action' => 'paged']]); <add> $expected = [ <add> 'li' => ['class' => 'last'], <add> 'a' => ['href' => '/paged?page=7'], <add> 'lastest', <add> '/a', <add> '/li', <add> ]; <add> $this->assertHtml($expected, $result); <ide> } <ide> <ide> /**
2
Javascript
Javascript
replace concat with template literals
506a5f75f859c5664c85a324e6950a00b4f64ea2
<ide><path>test/inspector/test-bindings.js <ide> function testSampleDebugSession() { <ide> actual = v['value']['value']; <ide> expected = expects[v['name']][i]; <ide> if (actual !== expected) { <del> failures.push('Iteration ' + i + ' variable: ' + v['name'] + <del> ' expected: ' + expected + ' actual: ' + actual); <add> failures.push(`Iteration ${i} variable: ${v['name']} ` + <add> `expected: ${expected} actual: ${actual}`); <ide> } <ide> } <ide> };
1
Python
Python
fix bug with padding mask + add corresponding test
da10de8466c001dceca328dac12751abb71c65eb
<ide><path>examples/utils_summarization.py <ide> def build_lm_labels(sequence, pad_token): <ide> def build_mask(sequence, pad_token): <ide> """ Builds the mask. The attention mechanism will only attend to positions <ide> with value 1. """ <del> mask = sequence.clone() <del> mask[mask != pad_token] = 1 <del> mask[mask == pad_token] = 0 <add> mask = torch.ones_like(sequence) <add> idx_pad_tokens = (sequence == pad_token) <add> mask[idx_pad_tokens] = 0 <ide> return mask <ide> <ide> <ide><path>examples/utils_summarization_test.py <ide> def test_build_mask(self): <ide> build_mask(sequence, 23).numpy(), expected.numpy() <ide> ) <ide> <add> def test_build_mask_with_padding_equal_to_one(self): <add> sequence = torch.tensor([8, 2, 3, 4, 1, 1, 1]) <add> expected = torch.tensor([1, 1, 1, 1, 0, 0, 0]) <add> np.testing.assert_array_equal( <add> build_mask(sequence, 1).numpy(), expected.numpy() <add> ) <add> <ide> def test_compute_token_type_ids(self): <ide> separator = 101 <ide> batch = torch.tensor(
2
Javascript
Javascript
add test for clicking an svg element
83f3c296f34611fe0e0f3a44c24b0e9667c43a09
<ide><path>spec/text-editor-component-spec.js <ide> describe('TextEditorComponent', function () { <ide> }) <ide> }) <ide> <add> describe('when the mousewheel event\'s target is an SVG element inside a block decoration', function () { <add> it('keeps the block decoration on the DOM if it is scrolled off-screen', function () { <add> wrapperNode.style.height = 4.5 * lineHeightInPixels + 'px' <add> wrapperNode.style.width = 20 * charWidth + 'px' <add> editor.update({autoHeight: false}) <add> component.measureDimensions() <add> runAnimationFrames() <add> <add> const item = document.createElement('div') <add> const svgElement = document.createElementNS("http://www.w3.org/2000/svg", "svg") <add> item.appendChild(svgElement) <add> editor.decorateMarker( <add> editor.markScreenPosition([0, 0], {invalidate: "never"}), <add> {type: "block", item: item} <add> ) <add> <add> runAnimationFrames() <add> <add> let wheelEvent = new WheelEvent('mousewheel', { <add> wheelDeltaX: 0, <add> wheelDeltaY: -500 <add> }) <add> Object.defineProperty(wheelEvent, 'target', { <add> get: function () { <add> return svgElement <add> } <add> }) <add> componentNode.dispatchEvent(wheelEvent) <add> runAnimationFrames() <add> <add> expect(component.getTopmostDOMNode().contains(item)).toBe(true) <add> }) <add> }) <add> <ide> it('only prevents the default action of the mousewheel event if it actually lead to scrolling', function () { <ide> spyOn(WheelEvent.prototype, 'preventDefault').andCallThrough() <ide> wrapperNode.style.height = 4.5 * lineHeightInPixels + 'px'
1
Text
Text
recommend use of rails over bin/rails
6ae2ab4f447b286b00eaab0df9072aed9e3246e8
<ide><path>README.md <ide> Assumes a Rails 6+ application with Active Storage and Webpacker installed. <ide> gem "actiontext", github: "rails/actiontext", require: "action_text" <ide> gem "image_processing", "~> 1.2" # for Active Storage variants <ide> ``` <del> <del>1. Install assets, npm dependency, and migrations <add> <add>1. Install assets, npm dependency, and migrations: <ide> <ide> ``` <del> ./bin/rails action_text:install <del> ./bin/rails db:migrate <add> rails action_text:install <add> rails db:migrate <ide> ``` <ide> <ide> ## Examples
1
Text
Text
create model card for schmidek/electra-small-cased
298bdab18a18e03d22068a9fd620f0fd81c3ab06
<ide><path>model_cards/schmidek/electra-small-cased/README.md <add>--- <add>language: english <add>license: apache-2.0 <add>--- <add> <add>## ELECTRA-small-cased <add> <add>This is a cased version of `google/electra-small-discriminator`, trained on the <add>[OpenWebText corpus](https://skylion007.github.io/OpenWebTextCorpus/). <add> <add>Uses the same tokenizer and vocab from `bert-base-cased`
1
Ruby
Ruby
drop unneeded assignment
a091539febd3a5a9e5306924b38e0dd681de4a07
<ide><path>test/visitors/test_oracle12.rb <ide> def compile node <ide> stmt.limit = Nodes::Limit.new(10) <ide> stmt.lock = Nodes::Lock.new(Arel.sql('FOR UPDATE')) <ide> assert_raises ArgumentError do <del> sql = compile(stmt) <add> compile(stmt) <ide> end <ide> end <ide>
1
Javascript
Javascript
convert configschema to js
17557fe7d6dc6a1c1b4509404a208c5b3f859a49
<add><path>src/config-schema.js <del><path>src/config-schema.coffee <del>path = require 'path' <del>fs = require 'fs-plus' <del> <del># This is loaded by atom.coffee. See https://atom.io/docs/api/latest/Config for <del># more information about config schemas. <del>module.exports = <del> core: <del> type: 'object' <del> properties: <del> ignoredNames: <del> type: 'array' <del> default: [".git", ".hg", ".svn", ".DS_Store", "._*", "Thumbs.db"] <del> items: <add>/** @babel */ <add> <add>import path from 'path' <add>import fs from 'fs-plus' <add> <add>const configSchema = { <add> core: { <add> type: 'object', <add> <add> properties: { <add> ignoredNames: { <add> type: 'array', <add> default: ['.git', '.hg', '.svn', '.DS_Store', '._*', 'Thumbs.db'], <add> <add> items: { <ide> type: 'string' <add> }, <add> <ide> description: 'List of [glob patterns](https://en.wikipedia.org/wiki/Glob_%28programming%29). Files and directories matching these patterns will be ignored by some packages, such as the fuzzy finder and tree view. Individual packages might have additional config settings for ignoring names.' <del> excludeVcsIgnoredPaths: <del> type: 'boolean' <del> default: true <del> title: 'Exclude VCS Ignored Paths' <add> }, <add> <add> excludeVcsIgnoredPaths: { <add> type: 'boolean', <add> default: true, <add> title: 'Exclude VCS Ignored Paths', <ide> description: 'Files and directories ignored by the current project\'s VCS system will be ignored by some packages, such as the fuzzy finder and find and replace. For example, projects using Git have these paths defined in the .gitignore file. Individual packages might have additional config settings for ignoring VCS ignored files and folders.' <del> followSymlinks: <del> type: 'boolean' <del> default: true <add> }, <add> <add> followSymlinks: { <add> type: 'boolean', <add> default: true, <ide> description: 'Follow symbolic links when searching files and when opening files with the fuzzy finder.' <del> disabledPackages: <del> type: 'array' <del> default: [] <del> items: <add> }, <add> <add> disabledPackages: { <add> type: 'array', <add> default: [], <add> <add> items: { <ide> type: 'string' <add> }, <add> <ide> description: 'List of names of installed packages which are not loaded at startup.' <del> customFileTypes: <del> type: 'object' <del> default: {} <del> description: 'Associates scope names (e.g. `"source.js"`) with arrays of file extensions and file names (e.g. `["Somefile", ".js2"]`)' <del> additionalProperties: <del> type: 'array' <del> items: <add> }, <add> <add> customFileTypes: { <add> type: 'object', <add> default: {}, <add> description: "Associates scope names (e.g. `\"source.js\"`) with arrays of file extensions and file names (e.g. `[\"Somefile\", \".js2\"]`)", <add> <add> additionalProperties: { <add> type: 'array', <add> <add> items: { <ide> type: 'string' <del> themes: <del> type: 'array' <del> default: ['one-dark-ui', 'one-dark-syntax'] <del> items: <add> } <add> } <add> }, <add> <add> themes: { <add> type: 'array', <add> default: ['one-dark-ui', 'one-dark-syntax'], <add> <add> items: { <ide> type: 'string' <add> }, <add> <ide> description: 'Names of UI and syntax themes which will be used when Atom starts.' <del> projectHome: <del> type: 'string' <del> default: path.join(fs.getHomeDirectory(), 'github') <add> }, <add> <add> projectHome: { <add> type: 'string', <add> default: path.join(fs.getHomeDirectory(), 'github'), <ide> description: 'The directory where projects are assumed to be located. Packages created using the Package Generator will be stored here by default.' <del> audioBeep: <del> type: 'boolean' <del> default: true <add> }, <add> <add> audioBeep: { <add> type: 'boolean', <add> default: true, <ide> description: 'Trigger the system\'s beep sound when certain actions cannot be executed or there are no results.' <del> destroyEmptyPanes: <del> type: 'boolean' <del> default: true <del> title: 'Remove Empty Panes' <add> }, <add> <add> destroyEmptyPanes: { <add> type: 'boolean', <add> default: true, <add> title: 'Remove Empty Panes', <ide> description: 'When the last tab of a pane is closed, remove that pane as well.' <del> closeEmptyWindows: <del> type: 'boolean' <del> default: true <add> }, <add> <add> closeEmptyWindows: { <add> type: 'boolean', <add> default: true, <ide> description: 'When a window with no open tabs or panes is given the \'Close Tab\' command, close that window.' <del> fileEncoding: <del> description: 'Default character set encoding to use when reading and writing files.' <del> type: 'string' <del> default: 'utf8' <add> }, <add> <add> fileEncoding: { <add> description: 'Default character set encoding to use when reading and writing files.', <add> type: 'string', <add> default: 'utf8', <add> <ide> enum: [ <ide> 'cp437', <ide> 'eucjp', <ide> module.exports = <ide> 'windows1258', <ide> 'windows866' <ide> ] <del> openEmptyEditorOnStart: <del> description: 'Automatically open an empty editor on startup.' <del> type: 'boolean' <add> }, <add> <add> openEmptyEditorOnStart: { <add> description: 'Automatically open an empty editor on startup.', <add> type: 'boolean', <ide> default: true <del> automaticallyUpdate: <del> description: 'Automatically update Atom when a new release is available.' <del> type: 'boolean' <add> }, <add> <add> automaticallyUpdate: { <add> description: 'Automatically update Atom when a new release is available.', <add> type: 'boolean', <ide> default: true <del> allowPendingPaneItems: <del> description: 'Allow items to be previewed without adding them to a pane permanently, such as when single clicking files in the tree view.' <del> type: 'boolean' <add> }, <add> <add> allowPendingPaneItems: { <add> description: 'Allow items to be previewed without adding them to a pane permanently, such as when single clicking files in the tree view.', <add> type: 'boolean', <ide> default: true <del> telemetryConsent: <del> description: 'Allow usage statistics and exception reports to be sent to the Atom team to help improve the product.' <del> title: 'Send Telemetry to the Atom Team' <del> type: 'string' <del> default: 'undecided' <del> enum: [ <del> {value: 'limited', description: 'Allow limited anonymous usage stats, exception and crash reporting'} <del> {value: 'no', description: 'Do not send any telemetry data'} <del> {value: 'undecided', description: 'Undecided (Atom will ask again next time it is launched)'} <del> ] <del> warnOnLargeFileLimit: <del> description: 'Warn before opening files larger than this number of megabytes.' <del> type: 'number' <add> }, <add> <add> telemetryConsent: { <add> description: 'Allow usage statistics and exception reports to be sent to the Atom team to help improve the product.', <add> title: 'Send Telemetry to the Atom Team', <add> type: 'string', <add> default: 'undecided', <add> <add> enum: [{ <add> value: 'limited', <add> description: 'Allow limited anonymous usage stats, exception and crash reporting' <add> }, { <add> value: 'no', <add> description: 'Do not send any telemetry data' <add> }, { <add> value: 'undecided', <add> description: 'Undecided (Atom will ask again next time it is launched)' <add> }] <add> }, <add> <add> warnOnLargeFileLimit: { <add> description: "Warn before opening files larger than this number of megabytes.", <add> type: "number", <ide> default: 20 <del> editor: <del> type: 'object' <del> properties: <del> # These settings are used in scoped fashion only. No defaults. <del> commentStart: <add> } <add> } <add> }, <add> <add> editor: { <add> type: 'object', <add> <add> properties: { <add> commentStart: { <ide> type: ['string', 'null'] <del> commentEnd: <add> }, <add> <add> commentEnd: { <ide> type: ['string', 'null'] <del> increaseIndentPattern: <add> }, <add> <add> increaseIndentPattern: { <ide> type: ['string', 'null'] <del> decreaseIndentPattern: <add> }, <add> <add> decreaseIndentPattern: { <ide> type: ['string', 'null'] <del> foldEndPattern: <add> }, <add> <add> foldEndPattern: { <ide> type: ['string', 'null'] <add> }, <ide> <del> # These can be used as globals or scoped, thus defaults. <del> fontFamily: <del> type: 'string' <del> default: '' <add> fontFamily: { <add> type: 'string', <add> default: '', <ide> description: 'The name of the font family used for editor text.' <del> fontSize: <del> type: 'integer' <del> default: 14 <del> minimum: 1 <del> maximum: 100 <add> }, <add> <add> fontSize: { <add> type: 'integer', <add> default: 14, <add> minimum: 1, <add> maximum: 100, <ide> description: 'Height in pixels of editor text.' <del> lineHeight: <del> type: ['string', 'number'] <del> default: 1.5 <add> }, <add> <add> lineHeight: { <add> type: ['string', 'number'], <add> default: 1.5, <ide> description: 'Height of editor lines, as a multiplier of font size.' <del> showInvisibles: <del> type: 'boolean' <del> default: false <add> }, <add> <add> showInvisibles: { <add> type: 'boolean', <add> default: false, <ide> description: 'Render placeholders for invisible characters, such as tabs, spaces and newlines.' <del> showIndentGuide: <del> type: 'boolean' <del> default: false <add> }, <add> <add> showIndentGuide: { <add> type: 'boolean', <add> default: false, <ide> description: 'Show indentation indicators in the editor.' <del> showLineNumbers: <del> type: 'boolean' <del> default: true <add> }, <add> <add> showLineNumbers: { <add> type: 'boolean', <add> default: true, <ide> description: 'Show line numbers in the editor\'s gutter.' <del> atomicSoftTabs: <del> type: 'boolean' <del> default: true <add> }, <add> <add> atomicSoftTabs: { <add> type: 'boolean', <add> default: true, <ide> description: 'Skip over tab-length runs of leading whitespace when moving the cursor.' <del> autoIndent: <del> type: 'boolean' <del> default: true <add> }, <add> <add> autoIndent: { <add> type: 'boolean', <add> default: true, <ide> description: 'Automatically indent the cursor when inserting a newline.' <del> autoIndentOnPaste: <del> type: 'boolean' <del> default: true <add> }, <add> <add> autoIndentOnPaste: { <add> type: 'boolean', <add> default: true, <ide> description: 'Automatically indent pasted text based on the indentation of the previous line.' <del> nonWordCharacters: <del> type: 'string' <del> default: "/\\()\"':,.;<>~!@#$%^&*|+=[]{}`?-…" <add> }, <add> <add> nonWordCharacters: { <add> type: 'string', <add> default: "/\\()\"':,.;<>~!@#$%^&*|+=[]{}`?-…", <ide> description: 'A string of non-word characters to define word boundaries.' <del> preferredLineLength: <del> type: 'integer' <del> default: 80 <del> minimum: 1 <add> }, <add> <add> preferredLineLength: { <add> type: 'integer', <add> default: 80, <add> minimum: 1, <ide> description: 'Identifies the length of a line which is used when wrapping text with the `Soft Wrap At Preferred Line Length` setting enabled, in number of characters.' <del> tabLength: <del> type: 'integer' <del> default: 2 <del> minimum: 1 <add> }, <add> <add> tabLength: { <add> type: 'integer', <add> default: 2, <add> minimum: 1, <ide> description: 'Number of spaces used to represent a tab.' <del> softWrap: <del> type: 'boolean' <del> default: false <add> }, <add> <add> softWrap: { <add> type: 'boolean', <add> default: false, <ide> description: 'Wraps lines that exceed the width of the window. When `Soft Wrap At Preferred Line Length` is set, it will wrap to the number of characters defined by the `Preferred Line Length` setting.' <del> softTabs: <del> type: 'boolean' <del> default: true <add> }, <add> <add> softTabs: { <add> type: 'boolean', <add> default: true, <ide> description: 'If the `Tab Type` config setting is set to "auto" and autodetection of tab type from buffer content fails, then this config setting determines whether a soft tab or a hard tab will be inserted when the Tab key is pressed.' <del> tabType: <del> type: 'string' <del> default: 'auto' <del> enum: ['auto', 'soft', 'hard'] <add> }, <add> <add> tabType: { <add> type: 'string', <add> default: 'auto', <add> enum: ['auto', 'soft', 'hard'], <ide> description: 'Determine character inserted when Tab key is pressed. Possible values: "auto", "soft" and "hard". When set to "soft" or "hard", soft tabs (spaces) or hard tabs (tab characters) are used. When set to "auto", the editor auto-detects the tab type based on the contents of the buffer (it uses the first leading whitespace on a non-comment line), or uses the value of the Soft Tabs config setting if auto-detection fails.' <del> softWrapAtPreferredLineLength: <del> type: 'boolean' <del> default: false <add> }, <add> <add> softWrapAtPreferredLineLength: { <add> type: 'boolean', <add> default: false, <ide> description: 'Instead of wrapping lines to the window\'s width, wrap lines to the number of characters defined by the `Preferred Line Length` setting. This will only take effect when the soft wrap config setting is enabled globally or for the current language. **Note:** If you want to hide the wrap guide (the vertical line) you can disable the `wrap-guide` package.' <del> softWrapHangingIndent: <del> type: 'integer' <del> default: 0 <del> minimum: 0 <add> }, <add> <add> softWrapHangingIndent: { <add> type: 'integer', <add> default: 0, <add> minimum: 0, <ide> description: 'When soft wrap is enabled, defines length of additional indentation applied to wrapped lines, in number of characters.' <del> scrollSensitivity: <del> type: 'integer' <del> default: 40 <del> minimum: 10 <del> maximum: 200 <add> }, <add> <add> scrollSensitivity: { <add> type: 'integer', <add> default: 40, <add> minimum: 10, <add> maximum: 200, <ide> description: 'Determines how fast the editor scrolls when using a mouse or trackpad.' <del> scrollPastEnd: <del> type: 'boolean' <del> default: false <add> }, <add> <add> scrollPastEnd: { <add> type: 'boolean', <add> default: false, <ide> description: 'Allow the editor to be scrolled past the end of the last line.' <del> undoGroupingInterval: <del> type: 'integer' <del> default: 300 <del> minimum: 0 <add> }, <add> <add> undoGroupingInterval: { <add> type: 'integer', <add> default: 300, <add> minimum: 0, <ide> description: 'Time interval in milliseconds within which text editing operations will be grouped together in the undo history.' <del> confirmCheckoutHeadRevision: <del> type: 'boolean' <del> default: true <del> title: 'Confirm Checkout HEAD Revision' <add> }, <add> <add> confirmCheckoutHeadRevision: { <add> type: 'boolean', <add> default: true, <add> title: 'Confirm Checkout HEAD Revision', <ide> description: 'Show confirmation dialog when checking out the HEAD revision and discarding changes to current file since last commit.' <del> invisibles: <del> type: 'object' <del> description: 'A hash of characters Atom will use to render whitespace characters. Keys are whitespace character types, values are rendered characters (use value false to turn off individual whitespace character types).' <del> properties: <del> eol: <del> type: ['boolean', 'string'] <del> default: '\u00ac' <del> maximumLength: 1 <add> }, <add> <add> invisibles: { <add> type: 'object', <add> description: 'A hash of characters Atom will use to render whitespace characters. Keys are whitespace character types, values are rendered characters (use value false to turn off individual whitespace character types).', <add> <add> properties: { <add> eol: { <add> type: ['boolean', 'string'], <add> default: '¬', <add> maximumLength: 1, <ide> description: 'Character used to render newline characters (\\n) when the `Show Invisibles` setting is enabled. ' <del> space: <del> type: ['boolean', 'string'] <del> default: '\u00b7' <del> maximumLength: 1 <add> }, <add> <add> space: { <add> type: ['boolean', 'string'], <add> default: '·', <add> maximumLength: 1, <ide> description: 'Character used to render leading and trailing space characters when the `Show Invisibles` setting is enabled.' <del> tab: <del> type: ['boolean', 'string'] <del> default: '\u00bb' <del> maximumLength: 1 <add> }, <add> <add> tab: { <add> type: ['boolean', 'string'], <add> default: '»', <add> maximumLength: 1, <ide> description: 'Character used to render hard tab characters (\\t) when the `Show Invisibles` setting is enabled.' <del> cr: <del> type: ['boolean', 'string'] <del> default: '\u00a4' <del> maximumLength: 1 <add> }, <add> <add> cr: { <add> type: ['boolean', 'string'], <add> default: '¤', <add> maximumLength: 1, <ide> description: 'Character used to render carriage return characters (for Microsoft-style line endings) when the `Show Invisibles` setting is enabled.' <del> zoomFontWhenCtrlScrolling: <del> type: 'boolean' <del> default: process.platform isnt 'darwin' <add> } <add> } <add> }, <add> <add> zoomFontWhenCtrlScrolling: { <add> type: 'boolean', <add> default: process.platform !== 'darwin', <ide> description: 'Change the editor font size when pressing the Ctrl key and scrolling the mouse up/down.' <add> } <add> } <add> } <add>}; <ide> <del>if process.platform in ['win32', 'linux'] <del> module.exports.core.properties.autoHideMenuBar = <del> type: 'boolean' <del> default: false <add>if (['win32', 'linux'].includes(process.platform)) { <add> configSchema.core.properties.autoHideMenuBar = { <add> type: 'boolean', <add> default: false, <ide> description: 'Automatically hide the menu bar and toggle it by pressing Alt. This is only supported on Windows & Linux.' <add> }; <add>} <ide> <del>if process.platform is 'darwin' <del> module.exports.core.properties.useCustomTitleBar = <del> type: 'boolean' <del> default: false <add>if (process.platform === 'darwin') { <add> configSchema.core.properties.useCustomTitleBar = { <add> type: 'boolean', <add> default: false, <ide> description: 'Use custom, theme-aware title bar.<br>Note: This currently does not include a proxy icon.<br>This setting will require a relaunch of Atom to take effect.' <add> }; <add>} <add> <add>export default configSchema
1
Go
Go
add last version
64450ae3f89b8f9b5288224c5a7d109a166cf22a
<ide><path>commands.go <ide> func (cli *DockerCli) CmdVersion(args ...string) error { <ide> if out.GoVersion != "" { <ide> fmt.Fprintf(cli.out, "Go version: %s\n", out.GoVersion) <ide> } <add> <add> release := utils.GetReleaseVersion() <add> if release != "" { <add> fmt.Fprintf(cli.out, "Last stable version: %s", release) <add> if VERSION != release || out.Version != release { <add> fmt.Fprintf(cli.out, ", please update docker") <add> } <add> fmt.Fprintf(cli.out, "\n") <add> } <ide> return nil <ide> } <ide> <ide><path>utils/utils.go <ide> func ParseHost(host string, port int, addr string) string { <ide> } <ide> return fmt.Sprintf("tcp://%s:%d", host, port) <ide> } <add> <add>func GetReleaseVersion() string { <add> type githubTag struct { <add> Name string `json:"name"` <add> } <add> <add> resp, err := http.Get("https://api.github.com/repos/dotcloud/docker/tags") <add> if err != nil { <add> return "" <add> } <add> defer resp.Body.Close() <add> body, err := ioutil.ReadAll(resp.Body) <add> if err != nil { <add> return "" <add> } <add> var tags []githubTag <add> err = json.Unmarshal(body, &tags) <add> if err != nil || len(tags) == 0 { <add> return "" <add> } <add> return strings.TrimPrefix(tags[0].Name, "v") <add>}
2