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
Python
Python
introduce ignore_depends_on_past parameters
e290804d9d23af3451de22f35f834b0e9e90f311
<ide><path>airflow/bin/cli.py <ide> def backfill(args, dag=None): <ide> donot_pickle=(args.donot_pickle or <ide> conf.getboolean('core', 'donot_pickle')), <ide> ignore_dependencies=args.ignore_dependencies, <add> ignore_first_depends_on_past=args.ignore_first_depends_on_past, <ide> pool=args.pool) <ide> <ide> <ide> def run(args, dag=None): <ide> mark_success=args.mark_success, <ide> force=args.force, <ide> pickle_id=args.pickle, <del> task_start_date=args.task_start_date, <ide> ignore_dependencies=args.ignore_dependencies, <add> ignore_depends_on_past=args.ignore_depends_on_past, <ide> pool=args.pool) <ide> run_job.run() <ide> elif args.raw: <ide> ti.run( <ide> mark_success=args.mark_success, <ide> force=args.force, <ide> ignore_dependencies=args.ignore_dependencies, <add> ignore_depends_on_past=args.ignore_depends_on_past, <ide> job_id=args.job_id, <ide> pool=args.pool, <ide> ) <ide> def run(args, dag=None): <ide> mark_success=args.mark_success, <ide> pickle_id=pickle_id, <ide> ignore_dependencies=args.ignore_dependencies, <add> ignore_depends_on_past=args.ignore_depends_on_past, <ide> force=args.force, <ide> pool=args.pool) <ide> executor.heartbeat() <ide> class CLIFactory(object): <ide> "matching the regexp. Only works in conjunction " <ide> "with task_regex"), <ide> "store_true"), <add> 'bf_ignore_first_depends_on_past': Arg( <add> ("-I", "--ignore_first_depends_on_past"), <add> ( <add> "Ignores depends_on_past dependencies for the first " <add> "set of tasks only (subsequent executions in the backfill " <add> "DO respect depends_on_past)."), <add> "store_true"), <ide> 'pool': Arg(("--pool",), "Resource pool to use"), <ide> # list_dags <ide> 'tree': Arg(("-t", "--tree"), "Tree view", "store_true"), <ide> class CLIFactory(object): <ide> ("-kt", "--keytab"), "keytab", <ide> nargs='?', default=conf.get('kerberos', 'keytab')), <ide> # run <del> 'task_start_date': Arg( <del> ("-s", "--task_start_date"), <del> "Override the tasks's start_date (used internally)", <del> type=parsedate), <ide> 'force': Arg( <ide> ("-f", "--force"), <ide> "Force a run regardless or previous success", "store_true"), <ide> 'raw': Arg(("-r", "--raw"), argparse.SUPPRESS, "store_true"), <ide> 'ignore_dependencies': Arg( <ide> ("-i", "--ignore_dependencies"), <ide> "Ignore upstream and depends_on_past dependencies", "store_true"), <add> 'ignore_depends_on_past': Arg( <add> ("-I", "--ignore_depends_on_past"), <add> "Ignore depends_on_past dependencies (but respect " <add> "upstream dependencies)", <add> "store_true"), <ide> 'ship_dag': Arg( <ide> ("--ship_dag",), <ide> "Pickles (serializes) the DAG and ships it to the worker", <ide> class CLIFactory(object): <ide> 'args': ( <ide> 'dag_id', 'task_regex', 'start_date', 'end_date', <ide> 'mark_success', 'local', 'donot_pickle', 'include_adhoc', <del> 'bf_ignore_dependencies', 'subdir', 'pool', 'dry_run') <add> 'bf_ignore_dependencies', 'bf_ignore_first_depends_on_past', <add> 'subdir', 'pool', 'dry_run') <ide> }, { <ide> 'func': list_tasks, <ide> 'help': "List the tasks within a DAG", <ide> class CLIFactory(object): <ide> 'args': ( <ide> 'dag_id', 'task_id', 'execution_date', 'subdir', <ide> 'mark_success', 'force', 'pool', <del> 'task_start_date', 'local', 'raw', 'ignore_dependencies', <del> 'ship_dag', 'pickle', 'job_id'), <add> 'local', 'raw', 'ignore_dependencies', <add> 'ignore_depends_on_past', 'ship_dag', 'pickle', 'job_id'), <ide> }, { <ide> 'func': initdb, <ide> 'help': "Initialize the metadata database", <ide><path>airflow/executors/base_executor.py <ide> def queue_command(self, key, command, priority=1, queue=None): <ide> self.queued_tasks[key] = (command, priority, queue) <ide> <ide> def queue_task_instance( <del> self, task_instance, mark_success=False, pickle_id=None, <del> force=False, ignore_dependencies=False, task_start_date=None, <add> self, <add> task_instance, <add> mark_success=False, <add> pickle_id=None, <add> force=False, <add> ignore_dependencies=False, <add> ignore_depends_on_past=False, <ide> pool=None): <ide> pool = pool or task_instance.pool <ide> command = task_instance.command( <ide> local=True, <ide> mark_success=mark_success, <ide> force=force, <ide> ignore_dependencies=ignore_dependencies, <del> task_start_date=task_start_date, <add> ignore_depends_on_past=ignore_depends_on_past, <ide> pool=pool, <ide> pickle_id=pickle_id) <ide> self.queue_command( <ide><path>airflow/jobs.py <ide> def __init__( <ide> include_adhoc=False, <ide> donot_pickle=False, <ide> ignore_dependencies=False, <add> ignore_first_depends_on_past=False, <ide> pool=None, <ide> *args, **kwargs): <ide> self.dag = dag <del> dag.override_start_date(start_date) <ide> self.dag_id = dag.dag_id <ide> self.bf_start_date = start_date <ide> self.bf_end_date = end_date <ide> self.mark_success = mark_success <ide> self.include_adhoc = include_adhoc <ide> self.donot_pickle = donot_pickle <ide> self.ignore_dependencies = ignore_dependencies <add> self.ignore_first_depends_on_past = ignore_first_depends_on_past <ide> self.pool = pool <ide> super(BackfillJob, self).__init__(*args, **kwargs) <ide> <ide> def __init__( <ide> self, <ide> task_instance, <ide> ignore_dependencies=False, <add> ignore_depends_on_past=False, <ide> force=False, <ide> mark_success=False, <ide> pickle_id=None, <del> task_start_date=None, <ide> pool=None, <ide> *args, **kwargs): <ide> self.task_instance = task_instance <ide> self.ignore_dependencies = ignore_dependencies <add> self.ignore_depends_on_past=ignore_depends_on_past <ide> self.force = force <ide> self.pool = pool <ide> self.pickle_id = pickle_id <ide> self.mark_success = mark_success <del> self.task_start_date = task_start_date <ide> super(LocalTaskJob, self).__init__(*args, **kwargs) <ide> <ide> def _execute(self): <ide> command = self.task_instance.command( <ide> raw=True, <ide> ignore_dependencies=self.ignore_dependencies, <add> ignore_depends_on_past=self.ignore_depends_on_past, <ide> force=self.force, <ide> pickle_id=self.pickle_id, <ide> mark_success=self.mark_success, <del> task_start_date=self.task_start_date, <ide> job_id=self.id, <ide> pool=self.pool, <ide> ) <ide><path>airflow/models.py <ide> def command( <ide> self, <ide> mark_success=False, <ide> ignore_dependencies=False, <add> ignore_depends_on_past=False, <ide> force=False, <ide> local=False, <ide> pickle_id=None, <ide> raw=False, <del> task_start_date=None, <ide> job_id=None, <ide> pool=None): <ide> """ <ide> def command( <ide> cmd += "--pickle {pickle_id} " if pickle_id else "" <ide> cmd += "--job_id {job_id} " if job_id else "" <ide> cmd += "-i " if ignore_dependencies else "" <add> cmd += "-I " if ignore_depends_on_past else "" <ide> cmd += "--force " if force else "" <ide> cmd += "--local " if local else "" <ide> cmd += "--pool {pool} " if pool else "" <ide> cmd += "--raw " if raw else "" <del> if task_start_date: <del> cmd += "-s " + task_start_date.isoformat() + ' ' <ide> if not pickle_id and dag and dag.full_filepath: <ide> cmd += "-sd DAGS_FOLDER/{dag.filepath} " <ide> return cmd.format(**locals()) <ide> def set_state(self, state, session): <ide> self.end_date = datetime.now() <ide> session.merge(self) <ide> <del> def is_queueable(self, flag_upstream_failed=False): <add> def is_queueable( <add> self, <add> include_queued=False, <add> ignore_depends_on_past=False, <add> flag_upstream_failed=False): <ide> """ <ide> Returns a boolean on whether the task instance has met all dependencies <ide> and is ready to run. It considers the task's state, the state <ide> of its dependencies, depends_on_past and makes sure the execution <ide> isn't in the future. It doesn't take into <ide> account whether the pool has a slot for it to run. <ide> <add> :param include_queued: If True, tasks that have already been queued <add> are included. Defaults to False. <add> :type include_queued: boolean <add> :param ignore_depends_on_past: if True, ignores depends_on_past <add> dependencies. Defaults to False. <add> :type ignore_depends_on_past: boolean <ide> :param flag_upstream_failed: This is a hack to generate <ide> the upstream_failed state creation while checking to see <ide> whether the task instance is runnable. It was the shortest <ide> path to add the feature <ide> :type flag_upstream_failed: boolean <ide> """ <add> # is the execution date in the future? <ide> if self.execution_date > datetime.now(): <ide> return False <add> # is the task still in the retry waiting period? <ide> elif self.state == State.UP_FOR_RETRY and not self.ready_for_retry(): <ide> return False <add> # does the task have an end_date prior to the execution date? <ide> elif self.task.end_date and self.execution_date > self.task.end_date: <ide> return False <del> elif self.state in (State.SKIPPED, State.QUEUED): <add> # has the task been skipped? <add> elif self.state == State.SKIPPED: <add> return False <add> # has the task already been queued (and are we excluding queued tasks)? <add> elif self.state == State.QUEUED and not include_queued: <ide> return False <add> # is the task runnable and have its dependencies been met? <ide> elif ( <ide> self.state in State.runnable() and <ide> self.are_dependencies_met( <add> ignore_depends_on_past=ignore_depends_on_past, <ide> flag_upstream_failed=flag_upstream_failed)): <ide> return True <add> # anything else <ide> else: <ide> return False <ide> <del> def is_runnable(self, flag_upstream_failed=False): <add> def is_runnable( <add> self, <add> include_queued=False, <add> ignore_depends_on_past=False, <add> flag_upstream_failed=False): <ide> """ <ide> Returns whether a task is ready to run AND there's room in the <ide> queue. <add> <add> :param include_queued: If True, tasks that are already QUEUED are <add> considered "runnable". Defaults to False. <add> :type include_queued: boolean <add> :param ignore_depends_on_past: if True, ignores depends_on_past <add> dependencies. Defaults to False. <add> :type ignore_depends_on_past: boolean <ide> """ <del> return self.is_queueable(flag_upstream_failed) and not self.pool_full() <add> queueable = self.is_queueable( <add> include_queued=include_queued, <add> ignore_depends_on_past=ignore_depends_on_past, <add> flag_upstream_failed=flag_upstream_failed) <add> return queueable and not self.pool_full() <ide> <ide> @provide_session <ide> def are_dependents_done(self, session=None): <ide> def are_dependents_done(self, session=None): <ide> <ide> @provide_session <ide> def are_dependencies_met( <del> self, session=None, flag_upstream_failed=False, <add> self, <add> session=None, <add> flag_upstream_failed=False, <add> ignore_depends_on_past=False, <ide> verbose=False): <ide> """ <ide> Returns a boolean on whether the upstream tasks are in a SUCCESS state <ide> def are_dependencies_met( <ide> whether the task instance is runnable. It was the shortest <ide> path to add the feature <ide> :type flag_upstream_failed: boolean <add> :param ignore_depends_on_past: if True, ignores depends_on_past <add> dependencies. Defaults to False. <add> :type ignore_depends_on_past: boolean <ide> :param verbose: verbose provides more logging in the case where the <ide> task instance is evaluated as a check right before being executed. <ide> In the case of the scheduler evaluating the dependencies, this <ide> def are_dependencies_met( <ide> task = self.task <ide> <ide> # Checking that the depends_on_past is fulfilled <del> if (task.depends_on_past and <add> if (task.depends_on_past and not ignore_depends_on_past and <ide> not self.execution_date == task.start_date): <ide> previous_ti = session.query(TI).filter( <ide> TI.dag_id == self.dag_id, <ide> def run( <ide> self, <ide> verbose=True, <ide> ignore_dependencies=False, # Doesn't check for deps, just runs <add> ignore_depends_on_past=False, # Ignore depends_on_past but respect <add> # other deps <ide> force=False, # Disregards previous successes <ide> mark_success=False, # Don't run the task, act as if it succeeded <ide> test_mode=False, # Doesn't record success or failure in the DB <ide> def run( <ide> "Task {self} previously succeeded" <ide> " on {self.end_date}".format(**locals()) <ide> ) <del> elif not ignore_dependencies and \ <del> not self.are_dependencies_met(session=session, verbose=True): <add> elif ( <add> not ignore_dependencies and <add> not self.are_dependencies_met( <add> session=session, <add> ignore_depends_on_past=ignore_depends_on_past, <add> verbose=True) <add> ): <ide> logging.warning("Dependencies not met yet") <del> elif self.state == State.UP_FOR_RETRY and \ <del> not self.ready_for_retry(): <add> elif ( <add> self.state == State.UP_FOR_RETRY and <add> not self.ready_for_retry() <add> ): <ide> next_run = (self.end_date + task.retry_delay).isoformat() <ide> logging.info( <ide> "Not ready for retry yet. " + <ide> def detect_downstream_cycle(self, task=None): <ide> return False <ide> <ide> def run( <del> self, start_date=None, end_date=None, ignore_dependencies=False, <del> force=False, mark_success=False): <add> self, <add> start_date=None, <add> end_date=None, <add> ignore_dependencies=False, <add> ignore_first_depends_on_past=False, <add> force=False, <add> mark_success=False): <ide> """ <ide> Run a set of task instances for a date range. <ide> """ <ide> def run( <ide> TaskInstance(self, dt).run( <ide> mark_success=mark_success, <ide> ignore_dependencies=ignore_dependencies, <add> ignore_depends_on_past=( <add> dt == start_date and ignore_first_depends_on_past), <ide> force=force,) <ide> <ide> def dry_run(self): <ide> def owner(self): <ide> @provide_session <ide> def concurrency_reached(self, session=None): <ide> """ <del> Returns a boolean as to whether the concurrency limit for this DAG <add> Returns a boolean indicating whether the concurrency limit for this DAG <ide> has been reached <ide> """ <ide> TI = TaskInstance <ide> def concurrency_reached(self, session=None): <ide> @provide_session <ide> def is_paused(self, session=None): <ide> """ <del> Returns a boolean as to whether this DAG is paused <add> Returns a boolean indicating whether this DAG is paused <ide> """ <ide> qry = session.query(DagModel).filter( <ide> DagModel.dag_id == self.dag_id) <ide> def crawl_for_tasks(objects): <ide> """ <ide> raise NotImplementedError("") <ide> <del> def override_start_date(self, start_date): <del> """ <del> Sets start_date of all tasks and of the DAG itself to a certain date. <del> This is used by BackfillJob. <del> """ <del> for t in self.tasks: <del> t.start_date = start_date <del> self.start_date = start_date <del> <ide> def get_template_env(self): <ide> ''' <ide> Returns a jinja2 Environment while taking into account the DAGs <ide> def db_merge(self): <ide> session.commit() <ide> <ide> def run( <del> self, start_date=None, end_date=None, mark_success=False, <del> include_adhoc=False, local=False, executor=None, <add> self, <add> start_date=None, <add> end_date=None, <add> mark_success=False, <add> include_adhoc=False, <add> local=False, <add> executor=None, <ide> donot_pickle=configuration.getboolean('core', 'donot_pickle'), <ide> ignore_dependencies=False, <add> ignore_first_depends_on_past=False, <ide> pool=None): <add> """ <add> Runs the DAG. <add> """ <ide> from airflow.jobs import BackfillJob <ide> if not executor and local: <ide> executor = LocalExecutor() <ide> def run( <ide> executor=executor, <ide> donot_pickle=donot_pickle, <ide> ignore_dependencies=ignore_dependencies, <add> ignore_first_depends_on_past=ignore_first_depends_on_past, <ide> pool=pool) <ide> job.run() <ide>
4
Ruby
Ruby
install tap if needed."
e10ade758d7937b9f713c7d4f1c7c95d2f2b6721
<ide><path>Library/Homebrew/formulary.rb <ide> def get_formula(spec, alias_path: nil) <ide> end <ide> <ide> def load_file <del> tap.install unless tap.installed? <del> <ide> super <ide> rescue MethodDeprecatedError => e <ide> e.issues_url = tap.issues_url || tap.to_s <ide><path>Library/Homebrew/test/formulary_spec.rb <ide> class Wrong#{described_class.class_s(formula_name)} < Formula <ide> end <ide> end <ide> <del> it "raises an error if the Formula is not available after tapping" do <del> expect_any_instance_of(Tap).to receive(:install) <add> it "raises an error if the Formula is not available" do <ide> expect { <ide> described_class.to_rack("a/b/#{formula_name}") <ide> }.to raise_error(TapFormulaUnavailableError)
2
Text
Text
update upgrad guide
a297fe838946f1412e61647797df78eb5b24b267
<ide><path>upgrade.md <ide> <ide> ## Upgrading From 4.0 to 4.1 <ide> <del>- Update `composer.json` to require `"laravel/framework": "4.1.*"` <add>- Update `composer.json` to require `"laravel/framework": "4.1.*"` <ide> - `composer update`. <ide> - Replace `public/index.php`, `artisan.php`. <ide> - Add new `expire_on_close` option to `session` configuration file. <ide> - If you are overriding `missingMethod` in your controllers, add $method as the first parameter. <ide> - Password reminder system tweaked for greater developer freedom. Inspect stub controller by running `auth:reminders-controller` Artisan command. <ide> - Update `reminders.php` language file. <add>- If you are using http hosts to set the $env variable in bootstrap/start.php, these should be changed to machine names (as returned by PHP's gethostname() function). <ide>\ No newline at end of file
1
Javascript
Javascript
fix dev mode
deb94f6f4aa414e9dad32c20e8dca38bc1c142cf
<ide><path>static/index.js <ide> let blobStore = null <ide> let devMode = false <ide> let useSnapshot = false <del> let requireFunction = null <ide> <ide> window.onload = function () { <ide> try { <ide> setupAtomHome() <ide> devMode = getWindowLoadSettings().devMode || !getWindowLoadSettings().resourcePath.startsWith(process.resourcesPath + path.sep) <ide> useSnapshot = !devMode && typeof snapshotResult !== 'undefined' <del> requireFunction = useSnapshot ? snapshotResult.customRequire : require <ide> <ide> if (devMode) { <ide> const metadata = require('../package.json') <ide> snapshotResult.entryPointDirPath = __dirname <ide> } <ide> <del> // const FileSystemBlobStore = requireFunction('../src/file-system-blob-store.js') <del> // blobStore = FileSystemBlobStore.load( <del> // path.join(process.env.ATOM_HOME, 'blob-store/') <del> // ) <del> <del> // const NativeCompileCache = requireFunction('../src/native-compile-cache.js') <del> // NativeCompileCache.setCacheStore(blobStore) <del> // NativeCompileCache.setV8Version(process.versions.v8) <del> // NativeCompileCache.install() <del> <ide> if (getWindowLoadSettings().profileStartup) { <ide> profileStartup(Date.now() - startTime) <ide> } else { <ide> } <ide> <ide> function setupWindow () { <del> const CompileCache = requireFunction('../src/compile-cache.js') <add> const CompileCache = useSnapshot ? snapshotResult.customRequire('../src/compile-cache.js') : require('../src/compile-cache') <ide> CompileCache.setAtomHomeDirectory(process.env.ATOM_HOME) <ide> CompileCache.install(require) <ide> <del> const ModuleCache = requireFunction('../src/module-cache.js') <add> const ModuleCache = useSnapshot ? snapshotResult.customRequire('../src/module-cache.js') : require('../src/module-cache') <ide> ModuleCache.register(getWindowLoadSettings()) <ide> <del> const startCrashReporter = requireFunction('../src/crash-reporter-start.js') <add> const startCrashReporter = useSnapshot ? snapshotResult.customRequire('../src/crash-reporter-start.js') : require('../src/crash-reporter-start') <ide> startCrashReporter({_version: getWindowLoadSettings().appVersion}) <ide> <del> const CSON = requireFunction(useSnapshot ? '../node_modules/season/lib/cson.js' : 'season') <add> const CSON = useSnapshot ? snapshotResult.customRequire('../node_modules/season/lib/cson.js') : require('season') <ide> CSON.setCacheDir(path.join(CompileCache.getCacheDirectory(), 'cson')) <ide> <ide> const initScriptPath = path.relative(entryPointDirPath, getWindowLoadSettings().windowInitializationScript) <del> const initialize = requireFunction(initScriptPath) <add> const initialize = useSnapshot ? snapshotResult.customRequire(initScriptPath) : require(initScriptPath) <ide> return initialize({blobStore: blobStore}).then(function () { <ide> electron.ipcRenderer.send('window-command', 'window:loaded') <ide> })
1
Go
Go
fix decode data loss when using int64 in json
0aa250bd60e472dadfd8e9e1f90465e041b03983
<ide><path>engine/env.go <ide> func (decoder *Decoder) Decode() (*Env, error) { <ide> // is returned. <ide> func (env *Env) Decode(src io.Reader) error { <ide> m := make(map[string]interface{}) <del> if err := json.NewDecoder(src).Decode(&m); err != nil { <add> d := json.NewDecoder(src) <add> // We need this or we'll lose data when we decode int64 in json <add> d.UseNumber() <add> if err := d.Decode(&m); err != nil { <ide> return err <ide> } <ide> for k, v := range m { <ide><path>engine/env_test.go <ide> func TestSetenv(t *testing.T) { <ide> } <ide> } <ide> <add>func TestDecodeEnv(t *testing.T) { <add> job := mkJob(t, "dummy") <add> type tmp struct { <add> Id1 int64 <add> Id2 int64 <add> } <add> body := []byte("{\"tags\":{\"Id1\":123, \"Id2\":1234567}}") <add> if err := job.DecodeEnv(bytes.NewBuffer(body)); err != nil { <add> t.Fatalf("DecodeEnv failed: %v", err) <add> } <add> mytag := tmp{} <add> if val := job.GetenvJson("tags", &mytag); val != nil { <add> t.Fatalf("GetenvJson returns incorrect value: %s", val) <add> } <add> <add> if mytag.Id1 != 123 || mytag.Id2 != 1234567 { <add> t.Fatal("Get wrong values set by job.DecodeEnv") <add> } <add>} <add> <ide> func TestSetenvBool(t *testing.T) { <ide> job := mkJob(t, "dummy") <ide> job.SetenvBool("foo", true)
2
PHP
PHP
improve static analyse
6cbf5c9e220a82fce5e1dc1740fdbcdb0ce47717
<ide><path>src/Illuminate/Database/Query/Builder.php <ide> public function select($columns = ['*']) <ide> /** <ide> * Add a subselect expression to the query. <ide> * <del> * @param \Closure|\Illuminate\Database\Query\Builder|string $query <add> * @param \Closure|$this|string $query <ide> * @param string $as <ide> * @return \Illuminate\Database\Query\Builder|static <ide> *
1
PHP
PHP
add tests for i18nshell option parser
d26703758a6e77fabf0edfe61ff5362bbc90d3e5
<ide><path>tests/TestCase/Shell/I18nShellTest.php <ide> public function tearDown() <ide> <ide> $deDir = $this->localeDir . 'de_DE' . DS; <ide> <del> unlink($this->localeDir . 'default.pot'); <del> unlink($this->localeDir . 'cake.pot'); <del> <del> unlink($deDir . 'default.po'); <del> unlink($deDir . 'cake.po'); <add> if (file_exists($this->localeDir . 'default.pot')) { <add> unlink($this->localeDir . 'default.pot'); <add> unlink($this->localeDir . 'cake.pot'); <add> } <add> if (file_exists($deDir . 'default.po')) { <add> unlink($deDir . 'default.po'); <add> unlink($deDir . 'cake.po'); <add> } <ide> } <ide> <ide> /** <ide> public function testInit() <ide> $this->assertFileExists($deDir . 'default.po'); <ide> $this->assertFileExists($deDir . 'cake.po'); <ide> } <add> <add> /** <add> * Test that the option parser is shaped right. <add> * <add> * @return void <add> */ <add> public function testGetOptionParser() <add> { <add> $this->shell->loadTasks(); <add> $parser = $this->shell->getOptionParser(); <add> $this->assertArrayHasKey('init', $parser->subcommands()); <add> $this->assertArrayHasKey('extract', $parser->subcommands()); <add> } <ide> }
1
Text
Text
fix typos "witht" and "spaguetti"
4f4100b00a36ce743a11f952a484b7d064a6d81e
<ide><path>guide/english/cplusplus/clean-code-guidelines/index.md <ide> int cucumber; // global variable "cucumber" <ide> ## Using goto, continue, etc. <ide> <ide> This is an usual discussion among programmers, just like global variables, these types of statements are usually considered bad practice. <del>They are considered bad because they lead to ["spaguetti code"](https://en.wikipedia.org/wiki/Spaghetti_code). When we program we want a <add>They are considered bad because they lead to ["spaghetti code"](https://en.wikipedia.org/wiki/Spaghetti_code). When we program we want a <ide> linear flow, when using those statements the flow is modified and lead to a "twisted and tangled" flow. <ide> <del>Goto was used in the past when while, for, if functions, however, witht the introduction of those structured programming was created. <add>Goto was used in the past when while, for, if functions, however, with the introduction of those structured programming was created. <ide> In general avoid using goto unless you are sure it will make your code cleaner and easier to read. An example might be using it in nested loops. <ide> <ide> The usage of break and continue are practically the same. Use them in switches and try to make functions with an only purpose so you only have one exit point.
1
Python
Python
fix integration test
fe35050a8f18dc52304aa8da4e463eececa25240
<ide><path>tests/integration_tests/applications_test.py <ide> def _test_application_basic(app, last_dim=1000): <ide> def _test_application_notop(app, last_dim): <ide> output_shape = _get_output_shape( <ide> lambda: app(weights=None, include_top=False)) <del> assert output_shape == (None, None, None, last_dim) <add> assert len(output_shape) == 4 <add> assert output_shape[-1] == last_dim <ide> <ide> <ide> def test_mobilenet_v2_legacy_import():
1
Python
Python
improve variable names in pty_helper.py
971915e89f1106444453eba39263ade92b3ed598
<ide><path>test/pseudo-tty/pty_helper.py <ide> def pipe(sfd, dfd): <ide> # Make select() interruptable by SIGCHLD. <ide> signal.signal(signal.SIGCHLD, lambda nr, _: None) <ide> <del> master_fd, slave_fd = pty.openpty() <del> assert master_fd > STDIN <add> parent_fd, child_fd = pty.openpty() <add> assert parent_fd > STDIN <ide> <del> mode = termios.tcgetattr(slave_fd) <add> mode = termios.tcgetattr(child_fd) <ide> # Don't translate \n to \r\n. <ide> mode[1] = mode[1] & ~termios.ONLCR # oflag <ide> # Disable ECHOCTL. It's a BSD-ism that echoes e.g. \x04 as ^D but it <ide> # doesn't work on platforms like AIX and Linux. I checked Linux's tty <ide> # driver and it's a no-op, the driver is just oblivious to the flag. <ide> mode[3] = mode[3] & ~termios.ECHOCTL # lflag <del> termios.tcsetattr(slave_fd, termios.TCSANOW, mode) <add> termios.tcsetattr(child_fd, termios.TCSANOW, mode) <ide> <ide> pid = os.fork() <ide> if not pid: <ide> os.setsid() <del> os.close(master_fd) <add> os.close(parent_fd) <ide> <ide> # Ensure the pty is a controlling tty. <del> name = os.ttyname(slave_fd) <add> name = os.ttyname(child_fd) <ide> fd = os.open(name, os.O_RDWR) <del> os.dup2(fd, slave_fd) <add> os.dup2(fd, child_fd) <ide> os.close(fd) <ide> <del> os.dup2(slave_fd, STDIN) <del> os.dup2(slave_fd, STDOUT) <del> os.dup2(slave_fd, STDERR) <add> os.dup2(child_fd, STDIN) <add> os.dup2(child_fd, STDOUT) <add> os.dup2(child_fd, STDERR) <ide> <del> if slave_fd > STDERR: <del> os.close(slave_fd) <add> if child_fd > STDERR: <add> os.close(child_fd) <ide> <ide> os.execve(argv[0], argv, os.environ) <ide> raise Exception('unreachable') <ide> <del> os.close(slave_fd) <add> os.close(child_fd) <ide> <del> fds = [STDIN, master_fd] <add> fds = [STDIN, parent_fd] <ide> while fds: <ide> try: <ide> rfds, _, _ = select.select(fds, [], []) <ide> def pipe(sfd, dfd): <ide> break <ide> <ide> if STDIN in rfds: <del> if pipe(STDIN, master_fd): <add> if pipe(STDIN, parent_fd): <ide> fds.remove(STDIN) <ide> <del> if master_fd in rfds: <del> if pipe(master_fd, STDOUT): <add> if parent_fd in rfds: <add> if pipe(parent_fd, STDOUT): <ide> break
1
Python
Python
add some comments to the code
237ea79464741350d11b0018e982881a0df24323
<ide><path>libcloud/storage/drivers/s3.py <ide> def _headers_to_object(self, object_name, container, headers): <ide> <ide> extra = {} <ide> <add> # Not all the S3 compatible implementations return this header, see <add> # https://github.com/apache/libcloud/pull/1695 for details <ide> if "content-type" in headers: <ide> extra["content_type"] = headers["content-type"] <ide> <add> # Google Storage S3 compatible API doesn't return this header under <add> # some scenarios https://github.com/apache/libcloud/issues/1682 <ide> if "etag" in headers: <ide> extra["etag"] = headers["etag"] <ide>
1
Javascript
Javascript
send user instead of req.user
73d26e4a7f57d66bf5733ae3537aebdfecae71fd
<ide><path>config/passport.js <ide> passport.use('tumblr', new OAuthStrategy({ <ide> User.findById(req.user._id, function(err, user) { <ide> user.tokens.push({ kind: 'tumblr', token: token, tokenSecret: tokenSecret }); <ide> user.save(function(err) { <del> done(err, req.user); <add> done(err, user); <ide> }); <ide> }); <ide> }
1
Python
Python
move path stuff into a separate function
2be54aa47c60ecebc8f759b8a48933927422a503
<ide><path>libcloud/pricing.py <ide> 'storage': {} <ide> } <ide> <add>def get_pricing_file_path(file_path=None): <add> pricing_directory = os.path.dirname(os.path.abspath(__file__)) <add> pricing_file_path = pjoin(pricing_directory, PRICING_FILE_PATH) <add> <add> return pricing_file_path <add> <ide> def get_pricing(driver_type, driver_name, pricing_file_path=None): <ide> """ <ide> Return pricing for the provided driver. <ide> def get_pricing(driver_type, driver_name, pricing_file_path=None): <ide> if not driver_type in [ 'compute', 'storage' ]: <ide> raise AttributeError('Invalid driver type: %s', driver_type) <ide> <del> driver_name = driver_name.lower().replace('nodedriver', '') <del> <ide> if driver_name in PRICING_DATA[driver_type]: <ide> return PRICING_DATA[driver_type][driver_name] <ide> <ide> if not pricing_file_path: <del> pricing_directory = os.path.dirname(os.path.abspath(__file__)) <del> pricing_file_path = pjoin(pricing_directory, PRICING_FILE_PATH) <add> pricing_file_path = get_pricing_file_path(file_path=pricing_file_path) <ide> <ide> with open(pricing_file_path) as fp: <ide> content = fp.read()
1
Javascript
Javascript
improve handling of built-in named parsers
74b04c9403af4fc7df5b6420f22c9f45a3e84140
<ide><path>src/ng/directive/input.js <ide> function createDateParser(regexp, mapping) { <ide> <ide> function createDateInputType(type, regexp, parseDate, format) { <ide> return function dynamicDateInputType(scope, element, attr, ctrl, $sniffer, $browser, $filter) { <del> badInputChecker(scope, element, attr, ctrl); <add> badInputChecker(scope, element, attr, ctrl, type); <ide> baseInputType(scope, element, attr, ctrl, $sniffer, $browser); <ide> var timezone = ctrl && ctrl.$options.getOption('timezone'); <ide> var previousDate; <ide> <del> ctrl.$$parserName = type; <ide> ctrl.$parsers.push(function(value) { <ide> if (ctrl.$isEmpty(value)) return null; <ide> if (regexp.test(value)) { <ide> function createDateInputType(type, regexp, parseDate, format) { <ide> } <ide> return parsedDate; <ide> } <add> ctrl.$$parserName = type; <ide> return undefined; <ide> }); <ide> <ide> function createDateInputType(type, regexp, parseDate, format) { <ide> }; <ide> } <ide> <del>function badInputChecker(scope, element, attr, ctrl) { <add>function badInputChecker(scope, element, attr, ctrl, parserName) { <ide> var node = element[0]; <ide> var nativeValidation = ctrl.$$hasNativeValidators = isObject(node.validity); <ide> if (nativeValidation) { <ide> ctrl.$parsers.push(function(value) { <ide> var validity = element.prop(VALIDITY_STATE_PROPERTY) || {}; <del> return validity.badInput || validity.typeMismatch ? undefined : value; <add> if (validity.badInput || validity.typeMismatch) { <add> ctrl.$$parserName = parserName; <add> return undefined; <add> } <add> <add> return value; <ide> }); <ide> } <ide> } <ide> <ide> function numberFormatterParser(ctrl) { <del> ctrl.$$parserName = 'number'; <ide> ctrl.$parsers.push(function(value) { <ide> if (ctrl.$isEmpty(value)) return null; <ide> if (NUMBER_REGEXP.test(value)) return parseFloat(value); <add> <add> ctrl.$$parserName = 'number'; <ide> return undefined; <ide> }); <ide> <ide> function isValidForStep(viewValue, stepBase, step) { <ide> } <ide> <ide> function numberInputType(scope, element, attr, ctrl, $sniffer, $browser) { <del> badInputChecker(scope, element, attr, ctrl); <add> badInputChecker(scope, element, attr, ctrl, 'number'); <ide> numberFormatterParser(ctrl); <ide> baseInputType(scope, element, attr, ctrl, $sniffer, $browser); <ide> <ide> function numberInputType(scope, element, attr, ctrl, $sniffer, $browser) { <ide> } <ide> <ide> function rangeInputType(scope, element, attr, ctrl, $sniffer, $browser) { <del> badInputChecker(scope, element, attr, ctrl); <add> badInputChecker(scope, element, attr, ctrl, 'range'); <ide> numberFormatterParser(ctrl); <ide> baseInputType(scope, element, attr, ctrl, $sniffer, $browser); <ide> <ide> function urlInputType(scope, element, attr, ctrl, $sniffer, $browser) { <ide> baseInputType(scope, element, attr, ctrl, $sniffer, $browser); <ide> stringBasedInputType(ctrl); <ide> <del> ctrl.$$parserName = 'url'; <ide> ctrl.$validators.url = function(modelValue, viewValue) { <ide> var value = modelValue || viewValue; <ide> return ctrl.$isEmpty(value) || URL_REGEXP.test(value); <ide> function emailInputType(scope, element, attr, ctrl, $sniffer, $browser) { <ide> baseInputType(scope, element, attr, ctrl, $sniffer, $browser); <ide> stringBasedInputType(ctrl); <ide> <del> ctrl.$$parserName = 'email'; <ide> ctrl.$validators.email = function(modelValue, viewValue) { <ide> var value = modelValue || viewValue; <ide> return ctrl.$isEmpty(value) || EMAIL_REGEXP.test(value); <ide><path>src/ng/directive/ngModel.js <ide> function NgModelController($scope, $exceptionHandler, $attr, $element, $parse, $ <ide> this.$$ngModelSet = this.$$parsedNgModelAssign; <ide> this.$$pendingDebounce = null; <ide> this.$$parserValid = undefined; <add> this.$$parserName = 'parse'; <ide> <ide> this.$$currentValidationRunId = 0; <ide> <ide> NgModelController.prototype = { <ide> processAsyncValidators(); <ide> <ide> function processParseErrors() { <del> var errorKey = that.$$parserName || 'parse'; <add> var errorKey = that.$$parserName; <add> <ide> if (isUndefined(that.$$parserValid)) { <ide> setValidity(errorKey, null); <ide> } else { <ide> NgModelController.prototype = { <ide> setValidity(name, null); <ide> }); <ide> } <add> <ide> // Set the parse error last, to prevent unsetting it, should a $validators key == parserName <ide> setValidity(errorKey, that.$$parserValid); <ide> return that.$$parserValid; <ide> NgModelController.prototype = { <ide> <ide> this.$$parserValid = isUndefined(modelValue) ? undefined : true; <ide> <add> // Reset any previous parse error <add> this.$setValidity(this.$$parserName, null); <add> this.$$parserName = 'parse'; <add> <ide> if (this.$$parserValid) { <ide> for (var i = 0; i < this.$parsers.length; i++) { <ide> modelValue = this.$parsers[i](modelValue); <ide><path>test/ng/directive/inputSpec.js <ide> describe('input', function() { <ide> helper.changeInputValueTo('stuff'); <ide> expect(inputElm.val()).toBe('stuff'); <ide> expect($rootScope.value).toBeUndefined(); <add> expect(inputElm).toHaveClass('ng-invalid-month'); <add> expect(inputElm).toBeInvalid(); <add> }); <add> <add> <add> it('should not set error=month when a later parser returns undefined', function() { <add> var inputElm = helper.compileInput('<input type="month" ng-model="value"/>'); <add> var ctrl = inputElm.controller('ngModel'); <add> <add> ctrl.$parsers.push(function() { <add> return undefined; <add> }); <add> <add> inputElm[0].setAttribute('type', 'text'); <add> <add> helper.changeInputValueTo('2017-01'); <add> <add> expect($rootScope.value).toBeUndefined(); <add> expect(ctrl.$error.month).toBeFalsy(); <add> expect(ctrl.$error.parse).toBeTruthy(); <add> expect(inputElm).not.toHaveClass('ng-invalid-month'); <add> expect(inputElm).toHaveClass('ng-invalid-parse'); <add> expect(inputElm).toBeInvalid(); <add> <add> helper.changeInputValueTo('asdf'); <add> <add> expect($rootScope.value).toBeUndefined(); <add> expect(ctrl.$error.month).toBeTruthy(); <add> expect(ctrl.$error.parse).toBeFalsy(); <add> expect(inputElm).toHaveClass('ng-invalid-month'); <add> expect(inputElm).not.toHaveClass('ng-invalid-parse'); <ide> expect(inputElm).toBeInvalid(); <ide> }); <ide> <ide> describe('input', function() { <ide> expect($rootScope.value).toBe(123214124123412412e-26); <ide> }); <ide> <add> it('should not set $error number if any other parser fails', function() { <add> var inputElm = helper.compileInput('<input type="number" ng-model="age"/>'); <add> var ctrl = inputElm.controller('ngModel'); <add> <add> var previousParserFail = false; <add> var laterParserFail = false; <add> <add> ctrl.$parsers.unshift(function(value) { <add> return previousParserFail ? undefined : value; <add> }); <add> <add> ctrl.$parsers.push(function(value) { <add> return laterParserFail ? undefined : value; <add> }); <add> <add> // to allow non-number values, we have to change type so that <add> // the browser which have number validation will not interfere with <add> // this test. <add> inputElm[0].setAttribute('type', 'text'); <add> <add> helper.changeInputValueTo('123X'); <add> expect(inputElm.val()).toBe('123X'); <add> <add> expect($rootScope.age).toBeUndefined(); <add> expect(inputElm).toBeInvalid(); <add> expect(ctrl.$error.number).toBe(true); <add> expect(ctrl.$error.parse).toBeFalsy(); <add> expect(inputElm).toHaveClass('ng-invalid-number'); <add> expect(inputElm).not.toHaveClass('ng-invalid-parse'); <add> <add> previousParserFail = true; <add> helper.changeInputValueTo('123'); <add> expect(inputElm.val()).toBe('123'); <add> <add> expect($rootScope.age).toBeUndefined(); <add> expect(inputElm).toBeInvalid(); <add> expect(ctrl.$error.number).toBeFalsy(); <add> expect(ctrl.$error.parse).toBe(true); <add> expect(inputElm).not.toHaveClass('ng-invalid-number'); <add> expect(inputElm).toHaveClass('ng-invalid-parse'); <add> <add> previousParserFail = false; <add> laterParserFail = true; <add> <add> helper.changeInputValueTo('1234'); <add> expect(inputElm.val()).toBe('1234'); <add> <add> expect($rootScope.age).toBeUndefined(); <add> expect(inputElm).toBeInvalid(); <add> expect(ctrl.$error.number).toBeFalsy(); <add> expect(ctrl.$error.parse).toBe(true); <add> expect(inputElm).not.toHaveClass('ng-invalid-number'); <add> expect(inputElm).toHaveClass('ng-invalid-parse'); <add> <add> laterParserFail = false; <add> <add> helper.changeInputValueTo('12345'); <add> expect(inputElm.val()).toBe('12345'); <add> <add> expect($rootScope.age).toBe(12345); <add> expect(inputElm).toBeValid(); <add> expect(ctrl.$error.number).toBeFalsy(); <add> expect(ctrl.$error.parse).toBeFalsy(); <add> expect(inputElm).not.toHaveClass('ng-invalid-number'); <add> expect(inputElm).not.toHaveClass('ng-invalid-parse'); <add> }); <add> <ide> <ide> describe('min', function() { <ide> <ide><path>test/ng/directive/ngModelSpec.js <ide> describe('ngModel', function() { <ide> } <ide> }; <ide> <del> ctrl.$$parserName = 'parserOrValidator'; <ide> ctrl.$parsers.push(function(value) { <ide> switch (value) { <ide> case 'allInvalid': <ide> case 'stillAllInvalid': <ide> case 'parseInvalid-validatorsValid': <ide> case 'stillParseInvalid-validatorsValid': <add> ctrl.$$parserName = 'parserOrValidator'; <ide> return undefined; <ide> default: <ide> return value;
4
Text
Text
remove link to forums in readme
f5201e3ca000acb44a318d3157b7628779fe5e6b
<ide><path>README.md <ide> ## Spring Framework <ide> The Spring Framework provides a comprehensive programming and configuration <del>model for modern Java-based enterprise applications - on any kind of deployment <add>model for modern Java-based enterprise applications -- on any kind of deployment <ide> platform. A key element of Spring is infrastructural support at the application <ide> level: Spring focuses on the "plumbing" of enterprise applications so that teams <ide> can focus on application-level business logic, without unnecessary ties to <ide> specific deployment environments. <ide> <del>The framework also serves as the foundation for [Spring Integration][], [Spring <del>Batch][] and the rest of the Spring [family of projects][]. Browse the repositories <del>under the [Spring organization][] on GitHub for a full list. <add>The framework also serves as the foundation for [Spring Integration][], [Spring Batch][] <add>and the rest of the Spring [family of projects][]. Browse the repositories under <add>the [Spring organization][] on GitHub for a full list. <ide> <ide> ## Downloading Artifacts <ide> See [downloading Spring artifacts][] for Maven repository information. Unable to <del>use Maven or other transitive dependency management tools? See [building a <del>distribution with dependencies][]. <add>use Maven or other transitive dependency management tools? <add>See [building a distribution with dependencies][]. <ide> <ide> ## Documentation <ide> See the current [Javadoc][] and [reference docs][]. <ide> <ide> ## Getting Support <del>Check out the [Spring forums][] and the [spring][spring tag] and <del>[spring-mvc][spring-mvc tag] tags on [Stack Overflow][]. [Commercial support][] <add>Check out the [spring][spring tags] tags on [Stack Overflow][]. [Commercial support][] <ide> is available too. <ide> <ide> ## Issue Tracking <del>Report issues via the [Spring Framework JIRA]. Understand our issue management <add>Report issues via the [Spring Framework JIRA][]. Understand our issue management <ide> process by reading about [the lifecycle of an issue][]. Think you've found a <ide> bug? Please consider submitting a reproduction project via the <ide> [spring-framework-issues][] GitHub repository. The [readme][] there provides <ide> The Spring Framework is released under version 2.0 of the [Apache License][]. <ide> [building a distribution with dependencies]: https://github.com/spring-projects/spring-framework/wiki/Building-a-distribution-with-dependencies <ide> [Javadoc]: http://docs.spring.io/spring-framework/docs/current/javadoc-api/ <ide> [reference docs]: http://docs.spring.io/spring-framework/docs/current/spring-framework-reference/ <del>[Spring forums]: http://forum.spring.io/ <del>[spring tag]: http://stackoverflow.com/questions/tagged/spring <del>[spring-mvc tag]: http://stackoverflow.com/questions/tagged/spring-mvc <add>[spring tags]: http://spring.io/questions <ide> [Stack Overflow]: http://stackoverflow.com/faq <ide> [Commercial support]: http://spring.io/services <ide> [Spring Framework JIRA]: https://jira.spring.io/browse/SPR
1
Javascript
Javascript
add api docs for observeactivetexteditor(callback)
14d8eccc6e5c7adff28888c338dda1086af2a556
<ide><path>src/workspace.js <ide> module.exports = class Workspace extends Model { <ide> return this.onDidChangeActivePaneItem(callback) <ide> } <ide> <add> // Essential: Invoke the given callback with the current active text editor <add> // (if any), with all future active text editors, and when there is no longer <add> // an active text editor. <add> // <add> // * `callback` {Function} to be called when the active text editor changes. <add> // * `editor` The active {TextEditor} or undefined if there is no longer an <add> // active text editor. <add> // <add> // Returns a {Disposable} on which `.dispose()` can be called to unsubscribe. <ide> observeActiveTextEditor (callback) { <ide> const activeTextEditor = this.getActiveTextEditor() <ide> if (activeTextEditor != null) { callback(activeTextEditor) }
1
PHP
PHP
remove old file
318e39278831a9d8f95b9d1ebfa3cc9cf8c7fd82
<ide><path>src/Illuminate/Foundation/Console/Optimize/config.php <ide> $basePath.'/vendor/laravel/framework/src/Illuminate/Foundation/Providers/FoundationServiceProvider.php', <ide> $basePath.'/vendor/laravel/framework/src/Illuminate/Foundation/Providers/EventServiceProvider.php', <ide> $basePath.'/vendor/laravel/framework/src/Illuminate/Foundation/Providers/FormRequestServiceProvider.php', <del> $basePath.'/vendor/laravel/framework/src/Illuminate/Routing/FilterServiceProvider.php', <ide> $basePath.'/vendor/laravel/framework/src/Illuminate/Routing/RouteServiceProvider.php', <ide> $basePath.'/vendor/laravel/framework/src/Illuminate/Auth/AuthServiceProvider.php', <ide> $basePath.'/vendor/laravel/framework/src/Illuminate/Support/Facades/Facade.php',
1
Ruby
Ruby
fix documentation for mattr_accessor methods
b864d887501d249b085db7ec686f4e266d301b8a
<ide><path>activesupport/lib/active_support/core_ext/module/attribute_accessors.rb <ide> class Module <ide> # include HairColors <ide> # end <ide> # <del> # Person.hair_colors # => [:brown, :black, :blonde, :red] <add> # Person.new.hair_colors # => [:brown, :black, :blonde, :red] <ide> def mattr_reader(*syms) <ide> options = syms.extract_options! <ide> syms.each do |sym| <ide> def #{sym} <ide> # <ide> # Also, you can pass a block to set up the attribute with a default value. <ide> # <del> # class HairColors <add> # module HairColors <ide> # mattr_writer :hair_colors do <ide> # [:brown, :black, :blonde, :red] <ide> # end <ide> def #{sym}=(obj) <ide> # include HairColors <ide> # end <ide> # <del> # Person.hair_colors = [:brown, :black, :blonde, :red] <del> # Person.hair_colors # => [:brown, :black, :blonde, :red] <add> # HairColors.hair_colors = [:brown, :black, :blonde, :red] <add> # HairColors.hair_colors # => [:brown, :black, :blonde, :red] <ide> # Person.new.hair_colors # => [:brown, :black, :blonde, :red] <ide> # <ide> # If a subclass changes the value then that would also change the value for <ide> def #{sym}=(obj) <ide> # class Male < Person <ide> # end <ide> # <del> # Male.hair_colors << :blue <del> # Person.hair_colors # => [:brown, :black, :blonde, :red, :blue] <add> # Male.new.hair_colors << :blue <add> # Person.new.hair_colors # => [:brown, :black, :blonde, :red, :blue] <ide> # <ide> # To opt out of the instance writer method, pass <tt>instance_writer: false</tt>. <ide> # To opt out of the instance reader method, pass <tt>instance_reader: false</tt>.
1
Text
Text
fix typo in dockervolumes.md
40dc0c4861df0e087ffe43c416176a58f574e641
<ide><path>docs/userguide/dockervolumes.md <ide> restore testing using your preferred tools. <ide> <ide> ## Important tips on using shared volumes <ide> <del>Multiple containers can also share one or more data volumes. However, multiple containers writing to a single shared volume can cause data corruption. Make sure you're applications are designed to write to shared data stores. <add>Multiple containers can also share one or more data volumes. However, multiple containers writing to a single shared volume can cause data corruption. Make sure your applications are designed to write to shared data stores. <ide> <ide> Data volumes are directly accessible from the Docker host. This means you can read and write to them with normal Linux tools. In most cases you should not do this as it can cause data corruption if your containers and applications are unaware of your direct access. <ide>
1
Javascript
Javascript
remove stupid suggestion in todo
7c1054cd099831c5806f2e330441664a8f403def
<ide><path>packages/ember-runtime/lib/computed/reduce_computed.js <ide> DependentArraysObserver.prototype = { <ide> Ember.run.once(this, 'flushChanges'); <ide> }, <ide> <del> // TODO: it probably makes more sense to remove the item during `willChange` <del> // and add it back (with the new value) during `didChange` <ide> flushChanges: function() { <ide> var changedItems = this.changedItems, key, c, changeMeta; <ide> for (key in changedItems) {
1
Ruby
Ruby
drop a conditional by always assigning
a1d7d65f0a21215851e45639ef7d0df35993ecaa
<ide><path>actionpack/lib/action_dispatch/middleware/params_parser.rb <ide> def initialize(app, parsers = {}) <ide> end <ide> <ide> def call(env) <del> if params = parse_formatted_parameters(env) <del> env["action_dispatch.request.request_parameters"] = params <del> end <add> default = env["action_dispatch.request.request_parameters"] <add> env["action_dispatch.request.request_parameters"] = parse_formatted_parameters(env, default) <ide> <ide> @app.call(env) <ide> end <ide> <ide> private <del> def parse_formatted_parameters(env) <add> def parse_formatted_parameters(env, default) <ide> request = Request.new(env) <ide> <del> return false if request.content_length.zero? <add> return default if request.content_length.zero? <ide> <del> strategy = @parsers.fetch(request.content_mime_type) { return false } <add> strategy = @parsers.fetch(request.content_mime_type) { return default } <ide> <ide> strategy.call(request.raw_post) <ide>
1
PHP
PHP
fix failing tests
b3eca7b79d41853812cff20bcbd3ccb00492f9d3
<ide><path>Test/TestCase/View/Helper/StringTemplateTraitTest.php <ide> public function testInitStringTemplates() { <ide> <ide> $result = $this->Template->templates(null); <ide> $this->assertEquals($result, [ <add> 'attribute' => '{{name}}="{{value}}"', <add> 'compactAttribute' => '{{name}}="{{value}}"', <ide> 'text' => '<p>{{text}}</p>' <ide> ]); <ide> }
1
Ruby
Ruby
use the right assetions to better error messages
af878151dbf93fae647ec682d96c0caaeb9a81f1
<ide><path>actionpack/test/controller/parameters/parameters_permit_test.rb <ide> def walk_permitted(params) <ide> test "to_h returns converted hash on permitted params" do <ide> @params.permit! <ide> <del> assert @params.to_h.is_a? ActiveSupport::HashWithIndifferentAccess <del> assert_not @params.to_h.is_a? ActionController::Parameters <add> assert_instance_of ActiveSupport::HashWithIndifferentAccess, @params.to_h <add> assert_not_kind_of ActionController::Parameters, @params.to_h <ide> end <ide> <ide> test "to_h returns converted hash when .permit_all_parameters is set" do <ide> begin <ide> ActionController::Parameters.permit_all_parameters = true <ide> params = ActionController::Parameters.new(crab: "Senjougahara Hitagi") <ide> <del> assert params.to_h.is_a? ActiveSupport::HashWithIndifferentAccess <del> assert_not params.to_h.is_a? ActionController::Parameters <add> assert_instance_of ActiveSupport::HashWithIndifferentAccess, params.to_h <add> assert_not_kind_of ActionController::Parameters, params.to_h <ide> assert_equal({ "crab" => "Senjougahara Hitagi" }, params.to_h) <ide> ensure <ide> ActionController::Parameters.permit_all_parameters = false <ide> def walk_permitted(params) <ide> end <ide> <ide> test "to_unsafe_h returns unfiltered params" do <del> assert @params.to_unsafe_h.is_a? ActiveSupport::HashWithIndifferentAccess <del> assert_not @params.to_unsafe_h.is_a? ActionController::Parameters <add> assert_instance_of ActiveSupport::HashWithIndifferentAccess, @params.to_unsafe_h <add> assert_not_kind_of ActionController::Parameters, @params.to_unsafe_h <ide> end <ide> <ide> test "to_unsafe_h returns unfiltered params even after accessing few keys" do <ide> params = ActionController::Parameters.new("f" => { "language_facet" => ["Tibetan"] }) <ide> expected = { "f" => { "language_facet" => ["Tibetan"] } } <ide> <del> assert params["f"].is_a? ActionController::Parameters <add> assert_instance_of ActionController::Parameters, params["f"] <ide> assert_equal expected, params.to_unsafe_h <ide> end <ide>
1
Ruby
Ruby
convert install test to spec
cd4705b7bca5f266907ea6424d721190617edbcd
<add><path>Library/Homebrew/cask/spec/cask/cli/install_spec.rb <del><path>Library/Homebrew/cask/test/cask/cli/install_test.rb <del>require "test_helper" <add>require "spec_helper" <ide> <ide> describe Hbc::CLI::Install do <ide> it "allows staging and activation of multiple Casks at once" do <ide> shutup do <ide> Hbc::CLI::Install.run("local-transmission", "local-caffeine") <ide> end <ide> <del> Hbc::CaskLoader.load_from_file(TEST_FIXTURE_DIR/"cask/Casks/local-transmission.rb").must_be :installed? <del> Hbc.appdir.join("Transmission.app").must_be :directory? <del> Hbc::CaskLoader.load_from_file(TEST_FIXTURE_DIR/"cask/Casks/local-caffeine.rb").must_be :installed? <del> Hbc.appdir.join("Caffeine.app").must_be :directory? <add> expect(Hbc::CaskLoader.load_from_file(TEST_FIXTURE_DIR/"cask/Casks/local-transmission.rb")).to be_installed <add> expect(Hbc.appdir.join("Transmission.app")).to be_a_directory <add> expect(Hbc::CaskLoader.load_from_file(TEST_FIXTURE_DIR/"cask/Casks/local-caffeine.rb")).to be_installed <add> expect(Hbc.appdir.join("Caffeine.app")).to be_a_directory <ide> end <ide> <ide> it "skips double install (without nuking existing installation)" do <ide> shutup do <ide> Hbc::CLI::Install.run("local-transmission") <ide> end <del> Hbc::CaskLoader.load_from_file(TEST_FIXTURE_DIR/"cask/Casks/local-transmission.rb").must_be :installed? <add> expect(Hbc::CaskLoader.load_from_file(TEST_FIXTURE_DIR/"cask/Casks/local-transmission.rb")).to be_installed <ide> end <ide> <ide> it "prints a warning message on double install" do <ide> shutup do <ide> Hbc::CLI::Install.run("local-transmission") <ide> end <ide> <del> lambda { <add> expect { <ide> Hbc::CLI::Install.run("local-transmission", "") <del> }.must_output nil, /Warning: A Cask for local-transmission is already installed./ <add> }.to output(/Warning: A Cask for local-transmission is already installed./).to_stderr <ide> end <ide> <ide> it "allows double install with --force" do <ide> shutup do <ide> Hbc::CLI::Install.run("local-transmission") <ide> end <ide> <del> lambda { <del> Hbc::CLI::Install.run("local-transmission", "--force") <del> }.must_output(/local-transmission was successfully installed!/) <add> expect { <add> expect { <add> Hbc::CLI::Install.run("local-transmission", "--force") <add> }.to output(/It seems there is already an App at.*overwriting\./).to_stderr <add> }.to output(/local-transmission was successfully installed!/).to_stdout <ide> end <ide> <ide> it "skips dependencies with --skip-cask-deps" do <ide> shutup do <ide> Hbc::CLI::Install.run("with-depends-on-cask-multiple", "--skip-cask-deps") <ide> end <del> Hbc::CaskLoader.load_from_file(TEST_FIXTURE_DIR/"cask/Casks/with-depends-on-cask-multiple.rb").must_be :installed? <del> Hbc::CaskLoader.load_from_file(TEST_FIXTURE_DIR/"cask/Casks/local-caffeine.rb").wont_be :installed? <del> Hbc::CaskLoader.load_from_file(TEST_FIXTURE_DIR/"cask/Casks/local-transmission.rb").wont_be :installed? <add> expect(Hbc::CaskLoader.load_from_file(TEST_FIXTURE_DIR/"cask/Casks/with-depends-on-cask-multiple.rb")).to be_installed <add> expect(Hbc::CaskLoader.load_from_file(TEST_FIXTURE_DIR/"cask/Casks/local-caffeine.rb")).not_to be_installed <add> expect(Hbc::CaskLoader.load_from_file(TEST_FIXTURE_DIR/"cask/Casks/local-transmission.rb")).not_to be_installed <ide> end <ide> <ide> it "properly handles Casks that are not present" do <del> lambda { <add> expect { <ide> shutup do <ide> Hbc::CLI::Install.run("notacask") <ide> end <del> }.must_raise Hbc::CaskError <add> }.to raise_error(Hbc::CaskError) <ide> end <ide> <ide> it "returns a suggestion for a misspelled Cask" do <del> lambda { <add> expect { <ide> begin <ide> Hbc::CLI::Install.run("googlechrome") <ide> rescue Hbc::CaskError <ide> nil <ide> end <del> }.must_output(nil, /No available Cask for googlechrome\. Did you mean:\ngoogle-chrome/) <add> }.to output(/No available Cask for googlechrome\. Did you mean:\ngoogle-chrome/).to_stderr <ide> end <ide> <ide> it "returns multiple suggestions for a Cask fragment" do <del> lambda { <add> expect { <ide> begin <ide> Hbc::CLI::Install.run("google") <ide> rescue Hbc::CaskError <ide> nil <ide> end <del> }.must_output(nil, /No available Cask for google\. Did you mean one of:\ngoogle/) <add> }.to output(/No available Cask for google\. Did you mean one of:\ngoogle/).to_stderr <ide> end <ide> <ide> describe "when no Cask is specified" do <ide> with_options = lambda do |options| <ide> it "raises an exception" do <del> lambda { <add> expect { <ide> Hbc::CLI::Install.run(*options) <del> }.must_raise Hbc::CaskUnspecifiedError <add> }.to raise_error(Hbc::CaskUnspecifiedError) <ide> end <ide> end <ide> <ide><path>Library/Homebrew/cask/spec/spec_helper.rb <ide> FileUtils.ln_s TEST_FIXTURE_DIR.join("cask"), tap.path <ide> end <ide> <add># pretend that the caskroom/cask Tap is installed <add>FileUtils.ln_s Pathname.new(ENV["HOMEBREW_LIBRARY"]).join("Taps", "caskroom", "homebrew-cask"), Tap.fetch("caskroom", "cask").path <add> <ide> RSpec.configure do |config| <ide> config.order = :random <ide> config.include(Test::Helper::Shutup)
2
Ruby
Ruby
remove more skip
78bac468e6ac0c97ff81c15fe81c5a5a99c1c177
<ide><path>activerecord/test/cases/migration/index_test.rb <ide> def test_add_index <ide> end <ide> end <ide> <del> def test_add_partial_index <del> skip 'only on pg' unless current_adapter?(:PostgreSQLAdapter) <add> if current_adapter?(:PostgreSQLAdapter) <add> def test_add_partial_index <add> connection.add_index("testings", "last_name", :where => "first_name = 'john doe'") <add> assert connection.index_exists?("testings", "last_name") <ide> <del> connection.add_index("testings", "last_name", :where => "first_name = 'john doe'") <del> assert connection.index_exists?("testings", "last_name") <del> <del> connection.remove_index("testings", "last_name") <del> assert !connection.index_exists?("testings", "last_name") <add> connection.remove_index("testings", "last_name") <add> assert !connection.index_exists?("testings", "last_name") <add> end <ide> end <ide> <ide> private <ide><path>activerecord/test/cases/migration/rename_table_test.rb <ide> def test_rename_table_does_not_rename_custom_named_index <ide> <ide> if current_adapter?(:PostgreSQLAdapter) <ide> def test_rename_table_for_postgresql_should_also_rename_default_sequence <del> skip 'not supported' <del> <ide> rename_table :test_models, :octopi <ide> <ide> pk, seq = connection.pk_and_sequence_for('octopi') <ide><path>activerecord/test/cases/migration_test.rb <ide> def test_create_table_with_binary_column <ide> <ide> if current_adapter? :OracleAdapter <ide> def test_create_table_with_custom_sequence_name <del> skip "not supported" <del> <ide> # table name is 29 chars, the standard sequence name will <ide> # be 33 chars and should be shortened <ide> assert_nothing_raised do <ide><path>activerecord/test/cases/primary_keys_test.rb <ide> class PrimaryKeyWithNoConnectionTest < ActiveRecord::TestCase <ide> <ide> unless in_memory_db? <ide> def test_set_primary_key_with_no_connection <del> return skip("disconnect wipes in-memory db") <del> <ide> connection = ActiveRecord::Base.remove_connection <ide> <ide> model = Class.new(ActiveRecord::Base)
4
PHP
PHP
apply fixes from styleci
4f7b2760aefea06d4860af6ee2b0d52b2e93b78b
<ide><path>src/Illuminate/Foundation/Testing/TestResponse.php <ide> public function assertOk() <ide> { <ide> PHPUnit::assertTrue( <ide> $this->isOk(), <del> 'Response status code [' . $this->getStatusCode() . '] does match expected 200 status code.' <add> 'Response status code ['.$this->getStatusCode().'] does match expected 200 status code.' <ide> ); <ide> <ide> return $this;
1
Javascript
Javascript
increase highwatermark on large reads
8c44869f1dc2cdc7337d5a2a4f64e10494b0fb2f
<ide><path>lib/_stream_readable.js <ide> function howMuchToRead(n, state) { <ide> if (n <= 0) <ide> return 0; <ide> <add> // If we're asking for more than the target buffer level, <add> // then raise the water mark. <add> if (n > state.highWaterMark) <add> state.highWaterMark = n; <add> <ide> // don't have that much. return null, unless we've ended. <ide> if (n > state.length) { <ide> if (!state.ended) { <ide><path>test/simple/test-stream-readable-flow-recursion.js <add>// Copyright Joyent, Inc. and other Node contributors. <add>// <add>// Permission is hereby granted, free of charge, to any person obtaining a <add>// copy of this software and associated documentation files (the <add>// "Software"), to deal in the Software without restriction, including <add>// without limitation the rights to use, copy, modify, merge, publish, <add>// distribute, sublicense, and/or sell copies of the Software, and to permit <add>// persons to whom the Software is furnished to do so, subject to the <add>// following conditions: <add>// <add>// The above copyright notice and this permission notice shall be included <add>// in all copies or substantial portions of the Software. <add>// <add>// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS <add>// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF <add>// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN <add>// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, <add>// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR <add>// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE <add>// USE OR OTHER DEALINGS IN THE SOFTWARE. <add> <add>var common = require('../common'); <add>var assert = require('assert'); <add> <add>// this test verifies that passing a huge number to read(size) <add>// will push up the highWaterMark, and cause the stream to read <add>// more data continuously, but without triggering a nextTick <add>// warning or RangeError. <add> <add>var Readable = require('stream').Readable; <add> <add>// throw an error if we trigger a nextTick warning. <add>process.throwDeprecation = true; <add> <add>var stream = new Readable({ highWaterMark: 2, bufferSize: 2 }); <add>var reads = 0; <add>stream._read = function(size) { <add> reads++; <add> stream.push(new Buffer(size)); <add>}; <add> <add>var depth = 0; <add> <add>function flow(stream, size, callback) { <add> depth += 1; <add> var chunk = stream.read(size); <add> <add> if (!chunk) <add> stream.once('readable', flow.bind(null, stream, size, callback)); <add> else <add> callback(chunk); <add> <add> depth -= 1; <add> console.log('flow(' + depth + '): exit'); <add>} <add> <add>flow(stream, 5000, function() { <add> console.log('complete (' + depth + ')'); <add>}); <add> <add>process.on('exit', function(code) { <add> assert.equal(reads, 5000); <add> // we pushed up the high water mark <add> assert.equal(stream._readableState.highWaterMark, 5000); <add> assert.equal(stream._readableState.length, 5000); <add> assert(!code); <add> assert.equal(depth, 0); <add> console.log('ok'); <add>});
2
Javascript
Javascript
add support for checkboxes printing
cb60523a15231d6bab9eecdc559c98fa13dc2b88
<ide><path>src/core/annotation.js <ide> class AnnotationFactory { <ide> * instance. <ide> */ <ide> static create(xref, ref, pdfManager, idFactory) { <del> return pdfManager.ensure(this, "_create", [ <del> xref, <del> ref, <del> pdfManager, <del> idFactory, <del> ]); <add> return pdfManager.ensureDoc("acroForm").then(acroForm => { <add> return pdfManager.ensure(this, "_create", [ <add> xref, <add> ref, <add> pdfManager, <add> idFactory, <add> acroForm, <add> ]); <add> }); <ide> } <ide> <ide> /** <ide> * @private <ide> */ <del> static _create(xref, ref, pdfManager, idFactory) { <add> static _create(xref, ref, pdfManager, idFactory, acroForm) { <ide> const dict = xref.fetchIfRef(ref); <ide> if (!isDict(dict)) { <ide> return undefined; <ide> class AnnotationFactory { <ide> subtype, <ide> id, <ide> pdfManager, <add> acroForm: acroForm instanceof Dict ? acroForm : Dict.empty, <ide> }; <ide> <ide> switch (subtype) { <ide> class Annotation { <ide> return Promise.resolve(new OperatorList()); <ide> } <ide> <add> const appearance = this.appearance; <ide> const data = this.data; <del> const appearanceDict = this.appearance.dict; <add> const appearanceDict = appearance.dict; <ide> const resourcesPromise = this.loadResources([ <ide> "ExtGState", <ide> "ColorSpace", <ide> class Annotation { <ide> opList.addOp(OPS.beginAnnotation, [data.rect, transform, matrix]); <ide> return evaluator <ide> .getOperatorList({ <del> stream: this.appearance, <add> stream: appearance, <ide> task, <ide> resources, <ide> operatorList: opList, <ide> }) <ide> .then(() => { <ide> opList.addOp(OPS.endAnnotation, []); <del> this.appearance.reset(); <add> appearance.reset(); <ide> return opList; <ide> }); <ide> }); <ide> class WidgetAnnotation extends Annotation { <ide> getArray: true, <ide> }); <ide> data.alternativeText = stringToPDFString(dict.get("TU") || ""); <del> data.defaultAppearance = getInheritableProperty({ dict, key: "DA" }) || ""; <add> data.defaultAppearance = <add> getInheritableProperty({ dict, key: "DA" }) || <add> params.acroForm.get("DA") || <add> ""; <ide> const fieldType = getInheritableProperty({ dict, key: "FT" }); <ide> data.fieldType = isName(fieldType) ? fieldType.name : null; <ide> this.fieldResources = <del> getInheritableProperty({ dict, key: "DR" }) || Dict.empty; <add> getInheritableProperty({ dict, key: "DR" }) || <add> params.acroForm.get("DR") || <add> Dict.empty; <ide> <ide> data.fieldFlags = getInheritableProperty({ dict, key: "Ff" }); <ide> if (!Number.isInteger(data.fieldFlags) || data.fieldFlags < 0) { <ide> class ButtonWidgetAnnotation extends WidgetAnnotation { <ide> constructor(params) { <ide> super(params); <ide> <add> this.checkedAppearance = null; <add> this.uncheckedAppearance = null; <add> <ide> this.data.checkBox = <ide> !this.hasFieldFlag(AnnotationFieldFlag.RADIO) && <ide> !this.hasFieldFlag(AnnotationFieldFlag.PUSHBUTTON); <ide> class ButtonWidgetAnnotation extends WidgetAnnotation { <ide> } <ide> } <ide> <add> getOperatorList(evaluator, task, renderForms, annotationStorage) { <add> if (annotationStorage) { <add> const value = annotationStorage[this.data.id] || false; <add> let appearance; <add> if (value) { <add> appearance = this.checkedAppearance; <add> } else { <add> appearance = this.uncheckedAppearance; <add> } <add> <add> if (appearance) { <add> const savedAppearance = this.appearance; <add> this.appearance = appearance; <add> const operatorList = super.getOperatorList( <add> evaluator, <add> task, <add> renderForms, <add> annotationStorage <add> ); <add> this.appearance = savedAppearance; <add> return operatorList; <add> } <add> <add> // No appearance <add> return Promise.resolve(new OperatorList()); <add> } <add> return super.getOperatorList( <add> evaluator, <add> task, <add> renderForms, <add> annotationStorage <add> ); <add> } <add> <ide> _processCheckBox(params) { <ide> if (isName(this.data.fieldValue)) { <ide> this.data.fieldValue = this.data.fieldValue.name; <ide> class ButtonWidgetAnnotation extends WidgetAnnotation { <ide> <ide> this.data.exportValue = <ide> exportValues[0] === "Off" ? exportValues[1] : exportValues[0]; <add> <add> const normalAppearance = customAppearance.get("N"); <add> if (!isDict(normalAppearance)) { <add> return; <add> } <add> <add> this.checkedAppearance = normalAppearance.get(this.data.exportValue); <add> this.uncheckedAppearance = normalAppearance.get("Off") || null; <ide> } <ide> <ide> _processRadioButton(params) { <ide><path>src/display/annotation_layer.js <ide> class CheckboxWidgetAnnotationElement extends WidgetAnnotationElement { <ide> * @returns {HTMLSectionElement} <ide> */ <ide> render() { <add> const storage = this.annotationStorage; <add> const data = this.data; <add> const id = data.id; <add> const value = storage.getOrCreateValue( <add> id, <add> data.fieldValue && data.fieldValue !== "Off" <add> ); <add> <ide> this.container.className = "buttonWidgetAnnotation checkBox"; <ide> <ide> const element = document.createElement("input"); <del> element.disabled = this.data.readOnly; <add> element.disabled = data.readOnly; <ide> element.type = "checkbox"; <ide> element.name = this.data.fieldName; <del> if (this.data.fieldValue && this.data.fieldValue !== "Off") { <add> if (value) { <ide> element.setAttribute("checked", true); <ide> } <ide> <add> element.addEventListener("change", function (event) { <add> storage.setValue(id, event.target.checked); <add> }); <add> <ide> this.container.appendChild(element); <ide> return this.container; <ide> } <ide><path>test/unit/annotation_spec.js <ide> import { <ide> AnnotationFieldFlag, <ide> AnnotationFlag, <ide> AnnotationType, <add> OPS, <ide> stringToBytes, <ide> stringToUTF8String, <ide> } from "../../src/shared/util.js"; <ide> import { createIdFactory, XRefMock } from "./test_utils.js"; <ide> import { Dict, Name, Ref } from "../../src/core/primitives.js"; <ide> import { Lexer, Parser } from "../../src/core/parser.js"; <add>import { PartialEvaluator } from "../../src/core/evaluator.js"; <ide> import { StringStream } from "../../src/core/stream.js"; <add>import { WorkerTask } from "../../src/core/worker.js"; <ide> <ide> describe("annotation", function () { <ide> class PDFManagerMock { <ide> constructor(params) { <ide> this.docBaseUrl = params.docBaseUrl || null; <add> this.pdfDocument = { <add> acroForm: new Dict(), <add> }; <ide> } <ide> <ide> ensure(obj, prop, args) { <ide> describe("annotation", function () { <ide> } <ide> }); <ide> } <add> <add> ensureDoc(prop, args) { <add> return this.ensure(this.pdfDocument, prop, args); <add> } <add> } <add> <add> function HandlerMock() { <add> this.inputs = []; <ide> } <add> HandlerMock.prototype = { <add> send(name, data) { <add> this.inputs.push({ name, data }); <add> }, <add> }; <ide> <del> let pdfManagerMock, idFactoryMock; <add> let pdfManagerMock, idFactoryMock, partialEvaluator; <ide> <ide> beforeAll(function (done) { <ide> pdfManagerMock = new PDFManagerMock({ <ide> docBaseUrl: null, <ide> }); <ide> idFactoryMock = createIdFactory(/* pageIndex = */ 0); <add> partialEvaluator = new PartialEvaluator({ <add> xref: new XRefMock(), <add> handler: new HandlerMock(), <add> pageIndex: 0, <add> idFactory: createIdFactory(/* pageIndex = */ 0), <add> }); <ide> done(); <ide> }); <ide> <ide> afterAll(function () { <ide> pdfManagerMock = null; <ide> idFactoryMock = null; <add> partialEvaluator = null; <ide> }); <ide> <ide> describe("AnnotationFactory", function () { <ide> describe("annotation", function () { <ide> }, done.fail); <ide> }); <ide> <add> it("should render checkboxes for printing", function (done) { <add> const appearanceStatesDict = new Dict(); <add> const exportValueOptionsDict = new Dict(); <add> const normalAppearanceDict = new Dict(); <add> const checkedAppearanceDict = new Dict(); <add> <add> const stream = new StringStream("0.1 0.2 0.3 rg"); <add> stream.dict = checkedAppearanceDict; <add> <add> checkedAppearanceDict.set("BBox", [0, 0, 8, 8]); <add> checkedAppearanceDict.set("FormType", 1); <add> checkedAppearanceDict.set("Matrix", [1, 0, 0, 1, 0, 0]); <add> normalAppearanceDict.set("Checked", stream); <add> exportValueOptionsDict.set("Off", 0); <add> exportValueOptionsDict.set("Checked", 1); <add> appearanceStatesDict.set("D", exportValueOptionsDict); <add> appearanceStatesDict.set("N", normalAppearanceDict); <add> <add> buttonWidgetDict.set("AP", appearanceStatesDict); <add> <add> const buttonWidgetRef = Ref.get(124, 0); <add> const xref = new XRefMock([ <add> { ref: buttonWidgetRef, data: buttonWidgetDict }, <add> ]); <add> const task = new WorkerTask("test print"); <add> <add> AnnotationFactory.create( <add> xref, <add> buttonWidgetRef, <add> pdfManagerMock, <add> idFactoryMock <add> ) <add> .then(annotation => { <add> const annotationStorage = {}; <add> annotationStorage[annotation.data.id] = true; <add> return annotation.getOperatorList( <add> partialEvaluator, <add> task, <add> false, <add> annotationStorage <add> ); <add> }, done.fail) <add> .then(opList => { <add> expect(opList.argsArray.length).toEqual(3); <add> expect(opList.fnArray).toEqual([ <add> OPS.beginAnnotation, <add> OPS.setFillRGBColor, <add> OPS.endAnnotation, <add> ]); <add> expect(opList.argsArray[1]).toEqual( <add> new Uint8ClampedArray([26, 51, 76]) <add> ); <add> done(); <add> }, done.fail); <add> }); <add> <ide> it("should handle radio buttons without a field value", function (done) { <ide> const normalAppearanceStateDict = new Dict(); <ide> normalAppearanceStateDict.set("2", null);
3
Mixed
Go
remove execution driver
1fb1136fecfd761300a38f64ac9178979cc0b270
<ide><path>api/client/system/info.go <ide> func runInfo(dockerCli *client.DockerCli) error { <ide> fmt.Fprintf(dockerCli.Out(), "%s: %s\n", pair[0], pair[1]) <ide> } <ide> } <del> ioutils.FprintfIfNotEmpty(dockerCli.Out(), "Execution Driver: %s\n", info.ExecutionDriver) <ide> ioutils.FprintfIfNotEmpty(dockerCli.Out(), "Logging Driver: %s\n", info.LoggingDriver) <ide> ioutils.FprintfIfNotEmpty(dockerCli.Out(), "Cgroup Driver: %s\n", info.CgroupDriver) <ide> <ide><path>docs/reference/api/docker_remote_api_v1.25.md <ide> Display system-wide information <ide> "DockerRootDir": "/var/lib/docker", <ide> "Driver": "btrfs", <ide> "DriverStatus": [[""]], <del> "ExecutionDriver": "native-0.1", <ide> "ExperimentalBuild": false, <ide> "HttpProxy": "http://test:test@localhost:8080", <ide> "HttpsProxy": "https://test:test@localhost:8080", <ide><path>integration-cli/docker_api_info_test.go <ide> func (s *DockerSuite) TestInfoApi(c *check.C) { <ide> "ContainersPaused", <ide> "ContainersStopped", <ide> "Images", <del> "ExecutionDriver", <ide> "LoggingDriver", <ide> "OperatingSystem", <ide> "NCPU",
3
Python
Python
fix typo in docs
6e1b72096d5ae1e2cc4d8592ff8271b62548d9cf
<ide><path>src/flask/app.py <ide> def handle_http_exception( <ide> <ide> .. versionchanged:: 1.0 <ide> Exceptions are looked up by code *and* by MRO, so <del> ``HTTPExcpetion`` subclasses can be handled with a catch-all <add> ``HTTPException`` subclasses can be handled with a catch-all <ide> handler for the base ``HTTPException``. <ide> <ide> .. versionadded:: 0.3
1
Python
Python
convert resnet model to use monitored_session
931c70a1b8c53d3a93dcec3772ac4c27e18ae3e7
<ide><path>resnet/cifar_input.py <ide> def build_input(dataset, data_path, batch_size, mode): <ide> # image = tf.image.random_brightness(image, max_delta=63. / 255.) <ide> # image = tf.image.random_saturation(image, lower=0.5, upper=1.5) <ide> # image = tf.image.random_contrast(image, lower=0.2, upper=1.8) <del> image = tf.image.per_image_whitening(image) <add> image = tf.image.per_image_standardization(image) <ide> <ide> example_queue = tf.RandomShuffleQueue( <ide> capacity=16 * batch_size, <ide><path>resnet/resnet_main.py <ide> <ide> """ResNet Train/Eval module. <ide> """ <del>import sys <ide> import time <add>import sys <ide> <ide> import cifar_input <ide> import numpy as np <ide> FLAGS = tf.app.flags.FLAGS <ide> tf.app.flags.DEFINE_string('dataset', 'cifar10', 'cifar10 or cifar100.') <ide> tf.app.flags.DEFINE_string('mode', 'train', 'train or eval.') <del>tf.app.flags.DEFINE_string('train_data_path', '', 'Filepattern for training data.') <del>tf.app.flags.DEFINE_string('eval_data_path', '', 'Filepattern for eval data') <add>tf.app.flags.DEFINE_string('train_data_path', '', <add> 'Filepattern for training data.') <add>tf.app.flags.DEFINE_string('eval_data_path', '', <add> 'Filepattern for eval data') <ide> tf.app.flags.DEFINE_integer('image_size', 32, 'Image side length.') <ide> tf.app.flags.DEFINE_string('train_dir', '', <ide> 'Directory to keep training outputs.') <ide> def train(hps): <ide> FLAGS.dataset, FLAGS.train_data_path, hps.batch_size, FLAGS.mode) <ide> model = resnet_model.ResNet(hps, images, labels, FLAGS.mode) <ide> model.build_graph() <del> summary_writer = tf.train.SummaryWriter(FLAGS.train_dir) <del> <del> sv = tf.train.Supervisor(logdir=FLAGS.log_root, <del> is_chief=True, <del> summary_op=None, <del> save_summaries_secs=60, <del> save_model_secs=300, <del> global_step=model.global_step) <del> sess = sv.prepare_or_wait_for_session( <del> config=tf.ConfigProto(allow_soft_placement=True)) <del> <del> step = 0 <del> lrn_rate = 0.1 <del> <del> while not sv.should_stop(): <del> (_, summaries, loss, predictions, truth, train_step) = sess.run( <del> [model.train_op, model.summaries, model.cost, model.predictions, <del> model.labels, model.global_step], <del> feed_dict={model.lrn_rate: lrn_rate}) <del> <del> if train_step < 40000: <del> lrn_rate = 0.1 <del> elif train_step < 60000: <del> lrn_rate = 0.01 <del> elif train_step < 80000: <del> lrn_rate = 0.001 <del> else: <del> lrn_rate = 0.0001 <del> <del> truth = np.argmax(truth, axis=1) <del> predictions = np.argmax(predictions, axis=1) <del> precision = np.mean(truth == predictions) <del> <del> step += 1 <del> if step % 100 == 0: <del> precision_summ = tf.Summary() <del> precision_summ.value.add( <del> tag='Precision', simple_value=precision) <del> summary_writer.add_summary(precision_summ, train_step) <del> summary_writer.add_summary(summaries, train_step) <del> tf.logging.info('loss: %.3f, precision: %.3f\n' % (loss, precision)) <del> summary_writer.flush() <del> <del> sv.Stop() <add> <add> param_stats = tf.contrib.tfprof.model_analyzer.print_model_analysis( <add> tf.get_default_graph(), <add> tfprof_options=tf.contrib.tfprof.model_analyzer. <add> TRAINABLE_VARS_PARAMS_STAT_OPTIONS) <add> sys.stdout.write('total_params: %d\n' % param_stats.total_parameters) <add> <add> tf.contrib.tfprof.model_analyzer.print_model_analysis( <add> tf.get_default_graph(), <add> tfprof_options=tf.contrib.tfprof.model_analyzer.FLOAT_OPS_OPTIONS) <add> <add> truth = tf.argmax(model.labels, axis=1) <add> predictions = tf.argmax(model.predictions, axis=1) <add> precision = tf.reduce_mean(tf.to_float(tf.equal(predictions, truth))) <add> <add> summary_hook = tf.train.SummarySaverHook( <add> save_steps=100, <add> output_dir=FLAGS.train_dir, <add> summary_op=[model.summaries, <add> tf.summary.scalar('Precision', precision)]) <add> <add> logging_hook = tf.train.LoggingTensorHook( <add> tensors={'step': model.global_step, <add> 'loss': model.cost, <add> 'precision': precision}, <add> every_n_iter=100) <add> <add> class _LearningRateSetterHook(tf.train.SessionRunHook): <add> """Sets learning_rate based on global step.""" <add> <add> def begin(self): <add> self._lrn_rate = 0.1 <add> <add> def before_run(self, run_context): <add> return tf.train.SessionRunArgs( <add> model.global_step, # Asks for global step value. <add> feed_dict={model.lrn_rate: self._lrn_rate}) # Sets learning rate <add> <add> def after_run(self, run_context, run_values): <add> train_step = run_values.results <add> if train_step < 40000: <add> self._lrn_rate = 0.1 <add> elif train_step < 60000: <add> self._lrn_rate = 0.01 <add> elif train_step < 80000: <add> self._lrn_rate = 0.001 <add> else: <add> self._lrn_rate = 0.0001 <add> <add> with tf.train.MonitoredTrainingSession( <add> checkpoint_dir=FLAGS.log_root, <add> hooks=[logging_hook, _LearningRateSetterHook()], <add> chief_only_hooks=[summary_hook], <add> # Since we provide a SummarySaverHook, we need to disable default <add> # SummarySaverHook. To do that we set save_summaries_steps to 0. <add> save_summaries_steps=0, <add> config=tf.ConfigProto(allow_soft_placement=True)) as mon_sess: <add> while not mon_sess.should_stop(): <add> mon_sess.run(model.train_op) <ide> <ide> <ide> def evaluate(hps): <ide> def evaluate(hps): <ide> model = resnet_model.ResNet(hps, images, labels, FLAGS.mode) <ide> model.build_graph() <ide> saver = tf.train.Saver() <del> summary_writer = tf.train.SummaryWriter(FLAGS.eval_dir) <add> summary_writer = tf.summary.FileWriter(FLAGS.eval_dir) <ide> <ide> sess = tf.Session(config=tf.ConfigProto(allow_soft_placement=True)) <ide> tf.train.start_queue_runners(sess) <ide><path>resnet/resnet_model.py <ide> def __init__(self, hps, images, labels, mode): <ide> <ide> def build_graph(self): <ide> """Build a whole graph for the model.""" <del> self.global_step = tf.Variable(0, name='global_step', trainable=False) <add> self.global_step = tf.contrib.framework.get_or_create_global_step() <ide> self._build_model() <ide> if self.mode == 'train': <ide> self._build_train_op()
3
Mixed
Javascript
add theme to styled-components example
8cdd539f98ee30ada96ecc6b60c46417d69ea1bc
<ide><path>examples/with-styled-components/README.md <ide> now <ide> <ide> This example features how you use a different styling solution than [styled-jsx](https://github.com/zeit/styled-jsx) that also supports universal styles. That means we can serve the required styles for the first render within the HTML and then load the rest in the client. In this case we are using [styled-components](https://github.com/styled-components/styled-components). <ide> <del>For this purpose we are extending the `<Document />` and injecting the server side rendered styles into the `<head>`, and also adding the `babel-plugin-styled-components`. (which is required for server side rendering) <add>For this purpose we are extending the `<Document />` and injecting the server side rendered styles into the `<head>`, and also adding the `babel-plugin-styled-components` (which is required for server side rendering). Additionally we set up a global [theme](https://www.styled-components.com/docs/advanced#theming) for styled-components using NextJS custom [`<App>`](https://nextjs.org/docs#custom-app) component. <ide><path>examples/with-styled-components/pages/_app.js <add>import App, { Container } from 'next/app' <add>import React from 'react' <add>import { ThemeProvider } from 'styled-components' <add> <add>const theme = { <add> colors: { <add> primary: '#0070f3' <add> } <add>} <add> <add>export default class MyApp extends App { <add> static async getInitialProps ({ Component, ctx }) { <add> let pageProps = {} <add> <add> if (Component.getInitialProps) { <add> pageProps = await Component.getInitialProps(ctx) <add> } <add> <add> return { pageProps } <add> } <add> <add> render () { <add> const { Component, pageProps } = this.props <add> return ( <add> <Container> <add> <ThemeProvider theme={theme}> <add> <Component {...pageProps} /> <add> </ThemeProvider> <add> </Container> <add> ) <add> } <add>} <ide><path>examples/with-styled-components/pages/index.js <ide> import React from 'react' <ide> import styled from 'styled-components' <ide> <ide> const Title = styled.h1` <del> color: red; <ide> font-size: 50px; <add> color: ${({ theme }) => theme.colors.primary}; <ide> ` <ide> <ide> export default () => <Title>My page</Title>
3
Text
Text
remove references to textcat spans
792aa7b6ab48ad40254102e5730c420e36822a70
<ide><path>website/docs/api/doc.md <ide> The L2 norm of the document's vector representation. <ide> | `mem` | `Pool` | The document's local memory heap, for all C data it owns. | <ide> | `vocab` | `Vocab` | The store of lexical types. | <ide> | `tensor` <Tag variant="new">2</Tag> | `ndarray` | Container for dense vector representations. | <del>| `cats` <Tag variant="new">2</Tag> | dictionary | Maps either a label to a score for categories applied to whole document, or `(start_char, end_char, label)` to score for categories applied to spans. `start_char` and `end_char` should be character offsets, label can be either a string or an integer ID, and score should be a float. | <add>| `cats` <Tag variant="new">2</Tag> | dict | Maps a label to a score for categories applied to the document. The label is a string and the score should be a float. | <ide> | `user_data` | - | A generic storage area, for user custom data. | <ide> | `lang` <Tag variant="new">2.1</Tag> | int | Language of the document's vocabulary. | <ide> | `lang_` <Tag variant="new">2.1</Tag> | unicode | Language of the document's vocabulary. | <ide><path>website/docs/api/goldparse.md <ide> source: spacy/gold.pyx <ide> <ide> ## GoldParse.\_\_init\_\_ {#init tag="method"} <ide> <del>Create a `GoldParse`. Unlike annotations in `entities`, label annotations in <del>`cats` can overlap, i.e. a single word can be covered by multiple labelled <del>spans. The [`TextCategorizer`](/api/textcategorizer) component expects true <del>examples of a label to have the value `1.0`, and negative examples of a label to <del>have the value `0.0`. Labels not in the dictionary are treated as missing – the <del>gradient for those labels will be zero. <add>Create a `GoldParse`. The [`TextCategorizer`](/api/textcategorizer) component <add>expects true examples of a label to have the value `1.0`, and negative examples <add>of a label to have the value `0.0`. Labels not in the dictionary are treated as <add>missing – the gradient for those labels will be zero. <ide> <ide> | Name | Type | Description | <ide> | ----------- | ----------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | <ide> gradient for those labels will be zero. <ide> | `heads` | iterable | A sequence of integers, representing syntactic head offsets. | <ide> | `deps` | iterable | A sequence of strings, representing the syntactic relation types. | <ide> | `entities` | iterable | A sequence of named entity annotations, either as BILUO tag strings, or as `(start_char, end_char, label)` tuples, representing the entity positions. If BILUO tag strings, you can specify missing values by setting the tag to None. | <del>| `cats` | dict | Labels for text classification. Each key in the dictionary may be a string or an int, or a `(start_char, end_char, label)` tuple, indicating that the label is applied to only part of the document (usually a sentence). | <del>| `links` | dict | Labels for entity linking. A dict with `(start_char, end_char)` keys, and the values being dicts with `kb_id:value` entries, representing external KB IDs mapped to either 1.0 (positive) or 0.0 (negative). | <add>| `cats` | dict | Labels for text classification. Each key in the dictionary is a string label for the category and each value is `1.0` (positive) or `0.0` (negative). | <add>| `links` | dict | Labels for entity linking. A dict with `(start_char, end_char)` keys, and the values being dicts with `kb_id:value` entries, representing external KB IDs mapped to either `1.0` (positive) or `0.0` (negative). | <ide> | **RETURNS** | `GoldParse` | The newly constructed object. | <ide> <ide> ## GoldParse.\_\_len\_\_ {#len tag="method"} <ide> Whether the provided syntactic annotations form a projective dependency tree. <ide> | `ner` | list | The named entity annotations as BILUO tags. | <ide> | `cand_to_gold` | list | The alignment from candidate tokenization to gold tokenization. | <ide> | `gold_to_cand` | list | The alignment from gold tokenization to candidate tokenization. | <del>| `cats` <Tag variant="new">2</Tag> | list | Entries in the list should be either a label, or a `(start, end, label)` triple. The tuple form is used for categories applied to spans of the document. | <add>| `cats` <Tag variant="new">2</Tag> | dict | Keys in the dictionary are string category labels with values `1.0` or `0.0`. | <ide> | `links` <Tag variant="new">2.2</Tag> | dict | Keys in the dictionary are `(start_char, end_char)` triples, and the values are dictionaries with `kb_id:value` entries. | <ide> <ide> ## Utilities {#util}
2
Text
Text
remove note about django 1.3
5b071ab35e9f3b1d3f06e90741ded0e10e8a1651
<ide><path>docs/api-guide/filtering.md <ide> For more details on using filter sets see the [django-filter documentation][djan <ide> * By default filtering is not enabled. If you want to use `DjangoFilterBackend` remember to make sure it is installed by using the `'DEFAULT_FILTER_BACKENDS'` setting. <ide> * When using boolean fields, you should use the values `True` and `False` in the URL query parameters, rather than `0`, `1`, `true` or `false`. (The allowed boolean values are currently hardwired in Django's [NullBooleanSelect implementation][nullbooleanselect].) <ide> * `django-filter` supports filtering across relationships, using Django's double-underscore syntax. <del>* For Django 1.3 support, make sure to install `django-filter` version 0.5.4, as later versions drop support for 1.3. <ide> <ide> --- <ide>
1
Ruby
Ruby
fix failing appcast check
a793bc500cf5f4c00fb37e15688b7dc6ade1e1a3
<ide><path>Library/Homebrew/cask/audit.rb <ide> def check_appcast_contains_version <ide> return if cask.appcast.must_contain == :no_check <ide> <ide> appcast_stanza = cask.appcast.to_s <del> appcast_contents, = curl_output("--compressed", "--user-agent", HOMEBREW_USER_AGENT_FAKE_SAFARI, "--location", <del> "--globoff", "--max-time", "5", appcast_stanza) <add> appcast_contents, = begin <add> curl_output("--compressed", "--user-agent", HOMEBREW_USER_AGENT_FAKE_SAFARI, "--location", <add> "--globoff", "--max-time", "5", appcast_stanza) <add> rescue <add> add_error "appcast at URL '#{appcast_stanza}' offline or looping" <add> return <add> end <add> <ide> version_stanza = cask.version.to_s <del> adjusted_version_stanza = if cask.appcast.configuration.blank? <add> adjusted_version_stanza = if cask.appcast.must_contain.blank? <ide> version_stanza.match(/^[[:alnum:].]+/)[0] <ide> else <ide> cask.appcast.must_contain <ide> def check_appcast_contains_version <ide> <ide> add_warning "appcast at URL '#{appcast_stanza}' does not contain"\ <ide> " the version number '#{adjusted_version_stanza}':\n#{appcast_contents}" <del> rescue <del> add_error "appcast at URL '#{appcast_stanza}' offline or looping" <ide> end <ide> <ide> def check_github_repository
1
Java
Java
fix sniff task warnings
71b942698de314cc0ebe0a235188029675922349
<ide><path>spring-context/src/main/java/org/springframework/scheduling/concurrent/ScheduledExecutorFactoryBean.java <ide> public void setExposeUnconfigurableExecutor(boolean exposeUnconfigurableExecutor <ide> <ide> <ide> @Override <add> @UsesJava7 <ide> protected ExecutorService initializeExecutor( <ide> ThreadFactory threadFactory, RejectedExecutionHandler rejectedExecutionHandler) { <ide> <ide><path>spring-context/src/main/java/org/springframework/scheduling/concurrent/ThreadPoolTaskScheduler.java <ide> <ide> import org.springframework.core.task.AsyncListenableTaskExecutor; <ide> import org.springframework.core.task.TaskRejectedException; <add>import org.springframework.lang.UsesJava7; <ide> import org.springframework.scheduling.SchedulingTaskExecutor; <ide> import org.springframework.scheduling.TaskScheduler; <ide> import org.springframework.scheduling.Trigger; <ide> public void setPoolSize(int poolSize) { <ide> * There is no default. If not set, the executor property is not set. <ide> * <p><b>This setting can be modified at runtime, for example through JMX.</b> <ide> */ <add> @UsesJava7 <ide> public void setRemoveOnCancelPolicy(boolean removeOnCancelPolicy) { <ide> this.removeOnCancelPolicy = removeOnCancelPolicy; <ide> if (this.scheduledExecutor instanceof ScheduledThreadPoolExecutor) { <ide> public void setErrorHandler(ErrorHandler errorHandler) { <ide> this.errorHandler = errorHandler; <ide> } <ide> <add> @UsesJava7 <ide> @Override <ide> protected ExecutorService initializeExecutor( <ide> ThreadFactory threadFactory, RejectedExecutionHandler rejectedExecutionHandler) { <ide> public int getPoolSize() { <ide> * Return the current setting of removeOnCancelPolicy. <ide> * <p>Requires an underlying {@link ScheduledThreadPoolExecutor} and JDK 1.7+. <ide> */ <add> @UsesJava7 <ide> public boolean isRemoveOnCancelPolicy() { <ide> if (this.scheduledExecutor == null) { <ide> // Not initialized yet: return false (the default of the executor) <ide><path>spring-websocket/src/main/java/org/springframework/web/socket/config/WebSocketNamespaceUtils.java <ide> package org.springframework.web.socket.config; <ide> <ide> import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler; <del>import org.springframework.util.ClassUtils; <del>import org.springframework.web.socket.config.annotation.WebSocketConfigurationSupport; <ide> import org.w3c.dom.Element; <ide> <ide> import org.springframework.beans.factory.config.BeanDefinition; <ide> */ <ide> class WebSocketNamespaceUtils { <ide> <del> // Check for setRemoveOnCancelPolicy method - available on JDK 7 and higher <del> private static boolean hasRemoveOnCancelPolicyMethod = ClassUtils.hasMethod( <del> ScheduledThreadPoolExecutor.class, "setRemoveOnCancelPolicy", boolean.class); <del> <ide> <ide> public static RuntimeBeanReference registerHandshakeHandler(Element element, ParserContext parserContext, Object source) { <ide> RuntimeBeanReference handlerRef; <ide> private static RuntimeBeanReference registerSockJsTaskScheduler(String scheduler <ide> taskSchedulerDef.setRole(BeanDefinition.ROLE_INFRASTRUCTURE); <ide> taskSchedulerDef.getPropertyValues().add("poolSize", Runtime.getRuntime().availableProcessors()); <ide> taskSchedulerDef.getPropertyValues().add("threadNamePrefix", schedulerName + "-"); <del> if (hasRemoveOnCancelPolicyMethod) { <del> taskSchedulerDef.getPropertyValues().add("removeOnCancelPolicy", true); <del> } <add> taskSchedulerDef.getPropertyValues().add("removeOnCancelPolicy", true); <ide> parserContext.getRegistry().registerBeanDefinition(schedulerName, taskSchedulerDef); <ide> parserContext.registerComponent(new BeanComponentDefinition(taskSchedulerDef, schedulerName)); <ide> } <ide><path>spring-websocket/src/main/java/org/springframework/web/socket/config/annotation/WebSocketConfigurationSupport.java <ide> <ide> import org.springframework.context.annotation.Bean; <ide> import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler; <del>import org.springframework.util.ClassUtils; <ide> import org.springframework.web.servlet.HandlerMapping; <ide> <del>import java.util.concurrent.ScheduledThreadPoolExecutor; <del> <ide> /** <ide> * Configuration support for WebSocket request handling. <ide> * <ide> */ <ide> public class WebSocketConfigurationSupport { <ide> <del> // Check for setRemoveOnCancelPolicy method - available on JDK 7 and higher <del> private static boolean hasRemoveOnCancelPolicyMethod = ClassUtils.hasMethod( <del> ScheduledThreadPoolExecutor.class, "setRemoveOnCancelPolicy", boolean.class); <del> <del> <ide> @Bean <ide> public HandlerMapping webSocketHandlerMapping() { <ide> ServletWebSocketHandlerRegistry registry = new ServletWebSocketHandlerRegistry(defaultSockJsTaskScheduler()); <ide> public ThreadPoolTaskScheduler defaultSockJsTaskScheduler() { <ide> ThreadPoolTaskScheduler scheduler = new ThreadPoolTaskScheduler(); <ide> scheduler.setThreadNamePrefix("SockJS-"); <ide> scheduler.setPoolSize(Runtime.getRuntime().availableProcessors()); <del> if (hasRemoveOnCancelPolicyMethod) { <del> scheduler.setRemoveOnCancelPolicy(true); <del> } <add> scheduler.setRemoveOnCancelPolicy(true); <ide> return scheduler; <ide> } <ide> <ide><path>spring-websocket/src/main/java/org/springframework/web/socket/config/annotation/WebSocketMessageBrokerConfigurationSupport.java <ide> package org.springframework.web.socket.config.annotation; <ide> <ide> import java.util.Collections; <del>import java.util.concurrent.ScheduledThreadPoolExecutor; <ide> <ide> import org.springframework.beans.factory.config.CustomScopeConfigurer; <ide> import org.springframework.context.annotation.Bean; <ide> import org.springframework.messaging.simp.SimpSessionScope; <ide> import org.springframework.messaging.simp.config.AbstractMessageBrokerConfiguration; <ide> import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler; <del>import org.springframework.util.ClassUtils; <ide> import org.springframework.web.servlet.HandlerMapping; <ide> import org.springframework.web.socket.WebSocketHandler; <ide> import org.springframework.web.socket.messaging.SubProtocolWebSocketHandler; <ide> */ <ide> public abstract class WebSocketMessageBrokerConfigurationSupport extends AbstractMessageBrokerConfiguration { <ide> <del> // Check for setRemoveOnCancelPolicy method - available on JDK 7 and higher <del> private static boolean hasRemoveOnCancelPolicyMethod = ClassUtils.hasMethod( <del> ScheduledThreadPoolExecutor.class, "setRemoveOnCancelPolicy", boolean.class); <del> <ide> private WebSocketTransportRegistration transportRegistration; <ide> <ide> <ide> public ThreadPoolTaskScheduler messageBrokerSockJsTaskScheduler() { <ide> ThreadPoolTaskScheduler scheduler = new ThreadPoolTaskScheduler(); <ide> scheduler.setThreadNamePrefix("MessageBrokerSockJS-"); <ide> scheduler.setPoolSize(Runtime.getRuntime().availableProcessors()); <del> if (hasRemoveOnCancelPolicyMethod) { <del> scheduler.setRemoveOnCancelPolicy(true); <del> } <add> scheduler.setRemoveOnCancelPolicy(true); <ide> return scheduler; <ide> } <ide>
5
Text
Text
fix broken link in ``dev/refreshing_ci_cache.md``
f222aade58b697550aedfd33b0773749ba71834c
<ide><path>dev/REFRESHING_CI_CACHE.md <ide> merges to `main` branch have separate maintenance step that take care about refr <ide> used to speed up our builds and to speed up rebuilding of [Breeze](../BREEZE.rst) images for development <ide> purpose. This is all happening automatically, usually: <ide> <del>* The latest [constraints](../COMMITTERS.rst#pinned-constraint-files) are pushed to appropriate branch <add>* The latest [constraints](../CONTRIBUTING.rst#pinned-constraint-files) are pushed to appropriate branch <ide> after all tests succeeded in `main` merge or in `scheduled` build <ide> <ide> * The [images](../IMAGES.rst) in `ghcr.io` registry are refreshed after every successful merge to `main`
1
PHP
PHP
add tests to translatebehaviorshadowtabletest for
c1eaa40453d9251fb4bd3199d5b48b239403f858
<ide><path>tests/TestCase/ORM/Behavior/TranslateBehaviorShadowTableTest.php <ide> public function testAllowEmptyFalse() <ide> $this->assertEmpty($noFra); <ide> } <ide> <add> /** <add> * Tests adding new translation to a record with a missing translation <add> * <add> * @return void <add> */ <add> public function testAllowEmptyFalseWithNull() <add> { <add> $table = $this->getTableLocator()->get('Articles'); <add> $table->addBehavior('Translate', ['fields' => ['title', 'description'], 'allowEmptyTranslations' => false]); <add> <add> $article = $table->find()->first(); <add> $this->assertSame(1, $article->get('id')); <add> <add> $article = $table->patchEntity($article, [ <add> '_translations' => [ <add> 'fra' => [ <add> 'title' => 'Title', <add> ], <add> ], <add> ]); <add> <add> $table->save($article); <add> <add> // Remove the Behavior to unset the content != '' condition <add> $table->removeBehavior('Translate'); <add> <add> $fra = $table->ArticlesTranslations->find()->where(['locale' => 'fra'])->first(); <add> $this->assertNotEmpty($fra); <add> } <add> <ide> /** <ide> * Tests adding new translation to a record <ide> * <ide><path>tests/TestCase/ORM/Behavior/TranslateBehaviorTest.php <ide> public function testAllowEmptyFalse() <ide> } <ide> <ide> /** <del> * Tests adding new translation to a record <add> * Tests adding new translation to a record with a missing translation <ide> * <ide> * @return void <ide> */
2
Text
Text
fix the chinese document of java
53d9d7f3e30f0f9c1a9397384aa0dd8f79f24cdd
<ide><path>guide/chinese/java/index.md <ide> --- <ide> title: Java <del>localeTitle: Java的 <add>localeTitle: Java <ide> --- <ide> **什么是Java?** <ide> <ide> Java有大量[文档记录](https://docs.oracle.com/javase/8/docs/) ,因为它 <ide> <ide> 此外,这里是Java编码的免费IDE列表: <ide> <del>* [NetBeans的](https://netbeans.org/) <add>* [NetBeans](https://netbeans.org/) <ide> * [日食](https://eclipse.org/) <ide> * [IntelliJ IDEA](https://www.jetbrains.com/idea/features/) <ide> * [Android Studio](https://developer.android.com/studio/index.html) <del>* [BlueJ的](https://www.bluej.org/) <del>* [jEdit的](http://www.jedit.org/) <del>* [Oracle JDeveloper](http://www.oracle.com/technetwork/developer-tools/jdev/overview/index-094652.html) <ide>\ No newline at end of file <add>* [BlueJ](https://www.bluej.org/) <add>* [jEdit](http://www.jedit.org/) <add>* [Oracle JDeveloper](http://www.oracle.com/technetwork/developer-tools/jdev/overview/index-094652.html)
1
Javascript
Javascript
fix constructor call in crypto streams
fed8cff1d0170bb6558da0e7d143599e7c37a47f
<ide><path>lib/crypto.js <ide> function LazyTransform(options) { <ide> } <ide> util.inherits(LazyTransform, stream.Transform); <ide> <del>['read', 'write', 'end'].forEach(function(action, i, actions) { <add>var transformMethods = ['read', 'write', 'end', 'pipe', 'unpipe', <add> 'setEncoding', 'pause', 'resume']; <add> <add>transformMethods.forEach(function(action, i, actions) { <ide> LazyTransform.prototype[action] = function() { <ide> stream.Transform.call(this, this._options); <ide> <ide><path>test/simple/test-crypto-stream.js <add>// Copyright Joyent, Inc. and other Node contributors. <add>// <add>// Permission is hereby granted, free of charge, to any person obtaining a <add>// copy of this software and associated documentation files (the <add>// "Software"), to deal in the Software without restriction, including <add>// without limitation the rights to use, copy, modify, merge, publish, <add>// distribute, sublicense, and/or sell copies of the Software, and to permit <add>// persons to whom the Software is furnished to do so, subject to the <add>// following conditions: <add>// <add>// The above copyright notice and this permission notice shall be included <add>// in all copies or substantial portions of the Software. <add>// <add>// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS <add>// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF <add>// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN <add>// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, <add>// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR <add>// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE <add>// USE OR OTHER DEALINGS IN THE SOFTWARE. <add> <add>var common = require('../common'); <add>var assert = require('assert'); <add>var stream = require('stream'); <add>var util = require('util'); <add> <add>try { <add> var crypto = require('crypto'); <add>} catch (e) { <add> console.log('Not compiled with OPENSSL support.'); <add> process.exit(); <add>} <add> <add>// Small stream to buffer converter <add>function Stream2buffer(callback) { <add> stream.Writable.call(this); <add> <add> this._buffers = []; <add> this.once('finish', function () { <add> callback(null, Buffer.concat(this._buffers)); <add> }); <add>} <add>util.inherits(Stream2buffer, stream.Writable); <add> <add>Stream2buffer.prototype._write = function (data, encodeing, done) { <add> this._buffers.push(data); <add> return done(null); <add>}; <add> <add>// Create an md5 hash of "Hallo world" <add>var hasher1 = crypto.createHash('md5'); <add> hasher1.pipe(new Stream2buffer(common.mustCall(function end(err, hash) { <add> assert.equal(err, null); <add> assert.equal(hash.toString('hex'), '06460dadb35d3d503047ce750ceb2d07'); <add> }))); <add> hasher1.end('Hallo world'); <add> <add>// Simpler check for unpipe, setEncoding, pause and resume <add>crypto.createHash('md5').unpipe({}); <add>crypto.createHash('md5').setEncoding('utf8'); <add>crypto.createHash('md5').pause(); <add>crypto.createHash('md5').resume();
2
Java
Java
remove resourceservlet deprecated in 4.3.x
132022861e635736e2d4ab0f95247ad10cc39cc0
<ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/ResourceServlet.java <del>/* <del> * Copyright 2002-2017 the original author or authors. <del> * <del> * Licensed under the Apache License, Version 2.0 (the "License"); <del> * you may not use this file except in compliance with the License. <del> * You may obtain a copy of the License at <del> * <del> * http://www.apache.org/licenses/LICENSE-2.0 <del> * <del> * Unless required by applicable law or agreed to in writing, software <del> * distributed under the License is distributed on an "AS IS" BASIS, <del> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <del> * See the License for the specific language governing permissions and <del> * limitations under the License. <del> */ <del> <del>package org.springframework.web.servlet; <del> <del>import java.io.IOException; <del>import javax.servlet.RequestDispatcher; <del>import javax.servlet.ServletException; <del>import javax.servlet.http.HttpServletRequest; <del>import javax.servlet.http.HttpServletResponse; <del> <del>import org.springframework.lang.Nullable; <del>import org.springframework.util.AntPathMatcher; <del>import org.springframework.util.Assert; <del>import org.springframework.util.PathMatcher; <del>import org.springframework.util.StringUtils; <del>import org.springframework.web.context.support.ServletContextResource; <del> <del>/** <del> * Simple servlet that can expose an internal resource, including a <del> * default URL if the specified resource is not found. An alternative, <del> * for example, to trying and catching exceptions when using JSP include. <del> * <del> * <p>A further usage of this servlet is the ability to apply last-modified <del> * timestamps to quasi-static resources (typically JSPs). This can happen <del> * as bridge to parameter-specified resources, or as proxy for a specific <del> * target resource (or a list of specific target resources to combine). <del> * <del> * <p>A typical usage would map a URL like "/ResourceServlet" onto an instance <del> * of this servlet, and use the "JSP include" action to include this URL, <del> * with the "resource" parameter indicating the actual target path in the WAR. <del> * <del> * <p>The {@code defaultUrl} property can be set to the internal <del> * resource path of a default URL, to be rendered when the target resource <del> * is not found or not specified in the first place. <del> * <del> * <p>The "resource" parameter and the {@code defaultUrl} property can <del> * also specify a list of target resources to combine. Those resources will be <del> * included one by one to build the response. If last-modified determination <del> * is active, the newest timestamp among those files will be used. <del> * <del> * <p>The {@code allowedResources} property can be set to a URL <del> * pattern of resources that should be available via this servlet. <del> * If not set, any target resource can be requested, including resources <del> * in the WEB-INF directory! <del> * <del> * <p>If using this servlet for direct access rather than via includes, <del> * the {@code contentType} property should be specified to apply a <del> * proper content type. Note that a content type header in the target JSP will <del> * be ignored when including the resource via a RequestDispatcher include. <del> * <del> * <p>To apply last-modified timestamps for the target resource, set the <del> * {@code applyLastModified} property to true. This servlet will then <del> * return the file timestamp of the target resource as last-modified value, <del> * falling back to the startup time of this servlet if not retrievable. <del> * <del> * <p>Note that applying the last-modified timestamp in the above fashion <del> * just makes sense if the target resource does not generate content that <del> * depends on the HttpSession or cookies; it is just allowed to evaluate <del> * request parameters. <del> * <del> * <p>A typical case for such last-modified usage is a JSP that just makes <del> * minimal usage of basic means like includes or message resolution to <del> * build quasi-static content. Regenerating such content on every request <del> * is unnecessary; it can be cached as long as the file hasn't changed. <del> * <del> * <p>Note that this servlet will apply the last-modified timestamp if you <del> * tell it to do so: It's your decision whether the content of the target <del> * resource can be cached in such a fashion. Typical use cases are helper <del> * resources that are not fronted by a controller, like JavaScript files <del> * that are generated by a JSP (without depending on the HttpSession). <del> * <del> * @author Juergen Hoeller <del> * @author Rod Johnson <del> * @see #setDefaultUrl <del> * @see #setAllowedResources <del> * @see #setApplyLastModified <del> */ <del>@SuppressWarnings("serial") <del>public class ResourceServlet extends HttpServletBean { <del> <del> /** <del> * Any number of these characters are considered delimiters <del> * between multiple resource paths in a single String value. <del> */ <del> public static final String RESOURCE_URL_DELIMITERS = ",; \t\n"; <del> <del> /** <del> * Name of the parameter that must contain the actual resource path. <del> */ <del> public static final String RESOURCE_PARAM_NAME = "resource"; <del> <del> <del> @Nullable <del> private String defaultUrl; <del> <del> @Nullable <del> private String allowedResources; <del> <del> @Nullable <del> private String contentType; <del> <del> private boolean applyLastModified = false; <del> <del> @Nullable <del> private PathMatcher pathMatcher; <del> <del> private long startupTime; <del> <del> <del> /** <del> * Set the URL within the current web application from which to <del> * include content if the requested path isn't found, or if none <del> * is specified in the first place. <del> * <p>If specifying multiple URLs, they will be included one by one <del> * to build the response. If last-modified determination is active, <del> * the newest timestamp among those files will be used. <del> * @see #setApplyLastModified <del> */ <del> public void setDefaultUrl(String defaultUrl) { <del> this.defaultUrl = defaultUrl; <del> } <del> <del> /** <del> * Set allowed resources as URL pattern, e.g. "/WEB-INF/res/*.jsp", <del> * The parameter can be any Ant-style pattern parsable by AntPathMatcher. <del> * @see org.springframework.util.AntPathMatcher <del> */ <del> public void setAllowedResources(String allowedResources) { <del> this.allowedResources = allowedResources; <del> } <del> <del> /** <del> * Set the content type of the target resource (typically a JSP). <del> * Default is none, which is appropriate when including resources. <del> * <p>For directly accessing resources, for example to leverage this <del> * servlet's last-modified support, specify a content type here. <del> * Note that a content type header in the target JSP will be ignored <del> * when including the resource via a RequestDispatcher include. <del> */ <del> public void setContentType(String contentType) { <del> this.contentType = contentType; <del> } <del> <del> /** <del> * Set whether to apply the file timestamp of the target resource <del> * as last-modified value. Default is "false". <del> * <p>This is mainly intended for JSP targets that don't generate <del> * session-specific or database-driven content: Such files can be <del> * cached by the browser as long as the last-modified timestamp <del> * of the JSP file doesn't change. <del> * <p>This will only work correctly with expanded WAR files that <del> * allow access to the file timestamps. Else, the startup time <del> * of this servlet is returned. <del> */ <del> public void setApplyLastModified(boolean applyLastModified) { <del> this.applyLastModified = applyLastModified; <del> } <del> <del> <del> /** <del> * Remember the startup time, using no last-modified time before it. <del> */ <del> @Override <del> protected void initServletBean() { <del> this.pathMatcher = getPathMatcher(); <del> this.startupTime = System.currentTimeMillis(); <del> } <del> <del> /** <del> * Return a PathMatcher to use for matching the "allowedResources" URL pattern. <del> * Default is AntPathMatcher. <del> * @see #setAllowedResources <del> * @see org.springframework.util.AntPathMatcher <del> */ <del> protected PathMatcher getPathMatcher() { <del> return new AntPathMatcher(); <del> } <del> <del> <del> /** <del> * Determine the URL of the target resource and include it. <del> * @see #determineResourceUrl <del> */ <del> @Override <del> protected final void doGet(HttpServletRequest request, HttpServletResponse response) <del> throws ServletException, IOException { <del> <del> // determine URL of resource to include <del> String resourceUrl = determineResourceUrl(request); <del> <del> if (resourceUrl != null) { <del> try { <del> doInclude(request, response, resourceUrl); <del> } <del> catch (ServletException | IOException ex) { <del> if (logger.isWarnEnabled()) { <del> logger.warn("Failed to include content of resource [" + resourceUrl + "]", ex); <del> } <del> // Try including default URL if appropriate. <del> if (!includeDefaultUrl(request, response)) { <del> throw ex; <del> } <del> } <del> } <del> <del> // no resource URL specified -> try to include default URL. <del> else if (!includeDefaultUrl(request, response)) { <del> throw new ServletException("No target resource URL found for request"); <del> } <del> } <del> <del> /** <del> * Determine the URL of the target resource of this request. <del> * <p>Default implementation returns the value of the "resource" parameter. <del> * Can be overridden in subclasses. <del> * @param request current HTTP request <del> * @return the URL of the target resource, or {@code null} if none found <del> * @see #RESOURCE_PARAM_NAME <del> */ <del> @Nullable <del> protected String determineResourceUrl(HttpServletRequest request) { <del> return request.getParameter(RESOURCE_PARAM_NAME); <del> } <del> <del> /** <del> * Include the specified default URL, if appropriate. <del> * @param request current HTTP request <del> * @param response current HTTP response <del> * @return whether a default URL was included <del> * @throws ServletException if thrown by the RequestDispatcher <del> * @throws IOException if thrown by the RequestDispatcher <del> */ <del> private boolean includeDefaultUrl(HttpServletRequest request, HttpServletResponse response) <del> throws ServletException, IOException { <del> <del> if (this.defaultUrl == null) { <del> return false; <del> } <del> doInclude(request, response, this.defaultUrl); <del> return true; <del> } <del> <del> /** <del> * Include the specified resource via the RequestDispatcher. <del> * @param request current HTTP request <del> * @param response current HTTP response <del> * @param resourceUrl the URL of the target resource <del> * @throws ServletException if thrown by the RequestDispatcher <del> * @throws IOException if thrown by the RequestDispatcher <del> */ <del> private void doInclude(HttpServletRequest request, HttpServletResponse response, String resourceUrl) <del> throws ServletException, IOException { <del> <del> if (this.contentType != null) { <del> response.setContentType(this.contentType); <del> } <del> String[] resourceUrls = <del> StringUtils.tokenizeToStringArray(resourceUrl, RESOURCE_URL_DELIMITERS); <del> for (String url : resourceUrls) { <del> // check whether URL matches allowed resources <del> if (this.allowedResources != null) { <del> Assert.state(this.pathMatcher != null, "No PathMatcher available"); <del> if (!this.pathMatcher.match(this.allowedResources, url)) { <del> throw new ServletException("Resource [" + url + <del> "] does not match allowed pattern [" + this.allowedResources + "]"); <del> } <del> } <del> if (logger.isDebugEnabled()) { <del> logger.debug("Including resource [" + url + "]"); <del> } <del> RequestDispatcher rd = request.getRequestDispatcher(url); <del> rd.include(request, response); <del> } <del> } <del> <del> /** <del> * Return the last-modified timestamp of the file that corresponds <del> * to the target resource URL (i.e. typically the request ".jsp" file). <del> * Will simply return -1 if "applyLastModified" is false (the default). <del> * <p>Returns no last-modified date before the startup time of this servlet, <del> * to allow for message resolution etc that influences JSP contents, <del> * assuming that those background resources might have changed on restart. <del> * <p>Returns the startup time of this servlet if the file that corresponds <del> * to the target resource URL couldn't be resolved (for example, because <del> * the WAR is not expanded). <del> * @see #determineResourceUrl <del> * @see #getFileTimestamp <del> */ <del> @Override <del> protected final long getLastModified(HttpServletRequest request) { <del> if (this.applyLastModified) { <del> String resourceUrl = determineResourceUrl(request); <del> if (resourceUrl == null) { <del> resourceUrl = this.defaultUrl; <del> } <del> if (resourceUrl != null) { <del> String[] resourceUrls = StringUtils.tokenizeToStringArray(resourceUrl, RESOURCE_URL_DELIMITERS); <del> long latestTimestamp = -1; <del> for (String url : resourceUrls) { <del> long timestamp = getFileTimestamp(url); <del> if (timestamp > latestTimestamp) { <del> latestTimestamp = timestamp; <del> } <del> } <del> return (latestTimestamp > this.startupTime ? latestTimestamp : this.startupTime); <del> } <del> } <del> return -1; <del> } <del> <del> /** <del> * Return the file timestamp for the given resource. <del> * @param resourceUrl the URL of the resource <del> * @return the file timestamp in milliseconds, or -1 if not determinable <del> */ <del> protected long getFileTimestamp(String resourceUrl) { <del> ServletContextResource resource = new ServletContextResource(getServletContext(), resourceUrl); <del> try { <del> long lastModifiedTime = resource.lastModified(); <del> if (logger.isDebugEnabled()) { <del> logger.debug("Last-modified timestamp of " + resource + " is " + lastModifiedTime); <del> } <del> return lastModifiedTime; <del> } <del> catch (IOException ex) { <del> logger.warn("Couldn't retrieve last-modified timestamp of [" + resource + <del> "] - using ResourceServlet startup time"); <del> return -1; <del> } <del> } <del> <del>}
1
Python
Python
enable defaultdatacollator class
3e8761ab8077e3bb243fe2f78b2a682bd2257cf1
<ide><path>src/transformers/data/data_collator.py <ide> def default_data_collator(features: List[InputDataClass], return_tensors="pt") - <ide> class DefaultDataCollator(DataCollatorMixin): <ide> return_tensors: str = "pt" <ide> <add> def __call__(self, features: List[Dict[str, Any]], return_tensors=None) -> Dict[str, Any]: <add> if return_tensors is None: <add> return_tensors = self.return_tensors <add> return default_data_collator(features, return_tensors) <add> <ide> <ide> def torch_default_data_collator(features: List[InputDataClass]) -> Dict[str, Any]: <ide> import torch
1
Javascript
Javascript
add any function
2878c1d0d48e02204c69d37afb7eb608d22a7039
<ide><path>src/js/event-target.js <ide> EventTarget.prototype.removeEventListener = EventTarget.prototype.off; <ide> * The function to be called once for each event name. <ide> */ <ide> EventTarget.prototype.one = function(type, fn) { <del> // Remove the addEventListener alialing Events.on <add> // Remove the addEventListener aliasing Events.on <ide> // so we don't get into an infinite type loop <ide> const ael = this.addEventListener; <ide> <ide> EventTarget.prototype.one = function(type, fn) { <ide> this.addEventListener = ael; <ide> }; <ide> <add>EventTarget.prototype.any = function(type, fn) { <add> // Remove the addEventListener aliasing Events.on <add> // so we don't get into an infinite type loop <add> const ael = this.addEventListener; <add> <add> this.addEventListener = () => {}; <add> Events.any(this, type, fn); <add> this.addEventListener = ael; <add>}; <add> <ide> /** <ide> * This function causes an event to happen. This will then cause any `event listeners` <ide> * that are waiting for that event, to get called. If there are no `event listeners` <ide><path>src/js/mixins/evented.js <ide> const EventedMixin = { <ide> <ide> /** <ide> * Add a listener to an event (or events) on this object or another evented <del> * object. The listener will only be called once and then removed. <add> * object. The listener will be called once per event and then removed. <ide> * <ide> * @param {string|Array|Element|Object} targetOrType <ide> * If this is a string or array, it represents the event type(s) <ide> const EventedMixin = { <ide> <ide> // Targeting another evented object. <ide> } else { <add> // TODO: This wrapper is incorrect! It should only <add> // remove the wrapper for the event type that called it. <add> // Instead all listners are removed on the first trigger! <add> // see https://github.com/videojs/video.js/issues/5962 <ide> const wrapper = (...largs) => { <ide> this.off(target, type, wrapper); <ide> listener.apply(null, largs); <ide> const EventedMixin = { <ide> } <ide> }, <ide> <add> /** <add> * Add a listener to an event (or events) on this object or another evented <add> * object. The listener will only be called once for the first event that is triggered <add> * then removed. <add> * <add> * @param {string|Array|Element|Object} targetOrType <add> * If this is a string or array, it represents the event type(s) <add> * that will trigger the listener. <add> * <add> * Another evented object can be passed here instead, which will <add> * cause the listener to listen for events on _that_ object. <add> * <add> * In either case, the listener's `this` value will be bound to <add> * this object. <add> * <add> * @param {string|Array|Function} typeOrListener <add> * If the first argument was a string or array, this should be the <add> * listener function. Otherwise, this is a string or array of event <add> * type(s). <add> * <add> * @param {Function} [listener] <add> * If the first argument was another evented object, this will be <add> * the listener function. <add> */ <add> any(...args) { <add> const {isTargetingSelf, target, type, listener} = normalizeListenArgs(this, args); <add> <add> // Targeting this evented object. <add> if (isTargetingSelf) { <add> listen(target, 'any', type, listener); <add> <add> // Targeting another evented object. <add> } else { <add> const wrapper = (...largs) => { <add> this.off(target, type, wrapper); <add> listener.apply(null, largs); <add> }; <add> <add> // Use the same function ID as the listener so we can remove it later <add> // it using the ID of the original listener. <add> wrapper.guid = listener.guid; <add> listen(target, 'any', type, wrapper); <add> } <add> }, <add> <ide> /** <ide> * Removes listener(s) from event(s) on an evented object. <ide> * <ide><path>src/js/utils/events.js <ide> export function one(elem, type, fn) { <ide> func.guid = fn.guid = fn.guid || Guid.newGUID(); <ide> on(elem, type, func); <ide> } <add> <add>/** <add> * Trigger a listener only once and then turn if off for all <add> * configured events <add> * <add> * @param {Element|Object} elem <add> * Element or object to bind to. <add> * <add> * @param {string|string[]} type <add> * Name/type of event <add> * <add> * @param {Event~EventListener} fn <add> * Event listener function <add> */ <add>export function any(elem, type, fn) { <add> const func = function() { <add> off(elem, type, func); <add> fn.apply(this, arguments); <add> }; <add> <add> // copy the guid to the new function so it can removed using the original function's ID <add> func.guid = fn.guid = fn.guid || Guid.newGUID(); <add> <add> // multiple ons, but one off for everything <add> on(elem, type, func); <add>} <ide><path>test/unit/events.test.js <ide> QUnit.test('retrigger with an object should use the old element as target', func <ide> Events.off(el1, 'click'); <ide> Events.off(el2, 'click'); <ide> }); <add> <add>QUnit.test('should listen only once for any', function(assert) { <add> const el = document.createElement('div'); <add> let triggered = 0; <add> const listener = () => triggered++; <add> <add> Events.any(el, 'click', listener); <add> assert.equal(triggered, 0, 'listener was not yet triggered'); <add> // 1 click <add> Events.trigger(el, 'click'); <add> <add> assert.equal(triggered, 1, 'listener was triggered'); <add> // No click should happen. <add> Events.trigger(el, 'click'); <add> assert.equal(triggered, 1, 'listener was not triggered again'); <add>}); <add> <add>QUnit.test('only the first event should call listener via any', function(assert) { <add> const el = document.createElement('div'); <add> let triggered = 0; <add> const listener = () => triggered++; <add> <add> Events.any(el, ['click', 'event1', 'event2'], listener); <add> assert.equal(triggered, 0, 'listener was not yet triggered'); <add> <add> // 1 click <add> Events.trigger(el, 'click'); <add> assert.equal(triggered, 1, 'listener was triggered'); <add> // nothing below here should trigger the Callback <add> Events.trigger(el, 'click'); <add> Events.trigger(el, 'event1'); <add> Events.trigger(el, 'event1'); <add> Events.trigger(el, 'event2'); <add> Events.trigger(el, 'event2'); <add> assert.equal(triggered, 1, 'listener was not triggered again'); <add>}); <ide><path>test/unit/mixins/evented.test.js <ide> QUnit.test('evented() with custom element', function(assert) { <ide> ); <ide> }); <ide> <del>QUnit.test('on() and one() errors', function(assert) { <add>QUnit.test('on(), one(), and any() errors', function(assert) { <ide> const targeta = this.targets.a = evented({}); <ide> const targetb = this.targets.b = evented({}); <ide> <del> ['on', 'one'].forEach(method => { <add> ['on', 'one', 'any'].forEach(method => { <ide> assert.throws(() => targeta[method](), errors.type, 'the expected error is thrown'); <ide> assert.throws(() => targeta[method](' '), errors.type, 'the expected error is thrown'); <ide> assert.throws(() => targeta[method]([]), errors.type, 'the expected error is thrown'); <ide> QUnit.test('one() can add a listener to an array of event types on this object', <ide> }); <ide> }); <ide> <add>QUnit.test('one() can add a listener to an array of event types on this object', function(assert) { <add> const a = this.targets.a = evented({}); <add> const spy = sinon.spy(); <add> <add> a.one(['x', 'y'], spy); <add> a.trigger('x'); <add> a.trigger('y'); <add> a.trigger('x'); <add> a.trigger('y'); <add> <add> assert.strictEqual(spy.callCount, 2, 'the listener was called the expected number of times'); <add> <add> validateListenerCall(spy.getCall(0), a, { <add> type: 'x', <add> target: a.eventBusEl_ <add> }); <add> <add> validateListenerCall(spy.getCall(1), a, { <add> type: 'y', <add> target: a.eventBusEl_ <add> }); <add>}); <add> <add>QUnit.test('any() can add a listener to one event type on this object', function(assert) { <add> const a = this.targets.a = evented({}); <add> const spy = sinon.spy(); <add> <add> a.any('x', spy); <add> a.trigger('x'); <add> a.trigger('x'); <add> <add> assert.strictEqual(spy.callCount, 1, 'the listener was called the expected number of times'); <add> <add> validateListenerCall(spy.getCall(0), a, { <add> type: 'x', <add> target: a.eventBusEl_ <add> }); <add>}); <add> <add>QUnit.test('any() can add a listener to an array of event types on this object', function(assert) { <add> const a = this.targets.a = evented({}); <add> const spy = sinon.spy(); <add> <add> a.any(['x', 'y'], spy); <add> a.trigger('x'); <add> a.trigger('y'); <add> a.trigger('x'); <add> a.trigger('y'); <add> <add> assert.strictEqual(spy.callCount, 1, 'the listener was called the expected number of times'); <add> <add> validateListenerCall(spy.getCall(0), a, { <add> type: 'x', <add> target: a.eventBusEl_ <add> }); <add>}); <add> <ide> QUnit.test('on() can add a listener to one event type on a different target object', function(assert) { <ide> const a = this.targets.a = evented({}); <ide> const b = this.targets.b = evented({}); <ide> QUnit.test('one() can add a listener to one event type on a different target obj <ide> }); <ide> }); <ide> <del>// The behavior here unfortunately differs from the identical case where "a" <del>// listens to itself. This is something that should be resolved... <add>// TODO: This test is incorrect! this listener should be called twice, <add>// but instead all listners are removed on the first trigger! <add>// see https://github.com/videojs/video.js/issues/5962 <ide> QUnit.test('one() can add a listener to an array of event types on a different target object', function(assert) { <ide> const a = this.targets.a = evented({}); <ide> const b = this.targets.b = evented({}); <ide> QUnit.test('one() can add a listener to an array of event types on a different t <ide> }); <ide> }); <ide> <add>QUnit.test('any() can add a listener to one event type on a different target object', function(assert) { <add> const a = this.targets.a = evented({}); <add> const b = this.targets.b = evented({}); <add> const spy = sinon.spy(); <add> <add> a.any(b, 'x', spy); <add> b.trigger('x'); <add> <add> // Make sure we aren't magically binding a listener to "a". <add> a.trigger('x'); <add> <add> assert.strictEqual(spy.callCount, 1, 'the listener was called the expected number of times'); <add> <add> validateListenerCall(spy.getCall(0), a, { <add> type: 'x', <add> target: b.eventBusEl_ <add> }); <add>}); <add> <add>QUnit.test('any() can add a listener to an array of event types on a different target object', function(assert) { <add> const a = this.targets.a = evented({}); <add> const b = this.targets.b = evented({}); <add> const spy = sinon.spy(); <add> <add> a.any(b, ['x', 'y'], spy); <add> b.trigger('x'); <add> b.trigger('y'); <add> b.trigger('x'); <add> b.trigger('y'); <add> <add> // Make sure we aren't magically binding a listener to "a". <add> a.trigger('x'); <add> a.trigger('y'); <add> <add> assert.strictEqual(spy.callCount, 1, 'the listener was called the expected number of times'); <add> <add> validateListenerCall(spy.getCall(0), a, { <add> type: 'x', <add> target: b.eventBusEl_ <add> }); <add>}); <add> <ide> QUnit.test('off() with no arguments will remove all listeners from all events on this object', function(assert) { <ide> const a = this.targets.a = evented({}); <ide> const spyX = sinon.spy();
5
Go
Go
add info struct for v1.24
667315576fac663bd80bbada4364413692e57ac6
<ide><path>api/server/router/system/system_routes.go <ide> import ( <ide> "github.com/docker/docker/api/types/registry" <ide> timetypes "github.com/docker/docker/api/types/time" <ide> "github.com/docker/docker/api/types/versions" <add> "github.com/docker/docker/api/types/versions/v1p24" <ide> "github.com/docker/docker/pkg/ioutils" <ide> "golang.org/x/net/context" <ide> ) <ide> func (s *systemRouter) getInfo(ctx context.Context, w http.ResponseWriter, r *ht <ide> <ide> if versions.LessThan(httputils.VersionFromContext(ctx), "1.25") { <ide> // TODO: handle this conversion in engine-api <del> type oldInfo struct { <del> *types.InfoBase <del> ExecutionDriver string <del> SecurityOptions []string <del> } <del> old := &oldInfo{ <add> oldInfo := &v1p24.Info{ <ide> InfoBase: info.InfoBase, <ide> ExecutionDriver: "<not supported>", <ide> } <ide> for _, s := range info.SecurityOptions { <ide> if s.Key == "Name" { <del> old.SecurityOptions = append(old.SecurityOptions, s.Value) <add> oldInfo.SecurityOptions = append(oldInfo.SecurityOptions, s.Value) <ide> } <ide> } <del> return httputils.WriteJSON(w, http.StatusOK, old) <add> return httputils.WriteJSON(w, http.StatusOK, oldInfo) <ide> } <ide> return httputils.WriteJSON(w, http.StatusOK, info) <ide> } <ide><path>api/types/versions/v1p24/types.go <add>// Package v1p24 provides specific API types for the API version 1, patch 24. <add>package v1p24 <add> <add>import "github.com/docker/docker/api/types" <add> <add>type Info struct { <add> *types.InfoBase <add> ExecutionDriver string <add> SecurityOptions []string <add>}
2
Ruby
Ruby
use assert_match for exception messages
bb15edf524144480257755196e87a41f9d73d77d
<ide><path>actionpack/test/dispatch/routing_test.rb <ide> def app; APP end <ide> message = "No route matches #{url.inspect}, possible unmatched constraints: #{missing.inspect}" <ide> <ide> error = assert_raises(ActionController::UrlGenerationError, message) { product_path(id: nil) } <del> assert_equal message, error.message <add> assert_match message, error.message <ide> end <ide> <ide> test "URL helpers raise message with mixed parameters when generation fails" do <ide> def app; APP end <ide> <ide> # Optimized URL helper <ide> error = assert_raises(ActionController::UrlGenerationError) { product_path(nil, "id" => "url-tested") } <del> assert_equal message, error.message <add> assert_match message, error.message <ide> <ide> # Non-optimized URL helper <ide> error = assert_raises(ActionController::UrlGenerationError, message) { product_path(id: nil, "id" => "url-tested") } <del> assert_equal message, error.message <add> assert_match message, error.message <ide> end <ide> end <ide>
1
Ruby
Ruby
allow access to lock directory inside tests
b7ea9e18306ec0e34b8f3d9bdffba68ee0b3ee7c
<ide><path>Library/Homebrew/dev-cmd/test.rb <ide> def test <ide> sandbox.allow_write_log(f) <ide> sandbox.allow_write_xcode <ide> sandbox.allow_write_path(HOMEBREW_PREFIX/"var/cache") <add> sandbox.allow_write_path(HOMEBREW_PREFIX/"var/homebrew/locks") <ide> sandbox.allow_write_path(HOMEBREW_PREFIX/"var/log") <ide> sandbox.allow_write_path(HOMEBREW_PREFIX/"var/run") <ide> sandbox.exec(*args)
1
Go
Go
remove worthless iptables test
58e011595e4c518a38ec27716585177faa969f72
<ide><path>integration/iptables_test.go <del>package docker <del> <del>import ( <del> "github.com/dotcloud/docker/pkg/iptables" <del> "os" <del> "testing" <del>) <del> <del>// FIXME: this test should be a unit test. <del>// For example by mocking os/exec to make sure iptables is not actually called. <del> <del>func TestIptables(t *testing.T) { <del> if _, err := iptables.Raw("-L"); err != nil { <del> t.Fatal(err) <del> } <del> path := os.Getenv("PATH") <del> os.Setenv("PATH", "") <del> defer os.Setenv("PATH", path) <del> if _, err := iptables.Raw("-L"); err == nil { <del> t.Fatal("Not finding iptables in the PATH should cause an error") <del> } <del>}
1
Python
Python
fix loss masking tests
ae4219e6b13fbe666d4ad5c34ac3cfa86355d8df
<ide><path>tests/auto/test_loss_masking.py <ide> import numpy as np <add>import unittest <ide> from keras.models import Sequential <ide> from keras.layers.core import TimeDistributedDense, Masking <ide> <ide> <del>def test_cost_masking(): <del> X = np.array( <del> [[[1, 1], [2, 1], [3, 1], [5, 5]], <del> [[1, 5], [5, 0], [0, 0], [0, 0]]], dtype=np.int32) <add>class TestLossMasking(unittest.TestCase): <add> def test_loss_masking(self): <add> X = np.array( <add> [[[1, 1], [2, 1], [3, 1], [5, 5]], <add> [[1, 5], [5, 0], [0, 0], [0, 0]]], dtype=np.int32) <ide> <del> model = Sequential() <del> model.add(Masking(mask_value=0)) <del> model.add(TimeDistributedDense(2, 1, init='one')) <del> model.compile(loss='mse', optimizer='sgd') <del> y = model.predict(X) <add> model = Sequential() <add> model.add(Masking(mask_value=0)) <add> model.add(TimeDistributedDense(2, 1, init='one')) <add> model.compile(loss='mse', optimizer='sgd') <add> y = model.predict(X) <ide> <del> loss = model.fit(X, 4*y, nb_epoch=1, batch_size=2, verbose=1).history['loss'][0] <del> assert loss == 213.75 <add> loss = model.fit(X, 4*y, nb_epoch=1, batch_size=2, verbose=1).history['loss'][0] <add> assert loss == 213.75 <ide> <del> model = Sequential() <del> model.add(Masking(mask_value=0)) <del> model.add(TimeDistributedDense(2, 1, init='one')) <del> model.compile(loss='mse', optimizer='sgd', mask_cost=True) <del> loss = model.fit(X, 4*y, nb_epoch=1, batch_size=2, verbose=1).history['loss'][0] <del> assert loss == 282.375 <add> model = Sequential() <add> model.add(Masking(mask_value=0)) <add> model.add(TimeDistributedDense(2, 1, init='one')) <add> model.compile(loss='mse', optimizer='sgd', mask_cost=True) <add> loss = model.fit(X, 4*y, nb_epoch=1, batch_size=2, verbose=1).history['loss'][0] <add> assert loss == 282.375 <add> <add> <add>if __name__ == '__main__': <add> print('Test loss masking') <add> unittest.main()
1
Javascript
Javascript
apply null as `this` for util.format
0903b6d8a8b63075ff7f2efae8a1922542439728
<ide><path>lib/console.js <ide> function Console(stdout, stderr) { <ide> } <ide> <ide> Console.prototype.log = function() { <del> this._stdout.write(util.format.apply(this, arguments) + '\n'); <add> this._stdout.write(util.format.apply(null, arguments) + '\n'); <ide> }; <ide> <ide> <ide> Console.prototype.info = Console.prototype.log; <ide> <ide> <ide> Console.prototype.warn = function() { <del> this._stderr.write(util.format.apply(this, arguments) + '\n'); <add> this._stderr.write(util.format.apply(null, arguments) + '\n'); <ide> }; <ide> <ide> <ide> Console.prototype.trace = function trace() { <ide> // exposed. <ide> var err = new Error(); <ide> err.name = 'Trace'; <del> err.message = util.format.apply(this, arguments); <add> err.message = util.format.apply(null, arguments); <ide> Error.captureStackTrace(err, trace); <ide> this.error(err.stack); <ide> }; <ide> Console.prototype.trace = function trace() { <ide> Console.prototype.assert = function(expression) { <ide> if (!expression) { <ide> var arr = Array.prototype.slice.call(arguments, 1); <del> require('assert').ok(false, util.format.apply(this, arr)); <add> require('assert').ok(false, util.format.apply(null, arr)); <ide> } <ide> }; <ide>
1
Javascript
Javascript
remove an unused argument
f165e08b1696973a24b0ea57a197dbd0861b95dd
<ide><path>src/Angular.js <ide> function bootstrap(element, modules, config) { <ide> }]); <ide> modules.unshift('ng'); <ide> var injector = createInjector(modules, config.strictDi); <del> injector.invoke(['$rootScope', '$rootElement', '$compile', '$injector', '$animate', <del> function(scope, element, compile, injector, animate) { <add> injector.invoke(['$rootScope', '$rootElement', '$compile', '$injector', <add> function(scope, element, compile, injector) { <ide> scope.$apply(function() { <ide> element.data('$injector', injector); <ide> compile(element)(scope);
1
Ruby
Ruby
add readonly support for relations
7cce95b25ace33e04526d4490e487a080c1f9b96
<ide><path>activerecord/lib/active_record/base.rb <ide> def default_select(qualified) <ide> <ide> def construct_finder_arel(options = {}, scope = scope(:find)) <ide> # TODO add lock to Arel <del> arel_table(options[:from]). <add> relation = arel_table(options[:from]). <ide> joins(construct_join(options[:joins], scope)). <ide> conditions(construct_conditions(options[:conditions], scope)). <ide> select(options[:select] || (scope && scope[:select]) || default_select(options[:joins] || (scope && scope[:joins]))). <ide> group(construct_group(options[:group], options[:having], scope)). <ide> order(construct_order(options[:order], scope)). <ide> limit(construct_limit(options[:limit], scope)). <ide> offset(construct_offset(options[:offset], scope)) <add> <add> relation = relation.readonly if options[:readonly] <add> <add> relation <add> <ide> end <ide> <ide> def construct_finder_sql(options, scope = scope(:find)) <ide><path>activerecord/lib/active_record/relation.rb <ide> class Relation <ide> <ide> def initialize(klass, relation) <ide> @klass, @relation = klass, relation <add> @readonly = false <add> end <add> <add> def readonly <add> @readonly = true <add> self <ide> end <ide> <ide> def to_a <del> @klass.find_by_sql(@relation.to_sql) <add> records = @klass.find_by_sql(@relation.to_sql) <add> <add> records.each { |record| record.readonly! } if @readonly <add> <add> records <ide> end <ide> <ide> def each(&block) <ide><path>activerecord/test/cases/relations_test.rb <ide> def test_relation_responds_to_delegated_methods <ide> assert relation.respond_to?(method) <ide> end <ide> end <add> <add> def test_find_with_readonly_option <add> Developer.all.each { |d| assert !d.readonly? } <add> Developer.all.readonly.each { |d| assert d.readonly? } <add> Developer.all(:readonly => true).each { |d| assert d.readonly? } <add> end <ide> end <ide>
3
Python
Python
remove uses of localstack
82c2e0366ce6b74a3786a64631ce58b85b3a7d4e
<ide><path>src/flask/app.py <ide> from .ctx import _AppCtxGlobals <ide> from .ctx import AppContext <ide> from .ctx import RequestContext <del>from .globals import _app_ctx_stack <del>from .globals import _request_ctx_stack <add>from .globals import _cv_app <add>from .globals import _cv_req <ide> from .globals import g <ide> from .globals import request <add>from .globals import request_ctx <ide> from .globals import session <ide> from .helpers import _split_blueprint_path <ide> from .helpers import get_debug_flag <ide> def dispatch_request(self) -> ft.ResponseReturnValue: <ide> This no longer does the exception handling, this code was <ide> moved to the new :meth:`full_dispatch_request`. <ide> """ <del> req = _request_ctx_stack.top.request <add> req = request_ctx.request <ide> if req.routing_exception is not None: <ide> self.raise_routing_exception(req) <del> rule = req.url_rule <add> rule: Rule = req.url_rule # type: ignore[assignment] <ide> # if we provide automatic options for this URL and the <ide> # request came with the OPTIONS method, reply automatically <ide> if ( <ide> def dispatch_request(self) -> ft.ResponseReturnValue: <ide> ): <ide> return self.make_default_options_response() <ide> # otherwise dispatch to the handler for that endpoint <del> return self.ensure_sync(self.view_functions[rule.endpoint])(**req.view_args) <add> view_args: t.Dict[str, t.Any] = req.view_args # type: ignore[assignment] <add> return self.ensure_sync(self.view_functions[rule.endpoint])(**view_args) <ide> <ide> def full_dispatch_request(self) -> Response: <ide> """Dispatches the request and on top of that performs request <ide> def make_default_options_response(self) -> Response: <ide> <ide> .. versionadded:: 0.7 <ide> """ <del> adapter = _request_ctx_stack.top.url_adapter <del> methods = adapter.allowed_methods() <add> adapter = request_ctx.url_adapter <add> methods = adapter.allowed_methods() # type: ignore[union-attr] <ide> rv = self.response_class() <ide> rv.allow.update(methods) <ide> return rv <ide> def url_for( <ide> .. versionadded:: 2.2 <ide> Moved from ``flask.url_for``, which calls this method. <ide> """ <del> req_ctx = _request_ctx_stack.top <add> req_ctx = _cv_req.get(None) <ide> <ide> if req_ctx is not None: <ide> url_adapter = req_ctx.url_adapter <ide> def url_for( <ide> if _external is None: <ide> _external = _scheme is not None <ide> else: <del> app_ctx = _app_ctx_stack.top <add> app_ctx = _cv_app.get(None) <ide> <ide> # If called by helpers.url_for, an app context is active, <ide> # use its url_adapter. Otherwise, app.url_for was called <ide> def url_for( <ide> self.inject_url_defaults(endpoint, values) <ide> <ide> try: <del> rv = url_adapter.build( <add> rv = url_adapter.build( # type: ignore[union-attr] <ide> endpoint, <ide> values, <ide> method=_method, <ide> def process_response(self, response: Response) -> Response: <ide> :return: a new response object or the same, has to be an <ide> instance of :attr:`response_class`. <ide> """ <del> ctx = _request_ctx_stack.top <add> ctx = request_ctx._get_current_object() # type: ignore[attr-defined] <ide> <ide> for func in ctx._after_request_functions: <ide> response = self.ensure_sync(func)(response) <ide> def wsgi_app(self, environ: dict, start_response: t.Callable) -> t.Any: <ide> return response(environ, start_response) <ide> finally: <ide> if "werkzeug.debug.preserve_context" in environ: <del> environ["werkzeug.debug.preserve_context"](_app_ctx_stack.top) <del> environ["werkzeug.debug.preserve_context"](_request_ctx_stack.top) <add> environ["werkzeug.debug.preserve_context"](_cv_app.get()) <add> environ["werkzeug.debug.preserve_context"](_cv_req.get()) <ide> <ide> if error is not None and self.should_ignore_error(error): <ide> error = None <ide><path>src/flask/cli.py <ide> def shell_command() -> None: <ide> without having to manually configure the application. <ide> """ <ide> import code <del> from .globals import _app_ctx_stack <ide> <del> app = _app_ctx_stack.top.app <ide> banner = ( <ide> f"Python {sys.version} on {sys.platform}\n" <del> f"App: {app.import_name} [{app.env}]\n" <del> f"Instance: {app.instance_path}" <add> f"App: {current_app.import_name} [{current_app.env}]\n" <add> f"Instance: {current_app.instance_path}" <ide> ) <ide> ctx: dict = {} <ide> <ide> def shell_command() -> None: <ide> with open(startup) as f: <ide> eval(compile(f.read(), startup, "exec"), ctx) <ide> <del> ctx.update(app.make_shell_context()) <add> ctx.update(current_app.make_shell_context()) <ide> <ide> # Site, customize, or startup script can set a hook to call when <ide> # entering interactive mode. The default one sets up readline with <ide><path>src/flask/ctx.py <ide> from werkzeug.exceptions import HTTPException <ide> <ide> from . import typing as ft <del>from .globals import _app_ctx_stack <ide> from .globals import _cv_app <ide> from .globals import _cv_req <del>from .globals import _request_ctx_stack <ide> from .signals import appcontext_popped <ide> from .signals import appcontext_pushed <ide> <ide> def __iter__(self) -> t.Iterator[str]: <ide> return iter(self.__dict__) <ide> <ide> def __repr__(self) -> str: <del> top = _app_ctx_stack.top <del> if top is not None: <del> return f"<flask.g of {top.app.name!r}>" <add> ctx = _cv_app.get(None) <add> if ctx is not None: <add> return f"<flask.g of '{ctx.app.name}'>" <ide> return object.__repr__(self) <ide> <ide> <ide> def add_header(response): <ide> <ide> .. versionadded:: 0.9 <ide> """ <del> top = _request_ctx_stack.top <add> ctx = _cv_req.get(None) <ide> <del> if top is None: <add> if ctx is None: <ide> raise RuntimeError( <del> "This decorator can only be used when a request context is" <del> " active, such as within a view function." <add> "'after_this_request' can only be used when a request" <add> " context is active, such as in a view function." <ide> ) <ide> <del> top._after_request_functions.append(f) <add> ctx._after_request_functions.append(f) <ide> return f <ide> <ide> <ide> def do_some_work(): <ide> <ide> .. versionadded:: 0.10 <ide> """ <del> top = _request_ctx_stack.top <add> ctx = _cv_req.get(None) <ide> <del> if top is None: <add> if ctx is None: <ide> raise RuntimeError( <del> "This decorator can only be used when a request context is" <del> " active, such as within a view function." <add> "'copy_current_request_context' can only be used when a" <add> " request context is active, such as in a view function." <ide> ) <ide> <del> reqctx = top.copy() <add> ctx = ctx.copy() <ide> <ide> def wrapper(*args, **kwargs): <del> with reqctx: <del> return reqctx.app.ensure_sync(f)(*args, **kwargs) <add> with ctx: <add> return ctx.app.ensure_sync(f)(*args, **kwargs) <ide> <ide> return update_wrapper(wrapper, f) <ide> <ide> class AppContext: <ide> def __init__(self, app: "Flask") -> None: <ide> self.app = app <ide> self.url_adapter = app.create_url_adapter(None) <del> self.g = app.app_ctx_globals_class() <add> self.g: _AppCtxGlobals = app.app_ctx_globals_class() <ide> self._cv_tokens: t.List[contextvars.Token] = [] <ide> <ide> def push(self) -> None: <ide> def __init__( <ide> self.app = app <ide> if request is None: <ide> request = app.request_class(environ) <del> self.request = request <add> self.request: Request = request <ide> self.url_adapter = None <ide> try: <ide> self.url_adapter = app.create_url_adapter(self.request) <ide> except HTTPException as e: <ide> self.request.routing_exception = e <del> self.flashes = None <del> self.session = session <add> self.flashes: t.Optional[t.List[t.Tuple[str, str]]] = None <add> self.session: t.Optional["SessionMixin"] = session <ide> # Functions that should be executed after the request on the response <ide> # object. These will be called before the regular "after_request" <ide> # functions. <ide><path>src/flask/debughelpers.py <ide> <ide> from .app import Flask <ide> from .blueprints import Blueprint <del>from .globals import _request_ctx_stack <add>from .globals import request_ctx <ide> <ide> <ide> class UnexpectedUnicodeError(AssertionError, UnicodeError): <ide> def explain_template_loading_attempts(app: Flask, template, attempts) -> None: <ide> info = [f"Locating template {template!r}:"] <ide> total_found = 0 <ide> blueprint = None <del> reqctx = _request_ctx_stack.top <del> if reqctx is not None and reqctx.request.blueprint is not None: <del> blueprint = reqctx.request.blueprint <add> if request_ctx and request_ctx.request.blueprint is not None: <add> blueprint = request_ctx.request.blueprint <ide> <ide> for idx, (loader, srcobj, triple) in enumerate(attempts): <ide> if isinstance(srcobj, Flask): <ide><path>src/flask/helpers.py <ide> from werkzeug.exceptions import abort as _wz_abort <ide> from werkzeug.utils import redirect as _wz_redirect <ide> <del>from .globals import _request_ctx_stack <add>from .globals import _cv_req <ide> from .globals import current_app <ide> from .globals import request <add>from .globals import request_ctx <ide> from .globals import session <ide> from .signals import message_flashed <ide> <ide> def decorator(*args: t.Any, **kwargs: t.Any) -> t.Any: <ide> return update_wrapper(decorator, generator_or_function) # type: ignore <ide> <ide> def generator() -> t.Generator: <del> ctx = _request_ctx_stack.top <add> ctx = _cv_req.get(None) <ide> if ctx is None: <ide> raise RuntimeError( <del> "Attempted to stream with context but " <del> "there was no context in the first place to keep around." <add> "'stream_with_context' can only be used when a request" <add> " context is active, such as in a view function." <ide> ) <ide> with ctx: <ide> # Dummy sentinel. Has to be inside the context block or we're <ide> def get_flashed_messages( <ide> :param category_filter: filter of categories to limit return values. Only <ide> categories in the list will be returned. <ide> """ <del> flashes = _request_ctx_stack.top.flashes <add> flashes = request_ctx.flashes <ide> if flashes is None: <del> _request_ctx_stack.top.flashes = flashes = ( <del> session.pop("_flashes") if "_flashes" in session else [] <del> ) <add> flashes = session.pop("_flashes") if "_flashes" in session else [] <add> request_ctx.flashes = flashes <ide> if category_filter: <ide> flashes = list(filter(lambda f: f[0] in category_filter, flashes)) <ide> if not with_categories: <ide><path>src/flask/templating.py <ide> from jinja2 import Template <ide> from jinja2 import TemplateNotFound <ide> <del>from .globals import _app_ctx_stack <del>from .globals import _request_ctx_stack <add>from .globals import _cv_app <add>from .globals import _cv_req <ide> from .globals import current_app <ide> from .globals import request <ide> from .helpers import stream_with_context <ide> def _default_template_ctx_processor() -> t.Dict[str, t.Any]: <ide> """Default template context processor. Injects `request`, <ide> `session` and `g`. <ide> """ <del> reqctx = _request_ctx_stack.top <del> appctx = _app_ctx_stack.top <del> rv = {} <add> appctx = _cv_app.get(None) <add> reqctx = _cv_req.get(None) <add> rv: t.Dict[str, t.Any] = {} <ide> if appctx is not None: <ide> rv["g"] = appctx.g <ide> if reqctx is not None: <ide> def list_templates(self) -> t.List[str]: <ide> return list(result) <ide> <ide> <del>def _render(template: Template, context: dict, app: "Flask") -> str: <add>def _render(app: "Flask", template: Template, context: t.Dict[str, t.Any]) -> str: <add> app.update_template_context(context) <ide> before_render_template.send(app, template=template, context=context) <ide> rv = template.render(context) <ide> template_rendered.send(app, template=template, context=context) <ide> def render_template( <ide> template_name_or_list: t.Union[str, Template, t.List[t.Union[str, Template]]], <ide> **context: t.Any <ide> ) -> str: <del> """Renders a template from the template folder with the given <del> context. <add> """Render a template by name with the given context. <ide> <del> :param template_name_or_list: the name of the template to be <del> rendered, or an iterable with template names <del> the first one existing will be rendered <del> :param context: the variables that should be available in the <del> context of the template. <add> :param template_name_or_list: The name of the template to render. If <add> a list is given, the first name to exist will be rendered. <add> :param context: The variables to make available in the template. <ide> """ <del> ctx = _app_ctx_stack.top <del> ctx.app.update_template_context(context) <del> return _render( <del> ctx.app.jinja_env.get_or_select_template(template_name_or_list), <del> context, <del> ctx.app, <del> ) <add> app = current_app._get_current_object() # type: ignore[attr-defined] <add> template = app.jinja_env.get_or_select_template(template_name_or_list) <add> return _render(app, template, context) <ide> <ide> <ide> def render_template_string(source: str, **context: t.Any) -> str: <del> """Renders a template from the given template source string <del> with the given context. Template variables will be autoescaped. <add> """Render a template from the given source string with the given <add> context. <ide> <del> :param source: the source code of the template to be <del> rendered <del> :param context: the variables that should be available in the <del> context of the template. <add> :param source: The source code of the template to render. <add> :param context: The variables to make available in the template. <ide> """ <del> ctx = _app_ctx_stack.top <del> ctx.app.update_template_context(context) <del> return _render(ctx.app.jinja_env.from_string(source), context, ctx.app) <add> app = current_app._get_current_object() # type: ignore[attr-defined] <add> template = app.jinja_env.from_string(source) <add> return _render(app, template, context) <ide> <ide> <ide> def _stream( <ide><path>src/flask/testing.py <ide> def session_transaction( <ide> # behavior. It's important to not use the push and pop <ide> # methods of the actual request context object since that would <ide> # mean that cleanup handlers are called <del> token = _cv_req.set(outer_reqctx) <add> token = _cv_req.set(outer_reqctx) # type: ignore[arg-type] <ide> try: <ide> yield sess <ide> finally: <ide><path>tests/conftest.py <ide> import pytest <ide> from _pytest import monkeypatch <ide> <del>import flask <del>from flask import Flask as _Flask <add>from flask import Flask <add>from flask.globals import request_ctx <ide> <ide> <ide> @pytest.fixture(scope="session", autouse=True) <ide> def _reset_os_environ(monkeypatch, _standard_os_environ): <ide> monkeypatch._setitem.extend(_standard_os_environ) <ide> <ide> <del>class Flask(_Flask): <del> testing = True <del> secret_key = "test key" <del> <del> <ide> @pytest.fixture <ide> def app(): <ide> app = Flask("flask_test", root_path=os.path.dirname(__file__)) <add> app.config.update( <add> TESTING=True, <add> SECRET_KEY="test key", <add> ) <ide> return app <ide> <ide> <ide> def leak_detector(): <ide> # make sure we're not leaking a request context since we are <ide> # testing flask internally in debug mode in a few cases <ide> leaks = [] <del> while flask._request_ctx_stack.top is not None: <del> leaks.append(flask._request_ctx_stack.pop()) <add> while request_ctx: <add> leaks.append(request_ctx._get_current_object()) <add> request_ctx.pop() <add> <ide> assert leaks == [] <ide> <ide> <ide><path>tests/test_appctx.py <ide> import pytest <ide> <ide> import flask <add>from flask.globals import app_ctx <add>from flask.globals import request_ctx <ide> <ide> <ide> def test_basic_url_generation(app): <ide> def test_url_generation_without_context_fails(): <ide> <ide> def test_request_context_means_app_context(app): <ide> with app.test_request_context(): <del> assert flask.current_app._get_current_object() == app <del> assert flask._app_ctx_stack.top is None <add> assert flask.current_app._get_current_object() is app <add> assert not flask.current_app <ide> <ide> <ide> def test_app_context_provides_current_app(app): <ide> with app.app_context(): <del> assert flask.current_app._get_current_object() == app <del> assert flask._app_ctx_stack.top is None <add> assert flask.current_app._get_current_object() is app <add> assert not flask.current_app <ide> <ide> <ide> def test_app_tearing_down(app): <ide> def teardown_app(error=None): <ide> <ide> @app.route("/") <ide> def index(): <del> with flask._app_ctx_stack.top: <del> with flask._request_ctx_stack.top: <add> with app_ctx: <add> with request_ctx: <ide> pass <del> env = flask._request_ctx_stack.top.request.environ <del> assert env["werkzeug.request"] is not None <add> <add> assert flask.request.environ["werkzeug.request"] is not None <ide> return "" <ide> <ide> res = client.get("/") <ide><path>tests/test_basic.py <ide> def test_enctype_debug_helper(app, client): <ide> def index(): <ide> return flask.request.files["foo"].filename <ide> <del> # with statement is important because we leave an exception on the <del> # stack otherwise and we want to ensure that this is not the case <del> # to not negatively affect other tests. <del> with client: <del> with pytest.raises(DebugFilesKeyError) as e: <del> client.post("/fail", data={"foo": "index.txt"}) <del> assert "no file contents were transmitted" in str(e.value) <del> assert "This was submitted: 'index.txt'" in str(e.value) <add> with pytest.raises(DebugFilesKeyError) as e: <add> client.post("/fail", data={"foo": "index.txt"}) <add> assert "no file contents were transmitted" in str(e.value) <add> assert "This was submitted: 'index.txt'" in str(e.value) <ide> <ide> <ide> def test_response_types(app, client): <ide> def subdomain(): <ide> assert rv.data == b"subdomain" <ide> <ide> <del>@pytest.mark.filterwarnings("ignore::pytest.PytestUnraisableExceptionWarning") <del>@pytest.mark.filterwarnings("ignore::pytest.PytestUnhandledThreadExceptionWarning") <del>def test_exception_propagation(app, client): <del> def apprunner(config_key): <del> @app.route("/") <del> def index(): <del> 1 // 0 <add>@pytest.mark.parametrize("key", ["TESTING", "PROPAGATE_EXCEPTIONS", "DEBUG", None]) <add>def test_exception_propagation(app, client, key): <add> app.testing = False <ide> <del> if config_key is not None: <del> app.config[config_key] = True <del> with pytest.raises(Exception): <del> client.get("/") <del> else: <del> assert client.get("/").status_code == 500 <del> <del> # we have to run this test in an isolated thread because if the <del> # debug flag is set to true and an exception happens the context is <del> # not torn down. This causes other tests that run after this fail <del> # when they expect no exception on the stack. <del> for config_key in "TESTING", "PROPAGATE_EXCEPTIONS", "DEBUG", None: <del> t = Thread(target=apprunner, args=(config_key,)) <del> t.start() <del> t.join() <add> @app.route("/") <add> def index(): <add> 1 // 0 <add> <add> if key is not None: <add> app.config[key] = True <add> <add> with pytest.raises(ZeroDivisionError): <add> client.get("/") <add> else: <add> assert client.get("/").status_code == 500 <ide> <ide> <ide> @pytest.mark.parametrize("debug", [True, False]) <ide><path>tests/test_reqctx.py <ide> import pytest <ide> <ide> import flask <add>from flask.globals import request_ctx <ide> from flask.sessions import SecureCookieSessionInterface <ide> from flask.sessions import SessionInterface <ide> <ide> def meh(): <ide> assert index() == "Hello World!" <ide> with app.test_request_context("/meh"): <ide> assert meh() == "http://localhost/meh" <del> assert flask._request_ctx_stack.top is None <add> assert not flask.request <ide> <ide> <ide> def test_context_test(app): <ide> def test_greenlet_context_copying(self, app, client): <ide> @app.route("/") <ide> def index(): <ide> flask.session["fizz"] = "buzz" <del> reqctx = flask._request_ctx_stack.top.copy() <add> reqctx = request_ctx.copy() <ide> <ide> def g(): <ide> assert not flask.request <ide><path>tests/test_session_interface.py <ide> import flask <add>from flask.globals import request_ctx <ide> from flask.sessions import SessionInterface <ide> <ide> <ide> def save_session(self, app, session, response): <ide> pass <ide> <ide> def open_session(self, app, request): <del> flask._request_ctx_stack.top.match_request() <add> request_ctx.match_request() <ide> assert request.endpoint is not None <ide> <ide> app = flask.Flask(__name__) <ide><path>tests/test_testing.py <ide> import flask <ide> from flask import appcontext_popped <ide> from flask.cli import ScriptInfo <add>from flask.globals import _cv_req <ide> from flask.json import jsonify <ide> from flask.testing import EnvironBuilder <ide> from flask.testing import FlaskCliRunner <ide> def index(): <ide> # close the response, releasing the context held by stream_with_context <ide> rv.close() <ide> # only req_ctx fixture should still be pushed <del> assert flask._request_ctx_stack.top is req_ctx <add> assert _cv_req.get(None) is req_ctx
13
Javascript
Javascript
support semver v2 version number format
7b203fcff6dd01da0bebb43130a0e861c05c4e9c
<ide><path>lib/grunt/utils.js <ide> module.exports = { <ide> if (version) return version; <ide> <ide> var package = JSON.parse(fs.readFileSync('package.json', 'UTF-8')); <del> // TODO(brian): change `(-|rc)` to `-` in the regex below after bower <del> // fixes this issue: https://github.com/bower/bower/issues/782 <del> var match = package.version.match(/^([^\-]*)(?:(-|rc)(.+))?$/); <add> var match = package.version.match(/^([^\-]*)(?:\-(.+))?$/); <ide> var semver = match[1].split('.'); <ide> var hash = shell.exec('git rev-parse --short HEAD', {silent: true}).output.replace('\n', ''); <ide> <del> var fullVersion = (match[1] + (match[2] ? '-' + hash : '')); <add> var fullVersion = match[1]; <add> <add> if (match[2]) { <add> fullVersion += '-'; <add> fullVersion += (match[2] == 'snapshot') ? hash : match[2]; <add> } <add> <ide> version = { <ide> full: fullVersion, <ide> major: semver[0],
1
Javascript
Javascript
add some missing attributes
203dba271b6128f03c99b1ce2f573a316adb4e4e
<ide><path>src/dom/DefaultDOMPropertyConfig.js <ide> var DefaultDOMPropertyConfig = { <ide> /** <ide> * Standard Properties <ide> */ <add> accessKey: null, <ide> accept: null, <ide> action: null, <ide> ajaxify: MUST_USE_ATTRIBUTE, <ide> allowFullScreen: MUST_USE_ATTRIBUTE | HAS_BOOLEAN_VALUE, <ide> alt: null, <ide> autoComplete: null, <add> autofocus: HAS_BOOLEAN_VALUE, <ide> autoplay: HAS_BOOLEAN_VALUE, <ide> cellPadding: null, <ide> cellSpacing: null, <ide> checked: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE, <ide> className: MUST_USE_PROPERTY, <ide> colSpan: null, <ide> contentEditable: null, <add> contextMenu: MUST_USE_ATTRIBUTE, <ide> controls: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE, <ide> data: null, // For `<object />` acts as `src`. <ide> dateTime: MUST_USE_ATTRIBUTE, <ide> var DefaultDOMPropertyConfig = { <ide> hidden: MUST_USE_ATTRIBUTE | HAS_BOOLEAN_VALUE, <ide> href: null, <ide> htmlFor: null, <add> icon: null, <ide> id: MUST_USE_PROPERTY, <add> label: null, <add> lang: null, <add> list: null, <ide> max: null, <add> maxLength: MUST_USE_ATTRIBUTE, <ide> method: null, <ide> min: null, <ide> multiple: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE, <ide> name: null, <add> pattern: null, <ide> poster: null, <ide> preload: null, <ide> placeholder: null, <add> radiogroup: null, <ide> rel: null, <add> readOnly: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE, <ide> required: HAS_BOOLEAN_VALUE, <ide> role: MUST_USE_ATTRIBUTE, <ide> scrollLeft: MUST_USE_PROPERTY, <ide> scrollTop: MUST_USE_PROPERTY, <ide> selected: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE, <add> size: null, <ide> spellCheck: null, <ide> src: null, <ide> step: null,
1
Javascript
Javascript
turn elements/index into an index
ac69e81b045350724f2bc2ff28ed5ccad2690a67
<ide><path>src/controllers/controller.bar.js <ide> import DatasetController from '../core/core.datasetController'; <ide> import defaults from '../core/core.defaults'; <del>import Rectangle from '../elements/element.rectangle'; <add>import {Rectangle} from '../elements/index'; <ide> import {clipArea, unclipArea} from '../helpers/helpers.canvas'; <ide> import {isArray, isNullOrUndef, valueOrDefault} from '../helpers/helpers.core'; <ide> import {_limitValue, sign} from '../helpers/helpers.math'; <ide><path>src/controllers/controller.bubble.js <ide> import DatasetController from '../core/core.datasetController'; <ide> import defaults from '../core/core.defaults'; <del>import Point from '../elements/element.point'; <add>import {Point} from '../elements/index'; <ide> import {resolve} from '../helpers/helpers.options'; <ide> <ide> defaults.set('bubble', { <ide><path>src/controllers/controller.doughnut.js <ide> import DatasetController from '../core/core.datasetController'; <ide> import defaults from '../core/core.defaults'; <del>import Arc from '../elements/element.arc'; <add>import {Arc} from '../elements/index'; <ide> import {isArray, valueOrDefault} from '../helpers/helpers.core'; <ide> <ide> /** <ide><path>src/controllers/controller.line.js <ide> import DatasetController from '../core/core.datasetController'; <ide> import defaults from '../core/core.defaults'; <del>import Line from '../elements/element.line'; <del>import Point from '../elements/element.point'; <add>import {Line, Point} from '../elements/index'; <ide> import {valueOrDefault} from '../helpers/helpers.core'; <ide> import {isNumber} from '../helpers/helpers.math'; <ide> import {resolve} from '../helpers/helpers.options'; <ide><path>src/controllers/controller.polarArea.js <ide> import DatasetController from '../core/core.datasetController'; <ide> import defaults from '../core/core.defaults'; <del>import Arc from '../elements/element.arc'; <add>import {Arc} from '../elements/index'; <ide> import {toRadians} from '../helpers/helpers.math'; <ide> import {resolve} from '../helpers/helpers.options'; <ide> <ide><path>src/controllers/controller.radar.js <ide> import DatasetController from '../core/core.datasetController'; <ide> import defaults from '../core/core.defaults'; <del>import Line from '../elements/element.line'; <del>import Point from '../elements/element.point'; <add>import {Line, Point} from '../elements/index'; <ide> import {valueOrDefault} from '../helpers/helpers.core'; <ide> <ide> defaults.set('radar', { <ide><path>src/elements/index.js <del>import Arc from './element.arc'; <del>import Line from './element.line'; <del>import Point from './element.point'; <del>import Rectangle from './element.rectangle'; <del> <del>export default { <del> Arc, <del> Line, <del> Point, <del> Rectangle <del>}; <add>export {default as Arc} from './element.arc'; <add>export {default as Line} from './element.line'; <add>export {default as Point} from './element.point'; <add>export {default as Rectangle} from './element.rectangle'; <ide><path>src/index.js <add>/* eslint-disable import/no-namespace, import/namespace */ <add> <ide> /** <ide> * @namespace Chart <ide> */ <ide> import controllers from './controllers/index'; <ide> import DatasetController from './core/core.datasetController'; <ide> import defaults from './core/core.defaults'; <ide> import Element from './core/core.element'; <del>import elements from './elements/index'; <add>import * as elements from './elements/index'; <ide> import Interaction from './core/core.interaction'; <ide> import layouts from './core/core.layouts'; <ide> import platforms from './platform/platforms'; <ide><path>test/specs/global.namespace.tests.js <ide> describe('Chart namespace', function() { <ide> }); <ide> <ide> describe('Chart.elements', function() { <del> it('should be an object', function() { <del> expect(Chart.elements instanceof Object).toBeTruthy(); <del> }); <ide> it('should contains "elements" classes', function() { <ide> expect(Chart.elements.Arc instanceof Function).toBeTruthy(); <ide> expect(Chart.elements.Line instanceof Function).toBeTruthy();
9
Javascript
Javascript
fix the redeclaration and fix performance
58dd3acf92d2bd6693501df2b50f953e72cf1b38
<ide><path>src/renderers/WebGLRenderer.js <ide> THREE.WebGLRenderer = function ( parameters ) { <ide> var gonnaUse = []; <ide> <ide> for ( i = 0; i < il; i ++ ) { <del> var candidateInfluence = influences[ i ] <add> candidateInfluence = influences[ i ] <ide> if ( candidateInfluence > 0 ) { <ide> gonnaUse.push(i); <ide> }
1
Text
Text
add tunniclm as a collaborator
5579e859f72a921558a053e9eddb0d9b3e09bc59
<ide><path>README.md <ide> information about the governance of the Node.js project, see <ide> * [thefourtheye](https://github.com/thefourtheye) - **Sakthipriyan Vairamani** &lt;[email protected]&gt; <ide> * [thlorenz](https://github.com/thlorenz) - **Thorsten Lorenz** &lt;[email protected]&gt; <ide> * [Trott](https://github.com/Trott) - **Rich Trott** &lt;[email protected]&gt; <add>* [tunniclm](https://github.com/tunniclm) - **Mike Tunnicliffe** &lt;[email protected]&gt; <ide> * [vkurchatkin](https://github.com/vkurchatkin) - **Vladimir Kurchatkin** &lt;[email protected]&gt; <ide> * [yosuke-furukawa](https://github.com/yosuke-furukawa) - **Yosuke Furukawa** &lt;[email protected]&gt; <ide>
1
Javascript
Javascript
fix the versions script
2b741dc8b8568bab1a687ac14eefbae126654e97
<ide><path>lib/versions/version-info.js <ide> var getTaggedVersion = function() { <ide> var gitTagResult = shell.exec('git describe --exact-match', {silent:true}); <ide> <ide> if ( gitTagResult.code === 0 ) { <del> var tag = gitTagResult.output; <add> var tag = gitTagResult.output.trim(); <ide> var version = semver.parse(tag); <del> if ( version ) { <del> if ( version.satisfies(currentPackage.branchVersion) ) { <del> version.codeName = getCodeName(tag); <del> } <add> <add> if ( version && semver.satisfies(version, currentPackage.branchVersion)) { <add> version.codeName = getCodeName(tag); <ide> version.full = version.version + '+' + version.build; <ide> return version; <ide> } <ide> } <add> <add> return null; <ide> }; <ide> <ide> /**
1
Text
Text
fix debugging rails application [ci skip]
b44b3932438a5fc794e9d6711bc76c2f3f35aa8f
<ide><path>guides/source/debugging_rails_applications.md <ide> class ArticlesController < ApplicationController <ide> # ... <ide> <ide> def create <del> @article = Article.new(params[:article]) <add> @article = Article.new(article_params) <ide> logger.debug "New article: #{@article.attributes.inspect}" <ide> logger.debug "Article should be valid: #{@article.valid?}" <ide> <ide> if @article.save <del> flash[:notice] = 'Article was successfully created.' <ide> logger.debug "The article was saved and now the user is going to be redirected..." <del> redirect_to(@article) <add> redirect_to @article, notice: 'Article was successfully created.' <ide> else <del> render action: "new" <add> render :new <ide> end <ide> end <ide> <ide> # ... <add> <add> private <add> def article_params <add> params.require(:article).permit(:title, :body, :published) <add> end <ide> end <ide> ``` <ide> <ide> command later in this guide). <ide> 9 <ide> => 10 respond_to do |format| <ide> 11 format.html # index.html.erb <del> 12 format.json { render json: @articles } <add> 12 format.json { render json: @articles } <ide> 13 end <ide> 14 end <ide> 15
1
Javascript
Javascript
add some comments
486dabaaf9193a2e141a744c34e17d976f2f6ed9
<ide><path>src/chart/bullet.js <ide> d3.chart.bullet = function() { <ide> return reversed ? function(d) { return width - scale(d); } : 0; <ide> }; <ide> <add> // Update the title. <ide> var titleText = g.selectAll('text.title') <ide> .data(d3_chart_title); <ide> <ide> d3.chart.bullet = function() { <ide> titleText <ide> .text(d3_chart_identity); <ide> <add> // Update the subtitle. <ide> var subtitleText = g.selectAll('text.subtitle') <ide> .data(d3_chart_subtitle); <ide> <ide> d3.chart.bullet = function() { <ide> subtitleText <ide> .text(d3_chart_identity); <ide> <add> // Update the chart. <ide> g.selectAll('g.chart') <ide> .data(d3_chart_bulletChart) <ide> .enter().append("svg:g")
1
PHP
PHP
fix custom keys in belongstomany
cbdfd0a5c44425db21df3086ba95a10514cd1830
<ide><path>src/ORM/Association/BelongsToMany.php <ide> public function junction($table = null) <ide> ]); <ide> } <ide> <add> if (!$source->association($junctionAlias)) { <add> $source->hasMany($junctionAlias, [ <add> 'targetTable' => $table, <add> 'foreignKey' => $this->foreignKey(), <add> ]); <add> } <add> <ide> if (!$target->association($sAlias)) { <ide> $target->belongsToMany($sAlias, [ <ide> 'sourceTable' => $target, <ide> public function junction($table = null) <ide> ]); <ide> } <ide> <del> if (!$source->association($table->alias())) { <del> $source->hasMany($junctionAlias)->target($table); <del> } <del> <ide> return $this->_junctionTable = $table; <ide> } <ide> <ide><path>tests/TestCase/ORM/Association/BelongsToManyTest.php <ide> public function testJunction() <ide> $this->assertSame($junction, $assoc->junction()); <ide> } <ide> <add> /** <add> * Tests the junction method custom keys <add> * <add> * @return void <add> */ <add> public function testJunctionCustomKeys() <add> { <add> $this->article->belongsToMany('Tags', [ <add> 'joinTable' => 'articles_tags', <add> 'foreignKey' => 'article', <add> 'targetForeignKey' => 'tag' <add> ]); <add> $this->tag->belongsToMany('Articles', [ <add> 'joinTable' => 'articles_tags', <add> 'foreignKey' => 'tag', <add> 'targetForeignKey' => 'article' <add> ]); <add> $junction = $this->article->association('Tags')->junction(); <add> $this->assertEquals('article', $junction->association('Articles')->foreignKey()); <add> $this->assertEquals('article', $this->article->association('ArticlesTags')->foreignKey()); <add> <add> $junction = $this->tag->association('Articles')->junction(); <add> $this->assertEquals('tag', $junction->association('Tags')->foreignKey()); <add> $this->assertEquals('tag', $this->tag->association('ArticlesTags')->foreignKey()); <add> } <add> <ide> /** <ide> * Tests it is possible to set the table name for the join table <ide> * <ide><path>tests/TestCase/ORM/QueryRegressionTest.php <ide> public function testReciprocalBelongsToMany() <ide> * <ide> * @return void <ide> */ <del> public function testReciprocalBelongsToMany2() <add> public function testReciprocalBelongsToManyNoOverwrite() <ide> { <ide> $articles = TableRegistry::get('Articles'); <ide> $tags = TableRegistry::get('Tags');
3
Python
Python
add exceptions for `fit_loop`
a80ecd78daf7d464a6ff915111f62b8cd21c8b6b
<ide><path>keras/engine/training_arrays.py <ide> def fit_loop(model, f, ins, <ide> 'when doing step-wise ' <ide> 'training, i.e. `steps_per_epoch` ' <ide> 'must be set.') <add> elif do_validation: <add> if steps_per_epoch: <add> raise ValueError('Must specify `validation_steps` ' <add> 'to perform validation ' <add> 'when doing step-wise training.') <ide> <ide> num_train_samples = check_num_samples(ins, <ide> batch_size=batch_size,
1
Javascript
Javascript
use abortcontroller with correct name/message
5d179cb2eccac38205b6f03ecf6403df65deea51
<ide><path>lib/timers/promises.js <ide> const { <ide> <ide> let DOMException; <ide> <del>const lazyDOMException = hideStackFrames((message) => { <add>const lazyDOMException = hideStackFrames((message, name) => { <ide> if (DOMException === undefined) <ide> DOMException = internalBinding('messaging').DOMException; <del> return new DOMException(message); <add> return new DOMException(message, name); <ide> }); <ide> <ide> function setTimeout(after, value, options = {}) { <ide> function setTimeout(after, value, options = {}) { <ide> // TODO(@jasnell): If a decision is made that this cannot be backported <ide> // to 12.x, then this can be converted to use optional chaining to <ide> // simplify the check. <del> if (signal && signal.aborted) <del> return PromiseReject(lazyDOMException('AbortError')); <add> if (signal && signal.aborted) { <add> return PromiseReject( <add> lazyDOMException('The operation was aborted', 'AbortError')); <add> } <ide> return new Promise((resolve, reject) => { <ide> const timeout = new Timeout(resolve, after, args, false, true); <ide> if (!ref) timeout.unref(); <ide> function setTimeout(after, value, options = {}) { <ide> if (!timeout._destroyed) { <ide> // eslint-disable-next-line no-undef <ide> clearTimeout(timeout); <del> reject(lazyDOMException('AbortError')); <add> reject(lazyDOMException('The operation was aborted', 'AbortError')); <ide> } <ide> }, { once: true }); <ide> } <ide> function setImmediate(value, options = {}) { <ide> // TODO(@jasnell): If a decision is made that this cannot be backported <ide> // to 12.x, then this can be converted to use optional chaining to <ide> // simplify the check. <del> if (signal && signal.aborted) <del> return PromiseReject(lazyDOMException('AbortError')); <add> if (signal && signal.aborted) { <add> return PromiseReject( <add> lazyDOMException('The operation was aborted', 'AbortError')); <add> } <ide> return new Promise((resolve, reject) => { <ide> const immediate = new Immediate(resolve, [value]); <ide> if (!ref) immediate.unref(); <ide> function setImmediate(value, options = {}) { <ide> if (!immediate._destroyed) { <ide> // eslint-disable-next-line no-undef <ide> clearImmediate(immediate); <del> reject(lazyDOMException('AbortError')); <add> reject(lazyDOMException('The operation was aborted', 'AbortError')); <ide> } <ide> }, { once: true }); <ide> }
1
Python
Python
fix gpu evaluation
bbb59e371c2060504ea5548a3a440b1b093fde9b
<ide><path>spacy/train.py <ide> def _epoch(indices): <ide> self.nr_epoch += 1 <ide> <ide> def evaluate(self, dev_sents, gold_preproc=False): <del> scorer = Scorer() <add> all_docs = [] <add> all_golds = [] <ide> for raw_text, paragraph_tuples in dev_sents: <ide> if gold_preproc: <ide> raw_text = None <ide> else: <ide> paragraph_tuples = merge_sents(paragraph_tuples) <ide> docs = self.make_docs(raw_text, paragraph_tuples) <ide> golds = self.make_golds(docs, paragraph_tuples) <del> for doc, gold in zip(docs, golds): <del> state = {} <del> for process in self.nlp.pipeline: <del> assert state is not None, process.name <del> state = process(doc, state=state) <del> scorer.score(doc, gold) <add> all_docs.extend(docs) <add> all_golds.extend(golds) <add> scorer = Scorer() <add> for doc, gold in zip(self.nlp.pipe(all_docs), all_golds): <add> scorer.score(doc, gold) <ide> return scorer <ide> <ide> def make_docs(self, raw_text, paragraph_tuples):
1
Javascript
Javascript
add basic missing docs for the $aria service
bf2c55ea297cc55786593dd4100468b7103df0ca
<ide><path>src/ngAria/aria.js <ide> var ngAriaModule = angular.module('ngAria', ['ng']). <ide> * Used for configuring aria attributes. <ide> * <ide> * ## Dependencies <del> * Requires the {@link ngAria `ngAria`} module to be installed. <add> * Requires the {@link ngAria} module to be installed. <ide> */ <ide> function $AriaProvider() { <ide> var config = { <ide> function $AriaProvider() { <ide> }; <ide> } <ide> <add> /** <add> * @ngdoc service <add> * @name $aria <add> * <add> * @description <add> * <add> * Contains helper methods for applying aria tags to HTML <add> * <add> * ## Dependencies <add> * Requires the {@link ngAria} module to be installed. <add> */ <ide> this.$get = function() { <ide> return { <ide> watchExpr: watchExpr,
1
PHP
PHP
fix fatal error when checking for phpunit
7107cd663142fe79b98fde39529516344e729685
<ide><path>lib/Cake/Console/Shell.php <ide> public function createFile($path, $contents) { <ide> * @return boolean Success <ide> */ <ide> protected function _checkUnitTest() { <del> if (App::import('Vendor', 'phpunit', array('file' => 'PHPUnit' . DS . 'Autoload.php'))) { <add> if (class_exists('PHPUnit_Framework_TestCase')) { <ide> return true; <del> } <del> if (@include 'PHPUnit' . DS . 'Autoload.php') { <add> } elseif (@include 'PHPUnit' . DS . 'Autoload.php') { <add> return true; <add> } elseif (App::import('Vendor', 'phpunit', array('file' => 'PHPUnit' . DS . 'Autoload.php'))) { <ide> return true; <ide> } <add> <ide> $prompt = __d('cake_console', 'PHPUnit is not installed. Do you want to bake unit test files anyway?'); <ide> $unitTest = $this->in($prompt, array('y', 'n'), 'y'); <ide> $result = strtolower($unitTest) == 'y' || strtolower($unitTest) == 'yes';
1
Ruby
Ruby
move paths to utils
a126946a9be8a1915ce516a674ffe4663583f691
<ide><path>Library/Homebrew/cmd/commands.rb <ide> module Homebrew extend self <del> def paths <del> @paths ||= ENV['PATH'].split(File::PATH_SEPARATOR).collect do |p| <del> begin <del> File.expand_path(p).chomp('/') <del> rescue ArgumentError <del> onoe "The following PATH component is invalid: #{p}" <del> end <del> end.uniq.compact <del> end <del> <ide> def commands <ide> # Find commands in Homebrew/cmd <ide> cmds = (HOMEBREW_REPOSITORY/"Library/Homebrew/cmd"). <ide><path>Library/Homebrew/cmd/doctor.rb <ide> def get_mounts path=nil <ide> class Checks <ide> <ide> ############# HELPERS <del> def paths <del> @paths ||= ENV['PATH'].split(File::PATH_SEPARATOR).collect do |p| <del> begin <del> File.expand_path(p).chomp('/') <del> rescue ArgumentError <del> onoe "The following PATH component is invalid: #{p}" <del> end <del> end.uniq.compact <del> end <del> <ide> # Finds files in HOMEBREW_PREFIX *and* /usr/local. <ide> # Specify paths relative to a prefix eg. "include/foo.h". <ide> # Sets @found for your convenience. <ide><path>Library/Homebrew/utils.rb <ide> def nostdout <ide> end <ide> end <ide> <add>def paths <add> @paths ||= ENV['PATH'].split(File::PATH_SEPARATOR).collect do |p| <add> begin <add> File.expand_path(p).chomp('/') <add> rescue ArgumentError <add> onoe "The following PATH component is invalid: #{p}" <add> end <add> end.uniq.compact <add>end <add> <ide> module GitHub extend self <ide> ISSUES_URI = URI.parse("https://api.github.com/legacy/issues/search/mxcl/homebrew/open/") <ide>
3
Ruby
Ruby
fix tiny grammatical mistakes[skip ci]
4e2d55e1aabefecd51a5fec244837edfb0dab169
<ide><path>activejob/lib/active_job/test_helper.rb <ide> def queue_adapter_for_test <ide> # end <ide> # end <ide> # <del> # +:only+ and +:except+ options accepts Class, Array of Class or Proc. When passed a Proc, <add> # +:only+ and +:except+ options accept Class, Array of Class or Proc. When passed a Proc, <ide> # a hash containing the job's class and it's argument are passed as argument. <ide> # <ide> # Asserts the number of times a job is enqueued to a specific queue by passing +:queue+ option. <ide> def assert_enqueued_jobs(number, only: nil, except: nil, queue: nil, &block) <ide> # end <ide> # end <ide> # <del> # +:only+ and +:except+ options accepts Class, Array of Class or Proc. When passed a Proc, <add> # +:only+ and +:except+ options accept Class, Array of Class or Proc. When passed a Proc, <ide> # a hash containing the job's class and it's argument are passed as argument. <ide> # <ide> # Asserts that no jobs are enqueued to a specific queue by passing +:queue+ option <ide> def assert_performed_jobs(number, only: nil, except: nil, queue: nil, &block) <ide> # end <ide> # end <ide> # <del> # +:only+ and +:except+ options accepts Class, Array of Class or Proc. When passed a Proc, <add> # +:only+ and +:except+ options accept Class, Array of Class or Proc. When passed a Proc, <ide> # an instance of the job will be passed as argument. <ide> # <ide> # If the +:queue+ option is specified, <ide> def assert_performed_with(job: nil, args: nil, at: nil, queue: nil, priority: ni <ide> # assert_performed_jobs 1 <ide> # end <ide> # <del> # +:only+ and +:except+ options accepts Class, Array of Class or Proc. When passed a Proc, <add> # +:only+ and +:except+ options accept Class, Array of Class or Proc. When passed a Proc, <ide> # an instance of the job will be passed as argument. <ide> # <ide> # If the +:queue+ option is specified,
1
Javascript
Javascript
remove copy & copyable
f6cb99ee41910d06a6f1edea420947e5f89712ce
<ide><path>packages/@ember/-internals/runtime/index.js <ide> export { default as Object, FrameworkObject } from './lib/system/object'; <ide> export { default as RegistryProxyMixin } from './lib/mixins/registry_proxy'; <ide> export { default as ContainerProxyMixin } from './lib/mixins/container_proxy'; <del>export { default as copy } from './lib/copy'; <ide> export { default as compare } from './lib/compare'; <ide> export { default as isEqual } from './lib/is-equal'; <ide> export { <ide> export { default as ArrayProxy } from './lib/system/array_proxy'; <ide> export { default as ObjectProxy } from './lib/system/object_proxy'; <ide> export { default as CoreObject } from './lib/system/core_object'; <ide> export { default as ActionHandler } from './lib/mixins/action_handler'; <del>export { default as Copyable } from './lib/mixins/copyable'; <ide> export { default as Enumerable } from './lib/mixins/enumerable'; <ide> export { default as _ProxyMixin, contentFor as _contentFor } from './lib/mixins/-proxy'; <ide> export { default as Observable } from './lib/mixins/observable'; <ide><path>packages/@ember/-internals/runtime/lib/copy.js <del>import { assert, deprecate } from '@ember/debug'; <del>import EmberObject from './system/object'; <del>import Copyable from './mixins/copyable'; <del> <del>/** <del> @module @ember/object <del>*/ <del>function _copy(obj, deep, seen, copies) { <del> // primitive data types are immutable, just return them. <del> if (typeof obj !== 'object' || obj === null) { <del> return obj; <del> } <del> <del> let ret, loc; <del> <del> // avoid cyclical loops <del> if (deep && (loc = seen.indexOf(obj)) >= 0) { <del> return copies[loc]; <del> } <del> <del> if (deep) { <del> seen.push(obj); <del> } <del> <del> // IMPORTANT: this specific test will detect a native array only. Any other <del> // object will need to implement Copyable. <del> if (Array.isArray(obj)) { <del> ret = obj.slice(); <del> <del> if (deep) { <del> copies.push(ret); <del> loc = ret.length; <del> <del> while (--loc >= 0) { <del> ret[loc] = _copy(ret[loc], deep, seen, copies); <del> } <del> } <del> } else if (Copyable.detect(obj)) { <del> ret = obj.copy(deep, seen, copies); <del> if (deep) { <del> copies.push(ret); <del> } <del> } else if (obj instanceof Date) { <del> ret = new Date(obj.getTime()); <del> if (deep) { <del> copies.push(ret); <del> } <del> } else { <del> assert( <del> 'Cannot clone an EmberObject that does not implement Copyable', <del> !(obj instanceof EmberObject) || Copyable.detect(obj) <del> ); <del> <del> ret = {}; <del> if (deep) { <del> copies.push(ret); <del> } <del> <del> let key; <del> for (key in obj) { <del> // support Null prototype <del> if (!Object.prototype.hasOwnProperty.call(obj, key)) { <del> continue; <del> } <del> <del> // Prevents browsers that don't respect non-enumerability from <del> // copying internal Ember properties <del> if (key.substring(0, 2) === '__') { <del> continue; <del> } <del> <del> ret[key] = deep ? _copy(obj[key], deep, seen, copies) : obj[key]; <del> } <del> } <del> <del> return ret; <del>} <del> <del>/** <del> Creates a shallow copy of the passed object. A deep copy of the object is <del> returned if the optional `deep` argument is `true`. <del> <del> If the passed object implements the `Copyable` interface, then this <del> function will delegate to the object's `copy()` method and return the <del> result. See `Copyable` for further details. <del> <del> For primitive values (which are immutable in JavaScript), the passed object <del> is simply returned. <del> <del> @method copy <del> @deprecated Use 'ember-copy' addon instead <del> @static <del> @for @ember/object/internals <del> @param {Object} obj The object to clone <del> @param {Boolean} [deep=false] If true, a deep copy of the object is made. <del> @return {Object} The copied object <del> @public <del>*/ <del>export default function copy(obj, deep) { <del> deprecate('Use ember-copy addon instead of copy method and Copyable mixin.', false, { <del> id: 'ember-runtime.deprecate-copy-copyable', <del> until: '4.0.0', <del> url: 'https://deprecations.emberjs.com/v3.x/#toc_ember-runtime-deprecate-copy-copyable', <del> for: 'ember-source', <del> since: { <del> enabled: '3.3.0', <del> }, <del> }); <del> <del> // fast paths <del> if ('object' !== typeof obj || obj === null) { <del> return obj; // can't copy primitives <del> } <del> <del> if (!Array.isArray(obj) && Copyable.detect(obj)) { <del> return obj.copy(deep); <del> } <del> <del> return _copy(obj, deep, deep ? [] : null, deep ? [] : null); <del>} <ide><path>packages/@ember/-internals/runtime/lib/mixins/copyable.js <del>/** <del>@module ember <del>*/ <del> <del>import { Mixin } from '@ember/-internals/metal'; <del> <del>/** <del> Implements some standard methods for copying an object. Add this mixin to <del> any object you create that can create a copy of itself. This mixin is <del> added automatically to the built-in array. <del> <del> You should generally implement the `copy()` method to return a copy of the <del> receiver. <del> <del> @class Copyable <del> @namespace Ember <del> @since Ember 0.9 <del> @deprecated Use 'ember-copy' addon instead <del> @private <del>*/ <del>export default Mixin.create({ <del> /** <del> __Required.__ You must implement this method to apply this mixin. <del> <del> Override to return a copy of the receiver. Default implementation raises <del> an exception. <del> <del> @method copy <del> @param {Boolean} deep if `true`, a deep copy of the object should be made <del> @return {Object} copy of receiver <del> @private <del> */ <del> copy: null, <del>}); <ide><path>packages/@ember/-internals/runtime/tests/copyable-array/copy-test.js <del>import { AbstractTestCase } from 'internal-test-helpers'; <del>import { runArrayTests } from '../helpers/array'; <del> <del>class CopyTest extends AbstractTestCase { <del> '@test should return an equivalent copy'() { <del> let obj = this.newObject(); <del> let copy = obj.copy(); <del> this.assert.ok(this.isEqual(obj, copy), 'old object and new object should be equivalent'); <del> } <del>} <del> <del>runArrayTests('copy', CopyTest, 'CopyableNativeArray', 'CopyableArray'); <ide><path>packages/@ember/-internals/runtime/tests/core/copy_test.js <del>import copy from '../../lib/copy'; <del>import { moduleFor, AbstractTestCase } from 'internal-test-helpers'; <del> <del>moduleFor( <del> 'Ember Copy Method', <del> class extends AbstractTestCase { <del> ['@test Ember.copy null'](assert) { <del> let obj = { field: null }; <del> let copied = null; <del> expectDeprecation(() => { <del> copied = copy(obj, true); <del> }, 'Use ember-copy addon instead of copy method and Copyable mixin.'); <del> assert.equal(copied.field, null, 'null should still be null'); <del> } <del> <del> ['@test Ember.copy date'](assert) { <del> let date = new Date(2014, 7, 22); <del> let dateCopy = null; <del> expectDeprecation(() => { <del> dateCopy = copy(date); <del> }, 'Use ember-copy addon instead of copy method and Copyable mixin.'); <del> assert.equal(date.getTime(), dateCopy.getTime(), 'dates should be equivalent'); <del> } <del> <del> ['@test Ember.copy null prototype object'](assert) { <del> let obj = Object.create(null); <del> <del> obj.foo = 'bar'; <del> let copied = null; <del> expectDeprecation(() => { <del> copied = copy(obj); <del> }, 'Use ember-copy addon instead of copy method and Copyable mixin.'); <del> <del> assert.equal(copied.foo, 'bar', 'bar should still be bar'); <del> } <del> <del> ['@test Ember.copy Array'](assert) { <del> let array = [1, null, new Date(2015, 9, 9), 'four']; <del> let arrayCopy = null; <del> expectDeprecation(() => { <del> arrayCopy = copy(array); <del> }, 'Use ember-copy addon instead of copy method and Copyable mixin.'); <del> <del> assert.deepEqual(array, arrayCopy, 'array content cloned successfully in new array'); <del> } <del> <del> ['@test Ember.copy cycle detection'](assert) { <del> let obj = { <del> foo: { <del> bar: 'bar', <del> }, <del> }; <del> obj.foo.foo = obj.foo; <del> let cycleCopy = null; <del> expectDeprecation(() => { <del> cycleCopy = copy(obj, true); <del> }, 'Use ember-copy addon instead of copy method and Copyable mixin.'); <del> <del> assert.equal(cycleCopy.foo.bar, 'bar'); <del> assert.notEqual(cycleCopy.foo.foo, obj.foo.foo); <del> assert.strictEqual(cycleCopy.foo.foo, cycleCopy.foo.foo); <del> } <del> } <del>); <ide><path>packages/@ember/-internals/runtime/tests/helpers/array.js <ide> import EmberArray, { A as emberA, MutableArray } from '../../lib/mixins/array'; <ide> import { generateGuid, guidFor } from '@ember/-internals/utils'; <ide> import { <ide> get, <del> set, <ide> computed, <ide> addArrayObserver, <ide> removeArrayObserver, <ide> arrayContentWillChange, <ide> arrayContentDidChange, <ide> } from '@ember/-internals/metal'; <ide> import EmberObject from '../../lib/system/object'; <del>import Copyable from '../../lib/mixins/copyable'; <ide> import { moduleFor } from 'internal-test-helpers'; <ide> <ide> export function newFixture(cnt) { <ide> class NativeArrayHelpers extends AbstractArrayHelper { <ide> } <ide> } <ide> <del>class CopyableNativeArray extends AbstractArrayHelper { <del> newObject() { <del> return emberA([generateGuid()]); <del> } <del> <del> isEqual(a, b) { <del> if (!(a instanceof Array)) { <del> return false; <del> } <del> <del> if (!(b instanceof Array)) { <del> return false; <del> } <del> <del> if (a.length !== b.length) { <del> return false; <del> } <del> <del> return a[0] === b[0]; <del> } <del>} <del> <del>class CopyableArray extends AbstractArrayHelper { <del> newObject() { <del> return CopyableObject.create(); <del> } <del> <del> isEqual(a, b) { <del> if (!(a instanceof CopyableObject) || !(b instanceof CopyableObject)) { <del> return false; <del> } <del> <del> return get(a, 'id') === get(b, 'id'); <del> } <del>} <del> <ide> class ArrayProxyHelpers extends AbstractArrayHelper { <ide> newObject(ary) { <ide> return ArrayProxy.create({ content: emberA(super.newObject(ary)) }); <ide> const TestMutableArray = EmberObject.extend(MutableArray, { <ide> }, <ide> }); <ide> <del>const CopyableObject = EmberObject.extend(Copyable, { <del> id: null, <del> <del> init() { <del> this._super(...arguments); <del> set(this, 'id', generateGuid()); <del> }, <del> <del> copy() { <del> let ret = CopyableObject.create(); <del> set(ret, 'id', get(this, 'id')); <del> return ret; <del> }, <del>}); <del> <ide> class MutableArrayHelpers extends NativeArrayHelpers { <ide> newObject(ary) { <ide> return TestMutableArray.create(super.newObject(ary)); <ide> export function runArrayTests(name, Tests, ...types) { <ide> case 'MutableArray': <ide> moduleFor(`MutableArray: ${name}`, Tests, MutableArrayHelpers); <ide> break; <del> case 'CopyableArray': <del> moduleFor(`CopyableArray: ${name}`, Tests, CopyableArray); <del> break; <del> case 'CopyableNativeArray': <del> moduleFor(`CopyableNativeArray: ${name}`, Tests, CopyableNativeArray); <del> break; <ide> case 'NativeArray': <ide> moduleFor(`NativeArray: ${name}`, Tests, NativeArrayHelpers); <ide> break; <add> default: <add> throw new Error(`runArrayTests passed unexpected type ${type}`); <ide> } <ide> }); <ide> } else { <ide><path>packages/@ember/object/internals.js <ide> export { getCachedValueFor as cacheFor } from '@ember/-internals/metal'; <del>export { copy } from '@ember/-internals/runtime'; <ide> export { guidFor } from '@ember/-internals/utils'; <ide><path>packages/ember/index.js <ide> import { <ide> RegistryProxyMixin, <ide> ContainerProxyMixin, <ide> compare, <del> copy, <ide> isEqual, <ide> Array as EmberArray, <del> Copyable, <ide> MutableEnumerable, <ide> MutableArray, <ide> TargetActionSupport, <ide> Ember.Object = EmberObject; <ide> Ember._RegistryProxyMixin = RegistryProxyMixin; <ide> Ember._ContainerProxyMixin = ContainerProxyMixin; <ide> Ember.compare = compare; <del>Ember.copy = copy; <ide> Ember.isEqual = isEqual; <ide> <ide> /** <ide> Ember.ObjectProxy = ObjectProxy; <ide> Ember.ActionHandler = ActionHandler; <ide> Ember.CoreObject = CoreObject; <ide> Ember.NativeArray = NativeArray; <del>Ember.Copyable = Copyable; <ide> Ember.MutableEnumerable = MutableEnumerable; <ide> Ember.MutableArray = MutableArray; <ide> Ember.Evented = Evented; <ide><path>packages/ember/tests/reexports_test.js <ide> let allExports = [ <ide> <ide> // @ember/object/internals <ide> ['cacheFor', '@ember/object/internals', 'cacheFor'], <del> ['copy', '@ember/object/internals', 'copy'], <ide> ['guidFor', '@ember/object/internals', 'guidFor'], <ide> <ide> // @ember/object/mixin <ide> let allExports = [ <ide> ['Comparable', '@ember/-internals/runtime'], <ide> ['ActionHandler', '@ember/-internals/runtime'], <ide> ['NativeArray', '@ember/-internals/runtime'], <del> ['Copyable', '@ember/-internals/runtime'], <ide> ['MutableEnumerable', '@ember/-internals/runtime'], <ide> EMBER_MODERNIZED_BUILT_IN_COMPONENTS <ide> ? null <ide><path>tests/docs/expected.js <ide> module.exports = { <ide> 'controller', <ide> 'controllerFor', <ide> 'controllerName', <del> 'copy', <ide> 'create', <ide> 'createCache', <ide> 'current-when',
10
Ruby
Ruby
add support for namespaced validators
2650742bd02e108bc4ccdc59efa54b4916e3a443
<ide><path>activemodel/lib/active_model/validations/validates.rb <ide> module ClassMethods <ide> # validates :name, :title => true <ide> # end <ide> # <add> # Additionally validator classes may be in another namespace and still used within any class. <add> # <add> # validates :name, :'file/title' => true <add> # <ide> # The validators hash can also handle regular expressions, ranges, <ide> # arrays and strings in shortcut form, e.g. <ide> # <ide> def validates(*attributes) <ide> defaults.merge!(:attributes => attributes) <ide> <ide> validations.each do |key, options| <add> key = "#{key.to_s.camelize}Validator" <add> <ide> begin <del> validator = const_get("#{key.to_s.camelize}Validator") <add> validator = key.include?('::') ? key.constantize : const_get(key) <ide> rescue NameError <ide> raise ArgumentError, "Unknown validator: '#{key}'" <ide> end <ide><path>activemodel/test/cases/validations/validates_test.rb <ide> require 'models/person' <ide> require 'models/person_with_validator' <ide> require 'validators/email_validator' <add>require 'validators/namespace/email_validator' <ide> <ide> class ValidatesTest < ActiveModel::TestCase <ide> setup :reset_callbacks <ide> def test_validates_with_validator_class <ide> assert_equal ['is not an email'], person.errors[:karma] <ide> end <ide> <add> def test_validates_with_namespaced_validator_class <add> Person.validates :karma, :'namespace/email' => true <add> person = Person.new <add> person.valid? <add> assert_equal ['is not an email'], person.errors[:karma] <add> end <add> <ide> def test_validates_with_if_as_local_conditions <ide> Person.validates :karma, :presence => true, :email => { :unless => :condition_is_true } <ide> person = Person.new <ide><path>activemodel/test/validators/namespace/email_validator.rb <add>require 'validators/email_validator' <add> <add>module Namespace <add> class EmailValidator < ::EmailValidator <add> end <add>end
3
Javascript
Javascript
fix issue with rtl locales and zoomscale
bc7b5c3011460935614a47a03cd077cd1059de72
<ide><path>Libraries/Lists/VirtualizedList.js <ide> class VirtualizedList extends React.PureComponent<Props, State> { <ide> this._hasWarned.perf = true; <ide> } <ide> <del> const zoomScale = e.nativeEvent.zoomScale; <del> <add> // For invalid negative values (w/ RTL), set this to 1. <add> const zoomScale = e.nativeEvent.zoomScale < 0 ? 1 : e.nativeEvent.zoomScale; <ide> this._scrollMetrics = { <ide> contentLength, <ide> dt,
1
PHP
PHP
fix bug in validation unique method
fd446aec624ff607e07c3d0f3aa38fbdfc40dd41
<ide><path>laravel/validator.php <ide> protected function validate_unique($attribute, $value, $parameters) <ide> // fine for the given ID to exist in the table. <ide> if (isset($parameters[2])) <ide> { <del> $query->where('id', '<>', $parameters[2]); <add> $query->where($attribute, '<>', $parameters[2]); <ide> } <ide> <ide> return $query->count() == 0;
1
Ruby
Ruby
add test for --json=v2
d96ad81cd02e2cad1ba022e979e8fb83f0d431e7
<ide><path>Library/Homebrew/test/cmd/info_spec.rb <ide> .and not_to_output.to_stderr <ide> .and be_a_success <ide> end <add> <add> it "prints as json with the --json=v2 flag" do <add> setup_test_formula "testball" <add> <add> expect { brew "info", "testball", "--json=v2" } <add> .to output(a_json_string).to_stdout <add> .and not_to_output.to_stderr <add> .and be_a_success <add> end <ide> end <ide> <ide> describe Homebrew do
1
PHP
PHP
add test suffix to misnamed tests
6b207dfe4ce5e66be9638e02b8d2be9f190e823c
<add><path>tests/Database/DatabaseEloquentCastsDatabaseStringTest.php <del><path>tests/Database/DatabaseEloquentCastsDatabaseString.php <ide> use Illuminate\Database\Capsule\Manager as DB; <ide> use Illuminate\Database\Eloquent\Model as Eloquent; <ide> <del>class DatabaseEloquentCastsDatabaseString extends TestCase <add>class DatabaseEloquentCastsDatabaseStringTest extends TestCase <ide> { <ide> public function setUp() <ide> { <add><path>tests/Database/DatabaseEloquentTimestampsTest.php <del><path>tests/Database/DatabaseEloquentTimestamps.php <ide> use Illuminate\Database\Capsule\Manager as DB; <ide> use Illuminate\Database\Eloquent\Model as Eloquent; <ide> <del>class DatabaseEloquentTimestamps extends TestCase <add>class DatabaseEloquentTimestampsTest extends TestCase <ide> { <ide> public function setUp() <ide> {
2
Python
Python
add the `axis` keyword to linalg.norm
40000f508ab5f736b5a62c97a1e4bb72d55bf19c
<ide><path>numpy/linalg/linalg.py <ide> intc, single, double, csingle, cdouble, inexact, complexfloating, \ <ide> newaxis, ravel, all, Inf, dot, add, multiply, identity, sqrt, \ <ide> maximum, flatnonzero, diagonal, arange, fastCopyAndTranspose, sum, \ <del> isfinite, size, finfo, absolute, log, exp, errstate, geterrobj <del>from numpy.lib import triu <add> isfinite, size, finfo, absolute, log, exp, errstate, geterrobj, \ <add> float64, float128 <add>from numpy.lib import triu, asfarray <ide> from numpy.linalg import lapack_lite, _umath_linalg <ide> from numpy.matrixlib.defmatrix import matrix_power <ide> from numpy.compat import asbytes <ide> def lstsq(a, b, rcond=-1): <ide> st = s[:min(n, m)].copy().astype(result_real_t) <ide> return wrap(x), wrap(resids), results['rank'], st <ide> <del>def norm(x, ord=None): <add> <add>def norm(x, ord=None, axis=None): <ide> """ <ide> Matrix or vector norm. <ide> <ide> def norm(x, ord=None): <ide> ord : {non-zero int, inf, -inf, 'fro'}, optional <ide> Order of the norm (see table under ``Notes``). inf means numpy's <ide> `inf` object. <add> axis : int or None, optional <add> If `axis` is not None, it specifies the axis of `x` along which to <add> compute the vector norms. <ide> <ide> Returns <ide> ------- <del> n : float <del> Norm of the matrix or vector. <add> n : float or ndarray <add> Norm of the matrix or vector(s). <ide> <ide> Notes <ide> ----- <ide> def norm(x, ord=None): <ide> >>> LA.norm(a, -3) <ide> nan <ide> <add> Using the `axis` argument: <add> <add> >>> c = np.array([[ 1, 2, 3], <add> ... [-1, 1, 4]]) <add> >>> LA.norm(c, axis=0) <add> array([ 1.41421356, 2.23606798, 5. ]) <add> >>> LA.norm(c, axis=1) <add> array([ 3.74165739, 4.24264069]) <add> >>> LA.norm(c, ord=1, axis=1) <add> array([6, 6]) <add> <ide> """ <ide> x = asarray(x) <del> if ord is None: # check the default case first and handle it immediately <add> <add> # Check the default case first and handle it immediately. <add> if ord is None and axis is None: <add> s = (x.conj() * x).real <ide> return sqrt(add.reduce((x.conj() * x).ravel().real)) <ide> <ide> nd = x.ndim <del> if nd == 1: <add> if nd == 1 or axis is not None: <ide> if ord == Inf: <del> return abs(x).max() <add> return abs(x).max(axis=axis) <ide> elif ord == -Inf: <del> return abs(x).min() <add> return abs(x).min(axis=axis) <ide> elif ord == 0: <del> return (x != 0).sum() # Zero norm <add> # Zero norm <add> return (x != 0).sum(axis=axis) <ide> elif ord == 1: <del> return abs(x).sum() # special case for speedup <del> elif ord == 2: <del> return sqrt(((x.conj()*x).real).sum()) # special case for speedup <add> # special case for speedup <add> return add.reduce(abs(x), axis=axis) <add> elif ord is None or ord == 2: <add> # special case for speedup <add> s = (x.conj() * x).real <add> return sqrt(add.reduce(s, axis=axis)) <ide> else: <ide> try: <ide> ord + 1 <ide> except TypeError: <ide> raise ValueError("Invalid norm order for vectors.") <del> return ((abs(x)**ord).sum())**(1.0/ord) <add> if x.dtype != float128: <add> # Convert to a float type, so integer arrays give <add> # float results. Don't apply asfarray to float128 arrays, <add> # because it will downcast to float64. <add> absx = asfarray(abs(x)) <add> return add.reduce(absx**ord, axis=axis)**(1.0/ord) <ide> elif nd == 2: <ide> if ord == 2: <ide> return svd(x, compute_uv=0).max() <ide><path>numpy/linalg/tests/test_linalg.py <ide> def test_empty(self): <ide> assert_equal(norm(atleast_2d(array([], dtype=self.dt))), 0.0) <ide> <ide> def test_vector(self): <del> a = [1.0,2.0,3.0,4.0] <del> b = [-1.0,-2.0,-3.0,-4.0] <del> c = [-1.0, 2.0,-3.0, 4.0] <add> a = [1, 2, 3, 4] <add> b = [-1, -2, -3, -4] <add> c = [-1, 2, -3, 4] <ide> <ide> def _test(v): <ide> np.testing.assert_almost_equal(norm(v), 30**0.5, decimal=self.dec) <ide> def _test(v): <ide> _test(v) <ide> <ide> def test_matrix(self): <del> A = matrix([[1.,3.],[5.,7.]], dtype=self.dt) <del> A = matrix([[1.,3.],[5.,7.]], dtype=self.dt) <add> A = matrix([[1, 3], [5, 7]], dtype=self.dt) <ide> assert_almost_equal(norm(A), 84**0.5) <ide> assert_almost_equal(norm(A,'fro'), 84**0.5) <ide> assert_almost_equal(norm(A,inf), 12.0) <ide> def test_matrix(self): <ide> self.assertRaises(ValueError, norm, A, -3) <ide> self.assertRaises(ValueError, norm, A, 0) <ide> <add> def test_axis(self): <add> # Compare the use of `axis` with computing the norm of each row <add> # or column separately. <add> A = array([[1, 2, 3], [4, 5, 6]], dtype=self.dt) <add> for order in [None, -1, 0, 1, 2, 3, np.Inf, -np.Inf]: <add> expected0 = [norm(A[:,k], ord=order) for k in range(A.shape[1])] <add> assert_almost_equal(norm(A, ord=order, axis=0), expected0) <add> expected1 = [norm(A[k,:], ord=order) for k in range(A.shape[0])] <add> assert_almost_equal(norm(A, ord=order, axis=1), expected1) <add> <add> # Check bad case. Using `axis` implies vector norms are being <add> # computed, so also using `ord='fro'` raises a ValueError <add> # (just like `norm([1,2,3], ord='fro')` does). <add> self.assertRaises(ValueError, norm, A, 'fro', 0) <add> <ide> <ide> class TestNormDouble(_TestNorm): <ide> dt = np.double <ide> class TestNormSingle(_TestNorm): <ide> dec = 6 <ide> <ide> <add>class TestNormInt64(_TestNorm): <add> dt = np.int64 <add> dec = 12 <add> <add> <ide> class TestMatrixRank(object): <ide> def test_matrix_rank(self): <ide> # Full rank matrix
2
Javascript
Javascript
capture errors on request data streams
cb630218303095c0075182b542ccb2f72d20dd9d
<ide><path>lib/adapters/http.js <ide> module.exports = function httpAdapter(config) { <ide> <ide> // Send the request <ide> if (utils.isStream(data)) { <del> data.pipe(req); <add> data.on('error', function handleStreamError(err) { <add> reject(enhanceError(err, config, null, req)); <add> }).pipe(req); <ide> } else { <ide> req.end(data); <ide> } <ide><path>test/unit/adapters/http.js <ide> module.exports = { <ide> }); <ide> }, <ide> <add> testFailedStream: function(test) { <add> server = http.createServer(function (req, res) { <add> req.pipe(res); <add> }).listen(4444, function () { <add> axios.post('http://localhost:4444/', <add> fs.createReadStream('/does/not/exist') <add> ).then(function (res) { <add> test.fail(); <add> }).catch(function (err) { <add> test.equal(err.message, 'ENOENT: no such file or directory, open \'/does/not/exist\''); <add> test.done(); <add> }); <add> }); <add> }, <add> <ide> testBuffer: function(test) { <ide> var buf = new Buffer(1024); // Unsafe buffer < Buffer.poolSize (8192 bytes) <ide> buf.fill('x');
2
Javascript
Javascript
use obj instead of array
8d3c63ef073a5ecc4c9a62c982c1760865b1070c
<ide><path>web/viewer.js <ide> var PDFView = { <ide> // Helper function to parse query string (e.g. ?param1=value&parm2=...). <ide> parseQueryString: function pdfViewParseQueryString(query) { <ide> var parts = query.split('&'); <del> var params = []; <add> var params = {}; <ide> for (var i = 0, ii = parts.length; i < parts.length; ++i) { <ide> var param = parts[i].split('='); <ide> var key = param[0];
1
PHP
PHP
put methods in alpha order... *cough* jeffrey
661bf1413a2fe5c613d4ca8121850d9b029001ff
<ide><path>src/Illuminate/Foundation/helpers.php <ide> function bcrypt($value, $options = []) <ide> } <ide> } <ide> <add>if (! function_exists('cache')) { <add> /** <add> * Get / set the specified cache value. <add> * <add> * If an array is passed, we'll assume you want to put to the cache. <add> * <add> * @param dynamic key|key,default|data,expiration|null <add> * @return mixed <add> */ <add> function cache() <add> { <add> $arguments = func_get_args(); <add> <add> if (empty($arguments)) { <add> return app('cache'); <add> } <add> <add> if (is_string($arguments[0])) { <add> return app('cache')->get($arguments[0], isset($arguments[1]) ? $arguments[1] : null); <add> } <add> <add> if (is_array($arguments[0])) { <add> if (! isset($arguments[1])) { <add> throw new Exception( <add> 'You must set an expiration time when putting to the cache.' <add> ); <add> } <add> <add> return app('cache')->put(key($arguments[0]), reset($arguments[0]), $arguments[1]); <add> } <add> } <add>} <add> <ide> if (! function_exists('config')) { <ide> /** <ide> * Get / set the specified configuration value. <ide> function session($key = null, $default = null) <ide> } <ide> } <ide> <del>if (! function_exists('cache')) { <del> /** <del> * Get / set the specified cache value. <del> * <del> * If an array is passed, we'll assume you want to put to the cache. <del> * <del> * @param dynamic key|key,default|data,expiration|null <del> * @return mixed <del> */ <del> function cache() <del> { <del> $arguments = func_get_args(); <del> <del> if (empty($arguments)) { <del> return app('cache'); <del> } <del> <del> if (is_string($arguments[0])) { <del> return app('cache')->get($arguments[0], isset($arguments[1]) ? $arguments[1] : null); <del> } <del> <del> if (is_array($arguments[0])) { <del> if (! isset($arguments[1])) { <del> throw new Exception( <del> 'You must set an expiration time when putting to the cache.' <del> ); <del> } <del> <del> return app('cache')->put(key($arguments[0]), reset($arguments[0]), $arguments[1]); <del> } <del> } <del>} <del> <ide> if (! function_exists('storage_path')) { <ide> /** <ide> * Get the path to the storage folder.
1
Python
Python
add type hints for return values
b2ed8d443c03bd9fa8cc523bcefcca4eeff04c2e
<ide><path>matrix/rotate_matrix.py <ide> # -*- coding: utf-8 -*- <ide> <ide> """ <del> In this problem, we want to rotate the matrix elements by 90, 180, 270 (counterclockwise) <del> Discussion in stackoverflow: <del> https://stackoverflow.com/questions/42519/how-do-you-rotate-a-two-dimensional-array <add>In this problem, we want to rotate the matrix elements by 90, 180, 270 (counterclockwise) <add>Discussion in stackoverflow: <add>https://stackoverflow.com/questions/42519/how-do-you-rotate-a-two-dimensional-array <ide> """ <ide> <ide> <del>def rotate_90(matrix: [[]]): <add>def make_matrix(row_size: int = 4) -> [[int]]: <ide> """ <del> >>> rotate_90([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]]) <del> [[4, 8, 12, 16], [3, 7, 11, 15], [2, 6, 10, 14], [1, 5, 9, 13]] <add> >>> make_matrix() <add> [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]] <add> >>> make_matrix(1) <add> [[1]] <add> >>> make_matrix(-2) <add> [[1, 2], [3, 4]] <add> >>> make_matrix(3) <add> [[1, 2, 3], [4, 5, 6], [7, 8, 9]] <add> >>> make_matrix() == make_matrix(4) <add> True <ide> """ <del> <del> transpose(matrix) <del> reverse_row(matrix) <del> return matrix <del> <add> row_size = abs(row_size) or 4 <add> return [[1 + x + y * row_size for x in range(row_size)] for y in range(row_size)] <add> <ide> <del>def rotate_180(matrix: [[]]): <add>def rotate_90(matrix: [[]]) -> [[]]: <ide> """ <del> >>> rotate_180([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]]) <del> [[16, 15, 14, 13], [12, 11, 10, 9], [8, 7, 6, 5], [4, 3, 2, 1]] <add> >>> rotate_90(make_matrix()) <add> [[4, 8, 12, 16], [3, 7, 11, 15], [2, 6, 10, 14], [1, 5, 9, 13]] <add> >>> rotate_90(make_matrix()) == transpose(reverse_column(make_matrix())) <add> True <ide> """ <del> <del> reverse_column(matrix) <del> reverse_row(matrix) <del> <add> <add> return reverse_row(transpose(matrix)) <add> # OR.. transpose(reverse_column(matrix)) <add> <add> <add>def rotate_180(matrix: [[]]) -> [[]]: <ide> """ <del> OR <del> <del> reverse_row(matrix) <del> reverse_column(matrix) <add> >>> rotate_180(make_matrix()) <add> [[16, 15, 14, 13], [12, 11, 10, 9], [8, 7, 6, 5], [4, 3, 2, 1]] <add> >>> rotate_180(make_matrix()) == reverse_column(reverse_row(make_matrix())) <add> True <ide> """ <del> <del> return matrix <ide> <del> <del>def rotate_270(matrix: [[]]): <add> return reverse_row(reverse_column(matrix)) <add> # OR.. reverse_column(reverse_row(matrix)) <add> <add> <add>def rotate_270(matrix: [[]]) -> [[]]: <ide> """ <del> >>> rotate_270([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]]) <add> >>> rotate_270(make_matrix()) <ide> [[13, 9, 5, 1], [14, 10, 6, 2], [15, 11, 7, 3], [16, 12, 8, 4]] <add> >>> rotate_270(make_matrix()) == transpose(reverse_row(make_matrix())) <add> True <ide> """ <del> <del> transpose(matrix) <del> reverse_column(matrix) <del> <del> """ <del> OR <del> <del> reverse_row(matrix) <del> transpose(matrix) <del> """ <del> <del> return matrix <ide> <add> return reverse_column(transpose(matrix)) <add> # OR.. transpose(reverse_row(matrix)) <ide> <del>def transpose(matrix: [[]]): <add> <add>def transpose(matrix: [[]]) -> [[]]: <ide> matrix[:] = [list(x) for x in zip(*matrix)] <ide> return matrix <del> <del> <del>def reverse_row(matrix: [[]]): <add> <add> <add>def reverse_row(matrix: [[]]) -> [[]]: <ide> matrix[:] = matrix[::-1] <ide> return matrix <ide> <ide> <del>def reverse_column(matrix: [[]]): <add>def reverse_column(matrix: [[]]) -> [[]]: <ide> matrix[:] = [x[::-1] for x in matrix] <ide> return matrix <del> <del> <del>def print_matrix(matrix: [[]]): <add> <add> <add>def print_matrix(matrix: [[]]) -> [[]]: <ide> for i in matrix: <ide> print(*i) <ide> <ide> <del>if __name__ == '__main__': <del> matrix = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]] <add>if __name__ == "__main__": <add> matrix = make_matrix() <ide> print("\norigin:\n") <ide> print_matrix(matrix) <del> rotate_90(matrix) <ide> print("\nrotate 90 counterclockwise:\n") <del> print_matrix(matrix) <add> print_matrix(rotate_90(matrix)) <ide> <del> matrix = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]] <add> matrix = make_matrix() <ide> print("\norigin:\n") <ide> print_matrix(matrix) <del> rotate_180(matrix) <ide> print("\nrotate 180:\n") <del> print_matrix(matrix) <add> print_matrix(rotate_180(matrix)) <ide> <del> matrix = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]] <add> matrix = make_matrix() <ide> print("\norigin:\n") <ide> print_matrix(matrix) <del> rotate_270(matrix) <ide> print("\nrotate 270 counterclockwise:\n") <del> print_matrix(matrix) <add> print_matrix(rotate_270(matrix))
1
Python
Python
remove utils/logs usage for official models
2c6f12e3149ffc324b22de875ad6b7091b0cc638
<ide><path>official/benchmark/models/resnet_cifar_main.py <ide> from official.benchmark.models import resnet_cifar_model <ide> from official.benchmark.models import synthetic_util <ide> from official.utils.flags import core as flags_core <del>from official.utils.logs import logger <ide> from official.utils.misc import distribution_utils <ide> from official.utils.misc import keras_utils <ide> from official.vision.image_classification.resnet import common <ide> def define_cifar_flags(): <ide> <ide> <ide> def main(_): <del> with logger.benchmark_context(flags.FLAGS): <del> return run(flags.FLAGS) <add> return run(flags.FLAGS) <ide> <ide> <ide> if __name__ == '__main__': <ide><path>official/benchmark/models/resnet_imagenet_main.py <ide> import tensorflow_model_optimization as tfmot <ide> from official.modeling import performance <ide> from official.utils.flags import core as flags_core <del>from official.utils.logs import logger <ide> from official.utils.misc import distribution_utils <ide> from official.utils.misc import keras_utils <ide> from official.utils.misc import model_helpers <ide> def define_imagenet_keras_flags(): <ide> <ide> def main(_): <ide> model_helpers.apply_clean(flags.FLAGS) <del> with logger.benchmark_context(flags.FLAGS): <del> stats = run(flags.FLAGS) <add> stats = run(flags.FLAGS) <ide> logging.info('Run stats:\n%s', stats) <ide> <ide> <ide><path>official/nlp/transformer/transformer_main.py <ide> from official.nlp.transformer import translate <ide> from official.nlp.transformer.utils import tokenizer <ide> from official.utils.flags import core as flags_core <del>from official.utils.logs import logger <ide> from official.utils.misc import distribution_utils <ide> from official.utils.misc import keras_utils <ide> <ide> def _ensure_dir(log_dir): <ide> <ide> def main(_): <ide> flags_obj = flags.FLAGS <del> with logger.benchmark_context(flags_obj): <del> task = TransformerTask(flags_obj) <del> <del> # Execute flag override logic for better model performance <del> if flags_obj.tf_gpu_thread_mode: <del> keras_utils.set_gpu_thread_mode_and_count( <del> per_gpu_thread_count=flags_obj.per_gpu_thread_count, <del> gpu_thread_mode=flags_obj.tf_gpu_thread_mode, <del> num_gpus=flags_obj.num_gpus, <del> datasets_num_private_threads=flags_obj.datasets_num_private_threads) <del> <del> if flags_obj.mode == "train": <del> task.train() <del> elif flags_obj.mode == "predict": <del> task.predict() <del> elif flags_obj.mode == "eval": <del> task.eval() <del> else: <del> raise ValueError("Invalid mode {}".format(flags_obj.mode)) <add> task = TransformerTask(flags_obj) <add> <add> # Execute flag override logic for better model performance <add> if flags_obj.tf_gpu_thread_mode: <add> keras_utils.set_gpu_thread_mode_and_count( <add> per_gpu_thread_count=flags_obj.per_gpu_thread_count, <add> gpu_thread_mode=flags_obj.tf_gpu_thread_mode, <add> num_gpus=flags_obj.num_gpus, <add> datasets_num_private_threads=flags_obj.datasets_num_private_threads) <add> <add> if flags_obj.mode == "train": <add> task.train() <add> elif flags_obj.mode == "predict": <add> task.predict() <add> elif flags_obj.mode == "eval": <add> task.eval() <add> else: <add> raise ValueError("Invalid mode {}".format(flags_obj.mode)) <ide> <ide> <ide> if __name__ == "__main__": <ide><path>official/recommendation/data_preprocessing.py <ide> import pickle <ide> import time <ide> import timeit <del>import typing <del> <ide> # pylint: disable=wrong-import-order <add>from absl import logging <ide> import numpy as np <ide> import pandas as pd <ide> import tensorflow as tf <del>from absl import logging <add>import typing <ide> # pylint: enable=wrong-import-order <ide> <ide> from official.recommendation import constants as rconst <ide> from official.recommendation import data_pipeline <ide> from official.recommendation import movielens <del>from official.utils.logs import mlperf_helper <ide> <ide> <ide> DATASET_TO_NUM_USERS_AND_ITEMS = { <ide> def _filter_index_sort(raw_rating_path, cache_path): <ide> num_users = len(original_users) <ide> num_items = len(original_items) <ide> <del> mlperf_helper.ncf_print(key=mlperf_helper.TAGS.PREPROC_HP_NUM_EVAL, <del> value=rconst.NUM_EVAL_NEGATIVES) <del> <ide> assert num_users <= np.iinfo(rconst.USER_DTYPE).max <ide> assert num_items <= np.iinfo(rconst.ITEM_DTYPE).max <ide> assert df[movielens.USER_COLUMN].max() == num_users - 1 <ide><path>official/recommendation/ncf_keras_main.py <ide> from official.recommendation import ncf_common <ide> from official.recommendation import ncf_input_pipeline <ide> from official.recommendation import neumf_model <del>from official.utils.logs import logger <del>from official.utils.logs import mlperf_helper <ide> from official.utils.misc import distribution_utils <ide> from official.utils.misc import keras_utils <ide> from official.utils.misc import model_helpers <ide> def build_stats(loss, eval_result, time_callback): <ide> <ide> <ide> def main(_): <del> with logger.benchmark_context(FLAGS), \ <del> mlperf_helper.LOGGER(FLAGS.output_ml_perf_compliance_logging): <del> mlperf_helper.set_ncf_root(os.path.split(os.path.abspath(__file__))[0]) <del> run_ncf(FLAGS) <add> run_ncf(FLAGS) <ide> <ide> <ide> if __name__ == "__main__": <ide><path>official/recommendation/neumf_model.py <ide> <ide> from six.moves import xrange # pylint: disable=redefined-builtin <ide> import tensorflow as tf <del> <ide> from official.recommendation import constants as rconst <ide> from official.recommendation import movielens <ide> from official.recommendation import ncf_common <ide> from official.recommendation import stat_utils <del>from official.utils.logs import mlperf_helper <ide> <ide> <ide> def sparse_to_dense_grads(grads_and_vars): <ide> def neumf_model_fn(features, labels, mode, params): <ide> labels = tf.cast(labels, tf.int32) <ide> valid_pt_mask = features[rconst.VALID_POINT_MASK] <ide> <del> mlperf_helper.ncf_print(key=mlperf_helper.TAGS.OPT_NAME, value="adam") <del> mlperf_helper.ncf_print(key=mlperf_helper.TAGS.OPT_LR, <del> value=params["learning_rate"]) <del> mlperf_helper.ncf_print(key=mlperf_helper.TAGS.OPT_HP_ADAM_BETA1, <del> value=params["beta1"]) <del> mlperf_helper.ncf_print(key=mlperf_helper.TAGS.OPT_HP_ADAM_BETA2, <del> value=params["beta2"]) <del> mlperf_helper.ncf_print(key=mlperf_helper.TAGS.OPT_HP_ADAM_EPSILON, <del> value=params["epsilon"]) <del> <ide> optimizer = tf.compat.v1.train.AdamOptimizer( <ide> learning_rate=params["learning_rate"], <ide> beta1=params["beta1"], <ide> def neumf_model_fn(features, labels, mode, params): <ide> if params["use_tpu"]: <ide> optimizer = tf.compat.v1.tpu.CrossShardOptimizer(optimizer) <ide> <del> mlperf_helper.ncf_print(key=mlperf_helper.TAGS.MODEL_HP_LOSS_FN, <del> value=mlperf_helper.TAGS.BCE) <del> <ide> loss = tf.compat.v1.losses.sparse_softmax_cross_entropy( <ide> labels=labels, <ide> logits=softmax_logits, <ide> def construct_model(user_input, item_input, params): <ide> <ide> mf_dim = params["mf_dim"] <ide> <del> mlperf_helper.ncf_print(key=mlperf_helper.TAGS.MODEL_HP_MF_DIM, value=mf_dim) <del> mlperf_helper.ncf_print(key=mlperf_helper.TAGS.MODEL_HP_MLP_LAYER_SIZES, <del> value=model_layers) <del> <ide> if model_layers[0] % 2 != 0: <ide> raise ValueError("The first layer size should be multiple of 2!") <ide> <ide><path>official/vision/image_classification/resnet/resnet_ctl_imagenet_main.py <ide> from official.modeling import performance <ide> from official.staging.training import controller <ide> from official.utils.flags import core as flags_core <del>from official.utils.logs import logger <ide> from official.utils.misc import distribution_utils <ide> from official.utils.misc import keras_utils <ide> from official.utils.misc import model_helpers <ide> def run(flags_obj): <ide> <ide> def main(_): <ide> model_helpers.apply_clean(flags.FLAGS) <del> with logger.benchmark_context(flags.FLAGS): <del> stats = run(flags.FLAGS) <add> stats = run(flags.FLAGS) <ide> logging.info('Run stats:\n%s', stats) <ide> <ide>
7
Python
Python
test the full story processing
1aec940587255083b2451fc18aa604de29c1188c
<ide><path>examples/run_seq2seq_finetuning.py <ide> def __init_(self, tokenizer, data_dir="", block_size=512): <ide> path_to_stories = os.path.join(data_dir, dataset, "stories") <ide> assert os.path.isdir(path_to_stories) <ide> <del> stories_files = os.listdir(path_to_stories) <del> for story_file in stories_files: <del> path_to_story = os.path.join(path_to_stories, "story_file") <add> story_filenames_list = os.listdir(path_to_stories) <add> for story_filename in story_filenames_list: <add> path_to_story = os.path.join(path_to_stories, story_filename) <ide> if not os.path.isfile(path_to_story): <ide> continue <ide> <ide> with open(path_to_story, encoding="utf-8") as source: <ide> try: <ide> raw_story = source.read() <ide> story, summary = process_story(raw_story) <del> except IndexError: <add> except IndexError: # skip ill-formed stories <ide> continue <ide> <ide> story = tokenizer.convert_tokens_to_ids(tokenizer.tokenize(story)) <ide> summary = tokenizer.convert_tokens_to_ids(tokenizer.tokenize(summary)) <ide> story_seq, summary_seq = _fit_to_block_size(story, summary, block_size) <del> example = tokenizer.add_special_token_sequence_pair( <del> story_seq, summary_seq <add> <add> self.examples.append( <add> tokenizer.add_special_token_sequence_pair(story_seq, summary_seq) <ide> ) <del> self.examples.append(example) <ide> <ide> logger.info("Saving features into cache file %s", cached_features_file) <ide> with open(cached_features_file, "wb") as sink: <ide> def __getitem__(self, items): <ide> <ide> <ide> def process_story(raw_story): <del> """ Process the text contained in a story file. <del> Returns the story and the summary <add> """ Extract the story and summary from a story file. <add> <add> Attributes: <add> raw_story (str): content of the story file as an utf-8 encoded string. <add> <add> Raises: <add> IndexError: If the stoy is empty or contains no highlights. <ide> """ <ide> file_lines = list( <ide> filter(lambda x: len(x) != 0, [line.strip() for line in raw_story.split("\n")]) <ide> def _add_missing_period(line): <ide> return line <ide> if line[-1] in END_TOKENS: <ide> return line <del> return line + " ." <add> return line + "." <ide> <ide> <ide> def _fit_to_block_size(src_sequence, tgt_sequence, block_size): <ide> def _fit_to_block_size(src_sequence, tgt_sequence, block_size): <ide> block size of 512 this means limiting the source sequence's length to 384 <ide> and the target sequence's length to 128. <ide> <add> Attributes: <add> src_sequence (list): a list of ids that maps to the tokens of the <add> source sequence. <add> tgt_sequence (list): a list of ids that maps to the tokens of the <add> target sequence. <add> block_size (int): the model's block size. <add> <ide> [1] Dong, Li, et al. "Unified Language Model Pre-training for Natural <ide> Language Understanding and Generation." arXiv preprint arXiv:1905.03197 (2019). <ide> """ <ide><path>examples/run_seq2seq_finetuning_test.py <ide> # limitations under the License. <ide> import unittest <ide> <del>from run_seq2seq_finetuning import _fit_to_block_size <add>from run_seq2seq_finetuning import _fit_to_block_size, process_story <ide> <ide> <ide> class DataLoaderTest(unittest.TestCase): <ide> def setUp(self): <ide> self.block_size = 10 <ide> <del> def test_source_and_target_too_small(self): <add> def test_truncate_source_and_target_too_small(self): <ide> """ When the sum of the lengths of the source and target sequences is <ide> smaller than the block size (minus the number of special tokens), skip the example. """ <ide> src_seq = [1, 2, 3, 4] <ide> tgt_seq = [5, 6] <ide> self.assertEqual(_fit_to_block_size(src_seq, tgt_seq, self.block_size), None) <ide> <del> def test_source_and_target_fit_exactly(self): <add> def test_truncate_source_and_target_fit_exactly(self): <ide> """ When the sum of the lengths of the source and target sequences is <ide> equal to the block size (minus the number of special tokens), return the <ide> sequences unchanged. """ <ide> def test_source_and_target_fit_exactly(self): <ide> self.assertListEqual(src_seq, fitted_src) <ide> self.assertListEqual(tgt_seq, fitted_tgt) <ide> <del> def test_source_too_big_target_ok(self): <add> def test_truncate_source_too_big_target_ok(self): <ide> src_seq = [1, 2, 3, 4, 5, 6] <ide> tgt_seq = [1, 2] <ide> fitted_src, fitted_tgt = _fit_to_block_size(src_seq, tgt_seq, self.block_size) <ide> self.assertListEqual(fitted_src, [1, 2, 3, 4, 5]) <ide> self.assertListEqual(fitted_tgt, fitted_tgt) <ide> <del> def test_target_too_big_source_ok(self): <add> def test_truncate_target_too_big_source_ok(self): <ide> src_seq = [1, 2, 3, 4] <ide> tgt_seq = [1, 2, 3, 4] <ide> fitted_src, fitted_tgt = _fit_to_block_size(src_seq, tgt_seq, self.block_size) <ide> self.assertListEqual(fitted_src, src_seq) <ide> self.assertListEqual(fitted_tgt, [1, 2, 3]) <ide> <del> def test_source_and_target_too_big(self): <add> def test_truncate_source_and_target_too_big(self): <ide> src_seq = [1, 2, 3, 4, 5, 6, 7] <ide> tgt_seq = [1, 2, 3, 4, 5, 6, 7] <ide> fitted_src, fitted_tgt = _fit_to_block_size(src_seq, tgt_seq, self.block_size) <ide> self.assertListEqual(fitted_src, [1, 2, 3, 4, 5]) <ide> self.assertListEqual(fitted_tgt, [1, 2]) <ide> <add> def test_process_story_no_highlights(self): <add> """ Processing a story with no highlights should raise an exception. <add> """ <add> raw_story = """It was the year of Our Lord one thousand seven hundred and <add> seventy-five.\n\nSpiritual revelations were conceded to England at that <add> favoured period, as at this.""" <add> with self.assertRaises(IndexError): <add> process_story(raw_story) <add> <add> def test_process_empty_story(self): <add> """ An empty story should also raise and exception. <add> """ <add> raw_story = "" <add> with self.assertRaises(IndexError): <add> process_story(raw_story) <add> <add> def test_story_with_missing_period(self): <add> raw_story = ( <add> "It was the year of Our Lord one thousand seven hundred and " <add> "seventy-five\n\nSpiritual revelations were conceded to England " <add> "at that favoured period, as at this.\n@highlight\n\nIt was the best of times" <add> ) <add> story, summary = process_story(raw_story) <add> <add> expected_story = ( <add> "It was the year of Our Lord one thousand seven hundred and " <add> "seventy-five. Spiritual revelations were conceded to England at that " <add> "favoured period, as at this." <add> ) <add> self.assertEqual(expected_story, story) <add> <add> expected_summary = "It was the best of times." <add> self.assertEqual(expected_summary, summary) <add> <ide> <ide> if __name__ == "__main__": <ide> unittest.main()
2
Javascript
Javascript
fix korean test label
e8f8736b5d2a0c28b8fbad2de7ca88bec3d18f36
<ide><path>test/lang/ar-sa.js <ide> exports["lang:ar-sa"] = { <ide> }, <ide> <ide> "from" : function (test) { <del> test.expect(30); <del> <ide> var start = moment([2007, 1, 28]); <ide> test.equal(start.from(moment([2007, 1, 28]).add({s: 44}), true), "ثوان", "44 seconds = a few seconds"); <ide> test.equal(start.from(moment([2007, 1, 28]).add({s: 45}), true), "دقيقة", "45 seconds = a minute"); <ide> exports["lang:ar-sa"] = { <ide> test.equal(start.from(moment([2007, 1, 28]).add({d: 25}), true), "٢٥ أيام", "25 days = 25 days"); <ide> test.equal(start.from(moment([2007, 1, 28]).add({d: 26}), true), "شهر", "26 days = a month"); <ide> test.equal(start.from(moment([2007, 1, 28]).add({d: 30}), true), "شهر", "30 days = a month"); <del> test.equal(start.from(moment([2007, 1, 28]).add({d: 45}), true), "شهر", "45 days = a month"); <add> test.equal(start.from(moment([2007, 1, 28]).add({d: 43}), true), "شهر", "43 days = a month"); <ide> test.equal(start.from(moment([2007, 1, 28]).add({d: 46}), true), "٢ أشهر", "46 days = 2 months"); <ide> test.equal(start.from(moment([2007, 1, 28]).add({d: 74}), true), "٢ أشهر", "75 days = 2 months"); <ide> test.equal(start.from(moment([2007, 1, 28]).add({d: 76}), true), "٣ أشهر", "76 days = 3 months"); <ide> test.equal(start.from(moment([2007, 1, 28]).add({M: 1}), true), "شهر", "1 month = a month"); <ide> test.equal(start.from(moment([2007, 1, 28]).add({M: 5}), true), "٥ أشهر", "5 months = 5 months"); <del> test.equal(start.from(moment([2007, 1, 28]).add({d: 344}), true), "١١ أشهر", "344 days = 11 months"); <ide> test.equal(start.from(moment([2007, 1, 28]).add({d: 345}), true), "سنة", "345 days = a year"); <del> test.equal(start.from(moment([2007, 1, 28]).add({d: 547}), true), "سنة", "547 days = a year"); <ide> test.equal(start.from(moment([2007, 1, 28]).add({d: 548}), true), "٢ سنوات", "548 days = 2 years"); <ide> test.equal(start.from(moment([2007, 1, 28]).add({y: 1}), true), "سنة", "1 year = a year"); <ide> test.equal(start.from(moment([2007, 1, 28]).add({y: 5}), true), "٥ سنوات", "5 years = 5 years"); <ide><path>test/lang/az.js <ide> exports["lang:az"] = { <ide> }, <ide> <ide> "from" : function (test) { <del> test.expect(30); <ide> var start = moment([2007, 1, 28]); <ide> test.equal(start.from(moment([2007, 1, 28]).add({s: 44}), true), "birneçə saniyyə", "44 seconds = a few seconds"); <ide> test.equal(start.from(moment([2007, 1, 28]).add({s: 45}), true), "bir dəqiqə", "45 seconds = a minute"); <ide> exports["lang:az"] = { <ide> test.equal(start.from(moment([2007, 1, 28]).add({d: 25}), true), "25 gün", "25 days = 25 days"); <ide> test.equal(start.from(moment([2007, 1, 28]).add({d: 26}), true), "bir ay", "26 days = a month"); <ide> test.equal(start.from(moment([2007, 1, 28]).add({d: 30}), true), "bir ay", "30 days = a month"); <del> test.equal(start.from(moment([2007, 1, 28]).add({d: 45}), true), "bir ay", "45 days = a month"); <ide> test.equal(start.from(moment([2007, 1, 28]).add({d: 46}), true), "2 ay", "46 days = 2 months"); <ide> test.equal(start.from(moment([2007, 1, 28]).add({d: 74}), true), "2 ay", "75 days = 2 months"); <ide> test.equal(start.from(moment([2007, 1, 28]).add({d: 76}), true), "3 ay", "76 days = 3 months"); <ide> test.equal(start.from(moment([2007, 1, 28]).add({M: 1}), true), "bir ay", "1 month = a month"); <ide> test.equal(start.from(moment([2007, 1, 28]).add({M: 5}), true), "5 ay", "5 months = 5 months"); <del> test.equal(start.from(moment([2007, 1, 28]).add({d: 344}), true), "11 ay", "344 days = 11 months"); <ide> test.equal(start.from(moment([2007, 1, 28]).add({d: 345}), true), "bir il", "345 days = a year"); <del> test.equal(start.from(moment([2007, 1, 28]).add({d: 547}), true), "bir il", "547 days = a year"); <ide> test.equal(start.from(moment([2007, 1, 28]).add({d: 548}), true), "2 il", "548 days = 2 years"); <ide> test.equal(start.from(moment([2007, 1, 28]).add({y: 1}), true), "bir il", "1 year = a year"); <ide> test.equal(start.from(moment([2007, 1, 28]).add({y: 5}), true), "5 il", "5 years = 5 years"); <ide><path>test/lang/bn.js <ide> exports["lang:bn"] = { <ide> }, <ide> <ide> "from" : function (test) { <del> test.expect(30); <del> <ide> var start = moment([2007, 1, 28]); <ide> test.equal(start.from(moment([2007, 1, 28]).add({s: 44}), true), "কএক সেকেন্ড", "44 seconds = a few seconds"); <ide> test.equal(start.from(moment([2007, 1, 28]).add({s: 45}), true), "এক মিনিট", "45 seconds = a minute"); <ide> exports["lang:bn"] = { <ide> test.equal(start.from(moment([2007, 1, 28]).add({d: 25}), true), "২৫ দিন", "25 days = 25 days"); <ide> test.equal(start.from(moment([2007, 1, 28]).add({d: 26}), true), "এক মাস", "26 days = a month"); <ide> test.equal(start.from(moment([2007, 1, 28]).add({d: 30}), true), "এক মাস", "30 days = a month"); <del> test.equal(start.from(moment([2007, 1, 28]).add({d: 45}), true), "এক মাস", "45 days = a month"); <ide> test.equal(start.from(moment([2007, 1, 28]).add({d: 46}), true), "২ মাস", "46 days = 2 months"); <ide> test.equal(start.from(moment([2007, 1, 28]).add({d: 74}), true), "২ মাস", "75 days = 2 months"); <ide> test.equal(start.from(moment([2007, 1, 28]).add({d: 76}), true), "৩ মাস", "76 days = 3 months"); <ide> test.equal(start.from(moment([2007, 1, 28]).add({M: 1}), true), "এক মাস", "1 month = a month"); <ide> test.equal(start.from(moment([2007, 1, 28]).add({M: 5}), true), "৫ মাস", "5 months = 5 months"); <del> test.equal(start.from(moment([2007, 1, 28]).add({d: 344}), true), "১১ মাস", "344 days = 11 months"); <ide> test.equal(start.from(moment([2007, 1, 28]).add({d: 345}), true), "এক বছর", "345 days = a year"); <del> test.equal(start.from(moment([2007, 1, 28]).add({d: 547}), true), "এক বছর", "547 days = a year"); <ide> test.equal(start.from(moment([2007, 1, 28]).add({d: 548}), true), "২ বছর", "548 days = 2 years"); <ide> test.equal(start.from(moment([2007, 1, 28]).add({y: 1}), true), "এক বছর", "1 year = a year"); <ide> test.equal(start.from(moment([2007, 1, 28]).add({y: 5}), true), "৫ বছর", "5 years = 5 years"); <ide><path>test/lang/de-at.js <ide> exports["lang:de-at"] = { <ide> }, <ide> <ide> "from": function (test) { <del> test.expect(30); <ide> var start = moment([2007, 1, 28]); <ide> test.equal(start.from(moment([2007, 1, 28]).add({s: 44}), true), "ein paar Sekunden", "44 seconds = a few seconds"); <ide> test.equal(start.from(moment([2007, 1, 28]).add({s: 45}), true), "eine Minute", "45 seconds = a minute"); <ide> exports["lang:de-at"] = { <ide> test.equal(start.from(moment([2007, 1, 28]).add({d: 25}), true), "25 Tage", "25 days = 25 days"); <ide> test.equal(start.from(moment([2007, 1, 28]).add({d: 26}), true), "ein Monat", "26 days = a month"); <ide> test.equal(start.from(moment([2007, 1, 28]).add({d: 30}), true), "ein Monat", "30 days = a month"); <del> test.equal(start.from(moment([2007, 1, 28]).add({d: 45}), true), "ein Monat", "45 days = a month"); <ide> test.equal(start.from(moment([2007, 1, 28]).add({d: 46}), true), "2 Monate", "46 days = 2 months"); <ide> test.equal(start.from(moment([2007, 1, 28]).add({d: 74}), true), "2 Monate", "75 days = 2 months"); <ide> test.equal(start.from(moment([2007, 1, 28]).add({d: 76}), true), "3 Monate", "76 days = 3 months"); <ide> test.equal(start.from(moment([2007, 1, 28]).add({M: 1}), true), "ein Monat", "1 month = a month"); <ide> test.equal(start.from(moment([2007, 1, 28]).add({M: 5}), true), "5 Monate", "5 months = 5 months"); <del> test.equal(start.from(moment([2007, 1, 28]).add({d: 344}), true), "11 Monate", "344 days = 11 months"); <ide> test.equal(start.from(moment([2007, 1, 28]).add({d: 345}), true), "ein Jahr", "345 days = a year"); <del> test.equal(start.from(moment([2007, 1, 28]).add({d: 547}), true), "ein Jahr", "547 days = a year"); <ide> test.equal(start.from(moment([2007, 1, 28]).add({d: 548}), true), "2 Jahre", "548 days = 2 years"); <ide> test.equal(start.from(moment([2007, 1, 28]).add({y: 1}), true), "ein Jahr", "1 year = a year"); <ide> test.equal(start.from(moment([2007, 1, 28]).add({y: 5}), true), "5 Jahre", "5 years = 5 years"); <ide><path>test/lang/ko.js <ide> var moment = require("../../moment"); <ide> Korean <ide> *************************************************/ <ide> <del>exports["lang:kr"] = { <add>exports["lang:ko"] = { <ide> setUp : function (cb) { <ide> moment.lang('ko'); <ide> moment.createFromInputFallback = function () {
5
Python
Python
add greedy matcher tests
7072b395c9e0705338c857e7b1ef7087cdb7b928
<ide><path>spacy/tests/regression/test_issue1855.py <add># coding: utf-8 <add>from __future__ import unicode_literals <add>import re <add> <add>from ..matcher import Matcher <add> <add>import pytest <add> <add>pattern1 = [{'ORTH':'A','OP':'1'},{'ORTH':'A','OP':'*'}] <add>pattern2 = [{'ORTH':'A','OP':'*'},{'ORTH':'A','OP':'1'}] <add>pattern3 = [{'ORTH':'A','OP':'1'},{'ORTH':'A','OP':'1'}] <add>pattern4 = [{'ORTH':'B','OP':'1'},{'ORTH':'A','OP':'*'},{'ORTH':'B','OP':'1'}] <add>pattern5 = [{'ORTH':'B','OP':'*'},{'ORTH':'A','OP':'*'},{'ORTH':'B','OP':'1'}] <add> <add>re_pattern1 = 'AA*' <add>re_pattern2 = 'A*A' <add>re_pattern3 = 'AA' <add>re_pattern4 = 'BA*B' <add>re_pattern5 = 'B*A*B' <add> <add>@pytest.fixture <add>def text(): <add> return "(ABBAAAAAB)." <add> <add>@pytest.fixture <add>def doc(en_tokenizer,text): <add> doc = en_tokenizer(' '.join(text)) <add> return doc <add> <add>@pytest.mark.parametrize('pattern,re_pattern',[ <add> (pattern1,re_pattern1), <add> (pattern2,re_pattern2), <add> (pattern3,re_pattern3), <add> (pattern4,re_pattern4), <add> (pattern5,re_pattern5)]) <add>def test_greedy_matching(doc,text,pattern,re_pattern): <add> """ <add> Test that the greedy matching behavior of the * op <add> is consistant with other re implementations <add> """ <add> matcher = Matcher(doc.vocab) <add> matcher.add(re_pattern,None,pattern) <add> matches = matcher(doc) <add> re_matches = [m.span() for m in re.finditer(re_pattern,text)] <add> for match,re_match in zip(matches,re_matches): <add> assert match[1:]==re_match <add> <add>@pytest.mark.parametrize('pattern,re_pattern',[ <add> (pattern1,re_pattern1), <add> (pattern2,re_pattern2), <add> (pattern3,re_pattern3), <add> (pattern4,re_pattern4), <add> (pattern5,re_pattern5)]) <add>def test_match_consuming(doc,text,pattern,re_pattern): <add> """ <add> Test that matcher.__call__ consumes tokens on a match <add> similar to re.findall <add> """ <add> matcher = Matcher(doc.vocab) <add> matcher.add(re_pattern,None,pattern) <add> matches = matcher(doc) <add> re_matches = [m.span() for m in re.finditer(re_pattern,text)] <add> assert len(matches)==len(re_matches) <ide>\ No newline at end of file <ide><path>spacy/tests/test_matcher_greedy.py <add># coding: utf-8 <add>from __future__ import unicode_literals <add>import re <add> <add>from ..matcher import Matcher <add> <add>import pytest <add> <add>pattern1 = [{'ORTH':'A','OP':'1'},{'ORTH':'A','OP':'*'}] <add>pattern2 = [{'ORTH':'A','OP':'*'},{'ORTH':'A','OP':'1'}] <add>pattern3 = [{'ORTH':'A','OP':'1'},{'ORTH':'A','OP':'1'}] <add>pattern4 = [{'ORTH':'B','OP':'1'},{'ORTH':'A','OP':'*'},{'ORTH':'B','OP':'1'}] <add>pattern5 = [{'ORTH':'B','OP':'*'},{'ORTH':'A','OP':'*'},{'ORTH':'B','OP':'1'}] <add> <add>re_pattern1 = 'AA*' <add>re_pattern2 = 'A*A' <add>re_pattern3 = 'AA' <add>re_pattern4 = 'BA*B' <add>re_pattern5 = 'B*A*B' <add> <add>@pytest.fixture <add>def text(): <add> return "(ABBAAAAAB)." <add> <add>@pytest.fixture <add>def doc(en_tokenizer,text): <add> doc = en_tokenizer(' '.join(text)) <add> return doc <add> <add>@pytest.mark.parametrize('pattern,re_pattern',[ <add> (pattern1,re_pattern1), <add> (pattern2,re_pattern2), <add> (pattern3,re_pattern3), <add> (pattern4,re_pattern4), <add> (pattern5,re_pattern5)]) <add>def test_greedy_matching(doc,text,pattern,re_pattern): <add> """ <add> Test that the greedy matching behavior of the * op <add> is consistant with other re implementations <add> """ <add> matcher = Matcher(doc.vocab) <add> matcher.add(re_pattern,None,pattern) <add> matches = matcher(doc) <add> re_matches = [m.span() for m in re.finditer(re_pattern,text)] <add> for match,re_match in zip(matches,re_matches): <add> assert match[1:]==re_match <add> <add>@pytest.mark.parametrize('pattern,re_pattern',[ <add> (pattern1,re_pattern1), <add> (pattern2,re_pattern2), <add> (pattern3,re_pattern3), <add> (pattern4,re_pattern4), <add> (pattern5,re_pattern5)]) <add>def test_match_consuming(doc,text,pattern,re_pattern): <add> """ <add> Test that matcher.__call__ consumes tokens on a match <add> similar to re.findall <add> """ <add> matcher = Matcher(doc.vocab) <add> matcher.add(re_pattern,None,pattern) <add> matches = matcher(doc) <add> re_matches = [m.span() for m in re.finditer(re_pattern,text)] <add> assert len(matches)==len(re_matches) <ide>\ No newline at end of file
2
Javascript
Javascript
reset texture state
de61a95cefa648f74bdc807b593149d4cb9bdde4
<ide><path>src/renderers/webgl/WebGLState.js <ide> THREE.WebGLState = function ( gl, extensions, paramThreeToGL ) { <ide> <ide> compressedTextureFormats = null; <ide> <add> currentTextureSlot = undefined; <add> currentBoundTextures = {}; <add> <ide> currentBlending = null; <ide> <ide> currentColorWrite = null;
1
Javascript
Javascript
put libgit2 back
c7dcbeb0dacc42899c6e3ec3551ea9669bc445d7
<ide><path>script/lib/include-path-in-packaged-app.js <ide> const EXCLUDE_REGEXPS_SOURCES = [ <ide> escapeRegExp(path.join('build', 'Release', 'obj.target')), <ide> escapeRegExp(path.join('build', 'Release', 'obj')), <ide> escapeRegExp(path.join('build', 'Release', '.deps')), <del> escapeRegExp(path.join('deps', 'libgit2')), <ide> escapeRegExp(path.join('vendor', 'apm')), <ide> <ide> // These are only required in dev-mode, when pegjs grammars aren't precompiled <ide> const EXCLUDE_REGEXPS_SOURCES = [ <ide> 'node_modules' + escapeRegExp(path.sep) + '.*' + escapeRegExp(path.sep) + 'docs' + escapeRegExp(path.sep), <ide> 'node_modules' + escapeRegExp(path.sep) + '.*' + escapeRegExp(path.sep) + 'examples?' + escapeRegExp(path.sep), <ide> 'node_modules' + escapeRegExp(path.sep) + '.*' + escapeRegExp(path.sep) + 'samples?' + escapeRegExp(path.sep), <del> // 'node_modules' + escapeRegExp(path.sep) + '.*' + '\\.md$', <del> // 'node_modules' + escapeRegExp(path.sep) + '.*' + '\\.d\\.ts$', <del> // 'node_modules' + escapeRegExp(path.sep) + '.*' + '\\.js\\.map$' <add> 'node_modules' + escapeRegExp(path.sep) + '.*' + '\\.md$', <add> 'node_modules' + escapeRegExp(path.sep) + '.*' + '\\.d\\.ts$', <add> 'node_modules' + escapeRegExp(path.sep) + '.*' + '\\.js\\.map$' <ide> ] <ide> <ide> // Ignore spec directories in all bundled packages
1
Ruby
Ruby
fix regex to strip quotations from hstore values
2c9304891ef264409980abfac499f698876744d0
<ide><path>activerecord/lib/active_record/connection_adapters/postgresql/cast.rb <ide> def string_to_hstore(string) <ide> nil <ide> elsif String === string <ide> Hash[string.scan(HstorePair).map { |k,v| <del> v = v.upcase == 'NULL' ? nil : v.gsub(/^"(.*)"$/,'\1').gsub(/\\(.)/, '\1') <del> k = k.gsub(/^"(.*)"$/,'\1').gsub(/\\(.)/, '\1') <add> v = v.upcase == 'NULL' ? nil : v.gsub(/\A"(.*)"\Z/m,'\1').gsub(/\\(.)/, '\1') <add> k = k.gsub(/\A"(.*)"\Z/m,'\1').gsub(/\\(.)/, '\1') <ide> [k,v] <ide> }] <ide> else <ide><path>activerecord/test/cases/adapters/postgresql/hstore_test.rb <ide> def test_quoting_special_characters <ide> assert_cycle('ca' => 'cà', 'ac' => 'àc') <ide> end <ide> <add> def test_multiline <add> assert_cycle("a\nb" => "c\nd") <add> end <add> <ide> private <ide> def assert_cycle hash <ide> # test creation
2
PHP
PHP
apply fixes from styleci
3745d9a97a74185c90d76db921b6daba6d6e24f2
<ide><path>src/Illuminate/Database/Schema/Blueprint.php <ide> use BadMethodCallException; <ide> use Closure; <ide> use Illuminate\Database\Connection; <del>use Illuminate\Database\SQLiteConnection; <del>use Illuminate\Database\Schema\ForeignKeyDefinition; <ide> use Illuminate\Database\Schema\Grammars\Grammar; <add>use Illuminate\Database\SQLiteConnection; <ide> use Illuminate\Support\Fluent; <ide> use Illuminate\Support\Traits\Macroable; <ide> <ide><path>tests/Database/DatabaseMySqlSchemaGrammarTest.php <ide> public function testAddingForeignKey() <ide> $this->assertCount(1, $statements); <ide> $this->assertSame('alter table `users` add constraint `users_foo_id_foreign` foreign key (`foo_id`) references `orders` (`id`)', $statements[0]); <ide> <del> <ide> $blueprint = new Blueprint('users'); <ide> $blueprint->foreign('foo_id')->references('id')->on('orders')->cascadeOnDelete(); <ide> $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
2
Java
Java
fix trailing spaces
b47783e3186f83be6a87257a2d13c9619bccaa42
<ide><path>src/main/java/io/reactivex/rxjava3/internal/fuseable/FuseToFlowable.java <ide> * the operator goes from Flowable to some other reactive type and then the sequence calls <ide> * for toFlowable again: <ide> * <pre> <del> * {@code <add> * {@code <ide> * Single<Integer> single = Flowable.range(1, 10).reduce((a, b) -> a + b); <ide> * Flowable<Integer> flowable = single.toFlowable(); <ide> * } <ide><path>src/main/java/io/reactivex/rxjava3/internal/fuseable/FuseToMaybe.java <ide> * the operator goes from Maybe to some other reactive type and then the sequence calls <ide> * for toMaybe again: <ide> * <pre> <del> * {@code <add> * {@code <ide> * Single<Integer> single = Maybe.just(1).isEmpty(); <ide> * Maybe<Integer> maybe = single.toMaybe(); <ide> * } <ide><path>src/main/java/io/reactivex/rxjava3/internal/schedulers/SchedulerWhen.java <ide> * thread pool: <ide> * <ide> * <pre> <del> * {@code <add> * {@code <ide> * Scheduler limitScheduler = Schedulers.computation().when(workers -> { <ide> * // use merge max concurrent to limit the number of concurrent <ide> * // callbacks two at a time <ide> * to the second. <ide> * <ide> * <pre> <del> * {@code <add> * {@code <ide> * Scheduler limitScheduler = Schedulers.computation().when(workers -> { <ide> * // use merge max concurrent to limit the number of concurrent <ide> * // Observables two at a time <ide> * algorithm). <ide> * <ide> * <pre> <del> * {@code <add> * {@code <ide> * Scheduler slowScheduler = Schedulers.computation().when(workers -> { <ide> * // use concatenate to make each worker happen one at a time. <ide> * return Completable.concat(workers.map(actions -> { <ide><path>src/test/java/io/reactivex/rxjava3/observers/SerializedObserverTest.java <ide> public void run() { <ide> } <ide> }; <ide> <del> TestHelper.race(r1, r2); <add> TestHelper.race(r1, r2); <add> <ide> to.awaitDone(5, TimeUnit.SECONDS) <ide> .assertError(ex) <ide> .assertNotComplete();
4
Go
Go
display only the name of the requirement…
952c8aef3f221ee266627c26b9d8e4c0d936258f
<ide><path>integration-cli/requirement/requirement.go <ide> package requirement <ide> <ide> import ( <ide> "fmt" <add> "path" <ide> "reflect" <ide> "runtime" <add> "strings" <ide> ) <ide> <ide> type skipT interface { <ide> func Is(s skipT, requirements ...Test) { <ide> isValid := r() <ide> if !isValid { <ide> requirementFunc := runtime.FuncForPC(reflect.ValueOf(r).Pointer()).Name() <del> s.Skip(fmt.Sprintf("unmatched requirement %s", requirementFunc)) <add> s.Skip(fmt.Sprintf("unmatched requirement %s", extractRequirement(requirementFunc))) <ide> } <ide> } <ide> } <add> <add>func extractRequirement(requirementFunc string) string { <add> requirement := path.Base(requirementFunc) <add> return strings.SplitN(requirement, ".", 2)[1] <add>}
1
Text
Text
clarify `listening` event
8c12a08de56dde4e31f68c0a6944379dd8206dc8
<ide><path>doc/api/dgram.md <ide> function is passed a single `Error` object. <ide> added: v0.1.99 <ide> --> <ide> <del>The `'listening'` event is emitted whenever a socket begins listening for <del>datagram messages. This occurs as soon as UDP sockets are created. <add>The `'listening'` event is emitted once the `dgram.Socket` is addressable and <add>can receive data. This happens either explicitly with `socket.bind()` or <add>implicitly the first time data is sent using `socket.send()`. <add>Until the `dgram.Socket` is listening, the underlying system resources do not <add>exist and calls such as `socket.address()` and `socket.setTTL()` will fail. <ide> <ide> ### Event: `'message'` <ide> <!-- YAML
1
Go
Go
remove redundant format
514adcf4580effa4820be8d5e6d2c0ea9825ceb2
<ide><path>api/server/httputils/form.go <ide> package httputils <ide> <ide> import ( <del> "fmt" <add> "errors" <ide> "net/http" <ide> "path/filepath" <ide> "strconv" <ide> func ArchiveFormValues(r *http.Request, vars map[string]string) (ArchiveOptions, <ide> <ide> switch { <ide> case name == "": <del> return ArchiveOptions{}, fmt.Errorf("bad parameter: 'name' cannot be empty") <add> return ArchiveOptions{}, errors.New("bad parameter: 'name' cannot be empty") <ide> case path == "": <del> return ArchiveOptions{}, fmt.Errorf("bad parameter: 'path' cannot be empty") <add> return ArchiveOptions{}, errors.New("bad parameter: 'path' cannot be empty") <ide> } <ide> <ide> return ArchiveOptions{name, path}, nil <ide><path>builder/dockerfile/bflag.go <ide> func (bf *BFlags) Parse() error { <ide> flag.Value = value <ide> <ide> default: <del> panic(fmt.Errorf("No idea what kind of flag we have! Should never get here!")) <add> panic("No idea what kind of flag we have! Should never get here!") <ide> } <ide> <ide> } <ide><path>builder/dockerfile/bflag_test.go <ide> func TestBuilderFlags(t *testing.T) { <ide> } <ide> <ide> if flStr1.IsUsed() == true { <del> t.Fatalf("Test3 - str1 was not used!") <add> t.Fatal("Test3 - str1 was not used!") <ide> } <ide> if flBool1.IsUsed() == true { <del> t.Fatalf("Test3 - bool1 was not used!") <add> t.Fatal("Test3 - bool1 was not used!") <ide> } <ide> <ide> // --- <ide> func TestBuilderFlags(t *testing.T) { <ide> } <ide> <ide> if flStr1.Value != "HI" { <del> t.Fatalf("Str1 was supposed to default to: HI") <add> t.Fatal("Str1 was supposed to default to: HI") <ide> } <ide> if flBool1.IsTrue() { <del> t.Fatalf("Bool1 was supposed to default to: false") <add> t.Fatal("Bool1 was supposed to default to: false") <ide> } <ide> if flStr1.IsUsed() == true { <del> t.Fatalf("Str1 was not used!") <add> t.Fatal("Str1 was not used!") <ide> } <ide> if flBool1.IsUsed() == true { <del> t.Fatalf("Bool1 was not used!") <add> t.Fatal("Bool1 was not used!") <ide> } <ide> <ide> // --- <ide> func TestBuilderFlags(t *testing.T) { <ide> } <ide> <ide> if !flBool1.IsTrue() { <del> t.Fatalf("Test-b1 Bool1 was supposed to be true") <add> t.Fatal("Test-b1 Bool1 was supposed to be true") <ide> } <ide> <ide> // --- <ide> func TestBuilderFlags(t *testing.T) { <ide> } <ide> <ide> if flBool1.IsTrue() { <del> t.Fatalf("Test-b3 Bool1 was supposed to be false") <add> t.Fatal("Test-b3 Bool1 was supposed to be false") <ide> } <ide> <ide> // --- <ide><path>builder/dockerfile/builder.go <ide> func (b *Builder) build(stdout io.Writer, stderr io.Writer, out io.Writer) (stri <ide> select { <ide> case <-b.clientCtx.Done(): <ide> logrus.Debug("Builder: build cancelled!") <del> fmt.Fprintf(b.Stdout, "Build cancelled") <del> return "", fmt.Errorf("Build cancelled") <add> fmt.Fprint(b.Stdout, "Build cancelled") <add> return "", errors.New("Build cancelled") <ide> default: <ide> // Not cancelled yet, keep going... <ide> } <ide> func (b *Builder) build(stdout io.Writer, stderr io.Writer, out io.Writer) (stri <ide> } <ide> <ide> if b.image == "" { <del> return "", fmt.Errorf("No image was generated. Is your Dockerfile empty?") <add> return "", errors.New("No image was generated. Is your Dockerfile empty?") <ide> } <ide> <ide> if b.options.Squash { <ide><path>builder/dockerfile/dispatchers.go <ide> package dockerfile <ide> // package. <ide> <ide> import ( <add> "errors" <ide> "fmt" <ide> "regexp" <ide> "runtime" <ide> func from(b *Builder, args []string, attributes map[string]bool, original string <ide> // Windows cannot support a container with no base image. <ide> if name == api.NoBaseImageSpecifier { <ide> if runtime.GOOS == "windows" { <del> return fmt.Errorf("Windows does not support FROM scratch") <add> return errors.New("Windows does not support FROM scratch") <ide> } <ide> b.image = "" <ide> b.noBaseImage = true <ide> func onbuild(b *Builder, args []string, attributes map[string]bool, original str <ide> triggerInstruction := strings.ToUpper(strings.TrimSpace(args[0])) <ide> switch triggerInstruction { <ide> case "ONBUILD": <del> return fmt.Errorf("Chaining ONBUILD via `ONBUILD ONBUILD` isn't allowed") <add> return errors.New("Chaining ONBUILD via `ONBUILD ONBUILD` isn't allowed") <ide> case "MAINTAINER", "FROM": <ide> return fmt.Errorf("%s isn't allowed as an ONBUILD trigger", triggerInstruction) <ide> } <ide> func workdir(b *Builder, args []string, attributes map[string]bool, original str <ide> // <ide> func run(b *Builder, args []string, attributes map[string]bool, original string) error { <ide> if b.image == "" && !b.noBaseImage { <del> return fmt.Errorf("Please provide a source image with `from` prior to run") <add> return errors.New("Please provide a source image with `from` prior to run") <ide> } <ide> <ide> if err := b.flags.Parse(); err != nil { <ide> func healthcheck(b *Builder, args []string, attributes map[string]bool, original <ide> args = args[1:] <ide> if typ == "NONE" { <ide> if len(args) != 0 { <del> return fmt.Errorf("HEALTHCHECK NONE takes no arguments") <add> return errors.New("HEALTHCHECK NONE takes no arguments") <ide> } <ide> test := strslice.StrSlice{typ} <ide> b.runConfig.Healthcheck = &container.HealthConfig{ <ide> func healthcheck(b *Builder, args []string, attributes map[string]bool, original <ide> case "CMD": <ide> cmdSlice := handleJSONArgs(args, attributes) <ide> if len(cmdSlice) == 0 { <del> return fmt.Errorf("Missing command after HEALTHCHECK CMD") <add> return errors.New("Missing command after HEALTHCHECK CMD") <ide> } <ide> <ide> if !attributes["json"] { <ide> func volume(b *Builder, args []string, attributes map[string]bool, original stri <ide> for _, v := range args { <ide> v = strings.TrimSpace(v) <ide> if v == "" { <del> return fmt.Errorf("VOLUME specified can not be an empty string") <add> return errors.New("VOLUME specified can not be an empty string") <ide> } <ide> b.runConfig.Volumes[v] = struct{}{} <ide> } <ide><path>builder/dockerfile/dispatchers_test.go <ide> func TestFrom(t *testing.T) { <ide> <ide> if runtime.GOOS == "windows" { <ide> if err == nil { <del> t.Fatalf("Error not set on Windows") <add> t.Fatal("Error not set on Windows") <ide> } <ide> <ide> expectedError := "Windows does not support FROM scratch" <ide> func TestOnbuildIllegalTriggers(t *testing.T) { <ide> err := onbuild(b, []string{trigger.command}, nil, "") <ide> <ide> if err == nil { <del> t.Fatalf("Error should not be nil") <add> t.Fatal("Error should not be nil") <ide> } <ide> <ide> if !strings.Contains(err.Error(), trigger.expectedError) { <ide> func TestCmd(t *testing.T) { <ide> } <ide> <ide> if !b.cmdSet { <del> t.Fatalf("Command should be marked as set") <add> t.Fatal("Command should be marked as set") <ide> } <ide> } <ide> <ide> func TestEntrypoint(t *testing.T) { <ide> } <ide> <ide> if b.runConfig.Entrypoint == nil { <del> t.Fatalf("Entrypoint should be set") <add> t.Fatal("Entrypoint should be set") <ide> } <ide> <ide> var expectedEntrypoint strslice.StrSlice <ide> func TestExpose(t *testing.T) { <ide> } <ide> <ide> if b.runConfig.ExposedPorts == nil { <del> t.Fatalf("ExposedPorts should be set") <add> t.Fatal("ExposedPorts should be set") <ide> } <ide> <ide> if len(b.runConfig.ExposedPorts) != 1 { <ide> func TestVolume(t *testing.T) { <ide> } <ide> <ide> if b.runConfig.Volumes == nil { <del> t.Fatalf("Volumes should be set") <add> t.Fatal("Volumes should be set") <ide> } <ide> <ide> if len(b.runConfig.Volumes) != 1 { <ide> func TestShell(t *testing.T) { <ide> } <ide> <ide> if b.runConfig.Shell == nil { <del> t.Fatalf("Shell should be set") <add> t.Fatal("Shell should be set") <ide> } <ide> <ide> expectedShell := strslice.StrSlice([]string{shellCmd}) <ide><path>builder/dockerfile/evaluator.go <ide> package dockerfile <ide> <ide> import ( <add> "errors" <ide> "fmt" <ide> "strings" <ide> <ide> func (b *Builder) dispatch(stepN int, stepTotal int, ast *parser.Node) error { <ide> <ide> if cmd == "onbuild" { <ide> if ast.Next == nil { <del> return fmt.Errorf("ONBUILD requires at least one argument") <add> return errors.New("ONBUILD requires at least one argument") <ide> } <ide> ast = ast.Next.Children[0] <ide> strList = append(strList, ast.Value) <ide> func (b *Builder) checkDispatch(ast *parser.Node, onbuild bool) error { <ide> // least one argument <ide> if upperCasedCmd == "ONBUILD" { <ide> if ast.Next == nil { <del> return fmt.Errorf("ONBUILD requires at least one argument") <add> return errors.New("ONBUILD requires at least one argument") <ide> } <ide> } <ide> <ide> // The instruction is part of ONBUILD trigger (not the instruction itself) <ide> if onbuild { <ide> switch upperCasedCmd { <ide> case "ONBUILD": <del> return fmt.Errorf("Chaining ONBUILD via `ONBUILD ONBUILD` isn't allowed") <add> return errors.New("Chaining ONBUILD via `ONBUILD ONBUILD` isn't allowed") <ide> case "MAINTAINER", "FROM": <ide> return fmt.Errorf("%s isn't allowed as an ONBUILD trigger", upperCasedCmd) <ide> } <ide><path>builder/dockerfile/internals.go <ide> func (b *Builder) commit(id string, autoCmd strslice.StrSlice, comment string) e <ide> return nil <ide> } <ide> if b.image == "" && !b.noBaseImage { <del> return fmt.Errorf("Please provide a source image with `from` prior to commit") <add> return errors.New("Please provide a source image with `from` prior to commit") <ide> } <ide> b.runConfig.Image = b.image <ide> <ide> func (b *Builder) runContextCommand(args []string, allowRemote bool, allowLocalD <ide> } <ide> <ide> if len(infos) == 0 { <del> return fmt.Errorf("No source files were specified") <add> return errors.New("No source files were specified") <ide> } <ide> if len(infos) > 1 && !strings.HasSuffix(dest, string(os.PathSeparator)) { <ide> return fmt.Errorf("When using %s with more than one source file, the destination must be a directory and end with a /", cmdName) <ide> func (b *Builder) probeCache() (bool, error) { <ide> return false, nil <ide> } <ide> <del> fmt.Fprintf(b.Stdout, " ---> Using cache\n") <add> fmt.Fprint(b.Stdout, " ---> Using cache\n") <ide> logrus.Debugf("[BUILDER] Use cached version: %s", b.runConfig.Cmd) <ide> b.image = string(cache) <ide> <ide> func (b *Builder) probeCache() (bool, error) { <ide> <ide> func (b *Builder) create() (string, error) { <ide> if b.image == "" && !b.noBaseImage { <del> return "", fmt.Errorf("Please provide a source image with `from` prior to run") <add> return "", errors.New("Please provide a source image with `from` prior to run") <ide> } <ide> b.runConfig.Image = b.image <ide> <ide><path>builder/dockerfile/shell_parser_test.go <ide> func TestGetEnv(t *testing.T) { <ide> <ide> sw.envs = []string{} <ide> if sw.getEnv("foo") != "" { <del> t.Fatalf("2 - 'foo' should map to ''") <add> t.Fatal("2 - 'foo' should map to ''") <ide> } <ide> <ide> sw.envs = []string{"foo"} <ide> if sw.getEnv("foo") != "" { <del> t.Fatalf("3 - 'foo' should map to ''") <add> t.Fatal("3 - 'foo' should map to ''") <ide> } <ide> <ide> sw.envs = []string{"foo="} <ide> if sw.getEnv("foo") != "" { <del> t.Fatalf("4 - 'foo' should map to ''") <add> t.Fatal("4 - 'foo' should map to ''") <ide> } <ide> <ide> sw.envs = []string{"foo=bar"} <ide> if sw.getEnv("foo") != "bar" { <del> t.Fatalf("5 - 'foo' should map to 'bar'") <add> t.Fatal("5 - 'foo' should map to 'bar'") <ide> } <ide> <ide> sw.envs = []string{"foo=bar", "car=hat"} <ide> if sw.getEnv("foo") != "bar" { <del> t.Fatalf("6 - 'foo' should map to 'bar'") <add> t.Fatal("6 - 'foo' should map to 'bar'") <ide> } <ide> if sw.getEnv("car") != "hat" { <del> t.Fatalf("7 - 'car' should map to 'hat'") <add> t.Fatal("7 - 'car' should map to 'hat'") <ide> } <ide> <ide> // Make sure we grab the first 'car' in the list <ide> sw.envs = []string{"foo=bar", "car=hat", "car=bike"} <ide> if sw.getEnv("car") != "hat" { <del> t.Fatalf("8 - 'car' should map to 'hat'") <add> t.Fatal("8 - 'car' should map to 'hat'") <ide> } <ide> } <ide><path>daemon/cluster/cluster.go <ide> const ( <ide> ) <ide> <ide> // errNoSwarm is returned on leaving a cluster that was never initialized <del>var errNoSwarm = fmt.Errorf("This node is not part of a swarm") <add>var errNoSwarm = errors.New("This node is not part of a swarm") <ide> <ide> // errSwarmExists is returned on initialize or join request for a cluster that has already been activated <del>var errSwarmExists = fmt.Errorf("This node is already part of a swarm. Use \"docker swarm leave\" to leave this swarm and join another one.") <add>var errSwarmExists = errors.New("This node is already part of a swarm. Use \"docker swarm leave\" to leave this swarm and join another one.") <ide> <ide> // errSwarmJoinTimeoutReached is returned when cluster join could not complete before timeout was reached. <del>var errSwarmJoinTimeoutReached = fmt.Errorf("Timeout was reached before node was joined. The attempt to join the swarm will continue in the background. Use the \"docker info\" command to see the current swarm status of your node.") <add>var errSwarmJoinTimeoutReached = errors.New("Timeout was reached before node was joined. The attempt to join the swarm will continue in the background. Use the \"docker info\" command to see the current swarm status of your node.") <ide> <ide> // errSwarmLocked is returned if the swarm is encrypted and needs a key to unlock it. <del>var errSwarmLocked = fmt.Errorf("Swarm is encrypted and needs to be unlocked before it can be used. Please use \"docker swarm unlock\" to unlock it.") <add>var errSwarmLocked = errors.New("Swarm is encrypted and needs to be unlocked before it can be used. Please use \"docker swarm unlock\" to unlock it.") <ide> <ide> // errSwarmCertificatesExpired is returned if docker was not started for the whole validity period and they had no chance to renew automatically. <ide> var errSwarmCertificatesExpired = errors.New("Swarm certificates have expired. To replace them, leave the swarm and join again.") <ide> func (c *Cluster) Leave(force bool) error { <ide> if isLastManager(reachable, unreachable) { <ide> msg += "Removing the last manager erases all current state of the swarm. Use `--force` to ignore this message. " <ide> c.mu.Unlock() <del> return fmt.Errorf(msg) <add> return errors.New(msg) <ide> } <ide> msg += fmt.Sprintf("Removing this node leaves %v managers out of %v. Without a Raft quorum your swarm will be inaccessible. ", reachable-1, reachable+unreachable) <ide> } <ide> func (c *Cluster) Leave(force bool) error { <ide> <ide> msg += "The only way to restore a swarm that has lost consensus is to reinitialize it with `--force-new-cluster`. Use `--force` to suppress this message." <ide> c.mu.Unlock() <del> return fmt.Errorf(msg) <add> return errors.New(msg) <ide> } <ide> // release readers in here <ide> if err := nr.Stop(); err != nil { <ide> func (c *Cluster) errNoManager(st nodeState) error { <ide> if st.err == errSwarmCertificatesExpired { <ide> return errSwarmCertificatesExpired <ide> } <del> return fmt.Errorf("This node is not a swarm manager. Use \"docker swarm init\" or \"docker swarm join\" to connect this node to swarm and try again.") <add> return errors.New("This node is not a swarm manager. Use \"docker swarm init\" or \"docker swarm join\" to connect this node to swarm and try again.") <ide> } <ide> if st.swarmNode.Manager() != nil { <del> return fmt.Errorf("This node is not a swarm manager. Manager is being prepared or has trouble connecting to the cluster.") <add> return errors.New("This node is not a swarm manager. Manager is being prepared or has trouble connecting to the cluster.") <ide> } <del> return fmt.Errorf("This node is not a swarm manager. Worker nodes can't be used to view or modify cluster state. Please run this command on a manager node or promote the current node to a manager.") <add> return errors.New("This node is not a swarm manager. Worker nodes can't be used to view or modify cluster state. Please run this command on a manager node or promote the current node to a manager.") <ide> } <ide> <ide> // GetServices returns all services of a managed swarm cluster. <ide> func (c *Cluster) imageWithDigestString(ctx context.Context, image string, authC <ide> dockerRef = reference.WithDefaultTag(dockerRef) <ide> namedTaggedRef, ok := dockerRef.(reference.NamedTagged) <ide> if !ok { <del> return "", fmt.Errorf("unable to cast image to NamedTagged reference object") <add> return "", errors.New("unable to cast image to NamedTagged reference object") <ide> } <ide> <ide> repo, _, err := c.config.Backend.GetRepository(ctx, namedTaggedRef, authConfig) <ide> func (c *Cluster) CreateService(s types.ServiceSpec, encodedAuth string) (*apity <ide> <ide> ctnr := serviceSpec.Task.GetContainer() <ide> if ctnr == nil { <del> return nil, fmt.Errorf("service does not use container tasks") <add> return nil, errors.New("service does not use container tasks") <ide> } <ide> <ide> if encodedAuth != "" { <ide> func (c *Cluster) UpdateService(serviceIDOrName string, version uint64, spec typ <ide> <ide> newCtnr := serviceSpec.Task.GetContainer() <ide> if newCtnr == nil { <del> return nil, fmt.Errorf("service does not use container tasks") <add> return nil, errors.New("service does not use container tasks") <ide> } <ide> <ide> if encodedAuth != "" { <ide> func (c *Cluster) UpdateService(serviceIDOrName string, version uint64, spec typ <ide> ctnr = currentService.Spec.Task.GetContainer() <ide> case apitypes.RegistryAuthFromPreviousSpec: <ide> if currentService.PreviousSpec == nil { <del> return nil, fmt.Errorf("service does not have a previous spec") <add> return nil, errors.New("service does not have a previous spec") <ide> } <ide> ctnr = currentService.PreviousSpec.Task.GetContainer() <ide> default: <del> return nil, fmt.Errorf("unsupported registryAuthFromValue") <add> return nil, errors.New("unsupported registryAuthFrom value") <ide> } <ide> if ctnr == nil { <del> return nil, fmt.Errorf("service does not use container tasks") <add> return nil, errors.New("service does not use container tasks") <ide> } <ide> newCtnr.PullOptions = ctnr.PullOptions <ide> // update encodedAuth so it can be used to pin image by digest <ide> func (c *Cluster) WaitForDetachment(ctx context.Context, networkName, networkID, <ide> state := c.currentNodeState() <ide> if state.swarmNode == nil || state.swarmNode.Agent() == nil { <ide> c.mu.RUnlock() <del> return fmt.Errorf("invalid cluster node while waiting for detachment") <add> return errors.New("invalid cluster node while waiting for detachment") <ide> } <ide> <ide> c.mu.RUnlock() <ide> func (c *Cluster) AttachNetwork(target string, containerID string, addresses []s <ide> state := c.currentNodeState() <ide> if state.swarmNode == nil || state.swarmNode.Agent() == nil { <ide> c.mu.Unlock() <del> return nil, fmt.Errorf("invalid cluster node while attaching to network") <add> return nil, errors.New("invalid cluster node while attaching to network") <ide> } <ide> if attacher, ok := c.attachers[aKey]; ok { <ide> c.mu.Unlock() <ide> func validateAndSanitizeJoinRequest(req *types.JoinRequest) error { <ide> return fmt.Errorf("invalid ListenAddr %q: %v", req.ListenAddr, err) <ide> } <ide> if len(req.RemoteAddrs) == 0 { <del> return fmt.Errorf("at least 1 RemoteAddr is required to join") <add> return errors.New("at least 1 RemoteAddr is required to join") <ide> } <ide> for i := range req.RemoteAddrs { <ide> req.RemoteAddrs[i], err = validateAddr(req.RemoteAddrs[i]) <ide> func validateAndSanitizeJoinRequest(req *types.JoinRequest) error { <ide> <ide> func validateAddr(addr string) (string, error) { <ide> if addr == "" { <del> return addr, fmt.Errorf("invalid empty address") <add> return addr, errors.New("invalid empty address") <ide> } <ide> newaddr, err := opts.ParseTCPAddr(addr, defaultAddr) <ide> if err != nil { <ide> func initClusterSpec(node *swarmnode.Node, spec types.Spec) error { <ide> time.Sleep(200 * time.Millisecond) <ide> continue <ide> } <del> return fmt.Errorf("empty list of clusters was returned") <add> return errors.New("empty list of clusters was returned") <ide> } <ide> cluster = lcr.Clusters[0] <ide> break <ide><path>daemon/cluster/executor/container/adapter.go <ide> package container <ide> import ( <ide> "encoding/base64" <ide> "encoding/json" <add> "errors" <ide> "fmt" <ide> "io" <ide> "strings" <ide> func (c *containerAdapter) create(ctx context.Context) error { <ide> <ide> container := c.container.task.Spec.GetContainer() <ide> if container == nil { <del> return fmt.Errorf("unable to get container from task spec") <add> return errors.New("unable to get container from task spec") <ide> } <ide> <ide> // configure secrets <ide> func (c *containerAdapter) logs(ctx context.Context, options api.LogSubscription <ide> // See protobuf documentation for details of how this works. <ide> apiOptions.Tail = fmt.Sprint(-options.Tail - 1) <ide> } else if options.Tail > 0 { <del> return nil, fmt.Errorf("tail relative to start of logs not supported via docker API") <add> return nil, errors.New("tail relative to start of logs not supported via docker API") <ide> } <ide> <ide> if len(options.Streams) == 0 { <ide><path>daemon/cluster/executor/container/errors.go <ide> package container <ide> <del>import "fmt" <add>import ( <add> "errors" <add>) <ide> <ide> var ( <ide> // ErrImageRequired returned if a task is missing the image definition. <del> ErrImageRequired = fmt.Errorf("dockerexec: image required") <add> ErrImageRequired = errors.New("dockerexec: image required") <ide> <ide> // ErrContainerDestroyed returned when a container is prematurely destroyed <ide> // during a wait call. <del> ErrContainerDestroyed = fmt.Errorf("dockerexec: container destroyed") <add> ErrContainerDestroyed = errors.New("dockerexec: container destroyed") <ide> <ide> // ErrContainerUnhealthy returned if controller detects the health check failure <del> ErrContainerUnhealthy = fmt.Errorf("dockerexec: unhealthy container") <add> ErrContainerUnhealthy = errors.New("dockerexec: unhealthy container") <ide> ) <ide><path>daemon/cluster/executor/container/health_test.go <ide> func TestHealthStates(t *testing.T) { <ide> } <ide> case <-timer.C: <ide> if expectedErr != nil { <del> t.Fatalf("time limit exceeded, didn't get expected error") <add> t.Fatal("time limit exceeded, didn't get expected error") <ide> } <ide> } <ide> } <ide><path>daemon/cluster/executor/container/validate.go <ide> package container <ide> <ide> import ( <add> "errors" <ide> "fmt" <ide> "os" <ide> "path/filepath" <ide> func validateMounts(mounts []api.Mount) error { <ide> } <ide> case api.MountTypeTmpfs: <ide> if mount.Source != "" { <del> return fmt.Errorf("invalid tmpfs source, source must be empty") <add> return errors.New("invalid tmpfs source, source must be empty") <ide> } <ide> default: <ide> return fmt.Errorf("invalid mount type: %s", mount.Type) <ide><path>daemon/config.go <ide> func parseClusterAdvertiseSettings(clusterStore, clusterAdvertise string) (strin <ide> return "", errDiscoveryDisabled <ide> } <ide> if clusterStore == "" { <del> return "", fmt.Errorf("invalid cluster configuration. --cluster-advertise must be accompanied by --cluster-store configuration") <add> return "", errors.New("invalid cluster configuration. --cluster-advertise must be accompanied by --cluster-store configuration") <ide> } <ide> <ide> advertise, err := discovery.ParseAdvertise(clusterAdvertise) <ide><path>daemon/daemon.go <ide> var ( <ide> // DefaultInitBinary is the name of the default init binary <ide> DefaultInitBinary = "docker-init" <ide> <del> errSystemNotSupported = fmt.Errorf("The Docker daemon is not supported on this platform.") <add> errSystemNotSupported = errors.New("The Docker daemon is not supported on this platform.") <ide> ) <ide> <ide> // Daemon holds information about the Docker daemon. <ide> func NewDaemon(config *Config, registryService registry.Service, containerdRemot <ide> // Check if Devices cgroup is mounted, it is hard requirement for container security, <ide> // on Linux. <ide> if runtime.GOOS == "linux" && !sysInfo.CgroupDevicesEnabled { <del> return nil, fmt.Errorf("Devices cgroup isn't mounted") <add> return nil, errors.New("Devices cgroup isn't mounted") <ide> } <ide> <ide> d.ID = trustKey.PublicKey().KeyID() <ide> func (daemon *Daemon) shutdownContainer(c *container.Container) error { <ide> logrus.Debugf("Found container %s is paused, sending SIGTERM before unpausing it", c.ID) <ide> sig, ok := signal.SignalMap["TERM"] <ide> if !ok { <del> return fmt.Errorf("System does not support SIGTERM") <add> return errors.New("System does not support SIGTERM") <ide> } <ide> if err := daemon.kill(c, int(sig)); err != nil { <ide> return fmt.Errorf("sending SIGTERM to container %s with error: %v", c.ID, err) <ide> func (daemon *Daemon) shutdownContainer(c *container.Container) error { <ide> logrus.Debugf("container %s failed to exit in %d second of SIGTERM, sending SIGKILL to force", c.ID, stopTimeout) <ide> sig, ok := signal.SignalMap["KILL"] <ide> if !ok { <del> return fmt.Errorf("System does not support SIGKILL") <add> return errors.New("System does not support SIGKILL") <ide> } <ide> if err := daemon.kill(c, int(sig)); err != nil { <ide> logrus.Errorf("Failed to SIGKILL container %s", c.ID) <ide> func (daemon *Daemon) configureVolumes(rootUID, rootGID int) (*store.VolumeStore <ide> volumedrivers.RegisterPluginGetter(daemon.PluginStore) <ide> <ide> if !volumedrivers.Register(volumesDriver, volumesDriver.Name()) { <del> return nil, fmt.Errorf("local volume driver could not be registered") <add> return nil, errors.New("local volume driver could not be registered") <ide> } <ide> return store.New(daemon.configStore.Root) <ide> } <ide> func (daemon *Daemon) networkOptions(dconfig *Config, pg plugingetter.PluginGett <ide> if strings.TrimSpace(dconfig.ClusterStore) != "" { <ide> kv := strings.Split(dconfig.ClusterStore, "://") <ide> if len(kv) != 2 { <del> return nil, fmt.Errorf("kv store daemon config must be of the form KV-PROVIDER://KV-URL") <add> return nil, errors.New("kv store daemon config must be of the form KV-PROVIDER://KV-URL") <ide> } <ide> options = append(options, nwconfig.OptionKVProvider(kv[0])) <ide> options = append(options, nwconfig.OptionKVProviderURL(kv[1])) <ide><path>daemon/logs.go <ide> package daemon <ide> <ide> import ( <del> "fmt" <add> "errors" <ide> "io" <ide> "strconv" <ide> "time" <ide> import ( <ide> // configured with the given struct. <ide> func (daemon *Daemon) ContainerLogs(ctx context.Context, containerName string, config *backend.ContainerLogsConfig, started chan struct{}) error { <ide> if !(config.ShowStdout || config.ShowStderr) { <del> return fmt.Errorf("You must choose at least one stream") <add> return errors.New("You must choose at least one stream") <ide> } <ide> container, err := daemon.GetContainer(containerName) <ide> if err != nil { <ide><path>daemon/rename.go <ide> package daemon <ide> <ide> import ( <add> "errors" <ide> "fmt" <ide> "strings" <ide> <ide> func (daemon *Daemon) ContainerRename(oldName, newName string) error { <ide> ) <ide> <ide> if oldName == "" || newName == "" { <del> return fmt.Errorf("Neither old nor new names may be empty") <add> return errors.New("Neither old nor new names may be empty") <ide> } <ide> <ide> if newName[0] != '/' { <ide> func (daemon *Daemon) ContainerRename(oldName, newName string) error { <ide> oldIsAnonymousEndpoint := container.NetworkSettings.IsAnonymousEndpoint <ide> <ide> if oldName == newName { <del> return fmt.Errorf("Renaming a container with the same name as its current name") <add> return errors.New("Renaming a container with the same name as its current name") <ide> } <ide> <ide> container.Lock() <ide><path>daemon/search_test.go <ide> package daemon <ide> <ide> import ( <del> "fmt" <add> "errors" <ide> "strings" <ide> "testing" <ide> <ide> type FakeService struct { <ide> <ide> func (s *FakeService) Search(ctx context.Context, term string, limit int, authConfig *types.AuthConfig, userAgent string, headers map[string][]string) (*registrytypes.SearchResults, error) { <ide> if s.shouldReturnError { <del> return nil, fmt.Errorf("Search unknown error") <add> return nil, errors.New("Search unknown error") <ide> } <ide> return &registrytypes.SearchResults{ <ide> Query: s.term, <ide><path>distribution/pull.go <ide> package distribution <ide> <ide> import ( <add> "errors" <ide> "fmt" <ide> <ide> "github.com/Sirupsen/logrus" <ide> func writeStatus(requestedTag string, out progress.Output, layersDownloaded bool <ide> // ValidateRepoName validates the name of a repository. <ide> func ValidateRepoName(name string) error { <ide> if name == "" { <del> return fmt.Errorf("Repository name can't be empty") <add> return errors.New("Repository name can't be empty") <ide> } <ide> if name == api.NoBaseImageSpecifier { <ide> return fmt.Errorf("'%s' is a reserved name", api.NoBaseImageSpecifier)
20
Ruby
Ruby
stop debug exploding when zsh is used
6fe261bc5c1da9cd3629c03fd47810f743d532a4
<ide><path>Library/Homebrew/utils.rb <ide> def interactive_shell(f = nil) <ide> end <ide> <ide> if ENV["SHELL"].include?("zsh") && ENV["HOME"].start_with?(HOMEBREW_TEMP.resolved_path.to_s) <add> FileUtils.mkdir_p ENV["HOME"] <ide> FileUtils.touch "#{ENV["HOME"]}/.zshrc" <ide> end <ide>
1
Ruby
Ruby
pass explicit sort to handle apfs
35fae7ce6ab9a8bb0bde731b294771166ed9bdef
<ide><path>Library/Homebrew/cmd/tap-info.rb <ide> module Homebrew <ide> module_function <ide> <ide> def tap_info <add> # TODO: This still returns a non-alphabetised list on APFS. <ide> if ARGV.include? "--installed" <ide> taps = Tap <ide> else <del> taps = ARGV.named.map do |name| <add> taps = ARGV.named.sort.map do |name| <ide> Tap.fetch(name) <ide> end <ide> end
1
Python
Python
remove unnecessary else
dca8b983568e1ca7534ad7244e6eb57e1b87cc68
<ide><path>rest_framework/mixins.py <ide> def update(self, request, *args, **kwargs): <ide> self.object = serializer.save(force_insert=True) <ide> self.post_save(self.object, created=True) <ide> return Response(serializer.data, status=status.HTTP_201_CREATED) <del> else: <del> self.object = serializer.save(force_update=True) <del> self.post_save(self.object, created=False) <del> return Response(serializer.data, status=status.HTTP_200_OK) <add> <add> self.object = serializer.save(force_update=True) <add> self.post_save(self.object, created=False) <add> return Response(serializer.data, status=status.HTTP_200_OK) <ide> <ide> def partial_update(self, request, *args, **kwargs): <ide> kwargs['partial'] = True
1
Python
Python
switch parameter name to 'kind' over 'method'
cde60cee195660f2dafb2993e609d66559525fe8
<ide><path>numpy/lib/arraysetops.py <ide> def setxor1d(ar1, ar2, assume_unique=False): <ide> <ide> <ide> def _in1d_dispatcher(ar1, ar2, assume_unique=None, invert=None, <del> method=None): <add> kind=None): <ide> return (ar1, ar2) <ide> <ide> <ide> @array_function_dispatch(_in1d_dispatcher) <del>def in1d(ar1, ar2, assume_unique=False, invert=False, method='auto'): <add>def in1d(ar1, ar2, assume_unique=False, invert=False, kind=None): <ide> """ <ide> Test whether each element of a 1-D array is also present in a second array. <ide> <ide> def in1d(ar1, ar2, assume_unique=False, invert=False, method='auto'): <ide> False where an element of `ar1` is in `ar2` and True otherwise). <ide> Default is False. ``np.in1d(a, b, invert=True)`` is equivalent <ide> to (but is faster than) ``np.invert(in1d(a, b))``. <del> method : {'auto', 'sort', 'dictionary'}, optional <add> kind : {None, 'sort', 'dictionary'}, optional <ide> The algorithm to use. This will not affect the final result, <del> but will affect the speed. Default is 'auto'. <add> but will affect the speed. Default will select automatically <add> based on memory considerations. <ide> <ide> - If 'sort', will use a mergesort-based approach. This will have <ide> a memory usage of roughly 6 times the sum of the sizes of <ide> def in1d(ar1, ar2, assume_unique=False, invert=False, method='auto'): <ide> to be the faster method if the following formula is true: <ide> `log10(len(ar2)) > (log10(max(ar2)-min(ar2)) - 2.27) / 0.927`, <ide> but may use greater memory. <del> - If 'auto', will automatically choose 'dictionary' if <add> - If `None`, will automatically choose 'dictionary' if <ide> the required memory allocation is less than or equal to <ide> 6 times the sum of the sizes of `ar1` and `ar2`, <ide> otherwise will use 'sort'. This is done to not use <ide> a large amount of memory by default, even though <del> 'dictionary' may be faster in most cases. <add> 'dictionary' may be faster in most cases. <ide> <ide> .. versionadded:: 1.8.0 <ide> <ide> def in1d(ar1, ar2, assume_unique=False, invert=False, method='auto'): <ide> integer_arrays = (np.issubdtype(ar1.dtype, np.integer) and <ide> np.issubdtype(ar2.dtype, np.integer)) <ide> <del> if method not in {'auto', 'sort', 'dictionary'}: <add> if kind not in {None, 'sort', 'dictionary'}: <ide> raise ValueError( <del> "Invalid method: {0}. ".format(method) <del> + "Please use 'auto', 'sort' or 'dictionary'.") <add> "Invalid kind: {0}. ".format(kind) <add> + "Please use None, 'sort' or 'dictionary'.") <ide> <del> if integer_arrays and method in {'auto', 'dictionary'}: <add> if integer_arrays and kind in {None, 'dictionary'}: <ide> ar2_min = np.min(ar2) <ide> ar2_max = np.max(ar2) <ide> ar1_size = ar1.size <ide> def in1d(ar1, ar2, assume_unique=False, invert=False, method='auto'): <ide> below_memory_constraint = False <ide> <ide> # Use the fast integer algorithm <del> if below_memory_constraint or method == 'dictionary': <add> if below_memory_constraint or kind == 'dictionary': <ide> <ide> if invert: <ide> outgoing_array = np.ones_like(ar1, dtype=bool) <ide> def in1d(ar1, ar2, assume_unique=False, invert=False, method='auto'): <ide> ar2_min] <ide> <ide> return outgoing_array <del> elif method == 'dictionary': <add> elif kind == 'dictionary': <ide> raise ValueError( <del> "'dictionary' method is only " <add> "The 'dictionary' method is only " <ide> "supported for boolean or integer arrays. " <del> "Please select 'sort' or 'auto' for the method." <add> "Please select 'sort' or None for kind." <ide> ) <ide> <ide> <ide> def in1d(ar1, ar2, assume_unique=False, invert=False, method='auto'): <ide> <ide> <ide> def _isin_dispatcher(element, test_elements, assume_unique=None, invert=None, <del> method=None): <add> kind=None): <ide> return (element, test_elements) <ide> <ide> <ide> @array_function_dispatch(_isin_dispatcher) <ide> def isin(element, test_elements, assume_unique=False, invert=False, <del> method='auto'): <add> kind=None): <ide> """ <ide> Calculates ``element in test_elements``, broadcasting over `element` only. <ide> Returns a boolean array of the same shape as `element` that is True <ide> def isin(element, test_elements, assume_unique=False, invert=False, <ide> calculating `element not in test_elements`. Default is False. <ide> ``np.isin(a, b, invert=True)`` is equivalent to (but faster <ide> than) ``np.invert(np.isin(a, b))``. <del> method : {'auto', 'sort', 'dictionary'}, optional <add> kind : {None, 'sort', 'dictionary'}, optional <ide> The algorithm to use. This will not affect the final result, <del> but will affect the speed. Default is 'auto'. <add> but will affect the speed. Default will select automatically <add> based on memory considerations. <ide> <ide> - If 'sort', will use a mergesort-based approach. This will have <ide> a memory usage of roughly 6 times the sum of the sizes of <ide> def isin(element, test_elements, assume_unique=False, invert=False, <ide> to be the faster method if the following formula is true: <ide> `log10(len(ar2)) > (log10(max(ar2)-min(ar2)) - 2.27) / 0.927`, <ide> but may use greater memory. <del> - If 'auto', will automatically choose the method which is <del> expected to perform the fastest, using the above <del> formula. For larger sizes or smaller range, <del> 'dictionary' is chosen. For larger range or smaller <del> sizes, 'sort' is chosen. <add> - If `None`, will automatically choose 'dictionary' if <add> the required memory allocation is less than or equal to <add> 6 times the sum of the sizes of `ar1` and `ar2`, <add> otherwise will use 'sort'. This is done to not use <add> a large amount of memory by default, even though <add> 'dictionary' may be faster in most cases. <add> <ide> <ide> Returns <ide> ------- <ide> def isin(element, test_elements, assume_unique=False, invert=False, <ide> """ <ide> element = np.asarray(element) <ide> return in1d(element, test_elements, assume_unique=assume_unique, <del> invert=invert, method=method).reshape(element.shape) <add> invert=invert, kind=kind).reshape(element.shape) <ide> <ide> <ide> def _union1d_dispatcher(ar1, ar2):
1
Ruby
Ruby
add --git option to 'brew install -i'
54b5a7afbb7d562c3ee3adf607d6067cd6b7d2dc
<ide><path>Library/Homebrew/install.rb <ide> def install f <ide> ohai "Entering interactive mode" <ide> puts "Type `exit' to return and finalize the installation" <ide> puts "Install to this prefix: #{f.prefix}" <add> <add> if ARGV.flag? '--git' <add> system "git init" <add> system "git add -A" <add> puts "This folder is now a git repo. Make your changes and then use:" <add> puts " git diff | pbcopy" <add> puts "to copy the diff to the clipboard." <add> end <add> <ide> interactive_shell <ide> nil <ide> elsif ARGV.include? '--help'
1
Go
Go
add realchroot for non linux/windows
34d5b8867fe83403a6998d043a32a49e087f2477
<ide><path>pkg/chrootarchive/chroot_unix.go <ide> func chroot(path string) error { <ide> } <ide> return unix.Chdir("/") <ide> } <add> <add>func realChroot(path string) error { <add> return chroot(path) <add>}
1
PHP
PHP
fix various failing tests
0607437abd647d5e3145f6fbc4149d4c4b1fabff
<ide><path>lib/Cake/Test/Case/View/Helper/CacheHelperTest.php <ide> public function testComplexNoCache () { <ide> $result = $View->render('sequencial_nocache'); <ide> <ide> $this->assertNotRegExp('/cake:nocache/', $result); <del> $this->assertNotRegExpy('/php echo/', $result); <add> $this->assertNotRegExp('/php echo/', $result); <ide> $this->assertRegExp('/A\. Layout Before Content/', $result); <ide> $this->assertRegExp('/B\. In Plain Element/', $result); <ide> $this->assertRegExp('/C\. Layout After Test Element/', $result); <ide><path>lib/Cake/Test/Case/View/Helper/JsHelperTest.php <ide> public function setUp() { <ide> Configure::write('Asset.timestamp', false); <ide> <ide> $controller = null; <del> $this->View = $this->getMock('View', array('addScript'), array(&$controller)); <add> $this->View = $this->getMock('View', array('append'), array(&$controller)); <ide> $this->Js = new JsHelper($this->View, 'Option'); <ide> $request = new CakeRequest(null, false); <ide> $this->Js->request = $request; <ide> public function testWriteScriptsNoFile() { <ide> $result = $this->Js->writeBuffer(array('onDomReady' => true, 'cache' => false, 'clear' => false)); <ide> <ide> $this->View->expects($this->once()) <del> ->method('addScript') <del> ->with($this->matchesRegularExpression('/one\s\=\s1;\ntwo\s\=\s2;/')); <add> ->method('append') <add> ->with('script', $this->matchesRegularExpression('/one\s\=\s1;\ntwo\s\=\s2;/')); <ide> $result = $this->Js->writeBuffer(array('onDomReady' => false, 'inline' => false, 'cache' => false)); <ide> } <ide> <ide> public function testWriteBufferNotInline() { <ide> $this->Js->set('foo', 1); <ide> <ide> $this->View->expects($this->once()) <del> ->method('addScript') <del> ->with($this->matchesRegularExpression('#<script type="text\/javascript">window.app \= \{"foo"\:1\}\;<\/script>#')); <add> ->method('append') <add> ->with('script', $this->matchesRegularExpression('#<script type="text\/javascript">window.app \= \{"foo"\:1\}\;<\/script>#')); <ide> <ide> $result = $this->Js->writeBuffer(array('onDomReady' => false, 'inline' => false, 'safe' => false)); <ide> } <ide> class JsBaseEngineTest extends CakeTestCase { <ide> public function setUp() { <ide> parent::setUp(); <ide> $controller = null; <del> $this->View = $this->getMock('View', array('addScript'), array(&$controller)); <add> $this->View = $this->getMock('View', array('append'), array(&$controller)); <ide> $this->JsEngine = new OptionEngineHelper($this->View); <ide> } <ide> <ide><path>lib/Cake/TestSuite/ControllerTestCase.php <ide> class InterceptContentHelper extends Helper { <ide> * @param string $viewFile The view file <ide> */ <ide> public function afterRender($viewFile) { <del> $this->_View->_viewNoLayout = $this->_View->output; <add> $this->_View->assign('__view_no_layout__', $this->_View->fetch('content')); <ide> $this->_View->Helpers->unload('InterceptContent'); <ide> } <ide> } <ide> protected function _testAction($url = '', $options = array()) { <ide> $this->vars = $this->controller->viewVars; <ide> $this->contents = $this->controller->response->body(); <ide> if (isset($this->controller->View)) { <del> $this->view = $this->controller->View->_viewNoLayout; <add> $this->view = $this->controller->View->fetch('__view_no_layout__'); <ide> } <ide> $this->__dirtyController = true; <ide> $this->headers = $Dispatch->response->header(); <ide><path>lib/Cake/View/JsonView.php <ide> public function render($view = null, $layout = null) { <ide> } else { <ide> $data = isset($this->viewVars[$serialize]) ? $this->viewVars[$serialize] : null; <ide> } <del> return $this->output = json_encode($data); <add> $content = json_encode($data); <add> $this->Blocks->set('content', $content); <add> return $content; <ide> } <ide> if ($view !== false && $viewFileName = $this->_getViewFileName($view)) { <del> return $this->output = $this->_render($viewFileName); <add> $content = $this->_render($viewFileName); <add> $this->Blocks->set('content', $content); <add> return $content; <ide> } <ide> } <ide> <ide><path>lib/Cake/View/View.php <ide> protected function _render($viewFile, $data = array()) { <ide> if ($this->Blocks->active()) { <ide> throw new CakeException(__d('cake_dev', 'The "%s" block was left open.', $this->Blocks->active())); <ide> } <del> $content = $this->Helpers->trigger( <add> $result = $this->Helpers->trigger( <ide> 'afterRenderFile', <ide> array($viewFile, $content), <ide> array('modParams' => 1) <ide> ); <add> if ($result !== true) { <add> $content = $result; <add> } <ide> <ide> if (isset($this->_parents[$viewFile])) { <ide> $this->_stack[] = $this->fetch('content'); <ide><path>lib/Cake/View/XmlView.php <ide> public function render($view = null, $layout = null) { <ide> } else { <ide> $data = isset($this->viewVars[$serialize]) ? $this->viewVars[$serialize] : null; <ide> } <del> return $this->output = Xml::fromArray($data)->asXML(); <add> $content = Xml::fromArray($data)->asXML(); <add> $this->Blocks->set('content', $content); <add> return $content; <ide> } <ide> if ($view !== false && $viewFileName = $this->_getViewFileName($view)) { <del> return $this->output = $this->_render($viewFileName); <add> $content = $this->_render($viewFileName); <add> $this->Blocks->set('content', (string)$content); <add> return $content; <ide> } <ide> } <ide>
6
Text
Text
add few information about missing steps [ci skip]
a08cc479389a44aa34529bfa5bdce6baee2fc7c1
<ide><path>guides/source/upgrading_ruby_on_rails.md <ide> The following changes are meant for upgrading your application to Rails 4.0. <ide> <ide> ### Gemfile <ide> <del>Rails 4.0 removed the `assets` group from Gemfile. You'd need to remove that line from your Gemfile when upgrading. <add>Rails 4.0 removed the `assets` group from Gemfile. You'd need to remove that <add>line from your Gemfile when upgrading. You should also update your application <add>file (in `config/application.rb`): <add> <add>```ruby <add># Require the gems listed in Gemfile, including any gems <add># you've limited to :test, :development, or :production. <add>Bundler.require(:default, Rails.env) <add>``` <ide> <ide> ### vendor/plugins <ide> <ide> Rails 4.0 no longer supports loading plugins from `vendor/plugins`. You must rep <ide> <ide> * Rails 4.0 has removed `attr_accessible` and `attr_protected` feature in favor of Strong Parameters. You can use the [Protected Attributes gem](https://github.com/rails/protected_attributes) to a smoothly upgrade path. <ide> <add>* If you are not using Protected Attributes, you can remove any options related to <add>this gem such as `whitelist_attributes` or `mass_assignment_sanitizer` options. <add> <ide> * Rails 4.0 requires that scopes use a callable object such as a Proc or lambda: <ide> <ide> ```ruby <ide> Please read [Pull Request #9978](https://github.com/rails/rails/pull/9978) for d <ide> <ide> * Rails 4.0 deprecates the `dom_id` and `dom_class` methods in controllers (they are fine in views). You will need to include the `ActionView::RecordIdentifier` module in controllers requiring this feature. <ide> <add>* Rails 4.0 deprecates the `:confirm` option for the `link_to` helper. You should <add>instead rely on a data attribute (e.g. `data: { confirm: 'Are you sure?' }`). <add>This deprecation also concerns the helpers based on this one (such as `link_to_if` <add>or `link_to_unless`). <add> <ide> * Rails 4.0 changed how `assert_generates`, `assert_recognizes`, and `assert_routing` work. Now all these assertions raise `Assertion` instead of `ActionController::RoutingError`. <ide> <ide> * Rails 4.0 raises an `ArgumentError` if clashing named routes are defined. This can be triggered by explicitly defined named routes or by the `resources` method. Here are two examples that clash with routes named `example_path`: <ide> Active Record Observer and Action Controller Sweeper have been extracted to the <ide> ### sprockets-rails <ide> <ide> * `assets:precompile:primary` has been removed. Use `assets:precompile` instead. <add>* The `config.assets.compress` option should be changed to <add>`config.assets.js_compressor` like so for instance: <add> <add>```ruby <add>config.assets.js_compressor = :uglifier <add>``` <ide> <ide> ### sass-rails <ide>
1
Text
Text
fix diffrent naming in getting_started.md
9233f52bd96081c728b7087af9435d4fbadb7e46
<ide><path>guides/source/getting_started.md <ide> new articles. Create a file called `app/views/articles/edit.html.erb` and make <ide> it look as follows: <ide> <ide> ```html+erb <del><h1>Editing article</h1> <add><h1>Edit article</h1> <ide> <ide> <%= form_for :article, url: article_path(@article), method: :patch do |f| %> <ide>
1