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
remove isintance change for contrib strategy
21a4ad75c845ffaf9602318ab9c837977d5a9852
<ide><path>official/resnet/resnet_run_loop.py <ide> def input_fn_eval(): <ide> train_epochs = (0 if flags_obj.eval_only or not flags_obj.train_epochs else <ide> flags_obj.train_epochs) <ide> <del> use_train_and_evaluate = flags_obj.use_train_and_evaluate or isinstance( <del> distribution_strategy, tf.contrib.distribute.CollectiveAllReduceStrategy) <add> use_train_and_evaluate = flags_obj.use_train_and_evaluate or ( <add> distribution_strategy.__class__.__name__ == 'CollectiveAllReduceStrategy') <ide> if use_train_and_evaluate: <ide> train_spec = tf.estimator.TrainSpec( <ide> input_fn=lambda: input_fn_train(train_epochs), hooks=train_hooks,
1
Ruby
Ruby
upgrade outdated formulae with `brew install`
56e6710064bcbe8edc1caa97ed0bfb6ac8450e99
<ide><path>Library/Homebrew/cmd/install.rb <ide> def install_formula(f, args:) <ide> f.print_tap_action <ide> build_options = f.build <ide> <add> if f.outdated? && !f.head? <add> formulae = [f] + f.old_installed_formulae <add> version_upgrade = "#{f.linked_version} -> #{f.pkg_version}" <add> <add> oh1 <<~EOS <add> #{f.name} #{f.linked_version} is installed and out of date <add> Upgrading #{Formatter.identifier(f.name)} #{version_upgrade} <add> EOS <add> outdated_kegs = formulae.map(&:linked_keg) <add> .select(&:directory?) <add> .map { |k| Keg.new(k.resolved_path) } <add> linked_kegs = outdated_kegs.select(&:linked?) <add> end <add> <ide> fi = FormulaInstaller.new( <ide> f, <ide> **{ <ide> def install_formula(f, args:) <ide> ) <ide> fi.prelude <ide> fi.fetch <add> <add> outdated_kegs.each(&:unlink) if outdated_kegs.present? <add> <ide> fi.install <ide> fi.finish <ide> rescue FormulaInstallationAlreadyAttemptedError <ide> def install_formula(f, args:) <ide> nil <ide> rescue CannotInstallFormulaError => e <ide> ofail e.message <add> ensure <add> begin <add> # Re-link kegs if upgrade fails <add> linked_kegs.each(&:link) unless formula.latest_version_installed? <add> rescue <add> nil <add> end <ide> end <ide> end <ide><path>Library/Homebrew/formula_installer.rb <ide> def install <ide> message = <<~EOS <ide> #{formula.name} #{formula.linked_version} is already installed <ide> EOS <del> if formula.outdated? && !formula.head? <del> message += <<~EOS <del> To upgrade to #{formula.pkg_version}, run: <del> brew upgrade #{formula.full_name} <del> EOS <del> elsif only_deps? <add> if only_deps? <ide> message = nil <ide> else <ide> # some other version is already installed *and* linked
2
Ruby
Ruby
fix rubocop warnings
7b41ccd2ea842f81929c747d3a558123f98834be
<ide><path>Library/Homebrew/cmd/unlinkapps.rb <ide> def unlinkapps_from_dir(target_dir, opts = {}) <ide> <ide> def unlinkapps_unlink?(target_app, opts = {}) <ide> # Skip non-symlinks and symlinks that don't point into the Homebrew prefix. <del> app = "#{target_app.readlink}" if target_app.symlink? <add> app = target_app.readlink.to_s if target_app.symlink? <ide> return false unless app && app.start_with?(*UNLINKAPPS_PREFIXES) <ide> <ide> if opts.fetch(:prune, false)
1
Javascript
Javascript
use transform prop in panresponderexample
917f83c94043d78b1c7dd301abb5716db2b5d563
<ide><path>packages/rn-tester/js/examples/PanResponder/PanResponderExample.js <ide> class PanResponderExample extends React.Component<Props, State> { <ide> styles.circle, <ide> // $FlowFixMe[incompatible-type] <ide> { <del> translateX: this.state.left, <del> translateY: this.state.top, <add> transform: [ <add> {translateX: this.state.left}, <add> {translateY: this.state.top}, <add> ], <ide> backgroundColor: this.state.pressed ? 'blue' : 'green', <ide> }, <ide> ]}
1
Javascript
Javascript
reject pending promises when animation is updated
b55b361f97461996eec01c6013c6617601c77b12
<ide><path>src/core/core.animation.js <ide> export default class Animation { <ide> update(cfg, to, date) { <ide> const me = this; <ide> if (me._active) { <add> me._notify(false); <add> <ide> const currentValue = me._target[me._prop]; <ide> const elapsed = date - me._start; <ide> const remain = me._duration - elapsed; <ide><path>src/core/core.animations.js <ide> export default class Animations { <ide> // So any new updates to the shared options are observed <ide> awaitAll(target.options.$animations, newOptions).then(() => { <ide> target.options = newOptions; <add> }, () => { <add> // rejected, noop <ide> }); <ide> } <ide> <ide><path>test/specs/core.animations.tests.js <ide> describe('Chart.animations', function() { <ide> done(); <ide> }, 300); <ide> }); <add> <add> it('should not assign shared options to target when animations are cancelled', function(done) { <add> const chart = { <add> draw: function() {}, <add> options: { <add> animation: { <add> debug: false <add> } <add> } <add> }; <add> const anims = new Chart.Animations(chart, {value: {duration: 100}, option: {duration: 200}}); <add> <add> const target = { <add> value: 1, <add> options: { <add> option: 2 <add> } <add> }; <add> const sharedOpts = {option: 10, $shared: true}; <add> <add> expect(anims.update(target, { <add> options: sharedOpts <add> })).toBeTrue(); <add> <add> expect(target.options !== sharedOpts).toBeTrue(); <add> <add> Chart.animator.start(chart); <add> <add> setTimeout(function() { <add> expect(Chart.animator.running(chart)).toBeTrue(); <add> Chart.animator.stop(chart); <add> expect(Chart.animator.running(chart)).toBeFalse(); <add> <add> setTimeout(function() { <add> expect(target.options === sharedOpts).toBeFalse(); <add> <add> Chart.animator.remove(chart); <add> done(); <add> }, 250); <add> }, 50); <add> }); <add> <add> <add> it('should assign final shared options to target after animations complete', function(done) { <add> const chart = { <add> draw: function() {}, <add> options: { <add> animation: { <add> debug: false <add> } <add> } <add> }; <add> const anims = new Chart.Animations(chart, {value: {duration: 100}, option: {duration: 200}}); <add> <add> const origOpts = {option: 2}; <add> const target = { <add> value: 1, <add> options: origOpts <add> }; <add> const sharedOpts = {option: 10, $shared: true}; <add> const sharedOpts2 = {option: 20, $shared: true}; <add> <add> expect(anims.update(target, { <add> options: sharedOpts <add> })).toBeTrue(); <add> <add> expect(target.options !== sharedOpts).toBeTrue(); <add> <add> Chart.animator.start(chart); <add> <add> setTimeout(function() { <add> expect(Chart.animator.running(chart)).toBeTrue(); <add> <add> expect(target.options === origOpts).toBeTrue(); <add> <add> expect(anims.update(target, { <add> options: sharedOpts2 <add> })).toBeUndefined(); <add> <add> expect(target.options === origOpts).toBeTrue(); <add> <add> setTimeout(function() { <add> expect(target.options === sharedOpts2).toBeTrue(); <add> <add> Chart.animator.remove(chart); <add> done(); <add> }, 250); <add> }, 50); <add> }); <ide> });
3
Text
Text
add new introductory article about tailwind css
c05d680589428ebae4d9a76909782f8e65f3e6ef
<ide><path>guide/english/tailwindcss/index.md <add>--- <add>title: Tailwind CSS <add>--- <add># Tailwind CSS <add> <add>[Tailwind CSS](https://tailwindcss.com/) is a CSS framework following the "utility-first CSS" approach, a [term coined by Adam Wathan](https://twitter.com/adamwathan/status/1019206835335618560), who is one of the creators along with Jonathan Reinink, David Hemphill and Steve Schoger. Tailwind CSS is different from frontend libraries like [Bootstrap](https://getbootstrap.com) in the way that it does not provide a set of ready-to-use components. It rather comes with a curated but configurable set of CSS classes. This approach was [first described by Thierry Koblentz](https://www.smashingmagazine.com/2013/10/challenging-css-best-practices-atomic-approach/) and got known as "Atomic CSS", not to be confused with the "Atomic design" methodology. <add>Over the years the method of injecting CSS classes that are mostly applying only one single rule became more and more popular and was [thoroughly defended against criticism](https://frontstuff.io/in-defense-of-utility-first-css). While other frameworks use CSS utility classes as an addition, e.g. like [introduced in Bootstrap 4](https://getbootstrap.com/docs/4.1/utilities/), Tailwind CSS allows to create complex user interfaces merely using this technique. <add>The classes used in Tailwind CSS can be generated dynamically using a JavaScript configuration file which allows to adapt, add or remove classes. This includes adapting variables like color palettes or breakpoints used to generate the corresponding CSS classes. <add>Tailwind CSS is best suited for individually designed interfaces because it lacks components or a theme but instead gives the freedom to create a highly customized look without the need to override default styling. Nevertheless [custom components can easily be created](https://tailwindcss.com/docs/what-is-tailwind/#component-friendly) by applying the existing utility classes and to build common frontend components like [media cards](https://tailwindcss.com/docs/examples/cards).
1
Ruby
Ruby
use build_head here too
826ab8be71a7e3d5acbfed0f3ea4a6cd3498f6eb
<ide><path>Library/Homebrew/formula.rb <ide> def initialize name='__UNKNOWN__' <ide> set_instance_variable 'head' <ide> set_instance_variable 'specs' <ide> <del> if @head and (not @url or ARGV.flag? '--HEAD') <add> if @head and (not @url or ARGV.build_head?) <ide> @url=@head <ide> @version='HEAD' <ide> end
1
Text
Text
add missing docs for rm
88326e9b91435d2183f943a2905fa516d0b5d78e
<ide><path>docs/sources/reference/api/docker_remote_api_v1.14.md <ide> Remove the container `id` from the filesystem <ide> <ide> - **v** – 1/True/true or 0/False/false, Remove the volumes <ide> associated to the container. Default false <del> - **force** – 1/True/true or 0/False/false, Removes the container <del> even if it was running. Default false <add> - **stop** – 1/True/true or 0/False/false, Stop then remove the container. <add> Default false <add> - **kill** - 1/True/true or 0/False/false, Kill then remove the container. <add> Default false <ide> <ide> Status Codes: <ide>
1
Python
Python
suppress any exception in wasb task handler
59da94342813d382a768d064ac9cfd0245825679
<ide><path>airflow/providers/microsoft/azure/log/wasb_task_handler.py <ide> import shutil <ide> from typing import Any <ide> <del>from azure.common import AzureHttpError <del> <ide> from airflow.compat.functools import cached_property <ide> from airflow.configuration import conf <ide> from airflow.utils.log.file_task_handler import FileTaskHandler <ide> def hook(self): <ide> from airflow.providers.microsoft.azure.hooks.wasb import WasbHook <ide> <ide> return WasbHook(remote_conn_id) <del> except AzureHttpError: <add> except Exception: <ide> self.log.exception( <del> 'Could not create an WasbHook with connection id "%s".' <del> " Please make sure that apache-airflow[azure] is installed" <del> " and the Wasb connection exists.", <add> "Could not create a WasbHook with connection id '%s'. " <add> "Do you have apache-airflow[azure] installed? " <add> "Does connection the connection exist, and is it " <add> "configured properly?", <ide> remote_conn_id, <ide> ) <ide> return None <ide> def wasb_read(self, remote_log_location: str, return_error: bool = False): <ide> """ <ide> try: <ide> return self.hook.read_file(self.wasb_container, remote_log_location) <del> except AzureHttpError: <add> except Exception: <ide> msg = f"Could not read logs from {remote_log_location}" <ide> self.log.exception(msg) <ide> # return error if needed <ide> def wasb_write(self, log: str, remote_log_location: str, append: bool = True) -> <ide> <ide> try: <ide> self.hook.load_string(log, self.wasb_container, remote_log_location, overwrite=True) <del> except AzureHttpError: <add> except Exception: <ide> self.log.exception("Could not write logs to %s", remote_log_location) <ide><path>tests/providers/microsoft/azure/log/test_wasb_task_handler.py <ide> def test_hook(self, mock_service): <ide> assert isinstance(self.wasb_task_handler.hook, WasbHook) <ide> <ide> @conf_vars({("logging", "remote_log_conn_id"): "wasb_default"}) <del> def test_hook_raises(self): <add> def test_hook_warns(self): <ide> handler = self.wasb_task_handler <del> with mock.patch.object(handler.log, "error") as mock_error: <add> with mock.patch.object(handler.log, "exception") as mock_exc: <ide> with mock.patch("airflow.providers.microsoft.azure.hooks.wasb.WasbHook") as mock_hook: <ide> mock_hook.side_effect = AzureHttpError("failed to connect", 404) <ide> # Initialize the hook <ide> handler.hook <ide> <del> mock_error.assert_called_once_with( <del> 'Could not create an WasbHook with connection id "%s".' <del> " Please make sure that apache-airflow[azure] is installed" <del> " and the Wasb connection exists.", <del> "wasb_default", <del> exc_info=True, <del> ) <add> assert "Could not create a WasbHook with connection id '%s'" in mock_exc.call_args[0][0] <ide> <ide> def test_set_context_raw(self, ti): <ide> ti.raw = True
2
Python
Python
add subnet update
aedebcf9fbd062dae72a63f429c5213e21cc8eb8
<ide><path>libcloud/compute/drivers/openstack.py <ide> def ex_delete_subnet(self, subnet): <ide> self._subnets_url_prefix, subnet.id), method='DELETE') <ide> return resp.status in (httplib.NO_CONTENT, httplib.ACCEPTED) <ide> <add> def ex_update_subnet(self, subnet, **kwargs): <add> """ <add> Update data of an existing SubNet <add> <add> :param subnet: Subnet which should be updated <add> :type subnet: :class:`OpenStack_2_SubNet` <add> <add> :rtype: :class:`OpenStack_2_SubNet` <add> """ <add> data = {'subnet': {}} <add> for key, value in kwargs.items(): <add> data['subnet'][key] = value <add> response = self.network_connection.request( <add> "%s/%s" % (self._subnets_url_prefix, subnet.id), <add> method='PUT', data=data).object <add> return self._to_subnet(response['subnet']) <add> <ide> def ex_list_ports(self): <ide> """ <ide> List all OpenStack_2_PortInterfaces <ide><path>libcloud/test/compute/test_openstack.py <ide> def test_ex_delete_subnet(self): <ide> subnet = self.driver.ex_list_subnets()[0] <ide> self.assertTrue(self.driver.ex_delete_subnet(subnet=subnet)) <ide> <add> def test_ex_update_subnet(self): <add> subnet = self.driver.ex_list_subnets()[0] <add> subnet = self.driver.ex_update_subnet(subnet, name='net2') <add> self.assertEqual(subnet.name, 'name') <add> <ide> def test_ex_list_network(self): <ide> networks = self.driver.ex_list_networks() <ide> network = networks[0] <ide> def _v2_1337_v2_0_networks_d32019d3_bc6e_4319_9c1d_6722fc136a22(self, method, ur <ide> if method == 'GET': <ide> body = self.fixtures.load('_v2_0__networks_POST.json') <ide> return (httplib.OK, body, self.json_content_headers, httplib.responses[httplib.OK]) <del> if method == 'DELETE': <add> elif method == 'DELETE': <ide> body = '' <ide> return (httplib.NO_CONTENT, body, self.json_content_headers, httplib.responses[httplib.OK]) <ide> <ide> def _v2_1337_v2_0_subnets_08eae331_0402_425a_923c_34f7cfe39c1b(self, method, url <ide> if method == 'DELETE': <ide> body = '' <ide> return (httplib.NO_CONTENT, body, self.json_content_headers, httplib.responses[httplib.OK]) <add> elif method == 'PUT': <add> body = self.fixtures.load('_v2_0__subnet.json') <add> return (httplib.OK, body, self.json_content_headers, httplib.responses[httplib.OK]) <ide> <ide> def _v2_1337_v2_0_subnets(self, method, url, body, headers): <ide> if method == 'POST':
2
Java
Java
make extractor generic
839756b6d4d02463db1647c0bcabd5712e54808c
<ide><path>ReactAndroid/src/main/java/com/facebook/react/bridge/BaseJavaModule.java <ide> public abstract class BaseJavaModule implements NativeModule { <ide> static final public String METHOD_TYPE_REMOTE = "remote"; <ide> static final public String METHOD_TYPE_REMOTE_ASYNC = "remoteAsync"; <ide> <del> private static abstract class ArgumentExtractor { <add> private static abstract class ArgumentExtractor<T> { <ide> public int getJSArgumentsNeeded() { <ide> return 1; <ide> } <ide> <del> public abstract @Nullable Object extractArgument( <add> public abstract @Nullable T extractArgument( <ide> CatalystInstance catalystInstance, ReadableNativeArray jsArguments, int atIndex); <ide> } <ide> <del> static final private ArgumentExtractor ARGUMENT_EXTRACTOR_BOOLEAN = new ArgumentExtractor() { <del> @Override <del> public Object extractArgument( <del> CatalystInstance catalystInstance, ReadableNativeArray jsArguments, int atIndex <del> ) { <del> return Boolean.valueOf(jsArguments.getBoolean(atIndex)); <del> } <del> }; <del> <del> static final private ArgumentExtractor ARGUMENT_EXTRACTOR_DOUBLE = new ArgumentExtractor() { <del> @Override <del> public Object extractArgument( <del> CatalystInstance catalystInstance, ReadableNativeArray jsArguments, int atIndex <del> ) { <del> return Double.valueOf(jsArguments.getDouble(atIndex)); <del> } <del> }; <del> <del> static final private ArgumentExtractor ARGUMENT_EXTRACTOR_FLOAT = new ArgumentExtractor() { <del> @Override <del> public Object extractArgument( <del> CatalystInstance catalystInstance, ReadableNativeArray jsArguments, int atIndex <del> ) { <del> return Float.valueOf((float) jsArguments.getDouble(atIndex)); <del> } <del> }; <del> <del> static final private ArgumentExtractor ARGUMENT_EXTRACTOR_INTEGER = new ArgumentExtractor() { <del> @Override <del> public Object extractArgument( <del> CatalystInstance catalystInstance, ReadableNativeArray jsArguments, int atIndex <del> ) { <del> return Integer.valueOf((int) jsArguments.getDouble(atIndex)); <del> } <del> }; <del> <del> static final private ArgumentExtractor ARGUMENT_EXTRACTOR_STRING = new ArgumentExtractor() { <del> @Override <del> public Object extractArgument( <del> CatalystInstance catalystInstance, ReadableNativeArray jsArguments, int atIndex <del> ) { <del> return jsArguments.getString(atIndex); <del> } <del> }; <del> <del> static final private ArgumentExtractor ARGUMENT_EXTRACTOR_ARRAY = new ArgumentExtractor() { <del> @Override <del> public Object extractArgument( <del> CatalystInstance catalystInstance, ReadableNativeArray jsArguments, int atIndex <del> ) { <del> return jsArguments.getArray(atIndex); <del> } <del> }; <del> <del> static final private ArgumentExtractor ARGUMENT_EXTRACTOR_MAP = new ArgumentExtractor() { <del> @Override <del> public Object extractArgument( <del> CatalystInstance catalystInstance, ReadableNativeArray jsArguments, int atIndex <del> ) { <del> return jsArguments.getMap(atIndex); <del> } <del> }; <del> <del> static final private ArgumentExtractor ARGUMENT_EXTRACTOR_CALLBACK = new ArgumentExtractor() { <del> @Override <del> public @Nullable Object extractArgument( <del> CatalystInstance catalystInstance, ReadableNativeArray jsArguments, int atIndex <del> ) { <del> if (jsArguments.isNull(atIndex)) { <del> return null; <del> } <del> else { <del> int id = (int) jsArguments.getDouble(atIndex); <del> return new CallbackImpl(catalystInstance, id); <del> } <del> } <del> }; <add> static final private ArgumentExtractor<Boolean> ARGUMENT_EXTRACTOR_BOOLEAN = <add> new ArgumentExtractor<Boolean>() { <add> @Override <add> public Boolean extractArgument( <add> CatalystInstance catalystInstance, ReadableNativeArray jsArguments, int atIndex) { <add> return jsArguments.getBoolean(atIndex); <add> } <add> }; <add> <add> static final private ArgumentExtractor<Double> ARGUMENT_EXTRACTOR_DOUBLE = <add> new ArgumentExtractor<Double>() { <add> @Override <add> public Double extractArgument( <add> CatalystInstance catalystInstance, ReadableNativeArray jsArguments, int atIndex) { <add> return jsArguments.getDouble(atIndex); <add> } <add> }; <add> <add> static final private ArgumentExtractor<Float> ARGUMENT_EXTRACTOR_FLOAT = <add> new ArgumentExtractor<Float>() { <add> @Override <add> public Float extractArgument( <add> CatalystInstance catalystInstance, ReadableNativeArray jsArguments, int atIndex) { <add> return (float) jsArguments.getDouble(atIndex); <add> } <add> }; <add> <add> static final private ArgumentExtractor<Integer> ARGUMENT_EXTRACTOR_INTEGER = <add> new ArgumentExtractor<Integer>() { <add> @Override <add> public Integer extractArgument( <add> CatalystInstance catalystInstance, ReadableNativeArray jsArguments, int atIndex) { <add> return (int) jsArguments.getDouble(atIndex); <add> } <add> }; <add> <add> static final private ArgumentExtractor<String> ARGUMENT_EXTRACTOR_STRING = <add> new ArgumentExtractor<String>() { <add> @Override <add> public String extractArgument( <add> CatalystInstance catalystInstance, ReadableNativeArray jsArguments, int atIndex) { <add> return jsArguments.getString(atIndex); <add> } <add> }; <add> <add> static final private ArgumentExtractor<ReadableNativeArray> ARGUMENT_EXTRACTOR_ARRAY = <add> new ArgumentExtractor<ReadableNativeArray>() { <add> @Override <add> public ReadableNativeArray extractArgument( <add> CatalystInstance catalystInstance, ReadableNativeArray jsArguments, int atIndex) { <add> return jsArguments.getArray(atIndex); <add> } <add> }; <add> <add> static final private ArgumentExtractor<ReadableMap> ARGUMENT_EXTRACTOR_MAP = <add> new ArgumentExtractor<ReadableMap>() { <add> @Override <add> public ReadableMap extractArgument( <add> CatalystInstance catalystInstance, ReadableNativeArray jsArguments, int atIndex) { <add> return jsArguments.getMap(atIndex); <add> } <add> }; <add> <add> static final private ArgumentExtractor<Callback> ARGUMENT_EXTRACTOR_CALLBACK = <add> new ArgumentExtractor<Callback>() { <add> @Override <add> public @Nullable Callback extractArgument( <add> CatalystInstance catalystInstance, ReadableNativeArray jsArguments, int atIndex) { <add> if (jsArguments.isNull(atIndex)) { <add> return null; <add> } else { <add> int id = (int) jsArguments.getDouble(atIndex); <add> return new CallbackImpl(catalystInstance, id); <add> } <add> } <add> }; <ide> <del> static final private ArgumentExtractor ARGUMENT_EXTRACTOR_PROMISE = new ArgumentExtractor() { <del> @Override <del> public int getJSArgumentsNeeded() { <del> return 2; <del> } <add> static final private ArgumentExtractor<Promise> ARGUMENT_EXTRACTOR_PROMISE = <add> new ArgumentExtractor<Promise>() { <add> @Override <add> public int getJSArgumentsNeeded() { <add> return 2; <add> } <ide> <del> @Override <del> public Promise extractArgument( <del> CatalystInstance catalystInstance, ReadableNativeArray jsArguments, int atIndex) { <del> Callback resolve = (Callback) ARGUMENT_EXTRACTOR_CALLBACK <del> .extractArgument(catalystInstance, jsArguments, atIndex); <del> Callback reject = (Callback) ARGUMENT_EXTRACTOR_CALLBACK <del> .extractArgument(catalystInstance, jsArguments, atIndex + 1); <del> return new PromiseImpl(resolve, reject); <del> } <del> }; <add> @Override <add> public Promise extractArgument( <add> CatalystInstance catalystInstance, ReadableNativeArray jsArguments, int atIndex) { <add> Callback resolve = ARGUMENT_EXTRACTOR_CALLBACK <add> .extractArgument(catalystInstance, jsArguments, atIndex); <add> Callback reject = ARGUMENT_EXTRACTOR_CALLBACK <add> .extractArgument(catalystInstance, jsArguments, atIndex + 1); <add> return new PromiseImpl(resolve, reject); <add> } <add> }; <ide> <ide> private class JavaMethod implements NativeMethod { <ide>
1
Javascript
Javascript
use double quotes
45d9959751bbe95aa7880593791245ba41c91af0
<ide><path>lib/EnvironmentPlugin.js <ide> class EnvironmentPlugin { <ide> compiler.plugin("this-compilation", compilation => { <ide> const error = new Error( <ide> `EnvironmentPlugin - ${key} environment variable is undefined.\n\n` + <del> `You can pass an object with default values to suppress this warning.\n` + <del> `See https://webpack.js.org/plugins/environment-plugin for example.` <add> "You can pass an object with default values to suppress this warning.\n" + <add> "See https://webpack.js.org/plugins/environment-plugin for example." <ide> ); <ide> <ide> error.name = "EnvVariableNotDefinedError";
1
Javascript
Javascript
reduce false-positives in iselement tests
5fe1f39f027c6f2c6a530975dd5389d788d3c0eb
<ide><path>src/ng/parse.js <ide> function ensureSafeObject(obj, fullExpression) { <ide> 'Referencing the Window in Angular expressions is disallowed! Expression: {0}', <ide> fullExpression); <ide> } else if (// isElement(obj) <del> obj.children && (obj.nodeName || (obj.on && obj.find))) { <add> obj.children && (obj.nodeName || (obj.prop && obj.attr && obj.find))) { <ide> throw $parseMinErr('isecdom', <ide> 'Referencing DOM nodes in Angular expressions is disallowed! Expression: {0}', <ide> fullExpression); <ide><path>test/ng/parseSpec.js <ide> describe('parser', function() { <ide> '$parse', 'isecdom', 'Referencing DOM nodes in Angular expressions is ' + <ide> 'disallowed! Expression: a.b.doc.on("click")'); <ide> })); <add> <add> // Issue #4805 <add> it('should NOT throw isecdom when referencing a Backbone Collection', function() { <add> // Backbone stuff is sort of hard to mock, if you have a better way of doing this, <add> // please fix this. <add> var fakeBackboneCollection = { <add> children: [{}, {}, {}], <add> find: function() {}, <add> on: function() {}, <add> off: function() {}, <add> bind: function() {} <add> }; <add> scope.backbone = fakeBackboneCollection; <add> expect(function() { scope.$eval('backbone'); }).not.toThrow(); <add> }); <add> <add> it('should NOT throw isecdom when referencing an array with node properties', function() { <add> var array = [1,2,3]; <add> array.on = array.attr = array.prop = array.bind = true; <add> scope.array = array; <add> expect(function() { scope.$eval('array'); }).not.toThrow(); <add> }); <ide> }); <ide> }); <ide>
2
PHP
PHP
add string to docblocks
5319ddba567b3ccd94a21371a7ec760e4059e8a2
<ide><path>src/Illuminate/Collections/Enumerable.php <ide> public function nth($step, $offset = 0); <ide> /** <ide> * Get the items with the specified keys. <ide> * <del> * @param \Illuminate\Support\Enumerable<array-key, TKey>|array<array-key, TKey> $keys <add> * @param \Illuminate\Support\Enumerable<array-key, TKey>|array<array-key, TKey>|string $keys <ide> * @return static <ide> */ <ide> public function only($keys); <ide><path>src/Illuminate/Collections/LazyCollection.php <ide> public function nth($step, $offset = 0) <ide> /** <ide> * Get the items with the specified keys. <ide> * <del> * @param \Illuminate\Support\Enumerable<array-key, TKey>|array<array-key, TKey> $keys <add> * @param \Illuminate\Support\Enumerable<array-key, TKey>|array<array-key, TKey>|string $keys <ide> * @return static <ide> */ <ide> public function only($keys)
2
Javascript
Javascript
remove dependency on $window
7e49d37a982bea6d0e323c1f7655a54d5956311a
<ide><path>src/ng/urlUtils.js <ide> 'use strict'; <ide> <ide> function $$UrlUtilsProvider() { <del> this.$get = ['$window', '$document', function($window, $document) { <add> this.$get = ['$document', function($document) { <ide> var urlParsingNode = $document[0].createElement("a"), <del> originUrl = resolve($window.location.href, true); <add> // NOTE: The usage of window instead of $window here is deliberate. When the browser <add> // resolves a URL for XHR, it doesn't know about any mocked $window. $$urlUtils <add> // resolves URLs just as the browser would. Using $window here would confuse the <add> // isSameOrigin check causing unexpected failures. We avoid that by using the real window <add> // object. <add> originUrl = resolve(window.location.href, true); <ide> <ide> /** <ide> * @description
1
Java
Java
avoid double conversionfailedexception nesting
8e5c033446c6435d631107f73d83eeb413998628
<ide><path>org.springframework.core/src/main/java/org/springframework/core/convert/support/ConversionUtils.java <ide> public static Object invokeConverter(GenericConverter converter, Object source, <ide> try { <ide> return converter.convert(source, sourceType, targetType); <ide> } <add> catch (ConversionFailedException ex) { <add> throw ex; <add> } <ide> catch (Exception ex) { <ide> throw new ConversionFailedException(sourceType, targetType, source, ex); <ide> } <ide><path>org.springframework.web.servlet/src/test/java/org/springframework/web/servlet/config/MvcNamespaceTests.java <ide> <ide> package org.springframework.web.servlet.config; <ide> <del>import static org.junit.Assert.assertEquals; <del>import static org.junit.Assert.assertFalse; <del>import static org.junit.Assert.assertNotNull; <del>import static org.junit.Assert.assertNull; <del>import static org.junit.Assert.assertSame; <del>import static org.junit.Assert.assertTrue; <del> <ide> import java.util.Date; <ide> import java.util.Locale; <del> <ide> import javax.validation.Valid; <ide> import javax.validation.constraints.NotNull; <ide> <add>import static org.junit.Assert.*; <ide> import org.junit.Before; <ide> import org.junit.Test; <add> <add>import org.springframework.beans.TypeMismatchException; <ide> import org.springframework.beans.factory.xml.XmlBeanDefinitionReader; <ide> import org.springframework.context.i18n.LocaleContextHolder; <del>import org.springframework.core.convert.ConversionFailedException; <ide> import org.springframework.core.convert.ConversionService; <ide> import org.springframework.core.io.ClassPathResource; <ide> import org.springframework.format.annotation.DateTimeFormat; <ide> public void testDefaultConfig() throws Exception { <ide> assertTrue(handler.recordedValidationError); <ide> } <ide> <del> @Test(expected=ConversionFailedException.class) <add> @Test(expected=TypeMismatchException.class) <ide> public void testCustomConversionService() throws Exception { <ide> XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(appContext); <ide> reader.loadBeanDefinitions(new ClassPathResource("mvc-config-custom-conversion-service.xml", getClass()));
2
PHP
PHP
add test for capsulemanagertrait and fixes a typo
0d4b6eecc83ea43c48a3dad18be594167de4d2bc
<ide><path>tests/Support/SupportCapsuleManagerTraitTest.php <add><?php <add> <add>use Mockery as m; <add>use Illuminate\Container\Container; <add>use Illuminate\Support\Traits\CapsuleManagerTrait; <add> <add>class SupportCapsuleManagerTraitTest extends \PHPUnit_Framework_TestCase { <add> <add> use CapsuleManagerTrait; <add> <add> public function tearDown() <add> { <add> m::close(); <add> } <add> <add> public function testSetupContainerForCapsule() <add> { <add> $this->container = null; <add> $app = new Container; <add> <add> $this->assertNull($this->setupContainer($app)); <add> $this->assertEquals($app, $this->getContainer()); <add> $this->assertInstanceOf('\Illuminate\Support\Fluent', $app['config']); <add> } <add> <add> <add> public function testSetupContainerForCapsuleWhenConfigIsBound() <add> { <add> $this->container = null; <add> $app = new Container; <add> $app['config'] = m::mock('\Illuminate\Config\Repository'); <add> <add> $this->assertNull($this->setupContainer($app)); <add> $this->assertEquals($app, $this->getContainer()); <add> $this->assertInstanceOf('\Illuminate\Config\Repository', $app['config']); <add> } <add>} <ide><path>tests/Support/SupportMacroTraitTest.php <ide> public function testRegisterMacro() <ide> } <ide> <ide> <del> public function testResgisterMacroAndCallWithoutStatic() <add> public function testRegisterMacroAndCallWithoutStatic() <ide> { <ide> $macroTrait = $this->macroTrait; <ide> $macroTrait::macro(__CLASS__, function() { return 'Taylor'; });
2
Python
Python
try import instead of having it required
2e8080439e1d1e70bf6419d4ede68a0ba28ec61f
<ide><path>airflow/www/views.py <ide> def run(self): <ide> force = request.args.get('force') == "true" <ide> deps = request.args.get('deps') == "true" <ide> <del> from airflow.executors import DEFAULT_EXECUTOR as executor <del> from airflow.executors import CeleryExecutor <del> if not isinstance(executor, CeleryExecutor): <add> try: <add> from airflow.executors import DEFAULT_EXECUTOR as executor <add> from airflow.executors import CeleryExecutor <add> if not isinstance(executor, CeleryExecutor): <add> flash("Only works with the CeleryExecutor, sorry", "error") <add> return redirect(origin) <add> except ImportError: <add> # in case CeleryExecutor cannot be imported it is not active either <ide> flash("Only works with the CeleryExecutor, sorry", "error") <ide> return redirect(origin) <add> <ide> ti = models.TaskInstance(task=task, execution_date=execution_date) <ide> executor.start() <ide> executor.queue_task_instance(
1
PHP
PHP
remove trailing , for php 7.2
e83d4dc0bdf881f0de78232d169e5f9c4181c6ee
<ide><path>tests/TestCase/Http/Client/Auth/OauthTest.php <ide> public function testBaseStringWithXmlPostData() <ide> [ <ide> 'Content-Type' => 'application/xml', <ide> ], <del> '<xml>stuff</xml>', <add> '<xml>stuff</xml>' <ide> ); <ide> <ide> $auth = new Oauth();
1
Ruby
Ruby
install gcc if needed
8c6c644a6b1ae4d3ae377fbb4a869aaa1ce84095
<ide><path>Library/Contributions/cmd/brew-test-bot.rb <ide> def formula formula <ide> return <ide> end <ide> <add> begin <add> CompilerSelector.new(formula_object).compiler <add> rescue CompilerSelectionError <add> test "brew install apple-gcc42" <add> end <add> <ide> test "brew fetch #{dependencies}" unless dependencies.empty? <ide> formula_fetch_options = " " <ide> formula_fetch_options << " --build-bottle" unless ARGV.include? '--no-bottle'
1
Python
Python
fix typo in msvc runtime info for mingw
16f3279fa7aee9b4f3c8562e7f160f1259a50497
<ide><path>numpy/distutils/mingw32ccompiler.py <ide> def _build_import_library_x86(): <ide> _MSVCRVER_TO_FULLVER['90'] = "9.0.21022.8" <ide> # I took one version in my SxS directory: no idea if it is the good <ide> # one, and we can't retrieve it from python <del> _MSVCRVER_TO_FULLVER['90'] = "8.0.50727.42" <add> _MSVCRVER_TO_FULLVER['80'] = "8.0.50727.42" <ide> except ImportError: <ide> # If we are here, means python was not built with MSVC. Not sure what to do <ide> # in that case: manifest building will fail, but it should not be used in
1
Ruby
Ruby
expand glob patterns
5c185eaa4355810ccc6617cb078ee67d4fa0777c
<ide><path>Library/Homebrew/cask/lib/hbc/artifact/uninstall_base.rb <ide> def self.expand_path_strings(path_strings) <ide> end <ide> end <ide> <add> def self.expand_glob(path_strings) <add> path_strings.flat_map(&Pathname.method(:glob)) <add> end <add> <ide> def self.remove_relative_path_strings(action, path_strings) <ide> relative = path_strings.map do |path_string| <ide> path_string if %r{/\.\.(?:/|\Z)}.match(path_string) || !%r{\A/}.match(path_string) <ide> def self.remove_undeletable_path_strings(action, path_strings) <ide> path_strings - undeletable <ide> end <ide> <add> def self.prepare_path_strings(action, path_strings, expand_tilde) <add> path_strings = expand_path_strings(path_strings) if expand_tilde <add> path_strings = remove_relative_path_strings(action, path_strings) <add> path_strings = expand_glob(path_strings) <add> remove_undeletable_path_strings(action, path_strings) <add> end <add> <ide> def dispatch_uninstall_directives(expand_tilde: true) <ide> directives_set = @cask.artifacts[stanza] <ide> ohai "Running #{stanza} process for #{@cask}; your password may be necessary" <ide> def uninstall_pkgutil(directives) <ide> def uninstall_delete(directives, expand_tilde = true) <ide> Array(directives[:delete]).concat(Array(directives[:trash])).flatten.each_slice(PATH_ARG_SLICE_SIZE) do |path_slice| <ide> ohai "Removing files: #{path_slice.utf8_inspect}" <del> path_slice = self.class.expand_path_strings(path_slice) if expand_tilde <del> path_slice = self.class.remove_relative_path_strings(:delete, path_slice) <del> path_slice = self.class.remove_undeletable_path_strings(:delete, path_slice) <add> path_slice = self.class.prepare_path_strings(:delete, path_slice, expand_tilde) <ide> @command.run!("/bin/rm", args: path_slice.unshift("-rf", "--"), sudo: true) <ide> end <ide> end <ide> def uninstall_trash(directives, expand_tilde = true) <ide> uninstall_delete(directives, expand_tilde) <ide> end <ide> <del> def uninstall_rmdir(directives, expand_tilde = true) <del> Array(directives[:rmdir]).flatten.each do |directory| <del> directory = self.class.expand_path_strings([directory]).first if expand_tilde <del> directory = self.class.remove_relative_path_strings(:rmdir, [directory]).first <del> directory = self.class.remove_undeletable_path_strings(:rmdir, [directory]).first <add> def uninstall_rmdir(directories, expand_tilde = true) <add> action = :rmdir <add> self.class.prepare_path_strings(action, Array(directories[action]).flatten, expand_tilde).each do |directory| <ide> next if directory.to_s.empty? <ide> ohai "Removing directory if empty: #{directory.to_s.utf8_inspect}" <ide> directory = Pathname.new(directory) <ide><path>Library/Homebrew/cask/spec/cask/artifact/uninstall_spec.rb <ide> Hbc::Artifact::Uninstall.new(cask, command: Hbc::FakeSystemCommand) <ide> } <ide> <add> let(:absolute_path) { Pathname.new("#{TEST_TMPDIR}/absolute_path") } <add> let(:path_with_tilde) { Pathname.new("#{TEST_TMPDIR}/path_with_tilde") } <add> let(:glob_path1) { Pathname.new("#{TEST_TMPDIR}/glob_path1") } <add> let(:glob_path2) { Pathname.new("#{TEST_TMPDIR}/glob_path2") } <add> <ide> before(:each) do <add> FileUtils.touch(absolute_path) <add> FileUtils.touch(path_with_tilde) <add> FileUtils.touch(glob_path1) <add> FileUtils.touch(glob_path2) <add> ENV["HOME"] = TEST_TMPDIR <ide> shutup do <ide> InstallHelper.install_without_artifacts(cask) <ide> end <ide> it "can uninstall" do <ide> Hbc::FakeSystemCommand.expects_command( <ide> sudo(%w[/bin/rm -rf --], <del> Pathname.new("/permissible/absolute/path"), <del> Pathname.new("~/permissible/path/with/tilde").expand_path), <add> absolute_path, <add> path_with_tilde, <add> glob_path1, <add> glob_path2), <ide> ) <ide> <ide> subject <ide> it "can uninstall" do <ide> Hbc::FakeSystemCommand.expects_command( <ide> sudo(%w[/bin/rm -rf --], <del> Pathname.new("/permissible/absolute/path"), <del> Pathname.new("~/permissible/path/with/tilde").expand_path), <add> absolute_path, <add> path_with_tilde, <add> glob_path1, <add> glob_path2), <ide> ) <ide> <ide> subject <ide><path>Library/Homebrew/cask/spec/cask/artifact/zap_spec.rb <ide> Hbc::Artifact::Zap.new(cask, command: Hbc::FakeSystemCommand) <ide> } <ide> <add> let(:absolute_path) { Pathname.new("#{TEST_TMPDIR}/absolute_path") } <add> let(:path_with_tilde) { Pathname.new("#{TEST_TMPDIR}/path_with_tilde") } <add> let(:glob_path1) { Pathname.new("#{TEST_TMPDIR}/glob_path1") } <add> let(:glob_path2) { Pathname.new("#{TEST_TMPDIR}/glob_path2") } <add> <ide> before(:each) do <add> FileUtils.touch(absolute_path) <add> FileUtils.touch(path_with_tilde) <add> FileUtils.touch(glob_path1) <add> FileUtils.touch(glob_path2) <add> ENV["HOME"] = TEST_TMPDIR <ide> shutup do <ide> InstallHelper.install_without_artifacts(cask) <ide> end <ide> it "can zap" do <ide> Hbc::FakeSystemCommand.expects_command( <ide> sudo(%w[/bin/rm -rf --], <del> Pathname.new("/permissible/absolute/path"), <del> Pathname.new("~/permissible/path/with/tilde").expand_path), <add> absolute_path, <add> path_with_tilde, <add> glob_path1, <add> glob_path2), <ide> ) <ide> <ide> subject <ide> it "can zap" do <ide> Hbc::FakeSystemCommand.expects_command( <ide> sudo(%w[/bin/rm -rf --], <del> Pathname.new("/permissible/absolute/path"), <del> Pathname.new("~/permissible/path/with/tilde").expand_path), <add> absolute_path, <add> path_with_tilde, <add> glob_path1, <add> glob_path2), <ide> ) <ide> <ide> subject <ide><path>Library/Homebrew/test/support/fixtures/cask/Casks/with-installable.rb <ide> quit: 'my.fancy.package.app', <ide> login_item: 'Fancy', <ide> delete: [ <del> '/permissible/absolute/path', <del> '~/permissible/path/with/tilde', <add> "#{TEST_TMPDIR}/absolute_path", <add> '~/path_with_tilde', <add> "#{TEST_TMPDIR}/glob_path*", <ide> 'impermissible/relative/path', <ide> '/another/impermissible/../relative/path', <ide> ], <ide><path>Library/Homebrew/test/support/fixtures/cask/Casks/with-uninstall-delete.rb <ide> pkg 'Fancy.pkg' <ide> <ide> uninstall delete: [ <del> '/permissible/absolute/path', <del> '~/permissible/path/with/tilde', <add> "#{TEST_TMPDIR}/absolute_path", <add> '~/path_with_tilde', <add> "#{TEST_TMPDIR}/glob_path*", <ide> 'impermissible/relative/path', <ide> '/another/impermissible/../relative/path', <ide> ] <ide><path>Library/Homebrew/test/support/fixtures/cask/Casks/with-uninstall-trash.rb <ide> pkg 'Fancy.pkg' <ide> <ide> uninstall trash: [ <del> '/permissible/absolute/path', <del> '~/permissible/path/with/tilde', <add> "#{TEST_TMPDIR}/absolute_path", <add> '~/path_with_tilde', <add> "#{TEST_TMPDIR}/glob_path*", <ide> 'impermissible/relative/path', <ide> '/another/impermissible/../relative/path', <ide> ] <ide><path>Library/Homebrew/test/support/fixtures/cask/Casks/with-zap-delete.rb <ide> pkg 'Fancy.pkg' <ide> <ide> zap delete: [ <del> '/permissible/absolute/path', <del> '~/permissible/path/with/tilde', <add> "#{TEST_TMPDIR}/absolute_path", <add> '~/path_with_tilde', <add> "#{TEST_TMPDIR}/glob_path*", <ide> 'impermissible/relative/path', <ide> '/another/impermissible/../relative/path', <ide> ] <ide><path>Library/Homebrew/test/support/fixtures/cask/Casks/with-zap-trash.rb <ide> pkg 'Fancy.pkg' <ide> <ide> zap trash: [ <del> '/permissible/absolute/path', <del> '~/permissible/path/with/tilde', <add> "#{TEST_TMPDIR}/absolute_path", <add> '~/path_with_tilde', <add> "#{TEST_TMPDIR}/glob_path*", <ide> 'impermissible/relative/path', <ide> '/another/impermissible/../relative/path', <ide> ]
8
Ruby
Ruby
make `assert_index` private
a1772bba5d41492cf069b34d0c10df9c9a8af189
<ide><path>actionpack/lib/action_dispatch/middleware/stack.rb <ide> def build(app = Proc.new) <ide> middlewares.freeze.reverse.inject(app) { |a, e| e.build(a) } <ide> end <ide> <del> protected <add> private <ide> <ide> def assert_index(index, where) <ide> index = get_class index <ide> def assert_index(index, where) <ide> i <ide> end <ide> <del> private <del> <ide> def get_class(klass) <ide> if klass.is_a?(String) || klass.is_a?(Symbol) <ide> classcache = ActiveSupport::Dependencies::Reference
1
Ruby
Ruby
prefer array.wrap to array()
18d497651628c73287f3e808c3807121ad36e278
<ide><path>activesupport/lib/active_support/rescuable.rb <add>require 'active_support/core_ext/array/wrap' <ide> require 'active_support/core_ext/class/inheritable_attributes' <ide> require 'active_support/core_ext/proc' <ide> <ide> def rescue_with_handler(exception) <ide> def handler_for_rescue(exception) <ide> # We go from right to left because pairs are pushed onto rescue_handlers <ide> # as rescue_from declarations are found. <del> _, rescuer = Array(rescue_handlers).reverse.detect do |klass_name, handler| <add> _, rescuer = Array.wrap(rescue_handlers).reverse.detect do |klass_name, handler| <ide> # The purpose of allowing strings in rescue_from is to support the <ide> # declaration of handler associations for exception classes whose <ide> # definition is yet unknown.
1
PHP
PHP
fix phpdoc block for eloquent model find method
9a6b77518d16c7a4933cd4f25fe544a2c5325151
<ide><path>src/Illuminate/Database/Eloquent/Model.php <ide> public static function all($columns = array('*')) <ide> * <ide> * @param mixed $id <ide> * @param array $columns <del> * @return \Illuminate\Support\Collection|static <add> * @return \Illuminate\Support\Collection|static|null <ide> */ <ide> public static function find($id, $columns = array('*')) <ide> {
1
Text
Text
add example for file existence with fs.stat
23b9625c84e702f17b010bb653df132154ab6cad
<ide><path>doc/api/fs.md <ide> Asynchronous stat(2). The callback gets two arguments `(err, stats)` where <ide> `stats` is a [`fs.Stats`][] object. See the [`fs.Stats`][] section for more <ide> information. <ide> <add>In case of an error, the `err.code` will be one of [Common System Errors][]. <add> <add>Using `fs.stat()` to check for the existence of a file before calling <add>`fs.open()`, `fs.readFile()` or `fs.writeFile()` is not recommended. <add>Instead, user code should open/read/write the file directly and handle the <add>error raised if the file is not available. <add> <add>To check if a file exists without manipulating it afterwards, [`fs.access()`] <add>is recommended. <add> <ide> ## fs.statSync(path) <ide> <!-- YAML <ide> added: v0.1.21 <ide> The following constants are meant for use with the [`fs.Stats`][] object's <ide> [`event ports`]: http://illumos.org/man/port_create <ide> [`ReadDirectoryChangesW`]: https://msdn.microsoft.com/en-us/library/windows/desktop/aa365465%28v=vs.85%29.aspx <ide> [`AHAFS`]: https://www.ibm.com/developerworks/aix/library/au-aix_event_infrastructure/ <add>[Common System Errors]: errors.html#errors_common_system_errors <ide>\ No newline at end of file
1
Go
Go
add imageexists to docker utils
eb1e8e884d92a7086af96663d0c658d838315490
<ide><path>integration-cli/docker_utils.go <ide> func deleteImages(images string) error { <ide> return err <ide> } <ide> <add>func imageExists(image string) error { <add> inspectCmd := exec.Command(dockerBinary, "inspect", image) <add> exitCode, err := runCommand(inspectCmd) <add> if exitCode != 0 && err == nil { <add> err = fmt.Errorf("couldn't find image '%s'", image) <add> } <add> return err <add>} <add> <ide> func cmd(t *testing.T, args ...string) (string, int, error) { <ide> out, status, err := runCommandWithOutput(exec.Command(dockerBinary, args...)) <ide> errorOut(err, t, fmt.Sprintf("'%s' failed with errors: %v (%v)", strings.Join(args, " "), err, out))
1
Text
Text
clarify swarm concept
e0296317131782008dcb94c72d591244663d61b1
<ide><path>docs/swarm/key-concepts.md <ide> are built using **SwarmKit**. Engines participating in a cluster are <ide> running in **swarm mode**. You enable swarm mode for the Engine by either <ide> initializing a swarm or joining an existing swarm. <ide> <del>A **swarm** is a self-organizing cluster of Docker Engines where you deploy <add>A **swarm** is a cluster of Docker Engines where you deploy <ide> [services](#Services-and-tasks). The Docker Engine CLI includes the commands for <ide> swarm management, such as adding and removing nodes. The CLI also includes the <ide> commands you need to deploy services to the swarm and manage service
1
Go
Go
add unit tests for buildfile config instructions
e7f3f6fa5a10f890a1774a2320d31e236af56be9
<ide><path>buildfile_test.go <ide> CMD Hello world <ide> <ide> func TestBuild(t *testing.T) { <ide> for _, ctx := range testContexts { <del> runtime := mkRuntime(t) <del> defer nuke(runtime) <del> <del> srv := &Server{ <del> runtime: runtime, <del> pullingPool: make(map[string]struct{}), <del> pushingPool: make(map[string]struct{}), <del> } <del> <del> buildfile := NewBuildFile(srv, ioutil.Discard, false) <del> if _, err := buildfile.Build(mkTestContext(ctx.dockerfile, ctx.files, t)); err != nil { <del> t.Fatal(err) <del> } <add> buildImage(ctx, t) <ide> } <ide> } <ide> <del>func TestVolume(t *testing.T) { <add>func buildImage(context testContextTemplate, t *testing.T) *Image { <ide> runtime, err := newTestRuntime() <ide> if err != nil { <ide> t.Fatal(err) <ide> func TestVolume(t *testing.T) { <ide> pullingPool: make(map[string]struct{}), <ide> pushingPool: make(map[string]struct{}), <ide> } <del> <ide> buildfile := NewBuildFile(srv, ioutil.Discard, false) <del> imgId, err := buildfile.Build(mkTestContext(` <del>from %s <del>VOLUME /test <del>CMD Hello world <del>`, nil, t)) <add> <add> id, err := buildfile.Build(mkTestContext(context.dockerfile, context.files, t)) <ide> if err != nil { <ide> t.Fatal(err) <ide> } <del> img, err := srv.ImageInspect(imgId) <add> <add> img, err := srv.ImageInspect(id) <ide> if err != nil { <ide> t.Fatal(err) <ide> } <add> return img <add>} <add> <add>func TestVolume(t *testing.T) { <add> img := buildImage(testContextTemplate{` <add> from %s <add> volume /test <add> cmd Hello world <add> `, nil}, t) <add> <ide> if len(img.Config.Volumes) == 0 { <ide> t.Fail() <ide> } <ide> CMD Hello world <ide> } <ide> } <ide> } <add> <add>func TestBuildMaintainer(t *testing.T) { <add> img := buildImage(testContextTemplate{` <add> from %s <add> maintainer dockerio <add> `, nil}, t) <add> <add> if img.Author != "dockerio" { <add> t.Fail() <add> } <add>} <add> <add>func TestBuildEnv(t *testing.T) { <add> img := buildImage(testContextTemplate{` <add> from %s <add> env port 4243 <add> `, <add> nil}, t) <add> <add> if img.Config.Env[0] != "port=4243" { <add> t.Fail() <add> } <add>} <add> <add>func TestBuildCmd(t *testing.T) { <add> img := buildImage(testContextTemplate{` <add> from %s <add> cmd ["/bin/echo", "Hello World"] <add> `, <add> nil}, t) <add> <add> if img.Config.Cmd[0] != "/bin/echo" { <add> t.Log(img.Config.Cmd[0]) <add> t.Fail() <add> } <add> if img.Config.Cmd[1] != "Hello World" { <add> t.Log(img.Config.Cmd[1]) <add> t.Fail() <add> } <add>} <add> <add>func TestBuildExpose(t *testing.T) { <add> img := buildImage(testContextTemplate{` <add> from %s <add> expose 4243 <add> `, <add> nil}, t) <add> <add> if img.Config.PortSpecs[0] != "4243" { <add> t.Fail() <add> } <add>} <add> <add>func TestBuildEntrypoint(t *testing.T) { <add> img := buildImage(testContextTemplate{` <add> from %s <add> entrypoint ["/bin/echo"] <add> `, <add> nil}, t) <add> <add> if img.Config.Entrypoint[0] != "/bin/echo" { <add> } <add>}
1
Javascript
Javascript
allow falsy values as option group identifiers
b71d7c3f3c04e65b02d88b33c22dd90ae3cdfc27
<ide><path>src/ng/directive/ngOptions.js <ide> var ngOptionsDirective = ['$compile', '$parse', function($compile, $parse) { <ide> var groupElement; <ide> var optionElement; <ide> <del> if (option.group) { <add> if (isDefined(option.group)) { <ide> <ide> // This option is to live in a group <ide> // See if we have already created this group <ide><path>test/ng/directive/ngOptionsSpec.js <ide> describe('ngOptions', function() { <ide> <ide> scope.$apply(function() { <ide> scope.values = [{name: 'A'}, <del> {name: 'B', group: 'first'}, <del> {name: 'C', group: 'second'}, <del> {name: 'D', group: 'first'}, <del> {name: 'E', group: 'second'}]; <add> {name: 'B', group: 0}, <add> {name: 'C', group: 'first'}, <add> {name: 'D', group: 'second'}, <add> {name: 'E', group: 0}, <add> {name: 'F', group: 'first'}, <add> {name: 'G', group: 'second'}]; <ide> scope.selected = scope.values[3]; <ide> }); <ide> <ide> expect(element).toEqualSelectValue(scope.selected); <ide> <del> var first = jqLite(element.find('optgroup')[0]); <del> var b = jqLite(first.find('option')[0]); <del> var d = jqLite(first.find('option')[1]); <del> expect(first.attr('label')).toEqual('first'); <add> var zero = jqLite(element.find('optgroup')[0]); <add> var b = jqLite(zero.find('option')[0]); <add> var e = jqLite(zero.find('option')[1]); <add> expect(zero.attr('label')).toEqual('0'); <ide> expect(b.text()).toEqual('B'); <del> expect(d.text()).toEqual('D'); <add> expect(e.text()).toEqual('E'); <ide> <del> var second = jqLite(element.find('optgroup')[1]); <del> var c = jqLite(second.find('option')[0]); <del> var e = jqLite(second.find('option')[1]); <del> expect(second.attr('label')).toEqual('second'); <add> var first = jqLite(element.find('optgroup')[1]); <add> var c = jqLite(first.find('option')[0]); <add> var f = jqLite(first.find('option')[1]); <add> expect(first.attr('label')).toEqual('first'); <ide> expect(c.text()).toEqual('C'); <del> expect(e.text()).toEqual('E'); <add> expect(f.text()).toEqual('F'); <add> <add> var second = jqLite(element.find('optgroup')[2]); <add> var d = jqLite(second.find('option')[0]); <add> var g = jqLite(second.find('option')[1]); <add> expect(second.attr('label')).toEqual('second'); <add> expect(d.text()).toEqual('D'); <add> expect(g.text()).toEqual('G'); <ide> <ide> scope.$apply(function() { <ide> scope.selected = scope.values[0];
2
Ruby
Ruby
fix dry run
9abd7d31bd1db07e572a5f2dbc864ab538e811bc
<ide><path>Library/Homebrew/cleanup.rb <ide> def cleanup_path(path) <ide> <ide> if dry_run? <ide> puts "Would remove: #{path} (#{path.abv})" <add> @disk_cleanup_size += disk_usage <ide> else <ide> puts "Removing: #{path}... (#{path.abv})" <ide> yield <add> @disk_cleanup_size += disk_usage - path.disk_usage <ide> end <ide> <del> @disk_cleanup_size += disk_usage - path.disk_usage <ide> end <ide> <ide> def cleanup_lockfiles(*lockfiles)
1
Javascript
Javascript
move element cache to element[expando]
d702b7637a61e1973e08c27b8d8de2ed24a543e2
<ide><path>src/data/Data.js <ide> define([ <ide> ], function( jQuery, rnotwhite ) { <ide> <ide> function Data() { <del> // Support: Android<4, <del> // Old WebKit does not have Object.preventExtensions/freeze method, <del> // return new empty object instead with no [[set]] accessor <del> Object.defineProperty( this.cache = {}, 0, { <del> get: function() { <del> return {}; <del> } <del> }); <del> <ide> this.expando = jQuery.expando + Data.uid++; <ide> } <ide> <ide> Data.uid = 1; <ide> Data.accepts = jQuery.acceptData; <ide> <ide> Data.prototype = { <del> key: function( owner ) { <del> // We can accept data for non-element nodes in modern browsers, <del> // but we should not, see #8335. <del> // Always return the key for a frozen object. <del> if ( !Data.accepts( owner ) ) { <del> return 0; <del> } <del> <del> // Check if the owner object already has a cache key <del> var unlock = owner[ this.expando ]; <ide> <del> // If not, create one <del> if ( !unlock ) { <del> unlock = Data.uid++; <add> register: function( owner, initial ) { <add> var descriptor = {}, <add> value = initial || {}; <ide> <add> try { <ide> // If it is a node unlikely to be stringify-ed or looped over <ide> // use plain assignment <ide> if ( owner.nodeType ) { <del> owner[ this.expando ] = unlock; <add> owner[ this.expando ] = value; <add> <ide> // Otherwise secure it in a non-enumerable, non-writable property <add> // configurability must be true to allow the property to be <add> // deleted with the delete operator <ide> } else { <del> Object.defineProperty( owner, this.expando, { value: unlock } ); <add> descriptor[ this.expando ] = { <add> value: value, <add> writable: true, <add> configurable: true <add> }; <add> Object.defineProperties( owner, descriptor ); <ide> } <add> <add> // Support: Android < 4 <add> // Fallback to a less secure definition <add> } catch ( e ) { <add> descriptor[ this.expando ] = value; <add> jQuery.extend( owner, descriptor ); <ide> } <ide> <del> // Ensure the cache object <del> if ( !this.cache[ unlock ] ) { <del> this.cache[ unlock ] = {}; <add> return owner[ this.expando ]; <add> }, <add> cache: function( owner, initial ) { <add> // We can accept data for non-element nodes in modern browsers, <add> // but we should not, see #8335. <add> // Always return an empty object. <add> if ( !Data.accepts( owner ) ) { <add> return {}; <ide> } <ide> <del> return unlock; <add> // Check if the owner object already has a cache <add> var cache = owner[ this.expando ]; <add> <add> // If so, return it <add> if ( cache ) { <add> return cache; <add> } <add> <add> // If not, register one <add> return this.register( owner, initial ); <ide> }, <ide> set: function( owner, data, value ) { <ide> var prop, <del> // There may be an unlock assigned to this node, <del> // if there is no entry for this "owner", create one inline <del> // and set the unlock as though an owner entry had always existed <del> unlock = this.key( owner ), <del> cache = this.cache[ unlock ]; <add> cache = this.cache( owner ); <ide> <ide> // Handle: [ owner, key, value ] args <ide> if ( typeof data === "string" ) { <ide> Data.prototype = { <ide> } else { <ide> // Fresh assignments by object are shallow copied <ide> if ( jQuery.isEmptyObject( cache ) ) { <del> jQuery.extend( this.cache[ unlock ], data ); <add> <add> jQuery.extend( cache, data ); <ide> // Otherwise, copy the properties one-by-one to the cache object <ide> } else { <ide> for ( prop in data ) { <ide> Data.prototype = { <ide> return cache; <ide> }, <ide> get: function( owner, key ) { <del> // Either a valid cache is found, or will be created. <del> // New caches will be created and the unlock returned, <del> // allowing direct access to the newly created <del> // empty data object. A valid owner object must be provided. <del> var cache = this.cache[ this.key( owner ) ]; <add> var cache = this.cache( owner ); <ide> <ide> return key === undefined ? <ide> cache : cache[ key ]; <ide> Data.prototype = { <ide> }, <ide> remove: function( owner, key ) { <ide> var i, name, camel, <del> unlock = this.key( owner ), <del> cache = this.cache[ unlock ]; <add> cache = this.cache( owner ); <ide> <ide> if ( key === undefined ) { <del> this.cache[ unlock ] = {}; <add> this.register( owner ); <ide> <ide> } else { <ide> // Support array or space separated string of keys <ide> Data.prototype = { <ide> } <ide> <ide> i = name.length; <add> <ide> while ( i-- ) { <ide> delete cache[ name[ i ] ]; <ide> } <ide> } <ide> }, <ide> hasData: function( owner ) { <del> return !jQuery.isEmptyObject( <del> this.cache[ owner[ this.expando ] ] || {} <del> ); <add> var cache = owner[ this.expando ]; <add> return cache !== undefined && !jQuery.isEmptyObject( cache ); <ide> }, <ide> discard: function( owner ) { <ide> if ( owner[ this.expando ] ) { <del> delete this.cache[ owner[ this.expando ] ]; <add> delete owner[ this.expando ]; <ide> } <ide> } <ide> }; <ide><path>src/event.js <ide> jQuery.event = { <ide> <ide> // Remove the expando if it's no longer used <ide> if ( jQuery.isEmptyObject( events ) ) { <add> // Normally this should go through the data api <add> // but since event.js owns these properties, <add> // this exception is made for the sake of optimizing <add> // the operation. <ide> delete elemData.handle; <del> dataPriv.remove( elem, "events" ); <add> delete elemData.events; <ide> } <ide> }, <ide> <ide><path>src/manipulation.js <ide> jQuery.extend({ <ide> }, <ide> <ide> cleanData: function( elems ) { <del> var data, elem, type, key, <add> var data, elem, type, <ide> special = jQuery.event.special, <ide> i = 0; <ide> <ide> for ( ; (elem = elems[ i ]) !== undefined; i++ ) { <del> if ( jQuery.acceptData( elem ) ) { <del> key = elem[ dataPriv.expando ]; <del> <del> if ( key && (data = dataPriv.cache[ key ]) ) { <del> if ( data.events ) { <del> for ( type in data.events ) { <del> if ( special[ type ] ) { <del> jQuery.event.remove( elem, type ); <del> <del> // This is a shortcut to avoid jQuery.event.remove's overhead <del> } else { <del> jQuery.removeEvent( elem, type, data.handle ); <del> } <add> if ( jQuery.acceptData( elem ) && (data = elem[ dataPriv.expando ])) { <add> if ( data.events ) { <add> for ( type in data.events ) { <add> if ( special[ type ] ) { <add> jQuery.event.remove( elem, type ); <add> <add> // This is a shortcut to avoid jQuery.event.remove's overhead <add> } else { <add> jQuery.removeEvent( elem, type, data.handle ); <ide> } <ide> } <del> if ( dataPriv.cache[ key ] ) { <del> // Discard any remaining `private` data <del> delete dataPriv.cache[ key ]; <del> } <ide> } <add> delete data.events; <ide> } <del> // Discard any remaining `user` data <del> delete dataUser.cache[ elem[ dataUser.expando ] ]; <ide> } <ide> } <ide> }); <ide><path>test/unit/manipulation.js <ide> test( "text(undefined)", function() { <ide> <ide> function testText( valueObj ) { <ide> <del> expect( 7 ); <add> expect( 6 ); <ide> <ide> var val, j, expected, $multipleElements, $parentDiv, $childDiv; <ide> <ide> function testText( valueObj ) { <ide> $parentDiv = jQuery( "<div/>" ); <ide> $parentDiv.append( $childDiv ); <ide> $parentDiv.text("Dry off"); <del> <del> equal( $childDiv.data("leak"), undefined, "Check for leaks (#11809)" ); <ide> } <ide> <ide> test( "text(String)", function() { <ide> test( "clone()/html() don't expose jQuery/Sizzle expandos (#12858)", function() <ide> <ide> test( "remove() no filters", function() { <ide> <del> expect( 3 ); <add> expect( 2 ); <ide> <ide> var first = jQuery("#ap").children().first(); <ide> <ide> test( "remove() no filters", function() { <ide> jQuery("#ap").children().remove(); <ide> ok( jQuery("#ap").text().length > 10, "Check text is not removed" ); <ide> equal( jQuery("#ap").children().length, 0, "Check remove" ); <del> <del> equal( first.data("foo"), null, "first data" ); <del> <ide> }); <ide> <ide> test( "remove() with filters", function() {
4
Javascript
Javascript
add a shim for hmrclient in prod bundles
abc663dd5a1f6968f4571a80384dbd702340de45
<ide><path>Libraries/Core/setUpBatchedBridge.js <ide> if (!global.RN$Bridgeless) { <ide> 'HMRClient', <ide> require('../Utilities/HMRClient'), <ide> ); <add> } else { <add> BatchedBridge.registerCallableModule( <add> 'HMRClient', <add> require('../Utilities/HMRClientProdShim'), <add> ); <ide> } <ide> } <ide><path>Libraries/Utilities/HMRClient.js <ide> let didSetupSocket = false; <ide> let hmrClient = null; <ide> let hmrUnavailableReason: string | null = null; <ide> <add>export type HMRClientNativeInterface = {| <add> enable(): void, <add> disable(): void, <add> setup( <add> platform: string, <add> bundleEntry: string, <add> host: string, <add> port: number | string, <add> isEnabled: boolean, <add> ): void, <add>|}; <add> <ide> /** <ide> * HMR Client that receives from the server HMR updates and propagates them <ide> * runtime to reflects those changes. <ide> */ <del>const HMRClient = { <add>const HMRClient: HMRClientNativeInterface = { <ide> enable() { <ide> if (hmrUnavailableReason !== null) { <ide> // If HMR became unavailable while you weren't using it, <ide><path>Libraries/Utilities/HMRClientProdShim.js <add>/** <add> * Copyright (c) Facebook, Inc. and its affiliates. <add> * <add> * This source code is licensed under the MIT license found in the <add> * LICENSE file in the root directory of this source tree. <add> * <add> * @format <add> * @flow <add> */ <add>'use strict'; <add> <add>import type {HMRClientNativeInterface} from './HMRClient'; <add> <add>// This shim ensures DEV binary builds don't crash in JS <add>// when they're combined with a PROD JavaScript build. <add>const HMRClientProdShim: HMRClientNativeInterface = { <add> setup() {}, <add> enable() { <add> console.error( <add> 'Fast Refresh is disabled in JavaScript bundles built in production mode. ' + <add> 'Did you forget to run Metro?', <add> ); <add> }, <add> disable() {}, <add>}; <add> <add>module.exports = HMRClientProdShim;
3
Ruby
Ruby
save encrypted config even if yaml is invalid
772c462738339bfc1637d2cbfca7bd6cd455bb9e
<ide><path>activesupport/lib/active_support/encrypted_configuration.rb <ide> <ide> module ActiveSupport <ide> class EncryptedConfiguration < EncryptedFile <add> class InvalidContentError < RuntimeError <add> def initialize(content_path) <add> super "Invalid YAML in '#{content_path}'." <add> end <add> <add> def message <add> cause.is_a?(Psych::SyntaxError) ? "#{super}\n\n #{cause.message}" : super <add> end <add> end <add> <ide> delegate :[], :fetch, to: :config <ide> delegate_missing_to :options <ide> <ide> def read <ide> "" <ide> end <ide> <del> def write(contents) <del> deserialize(contents) <del> <del> super <add> def validate! # :nodoc: <add> deserialize(read) <ide> end <ide> <ide> def config <ide> def options <ide> @options ||= ActiveSupport::InheritableOptions.new(deep_transform(config)) <ide> end <ide> <del> def deserialize(config) <del> doc = YAML.respond_to?(:unsafe_load) ? YAML.unsafe_load(config) : YAML.load(config) <del> doc.presence || {} <add> def deserialize(content) <add> config = YAML.respond_to?(:unsafe_load) ? <add> YAML.unsafe_load(content, filename: content_path) : <add> YAML.load(content, filename: content_path) <add> <add> config.presence || {} <add> rescue Psych::SyntaxError <add> raise InvalidContentError.new(content_path) <ide> end <ide> end <ide> end <ide><path>activesupport/test/encrypted_configuration_test.rb <ide> class EncryptedConfigurationTest < ActiveSupport::TestCase <ide> assert_equal "things", @credentials[:new] <ide> end <ide> <del> test "raise error when writing an invalid format value" do <del> assert_raise(Psych::SyntaxError) do <del> @credentials.change do |config_file| <del> config_file.write "login: *login\n username: dummy" <del> end <add> test "raises helpful error when loading invalid content" do <add> @credentials.write("key: value\nbad") <add> <add> assert_raise(ActiveSupport::EncryptedConfiguration::InvalidContentError) do <add> @credentials.config <add> end <add> end <add> <add> test "raises helpful error when validating invalid content" do <add> @credentials.write("key: value\nbad") <add> <add> assert_raise(ActiveSupport::EncryptedConfiguration::InvalidContentError) do <add> @credentials.validate! <ide> end <ide> end <ide> <ide><path>railties/lib/rails/commands/credentials/credentials_command.rb <ide> def edit <ide> end <ide> <ide> say "File encrypted and saved." <add> warn_if_credentials_are_invalid <ide> rescue ActiveSupport::MessageEncryptor::InvalidMessage <ide> say "Couldn't decrypt #{content_path}. Perhaps you passed the wrong key?" <ide> end <ide> def change_credentials_in_system_editor <ide> end <ide> end <ide> <add> def warn_if_credentials_are_invalid <add> credentials.validate! <add> rescue ActiveSupport::EncryptedConfiguration::InvalidContentError => error <add> say "WARNING: #{error.message}", :red <add> say "" <add> say "Your application will not be able to load '#{content_path}' until the error has been fixed.", :red <add> end <add> <ide> def missing_credentials_message <ide> if !credentials.key? <ide> "Missing '#{key_path}' to decrypt credentials. See `bin/rails credentials:help`" <ide><path>railties/lib/rails/commands/encrypted/encrypted_command.rb <ide> def edit(*) <ide> end <ide> <ide> say "File encrypted and saved." <add> warn_if_encrypted_configuration_is_invalid <ide> rescue ActiveSupport::MessageEncryptor::InvalidMessage <ide> say "Couldn't decrypt #{content_path}. Perhaps you passed the wrong key?" <ide> end <ide> def change_encrypted_configuration_in_system_editor <ide> end <ide> end <ide> <add> def warn_if_encrypted_configuration_is_invalid <add> encrypted_configuration.validate! <add> rescue ActiveSupport::EncryptedConfiguration::InvalidContentError => error <add> say "WARNING: #{error.message}", :red <add> say "" <add> say "Your application will not be able to load '#{content_path}' until the error has been fixed.", :red <add> end <ide> <ide> def encryption_key_file_generator <ide> require "rails/generators" <ide><path>railties/test/commands/credentials_test.rb <ide> class Rails::Command::CredentialsCommandTest < ActiveSupport::TestCase <ide> assert_match %r/provides_secret_key_base: true/, run_edit_command <ide> end <ide> <add> test "edit command preserves user's content even if it contains invalid YAML" do <add> write_invalid_yaml = %(ruby -e "File.write ARGV[0], 'foo: bar: bad'") <add> <add> assert_match %r/WARNING: Invalid YAML/, run_edit_command(editor: write_invalid_yaml) <add> assert_match %r/foo: bar: bad/, run_edit_command <add> end <add> <ide> <ide> test "show credentials" do <ide> assert_match DEFAULT_CREDENTIALS_PATTERN, run_show_command <ide><path>railties/test/commands/encrypted_test.rb <ide> class Rails::Command::EncryptedCommandTest < ActiveSupport::TestCase <ide> assert_match(/access_key_id: 123/, run_edit_command(key: "config/tokens.key")) <ide> end <ide> <add> test "edit command preserves user's content even if it contains invalid YAML" do <add> write_invalid_yaml = %(ruby -e "File.write ARGV[0], 'foo: bar: bad'") <add> <add> assert_match %r/WARNING: Invalid YAML/, run_edit_command(editor: write_invalid_yaml) <add> assert_match %r/foo: bar: bad/, run_edit_command <add> end <add> <add> <ide> test "show encrypted file with custom key" do <ide> run_edit_command(key: "config/tokens.key") <ide>
6
Java
Java
fix checkstyle violation
b28f403bf8314d27704b789a0eeda11f74aaf886
<ide><path>spring-web/src/test/java/org/springframework/web/util/UrlPathHelperTests.java <ide> import org.springframework.web.testfixture.servlet.MockHttpServletRequest; <ide> <ide> import static org.assertj.core.api.Assertions.assertThat; <del>import static org.assertj.core.api.Assertions.assertThatExceptionOfType; <add>import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; <ide> <ide> /** <ide> * Unit tests for {@link UrlPathHelper}. <ide> void getLookupPathWithSemicolonContentAndNullPathInfo() { <ide> void defaultInstanceReadOnlyBehavior() { <ide> UrlPathHelper helper = UrlPathHelper.defaultInstance; <ide> <del> assertThatExceptionOfType(IllegalArgumentException.class) <add> assertThatIllegalArgumentException() <ide> .isThrownBy(() -> helper.setAlwaysUseFullPath(true)) <ide> .withMessage("This instance cannot be modified"); <del> assertThatExceptionOfType(IllegalArgumentException.class) <add> assertThatIllegalArgumentException() <ide> .isThrownBy(() -> helper.setUrlDecode(true)) <ide> .withMessage("This instance cannot be modified"); <del> assertThatExceptionOfType(IllegalArgumentException.class) <add> assertThatIllegalArgumentException() <ide> .isThrownBy(() -> helper.setRemoveSemicolonContent(true)) <ide> .withMessage("This instance cannot be modified"); <del> assertThatExceptionOfType(IllegalArgumentException.class) <add> assertThatIllegalArgumentException() <ide> .isThrownBy(() -> helper.setDefaultEncoding("UTF-8")) <ide> .withMessage("This instance cannot be modified"); <ide>
1
Javascript
Javascript
add constant kmaxcallbacksuntilqueueisshortened
aa05209d6db3ae7f8b28f29492f3d136daf3c7f8
<ide><path>lib/internal/process/next_tick.js <ide> 'use strict'; <ide> <add>// This value is used to prevent the nextTickQueue from becoming too <add>// large and cause the process to run out of memory. When this value <add>// is reached the nextTimeQueue array will be shortend (see tickDone <add>// for details). <add>const kMaxCallbacksUntilQueueIsShortened = 1e4; <add> <ide> exports.setup = setupNextTick; <ide> <ide> function setupNextTick() { <ide> function setupNextTick() { <ide> // callback invocation with small numbers of arguments to avoid the <ide> // performance hit associated with using `fn.apply()` <ide> _combinedTickCallback(args, callback); <del> if (1e4 < tickInfo[kIndex]) <add> if (kMaxCallbacksUntilQueueIsShortened < tickInfo[kIndex]) <ide> tickDone(); <ide> } <ide> tickDone(); <ide> function setupNextTick() { <ide> // callback invocation with small numbers of arguments to avoid the <ide> // performance hit associated with using `fn.apply()` <ide> _combinedTickCallback(args, callback); <del> if (1e4 < tickInfo[kIndex]) <add> if (kMaxCallbacksUntilQueueIsShortened < tickInfo[kIndex]) <ide> tickDone(); <ide> if (domain) <ide> domain.exit();
1
Javascript
Javascript
parse query string in using urlsearchparams
fe95e100e42139fbc340e466c54dd0a61c9e2b2d
<ide><path>test/driver.js <ide> var Driver = (function DriverClosure() { <ide> <ide> Driver.prototype = { <ide> _getQueryStringParameters: function Driver_getQueryStringParameters() { <del> var queryString = window.location.search.substring(1); <del> var values = queryString.split("&"); <del> var parameters = {}; <del> for (var i = 0, ii = values.length; i < ii; i++) { <del> var value = values[i].split("="); <del> parameters[unescape(value[0])] = unescape(value[1]); <del> } <del> return parameters; <add> const queryString = window.location.search.substring(1); <add> return Object.fromEntries(new URLSearchParams(queryString).entries()); <ide> }, <ide> <ide> run: function Driver_run() { <ide><path>test/resources/reftest-analyzer.js <ide> window.onload = function () { <ide> function hashParameters() { <ide> const query = window.location.hash.substring(1); <ide> const params = new Map(); <del> for (const part of query.split(/[&;]/)) { <del> const param = part.split("="), <del> key = param[0].toLowerCase(), <del> value = param.length > 1 ? param[1] : ""; <del> params.set(decodeURIComponent(key), decodeURIComponent(value)); <add> for (const [key, value] of new URLSearchParams(query)) { <add> params.set(key.toLowerCase(), value); <ide> } <ide> return params; <ide> } <ide><path>web/ui_utils.js <ide> function watchScroll(viewAreaElement, callback) { <ide> */ <ide> function parseQueryString(query) { <ide> const params = new Map(); <del> for (const part of query.split("&")) { <del> const param = part.split("="), <del> key = param[0].toLowerCase(), <del> value = param.length > 1 ? param[1] : ""; <del> params.set(decodeURIComponent(key), decodeURIComponent(value)); <add> for (const [key, value] of new URLSearchParams(query)) { <add> params.set(key.toLowerCase(), value); <ide> } <ide> return params; <ide> }
3
Javascript
Javascript
make hot loading faster
e75e861116b99de0d1815ecf5eb025e125177e06
<ide><path>local-cli/server/util/attachHMRServer.js <ide> function attachHMRServer({httpServer, path, packagerServer}) { <ide> <ide> function disconnect() { <ide> client = null; <add> packagerServer.setHMRFileChangeListener(null); <ide> } <ide> <ide> // Returns a promise with the full list of dependencies and the shallow <ide> function attachHMRServer({httpServer, path, packagerServer}) { <ide> }); <ide> } <ide> <del> packagerServer.addFileChangeListener(filename => { <del> if (!client) { <del> return; <del> } <del> <del> packagerServer.getShallowDependencies(filename) <del> .then(deps => { <del> // if the file dependencies have change we need to invalidate the <del> // dependencies caches because the list of files we need to send to the <del> // client may have changed <del> if (arrayEquals(deps, client.shallowDependencies[filename])) { <del> return Promise.resolve(); <del> } <del> return getDependencies(client.platform, client.bundleEntry) <del> .then(({dependenciesCache, shallowDependencies}) => { <del> // invalidate caches <del> client.dependenciesCache = dependenciesCache; <del> client.shallowDependencies = shallowDependencies; <del> }); <del> }) <del> .then(() => { <del> // make sure the file was modified is part of the bundle <del> if (!client.shallowDependencies[filename]) { <del> return; <del> } <del> <del> return packagerServer.buildBundleForHMR({ <del> platform: client.platform, <del> entryFile: filename, <del> }) <del> .then(bundle => client.ws.send(bundle)); <del> }) <del> .done(); <del> }); <del> <ide> const WebSocketServer = require('ws').Server; <ide> const wss = new WebSocketServer({ <ide> server: httpServer, <ide> function attachHMRServer({httpServer, path, packagerServer}) { <ide> shallowDependencies, <ide> }; <ide> <add> packagerServer.setHMRFileChangeListener(filename => { <add> if (!client) { <add> return Promise.resolve(); <add> } <add> <add> return packagerServer.getShallowDependencies(filename) <add> .then(deps => { <add> // if the file dependencies have change we need to invalidate the <add> // dependencies caches because the list of files we need to send <add> // to the client may have changed <add> if (arrayEquals(deps, client.shallowDependencies[filename])) { <add> return Promise.resolve(); <add> } <add> return getDependencies(client.platform, client.bundleEntry) <add> .then(({dependenciesCache, shallowDependencies}) => { <add> // invalidate caches <add> client.dependenciesCache = dependenciesCache; <add> client.shallowDependencies = shallowDependencies; <add> }); <add> }) <add> .then(() => { <add> // make sure the file was modified is part of the bundle <add> if (!client.shallowDependencies[filename]) { <add> return; <add> } <add> <add> return packagerServer.buildBundleForHMR({ <add> platform: client.platform, <add> entryFile: filename, <add> }) <add> .then(bundle => client.ws.send(bundle)); <add> }); <add> }); <add> <ide> client.ws.on('error', e => { <ide> console.error('[Hot Module Replacement] Unexpected error', e); <ide> disconnect(); <ide><path>packager/react-packager/src/Server/index.js <ide> class Server { <ide> this._fileWatcher.on('all', this._onFileChange.bind(this)); <ide> <ide> this._debouncedFileChangeHandler = _.debounce(filePath => { <add> // if Hot Loading is enabled avoid rebuilding bundles and sending live <add> // updates. Instead, send the HMR updates right away and once that <add> // finishes, invoke any other file change listener. <add> if (this._hmrFileChangeListener) { <add> this._hmrFileChangeListener(filePath).then(() => { <add> this._fileChangeListeners.forEach(listener => listener(filePath)); <add> }).done(); <add> return; <add> } <add> <ide> this._fileChangeListeners.forEach(listener => listener(filePath)); <ide> this._rebuildBundles(filePath); <ide> this._informChangeWatchers(); <ide> class Server { <ide> this._fileChangeListeners.push(listener); <ide> } <ide> <add> setHMRFileChangeListener(listener) { <add> this._hmrFileChangeListener = listener; <add> } <add> <ide> buildBundle(options) { <ide> return Promise.resolve().then(() => { <ide> if (!options.platform) {
2
Javascript
Javascript
fix a typo in spec description
f9eb324716972bd5d43a83186977f278983c8ec9
<ide><path>test/ng/rootScopeSpec.js <ide> describe('Scope', function() { <ide> })); <ide> <ide> <del> it('should decrement anscestor $$listenerCount entries', inject(function($rootScope) { <add> it('should decrement ancestor $$listenerCount entries', inject(function($rootScope) { <ide> var EVENT = 'fooEvent', <ide> spy = jasmine.createSpy('listener'), <ide> firstSecond = first.$new();
1
Text
Text
add sponsor link
52f69fcf2529501bed81b2bc5b036c4edd729cd5
<ide><path>README.md <ide> We would like to extend our thanks to the following sponsors for funding Laravel <ide> - [Hyper Host](https://hyper.host) <ide> - [Appoly](https://www.appoly.co.uk) <ide> - [OP.GG](https://op.gg) <add>- [δΊ‘θ½―η§‘ζŠ€](http://www.yunruan.ltd/) <ide> <ide> ## Contributing <ide>
1
Ruby
Ruby
add system curl <10.7 check
c992749986a949e84b62dcc4070751652d355b31
<ide><path>Library/Homebrew/cmd/doctor.rb <ide> def check_user_path_3 <ide> end <ide> end <ide> <add> def check_for_bad_curl <add> if MacOS.version <= "10.6" && !Formula["curl"].installed? then <<-EOS.undent <add> The system curl on 10.6 and below is often incapable of supporting <add> modern secure connections & will fail on fetching formulae. <add> We recommend you: <add> brew install curl <add> EOS <add> end <add> end <add> <ide> def check_user_curlrc <ide> if %w[CURL_HOME HOME].any? { |key| ENV[key] && File.exist?("#{ENV[key]}/.curlrc") } then <<-EOS.undent <ide> You have a curlrc file <ide> If you have trouble downloading packages with Homebrew, then maybe this <ide> is the problem? If the following command doesn't work, then try removing <ide> your curlrc: <del> curl http://github.com <add> curl https://github.com <ide> EOS <ide> end <ide> end
1
Python
Python
remove dumbass meaningless test
bd28e43ce48651669f36a3bc3d56cf55a2eb20fd
<ide><path>djangorestframework/tests/renderers.py <ide> def test_conflicting_format_query_and_accept_ignores_accept(self): <ide> self.assertEquals(resp.content, RENDERER_B_SERIALIZER(DUMMYCONTENT)) <ide> self.assertEquals(resp.status_code, DUMMYSTATUS) <ide> <del> def test_bla(self): # What the f***? <del> resp = self.client.get('/?format=formatb', <del> HTTP_ACCEPT='text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8') <del> self.assertEquals(resp['Content-Type'], RendererB.media_type) <del> self.assertEquals(resp.content, RENDERER_B_SERIALIZER(DUMMYCONTENT)) <del> self.assertEquals(resp.status_code, DUMMYSTATUS) <ide> <ide> _flat_repr = '{"foo": ["bar", "baz"]}' <ide> _indented_repr = '{\n "foo": [\n "bar",\n "baz"\n ]\n}'
1
Text
Text
fix italics in readme
d82a6057a18f75518a99add37ad4b8c31b087b9a
<ide><path>examples/with-dynamic-app-layout/README.md <ide> # With dynamic `App` layout example <ide> <del>Shows how to use _app.js to implement \_dynamic_ layouts for pages. This is achieved by attaching a static `Layout` property to each page that needs a different layout. In that way, once we use `_app.js` to wrap our pages, we can get it from `Component.Layout` and render it accordingly. <add>Shows how to use `pages/_app.js` to implement _dynamic_ layouts for pages. This is achieved by attaching a static `Layout` property to each page that needs a different layout. In that way, once we use `pages/_app.js` to wrap our pages, we can get it from `Component.Layout` and render it accordingly. <ide> <ide> ## Deploy your own <ide>
1
Text
Text
update dataset examples
576a37d19b0af6aac318d167673333d342150529
<ide><path>research/deeplab/g3doc/cityscapes.md <ide> A local training job using `xception_65` can be run with the following command: <ide> python deeplab/train.py \ <ide> --logtostderr \ <ide> <<<<<<< HEAD <add><<<<<<< HEAD <add>======= <add> --training_number_of_steps=90000 \ <add>>>>>>>> origin/master <ide> ======= <ide> --training_number_of_steps=90000 \ <ide> >>>>>>> origin/master <ide> python deeplab/train.py \ <ide> --train_crop_size=769 \ <ide> --train_batch_size=1 \ <ide> <<<<<<< HEAD <add><<<<<<< HEAD <add>======= <add> --dataset="cityscapes" \ <add> --train_split="train" \ <add>>>>>>>> origin/master <ide> ======= <ide> --dataset="cityscapes" \ <ide> --train_split="train" \ <ide> where ${PATH_TO_INITIAL_CHECKPOINT} is the path to the initial checkpoint <ide> directory in which training checkpoints and events will be written to, and <ide> ${PATH_TO_DATASET} is the directory in which the Cityscapes dataset resides. <ide> <add><<<<<<< HEAD <ide> <<<<<<< HEAD <ide> Note that for {train,eval,vis}.py: <ide> <ide> 1. We use small batch size during training. The users could change it based on <ide> the available GPU memory and also set `fine_tune_batch_norm` to be False or <ide> True depending on the use case. <ide> ======= <add>======= <add>>>>>>>> origin/master <ide> **Note that for {train,eval,vis}.py**: <ide> <ide> 1. In order to reproduce our results, one needs to use large batch size (> 8), <ide> Note that for {train,eval,vis}.py: <ide> GPU memory at hand, please fine-tune from our provided checkpoints whose <ide> batch norm parameters have been trained, and use smaller learning rate with <ide> fine_tune_batch_norm = False. <add><<<<<<< HEAD <add>>>>>>>> origin/master <add>======= <ide> >>>>>>> origin/master <ide> <ide> 2. The users should change atrous_rates from [6, 12, 18] to [12, 24, 36] if <ide> python deeplab/eval.py \ <ide> --eval_crop_size=1025 \ <ide> --eval_crop_size=2049 \ <ide> <<<<<<< HEAD <add><<<<<<< HEAD <add>======= <add> --dataset="cityscapes" \ <add> --eval_split="val" \ <add>>>>>>>> origin/master <ide> ======= <ide> --dataset="cityscapes" \ <ide> --eval_split="val" \ <ide> python deeplab/vis.py \ <ide> --vis_crop_size=1025 \ <ide> --vis_crop_size=2049 \ <ide> <<<<<<< HEAD <add><<<<<<< HEAD <add>======= <add> --dataset="cityscapes" \ <add> --vis_split="val" \ <add>>>>>>>> origin/master <ide> ======= <ide> --dataset="cityscapes" \ <ide> --vis_split="val" \ <ide><path>research/deeplab/g3doc/pascal.md <ide> A local training job using `xception_65` can be run with the following command: <ide> python deeplab/train.py \ <ide> --logtostderr \ <ide> <<<<<<< HEAD <add><<<<<<< HEAD <add>======= <add> --training_number_of_steps=30000 \ <add>>>>>>>> origin/master <ide> ======= <ide> --training_number_of_steps=30000 \ <ide> >>>>>>> origin/master <ide> python deeplab/train.py \ <ide> --train_crop_size=513 \ <ide> --train_batch_size=1 \ <ide> <<<<<<< HEAD <add><<<<<<< HEAD <add>======= <add> --dataset="pascal_voc_seg" \ <add> --train_split="train" \ <add>>>>>>>> origin/master <ide> ======= <ide> --dataset="pascal_voc_seg" \ <ide> --train_split="train" \ <ide> directory in which training checkpoints and events will be written to, and <ide> ${PATH_TO_DATASET} is the directory in which the PASCAL VOC 2012 dataset <ide> resides. <ide> <add><<<<<<< HEAD <ide> <<<<<<< HEAD <ide> Note that for {train,eval,vis}.py: <ide> <ide> 1. We use small batch size during training. The users could change it based on <ide> the available GPU memory and also set `fine_tune_batch_norm` to be False or <ide> True depending on the use case. <ide> ======= <add>======= <add>>>>>>>> origin/master <ide> **Note that for {train,eval,vis}.py:** <ide> <ide> 1. In order to reproduce our results, one needs to use large batch size (> 12), <ide> Note that for {train,eval,vis}.py: <ide> GPU memory at hand, please fine-tune from our provided checkpoints whose <ide> batch norm parameters have been trained, and use smaller learning rate with <ide> fine_tune_batch_norm = False. <add><<<<<<< HEAD <add>>>>>>>> origin/master <add>======= <ide> >>>>>>> origin/master <ide> <ide> 2. The users should change atrous_rates from [6, 12, 18] to [12, 24, 36] if <ide> python deeplab/eval.py \ <ide> --eval_crop_size=513 \ <ide> --eval_crop_size=513 \ <ide> <<<<<<< HEAD <add><<<<<<< HEAD <add>======= <add> --dataset="pascal_voc_seg" \ <add> --eval_split="val" \ <add>>>>>>>> origin/master <ide> ======= <ide> --dataset="pascal_voc_seg" \ <ide> --eval_split="val" \ <ide> python deeplab/vis.py \ <ide> --vis_crop_size=513 \ <ide> --vis_crop_size=513 \ <ide> <<<<<<< HEAD <add><<<<<<< HEAD <add>======= <add> --dataset="pascal_voc_seg" \ <add> --vis_split="val" \ <add>>>>>>>> origin/master <ide> ======= <ide> --dataset="pascal_voc_seg" \ <ide> --vis_split="val" \
2
Text
Text
adjust readme of example
0b1ef7cbf45ee23694b83b9efbf62eb9bd29f6c9
<ide><path>examples/with-zones/README.md <ide> cd with-zones <ide> <ide> ## Notes <ide> <del>In this example, we have two apps: 'home' and 'blog'. We'll start both apps with [Now](https://zeit.co/now): <del> <del>```bash <del>now dev <del>``` <del> <del>Then, you can visit <http://localhost:3000> and develop for both apps as a single app. <del> <del>You can also start the apps separately, for example: <add>In this example, we have two apps: 'home' and 'blog'. You can start each app separately, for example: <ide> <ide> ```bash <ide> cd blog <ide> yarn dev <ide> ``` <ide> <add>Then, you can visit <http://localhost:3000> and develop your app. <add> <ide> ## Special Notes <ide> <ide> - All pages should be unique across zones. For example, the 'home' app should not have a `pages/blog/index.js` page. <ide> yarn dev <ide> <ide> ## Production Deployment <ide> <del>We only need to run `now`, the same `now.json` used for development will be used for the deployment: <add>We only need to run `now <app>`, to deploy the app: <ide> <ide> ```bash <del>now <add>now blog <add>now home <ide> ``` <add> <add>> The rewrite destination in your `now.json` file in the `home` app must be adjusted to point to your deployment.
1
Python
Python
create beaufort cipher
3bbec1db49eea0598412aa839ed055d151541443
<ide><path>ciphers/beaufort_cipher.py <add>""" <add>Author: Mohit Radadiya <add>""" <add> <add>from string import ascii_uppercase <add> <add>dict1 = {char: i for i, char in enumerate(ascii_uppercase)} <add>dict2 = {i: char for i, char in enumerate(ascii_uppercase)} <add> <add> <add># This function generates the key in <add># a cyclic manner until it's length isn't <add># equal to the length of original text <add>def generate_key(message: str, key: str) -> str: <add> """ <add> >>> generate_key("THE GERMAN ATTACK","SECRET") <add> 'SECRETSECRETSECRE' <add> """ <add> x = len(message) <add> i = 0 <add> while True: <add> if x == i: <add> i = 0 <add> if len(key) == len(message): <add> break <add> key += key[i] <add> i += 1 <add> return key <add> <add> <add># This function returns the encrypted text <add># generated with the help of the key <add>def cipher_text(message: str, key_new: str) -> str: <add> """ <add> >>> cipher_text("THE GERMAN ATTACK","SECRETSECRETSECRE") <add> 'BDC PAYUWL JPAIYI' <add> """ <add> cipher_text = "" <add> i = 0 <add> for letter in message: <add> if letter == " ": <add> cipher_text += " " <add> else: <add> x = (dict1[letter] - dict1[key_new[i]]) % 26 <add> i += 1 <add> cipher_text += dict2[x] <add> return cipher_text <add> <add> <add># This function decrypts the encrypted text <add># and returns the original text <add>def original_text(cipher_text: str, key_new: str) -> str: <add> """ <add> >>> original_text("BDC PAYUWL JPAIYI","SECRETSECRETSECRE") <add> 'THE GERMAN ATTACK' <add> """ <add> or_txt = "" <add> i = 0 <add> for letter in cipher_text: <add> if letter == " ": <add> or_txt += " " <add> else: <add> x = (dict1[letter] + dict1[key_new[i]] + 26) % 26 <add> i += 1 <add> or_txt += dict2[x] <add> return or_txt <add> <add> <add>def main(): <add> message = "THE GERMAN ATTACK" <add> key = "SECRET" <add> key_new = generate_key(message, key) <add> s = cipher_text(message, key_new) <add> print(f"Encrypted Text = {s}") <add> print(f"Original Text = {original_text(s, key_new)}") <add> <add> <add>if __name__ == "__main__": <add> import doctest <add> <add> doctest.testmod() <add> main()
1
Python
Python
improve error message
8c52008043c3fd3ebf5ad8ec20d85100388f52ed
<ide><path>libcloud/common/base.py <ide> def request(self, action, params=None, data=None, headers=None, <ide> # with hostname" error. This error could simpli indicate that <ide> # "host" Connection class attribute is set to an incorrect <ide> # value <del> msg = ('%s. Perhaphs "host" Connection class attribute (%s) ' <del> 'is set to an invalid, non-hostname value?' % <del> (message, self.host)) <add> class_name = self.__class__.__name__ <add> msg = ('%s. Perhaphs "host" Connection class attribute ' <add> '(%s.connection) is set to an invalid, non-hostname ' <add> 'value (%s)?' % <add> (message, class_name, self.host)) <ide> raise socket.gaierror(msg) <ide> self.reset_context() <ide> raise e
1
Javascript
Javascript
eliminate duplicate statements
a10962187f3885e691e053839402ccf7a40e852c
<ide><path>test/parallel/test-crypto-rsa-dsa.js <ide> const decryptError = { <ide> { <ide> const input = 'I AM THE WALRUS'; <ide> const bufferToEncrypt = Buffer.from(input); <add> const bufferPassword = Buffer.from('password'); <ide> <ide> let encryptedBuffer = crypto.publicEncrypt(rsaPubPem, bufferToEncrypt); <ide> <ide> const decryptError = { <ide> <ide> encryptedBuffer = crypto.privateEncrypt({ <ide> key: rsaKeyPemEncrypted, <del> passphrase: Buffer.from('password') <add> passphrase: bufferPassword <ide> }, bufferToEncrypt); <ide> <ide> decryptedBufferWithPassword = crypto.publicDecrypt({ <ide> key: rsaKeyPemEncrypted, <del> passphrase: Buffer.from('password') <add> passphrase: bufferPassword <ide> }, encryptedBuffer); <ide> assert.strictEqual(decryptedBufferWithPassword.toString(), input); <ide> <ide> // Now with explicit RSA_PKCS1_PADDING. <ide> encryptedBuffer = crypto.privateEncrypt({ <ide> padding: crypto.constants.RSA_PKCS1_PADDING, <ide> key: rsaKeyPemEncrypted, <del> passphrase: Buffer.from('password') <add> passphrase: bufferPassword <ide> }, bufferToEncrypt); <ide> <ide> decryptedBufferWithPassword = crypto.publicDecrypt({ <ide> padding: crypto.constants.RSA_PKCS1_PADDING, <ide> key: rsaKeyPemEncrypted, <del> passphrase: Buffer.from('password') <add> passphrase: bufferPassword <ide> }, encryptedBuffer); <ide> assert.strictEqual(decryptedBufferWithPassword.toString(), input); <ide> <ide> // Omitting padding should be okay because RSA_PKCS1_PADDING is the default. <ide> decryptedBufferWithPassword = crypto.publicDecrypt({ <ide> key: rsaKeyPemEncrypted, <del> passphrase: Buffer.from('password') <add> passphrase: bufferPassword <ide> }, encryptedBuffer); <ide> assert.strictEqual(decryptedBufferWithPassword.toString(), input); <ide> <ide> const decryptError = { <ide> encryptedBuffer = crypto.privateEncrypt({ <ide> padding: crypto.constants.RSA_NO_PADDING, <ide> key: rsaKeyPemEncrypted, <del> passphrase: Buffer.from('password') <add> passphrase: bufferPassword <ide> }, Buffer.from(plaintext)); <ide> <ide> decryptedBufferWithPassword = crypto.publicDecrypt({ <ide> padding: crypto.constants.RSA_NO_PADDING, <ide> key: rsaKeyPemEncrypted, <del> passphrase: Buffer.from('password') <add> passphrase: bufferPassword <ide> }, encryptedBuffer); <ide> assert.strictEqual(decryptedBufferWithPassword.toString(), plaintext); <ide>
1
Python
Python
add regression tests so they get loaded
4c2a11b0f32caee44b18fd521a2e62006a19f72f
<ide><path>numpy/core/tests/test_multiarray.py <ide> def check_basic(self): <ide> # Import tests from unicode <ide> set_local_path() <ide> from test_unicode import * <add>from test_regression import * <ide> restore_path() <ide> <ide> if __name__ == "__main__":
1
Ruby
Ruby
remove unnecessary cd
4ce99fa0102c352f79071d8ae6aa64078ed1493d
<ide><path>Library/Homebrew/test/test_integration_cmds.rb <ide> class Testball < Formula <ide> url "https://example.com/testball-0.1.tar.gz" <ide> end <ide> EOS <del> HOMEBREW_CACHE.cd do <del> assert_match(/testball-0\.1.*\.bottle\.tar\.gz/, <del> cmd_output("bottle", "--no-revision", "testball")) <del> end <add> assert_match(/testball-0\.1.*\.bottle\.tar\.gz/, <add> cmd_output("bottle", "--no-revision", "testball")) <ide> ensure <ide> cmd("uninstall", "--force", "testball") <ide> cmd("cleanup", "--force", "--prune=all")
1
PHP
PHP
add no migrations event
dba3cbecbc1d695bb87534c413f3966f06afc96e
<ide><path>src/Illuminate/Database/Events/NoMigrations.php <add><?php <add> <add>namespace Illuminate\Database\Events; <add> <add>class NoMigrations <add>{ <add> /** <add> * The migration method that was called. <add> * <add> * @var string <add> */ <add> public $method; <add> <add> /** <add> * Create a new event instance. <add> * <add> * @param string $method <add> * @return void <add> */ <add> public function __construct($method) <add> { <add> $this->method = $method; <add> } <add>} <ide><path>src/Illuminate/Database/Migrations/Migrator.php <ide> use Illuminate\Database\Events\MigrationsEnded; <ide> use Illuminate\Database\Events\MigrationsStarted; <ide> use Illuminate\Database\Events\MigrationStarted; <add>use Illuminate\Database\Events\NoMigrations; <ide> use Illuminate\Filesystem\Filesystem; <ide> use Illuminate\Support\Arr; <ide> use Illuminate\Support\Collection; <ide> public function runPending(array $migrations, array $options = []) <ide> // aren't, we will just make a note of it to the developer so they're aware <ide> // that all of the migrations have been run against this database system. <ide> if (count($migrations) === 0) { <add> $this->fireMigrationEvent(new NoMigrations('up')); <add> <ide> $this->note('<info>Nothing to migrate.</info>'); <ide> <ide> return; <ide> public function rollback($paths = [], array $options = []) <ide> $migrations = $this->getMigrationsForRollback($options); <ide> <ide> if (count($migrations) === 0) { <add> $this->fireMigrationEvent(new NoMigrations('down')); <add> <ide> $this->note('<info>Nothing to rollback.</info>'); <ide> <ide> return []; <ide><path>tests/Integration/Database/MigrateWithRealpathTest.php <ide> public function testMigrationsHasTheMigratedTable() <ide> 'batch' => 1, <ide> ]); <ide> } <del> <del> public function testMigrationEventsAreFired() <del> { <del> Event::fake(); <del> <del> Event::listen(MigrationsStarted::class, function ($event) { <del> return $this->assertInstanceOf(MigrationsStarted::class, $event); <del> }); <del> <del> Event::listen(MigrationsEnded::class, function ($event) { <del> return $this->assertInstanceOf(MigrationsEnded::class, $event); <del> }); <del> <del> Event::listen(MigrationStarted::class, function ($event) { <del> return $this->assertInstanceOf(MigrationStarted::class, $event); <del> }); <del> <del> Event::listen(MigrationEnded::class, function ($event) { <del> return $this->assertInstanceOf(MigrationEnded::class, $event); <del> }); <del> <del> $this->artisan('migrate'); <del> } <ide> } <ide><path>tests/Integration/Database/MigratorEventsTest.php <add><?php <add> <add>namespace Illuminate\Tests\Integration\Database; <add> <add>use Illuminate\Database\Events\MigrationEnded; <add>use Illuminate\Database\Events\MigrationsEnded; <add>use Illuminate\Database\Events\MigrationsStarted; <add>use Illuminate\Database\Events\MigrationStarted; <add>use Illuminate\Database\Events\NoMigrations; <add>use Illuminate\Database\Migrations\Migration; <add>use Illuminate\Support\Facades\Event; <add> <add>class MigratorEventsTest extends DatabaseTestCase <add>{ <add> protected function migrateOptions() <add> { <add> return [ <add> '--path' => realpath(__DIR__.'/stubs/'), <add> '--realpath' => true, <add> ]; <add> } <add> <add> public function testMigrationEventsAreFired() <add> { <add> Event::fake(); <add> <add> $this->artisan('migrate', $this->migrateOptions()); <add> $this->artisan('migrate:rollback', $this->migrateOptions()); <add> <add> Event::assertDispatched(MigrationsStarted::class, 2); <add> Event::assertDispatched(MigrationsEnded::class, 2); <add> Event::assertDispatched(MigrationStarted::class, 2); <add> Event::assertDispatched(MigrationEnded::class, 2); <add> } <add> <add> public function testMigrationEventsContainTheMigrationAndMethod() <add> { <add> Event::fake(); <add> <add> $this->artisan('migrate', $this->migrateOptions()); <add> $this->artisan('migrate:rollback', $this->migrateOptions()); <add> <add> Event::assertDispatched(MigrationStarted::class, function ($event) { <add> return $event->method == 'up' && $event->migration instanceof Migration; <add> }); <add> Event::assertDispatched(MigrationStarted::class, function ($event) { <add> return $event->method == 'down' && $event->migration instanceof Migration; <add> }); <add> Event::assertDispatched(MigrationEnded::class, function ($event) { <add> return $event->method == 'up' && $event->migration instanceof Migration; <add> }); <add> Event::assertDispatched(MigrationEnded::class, function ($event) { <add> return $event->method == 'down' && $event->migration instanceof Migration; <add> }); <add> } <add> <add> public function testTheNoMigrationEventIsFiredWhenNothingToMigrate() <add> { <add> Event::fake(); <add> <add> $this->artisan('migrate'); <add> $this->artisan('migrate:rollback'); <add> <add> Event::assertDispatched(NoMigrations::class, function ($event) { <add> return $event->method == 'up'; <add> }); <add> Event::assertDispatched(NoMigrations::class, function ($event) { <add> return $event->method == 'down'; <add> }); <add> } <add>}
4
Go
Go
add setupinitlayer() placeholder for solaris
eb2fbaa3f2c59bf4a78a3f642fe99a74e3e33b3e
<ide><path>daemon/daemon_solaris.go <ide> func setupDaemonRoot(config *Config, rootDir string, rootUID, rootGID int) error <ide> return nil <ide> } <ide> <add>func (daemon *Daemon) getLayerInit() func(string) error { <add> return nil <add>} <add> <ide> // setupInitLayer populates a directory with mountpoints suitable <ide> // for bind-mounting dockerinit into the container. The mountpoint is simply an <ide> // empty file at /.dockerinit
1
Javascript
Javascript
add accessibility toggle
c5d4bedda5d4cbb751a5d170f3c83ec684dae70d
<ide><path>client/src/templates/Challenges/classic/Editor.js <ide> import { createSelector } from 'reselect'; <ide> import { <ide> canFocusEditorSelector, <ide> executeChallenge, <add> inAccessibilityModeSelector, <ide> setEditorFocusability, <add> setAccessibilityMode, <ide> updateFile <ide> } from '../redux'; <ide> import { userSelector, isDonationModalOpenSelector } from '../../../redux'; <ide> const propTypes = { <ide> executeChallenge: PropTypes.func.isRequired, <ide> ext: PropTypes.string, <ide> fileKey: PropTypes.string, <add> inAccessibilityMode: PropTypes.bool.isRequired, <add> setAccessibilityMode: PropTypes.func.isRequired, <ide> setEditorFocusability: PropTypes.func, <ide> theme: PropTypes.string, <ide> updateFile: PropTypes.func.isRequired <ide> }; <ide> <ide> const mapStateToProps = createSelector( <ide> canFocusEditorSelector, <add> inAccessibilityModeSelector, <ide> isDonationModalOpenSelector, <ide> userSelector, <del> (canFocus, open, { theme = 'default' }) => ({ <add> (canFocus, accessibilityMode, open, { theme = 'default' }) => ({ <ide> canFocus: open ? false : canFocus, <add> inAccessibilityMode: accessibilityMode, <ide> theme <ide> }) <ide> ); <ide> <ide> const mapDispatchToProps = { <ide> setEditorFocusability, <add> setAccessibilityMode, <ide> executeChallenge, <ide> updateFile <ide> }; <ide> class Editor extends Component { <ide> <ide> editorDidMount = (editor, monaco) => { <ide> this._editor = editor; <del> if (this.props.canFocus) { <add> this._editor.updateOptions({ <add> accessibilitySupport: this.props.inAccessibilityMode ? 'on' : 'auto' <add> }); <add> // Users who are using screen readers should not have to move focus from <add> // the editor to the description every time they open a challenge. <add> if (this.props.canFocus && !this.props.inAccessibilityMode) { <ide> this._editor.focus(); <ide> } else this.focusOnHotkeys(); <ide> this._editor.addAction({ <ide> class Editor extends Component { <ide> this.props.setEditorFocusability(false); <ide> } <ide> }); <add> this._editor.addAction({ <add> id: 'toggle-accessibility', <add> label: 'Toggle Accessibility Mode', <add> keybindings: [monaco.KeyMod.CtrlCmd | monaco.KeyCode.F1], <add> run: () => { <add> const currentAccessibility = this.props.inAccessibilityMode; <add> // The store needs to be updated first, as onDidChangeConfiguration is <add> // called before updateOptions returns <add> this.props.setAccessibilityMode(!currentAccessibility); <add> this._editor.updateOptions({ <add> accessibilitySupport: currentAccessibility ? 'auto' : 'on' <add> }); <add> } <add> }); <ide> this._editor.onDidFocusEditorWidget(() => <ide> this.props.setEditorFocusability(true) <ide> ); <add> // This is to persist changes caused by the accessibility tooltip. <add> // Unfortunately it relies on Monaco's implementation details <add> this._editor.onDidChangeConfiguration(() => { <add> if ( <add> this._editor.getConfiguration().accessibilitySupport === 2 && <add> !this.props.inAccessibilityMode <add> ) { <add> this.props.setAccessibilityMode(true); <add> } <add> }); <ide> }; <ide> <ide> focusOnHotkeys() { <ide><path>client/src/templates/Challenges/redux/index.js <ide> const initialState = { <ide> }, <ide> challengeTests: [], <ide> consoleOut: '', <add> inAccessibilityMode: false, <ide> isCodeLocked: false, <ide> isBuildEnabled: true, <ide> modal: { <ide> export const types = createTypes( <ide> <ide> 'moveToTab', <ide> <del> 'setEditorFocusability' <add> 'setEditorFocusability', <add> 'setAccessibilityMode' <ide> ], <ide> ns <ide> ); <ide> export const submitChallenge = createAction(types.submitChallenge); <ide> export const moveToTab = createAction(types.moveToTab); <ide> <ide> export const setEditorFocusability = createAction(types.setEditorFocusability); <add>export const setAccessibilityMode = createAction(types.setAccessibilityMode); <ide> <ide> export const currentTabSelector = state => state[ns].currentTab; <ide> export const challengeFilesSelector = state => state[ns].challengeFiles; <ide> export const challengeDataSelector = state => { <ide> }; <ide> <ide> export const canFocusEditorSelector = state => state[ns].canFocusEditor; <add>export const inAccessibilityModeSelector = state => <add> state[ns].inAccessibilityMode; <ide> <ide> const MAX_LOGS_SIZE = 64 * 1024; <ide> <ide> export const reducer = handleActions( <ide> [types.setEditorFocusability]: (state, { payload }) => ({ <ide> ...state, <ide> canFocusEditor: payload <add> }), <add> [types.setAccessibilityMode]: (state, { payload }) => ({ <add> ...state, <add> inAccessibilityMode: payload <ide> }) <ide> }, <ide> initialState
2
Mixed
Javascript
improve example build and test
0d980a75ba82f0f7937cbcdc321574b833db139b
<ide><path>examples/build-common.js <ide> const doCompileAndReplace = (args, prefix, callback) => { <ide> }; <ide> <ide> async.series([ <del> callback => doCompileAndReplace("--mode production", "production", callback), <del> callback => doCompileAndReplace("--mode development --devtool none", "development", callback), <del> callback => doCompileAndReplace("--mode none --output-pathinfo", "", callback) <add> callback => doCompileAndReplace("--mode production --env production", "production", callback), <add> callback => doCompileAndReplace("--mode development --env development --devtool none", "development", callback), <add> callback => doCompileAndReplace("--mode none --env none --output-pathinfo", "", callback) <ide> ], () => { <ide> readme = tc.replaceBase(readme); <ide> fs.writeFile("README.md", readme, "utf-8", function() {}); <ide><path>examples/persistent-caching/README.md <ide> module.exports = (env = "development") => ({ <ide> mode: env, <ide> cache: { <ide> type: "filesystem", <del> name: env, <ide> cacheDirectory: path.resolve(__dirname, ".cache"), <ide> warn: true <ide> } <ide> module.exports = (env = "development") => ({ <ide> Hash: 0a1b2c3d4e5f6a7b8c9d <ide> Version: webpack 5.0.0-next <ide> Asset Size Chunks Chunk Names <del>output.js 1.34 MiB 0 [emitted] main <add>output.js 1.44 MiB 0 [emitted] main <ide> Entrypoint main = output.js <del>chunk {0} output.js (main) 1.19 MiB [entry] <add>chunk {0} output.js (main) 1.23 MiB [entry] <ide> > .\example.js main <del> 670 modules <add> 684 modules <ide> ``` <ide><path>test/Examples.test.js <ide> describe("Examples", () => { <ide> webpackConfigPath.substr(1); <ide> if (fs.existsSync(webpackConfigPath)) <ide> options = require(webpackConfigPath); <add> if (typeof options === "function") options = options(); <ide> if (Array.isArray(options)) options.forEach(processOptions); <ide> else processOptions(options); <ide> <ide><path>tooling/print-cache-file.js <ide> const printData = async (data, indent) => { <ide> } <ide> return; <ide> } <add> let currentReference = 0; <add> let currentTypeReference = 0; <ide> let i = 0; <ide> const read = () => { <ide> return data[i++]; <ide> const printData = async (data, indent) => { <ide> console.log(`${indent}- undefined`); <ide> } else if (nextItem === ESCAPE_END_OBJECT) { <ide> indent = indent.slice(0, indent.length - 2); <del> console.log(`${indent}}`); <add> console.log(`${indent}} #${currentReference++}`); <ide> } else if (typeof nextItem === "number") { <del> console.log(`${indent}- Reference ${nextItem}`); <add> console.log( <add> `${indent}- Reference ${nextItem} => #${currentReference + nextItem}` <add> ); <ide> } else { <add> const request = nextItem; <ide> let name = read(); <del> console.log(`${indent}- Object (${name}) {`); <add> if (request === null && name < 0) { <add> console.log( <add> `${indent}- Object (Reference ${name} => @${currentTypeReference + <add> name}) {` <add> ); <add> } else { <add> console.log( <add> `${indent}- Object (${request} / ${name} @${currentTypeReference++}) {` <add> ); <add> } <ide> indent += " "; <ide> } <ide> } else if (typeof item === "string") { <del> console.log(`${indent}- string ${JSON.stringify(item)}`); <add> console.log( <add> `${indent}- string ${JSON.stringify(item)} #${currentReference++}` <add> ); <ide> } else if (Buffer.isBuffer(item)) { <del> console.log(`${indent}- buffer ${item.toString("hex")}`); <add> console.log( <add> `${indent}- buffer ${item.toString("hex")} #${currentReference++}` <add> ); <ide> } else if (typeof item === "function") { <ide> const innerData = await item(); <ide> console.log(`${indent}- lazy {`); <ide> await printData(innerData, indent + " "); <ide> console.log(`${indent}}`); <add> } else { <add> console.log(`${indent}- ${item}`); <ide> } <ide> } <ide> };
4
Text
Text
fix pr-url for dep0148
b586c6a7ee648c9e9f9e0b65ba57d70097303e61
<ide><path>doc/api/deprecations.md <ide> Use `fs.rm(path, { recursive: true, force: true })` instead. <ide> <!-- YAML <ide> changes: <ide> - version: v15.1.0 <del> pr-url: https://github.com/nodejs/node/pull/35746 <add> pr-url: https://github.com/nodejs/node/pull/35747 <ide> description: Runtime deprecation. <ide> - version: v14.13.0 <ide> pr-url: https://github.com/nodejs/node/pull/34718
1
Python
Python
add numeric check to to_n_bytes_from_memory_str
629b2efa9875e327ba9cd1869688645c4ea89c73
<ide><path>libcloud/utils/misc.py <ide> def to_n_bytes_from_memory_str(memory_str): <ide> """ <ide> if memory_str.startswith("0"): <ide> return 0 <add> if memory_str.isnumeric(): <add> return int(memory_str) <ide> for unit, multiplier in K8S_UNIT_MAP.items(): <ide> if memory_str.endswith(unit): <ide> return int(memory_str.strip(unit)) * multiplier
1
Javascript
Javascript
remove enumerable.detect checks
764b8a71c87785478d0ffa44f095c3762e5ff9d0
<ide><path>packages/ember-runtime/lib/mixins/mutable_array.js <ide> import { <ide> beginPropertyChanges, <ide> endPropertyChanges <ide> } from 'ember-metal'; <del>import Enumerable from './enumerable'; <ide> import MutableEnumerable from './mutable_enumerable'; <ide> import EmberArray, { objectAt } from './array'; <ide> import { Error as EmberError } from 'ember-debug'; <ide> export default Mixin.create(EmberArray, MutableEnumerable, { <ide> @public <ide> */ <ide> pushObjects(objects) { <del> if (!(Enumerable.detect(objects) || Array.isArray(objects))) { <add> if (!Array.isArray(objects)) { <ide> throw new TypeError('Must pass Enumerable to MutableArray#pushObjects'); <ide> } <ide> this.replace(get(this, 'length'), 0, objects); <ide><path>packages/ember-runtime/lib/system/array_proxy.js <ide> import { <ide> } from '../utils'; <ide> import EmberObject from './object'; <ide> import MutableArray from '../mixins/mutable_array'; <del>import Enumerable from '../mixins/enumerable'; <ide> import { <ide> addArrayObserver, <ide> removeArrayObserver, <ide> export default EmberObject.extend(MutableArray, { <ide> }, <ide> <ide> pushObjects(objects) { <del> if (!(Enumerable.detect(objects) || isArray(objects))) { <add> if (!isArray(objects)) { <ide> throw new TypeError('Must pass Enumerable to MutableArray#pushObjects'); <ide> } <ide> this._replace(get(this, 'length'), 0, objects);
2
Javascript
Javascript
fix bug with setbounds #65
078e49f9c41e2455d09dfda8b04f0ef5aa8c3826
<ide><path>dist/Immutable.dev.js <ide> var $Vector = Vector; <ide> var offsetShift = 0; <ide> while (newOrigin + offsetShift < 0) { <ide> newRoot = new VNode(newRoot.array.length ? [, newRoot] : [], owner); <del> offsetShift += 1 << newLevel; <ide> newLevel += SHIFT; <add> offsetShift += 1 << newLevel; <ide> } <ide> if (offsetShift) { <ide> newOrigin += offsetShift; <ide><path>dist/Immutable.js <ide> return e.length=t.length,e.entries=function(){return t},e.__iterateUncached=func <ide> });return o?n.length:s+1}},{},J),L.prototype.get=V.prototype.get,L.prototype.has=V.prototype.has;var K={},H=function(t){return t&&t.constructor===F?t:t&&0!==t.length?F.empty().merge(t):F.empty()},F=H;z.createClass(H,{toString:function(){return this.__toString("Map {","}")},get:function(t,e){return null==t||null==this._root?e:this._root.get(0,M(t),t,e)},set:function(t,e){if(null==t)return this;var r,n=this.length;if(this._root){var i=b();r=this._root.set(this.__ownerID,0,M(t),t,e,i),i.value&&n++}else n++,r=I(this.__ownerID,0,M(t),t,e);return this.__ownerID?(this.length=n,this._root=r,this):r===this._root?this:F._make(n,r)},"delete":function(t){if(null==t||null==this._root)return this;if(this.__ownerID){var e=b();return this._root=this._root.delete(this.__ownerID,0,M(t),t,e),e.value&&this.length--,this}var r=this._root.delete(this.__ownerID,0,M(t),t);return r?r===this._root?this:F._make(this.length-1,r):F.empty()},update:function(t,e){return this.set(t,e(this.get(t)))},clear:function(){return this.__ownerID?(this.length=0,this._root=null,this):F.empty()},merge:function(){return O(this,null,arguments)},mergeWith:function(t){for(var e=[],r=1;arguments.length>r;r++)e[r-1]=arguments[r];return O(this,t,e)},mergeDeep:function(){return O(this,k(null),arguments)},mergeDeepWith:function(t){for(var e=[],r=1;arguments.length>r;r++)e[r-1]=arguments[r];return O(this,k(t),e)},updateIn:function(t,e){return D(this,t,e,0)},withMutations:function(t){var e=this.asMutable();return t(e),e.__ensureOwner(this.__ownerID)},asMutable:function(){return this.__ownerID?this:this.__ensureOwner(new N)},asImmutable:function(){return this.__ensureOwner()},__ensureOwner:function(t){return t===this.__ownerID?this:t?F._make(this.length,this._root,t):(this.__ownerID=t,this)},__deepEqual:function(t){var e=this;return t.every(function(t,r){return w(e.get(r,K),t)})},__iterate:function(t,e){return this._root?this._root.iterate(this,t,e):0}},{empty:function(){return Y||(Y=F._make(0))},_make:function(t,e,r){var n=Object.create(F.prototype);return n.length=t,n._root=e,n.__ownerID=r,n <ide> }},B),H.from=H;var N=function(){};z.createClass(N,{},{});var G=function(t,e,r,n){this.ownerID=t,this.bitmap=e,this.keys=r,this.values=n},Q=G;z.createClass(G,{get:function(t,e,r,n){var i=e>>>t&se;if(0===(this.bitmap&1<<i))return n;var s=this.keys[i],u=this.values[i];return null==s?u.get(t+ne,e,r,n):r===s?u:n},set:function(t,e,r,n,i,s){var u,o=r>>>e&se,a=1<<o;if(0===(this.bitmap&a))return s&&(s.value=!0),u=this.ensureOwner(t),u.keys[o]=n,u.values[o]=i,u.bitmap|=a,u;var h,l=this.keys[o],c=this.values[o];if(null==l)return h=c.set(t,e+ne,r,n,i,s),h===c?this:(u=this.ensureOwner(t),u.values[o]=h,u);if(n===l)return i===c?this:(u=this.ensureOwner(t),u.values[o]=i,u);var f=M(l);return h=r===f?new T(t,r,[l,n],[c,i]):I(t,e+ne,f,l,c).set(t,e+ne,r,n,i),s&&(s.value=!0),u=this.ensureOwner(t),delete u.keys[o],u.values[o]=h,u},"delete":function(t,e,r,n,i){var s,u=r>>>e&se,o=1<<u,a=this.keys[u];if(0===(this.bitmap&o)||null!=a&&n!==a)return this;if(null==a){var h=this.values[u],l=h.delete(t,e+ne,r,n,i);if(l===h)return this;if(l)return s=this.ensureOwner(t),s.values[u]=l,s}else i&&(i.value=!0);return this.bitmap===o?null:(s=this.ensureOwner(t),delete s.keys[u],delete s.values[u],s.bitmap^=o,s)},ensureOwner:function(t){return t&&t===this.ownerID?this:new Q(t,this.bitmap,this.keys.slice(),this.values.slice())},iterate:function(t,e,r){for(var n=this.values,i=this.keys,s=n.length,u=0;s>=u;u++){var o=r?s-u:u,a=i[o],h=n[o];if(null!=a){if(e(h,a,t)===!1)return!1}else if(h&&!h.iterate(t,e,r))return!1}return!0}},{});var T=function(t,e,r,n){this.ownerID=t,this.collisionHash=e,this.keys=r,this.values=n},X=T;z.createClass(T,{get:function(t,e,r,n){var i=B(this.keys).indexOf(r);return-1===i?n:this.values[i]},set:function(t,e,r,n,i,s){if(r!==this.collisionHash)return s&&(s.value=!0),I(t,e,this.collisionHash,null,this).set(t,e,r,n,i);var u=B(this.keys).indexOf(n);if(u>=0&&this.values[u]===i)return this;var o=this.ensureOwner(t);return-1===u?(o.keys.push(n),o.values.push(i),s&&(s.value=!0)):o.values[u]=i,o},"delete":function(t,e,r,n,i){var s=this.keys.indexOf(n); <ide> if(-1===s)return this;if(i&&(i.value=!0),this.values.length>1){var u=this.ensureOwner(t);return u.keys[s]=u.keys.pop(),u.values[s]=u.values.pop(),u}},ensureOwner:function(t){return t&&t===this.ownerID?this:new X(t,this.collisionHash,this.keys.slice(),this.values.slice())},iterate:function(t,e,r){for(var n=this.values,i=this.keys,s=n.length-1,u=0;s>=u;u++){var o=r?s-u:u;if(e(n[o],i[o],t)===!1)return!1}return!0}},{});var Y,Z={value:!1},$=4294967296,te=255,ee=0,re={},ne=5,ie=1<<ne,se=ie-1,K={},ue=function(){for(var t=[],e=0;arguments.length>e;e++)t[e]=arguments[e];return oe.from(t)},oe=ue;z.createClass(ue,{toString:function(){return this.__toString("Vector [","]")},get:function(t,e){if(t=E(t,this._origin),t>=this._size)return e;var r=this._nodeFor(t),n=t&se;return r&&(void 0===e||r.array.hasOwnProperty(n))?r.array[n]:e},first:function(){return this.get(0)},last:function(){return this.get(this.length?this.length-1:0)},set:function(t,e){var r=C(this._size);if(t>=this.length)return this.withMutations(function(r){return r._setBounds(0,t+1).set(t,e)});if(this.get(t,K)===e)return this;if(t=E(t,this._origin),t>=r){var n=this._tail.ensureOwner(this.__ownerID);n.array[t&se]=e;var i=t>=this._size?t+1:this._size;return this.__ownerID?(this.length=i-this._origin,this._size=i,this._tail=n,this):oe._make(this._origin,i,this._level,this._root,n)}for(var s=this._root.ensureOwner(this.__ownerID),u=s,o=this._level;o>0;o-=ne){var a=t>>>o&se;u=u.array[a]=u.array[a]?u.array[a].ensureOwner(this.__ownerID):new ae([],this.__ownerID)}return u.array[t&se]=e,this.__ownerID?(this._root=s,this):oe._make(this._origin,this._size,this._level,s,this._tail)},"delete":function(t){if(!this.has(t))return this;var e=C(this._size);if(t=E(t,this._origin),t>=e){var r=this._tail.ensureOwner(this.__ownerID);return delete r.array[t&se],this.__ownerID?(this._tail=r,this):oe._make(this._origin,this._size,this._level,this._root,r)}for(var n=this._root.ensureOwner(this.__ownerID),i=n,s=this._level;s>0;s-=ne){var u=t>>>s&se;i=i.array[u]=i.array[u].ensureOwner(this.__ownerID) <del>}return delete i.array[t&se],this.__ownerID?(this._root=n,this):oe._make(this._origin,this._size,this._level,n,this._tail)},clear:function(){return this.__ownerID?(this.length=this._origin=this._size=0,this._level=ne,this._root=this._tail=fe,this):oe.empty()},push:function(){var t=arguments,e=this.length;return this.withMutations(function(r){r._setBounds(0,e+t.length);for(var n=0;t.length>n;n++)r.set(e+n,t[n])})},pop:function(){return this._setBounds(0,-1)},unshift:function(){var t=arguments;return this.withMutations(function(e){e._setBounds(-t.length);for(var r=0;t.length>r;r++)e.set(r,t[r])})},shift:function(){return this._setBounds(1)},merge:function(){for(var t=[],e=0;arguments.length>e;e++)t[e]=arguments[e];return H.prototype.merge.apply(x(this,t),arguments)},mergeWith:function(){for(var t=[],e=1;arguments.length>e;e++)t[e-1]=arguments[e];return H.prototype.mergeWith.apply(x(this,t),arguments)},mergeDeep:function(){for(var t=[],e=0;arguments.length>e;e++)t[e]=arguments[e];return H.prototype.mergeDeep.apply(x(this,t),arguments)},mergeDeepWith:function(){for(var t=[],e=1;arguments.length>e;e++)t[e-1]=arguments[e];return H.prototype.mergeDeepWith.apply(x(this,t),arguments)},setLength:function(t){return this._setBounds(0,t)},_setBounds:function(t,e){var r=this.__ownerID||new N,n=this._origin,i=this._size,s=n+t,u=null==e?i:0>e?i+e:n+e;if(s===n&&u===i)return this;if(s>=u)return this.clear();for(var o=this._level,a=this._root,h=0;0>s+h;)a=new ae(a.array.length?[,a]:[],r),h+=1<<o,o+=ne;h&&(s+=h,n+=h,u+=h,i+=h);for(var l=C(i),c=C(u);c>=1<<o+ne;)a=new ae(a.array.length?[a]:[],r),o+=ne;var f=this._tail,_=l>c?this._nodeFor(u):c>l?new ae([],r):f;if(c>l&&i>s&&f.array.length){a=a.ensureOwner(r);for(var p=a,v=o;v>ne;v-=ne){var g=l>>>v&se;p=p.array[g]=p.array[g]?p.array[g].ensureOwner(r):new ae([],r)}p.array[l>>>ne&se]=f}if(i>u&&(_=_.removeAfter(r,0,u)),s>=c)s-=c,u-=c,o=ne,a=fe,_=_.removeBefore(r,0,s);else if(s>n||l>c){var m,y;h=0;do m=s>>>o&se,y=c-1>>>o&se,m===y&&(m&&(h+=(1<<o)*m),o-=ne,a=a&&a.array[m]);while(a&&m===y);a&&s>n&&(a=a.removeBefore(r,o,s-h)),a&&l>c&&(a=a.removeAfter(r,o,c-h)),h&&(s-=h,u-=h),a=a||fe <add>}return delete i.array[t&se],this.__ownerID?(this._root=n,this):oe._make(this._origin,this._size,this._level,n,this._tail)},clear:function(){return this.__ownerID?(this.length=this._origin=this._size=0,this._level=ne,this._root=this._tail=fe,this):oe.empty()},push:function(){var t=arguments,e=this.length;return this.withMutations(function(r){r._setBounds(0,e+t.length);for(var n=0;t.length>n;n++)r.set(e+n,t[n])})},pop:function(){return this._setBounds(0,-1)},unshift:function(){var t=arguments;return this.withMutations(function(e){e._setBounds(-t.length);for(var r=0;t.length>r;r++)e.set(r,t[r])})},shift:function(){return this._setBounds(1)},merge:function(){for(var t=[],e=0;arguments.length>e;e++)t[e]=arguments[e];return H.prototype.merge.apply(x(this,t),arguments)},mergeWith:function(){for(var t=[],e=1;arguments.length>e;e++)t[e-1]=arguments[e];return H.prototype.mergeWith.apply(x(this,t),arguments)},mergeDeep:function(){for(var t=[],e=0;arguments.length>e;e++)t[e]=arguments[e];return H.prototype.mergeDeep.apply(x(this,t),arguments)},mergeDeepWith:function(){for(var t=[],e=1;arguments.length>e;e++)t[e-1]=arguments[e];return H.prototype.mergeDeepWith.apply(x(this,t),arguments)},setLength:function(t){return this._setBounds(0,t)},_setBounds:function(t,e){var r=this.__ownerID||new N,n=this._origin,i=this._size,s=n+t,u=null==e?i:0>e?i+e:n+e;if(s===n&&u===i)return this;if(s>=u)return this.clear();for(var o=this._level,a=this._root,h=0;0>s+h;)a=new ae(a.array.length?[,a]:[],r),o+=ne,h+=1<<o;h&&(s+=h,n+=h,u+=h,i+=h);for(var l=C(i),c=C(u);c>=1<<o+ne;)a=new ae(a.array.length?[a]:[],r),o+=ne;var f=this._tail,_=l>c?this._nodeFor(u):c>l?new ae([],r):f;if(c>l&&i>s&&f.array.length){a=a.ensureOwner(r);for(var p=a,v=o;v>ne;v-=ne){var g=l>>>v&se;p=p.array[g]=p.array[g]?p.array[g].ensureOwner(r):new ae([],r)}p.array[l>>>ne&se]=f}if(i>u&&(_=_.removeAfter(r,0,u)),s>=c)s-=c,u-=c,o=ne,a=fe,_=_.removeBefore(r,0,s);else if(s>n||l>c){var m,y;h=0;do m=s>>>o&se,y=c-1>>>o&se,m===y&&(m&&(h+=(1<<o)*m),o-=ne,a=a&&a.array[m]);while(a&&m===y);a&&s>n&&(a=a.removeBefore(r,o,s-h)),a&&l>c&&(a=a.removeAfter(r,o,c-h)),h&&(s-=h,u-=h),a=a||fe <ide> }return this.__ownerID?(this.length=u-s,this._origin=s,this._size=u,this._level=o,this._root=a,this._tail=_,this):oe._make(s,u,o,a,_)},__ensureOwner:function(t){return t===this.__ownerID?this:t?oe._make(this._origin,this._size,this._level,this._root,this._tail,t):(this.__ownerID=t,this)},slice:function(t,e,r){var n=z.superCall(this,oe.prototype,"slice",[t,e,r]);if(!r&&n!==this){var i=this,s=i.length;n.toVector=function(){return i._setBounds(0>t?Math.max(0,s+t):s?Math.min(s,t):t,null==e?s:0>e?Math.max(0,s+e):s?Math.min(s,e):e)}}return n},__deepEquals:function(t){var e=this.__iterator__();return t.every(function(t,r){var n=e.next();return r===n[0]&&w(t,n[1])})},__iterator__:function(){return new le(this,this._origin,this._size,this._level,this._root,this._tail)},__iterate:function(t,e,r){var n=this,i=0,s=n.length-1;r^=e;var u,o=function(e,u){return t(e,r?s-u:u,n)===!1?!1:(i=u,!0)},a=C(this._size);return u=e?this._tail.iterate(0,a-this._origin,this._size-this._origin,o,e)&&this._root.iterate(this._level,-this._origin,a-this._origin,o,e):this._root.iterate(this._level,-this._origin,a-this._origin,o,e)&&this._tail.iterate(0,a-this._origin,this._size-this._origin,o,e),(u?s:e?s-i:i)+1},_nodeFor:function(t){if(t>=C(this._size))return this._tail;if(1<<this._level+ne>t){for(var e=this._root,r=this._level;e&&r>0;)e=e.array[t>>>r&se],r-=ne;return e}}},{empty:function(){return ce||(ce=oe._make(0,0,ne,fe,fe))},from:function(t){if(t&&t.constructor===oe)return t;if(!t||0===t.length)return oe.empty();var e=Array.isArray(t);return t.length>0&&ie>t.length?oe._make(0,t.length,ne,fe,new ae(e?t.slice():B(t).toArray())):(e||(t=B(t),t instanceof J||(t=t.values())),oe.empty().merge(t))},_make:function(t,e,r,n,i,s){var u=Object.create(oe.prototype);return u.length=e-t,u._origin=t,u._size=e,u._level=r,u._root=n,u._tail=i,u.__ownerID=s,u}},J),ue.prototype.update=H.prototype.update,ue.prototype.updateIn=H.prototype.updateIn,ue.prototype.withMutations=H.prototype.withMutations,ue.prototype.asMutable=H.prototype.asMutable,ue.prototype.asImmutable=H.prototype.asImmutable; <ide> var N=function(){};z.createClass(N,{},{});var ae=function(t,e){this.array=t,this.ownerID=e},he=ae;z.createClass(ae,{ensureOwner:function(t){return t&&t===this.ownerID?this:new he(this.array.slice(),t)},removeBefore:function(t,e,r){if(r===1<<e||0===this.array.length)return this;var n=r>>>e&se;if(n>=this.array.length)return new he([],t);var i,s=0===n;if(e>0){var u=this.array[n];if(i=u&&u.removeBefore(t,e-ne,r),i===u&&s)return this}if(s&&!i)return this;var o=this.ensureOwner();if(!s)for(var a=0;n>a;a++)delete o.array[a];return i&&(o.array[n]=i),o},removeAfter:function(t,e,r){if(r===1<<e||0===this.array.length)return this;var n=r-1>>>e&se;if(n>=this.array.length)return this;var i,s=n===this.array.length-1;if(e>0){var u=this.array[n];if(i=u&&u.removeAfter(t,e-ne,r),i===u&&s)return this}if(s&&!i)return this;var o=this.ensureOwner();return s||(o.array.length=n+1),i&&(o.array[n]=i),o},iterate:function(t,e,r,n,i){if(0===t){if(i){for(var s=this.array.length-1;s>=0;s--)if(this.array.hasOwnProperty(s)){var u=s+e;if(u>=0&&r>u&&n(this.array[s],u)===!1)return!1}return!0}return this.array.every(function(t,i){var s=i+e;return 0>s||s>=r||n(t,s)!==!1})}var o=1<<t,a=t-ne;if(i){for(var h=this.array.length-1;h>=0;h--){var l=e+h*o;if(r>l&&l+o>0&&this.array.hasOwnProperty(h)&&!this.array[h].iterate(a,l,r,n,i))return!1}return!0}return this.array.every(function(t,s){var u=e+s*o;return u>=r||0>=u+o||t.iterate(a,u,r,n,i)})}},{});var le=function(t,e,r,n,i,s){var u=C(r);this._stack={node:i.array,level:n,offset:-e,max:u-e,__prev:{node:s.array,level:0,offset:u-e,max:r-e}}};z.createClass(le,{next:function(){var t=this._stack;t:for(;t;){if(0===t.level)for(t.rawIndex||(t.rawIndex=0);t.node.length>t.rawIndex;){var e=t.rawIndex+t.offset;if(e>=0&&t.max>e&&t.node.hasOwnProperty(t.rawIndex)){var r=t.node[t.rawIndex];return t.rawIndex++,[e,r]}t.rawIndex++}else{var n=1<<t.level;for(t.levelIndex||(t.levelIndex=0);t.node.length>t.levelIndex;){var i=t.offset+t.levelIndex*n;if(i+n>0&&t.max>i&&t.node.hasOwnProperty(t.levelIndex)){var s=t.node[t.levelIndex].array; <ide> t.levelIndex++,t=this._stack={node:s,level:t.level-ne,offset:i,max:t.max,__prev:t};continue t}t.levelIndex++}}t=this._stack=this._stack.__prev}if(global.StopIteration)throw global.StopIteration}},{});var ce,ne=5,ie=1<<ne,se=ie-1,K={},fe=new ae([]),_e=function(){for(var t=[],e=0;arguments.length>e;e++)t[e]=arguments[e];return pe.from(t)},pe=_e;z.createClass(_e,{toString:function(){return this.__toString("Set {","}")},has:function(t){return this._map?this._map.has(t):!1},get:function(t,e){return this.has(t)?t:e},add:function(t){if(null==t)return this;var e=this._map;return e||(e=H.empty().__ensureOwner(this.__ownerID)),e=e.set(t,null),this.__ownerID?(this.length=e.length,this._map=e,this):e===this._map?this:pe._make(e)},"delete":function(t){if(null==t||null==this._map)return this;var e=this._map.delete(t);return 0===e.length?this.clear():this.__ownerID?(this.length=e.length,this._map=e,this):e===this._map?this:pe._make(e)},clear:function(){return this.__ownerID?(this.length=0,this._map=null,this):pe.empty()},union:function(){var t=arguments;return 0===t.length?this:this.withMutations(function(e){for(var r=0;t.length>r;r++){var n=t[r];n=n.forEach?n:B(n),n.forEach(function(t){return e.add(t)})}})},intersect:function(){for(var t=[],e=0;arguments.length>e;e++)t[e]=arguments[e];if(0===t.length)return this;t=t.map(function(t){return B(t)});var r=this;return this.withMutations(function(e){r.forEach(function(r){t.every(function(t){return t.contains(r)})||e.delete(r)})})},subtract:function(){for(var t=[],e=0;arguments.length>e;e++)t[e]=arguments[e];if(0===t.length)return this;t=t.map(function(t){return B(t)});var r=this;return this.withMutations(function(e){r.forEach(function(r){t.some(function(t){return t.contains(r)})&&e.delete(r)})})},isSubset:function(t){return t=B(t),this.every(function(e){return t.contains(e)})},isSuperset:function(t){var e=this;return t=B(t),t.every(function(t){return e.contains(t)})},__ensureOwner:function(t){if(t===this.__ownerID)return this;var e=this._map&&this._map.__ensureOwner(t);return t?pe._make(e,t):(this.__ownerID=t,this._map=e,this) <ide><path>src/Vector.js <ide> class Vector extends IndexedSequence { <ide> while (newOrigin + offsetShift < 0) { <ide> // TODO: why only ever shifting over by 1? <ide> newRoot = new VNode(newRoot.array.length ? [,newRoot] : [], owner); <del> offsetShift += 1 << newLevel; <ide> newLevel += SHIFT; <add> offsetShift += 1 << newLevel; <ide> } <ide> if (offsetShift) { <ide> newOrigin += offsetShift;
3
Javascript
Javascript
use new build that fixes md links and checks them
5877f6b0408d3a3b186b13c985e0e52494a022cc
<ide><path>Gruntfile.js <ide> module.exports = function(grunt) { <ide> const buildStuff = require('./build/js/build'); <ide> const finish = this.async(); <ide> buildStuff({ <add> outDir: 'out', <ide> baseUrl: 'http://threejsfundamentals.org', <ide> rootFolder: 'threejs', <ide> lessonGrep: 'threejs*.md', <ide><path>build/js/build.js <del>/* global module require */ <add>/* global module require process */ <add>/* eslint no-undef: "error" */ <add>/* eslint no-console: "off" */ <add> <ide> 'use strict'; <ide> <ide> module.exports = function(settings) { // wrapper in case we're in module_context mode <ide> const url = require('url'); <ide> <ide> //process.title = 'build'; <ide> <add>let numErrors = 0; <add>function error(...args) { <add> ++numErrors; <add> console.error(...args); <add>} <add> <ide> const executeP = Promise.denodeify(utils.execute); <ide> <ide> marked.setOptions({ <ide> function slashify(s) { <ide> return s.replace(/\\/g, '/'); <ide> } <ide> <add>function articleFilter(f) { <add> return !process.env['ARTICLE_FILTER'] || f.indexOf(process.env['ARTICLE_FILTER']) >= 0; <add>} <add> <ide> const Builder = function(outBaseDir, options) { <ide> <ide> const g_articlesByLang = {}; <ide> const Builder = function(outBaseDir, options) { <ide> const g_origPath = options.origPath; <ide> <ide> // This are the english articles. <del> const g_origArticles = glob.sync(path.join(g_origPath, '*.md')).map(a => path.basename(a)).filter(a => a !== 'index.md'); <add> const g_origArticles = glob. <add> sync(path.join(g_origPath, '*.md')) <add> .map(a => path.basename(a)) <add> .filter(a => a !== 'index.md') <add> .filter(articleFilter); <ide> <ide> const extractHeader = (function() { <ide> const headerRE = /([A-Z0-9_-]+): (.*?)$/i; <ide> const Builder = function(outBaseDir, options) { <ide> return content; <ide> } <ide> <add> function isSameDomain(url, pageUrl) { <add> const fdq1 = new URL(pageUrl); <add> const fdq2 = new URL(url, pageUrl); <add> return fdq1.origin === fdq2.origin; <add> } <add> <add> function getUrlPath(url) { <add> // yes, this is a hack <add> const q = url.indexOf('?'); <add> return q >= 0 ? url.substring(0, q) : url; <add> } <add> <add> // Try top fix relative links. This *should* only <add> // happen in translations <add> const iframeLinkRE = /(<iframe[\s\S]*?\s+src=")(.*?)(")/g; <add> const imgLinkRE = /(<img[\s\S]*?\s+src=")(.*?)(")/g; <add> const aLinkRE = /(<a[\s\S]*?\s+href=")(.*?)(")/g; <add> const mdLinkRE = /(\[[\s\S]*?\]\()(.*?)(\))/g; <add> const handlebarLinkRE = /({{{.*?\s+url=")(.*?)(")/g; <add> const linkREs = [ <add> iframeLinkRE, <add> imgLinkRE, <add> aLinkRE, <add> mdLinkRE, <add> handlebarLinkRE, <add> ]; <add> function hackRelLinks(content, pageUrl) { <add> // console.log('---> pageUrl:', pageUrl); <add> function fixRelLink(m, prefix, url, suffix) { <add> if (isSameDomain(url, pageUrl)) { <add> // a link that starts with "../" should be "../../" if it's in a translation <add> // a link that starts with "resources" should be "../resources" if it's in a translation <add> if (url.startsWith('../') || <add> url.startsWith('resources')) { <add> // console.log(' url:', url); <add> return `${prefix}../${url}${suffix}`; <add> } <add> } <add> return m; <add> } <add> <add> return content <add> .replace(imgLinkRE, fixRelLink) <add> .replace(aLinkRE, fixRelLink) <add> .replace(iframeLinkRE, fixRelLink); <add> } <add> <add> /** <add> * Get all the local urls based on a regex that has <prefix><url><suffix> <add> */ <add> function getUrls(regex, str) { <add> const links = new Set(); <add> let m; <add> do { <add> m = regex.exec(str); <add> if (m && m[2][0] !== '#' && isSameDomain(m[2], 'http://example.com/a/b/c/d')) { <add> links.add(getUrlPath(m[2])); <add> } <add> } while (m); <add> return links; <add> } <add> <add> /** <add> * Get all the local links in content <add> */ <add> function getLinks(content) { <add> return new Set(linkREs.map(re => [...getUrls(re, content)]).flat()); <add> } <add> <add> function fixUrls(regex, content, origLinks) { <add> return content.replace(regex, (m, prefix, url, suffix) => { <add> const q = url.indexOf('?'); <add> const urlPath = q >= 0 ? url.substring(0, q) : url; <add> const urlQuery = q >= 0 ? url.substring(q) : ''; <add> if (!origLinks.has(urlPath) && <add> isSameDomain(urlPath, 'https://foo.com/a/b/c/d.html') && <add> !(/\/..\/^/.test(urlPath)) && // hacky test for link to main page. Example /webgl/lessons/ja/ <add> urlPath[0] !== '#') { // test for same page anchor -- bad test :( <add> for (const origLink of origLinks) { <add> if (urlPath.endsWith(origLink)) { <add> const newUrl = `${origLink}${urlQuery}`; <add> console.log(' fixing:', url, 'to', newUrl); <add> return `${prefix}${newUrl}${suffix}`; <add> } <add> } <add> error('could not fix:', url); <add> } <add> return m; <add> }); <add> } <add> <ide> const applyTemplateToContent = function(templatePath, contentFileName, outFileName, opt_extra, data) { <ide> // Call prep's Content which parses the HTML. This helps us find missing tags <ide> // should probably call something else. <ide> //Convert(md_content) <add> const relativeOutName = slashify(outFileName).substring(g_outBaseDir.length); <add> const pageUrl = `${settings.baseUrl}${relativeOutName}`; <ide> const metaData = data.headers; <ide> const content = data.content; <ide> //console.log(JSON.stringify(metaData, undefined, ' ')); <ide> const info = extractHandlebars(content); <ide> let html = marked(info.content); <add> // HACK! :-( <add> if (opt_extra && opt_extra.home && opt_extra.home.length > 1) { <add> html = hackRelLinks(html, pageUrl); <add> } <ide> html = insertHandlebars(info, html); <ide> html = replaceParams(html, [opt_extra, g_langInfo]); <del> const relativeOutName = slashify(outFileName).substring(g_outBaseDir.length); <ide> const pathRE = new RegExp(`^\\/${settings.rootFolder}\\/lessons\\/$`); <ide> const langs = Object.keys(g_langDB).map((name) => { <ide> const lang = g_langDB[name]; <ide> const Builder = function(outBaseDir, options) { <ide> metaData['toc'] = opt_extra.toc; <ide> metaData['templateOptions'] = opt_extra.templateOptions; <ide> metaData['langInfo'] = g_langInfo; <del> metaData['url'] = `${settings.baseUrl}${relativeOutName}`; <add> metaData['url'] = pageUrl; <ide> metaData['relUrl'] = relativeOutName; <ide> metaData['screenshot'] = `${settings.baseUrl}/${settings.rootFolder}/lessons/resources/${settings.siteThumbnail}`; <ide> const basename = path.basename(contentFileName, '.md'); <ide> const Builder = function(outBaseDir, options) { <ide> }; <ide> <ide> const applyTemplateToFiles = function(templatePath, filesSpec, extra) { <del> const files = glob.sync(filesSpec).sort(); <add> const files = glob <add> .sync(filesSpec) <add> .sort() <add> .filter(articleFilter); <ide> files.forEach(function(fileName) { <ide> const ext = path.extname(fileName); <ide> const baseName = fileName.substr(0, fileName.length - ext.length); <ide> const Builder = function(outBaseDir, options) { <ide> }; <ide> <ide> const getLanguageSelection = function(lang) { <del> const lessons = lang.lessons || (`${settings.rootFolder}/lessons/${lang.lang}`); <add> const lessons = lang.lessons; <ide> const langInfo = hanson.parse(fs.readFileSync(path.join(lessons, 'langinfo.hanson'), {encoding: 'utf8'})); <ide> langInfo.langCode = langInfo.langCode || lang.lang; <del> langInfo.home = lang.home || ('/' + lessons + '/'); <add> langInfo.home = lang.home; <ide> g_langDB[lang.lang] = { <ide> lang: lang.lang, <ide> language: langInfo.language, <ide> const Builder = function(outBaseDir, options) { <ide> <ide> this.process = function(options) { <ide> console.log('Processing Lang: ' + options.lang); // eslint-disable-line <del> options.lessons = options.lessons || (`${settings.rootFolder}/lessons/${options.lang}`); <del> options.toc = options.toc || (`${settings.rootFolder}/lessons/${options.lang}/toc.html`); <del> options.template = options.template || 'build/templates/lesson.template'; <del> options.examplePath = options.examplePath === undefined ? `/${settings.rootFolder}/lessons/` : options.examplePath; <del> <ide> g_articles = []; <ide> g_langInfo = g_langDB[options.lang].langInfo; <ide> <ide> applyTemplateToFiles(options.template, path.join(options.lessons, settings.lessonGrep), options); <ide> <del> // generate place holders for non-translated files <ide> const articlesFilenames = g_articles.map(a => path.basename(a.src_file_name)); <add> <add> // should do this first was easier to add here <add> if (options.lang !== 'en') { <add> const existing = g_origArticles.filter(name => articlesFilenames.indexOf(name) >= 0); <add> existing.forEach((name) => { <add> const origMdFilename = path.join(g_origPath, name); <add> const transMdFilename = path.join(g_origPath, options.lang, name); <add> const origLinks = getLinks(loadMD(origMdFilename).content); <add> const transLinks = getLinks(loadMD(transMdFilename).content); <add> <add> if (process.env['ARTICLE_VERBOSE']) { <add> console.log('---[', transMdFilename, ']---'); <add> console.log('origLinks: ---\n ', [...origLinks].join('\n ')); <add> console.log('transLinks: ---\n ', [...transLinks].join('\n ')); <add> } <add> <add> let show = true; <add> transLinks.forEach((link) => { <add> if (!origLinks.has(link)) { <add> if (show) { <add> show = false; <add> error('---[', transMdFilename, ']---'); <add> } <add> error(' link:[', link, '] not found in English file'); <add> } <add> }); <add> <add> if (!show && process.env['ARTICLE_FIX']) { <add> // there was an error, try to auto-fix <add> let fixedMd = fs.readFileSync(transMdFilename, {encoding: 'utf8'}); <add> linkREs.forEach((re) => { <add> fixedMd = fixUrls(re, fixedMd, origLinks); <add> }); <add> fs.writeFileSync(transMdFilename, fixedMd); <add> } <add> }); <add> } <add> <add> // generate place holders for non-translated files <ide> const missing = g_origArticles.filter(name => articlesFilenames.indexOf(name) < 0); <ide> missing.forEach(name => { <ide> const ext = path.extname(name); <ide> const Builder = function(outBaseDir, options) { <ide> }); <ide> return Promise.resolve(); <ide> }, function(err) { <del> console.error('ERROR!:'); // eslint-disable-line <del> console.error(err); // eslint-disable-line <add> error('ERROR!:'); <add> error(err); <ide> if (err.stack) { <del> console.error(err.stack); // eslint-disable-line <add> error(err.stack); // eslint-disable-line <ide> } <ide> throw new Error(err.toString()); <ide> }); <ide> const Builder = function(outBaseDir, options) { <ide> <ide> }; <ide> <del>const b = new Builder('out', { <add>const b = new Builder(settings.outDir, { <ide> origPath: `${settings.rootFolder}/lessons`, // english articles <ide> }); <ide> <ide> const isLangFolder = function(dirname) { <ide> <ide> <ide> const pathToLang = function(filename) { <add> const lang = path.basename(filename); <add> const lessonBase = `${settings.rootFolder}/lessons`; <add> const lessons = `${lessonBase}/${lang}`; <ide> return { <del> lang: path.basename(filename), <add> lang, <add> toc: `${settings.rootFolder}/lessons/${lang}/toc.html`, <add> lessons: `${lessonBase}/${lang}`, <add> template: 'build/templates/lesson.template', <add> examplePath: `/${lessonBase}/`, <add> home: `/${lessons}/`, <ide> }; <ide> }; <ide> <ide> langs = langs.concat(readdirs(`${settings.rootFolder}/lessons`) <ide> <ide> b.preProcess(langs); <ide> <add>{ <add> const filename = path.join(settings.outDir, 'link-check.html'); <add> const html = ` <add> <html> <add> <body> <add> ${langs.map(lang => `<a href="${lang.home}">${lang.lang}</a>`).join('\n')} <add> </body> <add> </html> <add> `; <add> writeFileIfChanged(filename, html); <add>} <add> <ide> const tasks = langs.map(function(lang) { <ide> return function() { <ide> return b.process(lang); <ide> return tasks.reduce(function(cur, next) { <ide> }, Promise.resolve()).then(function() { <ide> b.writeGlobalFiles(); <ide> cache.clear(); <del> return Promise.resolve(); <add> return numErrors ? Promise.reject(new Error(`${numErrors} errors`)) : Promise.resolve(); <ide> }); <ide> <ide> };
2
Text
Text
use commas consistently (mutating/array functions)
ec414f01dca4f010527b845b6ecf33ca88256f98
<ide><path>README.md <ide> of [ES2015][] [Array][], [Map][], and [Set][]. <ide> [Set]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set <ide> <ide> The difference for the immutable collections is that methods which would mutate <del>the collection, like `push`, `set`, `unshift` or `splice` instead return a new <del>immutable collection. Methods which return new arrays like `slice` or `concat` <add>the collection, like `push`, `set`, `unshift` or `splice`, instead return a new <add>immutable collection. Methods which return new arrays, like `slice` or `concat`, <ide> instead return new immutable collections. <ide> <ide> <!-- runkit:activate -->
1
Text
Text
fix tutorial instruction to also add pyyaml
dc6b3bf42e53c6bfdb597a67de931913c8bd0255
<ide><path>docs/tutorial/7-schemas-and-client-libraries.md <ide> automatically generated schemas. Since we're using viewsets and routers, <ide> we can simply use the automatic schema generation. <ide> <ide> You'll need to install the `coreapi` python package in order to include an <del>API schema. <add>API schema, and `pyyaml` to render the schema into the commonly used <add>YAML-based OpenAPI format. <ide> <del> $ pip install coreapi <add> $ pip install coreapi pyyaml <ide> <ide> We can now include a schema for our API, by including an autogenerated schema <ide> view in our URL configuration.
1
Ruby
Ruby
fix force_homebrew_on_linux behaviour
a867e78f62c807b65ff4f80587d1a512252febf0
<ide><path>Library/Homebrew/extend/os/mac/software_spec.rb <ide> # typed: false <ide> # frozen_string_literal: true <ide> <add># The Library/Homebrew/extend/os/software_spec.rb conditional logic will need to be more nuanced <add># if this file ever includes more than `uses_from_macos`. <ide> class SoftwareSpec <ide> undef uses_from_macos <ide> <ide><path>Library/Homebrew/extend/os/software_spec.rb <ide> # typed: strict <ide> # frozen_string_literal: true <ide> <del>if OS.linux? <del> require "extend/os/linux/software_spec" <del>elsif OS.mac? <add># This logic will need to be more nuanced if this file includes more than `uses_from_macos`. <add>if OS.mac? || Homebrew::EnvConfig.force_homebrew_on_linux? <ide> require "extend/os/mac/software_spec" <add>elsif OS.linux? <add> require "extend/os/linux/software_spec" <ide> end
2
Java
Java
call purge periodically on jdk 6 to avoid
b5aaf82ea8c7addd2cd197f1c61ddec9ee5ee962
<ide><path>src/main/java/rx/internal/schedulers/NewThreadWorker.java <ide> package rx.internal.schedulers; <ide> <ide> import java.lang.reflect.Method; <add>import java.util.Iterator; <ide> import java.util.concurrent.*; <add>import java.util.concurrent.atomic.AtomicReference; <ide> <ide> import rx.*; <add>import rx.exceptions.Exceptions; <ide> import rx.functions.Action0; <add>import rx.internal.util.RxThreadFactory; <ide> import rx.plugins.*; <ide> import rx.subscriptions.Subscriptions; <ide> <ide> public class NewThreadWorker extends Scheduler.Worker implements Subscription { <ide> private final ScheduledExecutorService executor; <ide> private final RxJavaSchedulersHook schedulersHook; <ide> volatile boolean isUnsubscribed; <del> <add> /** The purge frequency in milliseconds. */ <add> private static final String FREQUENCY_KEY = "io.reactivex.rxjava.scheduler.jdk6.purge-frequency-millis"; <add> /** Force the use of purge (true/false). */ <add> private static final String PURGE_FORCE_KEY = "io.reactivex.rxjava.scheduler.jdk6.purge-force"; <add> private static final String PURGE_THREAD_PREFIX = "RxSchedulerPurge-"; <add> /** Forces the use of purge even if setRemoveOnCancelPolicy is available. */ <add> private static final boolean PURGE_FORCE; <add> /** The purge frequency in milliseconds. */ <add> public static final int PURGE_FREQUENCY; <add> private static final ConcurrentHashMap<ScheduledThreadPoolExecutor, ScheduledThreadPoolExecutor> EXECUTORS; <add> private static final AtomicReference<ScheduledExecutorService> PURGE; <add> static { <add> EXECUTORS = new ConcurrentHashMap<ScheduledThreadPoolExecutor, ScheduledThreadPoolExecutor>(); <add> PURGE = new AtomicReference<ScheduledExecutorService>(); <add> PURGE_FORCE = Boolean.getBoolean(PURGE_FORCE_KEY); <add> PURGE_FREQUENCY = Integer.getInteger(FREQUENCY_KEY, 1000); <add> } <add> /** <add> * Registers the given executor service and starts the purge thread if not already started. <add> * <p>{@code public} visibility reason: called from other package(s) within RxJava <add> * @param service a scheduled thread pool executor instance <add> */ <add> public static void registerExecutor(ScheduledThreadPoolExecutor service) { <add> do { <add> ScheduledExecutorService exec = PURGE.get(); <add> if (exec != null) { <add> break; <add> } <add> exec = Executors.newScheduledThreadPool(1, new RxThreadFactory(PURGE_THREAD_PREFIX)); <add> if (PURGE.compareAndSet(null, exec)) { <add> exec.scheduleAtFixedRate(new Runnable() { <add> @Override <add> public void run() { <add> purgeExecutors(); <add> } <add> }, PURGE_FREQUENCY, PURGE_FREQUENCY, TimeUnit.MILLISECONDS); <add> <add> break; <add> } <add> } while (true); <add> <add> EXECUTORS.putIfAbsent(service, service); <add> } <add> /** <add> * Deregisters the executor service. <add> * <p>{@code public} visibility reason: called from other package(s) within RxJava <add> * @param service a scheduled thread pool executor instance <add> */ <add> public static void deregisterExecutor(ScheduledExecutorService service) { <add> EXECUTORS.remove(service); <add> } <add> /** Purges each registered executor and eagerly evicts shutdown executors. */ <add> static void purgeExecutors() { <add> try { <add> Iterator<ScheduledThreadPoolExecutor> it = EXECUTORS.keySet().iterator(); <add> while (it.hasNext()) { <add> ScheduledThreadPoolExecutor exec = it.next(); <add> if (!exec.isShutdown()) { <add> exec.purge(); <add> } else { <add> it.remove(); <add> } <add> } <add> } catch (Throwable t) { <add> Exceptions.throwIfFatal(t); <add> RxJavaPlugins.getInstance().getErrorHandler().handleError(t); <add> } <add> } <add> <add> /** <add> * Tries to enable the Java 7+ setRemoveOnCancelPolicy. <add> * <p>{@code public} visibility reason: called from other package(s) within RxJava. <add> * If the method returns false, the {@link #registerExecutor(ScheduledThreadPoolExecutor)} may <add> * be called to enable the backup option of purging the executors. <add> * @param exec the executor to call setRemoveOnCaneclPolicy if available. <add> * @return true if the policy was successfully enabled <add> */ <add> public static boolean tryEnableCancelPolicy(ScheduledExecutorService exec) { <add> if (!PURGE_FORCE) { <add> for (Method m : exec.getClass().getMethods()) { <add> if (m.getName().equals("setRemoveOnCancelPolicy") <add> && m.getParameterTypes().length == 1 <add> && m.getParameterTypes()[0] == Boolean.TYPE) { <add> try { <add> m.invoke(exec, true); <add> return true; <add> } catch (Exception ex) { <add> RxJavaPlugins.getInstance().getErrorHandler().handleError(ex); <add> } <add> } <add> } <add> } <add> return false; <add> } <add> <ide> /* package */ <ide> public NewThreadWorker(ThreadFactory threadFactory) { <del> executor = Executors.newScheduledThreadPool(1, threadFactory); <add> ScheduledExecutorService exec = Executors.newScheduledThreadPool(1, threadFactory); <ide> // Java 7+: cancelled future tasks can be removed from the executor thus avoiding memory leak <del> for (Method m : executor.getClass().getMethods()) { <del> if (m.getName().equals("setRemoveOnCancelPolicy") <del> && m.getParameterTypes().length == 1 <del> && m.getParameterTypes()[0] == Boolean.TYPE) { <del> try { <del> m.invoke(executor, true); <del> } catch (Exception ex) { <del> RxJavaPlugins.getInstance().getErrorHandler().handleError(ex); <del> } <del> break; <del> } <add> boolean cancelSupported = tryEnableCancelPolicy(exec); <add> if (!cancelSupported && exec instanceof ScheduledThreadPoolExecutor) { <add> registerExecutor((ScheduledThreadPoolExecutor)exec); <ide> } <ide> schedulersHook = RxJavaPlugins.getInstance().getSchedulersHook(); <add> executor = exec; <ide> } <ide> <ide> @Override <ide> public ScheduledAction scheduleActual(final Action0 action, long delayTime, Time <ide> public void unsubscribe() { <ide> isUnsubscribed = true; <ide> executor.shutdownNow(); <add> deregisterExecutor(executor); <ide> } <ide> <ide> @Override <ide><path>src/main/java/rx/schedulers/CachedThreadScheduler.java <ide> public Worker createWorker() { <ide> private static final class EventLoopWorker extends Scheduler.Worker { <ide> private final CompositeSubscription innerSubscription = new CompositeSubscription(); <ide> private final ThreadWorker threadWorker; <add> @SuppressWarnings("unused") <ide> volatile int once; <ide> static final AtomicIntegerFieldUpdater<EventLoopWorker> ONCE_UPDATER <ide> = AtomicIntegerFieldUpdater.newUpdater(EventLoopWorker.class, "once"); <ide><path>src/main/java/rx/schedulers/GenericScheduledExecutorService.java <ide> package rx.schedulers; <ide> <ide> import rx.Scheduler; <add>import rx.internal.schedulers.NewThreadWorker; <ide> import rx.internal.util.RxThreadFactory; <ide> <del>import java.util.concurrent.Executor; <del>import java.util.concurrent.ExecutorService; <del>import java.util.concurrent.Executors; <del>import java.util.concurrent.ScheduledExecutorService; <add>import java.util.concurrent.*; <ide> <ide> /** <ide> * A default {@link ScheduledExecutorService} that can be used for scheduling actions when a {@link Scheduler} implementation doesn't have that ability. <ide> private GenericScheduledExecutorService() { <ide> if (count > 8) { <ide> count = 8; <ide> } <del> executor = Executors.newScheduledThreadPool(count, THREAD_FACTORY); <add> ScheduledExecutorService exec = Executors.newScheduledThreadPool(count, THREAD_FACTORY); <add> if (!NewThreadWorker.tryEnableCancelPolicy(exec)) { <add> if (exec instanceof ScheduledThreadPoolExecutor) { <add> NewThreadWorker.registerExecutor((ScheduledThreadPoolExecutor)exec); <add> } <add> } <add> executor = exec; <ide> } <ide> <ide> /** <ide><path>src/test/java/rx/schedulers/CachedThreadSchedulerTest.java <ide> import rx.Observable; <ide> import rx.Scheduler; <ide> import rx.functions.*; <add>import rx.internal.schedulers.NewThreadWorker; <ide> import static org.junit.Assert.assertTrue; <ide> <ide> public class CachedThreadSchedulerTest extends AbstractSchedulerConcurrencyTests { <ide> public final void testHandledErrorIsNotDeliveredToThreadHandler() throws Interru <ide> <ide> @Test(timeout = 30000) <ide> public void testCancelledTaskRetention() throws InterruptedException { <del> try { <del> ScheduledThreadPoolExecutor.class.getMethod("setRemoveOnCancelPolicy", Boolean.TYPE); <del> <del> System.out.println("Wait before GC"); <del> Thread.sleep(1000); <del> <del> System.out.println("GC"); <del> System.gc(); <del> <del> Thread.sleep(1000); <del> <del> <del> MemoryMXBean memoryMXBean = ManagementFactory.getMemoryMXBean(); <del> MemoryUsage memHeap = memoryMXBean.getHeapMemoryUsage(); <del> long initial = memHeap.getUsed(); <del> <del> System.out.printf("Starting: %.3f MB%n", initial / 1024.0 / 1024.0); <del> <del> Scheduler.Worker w = Schedulers.io().createWorker(); <del> for (int i = 0; i < 750000; i++) { <del> if (i % 50000 == 0) { <del> System.out.println(" -> still scheduling: " + i); <del> } <del> w.schedule(Actions.empty(), 1, TimeUnit.DAYS); <add> System.out.println("Wait before GC"); <add> Thread.sleep(1000); <add> <add> System.out.println("GC"); <add> System.gc(); <add> <add> Thread.sleep(1000); <add> <add> <add> MemoryMXBean memoryMXBean = ManagementFactory.getMemoryMXBean(); <add> MemoryUsage memHeap = memoryMXBean.getHeapMemoryUsage(); <add> long initial = memHeap.getUsed(); <add> <add> System.out.printf("Starting: %.3f MB%n", initial / 1024.0 / 1024.0); <add> <add> Scheduler.Worker w = Schedulers.io().createWorker(); <add> for (int i = 0; i < 750000; i++) { <add> if (i % 50000 == 0) { <add> System.out.println(" -> still scheduling: " + i); <ide> } <del> <del> memHeap = memoryMXBean.getHeapMemoryUsage(); <del> long after = memHeap.getUsed(); <del> System.out.printf("Peak: %.3f MB%n", after / 1024.0 / 1024.0); <del> <del> w.unsubscribe(); <del> <del> System.out.println("Wait before second GC"); <del> Thread.sleep(1000); <del> <del> System.out.println("Second GC"); <del> System.gc(); <del> <del> Thread.sleep(1000); <del> <del> memHeap = memoryMXBean.getHeapMemoryUsage(); <del> long finish = memHeap.getUsed(); <del> System.out.printf("After: %.3f MB%n", finish / 1024.0 / 1024.0); <del> <del> if (finish > initial * 5) { <del> Assert.fail(String.format("Tasks retained: %.3f -> %.3f -> %.3f", initial / 1024 / 1024.0, after / 1024 / 1024.0, finish / 1024 / 1024d)); <del> } <del> } catch (NoSuchMethodException ex) { <del> // not supported, no reason to test for it <add> w.schedule(Actions.empty(), 1, TimeUnit.DAYS); <add> } <add> <add> memHeap = memoryMXBean.getHeapMemoryUsage(); <add> long after = memHeap.getUsed(); <add> System.out.printf("Peak: %.3f MB%n", after / 1024.0 / 1024.0); <add> <add> w.unsubscribe(); <add> <add> System.out.println("Wait before second GC"); <add> Thread.sleep(NewThreadWorker.PURGE_FREQUENCY + 2000); <add> <add> System.out.println("Second GC"); <add> System.gc(); <add> <add> Thread.sleep(1000); <add> <add> memHeap = memoryMXBean.getHeapMemoryUsage(); <add> long finish = memHeap.getUsed(); <add> System.out.printf("After: %.3f MB%n", finish / 1024.0 / 1024.0); <add> <add> if (finish > initial * 5) { <add> Assert.fail(String.format("Tasks retained: %.3f -> %.3f -> %.3f", initial / 1024 / 1024.0, after / 1024 / 1024.0, finish / 1024 / 1024d)); <ide> } <ide> } <ide>
4
Text
Text
fix some typos in docs
05a82e957c0fb75e4a58057b133dbcddd816112e
<ide><path>docs/sources/layers/core.md <ide> ## Base class <ide> <del>Note: Where ever we refer to a "Tensor" bear in mind that its type depends on the backend you are using. <add>Note: Where ever we refer to a *Tensor*, bear in mind that its type depends on the backend you are using. <ide> <ide> ```python <ide> keras.layers.core.Layer() <ide> Apply layer transformation an input Tensor `X`. <ide> <ide> - __Arguments__: <ide> - __X__: Tensor. Input Tensor. <del> - __train__: bool. Specifies whether output is computed in training mode or in testing mode, which can change the logic, for instance in there are any `Dropout` layers in the network. <add> - __train__: bool. Specifies whether output is computed in training mode or in testing mode, which may. change the logic. For instance Dropout and regularization is not applied is testing mode. <ide> <ide> <ide> ```python
1
Go
Go
add deviceset interface
e6216793d91a9b003814b535b0373902326753dd
<ide><path>deviceset.go <add>package docker <add> <add>type DeviceSet interface { <add> AddDevice(hash, baseHash string) error <add> SetInitialized(hash string) error <add> DeactivateDevice(hash string) error <add> RemoveDevice(hash string) error <add> MountDevice(hash, path string) error <add> HasDevice(hash string) bool <add> HasInitializedDevice(hash string) bool <add>}
1
Python
Python
get app from first task
8c9cb819b1e112fe61eb76a9338069f244a7cb8a
<ide><path>celery/result.py <ide> class ResultSet(ResultBase): <ide> :param results: List of result instances. <ide> <ide> """ <del> app = None <add> _app = None <ide> <ide> #: List of results in in the set. <ide> results = None <ide> <ide> def __init__(self, results, app=None, **kwargs): <del> self.app = app_or_default(app or self.app) <add> self.app = app <ide> self.results = results <ide> <ide> def add(self, result): <ide> def supports_native_join(self): <ide> except IndexError: <ide> pass <ide> <add> @property <add> def app(self): <add> if self._app is None: <add> self._app = (self.results[0].app if self.results else <add> current_app._get_current_object()) <add> return self._app <add> <add> @app.setter <add> def app(self, app): # noqa <add> self._app = app <add> <ide> @property <ide> def backend(self): <ide> return self.app.backend if self.app else self.results[0].backend
1
Ruby
Ruby
fix directory leak in test_cleanup
9a6d2a31d9cf7e608d575b1507cd6d287b770988
<ide><path>Library/Homebrew/test/test_cmd_cleanup.rb <ide> def test_cleanup <ide> refute_predicate f1, :installed? <ide> refute_predicate f2, :installed? <ide> assert_predicate f3, :installed? <add> ensure <add> [f1, f2, f3].each(&:clear_cache) <add> f3.rack.rmtree <ide> end <ide> end
1
Java
Java
make objectutils.addobjecttoarray() generic
b04987ccc37985eae59a2b5cc19a1c6ea5d6c844
<ide><path>org.springframework.beans/src/main/java/org/springframework/beans/factory/support/BeanDefinitionBuilder.java <ide> public BeanDefinitionBuilder addDependsOn(String beanName) { <ide> this.beanDefinition.setDependsOn(new String[] {beanName}); <ide> } <ide> else { <del> String[] added = (String[]) ObjectUtils.addObjectToArray(this.beanDefinition.getDependsOn(), beanName); <add> String[] added = ObjectUtils.addObjectToArray(this.beanDefinition.getDependsOn(), beanName); <ide> this.beanDefinition.setDependsOn(added); <ide> } <ide> return this; <ide><path>org.springframework.context/src/main/java/org/springframework/scripting/support/ScriptFactoryPostProcessor.java <ide> protected void prepareScriptBeans( <ide> ScriptFactory scriptFactory = this.scriptBeanFactory.getBean(scriptFactoryBeanName, ScriptFactory.class); <ide> ScriptSource scriptSource = <ide> getScriptSource(scriptFactoryBeanName, scriptFactory.getScriptSourceLocator()); <del> Class[] interfaces = scriptFactory.getScriptInterfaces(); <add> Class<?>[] interfaces = scriptFactory.getScriptInterfaces(); <ide> <del> Class[] scriptedInterfaces = interfaces; <add> Class<?>[] scriptedInterfaces = interfaces; <ide> if (scriptFactory.requiresConfigInterface() && !bd.getPropertyValues().isEmpty()) { <del> Class configInterface = createConfigInterface(bd, interfaces); <del> scriptedInterfaces = (Class[]) ObjectUtils.addObjectToArray(interfaces, configInterface); <add> Class<?> configInterface = createConfigInterface(bd, interfaces); <add> scriptedInterfaces = ObjectUtils.addObjectToArray(interfaces, configInterface); <ide> } <ide> <ide> BeanDefinition objectBd = createScriptedObjectBeanDefinition( <ide><path>org.springframework.core/src/main/java/org/springframework/util/ObjectUtils.java <ide> public static boolean containsElement(Object[] array, Object element) { <ide> } <ide> <ide> /** <del> * Append the given Object to the given array, returning a new array <del> * consisting of the input array contents plus the given Object. <add> * Append the given object to the given array, returning a new array <add> * consisting of the input array contents plus the given object. <ide> * @param array the array to append to (can be <code>null</code>) <del> * @param obj the Object to append <add> * @param obj the object to append <ide> * @return the new array (of the same component type; never <code>null</code>) <ide> */ <del> public static Object[] addObjectToArray(Object[] array, Object obj) { <del> Class compType = Object.class; <add> public static <A,O extends A> A[] addObjectToArray(A[] array, O obj) { <add> Class<?> compType = Object.class; <ide> if (array != null) { <ide> compType = array.getClass().getComponentType(); <ide> } <ide> else if (obj != null) { <ide> compType = obj.getClass(); <ide> } <ide> int newArrLength = (array != null ? array.length + 1 : 1); <del> Object[] newArr = (Object[]) Array.newInstance(compType, newArrLength); <add> @SuppressWarnings("unchecked") <add> A[] newArr = (A[]) Array.newInstance(compType, newArrLength); <ide> if (array != null) { <ide> System.arraycopy(array, 0, newArr, 0, array.length); <ide> } <ide><path>org.springframework.core/src/test/java/org/springframework/util/ObjectUtilsTests.java <ide> public void testAddObjectToArraySunnyDay() { <ide> public void testAddObjectToArrayWhenEmpty() { <ide> String[] array = new String[0]; <ide> String newElement = "foo"; <del> Object[] newArray = ObjectUtils.addObjectToArray(array, newElement); <add> String[] newArray = ObjectUtils.addObjectToArray(array, newElement); <ide> assertEquals(1, newArray.length); <ide> assertEquals(newElement, newArray[0]); <ide> } <ide> public void testAddObjectToSingleNonNullElementArray() { <ide> String existingElement = "foo"; <ide> String[] array = new String[] {existingElement}; <ide> String newElement = "bar"; <del> Object[] newArray = ObjectUtils.addObjectToArray(array, newElement); <add> String[] newArray = ObjectUtils.addObjectToArray(array, newElement); <ide> assertEquals(2, newArray.length); <ide> assertEquals(existingElement, newArray[0]); <ide> assertEquals(newElement, newArray[1]); <ide> public void testAddObjectToSingleNonNullElementArray() { <ide> public void testAddObjectToSingleNullElementArray() { <ide> String[] array = new String[] {null}; <ide> String newElement = "bar"; <del> Object[] newArray = ObjectUtils.addObjectToArray(array, newElement); <add> String[] newArray = ObjectUtils.addObjectToArray(array, newElement); <ide> assertEquals(2, newArray.length); <ide> assertEquals(null, newArray[0]); <ide> assertEquals(newElement, newArray[1]); <ide> } <ide> <ide> public void testAddObjectToNullArray() throws Exception { <ide> String newElement = "foo"; <del> Object[] newArray = ObjectUtils.addObjectToArray(null, newElement); <add> String[] newArray = ObjectUtils.addObjectToArray(null, newElement); <ide> assertEquals(1, newArray.length); <ide> assertEquals(newElement, newArray[0]); <ide> }
4
Java
Java
introduce soft assertions for mockmvc
35bec8102b014feac18c5b096b39c3592c27b76e
<ide><path>spring-test/src/main/java/org/springframework/test/web/servlet/ResultActions.java <ide> public interface ResultActions { <ide> * .andExpect(jsonPath("$.person.name").value("Jason")); <ide> * </pre> <ide> * <del> * <p>Or alternatively provide all matchers as a vararg: <add> * <p>Either provide all matchers as a vararg: <ide> * <pre class="code"> <ide> * static imports: MockMvcRequestBuilders.*, MockMvcResultMatchers.*, ResultMatcher.matchAll <ide> * <ide> public interface ResultActions { <ide> * flash().attribute("message", "success!")) <ide> * ); <ide> * </pre> <add> * <add> * <p>Or provide all matchers to be evaluated no matter if one of them fail: <add> * <pre class="code"> <add> * static imports: MockMvcRequestBuilders.*, MockMvcResultMatchers.*, ResultMatcher.matchAllSoftly <add> * mockMvc.perform(post("/form")) <add> * .andExpect(matchAllSoftly( <add> * status().isOk(), <add> * redirectedUrl("/person/1") <add> * ); <add> * </pre> <ide> */ <ide> ResultActions andExpect(ResultMatcher matcher) throws Exception; <ide> <ide><path>spring-test/src/main/java/org/springframework/test/web/servlet/ResultMatcher.java <ide> <ide> package org.springframework.test.web.servlet; <ide> <add>import java.util.ArrayList; <add>import java.util.List; <add> <ide> /** <ide> * A {@code ResultMatcher} matches the result of an executed request against <ide> * some expectation. <ide> static ResultMatcher matchAll(ResultMatcher... matchers) { <ide> }; <ide> } <ide> <add> /** <add> * Static method for matching with an array of result matchers whose assertion failures are caught and stored. <add> * Only when all of them would be called a {@link AssertionError} be thrown containing the error messages of those <add> * previously caught assertion failures. <add> * @param matchers the matchers <add> * @author MichaΕ‚ Rowicki <add> * @since 5.2 <add> */ <add> static ResultMatcher matchAllSoftly(ResultMatcher... matchers) { <add> return result -> { <add> List<String> failedMessages = new ArrayList<>(); <add> for (int i = 0; i < matchers.length; i++) { <add> ResultMatcher matcher = matchers[i]; <add> try { <add> matcher.match(result); <add> } <add> catch (AssertionError assertionException) { <add> failedMessages.add("[" + i + "] " + assertionException.getMessage()); <add> } <add> } <add> if (!failedMessages.isEmpty()) { <add> throw new AssertionError(String.join("\n", failedMessages)); <add> } <add> }; <add> } <add> <ide> } <ide><path>spring-test/src/test/java/org/springframework/test/web/servlet/ResultMatcherTests.java <add>/* <add> * Copyright 2002-2021 the original author or authors. <add> * <add> * Licensed under the Apache License, Version 2.0 (the "License"); <add> * you may not use this file except in compliance with the License. <add> * You may obtain a copy of the License at <add> * <add> * https://www.apache.org/licenses/LICENSE-2.0 <add> * <add> * Unless required by applicable law or agreed to in writing, software <add> * distributed under the License is distributed on an "AS IS" BASIS, <add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <add> * See the License for the specific language governing permissions and <add> * limitations under the License. <add> */ <add> <add>package org.springframework.test.web.servlet; <add> <add>import org.jetbrains.annotations.NotNull; <add>import org.junit.jupiter.api.Test; <add> <add>import static org.assertj.core.api.Assertions.assertThatExceptionOfType; <add>import static org.assertj.core.api.Assertions.assertThatNoException; <add> <add>class ResultMatcherTests { <add> <add> @Test <add> void whenProvidedMatcherPassesThenSoftAssertionsAlsoPasses() { <add> ResultMatcher resultMatcher = ResultMatcher.matchAllSoftly(this::doNothing); <add> StubMvcResult stubMvcResult = new StubMvcResult(null, null, null, null, null, null, null); <add> <add> assertThatNoException().isThrownBy(() -> resultMatcher.match(stubMvcResult)); <add> } <add> <add> @Test <add> void whenOneOfMatcherFailsThenSoftAssertionFailsWithTheVerySameMessage() { <add> String failMessage = "fail message"; <add> StubMvcResult stubMvcResult = new StubMvcResult(null, null, null, null, null, null, null); <add> ResultMatcher resultMatcher = ResultMatcher.matchAllSoftly(failMatcher(failMessage)); <add> <add> assertThatExceptionOfType(AssertionError.class) <add> .isThrownBy(() -> resultMatcher.match(stubMvcResult)) <add> .withMessage("[0] " + failMessage); <add> } <add> <add> @Test <add> void whenMultipleMatchersFailsThenSoftAssertionFailsWithOneErrorWithMessageContainingAllErrorMessagesWithTheSameOrder() { <add> String firstFail = "firstFail"; <add> String secondFail = "secondFail"; <add> StubMvcResult stubMvcResult = new StubMvcResult(null, null, null, null, null, null, null); <add> ResultMatcher resultMatcher = ResultMatcher.matchAllSoftly(failMatcher(firstFail), failMatcher(secondFail)); <add> <add> assertThatExceptionOfType(AssertionError.class) <add> .isThrownBy(() -> resultMatcher.match(stubMvcResult)) <add> .withMessage("[0] " + firstFail + "\n[1] " + secondFail); <add> } <add> <add> @NotNull <add> private ResultMatcher failMatcher(String failMessage) { <add> return result -> { <add> throw new AssertionError(failMessage); <add> }; <add> } <add> <add> void doNothing(MvcResult mvcResult) {} <add>}
3
Text
Text
add more examples
7d97f26870a6ec74281bc7d3651604dc7eb33b93
<ide><path>docs/docs/refactor/09-reference.md <ide> React has implemented a browser-independent events and DOM system for performanc <ide> <ide> * React powers all of Instagram.com and many components on Facebook.com, including the commenting interface, ads creation flows, and page insights. <ide> * We've included [a step-by-step tutorial](./09.1-tutorial.md) for creating a comment box widget with React <del>* [The React starter kit](/react/downloads.md) includes several examples which you can [view online in our GitHub repo](https://github.com/facebook/react/tree/master/examples/) <ide>\ No newline at end of file <add>* [The React starter kit](/react/downloads.md) includes several examples which you can [view online in our GitHub repo](https://github.com/facebook/react/tree/master/examples/) <add>* [reactapp](https://github.com/jordwalke/reactapp) is a simple app template to get you up-and-running quickly with React. <add>* [React one-hour email](https://github.com/petehunt/react-one-hour-email/commits/master) goes step-by-step from a static HTML mock to an interactive email reader (written in just one hour!) <add>* [Rendr + React app template](https://github.com/petehunt/rendr-react-template/) demonstrates how to use React's server rendering capabilities. <ide>\ No newline at end of file
1
Javascript
Javascript
click propagation change
8248e77a7b910bcbc71ca25c06bef44dd6712990
<ide><path>src/directives.js <ide> angularWidget("@ng:repeat", function(expression, element){ <ide> }; <ide> }); <ide> <add> <add>/* <add> * A directive that allows creation of custom onclick handlers that are defined as angular <add> * expressions and are compiled and executed within the current scope. <add> * <add> * Events that are handled via these handler are always configured not to propagate further. <add> * <add> * TODO: maybe we should consider allowing users to control even propagation in the future. <add> */ <ide> angularDirective("ng:click", function(expression, element){ <ide> return function(element){ <ide> var self = this; <ide> element.bind('click', function(event){ <ide> self.$tryEval(expression, element); <ide> self.$root.$eval(); <del> event.preventDefault(); <add> event.stopPropagation(); <ide> }); <ide> }; <ide> }); <ide><path>src/widgets.js <ide> var ngSwitch = angularWidget('ng:switch', function (element){ <ide> }, <ide> route: switchRouteMatcher <ide> }); <add> <add> <add>/* <add> * Modifies the default behavior of html A tag, so that the default action is prevented when href <add> * attribute is empty. <add> * <add> * The reasoning for this change is to allow easy creation of action links with ng:click without <add> * changing the location or causing page reloads, e.g.: <add> * <a href="" ng:click="model.$save()">Save</a> <add> */ <add>angular.widget('a', function() { <add> this.descend(true); <add> this.directives(true); <add> <add> return function(element) { <add> if (element.attr('href') === '') { <add> element.bind('click', function(event){ <add> event.preventDefault(); <add> }); <add> } <add> }; <add>}); <ide>\ No newline at end of file <ide><path>test/directivesSpec.js <ide> describe("directives", function(){ <ide> element.trigger('click'); <ide> expect(scope.$get('clicked')).toEqual(true); <ide> }); <add> <add> it('should stop event propagation', function() { <add> var scope = compile('<div ng:click="outer = true"><div ng:click="inner = true"></div></div>'); <add> scope.$eval(); <add> expect(scope.$get('outer')).not.toBeDefined(); <add> expect(scope.$get('inner')).not.toBeDefined(); <add> <add> var innerDiv = jqLite(element.children()[0]); <add> <add> innerDiv.trigger('click'); <add> expect(scope.$get('outer')).not.toBeDefined(); <add> expect(scope.$get('inner')).toEqual(true); <add> }) <ide> }); <ide> <ide> it('should ng:class', function(){ <ide><path>test/widgetsSpec.js <ide> describe("widget", function(){ <ide> expect(element.text()).toEqual(''); <ide> }); <ide> }); <add> <add> describe('a', function() { <add> it('should prevent default action to be executed when href is empty', function() { <add> var orgLocation = document.location.href, <add> preventDefaultCalled = false, <add> event; <add> <add> compile('<a href="">empty link</a>'); <add> <add> if (msie) { <add> <add> event = document.createEventObject(); <add> expect(event.returnValue).not.toBeDefined(); <add> element[0].fireEvent('onclick', event); <add> expect(event.returnValue).toEqual(false); <add> <add> } else { <add> <add> event = document.createEvent('MouseEvent'); <add> event.initMouseEvent('click', true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, _null); <add> <add> event.preventDefaultOrg = event.preventDefault; <add> event.preventDefault = function() { <add> preventDefaultCalled = true; <add> if (this.preventDefaultOrg) this.preventDefaultOrg(); <add> }; <add> <add> element[0].dispatchEvent(event); <add> <add> expect(preventDefaultCalled).toEqual(true); <add> } <add> <add> expect(document.location.href).toEqual(orgLocation); <add> }); <add> }) <ide> }); <ide>
4
Text
Text
emphasize module bundlers for browser use
a44b738a4bf51d0b4a8a22c0247bef0ad52011c7
<ide><path>README.md <ide> map1.get('b') + " vs. " + map2.get('b') // 2 vs. 50 <ide> <ide> ### Browser <ide> <del>To use Immutable.js from a browser, download [dist/immutable.min.js](https://github.com/facebook/immutable-js/blob/master/dist/immutable.min.js) <del>or use a CDN such as [CDNJS](https://cdnjs.com/libraries/immutable) <del>or [jsDelivr](http://www.jsdelivr.com/#!immutable.js). <add>Immutable.js has no depenencnies, which makes it predictable to include in a Browser. <ide> <del>Then, add it as a script tag to your page: <add>It's highly recommended to use a module bundler like [webpack](https://webpack.github.io/), <add>[rollup](https://rollupjs.org/), or <add>[browserify](http://browserify.org/). The `immutable` npm module works <add>without any additional consideration. All examples throughout the documentation <add>will assume use of this kind of tool. <add> <add>Alternatively, Immutable.js may be directly included as a script tag. Download <add>or link to a CDN such as [CDNJS](https://cdnjs.com/libraries/immutable) <add>or [jsDelivr](https://www.jsdelivr.com/package/npm/immutable). <add> <add>Use a script tag to directly add `Immutable` to the global scope: <ide> <ide> ```html <ide> <script src="immutable.min.js"></script> <ide> <script> <del> var map1 = Immutable.Map({a:1, b:2, c:3}); <del> var map2 = map1.set('b', 50); <del> map1.get('b'); // 2 <del> map2.get('b'); // 50 <add> var map1 = Immutable.Map({a:1, b:2, c:3}); <add> var map2 = map1.set('b', 50); <add> map1.get('b'); // 2 <add> map2.get('b'); // 50 <ide> </script> <ide> ``` <ide> <del>Or use an AMD loader (such as [RequireJS](http://requirejs.org/)): <add>Or use an AMD-style loader (such as [RequireJS](http://requirejs.org/)): <ide> <ide> ```js <ide> require(['./immutable.min.js'], function (Immutable) { <del> var map1 = Immutable.Map({a:1, b:2, c:3}); <del> var map2 = map1.set('b', 50); <del> map1.get('b'); // 2 <del> map2.get('b'); // 50 <add> var map1 = Immutable.Map({a:1, b:2, c:3}); <add> var map2 = map1.set('b', 50); <add> map1.get('b'); // 2 <add> map2.get('b'); // 50 <ide> }); <ide> ``` <ide> <del>If you're using [webpack](https://webpack.github.io/) or <del>[browserify](http://browserify.org/), the `immutable` npm module also works <del>from the browser. <del> <ide> ### Flow & TypeScript <ide> <ide> Use these Immutable collections and sequences as you would use native
1
Javascript
Javascript
upgrade dllmodule to es6
0af2125943acc7729654178a3b6e2e117c09813a
<ide><path>lib/DllModule.js <ide> /* <ide> MIT License http://www.opensource.org/licenses/mit-license.php <ide> Author Tobias Koppers @sokra <del>*/ <del>var Module = require("./Module"); <del>var RawSource = require("webpack-sources").RawSource; <del> <del>function DllModule(context, dependencies, name, type) { <del> Module.call(this); <del> this.context = context; <del> this.dependencies = dependencies; <del> this.name = name; <del> this.built = false; <del> this.cacheable = true; <del> this.type = type; <add> */ <add>"use strict"; <add> <add>const Module = require("./Module"); <add>const RawSource = require("webpack-sources").RawSource; <add> <add>class DllModule extends Module { <add> constructor(context, dependencies, name, type) { <add> super(); <add> this.context = context; <add> this.dependencies = dependencies; <add> this.name = name; <add> this.built = false; <add> this.cacheable = true; <add> this.type = type; <add> } <add> <add> identifier() { <add> return `dll ${this.name}`; <add> } <add> <add> readableIdentifier() { <add> return `dll ${this.name}`; <add> } <add> <add> disconnect() { <add> this.built = false; <add> super.disconnect(); <add> } <add> <add> build(options, compilation, resolver, fs, callback) { <add> this.built = true; <add> return callback(); <add> } <add> <add> source() { <add> return new RawSource("module.exports = __webpack_require__;"); <add> } <add> <add> needRebuild() { <add> return false; <add> } <add> <add> size() { <add> return 12; <add> } <add> <add> updateHash(hash) { <add> hash.update("dll module"); <add> hash.update(this.name || ""); <add> super.updateHash(hash); <add> } <ide> } <del>module.exports = DllModule; <del> <del>DllModule.prototype = Object.create(Module.prototype); <del>DllModule.prototype.constructor = DllModule; <del> <del>DllModule.prototype.identifier = function() { <del> return "dll " + this.name; <del>}; <del> <del>DllModule.prototype.readableIdentifier = function() { <del> return "dll " + this.name; <del>}; <del> <del>DllModule.prototype.disconnect = function disconnect() { <del> this.built = false; <del> Module.prototype.disconnect.call(this); <del>}; <ide> <del>DllModule.prototype.build = function build(options, compilation, resolver, fs, callback) { <del> this.built = true; <del> return callback(); <del>}; <del> <del>DllModule.prototype.source = function() { <del> return new RawSource("module.exports = __webpack_require__;"); <del>}; <del> <del>DllModule.prototype.needRebuild = function needRebuild() { <del> return false; <del>}; <del> <del>DllModule.prototype.size = function() { <del> return 12; <del>}; <del> <del>DllModule.prototype.updateHash = function(hash) { <del> hash.update("dll module"); <del> hash.update(this.name || ""); <del> Module.prototype.updateHash.call(this, hash); <del>}; <add>module.exports = DllModule;
1
Python
Python
fix typos in models.py
9259772e679c847304f5637e5bb7ce1aa3a9db8d
<ide><path>airflow/models.py <ide> class derived from this one results in the creation of a task object, <ide> which ultimately becomes a node in DAG objects. Task dependencies should <ide> be set by using the set_upstream and/or set_downstream methods. <ide> <del> Note that this class is derived from SQLAlquemy's Base class, which <add> Note that this class is derived from SQLAlchemy's Base class, which <ide> allows us to push metadata regarding tasks to the database. Deriving this <ide> classes needs to implement the polymorphic specificities documented in <ide> SQLAlchemy. This should become clear while reading the code for other <ide> class derived from this one results in the creation of a task object, <ide> :param retry_delay: delay between retries <ide> :type retry_delay: timedelta <ide> :param start_date: The ``start_date`` for the task, determines <del> the ``execution_date`` for the first task instanec. The best practice <add> the ``execution_date`` for the first task instance. The best practice <ide> is to have the start_date rounded <ide> to your DAG's ``schedule_interval``. Daily jobs have their start_date <ide> some day at 00:00:00, hourly jobs have their start_date at 00:00
1
Javascript
Javascript
fix missing chart.chart (deprecated) alias
87a74f99a1e73fef3ebd314a11c322829c3d7cd1
<ide><path>src/index.js <ide> if (typeof window !== 'undefined') { <ide> <ide> // DEPRECATIONS <ide> <add>/** <add> * Provided for backward compatibility, not available anymore <add> * @namespace Chart.Chart <add> * @deprecated since version 2.8.0 <add> * @todo remove at version 3 <add> * @private <add> */ <add>Chart.Chart = Chart; <add> <ide> /** <ide> * Provided for backward compatibility, not available anymore <ide> * @namespace Chart.Legend <ide><path>test/specs/global.deprecations.tests.js <ide> describe('Deprecations', function() { <ide> }); <ide> }); <ide> <add> describe('Chart.Chart', function() { <add> it('should be defined as an alias to Chart', function() { <add> expect(Chart.Chart).toBe(Chart); <add> }); <add> }); <add> <ide> describe('Chart.helpers.aliasPixel', function() { <ide> it('should be defined as a function', function() { <ide> expect(typeof Chart.helpers.aliasPixel).toBe('function');
2
PHP
PHP
fix several things
6af7b2102fdec7e33cead64b335f58664f9a3ea9
<ide><path>src/Illuminate/Foundation/helpers.php <ide> function logger($message = null, array $context = []) <ide> <ide> if (!function_exists('method_field')) { <ide> /** <del> * Generate a method spoof form field for POST method's. <add> * Generate a form field to spoof the HTTP verb used by forms. <ide> * <del> * @param string $method <add> * @param string $method <ide> * @return string <ide> */ <ide> function method_field($method = "") <ide> { <del> return new Illuminate\View\Expression('<input type="hidden" name="_method" value="$method">'); <add> return new Illuminate\View\Expression('<input type="hidden" name="_method" value="'.$method.'">'); <ide> } <ide> } <ide>
1
Ruby
Ruby
fix "instance variable not initialized" in tests
31ef17a5ebf9bb414a20c9cf63c21ae8b8a39cd7
<ide><path>actionpack/test/assertions/response_assertions_test.rb <ide> def initialize(*) <ide> end <ide> end <ide> <add> def setup <add> @controller = nil <add> @request = nil <add> end <add> <ide> def test_assert_response_predicate_methods <ide> [:success, :missing, :redirect, :error].each do |sym| <ide> @response = FakeResponse.new RESPONSE_PREDICATES[sym].to_s.sub(/\?/, '').to_sym
1
Go
Go
fix config load error with ulimits
e3164842f34a55048af709ee827566e4950aa508
<ide><path>daemon/config.go <ide> var flatOptions = map[string]bool{ <ide> "cluster-store-opts": true, <ide> "log-opts": true, <ide> "runtimes": true, <add> "default-ulimits": true, <ide> } <ide> <ide> // LogConfig represents the default log configuration. <ide><path>daemon/config_test.go <ide> import ( <ide> "github.com/spf13/pflag" <ide> ) <ide> <del>func TestDaemonConfigurationMerge(t *testing.T) { <del> f, err := ioutil.TempFile("", "docker-config-") <del> if err != nil { <del> t.Fatal(err) <del> } <del> <del> configFile := f.Name() <del> f.Write([]byte(`{"debug": true}`)) <del> f.Close() <del> <del> c := &Config{ <del> CommonConfig: CommonConfig{ <del> AutoRestart: true, <del> LogConfig: LogConfig{ <del> Type: "syslog", <del> Config: map[string]string{"tag": "test"}, <del> }, <del> }, <del> } <del> <del> cc, err := MergeDaemonConfigurations(c, nil, configFile) <del> if err != nil { <del> t.Fatal(err) <del> } <del> if !cc.Debug { <del> t.Fatalf("expected %v, got %v\n", true, cc.Debug) <del> } <del> if !cc.AutoRestart { <del> t.Fatalf("expected %v, got %v\n", true, cc.AutoRestart) <del> } <del> if cc.LogConfig.Type != "syslog" { <del> t.Fatalf("expected syslog config, got %q\n", cc.LogConfig) <del> } <del>} <del> <ide> func TestDaemonConfigurationNotFound(t *testing.T) { <ide> _, err := MergeDaemonConfigurations(&Config{}, nil, "/tmp/foo-bar-baz-docker") <ide> if err == nil || !os.IsNotExist(err) { <ide><path>daemon/config_unix_test.go <add>// +build !windows <add> <add>package daemon <add> <add>import ( <add> "io/ioutil" <add> "testing" <add>) <add> <add>func TestDaemonConfigurationMerge(t *testing.T) { <add> f, err := ioutil.TempFile("", "docker-config-") <add> if err != nil { <add> t.Fatal(err) <add> } <add> <add> configFile := f.Name() <add> <add> f.Write([]byte(` <add> { <add> "debug": true, <add> "default-ulimits": { <add> "nofile": { <add> "Name": "nofile", <add> "Hard": 2048, <add> "Soft": 1024 <add> } <add> }, <add> "log-opts": { <add> "tag": "test_tag" <add> } <add> }`)) <add> <add> f.Close() <add> <add> c := &Config{ <add> CommonConfig: CommonConfig{ <add> AutoRestart: true, <add> LogConfig: LogConfig{ <add> Type: "syslog", <add> Config: map[string]string{"tag": "test"}, <add> }, <add> }, <add> } <add> <add> cc, err := MergeDaemonConfigurations(c, nil, configFile) <add> if err != nil { <add> t.Fatal(err) <add> } <add> if !cc.Debug { <add> t.Fatalf("expected %v, got %v\n", true, cc.Debug) <add> } <add> if !cc.AutoRestart { <add> t.Fatalf("expected %v, got %v\n", true, cc.AutoRestart) <add> } <add> if cc.LogConfig.Type != "syslog" { <add> t.Fatalf("expected syslog config, got %q\n", cc.LogConfig) <add> } <add> <add> if configValue, OK := cc.LogConfig.Config["tag"]; !OK { <add> t.Fatal("expected syslog config attributes, got nil\n") <add> } else { <add> if configValue != "test_tag" { <add> t.Fatalf("expected syslog config attributes 'tag=test_tag', got 'tag=%s'\n", configValue) <add> } <add> } <add> <add> if cc.Ulimits == nil { <add> t.Fatal("expected default ulimit config, got nil\n") <add> } else { <add> if _, OK := cc.Ulimits["nofile"]; OK { <add> if cc.Ulimits["nofile"].Name != "nofile" || <add> cc.Ulimits["nofile"].Hard != 2048 || <add> cc.Ulimits["nofile"].Soft != 1024 { <add> t.Fatalf("expected default ulimit name, hard and soft are nofile, 2048, 1024, got %s, %d, %d\n", cc.Ulimits["nofile"].Name, cc.Ulimits["nofile"].Hard, cc.Ulimits["nofile"].Soft) <add> } <add> } else { <add> t.Fatal("expected default ulimit name nofile, got nil\n") <add> } <add> } <add>} <ide><path>daemon/config_windows_test.go <add>// +build windows <add> <add>package daemon <add> <add>import ( <add> "io/ioutil" <add> "testing" <add>) <add> <add>func TestDaemonConfigurationMerge(t *testing.T) { <add> f, err := ioutil.TempFile("", "docker-config-") <add> if err != nil { <add> t.Fatal(err) <add> } <add> <add> configFile := f.Name() <add> <add> f.Write([]byte(` <add> { <add> "debug": true, <add> "log-opts": { <add> "tag": "test_tag" <add> } <add> }`)) <add> <add> f.Close() <add> <add> c := &Config{ <add> CommonConfig: CommonConfig{ <add> AutoRestart: true, <add> LogConfig: LogConfig{ <add> Type: "syslog", <add> Config: map[string]string{"tag": "test"}, <add> }, <add> }, <add> } <add> <add> cc, err := MergeDaemonConfigurations(c, nil, configFile) <add> if err != nil { <add> t.Fatal(err) <add> } <add> if !cc.Debug { <add> t.Fatalf("expected %v, got %v\n", true, cc.Debug) <add> } <add> if !cc.AutoRestart { <add> t.Fatalf("expected %v, got %v\n", true, cc.AutoRestart) <add> } <add> if cc.LogConfig.Type != "syslog" { <add> t.Fatalf("expected syslog config, got %q\n", cc.LogConfig) <add> } <add> <add> if configValue, OK := cc.LogConfig.Config["tag"]; !OK { <add> t.Fatal("expected syslog config attributes, got nil\n") <add> } else { <add> if configValue != "test_tag" { <add> t.Fatalf("expected syslog config attributes 'tag=test_tag', got 'tag=%s'\n", configValue) <add> } <add> } <add>}
4
Python
Python
send model to the correct device
da5bb2921907c398e61ea1b73fd22d13938fc427
<ide><path>tests/models/speech_encoder_decoder/test_modeling_speech_encoder_decoder.py <ide> def test_training_gradient_checkpointing(self): <ide> ) <ide> <ide> model = SpeechEncoderDecoderModel(encoder=encoder_model, decoder=decoder_model) <add> model.to(torch_device) <ide> model.train() <ide> model.gradient_checkpointing_enable() <ide> model.config.decoder_start_token_id = 0 <ide><path>tests/models/vision_encoder_decoder/test_modeling_vision_encoder_decoder.py <ide> def test_training_gradient_checkpointing(self): <ide> ) <ide> <ide> model = VisionEncoderDecoderModel(encoder=encoder_model, decoder=decoder_model) <add> model.to(torch_device) <ide> model.train() <ide> model.gradient_checkpointing_enable() <ide> model.config.decoder_start_token_id = 0
2
Python
Python
fix lookup usage in french/catalan (fix )
aafee5e1b7c8d13d9ac14c438063621a18bec743
<ide><path>spacy/lang/ca/lemmatizer.py <ide> def rule_lemmatize(self, token: Token) -> List[str]: <ide> oov_forms.append(form) <ide> if not forms: <ide> forms.extend(oov_forms) <del> if not forms and string in lookup_table.keys(): <del> forms.append(self.lookup_lemmatize(token)[0]) <add> <add> # use lookups, and fall back to the token itself <ide> if not forms: <del> forms.append(string) <add> forms.append(lookup_table.get(string, [string])[0]) <ide> forms = list(dict.fromkeys(forms)) <ide> self.cache[cache_key] = forms <ide> return forms <ide><path>spacy/lang/fr/lemmatizer.py <ide> def rule_lemmatize(self, token: Token) -> List[str]: <ide> rules = rules_table.get(univ_pos, []) <ide> string = string.lower() <ide> forms = [] <add> # first try lookup in table based on upos <ide> if string in index: <ide> forms.append(string) <ide> self.cache[cache_key] = forms <ide> return forms <add> <add> # then add anything in the exceptions table <ide> forms.extend(exceptions.get(string, [])) <add> <add> # if nothing found yet, use the rules <ide> oov_forms = [] <ide> if not forms: <ide> for old, new in rules: <ide> def rule_lemmatize(self, token: Token) -> List[str]: <ide> forms.append(form) <ide> else: <ide> oov_forms.append(form) <add> <add> # if still nothing, add the oov forms from rules <ide> if not forms: <ide> forms.extend(oov_forms) <del> if not forms and string in lookup_table.keys(): <del> forms.append(self.lookup_lemmatize(token)[0]) <add> <add> # use lookups, which fall back to the token itself <ide> if not forms: <del> forms.append(string) <add> forms.append(lookup_table.get(string, [string])[0]) <ide> forms = list(dict.fromkeys(forms)) <ide> self.cache[cache_key] = forms <ide> return forms
2
Python
Python
add module doc for providers
f1a2f8de838cfdd65908138534b80d653ffc84cd
<ide><path>libcloud/providers.py <ide> # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <ide> # See the License for the specific language governing permissions and <ide> # limitations under the License. <add>""" <add>Provider related utilities <add>""" <add> <ide> from libcloud.types import Provider <ide> from libcloud.drivers.linode import LinodeNodeDriver as Linode <ide> from libcloud.drivers.slicehost import SlicehostNodeDriver as Slicehost <ide> from libcloud.drivers.rackspace import RackspaceNodeDriver as Rackspace <ide> <add> <ide> DRIVERS = { <ide> # Provider.DUMMY: <ide> # ('libcloud.drivers.dummy', 'DummyNodeDriver'), <ide> } <ide> <ide> def get_driver(provider): <del> """ Gets a driver <add> """Gets a driver <ide> @param provider: Id of provider to get driver <ide> @type provider: L{libcloud.types.Provider} <ide> """
1
Javascript
Javascript
add basic unit tests for obj.js
84d6a121af3849f3654cbef9efb7fde050baa1ea
<ide><path>src/obj.js <ide> var Name = (function NameClosure() { <ide> this.name = name; <ide> } <ide> <del> Name.prototype = { <del> }; <add> Name.prototype = {}; <ide> <ide> return Name; <ide> })(); <ide> var Cmd = (function CmdClosure() { <ide> this.cmd = cmd; <ide> } <ide> <del> Cmd.prototype = { <del> }; <del> <add> Cmd.prototype = {}; <ide> <ide> var cmdCache = {}; <ide> <ide> var Ref = (function RefClosure() { <ide> this.gen = gen; <ide> } <ide> <del> Ref.prototype = { <del> }; <add> Ref.prototype = {}; <ide> <ide> return Ref; <ide> })(); <ide><path>test/unit/obj_spec.js <ide> <ide> 'use strict'; <ide> <del>describe("obj", function() { <add>describe('obj', function() { <ide> <del> describe("Name", function() { <del> it("should retain the given name", function() { <del> var givenName = "Font"; <add> describe('Name', function() { <add> it('should retain the given name', function() { <add> var givenName = 'Font'; <ide> var name = new Name(givenName); <ide> expect(name.name).toEqual(givenName); <ide> }); <ide> }); <add> <add> describe('Cmd', function() { <add> it('should retain the given cmd name', function() { <add> var givenCmd = 'BT'; <add> var cmd = new Cmd(givenCmd); <add> expect(cmd.cmd).toEqual(givenCmd); <add> }); <add> <add> <add> it('should create only one object for a command and cache it', function() { <add> var firstBT = Cmd.get('BT'); <add> var secondBT = Cmd.get('BT'); <add> var firstET = Cmd.get('ET'); <add> var secondET = Cmd.get('ET'); <add> expect(firstBT).toBe(secondBT); <add> expect(firstET).toBe(secondET); <add> expect(firstBT).not.toBe(firstET); <add> }); <add> }); <add> <add> describe('Dict', function() { <add> beforeEach(function() { <add> this.checkInvalidHasValues = function(dict, key) { <add> expect(dict.has()).toBeFalsy(); <add> expect(dict.has(key)).toBeFalsy(); <add> }; <add> this.checkInvalidKeyValues = function(dict, key) { <add> expect(dict.get()).toBeUndefined(); <add> expect(dict.get(key)).toBeUndefined(); <add> expect(dict.get('Prev', 'Root')).toBeUndefined(); <add> <add> // Note that the getter with three arguments breaks the pattern here. <add> expect(dict.get('Encrypt', 'Info', 'ID')).toBeNull(); <add> }; <add> }); <add> <add> it('should return invalid values for unknown keys', function() { <add> var dict = new Dict(); <add> this.checkInvalidHasValues(dict, 'Size'); <add> this.checkInvalidKeyValues(dict, 'Size'); <add> }); <add> <add> it('should return correct value for stored Size key', function() { <add> var dict = new Dict(); <add> var storedSize = 42; <add> dict.set('Size', storedSize); <add> <add> expect(dict.has('Size')).toBeTruthy(); <add> <add> expect(dict.get('Size')).toEqual(storedSize); <add> expect(dict.get('Prev', 'Size')).toEqual(storedSize); <add> expect(dict.get('Prev', 'Root', 'Size')).toEqual(storedSize); <add> }); <add> <add> it('should return invalid values for unknown keys when Size key is stored', <add> function() { <add> var dict = new Dict(); <add> var storedSize = 42; <add> dict.set('Size', storedSize); <add> <add> this.checkInvalidHasValues(dict, 'Prev'); <add> this.checkInvalidKeyValues(dict, 'Prev'); <add> }); <add> <add> it('should return correct value for stored Size key with undefined value', <add> function() { <add> var dict = new Dict(); <add> dict.set('Size'); <add> <add> expect(dict.has('Size')).toBeTruthy(); <add> <add> this.checkInvalidKeyValues(dict, 'Size'); <add> }); <add> <add> it('should return correct values for multiple stored keys', function() { <add> var dict = new Dict(); <add> var storedSize = 42; <add> var storedPrev = 4; <add> var storedID = '[<06316BB1DF26984E89AFA8619B8722ED>' + <add> '<5E07F5458646544588630F1FD634FF2C>]'; <add> dict.set('Size', storedSize); <add> dict.set('Prev', storedPrev); <add> dict.set('ID', storedID); <add> <add> expect(dict.has('Size')).toBeTruthy(); <add> expect(dict.has('Prev')).toBeTruthy(); <add> expect(dict.has('ID')).toBeTruthy(); <add> <add> expect(dict.get('ID')).toEqual(storedID); <add> expect(dict.get('Prev', 'ID')).toEqual(storedPrev); <add> expect(dict.get('Size', 'Prev', 'ID')).toEqual(storedSize); <add> }); <add> <add> it('should callback for each stored key', function() { <add> var dict = new Dict(); <add> var storedSize = 42; <add> var storedPrev = 4; <add> var storedID = '[<06316BB1DF26984E89AFA8619B8722ED>' + <add> '<5E07F5458646544588630F1FD634FF2C>]'; <add> dict.set('Size', storedSize); <add> dict.set('Prev', storedPrev); <add> dict.set('ID', storedID); <add> <add> var callbackSpy = jasmine.createSpy('spy on callback in dictionary'); <add> <add> dict.forEach(callbackSpy); <add> <add> expect(callbackSpy).wasCalled(); <add> expect(callbackSpy.argsForCall[0]).toEqual(['Size', storedSize]); <add> expect(callbackSpy.argsForCall[1]).toEqual(['Prev', storedPrev]); <add> expect(callbackSpy.argsForCall[2]).toEqual(['ID', storedID]); <add> expect(callbackSpy.callCount).toEqual(3); <add> }); <add> }); <add> <add> describe('Ref', function() { <add> it('should retain the stored values', function() { <add> var storedNum = 42; <add> var storedGen = "fortytwo"; <add> var ref = new Ref(storedNum, storedGen); <add> expect(ref.num).toEqual(storedNum); <add> expect(ref.gen).toEqual(storedGen); <add> }); <add> }); <ide> }); <ide>
2
Javascript
Javascript
add text blast to example app showcase
d31b47c018180169c580d4b2ef023a248f5fefae
<ide><path>website/src/react-native/showcase.js <ide> var apps = [ <ide> link: 'https://itunes.apple.com/us/app/thai-tone/id1064086189?mt=8', <ide> author: 'Alexey Ledak', <ide> }, <add> { <add> name: 'Text Blast', <add> icon: 'http://a3.mzstatic.com/us/r30/Purple49/v4/4f/29/58/4f2958a1-7f35-9260-6340-c67ac29d7740/icon175x175.png', <add> link: 'https://itunes.apple.com/us/app/text-blast-2016/id1023852862?mt=8', <add> author: 'Sesh', <add> }, <ide> { <ide> name: 'Tong Xing Wang', <ide> icon: 'http://a3.mzstatic.com/us/r30/Purple1/v4/7d/52/a7/7d52a71f-9532-82a5-b92f-87076624fdb2/icon175x175.jpeg',
1
Python
Python
fix some pylint errors
9dd1c2c0aa2d4f4508543e9c34c2aa76678f8706
<ide><path>official/vision/beta/projects/yolo/modeling/decoders/yolo_decoder.py <ide> def get_raw_depths(self, minimum_depth, inputs): <ide> <ide> Args: <ide> minimum_depth: `int` depth of the smallest branch of the FPN. <del> inputs: `dict[str, tf.InputSpec]` of the shape of input args as a dictionary of <del> lists. <add> inputs: `dict[str, tf.InputSpec]` of the shape of input args as a <add> dictionary of lists. <ide> <ide> Returns: <ide> The unscaled depths of the FPN branches. <ide> """ <del> <add> <ide> depths = [] <ide> if len(inputs.keys()) > 3 or self._fpn_filter_scale > 1: <ide> for i in range(self._min_level, self._max_level + 1): <ide> def __init__(self, <ide> kernel_regularizer=None, <ide> bias_regularizer=None, <ide> **kwargs): <del> """Yolo Decoder initialization function. A unified model that ties all decoder <del> components into a conditionally build YOLO decder. <add> """Yolo Decoder initialization function. A unified model that ties all <add> decoder components into a conditionally build YOLO decoder. <ide> <ide> Args: <ide> input_specs: `dict[str, tf.InputSpec]`: input specs of each of the inputs <ide> def __init__(self, <ide> zero. <ide> kernel_initializer: kernel_initializer for convolutional layers. <ide> kernel_regularizer: tf.keras.regularizers.Regularizer object for Conv2D. <del> bias_regularizer: tf.keras.regularizers.Regularizer object for Conv2d. <add> bias_regularizer: tf.keras.regularizers.Regularizer object for Conv2D. <ide> **kwargs: keyword arguments to be passed. <ide> """ <ide> <ide><path>official/vision/beta/projects/yolo/modeling/layers/nn_blocks.py <ide> def build(self, input_shape): <ide> <ide> def call(self, inputs, training=None): <ide> if self._use_pooling: <del> depth_max = tf.reduce_max(inputs, axis=-1, keep_dims=True) <del> depth_avg = tf.reduce_mean(inputs, axis=-1, keep_dims=True) <add> depth_max = tf.reduce_max(inputs, axis=-1, keepdims=True) <add> depth_avg = tf.reduce_mean(inputs, axis=-1, keepdims=True) <ide> input_maps = tf.concat([depth_avg, depth_max], axis=-1) <ide> else: <ide> input_maps = inputs <ide> def build(self, input_shape): <ide> elif layer == 'spp': <ide> self.layers.append(self._spp(self._filters, dark_conv_args)) <ide> elif layer == 'sam': <del> self.layers.append(self._sam(-1, _args)) <add> self.layers.append(self._sam(-1, dark_conv_args)) <ide> <ide> self._lim = len(self.layers) <ide> super().build(input_shape)
2
Javascript
Javascript
add faster failure, and link to
9a6f936c8a62c1a6edad3bda0faa8d8112b7cf92
<ide><path>test/simple/test-fs-watch.js <ide> var assert = require('assert'); <ide> var path = require('path'); <ide> var fs = require('fs'); <ide> <add> <add>if (process.platform === 'darwin') { <add> assert(false, <add> 'This test is known to fail on OS X\n' + <add> 'See: https://github.com/joyent/node/issues/2813'); <add>} <add> <add> <ide> var expectFilePath = process.platform == 'win32' || process.platform == 'linux'; <ide> <ide> var watchSeenOne = 0;
1
Ruby
Ruby
fix swift compatability check
426c6e2c3f24ec48c33c3937c96ae76ca786a495
<ide><path>Library/Homebrew/requirements/xcode_requirement.rb <ide> def initialize(tags = []) <ide> <ide> def xcode_installed_version <ide> return false unless MacOS::Xcode.installed? <add> return false unless xcode_swift_compatability? <ide> return true unless @version <del> return true if xcode_swift_compatability? <ide> <ide> MacOS::Xcode.version >= @version <ide> end <ide> def inspect <ide> # method in favour of requiring 10.14.4 and 10.2. <ide> def xcode_swift_compatability? <ide> return true if MacOS::Xcode.version < "10.2" <del> return true if MacOS::Xcode.version >= "10.14.4" <add> return true if MacOS.full_version >= "10.14.4" <ide> <del> MacOS.version < "10.14" <add> MacOS.full_version < "10.14" <ide> end <ide> end
1
Text
Text
transform rest and spread properties using babel 6
ed8727ade783c5998b51ae75554af4cb391c2acc
<ide><path>docs/docs/06-transferring-props.md <ide> z; // { a: 3, b: 4 } <ide> <ide> > Note: <ide> > <del>> This proposal has reached stage 2 and is now enabled by default in Babel. Older versions of Babel may need to explicitly enable this transform with `babel --optional es7.objectRestSpread` <add>> To transform rest and spread properties using Babel 6, you need to install the [`es2015`](https://babeljs.io/docs/plugins/preset-es2015/) preset, the [`transform-object-rest-spread`](https://babeljs.io/docs/plugins/transform-object-rest-spread/) plugin and configure them in the `.babelrc` file. <ide> <ide> ## Transferring with Underscore <ide>
1
Javascript
Javascript
use fixture files
d73a1c0b7c5b6ad4c339ebca145ad3ce850973e7
<ide><path>node-tests/blueprints/controller-test-test.js <ide> const chai = require('ember-cli-blueprint-test-helpers/chai'); <ide> const expect = chai.expect; <ide> <ide> const generateFakePackageManifest = require('../helpers/generate-fake-package-manifest'); <add>const fixture = require('../helpers/fixture'); <ide> <ide> describe('Blueprint: controller-test', function() { <ide> setupTestHooks(this); <ide> describe('Blueprint: controller-test', function() { <ide> it('controller-test foo', function() { <ide> return emberGenerateDestroy(['controller-test', 'foo'], _file => { <ide> expect(_file('tests/unit/controllers/foo-test.js')) <del> .to.contain("import { moduleFor, test } from 'ember-qunit';") <del> .to.contain("moduleFor('controller:foo'"); <add> .to.equal(fixture('controller-test/default.js')); <ide> }); <ide> }); <ide> <ide> describe('Blueprint: controller-test', function() { <ide> it('controller-test foo for mocha', function() { <ide> return emberGenerateDestroy(['controller-test', 'foo'], _file => { <ide> expect(_file('tests/unit/controllers/foo-test.js')) <del> .to.contain("import { describeModule, it } from 'ember-mocha';") <del> .to.contain("describeModule('controller:foo', 'Unit | Controller | foo'"); <add> .to.equal(fixture('controller-test/mocha.js')); <ide> }); <ide> }); <ide> }); <ide> describe('Blueprint: controller-test', function() { <ide> it('controller-test foo', function() { <ide> return emberGenerateDestroy(['controller-test', 'foo'], _file => { <ide> expect(_file('tests/unit/controllers/foo-test.js')) <del> .to.contain("import { describe, it } from 'mocha';") <del> .to.contain("import { setupTest } from 'ember-mocha';") <del> .to.contain("describe('Unit | Controller | foo'") <del> .to.contain("setupTest('controller:foo',"); <add> .to.equal(fixture('controller-test/mocha-0.12.js')); <ide> }); <ide> }); <ide> }); <ide> describe('Blueprint: controller-test', function() { <ide> it('controller-test foo', function() { <ide> return emberGenerateDestroy(['controller-test', 'foo'], _file => { <ide> expect(_file('tests/unit/controllers/foo-test.js')) <del> .to.contain("import { moduleFor, test } from 'ember-qunit';") <del> .to.contain("moduleFor('controller:foo'"); <add> .to.equal(fixture('controller-test/default.js')); <ide> }); <ide> }); <ide> }); <ide><path>node-tests/fixtures/controller-test/default.js <add>import { moduleFor, test } from 'ember-qunit'; <add> <add>moduleFor('controller:foo', 'Unit | Controller | foo', { <add> // Specify the other units that are required for this test. <add> // needs: ['controller:foo'] <add>}); <add> <add>// Replace this with your real tests. <add>test('it exists', function(assert) { <add> let controller = this.subject(); <add> assert.ok(controller); <add>}); <ide><path>node-tests/fixtures/controller-test/mocha-0.12.js <add>import { expect } from 'chai'; <add>import { describe, it } from 'mocha'; <add>import { setupTest } from 'ember-mocha'; <add> <add>describe('Unit | Controller | foo', function() { <add> setupTest('controller:foo', { <add> // Specify the other units that are required for this test. <add> // needs: ['controller:foo'] <add> }); <add> <add> // Replace this with your real tests. <add> it('exists', function() { <add> let controller = this.subject(); <add> expect(controller).to.be.ok; <add> }); <add>}); <ide><path>node-tests/fixtures/controller-test/mocha.js <add>import { expect } from 'chai'; <add>import { describeModule, it } from 'ember-mocha'; <add> <add>describeModule('controller:foo', 'Unit | Controller | foo', <add> { <add> // Specify the other units that are required for this test. <add> // needs: ['controller:foo'] <add> }, <add> function() { <add> // Replace this with your real tests. <add> it('exists', function() { <add> let controller = this.subject(); <add> expect(controller).to.be.ok; <add> }); <add> } <add>);
4
Javascript
Javascript
fix this scope bug in test-stream2-writable.js
93df0853866bbdf40cc5877ac893e2fae1479d39
<ide><path>test/parallel/test-stream2-writable.js <ide> for (let i = 0; i < chunks.length; i++) { <ide> assert.strictEqual(this.writing, undefined); <ide> wrote = true; <ide> this.writing = true; <del> setTimeout(function() { <add> setTimeout(() => { <ide> this.writing = false; <ide> cb(); <ide> }, 1); <ide> }; <ide> w.on('finish', common.mustCall(function() { <ide> assert.strictEqual(wrote, true); <add> assert.strictEqual(this.writing, false); <ide> })); <ide> w.write(Buffer.alloc(0)); <ide> w.end();
1
Python
Python
add a new bar class to display bar in curse ui
2cf140ffdb78f98c1d7443f09b58a8a4eed1ff8c
<ide><path>glances/outputs/glances_bars.py <add># -*- coding: utf-8 -*- <add># <add># This file is part of Glances. <add># <add># Copyright (C) 2015 Nicolargo <[email protected]> <add># <add># Glances is free software; you can redistribute it and/or modify <add># it under the terms of the GNU Lesser General Public License as published by <add># the Free Software Foundation, either version 3 of the License, or <add># (at your option) any later version. <add># <add># Glances is distributed in the hope that it will be useful, <add># but WITHOUT ANY WARRANTY; without even the implied warranty of <add># MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the <add># GNU Lesser General Public License for more details. <add># <add># You should have received a copy of the GNU Lesser General Public License <add># along with this program. If not, see <http://www.gnu.org/licenses/>. <add> <add>"""Manage bars for Glances output.""" <add> <add># Import system lib <add>from math import modf <add> <add># Global vars <add>curses_bars = [" ", "▏", "β–Ž", "▍", "β–Œ", "β–‹", "β–Š", "β–‰", "β–ˆ"] <add> <add> <add>class Bar(object): <add> """Manage bar (progression or status) <add> <add> import sys <add> import time <add> b = Bar(10) <add> for p in range(0, 100): <add> b.set_percent(p) <add> print("\r%s" % b), <add> time.sleep(0.1) <add> sys.stdout.flush() <add> <add> """ <add> <add> def __init__(self, size): <add> # Bar size <add> self.__size = size <add> # Bar current percent <add> self.__percent = 0 <add> <add> def get_size(self): <add> return self.__size <add> <add> def set_size(self, size): <add> self.__size = size <add> return self.__size <add> <add> def get_percent(self): <add> return self.__percent <add> <add> def set_percent(self, percent): <add> assert percent >= 0 <add> assert percent <= 100 <add> self.__percent = percent <add> return self.__percent <add> <add> def __str__(self): <add> """Return the bars""" <add> frac, whole = modf(self.get_size() * self.get_percent() / 100.0) <add> ret = curses_bars[8] * int(whole) <add> if frac > 0: <add> ret += curses_bars[int(frac * 8)] <add> whole += 1 <add> ret += '_' * int(self.get_size() - whole) <add> return ret
1
Javascript
Javascript
remove typed option loading
55117ea60705c12b240778e2753c73aea2bd002c
<ide><path>local-cli/util/Config.js <ide> const Config = { <ide> }: ConfigT), <ide> <ide> find(startDir: string): ConfigT { <del> return Config.findCustom(startDir, Config.DEFAULTS); <del> }, <del> <del> /** <del> * This allows a callsite to grab a config that may have custom fields or <del> * a different version of the config. In that case the defaults have to be <del> * specified explicitely. <del> */ <del> findCustom<TConfig: {}>(startDir: string, defaults: TConfig): TConfig { <del> return Config.findWithPathCustom(startDir, defaults).config; <add> return this.findWithPath(startDir).config; <ide> }, <ide> <ide> findWithPath(startDir: string): {config: ConfigT, projectPath: string} { <del> return Config.findWithPathCustom(startDir, Config.DEFAULTS); <del> }, <del> <del> findWithPathCustom<TConfig: {}>(startDir: string, defaults: TConfig): {config: TConfig, projectPath: string} { <ide> const configPath = findConfigPath(startDir); <ide> invariant( <ide> configPath, <ide> `Can't find "${RN_CLI_CONFIG}" file in any parent folder of "${startDir}"`, <ide> ); <ide> const projectPath = path.dirname(configPath); <del> return {config: Config.loadFileCustom(configPath, defaults), projectPath}; <add> return {config: this.loadFile(configPath, startDir), projectPath}; <ide> }, <ide> <ide> findOptional(startDir: string): ConfigT { <del> return Config.findOptionalCustom(startDir, Config.DEFAULTS); <del> }, <del> <del> findOptionalCustom<TConfig: {}>(startDir: string, defaults: TConfig): TConfig { <ide> const configPath = findConfigPath(startDir); <ide> return configPath <del> ? Config.loadFileCustom(configPath, defaults) <del> : {...defaults}; <add> ? this.loadFile(configPath, startDir) <add> : {...Config.DEFAULTS}; <ide> }, <ide> <ide> loadFile(pathToConfig: string): ConfigT { <del> return Config.loadFileCustom(pathToConfig, Config.DEFAULTS); <del> }, <del> <del> loadFileCustom<TConfig: {}>(pathToConfig: string, defaults: TConfig): TConfig { <del> // $FlowFixMe: necessary dynamic require <add> //$FlowFixMe: necessary dynamic require <ide> const config: {} = require(pathToConfig); <del> return {...defaults, ...config}; <add> return {...Config.DEFAULTS, ...config}; <ide> }, <ide> }; <ide>
1
Javascript
Javascript
upgrade aggressivesplittingplugin to es6
7dae8fbc0025935b068e222a41efc7f624765043
<ide><path>lib/optimize/AggressiveSplittingPlugin.js <ide> MIT License http://www.opensource.org/licenses/mit-license.php <ide> Author Tobias Koppers @sokra <ide> */ <del>var path = require("path"); <add>"use strict"; <ide> <del>function AggressiveSplittingPlugin(options) { <del> this.options = options || {}; <del> if(typeof this.options.minSize !== "number") this.options.minSize = 30 * 1024; <del> if(typeof this.options.maxSize !== "number") this.options.maxSize = 50 * 1024; <del> if(typeof this.options.chunkOverhead !== "number") this.options.chunkOverhead = 0; <del> if(typeof this.options.entryChunkMultiplicator !== "number") this.options.entryChunkMultiplicator = 1; <del>} <del>module.exports = AggressiveSplittingPlugin; <add>let path = require("path"); <ide> <ide> function makeRelative(context) { <ide> return function(module) { <del> var identifier = module.identifier(); <del> return identifier.split("|").map(function(str) { <del> return str.split("!").map(function(str) { <add> let identifier = module.identifier(); <add> return identifier.split("|").map((str) => { <add> return str.split("!").map((str) => { <ide> return path.relative(context, str); <ide> }).join("!"); <ide> }).join("|"); <ide> function isNotAEntryModule(entryModule) { <ide> } <ide> <ide> function copyWithReason(obj) { <del> var newObj = {}; <del> Object.keys(obj).forEach(function(key) { <add> let newObj = {}; <add> Object.keys(obj).forEach((key) => { <ide> newObj[key] = obj[key]; <ide> }); <ide> if(!newObj.reasons || newObj.reasons.indexOf("aggressive-splitted") < 0) <ide> newObj.reasons = (newObj.reasons || []).concat("aggressive-splitted"); <ide> return newObj; <ide> } <ide> <del>AggressiveSplittingPlugin.prototype.apply = function(compiler) { <del> var _this = this; <del> compiler.plugin("compilation", function(compilation) { <del> compilation.plugin("optimize-chunks-advanced", function(chunks) { <del> var i, chunk, newChunk; <del> var savedSplits = compilation.records && compilation.records.aggressiveSplits || []; <del> var usedSplits = savedSplits; <del> if(compilation._aggressiveSplittingSplits) <del> usedSplits = usedSplits.concat(compilation._aggressiveSplittingSplits); <del> var minSize = _this.options.minSize; <del> var maxSize = _this.options.maxSize; <del> // 1. try to restore to recorded splitting <del> for(var j = 0; j < usedSplits.length; j++) { <del> var splitData = usedSplits[j]; <add>class AggressiveSplittingPlugin { <add> constructor(options) { <add> this.options = options || {}; <add> if(typeof this.options.minSize !== "number") this.options.minSize = 30 * 1024; <add> if(typeof this.options.maxSize !== "number") this.options.maxSize = 50 * 1024; <add> if(typeof this.options.chunkOverhead !== "number") this.options.chunkOverhead = 0; <add> if(typeof this.options.entryChunkMultiplicator !== "number") this.options.entryChunkMultiplicator = 1; <add> } <add> apply(compiler) { <add> compiler.plugin("compilation", (compilation) => { <add> compilation.plugin("optimize-chunks-advanced", (chunks) => { <add> let i, chunk, newChunk; <add> const savedSplits = compilation.records && compilation.records.aggressiveSplits || []; <add> let usedSplits = savedSplits; <add> if(compilation._aggressiveSplittingSplits) <add> usedSplits = usedSplits.concat(compilation._aggressiveSplittingSplits); <add> const minSize = this.options.minSize; <add> const maxSize = this.options.maxSize; <add> // 1. try to restore to recorded splitting <add> for(let j = 0; j < usedSplits.length; j++) { <add> const splitData = usedSplits[j]; <add> for(i = 0; i < chunks.length; i++) { <add> chunk = chunks[i]; <add> const chunkModuleNames = chunk.modules.map(makeRelative(compiler.context)); <add> <add> if(chunkModuleNames.length < splitData.modules) <add> continue; <add> const moduleIndicies = splitData.modules.map(toIndexOf(chunkModuleNames)); <add> const hasAllModules = moduleIndicies.every((idx) => { <add> return idx >= 0; <add> }); <add> if(hasAllModules) { <add> if(chunkModuleNames.length > splitData.modules.length) { <add> const selectedModules = moduleIndicies.map(toChunkModuleIndices(chunk.modules)); <add> newChunk = compilation.addChunk(); <add> selectedModules.forEach(moveModuleBetween(chunk, newChunk)); <add> chunk.split(newChunk); <add> chunk.name = null; <add> newChunk._fromAggressiveSplitting = true; <add> if(j < savedSplits.length) <add> newChunk._fromAggressiveSplittingIndex = j; <add> if(typeof splitData.id === "number") newChunk.id = splitData.id; <add> newChunk.origins = chunk.origins.map(copyWithReason); <add> chunk.origins = chunk.origins.map(copyWithReason); <add> return true; <add> } else { <add> if(j < savedSplits.length) <add> chunk._fromAggressiveSplittingIndex = j; <add> chunk.name = null; <add> if(typeof splitData.id === "number") chunk.id = splitData.id; <add> } <add> } <add> } <add> } <add> // 2. for any other chunk which isn't splitted yet, split it <ide> for(i = 0; i < chunks.length; i++) { <ide> chunk = chunks[i]; <del> var chunkModuleNames = chunk.modules.map(makeRelative(compiler.context)); <del> <del> if(chunkModuleNames.length < splitData.modules) <del> continue; <del> var moduleIndicies = splitData.modules.map(toIndexOf(chunkModuleNames)); <del> var hasAllModules = moduleIndicies.every(function(idx) { <del> return idx >= 0; <del> }); <del> if(hasAllModules) { <del> if(chunkModuleNames.length > splitData.modules.length) { <del> var selectedModules = moduleIndicies.map(toChunkModuleIndices(chunk.modules)); <del> newChunk = compilation.addChunk(); <del> selectedModules.forEach(moveModuleBetween(chunk, newChunk)); <add> const size = chunk.size(this.options); <add> if(size > maxSize && chunk.modules.length > 1) { <add> newChunk = compilation.addChunk(); <add> const modules = chunk.modules <add> .filter(isNotAEntryModule(chunk.entryModule)) <add> .sort((a, b) => { <add> a = a.identifier(); <add> b = b.identifier(); <add> if(a > b) return 1; <add> if(a < b) return -1; <add> return 0; <add> }); <add> for(let k = 0; k < modules.length; k++) { <add> chunk.moveModule(modules[k], newChunk); <add> const newSize = newChunk.size(this.options); <add> const chunkSize = chunk.size(this.options); <add> // break early if it's fine <add> if(chunkSize < maxSize && newSize < maxSize && newSize >= minSize && chunkSize >= minSize) <add> break; <add> if(newSize > maxSize && k === 0) { <add> // break if there is a single module which is bigger than maxSize <add> break; <add> } <add> if(newSize > maxSize || chunkSize < minSize) { <add> // move it back <add> newChunk.moveModule(modules[k], chunk); <add> // check if it's fine now <add> if(newSize < maxSize && newSize >= minSize && chunkSize >= minSize) <add> break; <add> } <add> } <add> if(newChunk.modules.length > 0) { <ide> chunk.split(newChunk); <ide> chunk.name = null; <del> newChunk._fromAggressiveSplitting = true; <del> if(j < savedSplits.length) <del> newChunk._fromAggressiveSplittingIndex = j; <del> if(typeof splitData.id === "number") newChunk.id = splitData.id; <ide> newChunk.origins = chunk.origins.map(copyWithReason); <ide> chunk.origins = chunk.origins.map(copyWithReason); <add> compilation._aggressiveSplittingSplits = (compilation._aggressiveSplittingSplits || []).concat({ <add> modules: newChunk.modules.map(makeRelative(compiler.context)) <add> }); <ide> return true; <ide> } else { <del> if(j < savedSplits.length) <del> chunk._fromAggressiveSplittingIndex = j; <del> chunk.name = null; <del> if(typeof splitData.id === "number") chunk.id = splitData.id; <add> chunks.splice(chunks.indexOf(newChunk), 1); <ide> } <ide> } <ide> } <del> } <del> // 2. for any other chunk which isn't splitted yet, split it <del> for(i = 0; i < chunks.length; i++) { <del> chunk = chunks[i]; <del> var size = chunk.size(_this.options); <del> if(size > maxSize && chunk.modules.length > 1) { <del> newChunk = compilation.addChunk(); <del> var modules = chunk.modules <del> .filter(isNotAEntryModule(chunk.entryModule)) <del> .sort(function(a, b) { <del> a = a.identifier(); <del> b = b.identifier(); <del> if(a > b) return 1; <del> if(a < b) return -1; <del> return 0; <del> }); <del> for(var k = 0; k < modules.length; k++) { <del> chunk.moveModule(modules[k], newChunk); <del> var newSize = newChunk.size(_this.options); <del> var chunkSize = chunk.size(_this.options); <del> // break early if it's fine <del> if(chunkSize < maxSize && newSize < maxSize && newSize >= minSize && chunkSize >= minSize) <del> break; <del> if(newSize > maxSize && k === 0) { <del> // break if there is a single module which is bigger than maxSize <del> break; <del> } <del> if(newSize > maxSize || chunkSize < minSize) { <del> // move it back <del> newChunk.moveModule(modules[k], chunk); <del> // check if it's fine now <del> if(newSize < maxSize && newSize >= minSize && chunkSize >= minSize) <del> break; <del> } <del> } <del> if(newChunk.modules.length > 0) { <del> chunk.split(newChunk); <del> chunk.name = null; <del> newChunk.origins = chunk.origins.map(copyWithReason); <del> chunk.origins = chunk.origins.map(copyWithReason); <del> compilation._aggressiveSplittingSplits = (compilation._aggressiveSplittingSplits || []).concat({ <del> modules: newChunk.modules.map(makeRelative(compiler.context)) <add> }); <add> compilation.plugin("record-hash", (records) => { <add> // 3. save to made splittings to records <add> const minSize = this.options.minSize; <add> if(!records.aggressiveSplits) records.aggressiveSplits = []; <add> compilation.chunks.forEach((chunk) => { <add> if(chunk.hasEntryModule()) return; <add> const size = chunk.size(this.options); <add> const incorrectSize = size < minSize; <add> const modules = chunk.modules.map(makeRelative(compiler.context)); <add> if(typeof chunk._fromAggressiveSplittingIndex === "undefined") { <add> if(incorrectSize) return; <add> chunk.recorded = true; <add> records.aggressiveSplits.push({ <add> modules: modules, <add> hash: chunk.hash, <add> id: chunk.id <ide> }); <del> return true; <ide> } else { <del> chunks.splice(chunks.indexOf(newChunk), 1); <del> } <del> } <del> } <del> }); <del> compilation.plugin("record-hash", function(records) { <del> // 3. save to made splittings to records <del> var minSize = _this.options.minSize; <del> if(!records.aggressiveSplits) records.aggressiveSplits = []; <del> compilation.chunks.forEach(function(chunk) { <del> if(chunk.hasEntryModule()) return; <del> var size = chunk.size(_this.options); <del> var incorrectSize = size < minSize; <del> var modules = chunk.modules.map(makeRelative(compiler.context)); <del> if(typeof chunk._fromAggressiveSplittingIndex === "undefined") { <del> if(incorrectSize) return; <del> chunk.recorded = true; <del> records.aggressiveSplits.push({ <del> modules: modules, <del> hash: chunk.hash, <del> id: chunk.id <del> }); <del> } else { <del> var splitData = records.aggressiveSplits[chunk._fromAggressiveSplittingIndex]; <del> if(splitData.hash !== chunk.hash || incorrectSize) { <del> if(chunk._fromAggressiveSplitting) { <del> chunk._aggressiveSplittingInvalid = true; <del> splitData.invalid = true; <del> } else { <del> splitData.hash = chunk.hash; <add> let splitData = records.aggressiveSplits[chunk._fromAggressiveSplittingIndex]; <add> if(splitData.hash !== chunk.hash || incorrectSize) { <add> if(chunk._fromAggressiveSplitting) { <add> chunk._aggressiveSplittingInvalid = true; <add> splitData.invalid = true; <add> } else { <add> splitData.hash = chunk.hash; <add> } <ide> } <ide> } <del> } <del> }); <del> records.aggressiveSplits = records.aggressiveSplits.filter(function(splitData) { <del> return !splitData.invalid; <add> }); <add> records.aggressiveSplits = records.aggressiveSplits.filter((splitData) => { <add> return !splitData.invalid; <add> }); <ide> }); <del> }); <del> compilation.plugin("need-additional-seal", function(callback) { <del> var invalid = this.chunks.some(function(chunk) { <del> return chunk._aggressiveSplittingInvalid; <add> compilation.plugin("need-additional-seal", (callback) => { <add> const invalid = compilation.chunks.some((chunk) => { <add> return chunk._aggressiveSplittingInvalid; <add> }); <add> if(invalid) <add> return true; <ide> }); <del> if(invalid) <del> return true; <ide> }); <del> }); <del>}; <add> } <add>} <add>module.exports = AggressiveSplittingPlugin;
1
Ruby
Ruby
improve sorbet typing
8c762d96879d598eaeb9e78abefadb2b6619f631
<ide><path>Library/Homebrew/dev-cmd/contributions.rb <ide> def contributions_args <ide> end <ide> end <ide> <del> sig { returns(NilClass) } <add> sig { void } <ide> def contributions <ide> args = contributions_args.parse <ide>
1
Ruby
Ruby
store the symbols as an array
91f2ad36821cc01d2084dd1690fecc0913fc541d
<ide><path>actionview/lib/action_view/template/types.rb <ide> module ActionView <ide> class Template <ide> class Types <ide> class Type <del> SET = Struct.new(:symbols).new(Set.new([ :html, :text, :js, :css, :xml, :json ])) <add> SET = Struct.new(:symbols).new([ :html, :text, :js, :css, :xml, :json ]) <ide> <ide> def self.[](type) <ide> if type.is_a?(self)
1
Javascript
Javascript
add a ply exporter
447130ed160595cc72167db1ed1cd5f4da656b1b
<ide><path>examples/js/exporters/PLYExporter.js <add>/** <add> * @author Garrett Johnson / http://gkjohnson.github.io/ <add> * https://github.com/gkjohnson/ply-exporter-js <add> * <add> * Usage: <add> * var exporter = new THREE.PLYExporter(); <add> * <add> * // second argument is an array of attributes to <add> * // exclude from the format ('color', 'uv', 'normal') <add> * var data = exporter.parse(mesh, [ 'color' ]); <add> * <add> * Format Definition: <add> * http://paulbourke.net/dataformats/ply/ <add> */ <add> <add>THREE.PLYExporter = function () {}; <add> <add>THREE.PLYExporter.prototype = { <add> <add> constructor: THREE.PLYExporter, <add> <add> parse: function ( object, excludeProperties ) { <add> <add> if ( Array.isArray( excludeProperties ) !== true ) { <add> <add> excludeProperties = []; <add> <add> } <add> <add> var includeNormals = excludeProperties.indexOf( 'normal' ) === - 1; <add> var includeColors = excludeProperties.indexOf( 'color' ) === - 1; <add> var includeUVs = excludeProperties.indexOf( 'uv' ) === - 1; <add> <add> // count the number of vertices <add> var vertexCount = 0; <add> var faceCount = 0; <add> var vertexList = ''; <add> var faceList = ''; <add> <add> var vertex = new THREE.Vector3(); <add> var normalMatrixWorld = new THREE.Matrix3(); <add> object.traverse( function ( child ) { <add> <add> if ( child instanceof THREE.Mesh ) { <add> <add> var mesh = child; <add> var geometry = mesh.geometry; <add> <add> if ( geometry instanceof THREE.Geometry ) { <add> <add> geometry = new THREE.BufferGeometry().setFromObject( mesh ); <add> <add> } <add> <add> if ( geometry instanceof THREE.BufferGeometry ) { <add> <add> var vertices = geometry.getAttribute( 'position' ); <add> var normals = geometry.getAttribute( 'normal' ); <add> var uvs = geometry.getAttribute( 'uv' ); <add> var colors = geometry.getAttribute( 'color' ); <add> var indices = geometry.getIndex(); <add> <add> normalMatrixWorld.getNormalMatrix( mesh.matrixWorld ); <add> <add> if ( vertices === undefined ) { <add> <add> return; <add> <add> } <add> <add> // form each line <add> for ( i = 0, l = vertices.count; i < l; i ++ ) { <add> <add> vertex.x = vertices.getX( i ); <add> vertex.y = vertices.getY( i ); <add> vertex.z = vertices.getZ( i ); <add> <add> vertex.applyMatrix4( mesh.matrixWorld ); <add> <add> <add> // Position information <add> var line = <add> vertex.x + ' ' + <add> vertex.y + ' ' + <add> vertex.z; <add> <add> // Normal information <add> if ( includeNormals === true ) { <add> <add> if ( normals !== undefined ) { <add> <add> vertex.x = normals.getX( i ); <add> vertex.y = normals.getY( i ); <add> vertex.z = normals.getZ( i ); <add> <add> vertex.applyMatrix3( normalMatrixWorld ); <add> <add> line += ' ' + <add> vertex.x + ' ' + <add> vertex.y + ' ' + <add> vertex.z; <add> <add> } else { <add> <add> line += ' 0 0 0'; <add> <add> } <add> <add> } <add> <add> // UV information <add> if ( includeUVs === true ) { <add> <add> if ( uvs !== undefined ) { <add> <add> line += ' ' + <add> uvs.getX( i ) + ' ' + <add> uvs.getY( i ); <add> <add> } else if ( includeUVs !== false ) { <add> <add> line += ' 0 0'; <add> <add> } <add> <add> } <add> <add> // Color information <add> if ( includeColors === true ) { <add> <add> if ( colors !== undefined ) { <add> <add> line += ' ' + <add> Math.floor( colors.getX( i ) ) + ' ' + <add> Math.floor( colors.getY( i ) ) + ' ' + <add> Math.floor( colors.getZ( i ) ); <add> <add> } else { <add> <add> line += ' 255 255 255'; <add> <add> } <add> <add> } <add> <add> vertexList += line + '\n'; <add> <add> } <add> <add> <add> // Create the face list <add> if ( indices !== null ) { <add> <add> for ( i = 0, l = indices.count; i < l; i += 3 ) { <add> <add> faceList += `3 ${ indices.getX( i + 0 ) + vertexCount }`; <add> faceList += ` ${ indices.getX( i + 1 ) + vertexCount }`; <add> faceList += ` ${ indices.getX( i + 2 ) + vertexCount }\n`; <add> <add> } <add> <add> } else { <add> <add> for ( var i = 0, l = vertices.count; i < l; i += 3 ) { <add> <add> faceList += `3 ${ vertexCount + i } ${ vertexCount + i + 1 } ${ vertexCount + i + 2 }\n`; <add> <add> } <add> <add> } <add> <add> vertexCount += vertices.count; <add> faceCount += indices ? indices.count / 3 : vertices.count / 3; <add> <add> } <add> <add> } <add> <add> } ); <add> <add> var output = <add> 'ply\n' + <add> 'format ascii 1.0\n' + <add> `element vertex ${vertexCount}\n` + <add> <add> // position <add> 'property float x\n' + <add> 'property float y\n' + <add> 'property float z\n'; <add> <add> if ( includeNormals === true ) { <add> <add> // normal <add> output += <add> 'property float nx\n' + <add> 'property float ny\n' + <add> 'property float nz\n'; <add> <add> } <add> <add> if ( includeUVs === true ) { <add> <add> // uvs <add> output += <add> 'property float s\n' + <add> 'property float t\n'; <add> <add> } <add> <add> if ( includeColors === true ) { <add> <add> // colors <add> output += <add> 'property uchar red\n' + <add> 'property uchar green\n' + <add> 'property uchar blue\n'; <add> <add> } <add> <add> // faces <add> output += <add> `element face ${faceCount}\n` + <add> 'property list uchar int vertex_index\n' + <add> 'end_header\n' + <add> <add> `${vertexList}\n` + <add> `${faceList}\n`; <add> <add> return output; <add> <add> } <add> <add>};
1
Text
Text
fix custom parser example
f161241e077b4a19e79be6b4b01b8cc26a9a54e1
<ide><path>docs/api-guide/parsers.md <ide> By default this will include the following keys: `view`, `request`, `args`, `kwa <ide> The following is an example plaintext parser that will populate the `request.data` property with a string representing the body of the request. <ide> <ide> class PlainTextParser(BaseParser): <del> """ <del> Plain text parser. <del> """ <del> <del> media_type = 'text/plain' <del> <del> def parse(self, stream, media_type=None, parser_context=None): <ide> """ <del> Simply return a string representing the body of the request. <add> Plain text parser. <ide> """ <del> return stream.read() <add> media_type = 'text/plain' <add> <add> def parse(self, stream, media_type=None, parser_context=None): <add> """ <add> Simply return a string representing the body of the request. <add> """ <add> return stream.read() <ide> <ide> --- <ide>
1
PHP
PHP
fix controller tests
055b574d8678316f5c3aa1155810777cd4cb7bf1
<ide><path>src/Controller/Component/PaginatorComponent.php <ide> public function implementedEvents() <ide> * $results = $paginator->paginate($query); <ide> * ``` <ide> * <add> * ### Scoping Request parameters <add> * <add> * By using request parameter scopes you can paginate multiple queries in the same controller action: <add> * <add> * ``` <add> * $articles = $paginator->paginate($articlesQuery, ['scope' => 'articles']); <add> * $tags = $paginator->paginate($tagsQuery, ['scope' => 'tags']); <add> * ``` <add> * <add> * Each of the above queries will use different query string parameter sets <add> * for pagination data. An example URL paginating both results would be: <add> * <add> * ``` <add> * /dashboard?articles[page]=1&tags[page]=2 <add> * ``` <add> * <ide> * @param \Cake\Datasource\RepositoryInterface|\Cake\Datasource\QueryInterface $object The table or query to paginate. <ide> * @param array $settings The settings/configuration used for pagination. <ide> * @return \Cake\Datasource\ResultSetInterface Query results <ide><path>tests/TestCase/Controller/ControllerTest.php <ide> public function testPaginate() <ide> $Controller = new Controller($request, $response); <ide> $Controller->request->query = [ <ide> 'url' => [], <del> 'prefix' => [ <add> 'posts' => [ <ide> 'page' => 2, <ide> 'limit' => 2, <ide> ] <ide> public function testPaginate() <ide> $this->assertSame($Controller->request->params['paging']['Posts']['pageCount'], 1); <ide> $this->assertSame($Controller->request->params['paging']['Posts']['prevPage'], false); <ide> $this->assertSame($Controller->request->params['paging']['Posts']['nextPage'], false); <add> $this->assertNull($Controller->request->params['paging']['Posts']['scope']); <ide> <del> $results = $Controller->paginate(TableRegistry::get('Posts'), ['prefix' => 'prefix']); <add> $results = $Controller->paginate(TableRegistry::get('Posts'), ['scope' => 'posts']); <ide> $this->assertInstanceOf('Cake\Datasource\ResultSetInterface', $results); <ide> $this->assertCount(1, $results); <ide> <ide> $this->assertSame($Controller->request->params['paging']['Posts']['page'], 2); <ide> $this->assertSame($Controller->request->params['paging']['Posts']['pageCount'], 2); <ide> $this->assertSame($Controller->request->params['paging']['Posts']['prevPage'], true); <ide> $this->assertSame($Controller->request->params['paging']['Posts']['nextPage'], false); <add> $this->assertSame($Controller->request->params['paging']['Posts']['scope'], 'posts'); <ide> } <ide> <ide> /**
2
Python
Python
remove duplicate code
4002f95eb66622a048ff01a383968af57023134d
<ide><path>examples/token-classification/run_ner_no_trainer.py <ide> def compute_metrics(): <ide> predictions=preds, <ide> references=refs, <ide> ) # predictions and preferences are expected to be a nested list of labels, not label_ids <del> preds, refs = get_labels(predictions_gathered, labels_gathered) <del> metric.add_batch( <del> predictions=preds, <del> references=refs, <del> ) # predictions and preferences are expected to be a nested list <ide> <ide> # eval_metric = metric.compute() <ide> eval_metric = compute_metrics()
1
Ruby
Ruby
remove chicken support
1ad2aeef86e6f0261a55d588a658a084a8f31ede
<ide><path>Library/Homebrew/dependency_collector.rb <ide> class DependencyCollector <ide> # Define the languages that we can handle as external dependencies. <ide> LANGUAGE_MODULES = Set[ <del> :chicken, :jruby, :lua, :node, :ocaml, :perl, :python, :python3, :ruby <add> :jruby, :lua, :node, :ocaml, :perl, :python, :python3, :ruby <ide> ].freeze <ide> <ide> CACHE = {} <ide><path>Library/Homebrew/requirements/language_module_requirement.rb <ide> def message; <<-EOS.undent <ide> <ide> def the_test <ide> case @language <del> when :chicken then %W[/usr/bin/env csi -e (use\ #{@import_name})] <ide> when :jruby then %W[/usr/bin/env jruby -rubygems -e require\ '#{@import_name}'] <ide> when :lua then %W[/usr/bin/env luarocks-5.2 show #{@import_name}] <ide> when :lua51 then %W[/usr/bin/env luarocks-5.1 show #{@import_name}] <ide> def the_test <ide> <ide> def command_line <ide> case @language <del> when :chicken then "chicken-install" <ide> when :jruby then "jruby -S gem install" <ide> when :lua then "luarocks-5.2 install" <ide> when :lua51 then "luarocks-5.1 install" <ide><path>Library/Homebrew/test/test_language_module_requirement.rb <ide> def test_good_ruby_deps <ide> assert_deps_pass "date" => :ruby <ide> end <ide> <del> if which("csc") <del> def test_bad_chicken_deps <del> assert_deps_fail "notapackage" => :chicken <del> end <del> <del> def test_good_chicken_deps <del> assert_deps_pass "extras" => :chicken <del> end <del> end <del> <ide> if which("node") <ide> def test_bad_node_deps <ide> assert_deps_fail "notapackage" => :node
3
PHP
PHP
fix doc block
cb077bddfa88429c2ea6e5f69af527457262e655
<ide><path>src/View/ViewBuilder.php <ide> public function setClassName($name) <ide> /** <ide> * Gets the view classname. <ide> * <del> * @return string <add> * @return string|null <ide> */ <ide> public function getClassName() <ide> {
1