hash
stringlengths
40
40
diff
stringlengths
131
114k
message
stringlengths
7
980
project
stringlengths
5
67
split
stringclasses
1 value
7909721d01b402983412462302ec0ac28f83371c
diff --git a/flask_oauthlib/contrib/client/application.py b/flask_oauthlib/contrib/client/application.py index <HASH>..<HASH> 100644 --- a/flask_oauthlib/contrib/client/application.py +++ b/flask_oauthlib/contrib/client/application.py @@ -165,8 +165,8 @@ class OAuth1Application(BaseApplication): object. """ if isinstance(token, dict): - access_token = token['token'] - access_token_secret = token['token_secret'] + access_token = token['oauth_token'] + access_token_secret = token['oauth_token_secret'] else: access_token, access_token_secret = token return self.make_oauth_session(
Contrib-OAuth1: use the key defined in token responses.
lepture_flask-oauthlib
train
e13ad1816007e1700dc70fd6bb1ddcfdd75ac39d
diff --git a/cmd/influxd/run/command_test.go b/cmd/influxd/run/command_test.go index <HASH>..<HASH> 100644 --- a/cmd/influxd/run/command_test.go +++ b/cmd/influxd/run/command_test.go @@ -22,13 +22,21 @@ func TestCommand_PIDFile(t *testing.T) { cmd := run.NewCommand() cmd.Getenv = func(key string) string { switch key { + case "INFLUXDB_DATA_DIR": + return filepath.Join(tmpdir, "data") + case "INFLUXDB_META_DIR": + return filepath.Join(tmpdir, "meta") + case "INFLUXDB_DATA_WAL_DIR": + return filepath.Join(tmpdir, "wal") case "INFLUXDB_BIND_ADDRESS", "INFLUXDB_HTTP_BIND_ADDRESS": return "127.0.0.1:0" + case "INFLUXDB_REPORTING_DISABLED": + return "true" default: return os.Getenv(key) } } - if err := cmd.Run("-pidfile", pidFile); err != nil { + if err := cmd.Run("-pidfile", pidFile, "-config", os.DevNull); err != nil { t.Fatalf("unexpected error: %s", err) }
Use the isolated temp dir for the test pid server
influxdata_influxdb
train
7153d4b5899230042fac8c3f00a86a36b6af4dc1
diff --git a/src/main/java/org/cp/elements/lang/reflect/support/MethodInvokingMethodInterceptor.java b/src/main/java/org/cp/elements/lang/reflect/support/MethodInvokingMethodInterceptor.java index <HASH>..<HASH> 100644 --- a/src/main/java/org/cp/elements/lang/reflect/support/MethodInvokingMethodInterceptor.java +++ b/src/main/java/org/cp/elements/lang/reflect/support/MethodInvokingMethodInterceptor.java @@ -26,6 +26,7 @@ import org.cp.elements.lang.reflect.MethodInvocation; * the {@link Method} on a specified target {@link Object}. * * @author John Blum + * @see java.lang.Object * @see java.lang.reflect.Method * @see org.cp.elements.lang.reflect.MethodInterceptor * @see org.cp.elements.lang.reflect.MethodInvocation @@ -37,12 +38,11 @@ public class MethodInvokingMethodInterceptor implements MethodInterceptor { private final Object target; /** - * Factory method to construct an instance of {@link MethodInvokingMethodInterceptor} initialized + * Factory method used to construct an instance of {@link MethodInvokingMethodInterceptor} initialized * with the given target {@link Object} on which the {@link Method} invocation will be called. * - * @param target target {@link Object} of the {@link Method} invocation. - * @return a new instance of {@link MethodInvokingMethodInterceptor} initialized with - * the given target {@link Object}. + * @param target {@link Object} on which the {@link Method} will be invoked. + * @return a new instance of {@link MethodInvokingMethodInterceptor} initialized with the given target {@link Object}. * @see org.cp.elements.lang.reflect.support.MethodInvokingMethodInterceptor * @see #MethodInvokingMethodInterceptor(Object) * @see java.lang.Object @@ -65,7 +65,7 @@ public class MethodInvokingMethodInterceptor implements MethodInterceptor { /** * Constructs an instance of the {@link MethodInvokingMethodInterceptor} initialized with - * the given target {@link Object} used in the actual {@link Method} invocation. + * the given target {@link Object} on which the {@link Method} will be invoked. * * @param target {@link Object} used as the target of the {@link Method} invocation. * @see java.lang.Object @@ -87,6 +87,6 @@ public class MethodInvokingMethodInterceptor implements MethodInterceptor { */ @Override public Object intercept(MethodInvocation methodInvocation) { - return methodInvocation.invoke(getTarget()); + return methodInvocation.makeAccessible().invoke(getTarget()); } } diff --git a/src/test/java/org/cp/elements/lang/reflect/support/MethodInvokingMethodInterceptorTests.java b/src/test/java/org/cp/elements/lang/reflect/support/MethodInvokingMethodInterceptorTests.java index <HASH>..<HASH> 100644 --- a/src/test/java/org/cp/elements/lang/reflect/support/MethodInvokingMethodInterceptorTests.java +++ b/src/test/java/org/cp/elements/lang/reflect/support/MethodInvokingMethodInterceptorTests.java @@ -94,7 +94,7 @@ public class MethodInvokingMethodInterceptorTests { @Data @RequiredArgsConstructor(staticName = "newAgeCalculator") @SuppressWarnings("unused") - public static class AgeCalculator { + static class AgeCalculator { @NonNull private final LocalDate birthDate;
Refactor the MethodInvokingMethodInterceptor.intercept(:MethodInvocation) method to call MethodInvocation.makeAccessible(). Refactor Javadoc comments in MethodInvokingMethodInterceptor. Remove the public access modifier on the AgeCalculator inner class of the MethodInvokingMethodInterceptorTests.
codeprimate-software_cp-elements
train
8673a298b6e131f7198094f901b82ffeec3f24e7
diff --git a/library/client.js b/library/client.js index <HASH>..<HASH> 100644 --- a/library/client.js +++ b/library/client.js @@ -1233,7 +1233,25 @@ client.prototype.api.root = { }; client.prototype.api.search = { - + channels: function channels(query, limit, offset) { + query = typeof query !== 'undefined' ? query : ''; + limit = typeof limit !== 'undefined' ? limit : 10; + offset = typeof offset !== 'undefined' ? offset : 0; + return apiAnonymousCall('https://api.twitch.tv/kraken/search/channels?q='+query+'&limit=' + limit + '&offset=' + offset, true); + }, + streams: function streams(query, limit, offset, hls) { + query = typeof query !== 'undefined' ? query : ''; + limit = typeof limit !== 'undefined' ? limit : 10; + offset = typeof offset !== 'undefined' ? offset : 0; + hls = typeof hls !== 'undefined' ? hls : false; + return apiAnonymousCall('https://api.twitch.tv/kraken/search/streams?q='+query+'&limit=' + limit + '&offset=' + offset+'&hls='+hls, true); + }, + games: function games(query, type, live) { + query = typeof query !== 'undefined' ? query : ''; + type = typeof type !== 'undefined' ? type : 'suggest'; + live = typeof live !== 'undefined' ? live : false; + return apiAnonymousCall('https://api.twitch.tv/kraken/search/games?q='+query+'&type='+type+'&live='+live, true); + } }; client.prototype.api.streams = {
Added Twitch API - Search.
twitch-irc_twitch-irc
train
5c4bb1e246532012ef3d81d3fdc982b526110ad2
diff --git a/src/bootstrap/ForceGdprVerificationBootstrap.php b/src/bootstrap/ForceGdprVerificationBootstrap.php index <HASH>..<HASH> 100644 --- a/src/bootstrap/ForceGdprVerificationBootstrap.php +++ b/src/bootstrap/ForceGdprVerificationBootstrap.php @@ -28,11 +28,11 @@ class ForceGdprVerificationBootstrap implements BootstrapInterface return; } - if ($app->user->getIsGuest()) { - return; - } - $app->on(Application::EVENT_BEFORE_ACTION, function (ActionEvent $event) use ($app) { + if ($app->user->getIsGuest()) { + return; + } + if ($app->request->getIsAjax()) { return; }
Enhanced ForceGdprVerificationBootstrap to check user later -> enhance performance
hiqdev_hipanel-module-client
train
67cf6df9b238f23e6d2509d5a791a0d722321520
diff --git a/acstools/acsphotcte.py b/acstools/acsphotcte.py index <HASH>..<HASH> 100644 --- a/acstools/acsphotcte.py +++ b/acstools/acsphotcte.py @@ -55,7 +55,7 @@ number of Y transfers is 2048 and so we scale by 2048. >>> print(cte_corrected_magnitudes[:5]) [-10.85516545 -9.68284332 -10.11060704 -9.11828746 -10.4918177 ] """ -from collections import Iterable +from collections.abc import Iterable import json import logging
Fixes deprecation warning with importing Iterable
spacetelescope_acstools
train
214c885b90722708db6a3febbbb80f90c8750eb2
diff --git a/server/build/webpack.js b/server/build/webpack.js index <HASH>..<HASH> 100644 --- a/server/build/webpack.js +++ b/server/build/webpack.js @@ -72,7 +72,7 @@ export default async function createCompiler (dir, { hotReload = false, dev = fa } const babelRuntimePath = require.resolve('babel-runtime/package') - .replace(/[\\\/]package\.json$/, '') + .replace(/[\\/]package\.json$/, '') const loaders = [{ test: /\.js$/,
remove unnecessary escape character for lint
zeit_next.js
train
c3a6fdd5f5e1d2b5f11a62de86566e19e2e93660
diff --git a/lib/brightbox-cli/api.rb b/lib/brightbox-cli/api.rb index <HASH>..<HASH> 100644 --- a/lib/brightbox-cli/api.rb +++ b/lib/brightbox-cli/api.rb @@ -30,6 +30,8 @@ module Brightbox elsif m.respond_to? :attributes and m.respond_to? :id @fog_model = m @id = m.id + elsif m.is_a?(Hash) && m["id"] + @id = m["id"] else raise InvalidArguments, "Can't initialize #{self.class} with #{m.inspect}" end
Handle a hash response from requests
brightbox_brightbox-cli
train
1e024aa70a9591f9a0ebab8f4a8d4a6f761bc8da
diff --git a/axiom/attributes.py b/axiom/attributes.py index <HASH>..<HASH> 100644 --- a/axiom/attributes.py +++ b/axiom/attributes.py @@ -855,6 +855,9 @@ class reference(integer): _cascadingDeletes.setdefault(reftype, []).append(self) def reprFor(self, oself): + obj = getattr(oself, self.underlying, None) + if obj is not None: + return 'reference(%d)' % (obj.storeID,) sid = getattr(oself, self.dbunderlying, None) if sid is None: return 'None' diff --git a/axiom/item.py b/axiom/item.py index <HASH>..<HASH> 100644 --- a/axiom/item.py +++ b/axiom/item.py @@ -326,7 +326,7 @@ class Item(Empowered, slotmachine._Strict): L = [self.__name__] L.append('(') A = [] - for nam, atr in self.getSchema(): + for nam, atr in sorted(self.getSchema()): try: V = atr.reprFor(self) except: @@ -338,7 +338,7 @@ class Item(Empowered, slotmachine._Strict): A.append('storeID=' + str(self.storeID)) L.append(', '.join(A)) L.append(')') - L.append('@' + hex(unsignedID(self))) + L.append('@0x%X' % unsignedID(self)) return ''.join(L)
Merge Axiom portion of pottery-persistence-<I> Author: exarkun Reviewer: glyph This makes Item.__repr__ deterministically order attributes and fixes reference to show only-in-memory reference values.
twisted_axiom
train
8733a8b8f21489e4437abce688ca8efce87adfcc
diff --git a/lib/github-auth.js b/lib/github-auth.js index <HASH>..<HASH> 100644 --- a/lib/github-auth.js +++ b/lib/github-auth.js @@ -243,7 +243,7 @@ function githubRequest(request, url, query, cb) { 'Accept': 'application/vnd.github.v3+json', }; - const githubToken = globalToken === null ? getReqRemainingToken() : globalToken; + const githubToken = globalToken === undefined ? getReqRemainingToken() : globalToken; if (githubToken != null) { // Typically, GitHub user tokens grants us 12500 req/hour.
Use GitHub token rotation in production :P (#<I>)
badges_shields
train
f749185055dd6f7c332ebee85a2511479de559f0
diff --git a/examples/tf_adder_tb.py b/examples/tf_adder_tb.py index <HASH>..<HASH> 100755 --- a/examples/tf_adder_tb.py +++ b/examples/tf_adder_tb.py @@ -18,9 +18,7 @@ Benchmark done, tensorboard at http://127.0.0.1:6006 To run on AWS aws configure # or set AWS_ACCESS_KEY_ID/AWS_SECRET_ACCESS_KEY/AWS_DEFAULT_REGION -export NCLUSTER_BACKEND=aws -export NCLUSTER_IMAGE="Deep Learning AMI (Amazon Linux) Version 13.0" -./tf_adder_tb +./tf_adder_tb.py --aws After a minute should see something like this @@ -41,6 +39,8 @@ parser.add_argument("--data-mb", default=128, help="size of vector in MBs") parser.add_argument("--sender-ip", default='127.0.0.1') parser.add_argument("--receiver-ip", default='127.0.0.1') parser.add_argument("--logdir", help='logging directory') +parser.add_argument("--aws", action='store_true') +parser.add_argument('--image', default='Deep Learning AMI (Amazon Linux) Version 13.0') args = parser.parse_args() cluster_spec = {'chief': [args.sender_ip + ':32300'], @@ -60,7 +60,9 @@ def _launch_server(role): def run_launcher(): import ncluster - job = ncluster.make_job('tf_adder_tb', num_tasks=2) + if args.aws: + ncluster.set_backend('aws') + job = ncluster.make_job('tf_adder_tb', num_tasks=2, image_name=args.image) job.upload(__file__) this_file = os.path.basename(__file__)
simplify AWS tf adder example
diux-dev_ncluster
train
1ccbd16f8d9833f53d0360bfdb9005fec99f5575
diff --git a/beeper/cmd.py b/beeper/cmd.py index <HASH>..<HASH> 100644 --- a/beeper/cmd.py +++ b/beeper/cmd.py @@ -141,7 +141,7 @@ def build(version, compress, conf): run(script) for file in conf['manifest']: - run('$WORK_DIR; cp -r %s $BUILD_DIR/' % file) + run('cd $WORK_DIR; cp -r %s $BUILD_DIR/' % file) manifest_files = ' '.join( conf['manifest'] | set(['install.sh', '.beeper-data'])
bugfix for missing cd.
soasme_beeper.py
train
72afdfc57d8f1d26fc3002055bb3397010360eb0
diff --git a/shinken/satellite.py b/shinken/satellite.py index <HASH>..<HASH> 100644 --- a/shinken/satellite.py +++ b/shinken/satellite.py @@ -79,7 +79,7 @@ from shinken.external_command import ExternalCommand # Pack of common Pyro exceptions Pyro_exp_pack = (Pyro.errors.ProtocolError, Pyro.errors.URIError, \ Pyro.errors.CommunicationError, \ - Pyro.errors.DaemonError) + Pyro.errors.DaemonError, Pyro.errors.ConnectionClosedError) # Class for say we are facing a non worker module @@ -332,13 +332,13 @@ class Satellite(BaseSatellite): if con is not None: # None = not initialized send_ok = con.put_results(ret) # Not connected or sched is gone - except (Pyro.errors.ProtocolError, KeyError) , exp: + except (Pyro_exp_pack, KeyError) , exp: print exp self.pynag_con_init(sched_id) return except AttributeError , exp: # the scheduler must not be initialized print exp - except Exception , exp: + except Exception, exp: print "Unknown exception", exp, type(exp) try: if PYRO_VERSION < "4.0":
Fix : (reported by : Thibaut Notteboom) catch ConnectionClosedError on poller/reactionner connections
Alignak-monitoring_alignak
train
550798cd3b082a28452a385f5c67f6474c5aa247
diff --git a/pact/pact-runtime/src/test/java/eu/stratosphere/pact/runtime/sort/UnilateralSortMergerITCase.java b/pact/pact-runtime/src/test/java/eu/stratosphere/pact/runtime/sort/UnilateralSortMergerITCase.java index <HASH>..<HASH> 100644 --- a/pact/pact-runtime/src/test/java/eu/stratosphere/pact/runtime/sort/UnilateralSortMergerITCase.java +++ b/pact/pact-runtime/src/test/java/eu/stratosphere/pact/runtime/sort/UnilateralSortMergerITCase.java @@ -46,12 +46,9 @@ import eu.stratosphere.pact.runtime.test.util.types.IntPair; import eu.stratosphere.pact.runtime.test.util.types.IntPairComparator; import eu.stratosphere.pact.runtime.test.util.types.IntPairSerializer; -/** - * @author Erik Nijkamp - * @author Stephan Ewen - */ -public class UnilateralSortMergerITCase -{ + +public class UnilateralSortMergerITCase { + private static final Log LOG = LogFactory.getLog(UnilateralSortMergerITCase.class); private static final long SEED = 649180756312423613L; @@ -106,8 +103,7 @@ public class UnilateralSortMergerITCase // -------------------------------------------------------------------------------------------- @Test - public void testInMemorySort() throws Exception - { + public void testInMemorySort() throws Exception { // comparator final Comparator<TestData.Key> keyComparator = new TestData.KeyComparator(); @@ -153,8 +149,7 @@ public class UnilateralSortMergerITCase } @Test - public void testInMemorySortUsing10Buffers() throws Exception - { + public void testInMemorySortUsing10Buffers() throws Exception { // comparator final Comparator<TestData.Key> keyComparator = new TestData.KeyComparator(); @@ -200,8 +195,7 @@ public class UnilateralSortMergerITCase } @Test - public void testSpillingSort() throws Exception - { + public void testSpillingSort() throws Exception { // comparator final Comparator<TestData.Key> keyComparator = new TestData.KeyComparator(); @@ -246,9 +240,8 @@ public class UnilateralSortMergerITCase merger.close(); } - @Test - public void testSpillingSortWithIntermediateMerge() throws Exception - { +// @Test + public void testSpillingSortWithIntermediateMerge() throws Exception { // amount of pairs final int PAIRS = 10000000; @@ -301,7 +294,7 @@ public class UnilateralSortMergerITCase merger.close(); } - @Test +// @Test public void testSpillingSortWithIntermediateMergeIntPair() throws Exception { // amount of pairs final int PAIRS = 50000000;
Temporarily accellerated external-sorter tests.
stratosphere_stratosphere
train
312630195b009a09b4727195a20d8a8e1440abde
diff --git a/src/main/java/org/metacsp/multi/spatioTemporal/paths/Quaternion.java b/src/main/java/org/metacsp/multi/spatioTemporal/paths/Quaternion.java index <HASH>..<HASH> 100644 --- a/src/main/java/org/metacsp/multi/spatioTemporal/paths/Quaternion.java +++ b/src/main/java/org/metacsp/multi/spatioTemporal/paths/Quaternion.java @@ -123,5 +123,65 @@ public class Quaternion implements Serializable { public double getW() { return w; } + + /** + * Get the norm of this {@link Quaternion}. + * @return The norm of this {@link Quaternion}. + */ + public double norm() { + return Math.sqrt(x*x + y*y + z*z + w*w); + } + + /** + * Get the conjugate of this {@link Quaternion}. + * @return The conjugate of this {@link Quaternion}. + */ + public Quaternion conjugate() { + return new Quaternion(x, -y, -z, -w); + } + + /** + * Add this and another {@link Quaternion}s. + * @param other A {@link Quaternion} to add to this {@link Quaternion}. + * @return The sum of this and the given {@link Quaternion}. + */ + public Quaternion plus(Quaternion other) { + return new Quaternion(this.x+other.x, this.y+other.y, this.z+other.z, this.w+other.w); + } + + /** + * Get a new {@link Quaternion} whose value is (<code>this</code> * <code>other</code>). + * @param other A {@link Quaternion} to multiply by. + * @return A new {@link Quaternion} whose value is (<code>this</code> * <code>other</code>). + */ + public Quaternion times(Quaternion other) { + double x = this.x*other.x - this.y*other.y - this.z*other.z - this.w*other.w; + double y = this.x*other.y + this.y*other.x + this.z*other.w - this.w*other.z; + double z = this.x*other.z - this.y*other.w + this.z*other.x + this.w*other.y; + double w = this.x*other.w + this.y*other.z - this.z*other.y + this.w*other.x; + return new Quaternion(x,y,z,w); + } + + /** + * Get this inverse of this {@link Quaternion}. + * @return The inverse of this {@link Quaternion}. + */ + public Quaternion inverse() { + double d = x*x + y*y + z*z + w*w; + return new Quaternion(x/d, -y/d, -z/d, -w/d); + } + + /** + * Get a new {@link Quaternion} whose value is <code>this</code> * <code>inverse(other)</code>. + * @param other A {@link Quaternion} to divide by. + * @return A new {@link Quaternion} whose value is <code>this</code> * <code>inverse(other)</code>. + */ + public Quaternion divide(Quaternion other) { + return this.times(other.inverse()); + } + + public String toString() { + return x + " + " + y + "i + " + z + "j + " + w + "k"; + } }
Added Quaternion util functions
FedericoPecora_meta-csp-framework
train
ad17e166cac2863692af96bccf0317d97e102e24
diff --git a/tests/integration/test_juju.py b/tests/integration/test_juju.py index <HASH>..<HASH> 100644 --- a/tests/integration/test_juju.py +++ b/tests/integration/test_juju.py @@ -19,3 +19,4 @@ async def test_get_controllers(event_loop): cc = await j.get_controller(controller.controller_name) assert isinstance(cc, Controller) assert controller.connection().endpoint == cc.connection().endpoint + await cc.disconnect()
Make sure to disconnect the extra connection before finishing the test
juju_python-libjuju
train
fd03fbd2f979cdd028783b274aa817426fc25234
diff --git a/lib/ProgressPlugin.js b/lib/ProgressPlugin.js index <HASH>..<HASH> 100644 --- a/lib/ProgressPlugin.js +++ b/lib/ProgressPlugin.js @@ -476,14 +476,26 @@ class ProgressPlugin { interceptHook(compiler.hooks.initialize, 0.0, "initialize"); interceptHook(compiler.hooks.beforeRun, 0.01, "before run"); interceptHook(compiler.hooks.run, 0.02, "run"); - interceptHook(compiler.hooks.watchRun, 0.02, "run"); - interceptHook(compiler.hooks.beforeCompile, 0.03, "before compile"); + interceptHook(compiler.hooks.watchRun, 0.02, "watch run"); + interceptHook( + compiler.hooks.normalModuleFactory, + 0.03, + "normal module factory" + ); + interceptHook( + compiler.hooks.contextModuleFactory, + 0.03, + "context module factory" + ); + interceptHook(compiler.hooks.beforeCompile, 0.035, "before compile"); interceptHook(compiler.hooks.compile, 0.04, "compile"); interceptHook(compiler.hooks.thisCompilation, 0.05, "setup compilation"); interceptHook(compiler.hooks.compilation, 0.06, "setup compilation"); + interceptHook(compiler.hooks.make, 0.71, " make"); interceptHook(compiler.hooks.emit, 0.95, "emitting"); interceptHook(compiler.hooks.afterEmit, 0.98, "after emitting"); interceptHook(compiler.hooks.done, 0.99, "done"); + interceptHook(compiler.hooks.watchClose, 0.99, "closing watch compilation"); compiler.hooks.done.intercept({ name: "ProgressPlugin", done() { diff --git a/test/ProgressPlugin.test.js b/test/ProgressPlugin.test.js index <HASH>..<HASH> 100644 --- a/test/ProgressPlugin.test.js +++ b/test/ProgressPlugin.test.js @@ -7,7 +7,7 @@ const captureStdio = require("./helpers/captureStdio"); let webpack; -describe("ProgressPlugin", function () { +describe("ProgressPlugin", function() { let stderr; let stdout; @@ -85,6 +85,18 @@ describe("ProgressPlugin", function () { }); }); + it("should contain the new compiler hooks", () => { + const compiler = createSimpleCompiler(); + + process.stderr.columns = undefined; + return RunCompilerAsync(compiler).then(() => { + const logs = getLogs(stderr.toString()); + + expect(logs).toContain("3% normal module factory"); + expect(logs).toContain("3% context module factory"); + }); + }); + it("should display all type of percentage when it is applied to SingleCompiler", () => { const compiler = createSimpleCompiler({ entries: true,
chore: added more compiler hooks progress
webpack_webpack
train
41cb82398d54221f150bc9ab9c22d4a25eb6c31f
diff --git a/src/JSTACK.Nova.js b/src/JSTACK.Nova.js index <HASH>..<HASH> 100644 --- a/src/JSTACK.Nova.js +++ b/src/JSTACK.Nova.js @@ -333,12 +333,7 @@ JSTACK.Nova = (function (JS, undefined) { } if (networks !== undefined) { - for (i in networks) { - if (networks[i] !== undefined) { - nets.push(networks[i]); - } - } - data.server.network = nets; + data.server.networks = networks; } onOK = function (result) {
Resolved a problem launching images with networks
ging_jstack
train
abb82ab25e63b8c30d149c4202396b5fb09eb61e
diff --git a/packages/@vue/cli-service/__tests__/Service.spec.js b/packages/@vue/cli-service/__tests__/Service.spec.js index <HASH>..<HASH> 100644 --- a/packages/@vue/cli-service/__tests__/Service.spec.js +++ b/packages/@vue/cli-service/__tests__/Service.spec.js @@ -52,6 +52,18 @@ test('load project options from package.json', () => { expect(service.projectOptions.lintOnSave).toBe(true) }) +test('handle option baseUrl and outputDir correctly', () => { + mockPkg({ + vue: { + baseUrl: 'https://foo.com/bar', + outputDir: '/public/' + } + }) + const service = createMockService() + expect(service.projectOptions.baseUrl).toBe('https://foo.com/bar/') + expect(service.projectOptions.outputDir).toBe('public') +}) + test('load project options from vue.config.js', () => { process.env.VUE_CLI_SERVICE_CONFIG_PATH = `/vue.config.js` fs.writeFileSync('/vue.config.js', `module.exports = { lintOnSave: false }`) diff --git a/packages/@vue/cli-service/lib/Service.js b/packages/@vue/cli-service/lib/Service.js index <HASH>..<HASH> 100644 --- a/packages/@vue/cli-service/lib/Service.js +++ b/packages/@vue/cli-service/lib/Service.js @@ -222,10 +222,12 @@ module.exports = class Service { } function ensureSlash (config, key) { - if (typeof config[key] === 'string') { - config[key] = config[key] - .replace(/^([^/.])/, '/$1') - .replace(/([^/])$/, '$1/') + let val = config[key] + if (typeof val === 'string') { + if (!/^https?:/.test(val)) { + val = val.replace(/^([^/.])/, '/$1') + } + config[key] = val.replace(/([^/])$/, '$1/') } }
fix(cli-service): should not add a leading slash to baseUrl when it is absolute (#<I>) fix #<I>
vuejs_vue-cli
train
cdf1875c2c3d52c40c95121367cab54bea55a9d1
diff --git a/Model/ResourceModel/NodeType/Product.php b/Model/ResourceModel/NodeType/Product.php index <HASH>..<HASH> 100644 --- a/Model/ResourceModel/NodeType/Product.php +++ b/Model/ResourceModel/NodeType/Product.php @@ -78,7 +78,7 @@ class Product extends AbstractNode public function fetchImageData($storeId, $productIds = []) { $collection = $this->productCollection->create(); - $collection->addAttributeToSelect(['thumbnail']) + $collection->addAttributeToSelect(['thumbnail'], 'left') ->addFieldToFilter('entity_id', ['in' => $productIds]) ->addStoreFilter($storeId);
Fix product node image issue #<I> (MR #<I>)
SnowdogApps_magento2-menu
train
b3b7bdb5b9853c3a0db5030697ea8a90e9f41cb7
diff --git a/test/common/base/index.js b/test/common/base/index.js index <HASH>..<HASH> 100755 --- a/test/common/base/index.js +++ b/test/common/base/index.js @@ -274,12 +274,6 @@ describe('base', function () { }) }) - it('should be able to differentiate an empty array from an empty object', function () { - var one = new Base({}) - var two = new Base([]) - expect(one).not.deep.equal(two) - }) - require('./output.js') require('./property.js') }) diff --git a/test/common/observable/emitter/overwrites/input.js b/test/common/observable/emitter/overwrites/input.js index <HASH>..<HASH> 100644 --- a/test/common/observable/emitter/overwrites/input.js +++ b/test/common/observable/emitter/overwrites/input.js @@ -89,9 +89,9 @@ describe('input', function () { expect(cnt).to.equal(0) }) - // so why does context not have the correct data??? - // and what are the implications? - // same for always emitting instances -- how much heavier does it make things + // // so why does context not have the correct data??? + // // and what are the implications? + // // same for always emitting instances -- how much heavier does it make things it('context, block update on context', function () { // console.clear() var cnt = 0 @@ -115,4 +115,24 @@ describe('input', function () { a.b.val = 'this is b!' expect(cnt).to.equal(1) }) + + it('instance, block update on instance, nested, property', function () { + console.clear() + var cnt = 0 + var a = new Observable({ + key: 'a', + on: { + property (data) { + cnt++ + } + } + }) + var b = new a.Constructor({ //eslint-disable-line + key: 'b', + randomField: true + }) + cnt = 0 + a.set({ randomField: 'this is a!' }) + expect(cnt).to.equal(1) + }) })
removed array thing, there is no difference in vigour objects if you want an array make a list object (with all methods like push, pop etc) marcus made the strt look back 2 months in vjs
vigour-io_vjs
train
9a734be3e42a330142b9e4de376783189e4675d3
diff --git a/spec/model.rb b/spec/model.rb index <HASH>..<HASH> 100644 --- a/spec/model.rb +++ b/spec/model.rb @@ -723,7 +723,7 @@ describe 'A created DBI::Model subclass instance' do end mc.id.should.not.be.nil mc.c1.should.equal 123 - mc.class.should.equal DBI::Model + mc.class.should.equal @m_conflict mc.class_.should.equal 'Mammalia' mc.dup.should.equal mc should.raise do
Corrected class check in Model spec.
Pistos_m4dbi
train
258e3f305975e51723238f27558b3bd96373b1e7
diff --git a/dataset/persistence/table.py b/dataset/persistence/table.py index <HASH>..<HASH> 100644 --- a/dataset/persistence/table.py +++ b/dataset/persistence/table.py @@ -231,6 +231,9 @@ class Table(object): yield row def __len__(self): + """ + Returns the number of rows in the table. + """ d = self.database.query(self.table.count()).next() return d.values().pop() @@ -268,3 +271,14 @@ class Table(object): rows = table.all()""" return self.find() + + def __iter__(self): + """ + Allows for iterating over all rows in the table without explicelty calling :py:meth:`all() <dataset.Table.all>`. + :: + + for row in table: + print row + """ + for row in self.all(): + yield row
Allowing for direct iteration over rows in a table
pudo_dataset
train
46b4fd87cca3b3e95a941fcf8501a5b5662c91d4
diff --git a/lib/api/2011-02-01/configuration.js b/lib/api/2011-02-01/configuration.js index <HASH>..<HASH> 100644 --- a/lib/api/2011-02-01/configuration.js +++ b/lib/api/2011-02-01/configuration.js @@ -1,6 +1,7 @@ var path = require('path'); var nroonga = require('../../wrapped-nroonga'); var Domain = require('../../database').Domain; +var IndexField = require('../../database').IndexField; var dateFormat = require('dateformat'); var xmlbuilder = require('../../xmlbuilder'); var ipv4 = require('../../ipv4'); @@ -281,25 +282,20 @@ function createIndexFieldStatus(options) { return indexFieldStatus; } -var TEXT_TYPE_FIELD_OPTIONS = [ - 'IndexField.TextOptions.DefaultValue', - 'IndexField.TextOptions.FacetEnabled', - 'IndexField.TextOptions.ResultEnabled' - ]; -var LITERAL_TYPE_FIELD_OPTIONS = [ - 'IndexField.LiteralOptions.DefaultValue', - 'IndexField.LiteralOptions.FacetEnabled', - 'IndexField.LiteralOptions.ResultEnabled', - 'IndexField.LiteralOptions.SearchEnabled' - ]; -var UINT_TYPE_FIELD_OPTIONS = [ - 'IndexField.LiteralOptions.DefaultValue' - ]; +var TEXT_FIELD_OPTIONS = IndexField.TEXT_FIELD_OPTIONS.map(function(option) { + return 'IndexField.TextOptions.' + option; + }); +var LITERAL_FIELD_OPTIONS = IndexField.LITERAL_FIELD_OPTIONS.map(function(option) { + return 'IndexField.LiteralOptions.' + option; + }); +var UINT_FIELD_OPTIONS = IndexField.UINT_FIELD_OPTIONS.map(function(option) { + return 'IndexField.UIntOptions.' + option; + }); function assertValidFieldOptions(request, type, domainName) { - var validOptions = type == 'text' ? TEXT_TYPE_FIELD_OPTIONS : - type == 'literal' ? LITERAL_TYPE_FIELD_OPTIONS : - UINT_TYPE_FIELD_OPTIONS; + var validOptions = type == 'text' ? TEXT_FIELD_OPTIONS : + type == 'literal' ? LITERAL_FIELD_OPTIONS : + UINT_FIELD_OPTIONS; var options = Object.keys(request.query).filter(function(name) { return /^IndexField\.[^\.]+Options\./.test(name); diff --git a/lib/database/index-field.js b/lib/database/index-field.js index <HASH>..<HASH> 100644 --- a/lib/database/index-field.js +++ b/lib/database/index-field.js @@ -40,6 +40,29 @@ var RESERVED_COLUMN_NAMES = '_key' ]; + +var TEXT_FIELD_OPTIONS = + IndexField.TEXT_FIELD_OPTIONS = + exports.TEXT_FIELD_OPTIONS = [ + 'DefaultValue', + 'FacetEnabled', + 'ResultEnabled' + ]; +var LITERAL_FIELD_OPTIONS = + IndexField.LITERAL_FIELD_OPTIONS = + exports.LITERAL_OPTIONS = [ + 'DefaultValue', + 'FacetEnabled', + 'ResultEnabled', + 'SearchEnabled' + ]; +var UINT_FIELD_OPTIONS = + IndexField.UINT_FIELD_OPTIONS = + exports.UINT_FIELD_OPTIONS = [ + 'DefaultValue' + ]; + + function assertValidFieldName(field) { if (typeof field != 'string') { var error = new Error('field name name must be a string');
Define list of valid options as class method of IndexField
groonga_gcs
train
bbb376c24ac38536c88184559e46723732508221
diff --git a/ibis/backends/tests/test_aggregation.py b/ibis/backends/tests/test_aggregation.py index <HASH>..<HASH> 100644 --- a/ibis/backends/tests/test_aggregation.py +++ b/ibis/backends/tests/test_aggregation.py @@ -683,14 +683,17 @@ def test_agg_sort(alltypes): def test_filter(backend, alltypes, df): expr = ( alltypes[_.string_col == "1"] - .group_by(_.bigint_col) + .mutate(x=L(1, "int64")) + .group_by(_.x) .aggregate(_.double_col.sum()) ) - result = expr.execute() + # TODO: The pyspark backend doesn't apply schemas to outputs + result = expr.execute().astype({"x": "int64"}) expected = ( df.loc[df.string_col == "1", :] - .groupby("bigint_col") + .assign(x=1) + .groupby("x") .double_col.sum() .rename("sum") .reset_index() diff --git a/ibis/expr/types/groupby.py b/ibis/expr/types/groupby.py index <HASH>..<HASH> 100644 --- a/ibis/expr/types/groupby.py +++ b/ibis/expr/types/groupby.py @@ -60,7 +60,10 @@ class GroupedTable: self, table, by, having=None, order_by=None, window=None, **expressions ): self.table = table - self.by = util.promote_list(by if by is not None else []) + [ + self.by = [ + _get_group_by_key(table, v) + for v in util.promote_list(by if by is not None else []) + ] + [ _get_group_by_key(table, v).name(k) for k, v in sorted(expressions.items(), key=toolz.first) ] diff --git a/ibis/expr/types/relations.py b/ibis/expr/types/relations.py index <HASH>..<HASH> 100644 --- a/ibis/expr/types/relations.py +++ b/ibis/expr/types/relations.py @@ -343,9 +343,24 @@ class Table(Expr): op = self.op().aggregate( self, - metrics, - by=util.promote_list(by if by is not None else []), - having=util.promote_list(having if having is not None else []), + [ + metric + if util.is_iterable(metric) + else self._ensure_expr(metric) + for metric in metrics + ], + by=list( + map( + self._ensure_expr, + util.promote_list(by if by is not None else []), + ) + ), + having=list( + map( + self._ensure_expr, + util.promote_list(having if having is not None else []), + ) + ), ) return op.to_expr()
fix(api): ensure that `Deferred` objects work in aggregations
ibis-project_ibis
train
fadc2a42c0d78eba4ee1153df073b1374655cdd8
diff --git a/lib/Parser.php b/lib/Parser.php index <HASH>..<HASH> 100644 --- a/lib/Parser.php +++ b/lib/Parser.php @@ -13,7 +13,7 @@ class Parser const SEPARATOR_OF_CLASS_AND_METHOD = "->"; const HTTP_METHOD = '(?<httpMethod>GET|POST|\*)'; const URI = '(?<url>(\/[a-zA-Z0-9]+|\/\[string\]|\/\[numeric\]|\/)*(#[a-zA-Z0-9]+)?)'; - const _CALLABLE = '(?<callable>[a-zA-Z]+[_a-zA-Z0-9]*->[_a-zA-Z]+[_a-zA-Z0-9]*)'; + const _CALLABLE = '(?<callable>([a-zA-Z]*\\\\)*[a-zA-Z]+[_a-zA-Z0-9]*->[_a-zA-Z]+[_a-zA-Z0-9]*)'; const ROUTE_FORMAT = '^%s[ \t]*%s[ \t]*%s^'; /** * @var bool @@ -33,7 +33,7 @@ class Parser */ private static function getRegularExpression() { - return $routeRegularExpression = sprintf(self::ROUTE_FORMAT, self::HTTP_METHOD, self::URI, self::_CALLABLE); + return sprintf(self::ROUTE_FORMAT, self::HTTP_METHOD, self::URI, self::_CALLABLE); } /**
Expanded regexp of callable for finding possible namespace
timtegeler_routerunner
train
a24bfeb3a8b9fd7aa274bbba3a914d38ab1818fc
diff --git a/Text/BlingMedia.php b/Text/BlingMedia.php index <HASH>..<HASH> 100644 --- a/Text/BlingMedia.php +++ b/Text/BlingMedia.php @@ -233,11 +233,11 @@ class sb_Text_BlingMedia extends sb_Text_Bling{ $uniqid = 'mp3'.uniqid(); if(self::$mobile ==1){ - $mp3 = '<object width="180" height="90"><param name="movie" value="'.self::$custom_mp3_player.'?file='.$mp3.'" /><param name="wmode" value="transparent" /><embed src="'.self::$custom_flv_player.'?file='.$mp3.'" type="application/x-shockwave-flash" wmode="transparent" width="180" height="90"></embed></object>'; + $mp3 = '<object width="180" height="90"><param name="movie" value="'.self::$custom_mp3_player.'?file='.$mp3.'" /><param name="wmode" value="transparent" /><embed src="'.self::$custom_mp3_player.'?file='.$mp3.'" type="application/x-shockwave-flash" wmode="transparent" width="180" height="90"></embed></object><p><a href="'.$mp3.'">::DOWNLOAD SOUND::</a></p>'; } else { self::$javascript .='var mp3 = new sb.swf({src:"'.self::$custom_mp3_player.'?file='.$mp3.'",width:"180", height:"90", bgColor:"#000000", version:6, alt: \' <a href="'.$mp3.'">::DOWNLOAD SOUND::</a> \'});mp3.embed("#'.$uniqid.'");mp3=null;'; - $mp3 = '<p id="'.$uniqid.'"></p>'; + $mp3 = '<p id="'.$uniqid.'"></p><p><a href="'.$mp3.'">::DOWNLOAD SOUND::</a></p>'; }
both textbling mobile and regular media now support sound file download and proper player is used in mobile site
surebert_surebert-framework
train
b76c925d9080215bcba9c0013e1df370e7c43ae4
diff --git a/DependencyInjection/Configuration.php b/DependencyInjection/Configuration.php index <HASH>..<HASH> 100644 --- a/DependencyInjection/Configuration.php +++ b/DependencyInjection/Configuration.php @@ -98,6 +98,7 @@ class Configuration implements ConfigurationInterface children()-> arrayNode($os)-> children()-> + scalarNode("timeout")->defaultValue(60)->end()-> booleanNode("sandbox")->defaultFalse()->end()-> scalarNode("pem")->isRequired()->cannotBeEmpty()->end()-> scalarNode("passphrase")->defaultValue("")->end()-> diff --git a/Resources/config/ios.xml b/Resources/config/ios.xml index <HASH>..<HASH> 100644 --- a/Resources/config/ios.xml +++ b/Resources/config/ios.xml @@ -15,6 +15,7 @@ <argument>%rms_push_notifications.ios.pem%</argument> <argument>%rms_push_notifications.ios.passphrase%</argument> <argument>%rms_push_notifications.ios.json_unescaped_unicode%</argument> + <argument>%rms_push_notifications.ios.timeout%</argument> <tag name="rms_push_notifications.handler" osType="rms_push_notifications.os.ios" /> </service> @@ -23,6 +24,7 @@ <argument>%rms_push_notifications.ios.sandbox%</argument> <argument>%rms_push_notifications.ios.pem%</argument> <argument>%rms_push_notifications.ios.passphrase%</argument> + <argument>%rms_push_notifications.ios.timeout%</argument> </service> diff --git a/Resources/config/mac.xml b/Resources/config/mac.xml index <HASH>..<HASH> 100644 --- a/Resources/config/mac.xml +++ b/Resources/config/mac.xml @@ -15,6 +15,7 @@ <argument>%rms_push_notifications.mac.pem%</argument> <argument>%rms_push_notifications.mac.passphrase%</argument> <argument>%rms_push_notifications.mac.json_unescaped_unicode%</argument> + <argument>%rms_push_notifications.mac.timeout%</argument> <tag name="rms_push_notifications.handler" osType="rms_push_notifications.os.mac" /> </service> </services> diff --git a/Service/OS/AppleNotification.php b/Service/OS/AppleNotification.php index <HASH>..<HASH> 100644 --- a/Service/OS/AppleNotification.php +++ b/Service/OS/AppleNotification.php @@ -58,6 +58,13 @@ class AppleNotification implements OSNotificationServiceInterface protected $jsonUnescapedUnicode = FALSE; /** + * Connection timeout + * + * @var int + */ + protected $timeout; + + /** * Collection of the responses from the APN * * @var array @@ -71,7 +78,7 @@ class AppleNotification implements OSNotificationServiceInterface * @param $pem * @param $passphrase */ - public function __construct($sandbox, $pem, $passphrase = "", $jsonUnescapedUnicode = FALSE) + public function __construct($sandbox, $pem, $passphrase = "", $jsonUnescapedUnicode = FALSE, $timeout = 60) { $this->useSandbox = $sandbox; $this->pem = $pem; @@ -80,6 +87,7 @@ class AppleNotification implements OSNotificationServiceInterface $this->messages = array(); $this->lastMessageId = -1; $this->jsonUnescapedUnicode = $jsonUnescapedUnicode; + $this->timeout = $timeout; } /** @@ -193,7 +201,7 @@ class AppleNotification implements OSNotificationServiceInterface if (!isset($this->apnStreams[$apnURL])) { // No stream found, setup a new stream $ctx = $this->getStreamContext(); - $this->apnStreams[$apnURL] = stream_socket_client($apnURL, $err, $errstr, 60, STREAM_CLIENT_CONNECT, $ctx); + $this->apnStreams[$apnURL] = stream_socket_client($apnURL, $err, $errstr, $this->timeout, STREAM_CLIENT_CONNECT, $ctx); if (!$this->apnStreams[$apnURL]) { throw new \RuntimeException("Couldn't connect to APN server. Error no $err: $errstr"); } diff --git a/Service/iOSFeedback.php b/Service/iOSFeedback.php index <HASH>..<HASH> 100644 --- a/Service/iOSFeedback.php +++ b/Service/iOSFeedback.php @@ -28,17 +28,26 @@ class iOSFeedback protected $passphrase; /** + * Connection timeout + * + * @var int + */ + protected $timeout; + + /** * Constructor * * @param $sandbox * @param $pem * @param $passphrase + * @param $timeout */ - public function __construct($sandbox, $pem, $passphrase) + public function __construct($sandbox, $pem, $passphrase, $timeout) { $this->sandbox = $sandbox; $this->pem = $pem; $this->passphrase = $passphrase; + $this->timeout = $timeout; } /** @@ -61,7 +70,7 @@ class iOSFeedback $data = ""; $ctx = $this->getStreamContext(); - $fp = stream_socket_client($feedbackURL, $err, $errstr, 60, STREAM_CLIENT_CONNECT|STREAM_CLIENT_PERSISTENT, $ctx); + $fp = stream_socket_client($feedbackURL, $err, $errstr, $this->timeout, STREAM_CLIENT_CONNECT|STREAM_CLIENT_PERSISTENT, $ctx); if (!$fp) { throw new \RuntimeException("Couldn't connect to APNS Feedback service. Error no $err: $errstr"); }
Add timeout to iOS and Mac. The iOS feedback service uses the iOS configuration as before.
richsage_RMSPushNotificationsBundle
train
272c53a56adbca55d22c7686d179d0ccd3f98107
diff --git a/languagetool-office-extension/src/main/java/org/languagetool/openoffice/Main.java b/languagetool-office-extension/src/main/java/org/languagetool/openoffice/Main.java index <HASH>..<HASH> 100644 --- a/languagetool-office-extension/src/main/java/org/languagetool/openoffice/Main.java +++ b/languagetool-office-extension/src/main/java/org/languagetool/openoffice/Main.java @@ -39,6 +39,7 @@ import com.sun.star.lang.IllegalArgumentException; import com.sun.star.linguistic2.LinguServiceEvent; import com.sun.star.linguistic2.LinguServiceEventFlags; import com.sun.star.text.TextMarkupType; + import org.jetbrains.annotations.Nullable; import org.languagetool.JLanguageTool; import org.languagetool.Language; @@ -89,6 +90,8 @@ public class Main extends WeakBase implements XJobExecutor, // e.g. language ="qlt" country="ES" variant="ca-ES-valencia": private static final String LIBREOFFICE_SPECIAL_LANGUAGE_TAG = "qlt"; + private static final int MAX_SUGGESTIONS = 15; + private static boolean testMode; private final List<XLinguServiceEventListener> xEventListeners; @@ -488,8 +491,14 @@ public class Main extends WeakBase implements XJobExecutor, aError.aShortComment = org.languagetool.gui.Tools .shortenComment(aError.aShortComment); - aError.aSuggestions = ruleMatch.getSuggestedReplacements().toArray( - new String[ruleMatch.getSuggestedReplacements().size()]); + int numSuggestions = ruleMatch.getSuggestedReplacements().size(); + String[] allSuggestions = ruleMatch.getSuggestedReplacements().toArray( + new String[numSuggestions]); + if (numSuggestions > MAX_SUGGESTIONS) { + aError.aSuggestions = Arrays.copyOfRange(allSuggestions, 0, MAX_SUGGESTIONS); + } else { + aError.aSuggestions = allSuggestions; + } aError.nErrorStart = ruleMatch.getFromPos() + startIndex; aError.nErrorLength = ruleMatch.getToPos() - ruleMatch.getFromPos(); aError.aRuleIdentifier = ruleMatch.getRule().getId();
[office-extension] limit the number of shown suggestions
languagetool-org_languagetool
train
4df96338ede62da8ae8c188de5454b4b6b186ff8
diff --git a/activemodel/lib/active_model/attribute_methods.rb b/activemodel/lib/active_model/attribute_methods.rb index <HASH>..<HASH> 100644 --- a/activemodel/lib/active_model/attribute_methods.rb +++ b/activemodel/lib/active_model/attribute_methods.rb @@ -165,6 +165,7 @@ module ActiveModel end end end + @attribute_methods_generated = true end def undefine_attribute_methods @@ -176,7 +177,6 @@ module ActiveModel def generated_attribute_methods #:nodoc: @generated_attribute_methods ||= begin - @attribute_methods_generated = true mod = Module.new include mod mod diff --git a/activemodel/test/cases/attribute_methods_test.rb b/activemodel/test/cases/attribute_methods_test.rb index <HASH>..<HASH> 100644 --- a/activemodel/test/cases/attribute_methods_test.rb +++ b/activemodel/test/cases/attribute_methods_test.rb @@ -4,6 +4,15 @@ class ModelWithAttributes include ActiveModel::AttributeMethods attribute_method_suffix '' + + def attributes + { :foo => 'value of foo' } + end + +private + def attribute(name) + attributes[name.to_sym] + end end class ModelWithAttributes2 @@ -17,4 +26,21 @@ class AttributeMethodsTest < ActiveModel::TestCase assert_not_equal ModelWithAttributes.send(:attribute_method_matchers), ModelWithAttributes2.send(:attribute_method_matchers) end + + test '#define_attribute_methods generates attribute methods' do + ModelWithAttributes.define_attribute_methods([:foo]) + + assert ModelWithAttributes.attribute_methods_generated? + assert ModelWithAttributes.new.respond_to?(:foo) + assert_equal "value of foo", ModelWithAttributes.new.foo + end + + test '#undefine_attribute_methods removes attribute methods' do + ModelWithAttributes.define_attribute_methods([:foo]) + ModelWithAttributes.undefine_attribute_methods + + assert !ModelWithAttributes.attribute_methods_generated? + assert !ModelWithAttributes.new.respond_to?(:foo) + assert_raises(NoMethodError) { ModelWithAttributes.new.foo } + end end
Fixed behavior of attribute_methods_generated? [#<I> state:resolved]
rails_rails
train
82c17c837fd11aaa9ab5015bb618e28d6a6a3aa5
diff --git a/src/GameQ/Protocols/Bf3.php b/src/GameQ/Protocols/Bf3.php index <HASH>..<HASH> 100644 --- a/src/GameQ/Protocols/Bf3.php +++ b/src/GameQ/Protocols/Bf3.php @@ -41,7 +41,8 @@ class Bf3 extends Protocol protected $packets = [ self::PACKET_STATUS => "\x00\x00\x00\x21\x1b\x00\x00\x00\x01\x00\x00\x00\x0a\x00\x00\x00serverInfo\x00", self::PACKET_VERSION => "\x00\x00\x00\x22\x18\x00\x00\x00\x01\x00\x00\x00\x07\x00\x00\x00version\x00", - self::PACKET_PLAYERS => "\x00\x00\x00\x23\x24\x00\x00\x00\x02\x00\x00\x00\x0b\x00\x00\x00listPlayers\x00\x03\x00\x00\x00\x61ll\x00", + self::PACKET_PLAYERS => + "\x00\x00\x00\x23\x24\x00\x00\x00\x02\x00\x00\x00\x0b\x00\x00\x00listPlayers\x00\x03\x00\x00\x00\x61ll\x00", ]; /**
PHPCS fix for bf3
Austinb_GameQ
train
48db25e659682671caf72929abe477a6abe09c13
diff --git a/tests/custom_object_test.py b/tests/custom_object_test.py index <HASH>..<HASH> 100644 --- a/tests/custom_object_test.py +++ b/tests/custom_object_test.py @@ -74,8 +74,8 @@ class AbstractSparseArray(core.ShapedArray): def indices(self): return sp_indices_p.bind(self) -def abstract_sparse_array(arr): - return AbstractSparseArray(arr.shape, arr.dtype, arr.index_dtype, arr.nnz) +class ConcreteSparseArray(AbstractSparseArray): + pass def sparse_array_result_handler(device, aval): def build_sparse_array(data_buf, indices_buf): @@ -96,9 +96,9 @@ def sparse_array_device_put_handler(a, device): xla.xb.get_device_backend(device).buffer_from_pyval(a.indices, device) ) -core.pytype_aval_mappings[SparseArray] = abstract_sparse_array +core.pytype_aval_mappings[SparseArray] = lambda x: x.aval core.raise_to_shaped_mappings[AbstractSparseArray] = lambda aval, _: aval -xla.pytype_aval_mappings[SparseArray] = abstract_sparse_array +xla.pytype_aval_mappings[SparseArray] = lambda x: x.aval xla.canonicalize_dtype_handlers[SparseArray] = lambda x: x xla.device_put_handlers[SparseArray] = sparse_array_device_put_handler xla.xla_result_handlers[AbstractSparseArray] = sparse_array_result_handler @@ -199,13 +199,13 @@ class AbstractEmpty(core.AbstractValue): def __eq__(self, other): return isinstance(other, AbstractEmpty) +class ConcreteEmpty(AbstractEmpty): + pass -def abstract_empty(e): - return AbstractEmpty() -core.pytype_aval_mappings[Empty] = abstract_empty +core.pytype_aval_mappings[Empty] = lambda x: ConcreteEmpty() core.raise_to_shaped_mappings[AbstractEmpty] = lambda aval, _: aval -xla.pytype_aval_mappings[Empty] = abstract_empty +xla.pytype_aval_mappings[Empty] = lambda x: AbstractEmpty() xla.canonicalize_dtype_handlers[Empty] = lambda x: x xla.device_put_handlers[Empty] = lambda _, __: () xla.xla_result_handlers[AbstractEmpty] = lambda _, __: lambda: Empty(AbstractEmpty())
[multi-buf] simplify custom object test avals
tensorflow_probability
train
5cdfac0e0c7ea8d2f83e92524fc3336219c2ebb3
diff --git a/Event/Subscriber/ExtraConfigurationSubscriber.php b/Event/Subscriber/ExtraConfigurationSubscriber.php index <HASH>..<HASH> 100644 --- a/Event/Subscriber/ExtraConfigurationSubscriber.php +++ b/Event/Subscriber/ExtraConfigurationSubscriber.php @@ -74,6 +74,11 @@ class ExtraConfigurationSubscriber implements EventSubscriberInterface $configuration = $event->getConfiguration(); // current action admin $admin = $event->getAdmin(); + // allowed actions according to the admin + $keys = $admin + ->getConfiguration() + ->getActions(); + $allowedActions = array_keys($keys); // if no field was provided in configuration, we try to take fields from doctrine metadata if (empty($configuration['fields']) || !count($configuration['fields'])) { @@ -100,13 +105,45 @@ class ExtraConfigurationSubscriber implements EventSubscriberInterface $configuration['fields'] = $fields; } } + if (array_key_exists('_actions', $configuration['fields']) + && !array_key_exists('type', $configuration['fields']['_actions']) + ) { + + if ($event->getActionName() == 'list') { + + if (in_array('edit', $allowedActions)) { + $configuration['fields']['_actions']['type'] = 'collection'; + $configuration['fields']['_actions']['options']['_edit'] = [ + 'type' => 'action', + 'options' => [ + 'title' => $this->applicationConfiguration->getTranslationKey('edit', $event->getAdmin()->getName()), + 'route' => $admin->generateRouteName('edit'), + 'parameters' => [ + 'id' => false + ], + 'icon' => 'pencil' + ] + ]; + } + if (in_array('delete', $allowedActions)) { + $configuration['fields']['_actions']['type'] = 'collection'; + $configuration['fields']['_actions']['options']['_delete'] = [ + 'type' => 'action', + 'options' => [ + 'title' => $this->applicationConfiguration->getTranslationKey('delete', $event->getAdmin()->getName()), + 'route' => $admin->generateRouteName('delete'), + 'parameters' => [ + 'id' => false + ], + 'icon' => 'remove' + ] + ]; + } + } + } // add default menu actions if none was provided if (empty($configuration['actions'])) { - $keys = $admin - ->getConfiguration() - ->getActions(); - $allowedActions = array_keys($keys); - + // by default, in list action we add a create linked action if ($event->getActionName() == 'list') { if (in_array('create', $allowedActions)) { $configuration['actions']['create'] = [
adding default edit and delete actions for default list action configuration
larriereguichet_AdminBundle
train
c001fadd2f2f420267db809439581e388684e9de
diff --git a/lib/arel/visitors/to_sql.rb b/lib/arel/visitors/to_sql.rb index <HASH>..<HASH> 100644 --- a/lib/arel/visitors/to_sql.rb +++ b/lib/arel/visitors/to_sql.rb @@ -254,6 +254,10 @@ key on UpdateManager using UpdateManager#key= "(#{visit o.expr})" end + def visit_Arel_SelectManager o + "(#{o.to_sql.rstrip})" + end + def visit_Arel_Nodes_Ascending o "#{visit o.expr} ASC" end diff --git a/test/visitors/test_to_sql.rb b/test/visitors/test_to_sql.rb index <HASH>..<HASH> 100644 --- a/test/visitors/test_to_sql.rb +++ b/test/visitors/test_to_sql.rb @@ -126,6 +126,11 @@ module Arel @visitor.accept(nil).must_be_like "NULL" end + it "should visit_Arel_SelectManager, which is a subquery" do + mgr = Table.new(:foo).project(:bar) + @visitor.accept(mgr).must_be_like '(SELECT bar FROM "foo")' + end + it "should visit_Arel_Nodes_And" do node = Nodes::And.new [@attr.eq(10), @attr.eq(11)] @visitor.accept(node).must_be_like %{
to_sql: add support for emitting SQL subqueries
rails_rails
train
b79868d4e28cbd8c2a9a90facad56663ef6af00f
diff --git a/AdvancedHTMLParser/constants.py b/AdvancedHTMLParser/constants.py index <HASH>..<HASH> 100644 --- a/AdvancedHTMLParser/constants.py +++ b/AdvancedHTMLParser/constants.py @@ -82,7 +82,7 @@ TAG_NAMES_TO_ADDITIONAL_ATTRIBUTES = { # TODO: input->size is an integer through dot-access, also throws exception on invalid value # TODO: input->size has a minimum value of 1 # TODO: input->src is a url can be realitve and we don't know the current url - 'input' : { 'accept', 'align', 'alt', 'autocomplete', 'autofocus', 'checked', 'dir', 'disabled', 'formAction', 'formEnctype', + 'input' : { 'accept', 'align', 'alt', 'autocomplete', 'autofocus', 'checked', 'dir', 'disabled', 'form', 'formAction', 'formEnctype', 'formAction', 'formEnctype', 'formMethod', 'formNoValidate', 'formTarget', 'list', 'max', 'maxLength', 'min', 'multiple', 'pattern', 'placeholder', 'readOnly', 'required', 'size', 'src', 'step', 'type', 'value', 'width', }, @@ -270,5 +270,6 @@ TAG_ITEM_ATTRIBUTES_SPECIAL_VALUES = { # Use empty str for now, as current impl doesn't support splitting like that 'autocomplete' : lambda em : convertPossibleValues(em.getAttribute('autocomplete', ''), POSSIBLE_VALUES_ON_OFF, invalidDefault="on", emptyValue=''), 'method' : lambda em : convertPossibleValues(em.getAttribute('method', 'get'), POSSIBLE_VALUES_FORM_METHOD, invalidDefault="get", emptyValue=''), + 'form' : lambda em : em.getParentElementCustomFilter( lambda em : em.tagName == 'form' ), } diff --git a/tests/AdvancedHTMLParserTests/test_Attributes.py b/tests/AdvancedHTMLParserTests/test_Attributes.py index <HASH>..<HASH> 100755 --- a/tests/AdvancedHTMLParserTests/test_Attributes.py +++ b/tests/AdvancedHTMLParserTests/test_Attributes.py @@ -666,6 +666,36 @@ class TestAttributes(object): assert 'method="put"' in formHTML , 'Expected html representation to have the value as provided, even though dot-access returns a different value. Got: ' + repr(formHTML) + def test_formAttribute(self): + ''' + test the "form" attribute, that links to parent form + ''' + + document = AdvancedHTMLParser() + document.parseStr('''<html><head></head><body><div id="main"> <form id="myForm"> <div> <input type="text" id="inputWithinForm" /> </div> </form> </div> <input type="text" id="inputOutsideForm" /> </body></html>''') + + + myFormEm = document.getElementById('myForm') + + assert myFormEm , 'Failed to get element by id="myForm"' + + inputWithinFormEm = document.getElementById('inputWithinForm') + + assert inputWithinFormEm , 'Failed to get element with id="inputWithinForm"' + + foundFormEm = inputWithinFormEm.form + + assert foundFormEm , 'Expected inputWithinFormEm.form to return parent form. Got nada.' + + assert foundFormEm is myFormEm , 'Expected to get parent form via .form, got: ' + str(foundFormEm.getStartTag()) + + inputOutsideFormEm = document.getElementById('inputOutsideForm') + + assert inputOutsideFormEm , 'Failed to get element with id="inputOutsideForm"' + + foundFormEm = inputOutsideFormEm.form + + assert foundFormEm is None , 'Expected .form to return None on an input outside of form. Got: ' + str(foundFormEm.getStartTag()) if __name__ == '__main__': sys.exit(subprocess.Popen('GoodTests.py -n1 "%s" %s' %(sys.argv[0], ' '.join(['"%s"' %(arg.replace('"', '\\"'), ) for arg in sys.argv[1:]]) ), shell=True).wait())
Implement 'form' attribute on the tags which define it, which returns the form in which it is contained (parent form), or None if not within a form. With tests.
kata198_AdvancedHTMLParser
train
f3c2ea658c6d35e5cc68d50f6d8b724b1180139a
diff --git a/benchexec/tablegenerator/react-table/src/utils/utils.js b/benchexec/tablegenerator/react-table/src/utils/utils.js index <HASH>..<HASH> 100644 --- a/benchexec/tablegenerator/react-table/src/utils/utils.js +++ b/benchexec/tablegenerator/react-table/src/utils/utils.js @@ -154,6 +154,53 @@ const isOkStatus = (status) => { return status === 0 || status === 200; }; +const buildMatcher = (filters) => + filters.reduce((acc, { id, value }) => { + if (isNil(value)) { + return acc; + } + const [tool, , columnIdx] = id.split("_"); + if (!acc[tool]) { + acc[tool] = {}; + } + if (value.includes(":")) { + let [minV, maxV] = value.split(":"); + minV = minV === "" ? -Infinity : Number(minV); + maxV = maxV === "" ? Infinity : Number(maxV); + acc[tool][columnIdx] = { min: minV, max: maxV }; + return acc; + } + acc[tool][columnIdx] = { value }; + return acc; + }, {}); + +const applyMatcher = (matcher) => (data) => { + return data.filter((row) => { + for (const tool in matcher) { + let rowPass = true; + for (const column in matcher[tool]) { + const { value, min, max } = matcher[tool][column]; + + if (!isNil(min) && !isNil(max)) { + const num = Number(row.results[tool].values[column].raw); + if (num < min || num > max) { + rowPass = false; + break; + } + } else { + if (row.results[tool].values[column].raw !== value) { + rowPass = false; + break; + } + } + } + if (!rowPass) { + return false; + } + } + return true; + }); +}; // Best-effort attempt for calculating a meaningful column width const determineColumnWidth = (column, min_width, max_width) => { let width = column.max_width; // number of chars in column @@ -282,4 +329,6 @@ export { setParam, stringAsBoolean, getFilterableData, + buildMatcher, + applyMatcher, };
Add matcher generation and custom filter logic
sosy-lab_benchexec
train
2348d42606c003bb171c217f791b7817bd0f6337
diff --git a/src/edu/rpi/cmt/timezones/TimezonesImpl.java b/src/edu/rpi/cmt/timezones/TimezonesImpl.java index <HASH>..<HASH> 100644 --- a/src/edu/rpi/cmt/timezones/TimezonesImpl.java +++ b/src/edu/rpi/cmt/timezones/TimezonesImpl.java @@ -536,7 +536,7 @@ public class TimezonesImpl extends Timezones { } public String getTz(final String id) throws TimezonesException { - return call("tzid=" + id); + return call("action=get&tzid=" + id); } /* Not used - remove from server
More bringing tzsvr in line with spec
Bedework_bw-util
train
8ed0953428e5fd733ec97c2d69113c704a80a25f
diff --git a/ezp/content/services/translation.php b/ezp/content/services/translation.php index <HASH>..<HASH> 100644 --- a/ezp/content/services/translation.php +++ b/ezp/content/services/translation.php @@ -43,40 +43,44 @@ class Translation implements ServiceInterface } /** - * Adds a Translation to $content in $locale optionnally based on existing + * Adds a Translation to $content in $locale optionnally based on existing * translation in $base. * * @param Content $content * @param Locale $locale * @param Locale $base * @return Translation - * @throw \InvalidArgumentException if translation in $locale already exists - * or if translation in $base does not exist. + * @throw \InvalidArgumentException if translation in $base does not exist. */ public function add( Content $content, Locale $locale, Locale $base = null ) { + if ( $base !== null && !isset( $content->translations[$base->code] ) ) + { + throw new \InvalidArgumentException( "Translation {$base->code} does not exist" ); + } if ( isset( $content->translations[$locale->code] ) ) { - throw new \InvalidArgumentException( "Translation {$locale->code} already exists" ); + $tr = $content->translations[$locale->code]; } - if ( $base !== null && !isset( $content->translations[$base->code] ) ) + else { - throw new \InvalidArgumentException( "Translation {$base->code} does not exist" ); + $tr = new Translation( $locale, $content ); + $content->translations[$locale->code] = $tr; } - $tr = new Translation( $locale, $content ); + + $newVersion = null; if ( $base !== null ) { - $newVersion = clone $content->translations[$base->code]->last; + $newVersion = clone $content->translations[$base->code]->current; } - else + if ( $newVersion === null ) { $newVersion = new Version( $content ); } $newVersion->locale = $locale; $tr->versions[] = $newVersion; $content->versions[] = $newVersion; - $content->translations[$locale->code] = $tr; - return $content->translations[$locale->code]; + return $tr; } } diff --git a/ezp/content/translation.php b/ezp/content/translation.php index <HASH>..<HASH> 100644 --- a/ezp/content/translation.php +++ b/ezp/content/translation.php @@ -34,6 +34,7 @@ class Translation extends \ezp\base\AbstractModel 'contentId' => false, 'fields' => false, 'last' => false, + 'current' => false, ); @@ -96,6 +97,23 @@ class Translation extends \ezp\base\AbstractModel } /** + * Returns the published version in the translation + * + * @return Version|null + */ + protected function getCurrent() + { + foreach( $this->versions as $version ) + { + if ( $version->status === Version::STATUS_PUBLISHED ) + { + return $version; + } + } + return null; + } + + /** * Returns the field collection in the last version added to the * translation * diff --git a/ezp/content/version.php b/ezp/content/version.php index <HASH>..<HASH> 100644 --- a/ezp/content/version.php +++ b/ezp/content/version.php @@ -25,6 +25,18 @@ namespace ezp\content; class Version extends \ezp\base\AbstractModel implements \ezp\base\ObserverInterface { /** + * @todo taken from eZContentObjectVersion, to be redefined + */ + const STATUS_DRAFT = 0; + const STATUS_PUBLISHED = 1; + const STATUS_PENDING = 2; + const STATUS_ARCHIVED = 3; + const STATUS_REJECTED = 4; + const STATUS_INTERNAL_DRAFT = 5; + const STATUS_REPEAT = 6; + const STATUS_QUEUED = 7; + + /** * @var array Readable of properties on this object */ protected $readableProperties = array(
Changed: do not throw an exception is the translation already exists, just create a new version from the currently published one
ezsystems_ezpublish-kernel
train
173bf3506d99c0767a41d30fbe4d306201369194
diff --git a/actionpack/lib/action_dispatch/testing/integration.rb b/actionpack/lib/action_dispatch/testing/integration.rb index <HASH>..<HASH> 100644 --- a/actionpack/lib/action_dispatch/testing/integration.rb +++ b/actionpack/lib/action_dispatch/testing/integration.rb @@ -424,9 +424,9 @@ module ActionDispatch def append_format_to(path) if @url_encoded_form - path + @path_format - else path + else + path + @path_format end end
Fix conditional order broken in ea<I>ec<I>.
rails_rails
train
d1b6120c988915a618a2682015924316895c2193
diff --git a/src/visualizers/widgets/HFSMViz/HFSMVizWidget.js b/src/visualizers/widgets/HFSMViz/HFSMVizWidget.js index <HASH>..<HASH> 100644 --- a/src/visualizers/widgets/HFSMViz/HFSMVizWidget.js +++ b/src/visualizers/widgets/HFSMViz/HFSMVizWidget.js @@ -142,6 +142,18 @@ define([ }; }; + HFSMVizWidget.prototype.initializeSimulator = function() { + if (this._simulator) { + delete this._simulator; + } + // SIMULATOR + this._simulator = new Simulator(); + this._simulator.initialize( this._left, this.nodes, this._client ); + this._simulator.onStateChanged( this.showActiveState.bind(this) ); + this._simulator.onAnimateElement( this.animateElement.bind(this) ); + this._simulator.onShowTransitions( this.showTransitions.bind(this) ); + }; + HFSMVizWidget.prototype._initialize = function () { var width = this._el.width(), height = this._el.height(), @@ -168,11 +180,7 @@ define([ this._right.css('width', '80%'); // SIMULATOR - this._simulator = new Simulator(); - this._simulator.initialize( this._left, this.nodes, this._client ); - this._simulator.onStateChanged( this.showActiveState.bind(this) ); - this._simulator.onAnimateElement( this.animateElement.bind(this) ); - this._simulator.onShowTransitions( this.showTransitions.bind(this) ); + this.initializeSimulator(); // DRAGGING INFO this.isDragging = false; @@ -1777,8 +1785,10 @@ define([ HFSMVizWidget.prototype.clearNodes = function() { delete this.nodes; this._cy.nodes().remove(); + // now re-init this.nodes = {}; this._debounced_one_time_zoom = _.debounce(_.once(this.onZoomClicked.bind(this)), 250); + this.initializeSimulator(); }; HFSMVizWidget.prototype.shutdown = function() {
closes #<I> properly delete and re-initialize simulator when destroying or clearing nodes.
finger563_webgme-hfsm
train
1836c9f8bcd982e0ced48dfb87318f01d5edc93e
diff --git a/spyderlib/userconfig.py b/spyderlib/userconfig.py index <HASH>..<HASH> 100644 --- a/spyderlib/userconfig.py +++ b/spyderlib/userconfig.py @@ -68,6 +68,27 @@ class DefaultsConfig(cp.ConfigParser): cp.ConfigParser.__init__(self) self.name = name self.subfolder = subfolder + + def _write(self, fp): + """ + Private write method for Python 2 + The one from configparser fails for non-ascii Windows accounts + """ + if self._defaults: + fp.write("[%s]\n" % DEFAULTSECT) + for (key, value) in self._defaults.items(): + fp.write("%s = %s\n" % (key, str(value).replace('\n', '\n\t'))) + fp.write("\n") + for section in self._sections: + fp.write("[%s]\n" % section) + for (key, value) in self._sections[section].items(): + if key == "__name__": + continue + if (value is not None) or (self._optcre == self.OPTCRE): + value = to_text_string(value) + key = " = ".join((key, value.replace('\n', '\n\t'))) + fp.write("%s\n" % (key)) + fp.write("\n") def _set(self, section, option, value, verbose): """ @@ -93,7 +114,7 @@ class DefaultsConfig(cp.ConfigParser): if PY2: # Python 2 with open(fname, 'w') as configfile: - self.write(configfile) + self._write(configfile) else: # Python 3 with open(fname, 'w', encoding='utf-8') as configfile: @@ -397,6 +418,11 @@ class UserConfig(DefaultsConfig): section = self.__check_section_option(section, option) default_value = self.get_default(section, option) if default_value is NoDefault: + # This let us save correctly string value options with + # no config default that contain non-ascii chars in + # Python 2 + if PY2 and is_text_string(value): + value = repr(value) default_value = value self.set_default(section, option, default_value) if isinstance(default_value, bool):
userconfig: Spyder was not starting on non-ascii Windows under Python 2 - This was because several options ended up containing non-ascii chars and the configparser write method assume all options are byte strings. So we changed that method.
spyder-ide_spyder
train
66b85e5945f49f7fa601850528e5580dd7892707
diff --git a/tests/Unit/DjThossi/Ensure/EnsureIsBooleanTraitTest.php b/tests/Unit/DjThossi/Ensure/EnsureIsBooleanTraitTest.php index <HASH>..<HASH> 100644 --- a/tests/Unit/DjThossi/Ensure/EnsureIsBooleanTraitTest.php +++ b/tests/Unit/DjThossi/Ensure/EnsureIsBooleanTraitTest.php @@ -64,6 +64,7 @@ class EnsureIsBooleanTraitTest extends PHPUnit_Framework_TestCase 'Integer' => ['FieldName', 1337, 3, 'FieldName is not a boolean, got "integer"'], 'object' => ['FieldName', new stdClass(), 4, 'FieldName is not a boolean, got "stdClass"'], 'empty' => ['FieldName', '', 5, 'FieldName is not a boolean, got "string"'], + 'null' => ['FieldName', null, 5, 'FieldName is not a boolean, got "NULL"'], ]; } } diff --git a/tests/Unit/DjThossi/Ensure/EnsureIsIntegerTraitTest.php b/tests/Unit/DjThossi/Ensure/EnsureIsIntegerTraitTest.php index <HASH>..<HASH> 100644 --- a/tests/Unit/DjThossi/Ensure/EnsureIsIntegerTraitTest.php +++ b/tests/Unit/DjThossi/Ensure/EnsureIsIntegerTraitTest.php @@ -66,6 +66,8 @@ class EnsureIsIntegerTraitTest extends PHPUnit_Framework_TestCase 'False' => ['FieldName', false, 4, 'FieldName is not an integer, got "boolean"'], 'object' => ['FieldName', new stdClass(), 5, 'FieldName is not an integer, got "stdClass"'], 'empty' => ['FieldName', '', 6, 'FieldName is not an integer, got "string"'], + 'null' => ['FieldName', null, 5, 'FieldName is not an integer, got "NULL"'], + ]; } } diff --git a/tests/Unit/DjThossi/Ensure/EnsureIsStringTraitTest.php b/tests/Unit/DjThossi/Ensure/EnsureIsStringTraitTest.php index <HASH>..<HASH> 100644 --- a/tests/Unit/DjThossi/Ensure/EnsureIsStringTraitTest.php +++ b/tests/Unit/DjThossi/Ensure/EnsureIsStringTraitTest.php @@ -64,6 +64,7 @@ class EnsureIsStringTraitTest extends PHPUnit_Framework_TestCase 'Double' => ['FieldName', 1.337, 3, 'FieldName is not a string, got "double"'], 'Integer' => ['FieldName', 1337, 4, 'FieldName is not a string, got "integer"'], 'object' => ['FieldName', new stdClass(), 5, 'FieldName is not a string, got "stdClass"'], + 'null' => ['FieldName', null, 5, 'FieldName is not a string, got "NULL"'], ]; } }
Added tests fro value null
DjThossi_Ensure
train
e8a966fd29da8deafb461ea758de7fe63ffbec32
diff --git a/lib/Kaba.js b/lib/Kaba.js index <HASH>..<HASH> 100644 --- a/lib/Kaba.js +++ b/lib/Kaba.js @@ -4,6 +4,7 @@ const kabaBabelPreset = require("kaba-babel-preset"); const path = require("path"); const program = require("commander"); const typeScriptErrorFormatter = require("@becklyn/typescript-error-formatter"); +const UglifyJsPlugin = require('uglifyjs-webpack-plugin'); /** * @typedef {{ @@ -477,6 +478,21 @@ class Kaba // optimization optimization: { concatenateModules: this.moduleConcatenationEnabled, + minimizer: [ + new UglifyJsPlugin({ + uglifyOptions: { + warnings: false, + //eslint-disable-next-line camelcase + drop_console: false, + output: { + comments: false, + }, + }, + parallel: true, + cache: true, + extractComments: true, + }), + ], }, // performance diff --git a/lib/runner/WebpackRunner.js b/lib/runner/WebpackRunner.js index <HASH>..<HASH> 100644 --- a/lib/runner/WebpackRunner.js +++ b/lib/runner/WebpackRunner.js @@ -194,7 +194,9 @@ class WebpackRunner files.forEach( file => { const baseName = path.basename(file); - if (usedFiles[baseName] !== true) + const licenseFile = baseName.replace(/\.LICENSE/, ""); + + if (usedFiles[baseName] !== true && usedFiles[licenseFile] !== true) { fs.removeSync(file); } diff --git a/package.json b/package.json index <HASH>..<HASH> 100644 --- a/package.json +++ b/package.json @@ -30,6 +30,7 @@ "raw-loader": "^0.5.1", "ts-loader": "^4.2.0", "typescript": "^2.8.1", + "uglifyjs-webpack-plugin": "^1.2.5", "webpack": "^4.5.0", "webpack-bundle-analyzer": "^2.11.1" },
Use uglify webpack plugin
Becklyn_kaba
train
7e199f9f4e11bf05468dfb80209bb7d086497bc6
diff --git a/test/case6/case6.js b/test/case6/case6.js index <HASH>..<HASH> 100644 --- a/test/case6/case6.js +++ b/test/case6/case6.js @@ -4,15 +4,18 @@ var div = document.createElement('div'); div.innerHTML = ` - <${tagContent} hash="case6"> + <${tagContent} id="case6-1" hash="case\\d+"> + Case 6 via RegExp </${tagContent}> `; - var async1 = async_test('Case 6: hash changed to content[hash="case6"]'); + var async1 = async_test('Case 6: hash changed to content[hash="case(\d+)"]'); async1.next = async1.step_func(_ => { var check_hash = async1.step_func((e) => { window.removeEventListener('hashchange', check_hash); + var content1 = document.querySelector('#case6-1'); + assert_false(content1.hidden); document.body.removeChild(div); async1.done();
Test case 6 - matching via RegExp Bear in mind that the \ to define a RegExp must be passed twice. E.g. \d+ should be passed as \\d+ So, for a while this is the first restriction for matching.
m3co_router3
train
177e0aaebdfb981774cf5d726eb93cc79ea3fb22
diff --git a/visidata/editor.py b/visidata/editor.py index <HASH>..<HASH> 100644 --- a/visidata/editor.py +++ b/visidata/editor.py @@ -18,7 +18,7 @@ class SuspendCurses: curses.doupdate() -@visidata.VisiData.api +@visidata.VisiData.global_api def launchEditor(vd, *args): editor = os.environ.get('EDITOR') or fail('$EDITOR not set') args = [editor] + list(args) @@ -26,7 +26,7 @@ def launchEditor(vd, *args): return subprocess.call(args) -@visidata.VisiData.api +@visidata.VisiData.global_api def launchExternalEditor(vd, v, linenum=0): import tempfile with tempfile.NamedTemporaryFile() as temp:
[editor-] launchEditor is part of global_api
saulpw_visidata
train
dd6217120ff2e966da6ca01b654fe0b92dcd8307
diff --git a/dvc/remote/base.py b/dvc/remote/base.py index <HASH>..<HASH> 100644 --- a/dvc/remote/base.py +++ b/dvc/remote/base.py @@ -592,6 +592,7 @@ class RemoteBASE(object): self.link(cache_info, path_info) self.state.save_link(path_info) + self.state.save(path_info, checksum) if progress_callback: progress_callback.update(path_info.url) @@ -613,22 +614,24 @@ class RemoteBASE(object): entry_info = copy(path_info) for entry in dir_info: relpath = entry[self.PARAM_RELPATH] - checksum = entry[self.PARAM_CHECKSUM] - entry_cache_info = self.checksum_to_path_info(checksum) + entry_checksum = entry[self.PARAM_CHECKSUM] + entry_cache_info = self.checksum_to_path_info(entry_checksum) entry_info.url = self.ospath.join(path_info.url, relpath) entry_info.path = self.ospath.join(path_info.path, relpath) - entry_checksum_info = {self.PARAM_CHECKSUM: checksum} + entry_checksum_info = {self.PARAM_CHECKSUM: entry_checksum} if self.changed(entry_info, entry_checksum_info): if self.exists(entry_info): self.safe_remove(entry_info, force=force) self.link(entry_cache_info, entry_info) + self.state.save(entry_info, entry_checksum) if progress_callback: progress_callback.update(entry_info.url) self._remove_redundant_files(path_info, dir_info, force) self.state.save_link(path_info) + self.state.save(path_info, checksum) def _remove_redundant_files(self, path_info, dir_info, force): existing_files = set(
remote: checkout: save checksums without re-computation We do a similar thing on save, where we set cache checksum from already computated ones for actual data. This patch does the same thing but in revers: on checkout we know cache checksums, so we can set data checksums from it without having to re-calculate it. Fixes #<I>
iterative_dvc
train
4a41188f40b3bea14d4a57fbb441161ac4def9b9
diff --git a/eZ/Publish/API/Repository/Values/User/UserGroup.php b/eZ/Publish/API/Repository/Values/User/UserGroup.php index <HASH>..<HASH> 100644 --- a/eZ/Publish/API/Repository/Values/User/UserGroup.php +++ b/eZ/Publish/API/Repository/Values/User/UserGroup.php @@ -8,7 +8,7 @@ use eZ\Publish\API\Repository\Values\Content\Content; * This class represents a user group * * @property-read mixed $id - * @property-read int $parentId + * @property-read mixed $parentId * @property-read int $subGroupCount */ abstract class UserGroup extends Content @@ -16,21 +16,21 @@ abstract class UserGroup extends Content /** * The id of the user group * - * @var integer + * @var mixed */ - public $id; + protected $id; /** * * the parent id of the user group - * @var integer + * @var mixed */ - public $parentId; + protected $parentId; /** * * The number of sub groups * @var integer */ - public $subGroupCount; + protected $subGroupCount; }
changed properties to protected and id are now "mixed"
ezsystems_ezpublish-kernel
train
6bf57d43c70c74ec4fd94f1a4b836de8d53162ca
diff --git a/Eloquent/Factories/Factory.php b/Eloquent/Factories/Factory.php index <HASH>..<HASH> 100644 --- a/Eloquent/Factories/Factory.php +++ b/Eloquent/Factories/Factory.php @@ -705,9 +705,9 @@ abstract class Factory $relationship = Str::camel(Str::substr($method, 3)); - $factory = static::factoryForModel( - get_class($this->newModel()->{$relationship}()->getRelated()) - ); + $relationshipClass = get_class($this->newModel()->{$relationship}()->getRelated()); + + $factory = $relationshipClass::newFactory() ?: static::factoryForModel($relationshipClass); if (Str::startsWith($method, 'for')) { return $this->for($factory->state($parameters[0] ?? []), $relationship);
Allow dynamic factory methods to obey newFactory method on model
illuminate_database
train
f2f8a5aba63feecd4079b2a8f6efdd36f710e044
diff --git a/pgmpy/models/DynamicBayesianNetwork.py b/pgmpy/models/DynamicBayesianNetwork.py index <HASH>..<HASH> 100644 --- a/pgmpy/models/DynamicBayesianNetwork.py +++ b/pgmpy/models/DynamicBayesianNetwork.py @@ -640,7 +640,7 @@ class DynamicBayesianNetwork(DAG): if not any(x.variable == temp_var for x in self.cpds): if all(x[1] == parents[0][1] for x in parents): if parents: - evidence_card = cpd.cardinality[:0:-1] + evidence_card = cpd.cardinality[1:] new_cpd = TabularCPD( temp_var, cpd.variable_card,
Fixes bug in DynamicBayesianNetwork.initial_initial_state [fixes #<I>] (#<I>)
pgmpy_pgmpy
train
6d788787fe2e91ec3fa583f0b734416a142c2793
diff --git a/lib/copy-sync/__tests__/preserve-time.test.js b/lib/copy-sync/__tests__/preserve-time.test.js index <HASH>..<HASH> 100644 --- a/lib/copy-sync/__tests__/preserve-time.test.js +++ b/lib/copy-sync/__tests__/preserve-time.test.js @@ -3,6 +3,7 @@ var fs = require('fs') var os = require('os') var path = require('path') var copySync = require('../copy-sync') +var utimes = require('../../util/utimes') /* global beforeEach, describe, it */ @@ -41,8 +42,14 @@ describe('copy', function () { var fromStat = fs.statSync(a) var toStat = fs.statSync(b) if (options.preserveTimestamps) { - assert.strictEqual(toStat.mtime.getTime(), fromStat.mtime.getTime()) - assert.strictEqual(toStat.atime.getTime(), fromStat.atime.getTime()) + // https://github.com/nodejs/io.js/issues/2069 + if (process.platform !== 'win32') { + assert.strictEqual(toStat.mtime.getTime(), fromStat.mtime.getTime()) + assert.strictEqual(toStat.atime.getTime(), fromStat.atime.getTime()) + } else { + assert.strictEqual(toStat.mtime.getTime(), utimes.timeRemoveMillis(fromStat.mtime.getTime())) + assert.strictEqual(toStat.atime.getTime(), utimes.timeRemoveMillis(fromStat.atime.getTime())) + } } else { assert.notEqual(toStat.mtime.getTime(), fromStat.mtime.getTime()) // the access time might actually be the same, so check only modification time diff --git a/lib/copy/__tests__/copy-preserve-time.test.js b/lib/copy/__tests__/copy-preserve-time.test.js index <HASH>..<HASH> 100644 --- a/lib/copy/__tests__/copy-preserve-time.test.js +++ b/lib/copy/__tests__/copy-preserve-time.test.js @@ -3,6 +3,7 @@ var fs = require('fs') var os = require('os') var path = require('path') var copy = require('../copy') +var utimes = require('../../util/utimes') /* global beforeEach, describe, it */ @@ -49,8 +50,14 @@ describe('copy', function () { var fromStat = fs.statSync(a) var toStat = fs.statSync(b) if (options.preserveTimestamps) { - assert.strictEqual(toStat.mtime.getTime(), fromStat.mtime.getTime()) - assert.strictEqual(toStat.atime.getTime(), fromStat.atime.getTime()) + // https://github.com/nodejs/io.js/issues/2069 + if (process.platform !== 'win32') { + assert.strictEqual(toStat.mtime.getTime(), fromStat.mtime.getTime()) + assert.strictEqual(toStat.atime.getTime(), fromStat.atime.getTime()) + } else { + assert.strictEqual(toStat.mtime.getTime(), utimes.timeRemoveMillis(fromStat.mtime.getTime())) + assert.strictEqual(toStat.atime.getTime(), utimes.timeRemoveMillis(fromStat.atime.getTime())) + } } else { assert.notEqual(toStat.mtime.getTime(), fromStat.mtime.getTime()) // the access time might actually be the same, so check only modification time
lib/{copy, copy-sync}/__tests__/preserve-time: fixed for Windows.
jprichardson_node-fs-extra
train
a5133b1056522fb6a0020e859698cf97a3e68032
diff --git a/tests/unit/test_commands.py b/tests/unit/test_commands.py index <HASH>..<HASH> 100644 --- a/tests/unit/test_commands.py +++ b/tests/unit/test_commands.py @@ -360,12 +360,12 @@ class TestCommands(object): """ Get the current stock price of the NASDAQ. - ^IXIC at 10:37am (ET): 2490.40 (0.4%) + ^IXIC at 10:37am (ET): 3403.247 (0.0%) """ res = commands.ticker(c, e, "#test", "testrunner", "^ixic") print(res) assert re.match(r"^\^IXIC at \d{1,2}:\d{2}(?:am|pm) \([A-z]{1,3}\): " - r"\d{4,5}.\d{2} \(\-?\d{1,3}.\d%\)$", res), res + r"\d{4,5}.\d{2,4} \(\-?\d{1,3}.\d%\)$", res), res def test_pick_or(self): """
Fix nasdaq test, which was overmatching
yougov_pmxbot
train
3f0e28b7026213ea9a642302aa21695d5f09d609
diff --git a/package.json b/package.json index <HASH>..<HASH> 100644 --- a/package.json +++ b/package.json @@ -22,11 +22,9 @@ "test": "grunt test" }, "devDependencies": { - "babel": "^6.5.2", - "babel-core": "^6.21.0", + "babel-core": "^6.22.1", "babel-loader": "^6.2.10", - "babel-preset-es2015": "^6.5.0", - "babelify": "^6.1.0", + "babel-preset-es2015": "^6.22.0", "clean-webpack-plugin": "^0.1.15", "express": "~3.4.8", "grunt": "~0.4.5", @@ -34,14 +32,14 @@ "grunt-contrib-copy": "^1.0.0", "grunt-contrib-jshint": "~1.0.0", "grunt-contrib-watch": "~0.6.1", - "grunt-karma": "~0.12.0", + "grunt-karma": "^2.0.0", "grunt-webpack": "^1.0.18", - "jasmine-core": "^2.4.1", - "karma": "~0.13", - "karma-chrome-launcher": "~0.2", - "karma-firefox-launcher": "~0.1", - "karma-ie-launcher": "~0.2", - "karma-jasmine": "~0.3", + "jasmine-core": "^2.5.2", + "karma": "^1.4.0", + "karma-chrome-launcher": "^2.0.0", + "karma-firefox-launcher": "^1.0.0", + "karma-ie-launcher": "^1.0.0", + "karma-jasmine": "^1.1.0", "webpack": "^1.14.0" }, "keywords": [ diff --git a/src/modules/jqLiteExtras.js b/src/modules/jqLiteExtras.js index <HASH>..<HASH> 100644 --- a/src/modules/jqLiteExtras.js +++ b/src/modules/jqLiteExtras.js @@ -1,3 +1,14 @@ +/*! + globals: angular, window + List of used element methods available in JQuery but not in JQuery Lite + element.before(elem) + element.height() + element.outerHeight(true) + element.height(value) = only for Top/Bottom padding elements + element.scrollTop() + element.scrollTop(value) + */ + export default class JQLiteExtras { registerFor(element) { diff --git a/src/ui-scroll.js b/src/ui-scroll.js index <HASH>..<HASH> 100644 --- a/src/ui-scroll.js +++ b/src/ui-scroll.js @@ -1,14 +1,3 @@ -/*! - globals: angular, window - List of used element methods available in JQuery but not in JQuery Lite - element.before(elem) - element.height() - element.outerHeight(true) - element.height(value) = only for Top/Bottom padding elements - element.scrollTop() - element.scrollTop(value) - */ - import JQLiteExtras from './modules/jqLiteExtras'; import ElementRoutines from './modules/elementRoutines.js'; import ScrollBuffer from './modules/buffer.js'; diff --git a/webpack.config.js b/webpack.config.js index <HASH>..<HASH> 100644 --- a/webpack.config.js +++ b/webpack.config.js @@ -44,14 +44,9 @@ var plugins = [ }) ]; -module.exports.devPlugins = plugins; +module.exports.devPlugins = plugins.concat([]); module.exports.prodPlugins = plugins.concat([ - new CleanWebpackPlugin(['temp'], { - root: process.cwd(), - verbose: true, - dry: false, - }), new webpack.optimize.UglifyJsPlugin({ compress: { warnings: true,
babel and karma update
angular-ui_ui-scroll
train
67c247783a9b019d9bc8078404d7716bb7e34431
diff --git a/Script/Gt.js b/Script/Gt.js index <HASH>..<HASH> 100644 --- a/Script/Gt.js +++ b/Script/Gt.js @@ -26,7 +26,9 @@ // Callback function provided, execute on DomReady event. return GT.ready(arguments[0], arguments[1]); } - if(typeof arguments[0] === "string") { + if(typeof arguments[0] === "string" + || arguments[0] instanceof NodeList + || arguments[0] instanceof HTMLElement) { // Return matching DomNodes from CSS selector. return GT.dom(arguments[0], arguments[1]); } @@ -48,6 +50,63 @@ } tmplDiv.parentNode.removeChild(tmplDiv); } + }, + helpers = { + "addClass": function(name) { + this.className += " " + name; + return this; + }, + "removeClass": function(name) { + this.className.replace(name, ""); + return this; + }, + "hasClass": function(name) { + var match = new Regexp(name, "im"); + return classname.match(match); + }, + "remove": function() { + this.parentNode.removeChild(this); + return this; + }, + "append": function(element) { + this.appendChild(element); + return element; + }, + "prepend": function(element) { + this.insertBefore(element, this.firstChild); + return element; + }, + "before": function(element) { + this.parentNode.insertBefore(element, this); + return element; + }, + "after": function(element) { + this.parentNode.insertBefore(element, this.nextSibling); + return element; + } + }, + nodeListWrap = function(me, funcName, args) { + var i; + for(i = 0; i < me.length; i++) { + me[i][funcName].apply(me[i], args); + } + }, + addHelpers = function() { + Object.keys(helpers).map(function(key) { + Element.prototype[key] = helpers[key]; + NodeList.prototype[key] = function() { + nodeListWrap(this, key, arguments); + } + }); + /*Element.prototype.addClass = addClass; + Element.prototype.removeClass = removeClass; + Element.prototype.hasClass = hasClass; + + NodeList.prototype.addClass = function(name) { + mapFunc(addClass, name) + }; + NodeList.prototype.removeClass = removeClass; + NodeList.prototype.hasClass = hasClass;*/ }; GT.error = function(message) { @@ -132,12 +191,37 @@ }; /** - * Wrapper to querySelectorAll method. + * Wrapper to querySelectorAll method. Pass an optional context node to + * perform a query selection within that node. + * * @param string selector The CSS selector to find. * @return DomNodeList An array containing the matching elements. */ GT.dom = function(selector) { - return document.querySelectorAll(selector); + var context = document; + if(arguments.length > 1) { + if(arguments[0] instanceof String) { + selector = arguments[0]; + } + if(arguments[1] instanceof String) { + selector = arguments[1]; + } + if(arguments[0] instanceof HTMLElement) { + context = arguments[0]; + selector = arguments[1]; + } + if(arguments[1] instanceof HTMLElement) { + context = arguments[1]; + } + if(arguments[0] instanceof NodeList) { + context = arguments[0][0]; + selector = arguments[1]; + } + if(arguments[1] instanceof NodeList) { + context = arguments[1][0]; + } + } + return context.querySelectorAll(selector); }; GT.template = function(name) { @@ -153,9 +237,68 @@ GT.tool = function(name) { }; + + /** + * Provides a really simple ajax library, intended for modern browsers. + * Will automatically parse the response, converting into JSON object when + * possible. + * + * @param string url The url to request, with parameters in the query string + * for GET and POST. + * @param function callback The function to call when response is ready. + * @return XMLHttpRequest The XHR object. + */ + GT.ajax = new function(url, callback) { + var req = function(url, callback, method) { + var xhr, + method = method.toUpperCase(); + if(window.XMLHttpRequest) { + xhr = new XMLHttpRequest(); + } + else { + xhr = new ActiveXObject("Microsoft.XMLHTTP"); + } + xhr.open(method, url, true); + + if(method === "POST") { + httpRequest.setRequestHeader( + "Content-Type", "application/x-www-form-urlencoded"); + } + + xhr.onreadystatechange = function() { + var response; + if(xhr.readyState === 4) { + console.log(xhr); + if(callback) { + response = xhr.response; + // Quick and dirty JSON detection (skipping real + // detection). + if(xhr.response[0] === "{" || xhr.response[0] === "[") { + // Real JSON detection (slower). + try { + response = JSON.parse(xhr.response); + } + catch(e) {} + } + callback(response, xhr); + } + } + }; + + xhr.send(); + return xhr; + }; + this.get = function(url, callback) { + return req(url, callback, "get"); + }; + this.post = function(url, callback) { + return req(url, callback, "post"); + }; + }; window.GT = GT; // Perform automatic template collection. // The template elements are provided by PHP.Gt just before DOM flushing. GT(templateScrape); + GT(addHelpers); }()); \ No newline at end of file
Much more simplified JavaScript, attaches helper functions to DOM Elements.
PhpGt_WebEngine
train
625bac027055c36f1cbcd6d7f32351ff9e936c51
diff --git a/pyravendb/data/document_conventions.py b/pyravendb/data/document_conventions.py index <HASH>..<HASH> 100644 --- a/pyravendb/data/document_conventions.py +++ b/pyravendb/data/document_conventions.py @@ -1,9 +1,9 @@ from pyravendb.data.indexes import SortOptions from datetime import datetime, timedelta from pyravendb.tools.utils import Utils -from inflector import Inflector +import inflect -inflector = Inflector() +inflector = inflect.engine() class DocumentConventions(object): @@ -39,7 +39,7 @@ class DocumentConventions(object): @staticmethod def default_transform_plural(name): - return inflector.conditional_plural(2, name) + return inflector.plural(name) @staticmethod def default_transform_type_tag_name(name): diff --git a/setup.py b/setup.py index <HASH>..<HASH> 100644 --- a/setup.py +++ b/setup.py @@ -3,7 +3,7 @@ from setuptools import setup, find_packages setup( name='pyravendb', packages=find_packages(), - version='4.0.4.9', + version='4.0.5.0', long_description=open("README.rst").read(), description='This is the official python client for RavenDB v4.0 document database', author='RavenDB', @@ -14,11 +14,11 @@ setup( install_requires= [ 'requests >= 2.18.4', - 'inflector >= 2.0.12', 'xxhash >= 1.0.1', 'pyOpenSSL >= 17.2.0', 'ijson >= 2.3', - 'websocket-client >= 0.46.0' + 'websocket-client >= 0.46.0', + 'inflect >= 1.0.0' ], zip_safe=False )
Change inflector lib to inflect for plural
ravendb_ravendb-python-client
train
823a582a80fb8172e1c4447868e1f53e4fce9fad
diff --git a/org/postgresql/Connection.java b/org/postgresql/Connection.java index <HASH>..<HASH> 100644 --- a/org/postgresql/Connection.java +++ b/org/postgresql/Connection.java @@ -791,6 +791,36 @@ public abstract class Connection public abstract void close() throws SQLException; /** + * A sub-space of this Connection's database may be selected by + * setting a catalog name. If the driver does not support catalogs, + * it will silently ignore this request + * + * @exception SQLException if a database access error occurs + */ + public void setCatalog(String catalog) throws SQLException + { + if(catalog!=null && !catalog.equals(PG_DATABASE)) { + close(); + Properties info=new Properties(); + info.setProperty("user", PG_USER); + info.setProperty("password", PG_PASSWORD); + openConnection(PG_HOST, PG_PORT, info, catalog, this_url, this_driver); + } + } + + /** + * Return the connections current catalog name, or null if no + * catalog name is set, or we dont support catalogs. + * + * @return the current catalog name or null + * @exception SQLException if a database access error occurs + */ + public String getCatalog() throws SQLException + { + return PG_DATABASE; + } + + /** * Overides finalize(). If called, it closes the connection. * * This was done at the request of Rachel Greenham diff --git a/org/postgresql/jdbc1/Connection.java b/org/postgresql/jdbc1/Connection.java index <HASH>..<HASH> 100644 --- a/org/postgresql/jdbc1/Connection.java +++ b/org/postgresql/jdbc1/Connection.java @@ -273,30 +273,6 @@ public class Connection extends org.postgresql.Connection implements java.sql.Co } /** - * A sub-space of this Connection's database may be selected by - * setting a catalog name. If the driver does not support catalogs, - * it will silently ignore this request - * - * @exception SQLException if a database access error occurs - */ - public void setCatalog(String catalog) throws SQLException - { - // No-op - } - - /** - * Return the connections current catalog name, or null if no - * catalog name is set, or we dont support catalogs. - * - * @return the current catalog name or null - * @exception SQLException if a database access error occurs - */ - public String getCatalog() throws SQLException - { - return null; - } - - /** * You can call this method to try to change the transaction * isolation level using one of the TRANSACTION_* values. * diff --git a/org/postgresql/jdbc2/Connection.java b/org/postgresql/jdbc2/Connection.java index <HASH>..<HASH> 100644 --- a/org/postgresql/jdbc2/Connection.java +++ b/org/postgresql/jdbc2/Connection.java @@ -356,30 +356,6 @@ public class Connection extends org.postgresql.Connection implements java.sql.Co } /** - * A sub-space of this Connection's database may be selected by - * setting a catalog name. If the driver does not support catalogs, - * it will silently ignore this request - * - * @exception SQLException if a database access error occurs - */ - public void setCatalog(String catalog) throws SQLException - { - // No-op - } - - /** - * Return the connections current catalog name, or null if no - * catalog name is set, or we dont support catalogs. - * - * @return the current catalog name or null - * @exception SQLException if a database access error occurs - */ - public String getCatalog() throws SQLException - { - return null; - } - - /** * You can call this method to try to change the transaction * isolation level using one of the TRANSACTION_* values. *
Great, here is a context diff of CVS for implementing the get/setCatalog methods in Connection - note: I've updated setCatalog(String catalog) from my previous diff so it checks whether it is already connected to the specified catalog. Jason Davies
pgjdbc_pgjdbc
train
d30632724a5f9224791f174be0bc02e824e4d30a
diff --git a/oidc_auth/util.py b/oidc_auth/util.py index <HASH>..<HASH> 100644 --- a/oidc_auth/util.py +++ b/oidc_auth/util.py @@ -6,11 +6,15 @@ from .settings import api_settings class cache(object): """ Cache decorator that memoizes the return value of a method for some time. + + Increment the cache_version everytime your method's implementation changes in such a way that it returns values + that are not backwards compatible. For more information, see the Django cache documentation: + https://docs.djangoproject.com/en/2.2/topics/cache/#cache-versioning """ - cache_version = 1 - def __init__(self, ttl): + def __init__(self, ttl, cache_version=1): self.ttl = ttl + self.cache_version = cache_version def __call__(self, fn): @functools.wraps(fn)
fixup! Use the built-in Django cache instead of a bespoke one.
ByteInternet_drf-oidc-auth
train
613166ad52fbb85f1d8b40c2c196a889e7e4b3f3
diff --git a/src/cr/cube/cube_slice.py b/src/cr/cube/cube_slice.py index <HASH>..<HASH> 100644 --- a/src/cr/cube/cube_slice.py +++ b/src/cr/cube/cube_slice.py @@ -110,7 +110,15 @@ class CubeSlice(object): @lazyproperty def can_compare_pairwise(self): - return self.dim_types == (DT.CAT, DT.CAT) + """Return bool indicating if slice can compute pairwise comparisons. + + Currently, only the CAT x CAT slice can compute pairwise comparisons. This also + includes the categorical array categories dimnension (CA_CAT). + """ + if self.ndim != 2: + return False + + return all(dt in (DT.CAT, DT.CA_CAT) for dt in self.dim_types) @lazyproperty def dim_types(self): diff --git a/tests/unit/test_cube_slice.py b/tests/unit/test_cube_slice.py index <HASH>..<HASH> 100644 --- a/tests/unit/test_cube_slice.py +++ b/tests/unit/test_cube_slice.py @@ -54,10 +54,11 @@ class DescribeCubeSlice(object): assert is_double_mr is expected_value def it_can_compare_pairwise( - self, cube_, dim_types_prop_, pairwise_comparisons_fixture + self, cube_, dim_types_prop_, ndim_prop_, pairwise_comparisons_fixture ): dim_types, slice_can_show = pairwise_comparisons_fixture dim_types_prop_.return_value = dim_types + ndim_prop_.return_value = len(dim_types) slice_ = CubeSlice(cube_, None) assert slice_.can_compare_pairwise == slice_can_show @@ -80,7 +81,8 @@ class DescribeCubeSlice(object): ((DT.DATETIME, DT.CAT), False), ((DT.LOGICAL, DT.CAT), False), ((DT.TEXT, DT.CAT), False), - ((DT.CA_CAT, DT.CAT), False), + ((DT.CA_CAT, DT.CAT), True), + ((DT.CAT, DT.CA_CAT), True), ((DT.CAT, DT.CAT), True), ] ) @@ -248,6 +250,10 @@ class DescribeCubeSlice(object): return property_mock(request, CubeSlice, "dim_types") @pytest.fixture + def ndim_prop_(self, request): + return property_mock(request, CubeSlice, "ndim") + + @pytest.fixture def _array_type_std_res(self, request): return method_mock(request, CubeSlice, "_array_type_std_res")
Allow pairwise for `CA_CAT` dimension type * Add necessary unit tests * Implement functionality This is essentially just a categorical dimension (even though it's paired with a respective CA_SUBVAR dimnension). If the subvar dimension is only used for slicing (of a 3D cube), we can then treat individual slices as categorical x categorical.
Crunch-io_crunch-cube
train
e0302c3f4a0ce8ccb9f3692995382e330ffd2fad
diff --git a/sources/meta/GenerateAll.java b/sources/meta/GenerateAll.java index <HASH>..<HASH> 100644 --- a/sources/meta/GenerateAll.java +++ b/sources/meta/GenerateAll.java @@ -86,6 +86,7 @@ public class GenerateAll extends AbstractMain { FileWriter output = new FileWriter(target); output.write(writer.toString()); output.close(); + target.setReadOnly(); } catch (IOException exception) { throw abort(exception); }
- Added read-only flag to generated files
scala_scala
train
d6f0eb46d2e6966b0b52799a6679ad1bf19fa894
diff --git a/fastjsonschema/generator.py b/fastjsonschema/generator.py index <HASH>..<HASH> 100644 --- a/fastjsonschema/generator.py +++ b/fastjsonschema/generator.py @@ -376,6 +376,7 @@ class CodeGenerator: """ self.l('{variable}_any_of_count = 0') for definition_item in self._definition['anyOf']: + # When we know it's passing (at least once), we do not need to do another expensive try-except. with self.l('if not {variable}_any_of_count:'): with self.l('try:'): self.generate_func_code_block(definition_item, self._variable, self._variable_name, clear_variables=True) @@ -403,10 +404,12 @@ class CodeGenerator: """ self.l('{variable}_one_of_count = 0') for definition_item in self._definition['oneOf']: - with self.l('try:'): - self.generate_func_code_block(definition_item, self._variable, self._variable_name, clear_variables=True) - self.l('{variable}_one_of_count += 1') - self.l('except JsonSchemaException: pass') + # When we know it's failing (one of means exactly once), we do not need to do another expensive try-except. + with self.l('if {variable}_one_of_count < 2:'): + with self.l('try:'): + self.generate_func_code_block(definition_item, self._variable, self._variable_name, clear_variables=True) + self.l('{variable}_one_of_count += 1') + self.l('except JsonSchemaException: pass') with self.l('if {variable}_one_of_count != 1:'): self.l('raise JsonSchemaException("{name} must be valid exactly by one of oneOf definition")')
Optimalization of one of counting
horejsek_python-fastjsonschema
train
375d93bc86fe7d1d277c3d7d742afeeb601eed00
diff --git a/lib/should.js b/lib/should.js index <HASH>..<HASH> 100644 --- a/lib/should.js +++ b/lib/should.js @@ -24,7 +24,10 @@ var should = function(obj) { return new Assertion(util.isWrapperType(obj) ? obj.valueOf(): obj); }; -should.inspect = inspect; +should.inspect = function(obj, opts) { + if(util.isDate(obj) && typeof obj.inspect !== 'function') obj = obj.toISOString(); + return inspect(obj, opts); +}; /** * Expose assert to should diff --git a/test/should.test.js b/test/should.test.js index <HASH>..<HASH> 100644 --- a/test/should.test.js +++ b/test/should.test.js @@ -901,6 +901,17 @@ module.exports = { err(function(){ (function(){ throw 'error'; }).should.throw(Error); }, "expected an exception to be thrown of type Error, but got String"); + }, + + 'test .inspect to format Dates': function() { + var d = new Date(); + should.inspect(d).should.be.exactly("'"+d.toISOString()+"'"); + }, + + 'test .inspect to use custom inspect on Dates': function() { + var d = new Date(); + d.inspect = function() { return this.getTime(); } + should.inspect(d).should.be.exactly(d.getTime().toString()); } };
Allow dates to be formatted as ISOStrings (to display ms). Closes #<I>.
tj_should.js
train
c8953725fa1cb199245bb5d27b16fd753ba07b18
diff --git a/meleeuploader/consts.py b/meleeuploader/consts.py index <HASH>..<HASH> 100755 --- a/meleeuploader/consts.py +++ b/meleeuploader/consts.py @@ -19,6 +19,10 @@ queue_values = os.path.join(os.path.expanduser("~"), ".smash_queue_values.txt") log_file = os.path.join(os.path.expanduser("~"), ".smash_log.txt") custom_list_file = os.path.join(os.path.expanduser("~"), ".smash_custom_list.txt") +abbrv = "smash" +short_name = "meleeuploader" +long_name = "Melee YouTube Uploader" + spreadsheetID = "1TavrlG3uiLLJUwrx6UB0CCyjbiWElYE8sCev6fWclaw" rowRange = "Data!A1:G1" diff --git a/meleeuploader/youtube.py b/meleeuploader/youtube.py index <HASH>..<HASH> 100755 --- a/meleeuploader/youtube.py +++ b/meleeuploader/youtube.py @@ -10,6 +10,8 @@ import sys import errno from decimal import Decimal +from . import consts + from googleapiclient.discovery import build from googleapiclient.errors import HttpError from googleapiclient.http import MediaFileUpload @@ -37,7 +39,8 @@ SPREADSHEETS_SCOPE = "https://www.googleapis.com/auth/spreadsheets" def upload(yt, body, file): vid = None ret = None - while not vid: + retries = 0 + while not vid and retries < 10: insert_request = yt.videos().insert( part=",".join(body.keys()), body=body, @@ -45,6 +48,7 @@ def upload(yt, body, file): chunksize=104857600, resumable=True),) ret, vid = upload_service(insert_request) + retries += 1 return ret, vid @@ -69,6 +73,13 @@ def upload_service(insert_request): elif b"503" in e.content: print("Backend Error: will attempt to retry upload") return False, None + elif b"uploadLimitExceeded" in e.content: + print("You have exceeded the YouTube Upload Limit") + print("Waiting 10 minutes before retrying to avoid the limit") + sleep(600) + return False, None + else: + print("") except retry_exceptions as e: print(f"A retriable error occurred: {e}") @@ -94,12 +105,12 @@ def get_youtube_service(): sys.prefix, os.path.join(sys.prefix, "local"), "/usr", os.path.join("/usr", "local") - ), ("client_secrets.json", ".client_secrets.json", "share/meleeuploader/client_secrets.json")) + ), ("client_secrets.json", ".client_secrets.json", f"share/{consts.short_name}/client_secrets.json")) flow = flow_from_clientsecrets(CLIENT_SECRETS_FILE, scope=YOUTUBE_UPLOAD_SCOPE) - flow.user_agent = "Melee YouTube Uploader" - storage = Storage(os.path.join(os.path.expanduser("~"), ".smash-oauth2-youtube.json")) + flow.user_agent = consts.long_name + storage = Storage(os.path.join(os.path.expanduser("~"), f".{consts.abbrv}-oauth2-youtube.json")) credentials = storage.get() if credentials is None or credentials.invalid: @@ -119,8 +130,8 @@ def get_partner_service(): flow = flow_from_clientsecrets(CLIENT_SECRETS_FILE, scope=("https://www.googleapis.com/auth/youtubepartner", "https://www.googleapis.com/auth/youtube",)) - flow.user_agent = "Melee YouTube Uploader" - storage = Storage(os.path.join(os.path.expanduser("~"), ".smash-oauth2-partner.json")) + flow.user_agent = consts.long_name + storage = Storage(os.path.join(os.path.expanduser("~"), f".{consts.abbrv}-oauth2-partner.json")) credentials = storage.get() if credentials is None or credentials.invalid: @@ -138,13 +149,12 @@ def get_spreadsheet_service(): sys.prefix, os.path.join(sys.prefix, "local"), "/usr", os.path.join("/usr", "local") - ), ("client_secrets.json", ".client_secrets.json", "share/meleeuploader/client_secrets.json")) + ), ("client_secrets.json", ".client_secrets.json", f"share/{consts.short_name}/client_secrets.json")) flow = flow_from_clientsecrets(CLIENT_SECRETS_FILE, scope=SPREADSHEETS_SCOPE) - flow.user_agent = "Melee YouTube Uploader" - - storage = Storage(os.path.join(os.path.expanduser("~"), ".smash-oauth2-spreadsheet.json")) + flow.user_agent = consts.long_name + storage = Storage(os.path.join(os.path.expanduser("~"), f".{consts.abbrv}-oauth2-spreadsheet.json")) credentials = storage.get() if credentials is None or credentials.invalid:
make youtube.py more general
NikhilNarayana_Melee-YouTube-Uploader
train
161e92ef2df6edbae83ca10da8cf541f4f69cdb5
diff --git a/lib/auto-globals.js b/lib/auto-globals.js index <HASH>..<HASH> 100644 --- a/lib/auto-globals.js +++ b/lib/auto-globals.js @@ -17,7 +17,7 @@ function create() { return { dataset: {}, appendChild: stub(), - getAttributes: stub(), + getAttribute: stub(), removeChild: stub(), addEventListener: stub(), removeEventListener: stub(), diff --git a/test/create.js b/test/create.js index <HASH>..<HASH> 100644 --- a/test/create.js +++ b/test/create.js @@ -12,11 +12,11 @@ test('auto-globals: create: querySelector', (t) => { t.end(); }); -test('auto-globals: create: getAttributes', (t) => { +test('auto-globals: create: getAttribute', (t) => { const el = create(); - el.getAttributes.returns('hello'); + el.getAttribute.returns('hello'); - const result = el.getAttributes(); + const result = el.getAttribute(); t.equal(result, 'hello', 'should equal'); t.end();
fix(auto-globals) create: getAttributes -> getAttribute
coderaiser_auto-globals
train
08193ec2fd9b0e47961cbe9c64289bff91500729
diff --git a/DependencyInjection/Configuration.php b/DependencyInjection/Configuration.php index <HASH>..<HASH> 100644 --- a/DependencyInjection/Configuration.php +++ b/DependencyInjection/Configuration.php @@ -288,6 +288,7 @@ class Configuration implements ConfigurationInterface ->append($this->getBoostNode()) ->append($this->getRoutingNode()) ->append($this->getParentNode()) + ->append($this->getAllNode()) ->end() ; @@ -530,4 +531,21 @@ class Configuration implements ConfigurationInterface return $node; } + + /** + * Returns the array node used for "_all" + */ + protected function getAllNode() + { + $builder = new TreeBuilder(); + $node = $builder->root('_all'); + + $node + ->children() + ->scalarNode('enabled')->defaultValue(true)->end() + ->end() + ; + + return $node; + } } diff --git a/DependencyInjection/FOSElasticaExtension.php b/DependencyInjection/FOSElasticaExtension.php index <HASH>..<HASH> 100644 --- a/DependencyInjection/FOSElasticaExtension.php +++ b/DependencyInjection/FOSElasticaExtension.php @@ -231,6 +231,9 @@ class FOSElasticaExtension extends Extension if (isset($type['index'])) { $this->indexConfigs[$indexName]['config']['mappings'][$name]['index'] = $type['index']; } + if (isset($type['_all'])) { + $this->indexConfigs[$indexName]['config']['mappings'][$name]['_all'] = $type['_all']; + } } }
Add support to disable the _all field for a type
FriendsOfSymfony_FOSElasticaBundle
train
8c79daf0ae51210f780393e11e73716dfdc171e5
diff --git a/src/Http/Middleware/VerifyCsrfToken.php b/src/Http/Middleware/VerifyCsrfToken.php index <HASH>..<HASH> 100644 --- a/src/Http/Middleware/VerifyCsrfToken.php +++ b/src/Http/Middleware/VerifyCsrfToken.php @@ -1,13 +1,12 @@ <?php namespace Laravel\Lumen\Http\Middleware; use Closure; -use Illuminate\Contracts\Routing\Middleware; use Symfony\Component\HttpFoundation\Cookie; use Illuminate\Contracts\Encryption\Encrypter; use Illuminate\Session\TokenMismatchException; use Symfony\Component\Security\Core\Util\StringUtils; -class VerifyCsrfToken implements Middleware +class VerifyCsrfToken { /**
Don't implement deprecated interface
orchestral_lumen
train
f9e14b02f586d509499b292ea9b8017208f02ce3
diff --git a/modules/system/twig/Loader.php b/modules/system/twig/Loader.php index <HASH>..<HASH> 100644 --- a/modules/system/twig/Loader.php +++ b/modules/system/twig/Loader.php @@ -2,6 +2,7 @@ use App; use File; +use View; use Twig\Source as TwigSource; use Twig\Loader\LoaderInterface as TwigLoaderInterface; use Exception; @@ -15,11 +16,6 @@ use Exception; class Loader implements TwigLoaderInterface { /** - * @var string Expected file extension - */ - protected $extension = 'htm'; - - /** * @var array Cache */ protected $cache = []; @@ -37,22 +33,13 @@ class Loader implements TwigLoaderInterface return $this->cache[$name]; } - if (File::isFile($name)) { - return $this->cache[$name] = $name; - } - - $view = $name; - if (File::extension($view) === $this->extension) { - $view = substr($view, 0, -strlen($this->extension)); - } - - $path = $finder->find($view); + $path = $finder->find($name); return $this->cache[$name] = $path; } public function getSourceContext($name) { - return new TwigSource(File::get($this->findTemplate($name)), $name); + return new TwigSource((string) View::make($name), $name); } public function getCacheKey($name)
Only allow view files in system twig This no longer allows arbitrary inclusions, only views from the native Laravel view engine. Note this also affects the cms twig loader
octobercms_october
train
85186ff0b717d673090170fa4b44e699889af551
diff --git a/lib/ruby_speech/generic_element.rb b/lib/ruby_speech/generic_element.rb index <HASH>..<HASH> 100644 --- a/lib/ruby_speech/generic_element.rb +++ b/lib/ruby_speech/generic_element.rb @@ -115,10 +115,10 @@ module RubySpeech if const_name == 'String' || self.class.module.const_defined?(const_name) const = self.class.module.const_get const_name if self.class::VALID_CHILD_TYPES.include?(const) - if const == String - self << encode_special_chars(args.first) + self << if const == String + encode_special_chars args.first else - self << const.new(*args, &block) + const.new *args, &block end end elsif @block_binding && @block_binding.respond_to?(method_name)
[CS] Minor reduction in duplication
adhearsion_ruby_speech
train
337ca6b896f334cfe489e4a22edae659687ff809
diff --git a/isort/parse.py b/isort/parse.py index <HASH>..<HASH> 100644 --- a/isort/parse.py +++ b/isort/parse.py @@ -293,6 +293,7 @@ def file_contents(contents: str, config: Config = DEFAULT_CONFIG) -> ParsedConte else: while line.strip().endswith("\\"): line, new_comment = parse_comments(in_lines[index]) + line = line.lstrip() index += 1 if new_comment: comments.append(new_comment)
Correct the multiline tab bug as raised in issue #<I>
timothycrosley_isort
train
b1249adcd4ee1c367868e942657b60e141fdbb86
diff --git a/src/Storage.php b/src/Storage.php index <HASH>..<HASH> 100644 --- a/src/Storage.php +++ b/src/Storage.php @@ -27,7 +27,7 @@ class Storage implements IStorage { return false; } if (!is_writable($this->file)) { - @chmod($this->file, '0755'); + @chmod($this->file, 0755); if (!is_writable($this->file)) { $this->error = "Please make the storage file writable: $this->file"; return false;
set the proper permission bits on storage.json chmod '<I>' actually sets the mode to: --wxrw--wt chmod needs permissions in octal to set: -rwxr-xr-x
ptrofimov_beanstalk_console
train
8493e05a6a66a64fce03ceaa98c2c26c503a922c
diff --git a/lib/client.js b/lib/client.js index <HASH>..<HASH> 100644 --- a/lib/client.js +++ b/lib/client.js @@ -15,6 +15,18 @@ var Client = function() { var that = this; + var deleteLocalFile = function(file){ + var deferred = Q.defer(); + fs.unlink(file, function (err) { + if (err) { + deferred.reject(err); + } else { + deferred.resolve(); + } + }); + return deferred.promise; + }; + var writeToLocalFile = function(project, file){ var deferred = Q.defer(); project.getFile(file).then(function(source){ @@ -61,7 +73,7 @@ var Client = function() { } else if(overwrite === that.OVERWRITE_IF_NEWER){ result.action = ( new Date(remoteFile.lastModified).getTime() - < + > new Date(localFile.lastModified).getTime() ); deferred.resolve(result); @@ -74,6 +86,7 @@ var Client = function() { this.download = function(project, remote, local, overwrite, deleteOrphaned, simulate){ var promises = []; + Object.keys(remote).forEach(function(file){ var remoteFile = { @@ -111,6 +124,30 @@ var Client = function() { return deferred.promise; }); }); + + if(deleteOrphaned) { + Object.keys(local).forEach(function(file){ + if(!remote[file]) { + promises.push(function(){ + var deferred = Q.defer(); + console.log('Delete ' + file); + if(!simulate) { + deleteLocalFile(file) + .then(function(){ + deferred.resolve(); + }) + .catch(function(error){ + deferred.reject(error); + }); + } else { + deferred.resolve(); + } + return deferred.promise; + }); + } + }); + } + return promises.reduce(Q.when, Q()); } };
Implement orphanted option in the download command.
28msec_28
train
5172d915b4293cfe94da2343c43340bbc7ff6833
diff --git a/lib/pkgr/buildpack.rb b/lib/pkgr/buildpack.rb index <HASH>..<HASH> 100644 --- a/lib/pkgr/buildpack.rb +++ b/lib/pkgr/buildpack.rb @@ -98,7 +98,7 @@ module Pkgr def replace_app_with_app_home(app_home) Dir.chdir(dir) do - buildpack_replace = Mixlib::ShellOut.new("find . -type f -not -path '*/.git/*' -print0 | xargs -0 perl -pi -e s,/app,#{app_home},g") + buildpack_replace = Mixlib::ShellOut.new("find . -type f -not -path '*/.git/*' -print0 | xargs -0 perl -pi -e s,/app/,#{app_home}/,g") buildpack_replace.logger = Pkgr.logger buildpack_replace.run_command buildpack_replace.error!
Replace only instances of `/app/` and not `/app` in buildpacks Fixes #<I>
crohr_pkgr
train
dd3b055d9c49e013634e480867151d09c7dc5ba5
diff --git a/swifter/swifter.py b/swifter/swifter.py index <HASH>..<HASH> 100644 --- a/swifter/swifter.py +++ b/swifter/swifter.py @@ -217,6 +217,11 @@ class SeriesAccessor(_SwifterObject): """ Apply the function to the Series using swifter """ + + # Short-circuit an empty Series + if not self._nrows: + return self._obj.apply(func, convert_dtype=convert_dtype, args=args, **kwds) + sample = self._obj.iloc[: self._npartitions * 2] # check if input is string or if the user is overriding the string processing default allow_dask_processing = True if self._allow_dask_on_strings else (sample.dtype != "object") @@ -324,6 +329,20 @@ class DataFrameAccessor(_SwifterObject): """ Apply the function to the DataFrame using swifter """ + + # If there are no rows + if not self._nrows: + return self._obj.apply( + func, + axis=axis, + broadcast=broadcast, + raw=raw, + reduce=reduce, + result_type=result_type, + args=args, + **kwds + ) + sample = self._obj.iloc[: self._npartitions * 2, :] # check if input is string or if the user is overriding the string processing default allow_dask_processing = True if self._allow_dask_on_strings else ("object" not in sample.dtypes.values) diff --git a/swifter/swifter_tests.py b/swifter/swifter_tests.py index <HASH>..<HASH> 100644 --- a/swifter/swifter_tests.py +++ b/swifter/swifter_tests.py @@ -358,3 +358,13 @@ class TestSwifter(unittest.TestCase): self.assertEqual(pd_val, swifter_val) self.assertLess(swifter_time, pd_time) + + def test_apply_on_empty_dataframe(self): + df = pd.DataFrame() + df.swifter.apply(lambda x : 1, axis=1) + + def test_appply_on_empty_series(self): + series = pd.Series() + series.swifter.apply(math_foo, compare_to=1) + +
Add tests and short-circuit for empty dataframes and series
jmcarpenter2_swifter
train
c849f407212075d53d6331aa6984d1c1794130f5
diff --git a/core/metrics-core-service/src/main/java/org/hawkular/metrics/core/service/MetricsServiceImpl.java b/core/metrics-core-service/src/main/java/org/hawkular/metrics/core/service/MetricsServiceImpl.java index <HASH>..<HASH> 100644 --- a/core/metrics-core-service/src/main/java/org/hawkular/metrics/core/service/MetricsServiceImpl.java +++ b/core/metrics-core-service/src/main/java/org/hawkular/metrics/core/service/MetricsServiceImpl.java @@ -46,6 +46,7 @@ import org.hawkular.metrics.core.service.transformers.MetricsIndexRowTransformer import org.hawkular.metrics.core.service.transformers.TagsIndexRowTransformer; import org.hawkular.metrics.model.AvailabilityBucketPoint; import org.hawkular.metrics.model.AvailabilityType; +import org.hawkular.metrics.model.BucketPoint; import org.hawkular.metrics.model.Buckets; import org.hawkular.metrics.model.DataPoint; import org.hawkular.metrics.model.Metric; @@ -705,7 +706,7 @@ public class MetricsServiceImpl implements MetricsService { buckets, percentiles); } } else { - Observable<Observable<NumericBucketPoint>> individualStats = null; + Observable<Observable<NumericBucketPoint>> individualStats; if (MetricType.COUNTER.equals(metricType) || MetricType.GAUGE.equals(metricType)) { individualStats = findMetricsWithFilters(tenantId, metricType, tagFilters) @@ -719,11 +720,12 @@ public class MetricsServiceImpl implements MetricsService { } return Observable.merge(individualStats) - .groupBy(g -> g.getStart()) + .groupBy(BucketPoint::getStart) .flatMap(group -> group.collect(SumNumericBucketPointCollector::new, SumNumericBucketPointCollector::increment)) .map(SumNumericBucketPointCollector::toBucketPoint) - .toList(); + .toMap(NumericBucketPoint::getStart) + .map(pointMap -> NumericBucketPoint.toList(pointMap, buckets)); } }; @@ -749,7 +751,7 @@ public class MetricsServiceImpl implements MetricsService { buckets, percentiles); } } else { - Observable<Observable<NumericBucketPoint>> individualStats = null; + Observable<Observable<NumericBucketPoint>> individualStats; if (MetricType.COUNTER.equals(metricType) || MetricType.GAUGE.equals(metricType)) { individualStats = Observable.from(metrics) @@ -767,11 +769,12 @@ public class MetricsServiceImpl implements MetricsService { } return Observable.merge(individualStats) - .groupBy(g -> g.getStart()) - .flatMap(group -> group.collect(() -> new SumNumericBucketPointCollector(), + .groupBy(BucketPoint::getStart) + .flatMap(group -> group.collect(SumNumericBucketPointCollector::new, SumNumericBucketPointCollector::increment)) .map(SumNumericBucketPointCollector::toBucketPoint) - .toList(); + .toMap(NumericBucketPoint::getStart) + .map(pointMap -> NumericBucketPoint.toList(pointMap, buckets)); } }
HWKMETRICS-<I> Stacked metrics not ordered in any way BucketPointCollector instances can be emitted in any order (coming from a flatMap of a groupObservable).
hawkular_hawkular-metrics
train
b271c62e6b7413b0521a45f89727ccc79df3aea8
diff --git a/lib/biran/configurinator.rb b/lib/biran/configurinator.rb index <HASH>..<HASH> 100644 --- a/lib/biran/configurinator.rb +++ b/lib/biran/configurinator.rb @@ -30,12 +30,17 @@ module Biran .tap { |files_list| files_list.each(&sanitize_config_files(files_list)) } end - def create(name:, extension:, output_dir: nil, output_name: nil) + def create(name:, extension:, output_dir: nil, output_name: nil, config_index_list: []) output_dir ||= config_dir output_name ||= name generated_file = ERBConfig.new(filtered_config, name, extension, config_dir, output_dir, output_name) generated_file.bindings = bindings - generated_file.save! + return generated_file.save! unless config_index_list.any? + config_index_list.each do |config_index| + generated_file.output_name = "#{output_name}-#{config_index}" + generated_file.config_index = config_index + generated_file.save! + end end private diff --git a/lib/biran/erb_config.rb b/lib/biran/erb_config.rb index <HASH>..<HASH> 100644 --- a/lib/biran/erb_config.rb +++ b/lib/biran/erb_config.rb @@ -1,7 +1,9 @@ module Biran class ERBConfig - attr_reader :output_dir, :source_dir, :name, :extension, :config, :output_name - attr_accessor :bindings + attr_reader :output_dir, :source_dir, :name, :extension, :config, :template_contents + attr_accessor :bindings, :output_name, :config_index + + DEFAULT_CONFIG_INDEX = 1 def initialize(config, name, extension, source, output_dir, output_name) @name = name @@ -10,11 +12,12 @@ module Biran @source_dir = source @output_dir = output_dir @output_name = output_name + @template_contents = process_erb end def save! File.open(File.join(output_dir, "#{output_name}#{extension}"), 'w') do |f| - f.print process_erb.result(build_erb_env.call) + f.print template_contents.result(build_erb_env.call) end end @@ -29,6 +32,7 @@ module Biran proc do @environment = config[:env] @app_config = config + @config_index = config_index || DEFAULT_CONFIG_INDEX @bindings.each(&assign_instance_vars) unless @bindings.nil?
Re-use erb template to generate multiple copies - ERBConfig creates an instance of the template and we pass in a separate config index number that can be used to pull different values from different parts of the config block passed to the template - If no list of config indexes is passed, we retain current, previous behaviour.
amco_biran
train
468507ed3fb82c65de600be5f75a0ac1f922997e
diff --git a/src/ai-examples/HISTORY.rst b/src/ai-examples/HISTORY.rst index <HASH>..<HASH> 100644 --- a/src/ai-examples/HISTORY.rst +++ b/src/ai-examples/HISTORY.rst @@ -3,6 +3,10 @@ Release History =============== +0.2.3 +++++++ +* Add fallback to use built-in values if there is an issue with using the service + 0.2.2 ++++++ * Fix bug causing queries to fail when not logged in and when telemetry is disabled diff --git a/src/ai-examples/azext_ai_examples/custom.py b/src/ai-examples/azext_ai_examples/custom.py index <HASH>..<HASH> 100644 --- a/src/ai-examples/azext_ai_examples/custom.py +++ b/src/ai-examples/azext_ai_examples/custom.py @@ -24,7 +24,13 @@ def check_connection_aladdin(): def new_examples(help_file): - help_file.examples = replace_examples(help_file.command) + try: + examples = replace_examples(help_file.command) + except requests.exceptions.ConnectionError: + examples = [] + + if examples: + help_file.examples = examples # Replace built in examples with Aladdin ones diff --git a/src/ai-examples/setup.py b/src/ai-examples/setup.py index <HASH>..<HASH> 100644 --- a/src/ai-examples/setup.py +++ b/src/ai-examples/setup.py @@ -15,7 +15,7 @@ except ImportError: logger.warn("Wheel is not available, disabling bdist_wheel hook") # HISTORY.rst entry. -VERSION = '0.2.2' +VERSION = '0.2.3' # The full list of classifiers is available at # https://pypi.python.org/pypi?%3Aaction=list_classifiers
[ai-examples] Add fallback to use built-in values if there is an issue with the service (#<I>)
Azure_azure-cli-extensions
train
a57fe164e9bd3841fac0d984e5340711964ae540
diff --git a/composer.json b/composer.json index <HASH>..<HASH> 100644 --- a/composer.json +++ b/composer.json @@ -22,7 +22,7 @@ }, "require": { "php": ">=7.1", - "laravie/codex": "~2.2", + "laravie/codex": "^1.5", "moneyphp/money": "^3.0", "php-http/multipart-stream-builder": "^1.0" }, diff --git a/src/Base/Bill.php b/src/Base/Bill.php index <HASH>..<HASH> 100644 --- a/src/Base/Bill.php +++ b/src/Base/Bill.php @@ -112,7 +112,7 @@ abstract class Bill extends Request 'billplzid', 'billplzpaid_at', 'billplzpaid', ]); - if (!! $validated) { + if ((bool) $validated) { return $this->sanitizeTo($data['billplz']); } } @@ -131,7 +131,7 @@ abstract class Bill extends Request 'paid_amount', 'paid_at', 'paid', 'state', 'url', ]); - if (!! $validated) { + if ((bool) $validated) { return $this->sanitizeTo($data); } } @@ -144,10 +144,9 @@ abstract class Bill extends Request * @param array $parameters * * @throws \Billplz\Exceptions\FailedSignatureVerification + * @throws \Billplz\Exceptions\FailedSignatureVerification * * @return bool - * - * @throws \Billplz\Exceptions\FailedSignatureVerification */ final protected function validateAgainstSignature(array $bill, ?string $signatureKey = null, array $parameters = []): bool { diff --git a/src/Request.php b/src/Request.php index <HASH>..<HASH> 100644 --- a/src/Request.php +++ b/src/Request.php @@ -2,8 +2,8 @@ namespace Billplz; +use Laravie\Codex\Endpoint; use Psr\Http\Message\UriInterface; -use Laravie\Codex\Contracts\Endpoint; use Laravie\Codex\Request as BaseRequest; abstract class Request extends BaseRequest diff --git a/src/Sanitizer.php b/src/Sanitizer.php index <HASH>..<HASH> 100644 --- a/src/Sanitizer.php +++ b/src/Sanitizer.php @@ -17,13 +17,13 @@ class Sanitizer extends BaseSanitizer $datetime = $casters['datetime'] ?? Casts\DateTime::class; $this->casts = [ - 'total' => new $money, - 'amount' => new $money, - 'due_at' => new $datetime, - 'paid_amount' => new $money, - 'paid_at' => new $datetime, + 'total' => new $money(), + 'amount' => new $money(), + 'due_at' => new $datetime(), + 'paid_amount' => new $money(), + 'paid_at' => new $datetime(), 'split_payment' => [ - 'fixed_cut' => new $money, + 'fixed_cut' => new $money(), ], ]; } diff --git a/tests/Base/BillTestCase.php b/tests/Base/BillTestCase.php index <HASH>..<HASH> 100644 --- a/tests/Base/BillTestCase.php +++ b/tests/Base/BillTestCase.php @@ -134,7 +134,7 @@ abstract class BillTestCase extends TestCase 'paid' => 'true', 'paid_at' => '2018-03-12+12%3A46%3A36+%2B0800', ], - 'x_signature' => 'a4ec01becf3b5f0221d1ad4a1296d77d1e9f8d3cc2d4404973d863983a25760f' + 'x_signature' => 'a4ec01becf3b5f0221d1ad4a1296d77d1e9f8d3cc2d4404973d863983a25760f', ]; $bill = $this->makeClient() @@ -162,7 +162,7 @@ abstract class BillTestCase extends TestCase 'paid' => 'false', 'paid_at' => '2018-03-12+12%3A46%3A36+%2B0800', ], - 'x_signature' => 'a4ec01becf3b5f0221d1ad4a1296d77d1e9f8d3cc2d4404973d863983a25760f' + 'x_signature' => 'a4ec01becf3b5f0221d1ad4a1296d77d1e9f8d3cc2d4404973d863983a25760f', ]; $bill = $this->makeClient()
Make it work with current codex first.
jomweb_billplz
train
0070208c904811a81b355505ac69eb0f8713fbbf
diff --git a/mongo_connector/connector.py b/mongo_connector/connector.py index <HASH>..<HASH> 100644 --- a/mongo_connector/connector.py +++ b/mongo_connector/connector.py @@ -365,9 +365,10 @@ class Connector(threading.Thread): else: # sharded cluster while self.can_run: - - for shard_doc in retry_until_ok(self.main_conn.admin.command, - 'listShards')['shards']: + # The backup role does not provide the listShards privilege, + # so use the config.shards collection instead. + for shard_doc in retry_until_ok( + lambda: list(self.main_conn.config.shards.find())): shard_id = shard_doc['_id'] if shard_id in self.shard_set: shard_thread = self.shard_set[shard_id]
Bug fix: backup role does not provide the listShards privilege (#<I>) Fixes #<I>.
yougov_mongo-connector
train
50b9cc3b4bae74c38998f0665943811d2e8fcd7a
diff --git a/lib/MiqVm/test/partitionAlignmentCheck.rb b/lib/MiqVm/test/partitionAlignmentCheck.rb index <HASH>..<HASH> 100644 --- a/lib/MiqVm/test/partitionAlignmentCheck.rb +++ b/lib/MiqVm/test/partitionAlignmentCheck.rb @@ -9,7 +9,7 @@ $vim_log = $log = Logger.new(STDERR) SERVER = raise "please define SERVER" USERNAME = raise "please define USERNAME" PASSWORD = raise "please define PASSWORD" -vim = MiqVim.new(SERVER, USERNAME, PASSWORD) +vim = MiqVim.new(:server => SERVER, :username => USERNAME, :password => PASSWORD) vimVm = nil vm = nil diff --git a/lib/MiqVm/test/remoteVm.rb b/lib/MiqVm/test/remoteVm.rb index <HASH>..<HASH> 100644 --- a/lib/MiqVm/test/remoteVm.rb +++ b/lib/MiqVm/test/remoteVm.rb @@ -13,7 +13,7 @@ USERNAME = raise "please define USERNAME" PASSWORD = raise "please define PASSWORD" TARGET_VM = raise "please define TARGET_VM" -vim = MiqVim.new(SERVER, USERNAME, PASSWORD) +vim = MiqVim.new(:server => SERVER, :username => USERNAME, :password => PASSWORD) begin vim_vm = vim.getVimVmByFilter("config.name" => TARGET_VM) diff --git a/lib/VolumeManager/test/ldm.rb b/lib/VolumeManager/test/ldm.rb index <HASH>..<HASH> 100644 --- a/lib/VolumeManager/test/ldm.rb +++ b/lib/VolumeManager/test/ldm.rb @@ -4,8 +4,8 @@ require 'more_core_extensions/core_ext/object/blank' require 'metadata/VmConfig/VmConfig' require "VolumeManager/MiqVolumeManager" require "fs/MiqFS/MiqFS" +require "MiqVm/MiqVim" require "MiqVm/MiqVm" -require 'VMwareWebService/MiqVimBroker' SRC_VM = raise "please define" vmCfg = "/Volumes/WDpassport/Virtual Machines/MIQAppliance-win2008x86/Win2008x86.vmx" @@ -19,8 +19,7 @@ vim = nil begin # Uncomment following 2 lines for clienr/server connection. - # broker = MiqVimBroker.new(:client) - # vim = broker.getMiqVim(SERVER, USERNAME, PASSWORD) + # vim = MiqVim.new(:server => SERVER, :username => USERNAME, :password => PASSWORD) # miqVm = vim.getVimVmByFilter("config.name" => SRC_VM) # # vmCfg = miqVm.vmh['summary']['config']['vmPathName'] diff --git a/lib/metadata/VmConfig/VmConfig.rb b/lib/metadata/VmConfig/VmConfig.rb index <HASH>..<HASH> 100644 --- a/lib/metadata/VmConfig/VmConfig.rb +++ b/lib/metadata/VmConfig/VmConfig.rb @@ -413,7 +413,7 @@ class VmConfig require 'VMwareWebService/MiqVim' password_decrypt = ManageIQ::Password.decrypt(ems_host['password']) - hostVim = MiqVim.new(ems_host['host'], ems_host['user'], password_decrypt) + hostVim = MiqVim.new(:server => ems_host['host'], :username => ems_host['user'], :password => password_decrypt) $log.info "#{conn_reason}: Connection to [#{ems_display_text}] completed for VM:[#{vmCfgFile}] in [#{Time.now - st}] seconds" return hostVim rescue Timeout::Error => err @@ -431,7 +431,7 @@ class VmConfig password_decrypt = ManageIQ::Password.decrypt(ems['password']) $log.debug "resolve_path_names: emsHost = #{ems['host']}, emsUser = #{ems['user']}" if $log - vi = MiqVimInventory.new(ems['host'], ems['user'], password_decrypt) + vi = MiqVimInventory.new(:server => ems['host'], :username => ems['user'], :password => password_decrypt) return getDsName(filename, vi) rescue diff --git a/manageiq-smartstate.gemspec b/manageiq-smartstate.gemspec index <HASH>..<HASH> 100644 --- a/manageiq-smartstate.gemspec +++ b/manageiq-smartstate.gemspec @@ -31,7 +31,7 @@ Gem::Specification.new do |spec| spec.add_dependency "rufus-lru", "~>1.0.3" spec.add_dependency "sys-uname", "~>1.2.1" spec.add_dependency "uuidtools", "~>2.1" - spec.add_dependency "vmware_web_service", "~>2.0" + spec.add_dependency "vmware_web_service", "~>3.0" spec.add_development_dependency "bundler" spec.add_development_dependency "camcorder"
Updates for the new MiqVim kwargs format
ManageIQ_manageiq-smartstate
train
ef59846a6c5c2d75cb981d37603a8920b20e67f9
diff --git a/templates.py b/templates.py index <HASH>..<HASH> 100644 --- a/templates.py +++ b/templates.py @@ -111,6 +111,72 @@ def disable_rate(start_date, experiment_id, addon_versions): ORDER BY date) """.format(start_date, experiment_id, addon_versions), ["date", "disable_rate", "type"] +def retention(events_table, retention_type, start_date, where_clause): + return """ + WITH population AS + (SELECT client_id AS unique_id, DATE_TRUNC('{1}', date) AS cohort_date, COUNT(*) + FROM {0} + WHERE 1 = 1 + {3} + GROUP BY 1, 2), + + activity AS + (SELECT DATE_TRUNC('{1}', date) AS activity_date, client_id AS unique_id, cohort_date + FROM {0} + JOIN population + ON population.unique_id = client_id + WHERE DATE_TRUNC('{1}', date) >= (CURRENT_DATE - INTERVAL '91 days') + AND DATE_TRUNC('{1}', cohort_date) >= (CURRENT_DATE - INTERVAL '91 days') + {3}), + + population_agg AS + (SELECT DATE_TRUNC('{1}', date) AS cohort_date, COUNT(DISTINCT client_id) AS total + FROM {0} + WHERE 1 = 1 + {3} + GROUP BY 1) + + SELECT * FROM + (SELECT date, day as week_number, value, total, MAX(day) over (PARTITION BY date) AS max_week_num + FROM + (SELECT activity.cohort_date AS date, + DATE_DIFF('{1}', activity.cohort_date, activity_date) AS day, + total, + COUNT(DISTINCT unique_id) AS value + FROM activity + JOIN population_agg + ON activity.cohort_date = population_agg.cohort_date + WHERE activity_date >= activity.cohort_date + AND activity.cohort_date > '{2}' + GROUP BY 1, 2, 3)) + WHERE week_number < max_week_num + ORDER BY date, week_number""".format(events_table, retention_type, start_date, where_clause), [] + +def all_events_weekly(events_table, start_date, where_clause): + return """ + WITH weekly_events AS + (SELECT DATE_TRUNC('week', date) AS week, COUNT(*) + FROM {0} + WHERE DATE_TRUNC('week', date) >= '{1}' + {2} + GROUP BY 1), + + event_counts AS + (SELECT week, event_type, count FROM + (SELECT *, RANK() over (PARTITION BY week ORDER BY count) AS rank FROM + (SELECT DATE_TRUNC('week', date) AS week, event_type, COUNT(*) + FROM {0} + WHERE DATE_TRUNC('week', date) >= '{1}' + {2} + GROUP BY 1, 2 + ORDER BY 1, 2)) + WHERE rank <= 20) + + SELECT weekly_events.week, event_counts.event_type, event_counts.count / weekly_events.count::FLOAT * 100 AS rate + FROM weekly_events + LEFT JOIN event_counts + ON weekly_events.week = event_counts.week""".format(events_table, start_date, where_clause), ["week", "rate", "event_type"] + def retention_diff(start_date, experiment_id, addon_versions): return """ WITH control_interactions AS @@ -192,4 +258,4 @@ def retention_diff(start_date, experiment_id, addon_versions): LEFT JOIN exp_retention AS exp ON con.date = exp.date AND con.week_number = exp.week_number - ORDER BY date, week_number""".format(start_date, experiment_id, addon_versions), ["date", "event_rate", "type"] + ORDER BY date, week_number""".format(start_date, experiment_id, addon_versions), []
Add retention and weekly events SQL templates.
mozilla_redash_client
train
a85a48266edfd5373207c6d0bbc007a786051c55
diff --git a/httpclient.go b/httpclient.go index <HASH>..<HASH> 100644 --- a/httpclient.go +++ b/httpclient.go @@ -565,7 +565,7 @@ func (c *HttpClient) Params(params map[string]interface{}) RequestOption { } // set the request URL parameters -func (c *HttpClient) StringParams(params map[string]string) RequestOption { +func StringParams(params map[string]string) RequestOption { return func(req *http.Request) (*http.Request, error) { q := req.URL.Query() for k, v := range params { @@ -576,7 +576,7 @@ func (c *HttpClient) StringParams(params map[string]string) RequestOption { } } -func StringParams(params map[string]string) RequestOption { +func (c *HttpClient) StringParams(params map[string]string) RequestOption { return StringParams(params) } @@ -589,17 +589,16 @@ func Body(r io.Reader) RequestOption { return req, nil } - rc, ok := r.(io.ReadCloser) - if !ok { - rc = ioutil.NopCloser(r) + if rc, ok := r.(io.ReadCloser); ok { + req.Body = rc + } else { + req.Body = ioutil.NopCloser(r) } - req.Body = rc - - if v, ok := r.(interface { - Len() int - }); ok { + if v, ok := r.(interface{ Len() int }); ok { req.ContentLength = int64(v.Len()) + } else if v, ok := r.(interface{ Size() int64 }); ok { + req.ContentLength = v.Size() } return req, nil
Fix StringParams and improved Body RequestOptions
gobs_httpclient
train
c55f7dfd642ce6580006084cbc9c686e8be4ddbb
diff --git a/plugins/provisioners/docker/config.rb b/plugins/provisioners/docker/config.rb index <HASH>..<HASH> 100644 --- a/plugins/provisioners/docker/config.rb +++ b/plugins/provisioners/docker/config.rb @@ -12,6 +12,10 @@ module VagrantPlugins @version = :latest end + def images=(images) + @images = Set.new(images) + end + def pull_images(*images) @images += images.map(&:to_s) end diff --git a/plugins/provisioners/docker/provisioner.rb b/plugins/provisioners/docker/provisioner.rb index <HASH>..<HASH> 100644 --- a/plugins/provisioners/docker/provisioner.rb +++ b/plugins/provisioners/docker/provisioner.rb @@ -12,6 +12,7 @@ module VagrantPlugins class Provisioner < Vagrant.plugin("2", :provisioner) def initialize(machine, config, installer = nil, client = nil) super(machine, config) + # TODO: Rename to installer / client (drop docker suffix) @installer = installer || DockerInstaller.new(@machine, config.version) @client = client || DockerClient.new(@machine)
provisioners/docker: allow images to be configured with images:
hashicorp_vagrant
train
296d9ee6746eda4164ad54ad5d3b8154a88850f8
diff --git a/source/rafcon/mvc/controllers/main_window.py b/source/rafcon/mvc/controllers/main_window.py index <HASH>..<HASH> 100644 --- a/source/rafcon/mvc/controllers/main_window.py +++ b/source/rafcon/mvc/controllers/main_window.py @@ -34,6 +34,7 @@ from rafcon.mvc.config import global_gui_config as gui_config from rafcon.mvc.runtime_config import global_runtime_config from rafcon.mvc.utils import constants from rafcon.mvc import gui_helper +from rafcon.utils import plugins from rafcon.utils import log logger = log.get_logger(__name__) @@ -250,6 +251,8 @@ class MainWindowController(ExtendedController): import rafcon.mvc.models.auto_backup as auto_backup auto_backup.check_for_crashed_rafcon_instances() + plugins.run_hook("main_window_setup", self) + def print_paned_pos(self, width, height, config_id): pane_id = constants.PANE_ID[config_id] view = self.view[pane_id] diff --git a/source/rafcon/mvc/controllers/menu_bar.py b/source/rafcon/mvc/controllers/menu_bar.py index <HASH>..<HASH> 100644 --- a/source/rafcon/mvc/controllers/menu_bar.py +++ b/source/rafcon/mvc/controllers/menu_bar.py @@ -30,7 +30,8 @@ from rafcon.mvc.config import global_gui_config from rafcon.mvc.runtime_config import global_runtime_config from rafcon.mvc.utils.dialog import RAFCONDialog -from rafcon.utils import log, constants +from rafcon.utils import plugins +from rafcon.utils import log logger = log.get_logger(__name__) @@ -527,6 +528,9 @@ class MenuBarController(ExtendedController): # Should close all tabs core_singletons.state_machine_manager.delete_all_state_machines() # Recursively destroys the main window + + plugins.run_hook("pre_main_window_destruction", mvc_singleton.main_window_controller) + mvc_singleton.main_window_controller.destroy() self.logging_view.quit_flag = True glib.idle_add(log.unregister_logging_view, 'main') diff --git a/source/rafcon/mvc/start.py b/source/rafcon/mvc/start.py index <HASH>..<HASH> 100755 --- a/source/rafcon/mvc/start.py +++ b/source/rafcon/mvc/start.py @@ -172,6 +172,8 @@ if __name__ == '__main__': sm.root_state.join() finally: + plugins.run_hook("post_main_window_destruction") + if profiler: stop_profiler(profiler) if global_gui_config.get_config_value('AUTO_RECOVERY_LOCK_ENABLED'):
Add three new hooks - main_window_setup: Passes reference to the main window controller and is called after the view has been registered - pre_main_window_destruction: Passes reference to the main window controller and is called right before the main window is destroyed - post_main_window_destruction: is called after the GTK main loop has been terminated
DLR-RM_RAFCON
train
d854111e1e5a36c6d4a567223a79bf48443889fb
diff --git a/code/libraries/joomlatools/component/koowa/dispatcher/behavior/decoratable.php b/code/libraries/joomlatools/component/koowa/dispatcher/behavior/decoratable.php index <HASH>..<HASH> 100644 --- a/code/libraries/joomlatools/component/koowa/dispatcher/behavior/decoratable.php +++ b/code/libraries/joomlatools/component/koowa/dispatcher/behavior/decoratable.php @@ -86,7 +86,7 @@ class ComKoowaDispatcherBehaviorDecoratable extends KControllerBehaviorAbstract $response = $context->getResponse(); //Pass back to Joomla - if(!$response->isDownloadable() && $this->getDecorator() == 'joomla') + if(!$response->isRedirect() && !$response->isDownloadable() && $this->getDecorator() == 'joomla') { //Contenttype JFactory::getDocument()->setMimeEncoding($response->getContentType());
#<I> Ignore re-direct requests
joomlatools_joomlatools-framework
train
755fea6e481f657d68cd09a9ebd5957099b5668d
diff --git a/Password.php b/Password.php index <HASH>..<HASH> 100755 --- a/Password.php +++ b/Password.php @@ -464,17 +464,17 @@ class Text_Password { switch($chars) { case 'alphanumeric': - $regex = 'A|B|C|D|E|F|G|H|I|J|K|L|M|N|O|P|Q|R|S|T|U|V|W|X|Y|Z|a|b|c|d|e|f|g|h|i|j|k|l|m|n|o|p|q|r|s|t|u|v|w|x|y|z|0|1|2|3|4|5|6|7|8|9'; + $chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'; $_Text_Password_NumberOfPossibleCharacters = 62; break; case 'numeric': - $regex = '0|1|2|3|4|5|6|7|8|9'; + $chars = '0123456789'; $_Text_Password_NumberOfPossibleCharacters = 10; break; case '': - $regex = '_|#|@|%|�|&|�|A|B|C|D|E|F|G|H|I|J|K|L|M|N|O|P|Q|R|S|T|U|V|W|X|Y|Z|a|b|c|d|e|f|g|h|i|j|k|l|m|n|o|p|q|r|s|t|u|v|w|x|y|z|0|1|2|3|4|5|6|7|8|9'; + $chars = '_#@%�&�ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'; $_Text_Password_NumberOfPossibleCharacters = 69; break; @@ -495,19 +495,17 @@ class Text_Password { $chars = substr($chars, 0, -1); } - $regex = str_replace(',', '|', $chars); - $_Text_Password_NumberOfPossibleCharacters = strlen(str_replace(',', '', $chars)); + $chars = str_replace(',', '', $chars); + $_Text_Password_NumberOfPossibleCharacters = strlen($chars); } /** * Generate password */ - do { - $chr = chr(mt_rand(0, 255)); - if (preg_match('/'.$regex.'/US', $chr)) { - $password .= $chr; - } - } while (strlen($password) < $length); + for ($i = 0; $i < $length; $i++) { + $num = mt_rand(0, $_Text_Password_NumberOfPossibleCharacters - 1); + $password .= substr($chars, $num, 1); + } /** * Return password
* Change the method for creating unpronounceable passwords to be more efficient. Bug: #<I> git-svn-id: <URL>
pear_Text_Password
train
4a88d781a24559df44f31959a77eda0c1ec00c2f
diff --git a/lib/nominet-epp/helpers.rb b/lib/nominet-epp/helpers.rb index <HASH>..<HASH> 100644 --- a/lib/nominet-epp/helpers.rb +++ b/lib/nominet-epp/helpers.rb @@ -135,7 +135,6 @@ module NominetEPP XML::Node.new('contact', nil, ns).tap do |node| node['order'] = contact.delete(:order).to_s if contact.has_key?(:order) - node['type'] = 'admin' node << contact_to_xml(contact) end
Remove the contact[type] attribute as this is not in the schemas
m247_nominet-epp
train
d1ea2693df8c77d86ac302749f0fa17b2c5f2401
diff --git a/ibis/backends/base/sql/__init__.py b/ibis/backends/base/sql/__init__.py index <HASH>..<HASH> 100644 --- a/ibis/backends/base/sql/__init__.py +++ b/ibis/backends/base/sql/__init__.py @@ -1,6 +1,7 @@ from __future__ import annotations import abc +import contextlib from functools import lru_cache from typing import Any, Mapping @@ -98,6 +99,10 @@ class BaseSQLBackend(BaseBackend): return cursor cursor.release() + @contextlib.contextmanager + def _safe_raw_sql(self, *args, **kwargs): + yield self.raw_sql(*args, **kwargs) + def execute( self, expr: ir.Expr, @@ -141,9 +146,11 @@ class BaseSQLBackend(BaseBackend): ) sql = query_ast.compile() self._log(sql) - cursor = self.raw_sql(sql, **kwargs) + schema = self.ast_schema(query_ast, **kwargs) - result = self.fetch_from_cursor(cursor, schema) + + with self._safe_raw_sql(sql, **kwargs) as cursor: + result = self.fetch_from_cursor(cursor, schema) if hasattr(getattr(query_ast, 'dml', query_ast), 'result_handler'): result = query_ast.dml.result_handler(result) @@ -252,9 +259,8 @@ class BaseSQLBackend(BaseBackend): statement = f'EXPLAIN {query}' - cur = self.raw_sql(statement) - result = self._get_list(cur) - cur.release() + with self._safe_raw_sql(statement) as cur: + result = self._get_list(cur) return '\n'.join(['Query:', util.indent(query, 2), '', *result]) diff --git a/ibis/backends/base/sql/alchemy/__init__.py b/ibis/backends/base/sql/alchemy/__init__.py index <HASH>..<HASH> 100644 --- a/ibis/backends/base/sql/alchemy/__init__.py +++ b/ibis/backends/base/sql/alchemy/__init__.py @@ -116,6 +116,11 @@ class BaseAlchemyBackend(BaseSQLBackend): self._inspector.info_cache.clear() return self._inspector + @contextlib.contextmanager + def _safe_raw_sql(self, *args, **kwargs): + with self.begin() as con: + yield con.execute(*args, **kwargs) + @staticmethod def _to_geodataframe(df, schema): """Convert `df` to a `GeoDataFrame`.
fix(backends): make execution transactional where possible
ibis-project_ibis
train
16add3bf9b31cd201be29a6c026b39d478ac8d45
diff --git a/modules/wyc/src/wyc/io/WhileyFileLexer.java b/modules/wyc/src/wyc/io/WhileyFileLexer.java index <HASH>..<HASH> 100755 --- a/modules/wyc/src/wyc/io/WhileyFileLexer.java +++ b/modules/wyc/src/wyc/io/WhileyFileLexer.java @@ -177,12 +177,17 @@ public class WhileyFileLexer { public Token scanStringConstant() { int start = pos; + boolean escaped = false; pos++; while (pos < input.length()) { char c = input.charAt(pos); - if (c == '"') { + if (c == '"' && !escaped) { String v = input.substring(start, ++pos); return new Token(Token.Kind.StringValue, v, start); + } else if(c == '\\') { + escaped = true; + } else { + escaped = false; } pos = pos + 1; }
WyC: bug fix for scanning string constants.
Whiley_WhileyCompiler
train
82daa43844556953101b201bc5983aed4fbe6233
diff --git a/builder/internals.go b/builder/internals.go index <HASH>..<HASH> 100644 --- a/builder/internals.go +++ b/builder/internals.go @@ -156,6 +156,7 @@ func (b *Builder) runContextCommand(args []string, allowRemote bool, allowDecomp dest, allowRemote, allowDecompression, + true, ); err != nil { return err } @@ -226,7 +227,7 @@ func (b *Builder) runContextCommand(args []string, allowRemote bool, allowDecomp return nil } -func calcCopyInfo(b *Builder, cmdName string, cInfos *[]*copyInfo, origPath string, destPath string, allowRemote bool, allowDecompression bool) error { +func calcCopyInfo(b *Builder, cmdName string, cInfos *[]*copyInfo, origPath string, destPath string, allowRemote bool, allowDecompression bool, allowWildcards bool) error { if origPath != "" && origPath[0] == '/' && len(origPath) > 1 { origPath = origPath[1:] @@ -351,7 +352,7 @@ func calcCopyInfo(b *Builder, cmdName string, cInfos *[]*copyInfo, origPath stri } // Deal with wildcards - if ContainsWildcards(origPath) { + if allowWildcards && ContainsWildcards(origPath) { for _, fileInfo := range b.context.GetSums() { if fileInfo.Name() == "" { continue @@ -361,7 +362,9 @@ func calcCopyInfo(b *Builder, cmdName string, cInfos *[]*copyInfo, origPath stri continue } - calcCopyInfo(b, cmdName, cInfos, fileInfo.Name(), destPath, allowRemote, allowDecompression) + // Note we set allowWildcards to false in case the name has + // a * in it + calcCopyInfo(b, cmdName, cInfos, fileInfo.Name(), destPath, allowRemote, allowDecompression, false) } return nil } diff --git a/integration-cli/docker_cli_build_test.go b/integration-cli/docker_cli_build_test.go index <HASH>..<HASH> 100644 --- a/integration-cli/docker_cli_build_test.go +++ b/integration-cli/docker_cli_build_test.go @@ -1113,10 +1113,10 @@ func (s *DockerSuite) TestBuildCopyWildcard(c *check.C) { "dir/nested_dir/nest_nest_file": "2 times nested", "dirt": "dirty", }) - defer ctx.Close() if err != nil { c.Fatal(err) } + defer ctx.Close() id1, err := buildImageFromContext(name, ctx, true) if err != nil { @@ -1155,6 +1155,31 @@ func (s *DockerSuite) TestBuildCopyWildcardNoFind(c *check.C) { } +func (s *DockerSuite) TestBuildCopyWildcardInName(c *check.C) { + name := "testcopywildcardinname" + defer deleteImages(name) + ctx, err := fakeContext(`FROM busybox + COPY *.txt /tmp/ + RUN [ "$(cat /tmp/\*.txt)" = 'hi there' ] + `, map[string]string{"*.txt": "hi there"}) + + if err != nil { + // Normally we would do c.Fatal(err) here but given that + // the odds of this failing are so rare, it must be because + // the OS we're running the client on doesn't support * in + // filenames (like windows). So, instead of failing the test + // just let it pass. Then we don't need to explicitly + // say which OSs this works on or not. + return + } + defer ctx.Close() + + _, err = buildImageFromContext(name, ctx, true) + if err != nil { + c.Fatalf("should have built: %q", err) + } +} + func (s *DockerSuite) TestBuildCopyWildcardCache(c *check.C) { name := "testcopywildcardcache" ctx, err := fakeContext(`FROM busybox diff --git a/integration-cli/docker_utils.go b/integration-cli/docker_utils.go index <HASH>..<HASH> 100644 --- a/integration-cli/docker_utils.go +++ b/integration-cli/docker_utils.go @@ -663,7 +663,6 @@ func fakeContextAddDockerfile(ctx *FakeContext, dockerfile string) error { func fakeContext(dockerfile string, files map[string]string) (*FakeContext, error) { ctx, err := fakeContextWithFiles(files) if err != nil { - ctx.Close() return nil, err } if err := fakeContextAddDockerfile(ctx, dockerfile); err != nil {
Fix for Daemon crashing when wildcards are used for COPY/ADD in the filename and the command itself Closes #<I>
containers_storage
train
a4e173a66780fba908648a937185baf9b896f099
diff --git a/sdk/examples/apps/JavaScript/Chart/chart.js b/sdk/examples/apps/JavaScript/Chart/chart.js index <HASH>..<HASH> 100644 --- a/sdk/examples/apps/JavaScript/Chart/chart.js +++ b/sdk/examples/apps/JavaScript/Chart/chart.js @@ -9,7 +9,7 @@ F2.Apps["com_markh_highchartsChart"] = function(){ ); //setup listener for duration change menu - $("ul.dropdown-menu a", "div.appcom_markh_highchartsChart").bind("click",function(e){ + $("ul.dropdown-menu a", "div.com_markh_highchartsChart").bind("click",function(e){ cht.changeTimeframe(e); });
fixing css reference in chart app
OpenF2_F2
train
95b451d5a9a44fdd631b398d830ccdc6f6238b74
diff --git a/login/forgot_password.php b/login/forgot_password.php index <HASH>..<HASH> 100644 --- a/login/forgot_password.php +++ b/login/forgot_password.php @@ -219,7 +219,7 @@ if ($page=='emailmaybeconfirmed') { // check $page for appropriate page to display if ($page=='emailconfirm') { // Confirm (internal method) email sent - $protectedemail = preg_replace('/([^@]*)@(.*)/', '???????@$2', $user->email); // obfuscate the email address to protect privacy + $protectedemail = preg_replace('/([^@]*)@(.*)/', '******@$2', $user->email); // obfuscate the email address to protect privacy $txt->emailpasswordconfirmsent = get_string( 'emailpasswordconfirmsent','',$protectedemail ); notice( $txt->emailpasswordconfirmsent,$CFG->wwwroot.'/index.php'); }
changed email obfuscation character to * MDL-<I> ; merged from MOODLE_<I>_STABLE
moodle_moodle
train
0643e2982fc176afe6bdd08f8f025d5f8368251d
diff --git a/tests/test_flask_oidc.py b/tests/test_flask_oidc.py index <HASH>..<HASH> 100644 --- a/tests/test_flask_oidc.py +++ b/tests/test_flask_oidc.py @@ -2,7 +2,10 @@ from pkg_resources import resource_filename, resource_stream import json import codecs from base64 import urlsafe_b64encode -import urlparse +try: + from urlparse import parse_qs +except ImportError: + from urllib.parse import parse_qs from six.moves.urllib.parse import urlsplit, parse_qs, urlencode from nose.tools import nottest @@ -45,7 +48,7 @@ class MockHttp(object): self.last_request['path'] = path post_args = {} if method == 'POST': - post_args = urlparse.parse_qs(post_string) + post_args = parse_qs(post_string) if path == 'https://test/token': return MockHttpResponse(), json.dumps({
Be forward compatible by accepting urllib.parse in tests
puiterwijk_flask-oidc
train
796bc4575526ad33b517ed43c3bb9bcf0a18fb4c
diff --git a/src/main/java/com/joptimizer/optimizers/PrimalDualMethod.java b/src/main/java/com/joptimizer/optimizers/PrimalDualMethod.java index <HASH>..<HASH> 100644 --- a/src/main/java/com/joptimizer/optimizers/PrimalDualMethod.java +++ b/src/main/java/com/joptimizer/optimizers/PrimalDualMethod.java @@ -133,9 +133,8 @@ public class PrimalDualMethod extends OptimizationRequestHandler { iteration++; // iteration limit condition if (iteration == getMaxIteration()+1) { - response.setReturnCode(OptimizationResponse.WARN); - log.warn("Max iterations limit reached"); - break; + response.setReturnCode(OptimizationResponse.FAILED); + throw new Exception("Max iterations limit reached"); } // determine functions evaluations
revert to old behaviour w.r.t. max iterations (i.e. throw an exception)
vincentk_joptimizer
train
b0d4612fc221622960e986a88a5d52c809ff7f1f
diff --git a/todomvc/gruntfile.js b/todomvc/gruntfile.js index <HASH>..<HASH> 100644 --- a/todomvc/gruntfile.js +++ b/todomvc/gruntfile.js @@ -24,9 +24,9 @@ module.exports = function(grunt) { build: { src: [ 'src/**/*.ts', - '!src/**/*ios.ts', - '!src/**/*ios.d.ts', - '!src/ios.d.ts', + //'!src/**/*ios.ts', + //'!src/**/*ios.d.ts', + //'!src/ios.d.ts', ], dest: 'app', options: { @@ -136,7 +136,7 @@ module.exports = function(grunt) { grunt.registerTask("updateTypings", [ "checkTypings", "copy:typingsFiles", - "copy:iosStub", + //"copy:iosStub", ]); grunt.registerTask("removeAppDir", function() {
Get rid of more android-only build configs.
NativeScript_nativescript-angular
train
c82ba35747de08f36d4d854d24790271a80c6743
diff --git a/integration_tests/blockstack_integration_tests/scenarios/testlib.py b/integration_tests/blockstack_integration_tests/scenarios/testlib.py index <HASH>..<HASH> 100644 --- a/integration_tests/blockstack_integration_tests/scenarios/testlib.py +++ b/integration_tests/blockstack_integration_tests/scenarios/testlib.py @@ -248,6 +248,8 @@ def blockstack_name_preorder( name, privatekey, register_addr, wallet=None, subs if wallet is not None: register_privkey_params = get_privkey_info_params( wallet.privkey ) + log.debug("Preorder '%s' for %s satoshis" % (name, name_cost_info['satoshis'])) + resp = blockstack_client.do_preorder( name, privatekey, register_addr, name_cost_info['satoshis'], test_proxy, test_proxy, owner_privkey_params=register_privkey_params, consensus_hash=consensus_hash, config_path=test_proxy.config_path, proxy=test_proxy, safety_checks=safety_checks ) api_call_history.append( APICallRecord( "preorder", name, resp ) ) @@ -313,6 +315,7 @@ def blockstack_name_renew( name, privatekey, register_addr=None, subsidy_key=Non if subsidy_key is not None: payment_key = subsidy_key + log.debug("Renew %s for %s satoshis" % (name, name_cost_info['satoshis'])) resp = blockstack_client.do_renewal( name, privatekey, payment_key, name_cost_info['satoshis'], test_proxy, test_proxy, config_path=test_proxy.config_path, proxy=test_proxy, safety_checks=safety_checks ) api_call_history.append( APICallRecord( "renew", name, resp ) ) @@ -397,7 +400,7 @@ def blockstack_client_initialize_wallet( password, payment_privkey, owner_privke wallet_path = os.path.join( os.path.dirname(config_path), blockstack_client.config.WALLET_FILENAME ) - wallet = blockstack_client.wallet.make_wallet( password, payment_privkey=payment_privkey, owner_privkey=owner_privkey, data_privkey=data_privkey ) + wallet = blockstack_client.wallet.make_wallet( password, payment_privkey_info=payment_privkey, owner_privkey_info=owner_privkey, data_privkey_info=data_privkey ) blockstack_client.wallet.write_wallet( wallet, path=wallet_path ) return wallet @@ -818,6 +821,9 @@ def snv_all_names( state_engine ): print "QUIRK: NAME_IMPORT: fee isn't a float" return False + elif type(snv_rec['op_fee']) not in [int,long]: + print "QUIRK: %s: fee isn't an int" % snv_rec['opcode'] + log.debug("SNV verified %s with (%s,%s) back to (%s,%s)" % (name, trusted_block_id, trusted_consensus_hash, block_id, consensus_hash )) return True @@ -948,23 +954,27 @@ def migrate_profile( name, proxy=None, wallet_keys=None ): if not legacy: return {'status': True} - _, payment_privkey = blockstack_client.get_payment_keypair( wallet_keys=wallet_keys, config_path=proxy.conf['path'] ) - _, owner_privkey = blockstack_client.get_owner_keypair( wallet_keys=wallet_keys, config_path=proxy.conf['path'] ) - _, data_privkey = blockstack_client.get_data_keypair( user_zonefile, wallet_keys=wallet_keys, config_path=proxy.conf['path'] ) + payment_privkey_info = blockstack_client.get_payment_privkey_info( wallet_keys=wallet_keys, config_path=proxy.conf['path'] ) + owner_privkey_info = blockstack_client.get_owner_privkey_info( wallet_keys=wallet_keys, config_path=proxy.conf['path'] ) + data_privkey_info = blockstack_client.get_data_privkey_info( user_zonefile, wallet_keys=wallet_keys, config_path=proxy.conf['path'] ) - if data_privkey is None: + if data_privkey_info is None: log.warn("No data private key set; falling back to owner private key") - data_privkey = owner_privkey + data_privkey_info = owner_privkey_info + + if not blockstack_client.keys.is_singlesig(data_privkey_info): + log.error("We only support single-signature private key info for data at this time.") + return {'error': 'Invalid data key'} user_zonefile_hash = blockstack_client.hash_zonefile( user_zonefile ) # replicate the profile - rc = storage.put_mutable_data( name, user_profile, data_privkey ) + rc = storage.put_mutable_data( name, user_profile, data_privkey_info ) if not rc: return {'error': 'Failed to move legacy profile to profile zonefile'} # do the update - res = blockstack_client.do_update( name, user_zonefile_hash, owner_privkey, payment_privkey, proxy, proxy, config_path=proxy.config_path, proxy=proxy ) + res = blockstack_client.do_update( name, user_zonefile_hash, owner_privkey_info, payment_privkey_info, proxy, proxy, config_path=proxy.config_path, proxy=proxy ) api_call_history.append( APICallRecord( "update", name, res ) ) if 'error' in res:
sync with client multisig private key data schema
blockstack_blockstack-core
train
521611104dbb2b1002a80e41daa6e7c8a9303dc2
diff --git a/src/providers/bitcoin/BitcoinSwapProvider.js b/src/providers/bitcoin/BitcoinSwapProvider.js index <HASH>..<HASH> 100644 --- a/src/providers/bitcoin/BitcoinSwapProvider.js +++ b/src/providers/bitcoin/BitcoinSwapProvider.js @@ -1,5 +1,6 @@ import Provider from '../../Provider' import { addressToPubKeyHash, compressPubKey, pubKeyToAddress, reverseBuffer, scriptNumEncode } from './BitcoinUtil' +import { BigNumber } from 'bignumber.js' import { sha256, padHexStart } from '../../crypto' import networks from '../../networks' @@ -230,7 +231,7 @@ export default class BitcoinSwapProvider extends Provider { const value = parseInt(reverseBuffer(output.amount).toString('hex'), 16) const { relayfee } = await this.getMethod('jsonrpc')('getinfo') const fee = this.getMethod('calculateFee')(1, 1, feePerByte) - const amount = value - Math.max(fee, relayfee) + const amount = value - Math.max(fee, BigNumber(relayfee).times(1e8).toNumber()) const amountLE = Buffer.from(padHexStart(amount.toString(16), 16), 'hex').reverse().toString('hex') // amount in little endian const pubKeyHash = addressToPubKeyHash(address)
Fix relayfee amount with BigNumber
liquality_chainabstractionlayer
train
bf2f421656200fd642b3cb092f2b22985aca5ce6
diff --git a/azure/servicemanagement/servicemanagementservice.py b/azure/servicemanagement/servicemanagementservice.py index <HASH>..<HASH> 100644 --- a/azure/servicemanagement/servicemanagementservice.py +++ b/azure/servicemanagement/servicemanagementservice.py @@ -1100,7 +1100,7 @@ class ServiceManagementService(_ServiceManagementClient): return self._perform_post( self._get_reserved_ip_path(), _XmlSerializer.create_reserved_ip_to_xml(name, label, location), - async=True, x_ms_version='2014-10-01') + async=True) def delete_reserved_ip_address(self, name): ''' @@ -1110,7 +1110,7 @@ class ServiceManagementService(_ServiceManagementClient): ''' _validate_not_none('name', name) return self._perform_delete(self._get_reserved_ip_path(name), - async=True, x_ms_version='2014-10-01') + async=True) def get_reserved_ip_address(self, name): ''' diff --git a/tests/test_servicemanagementservice.py b/tests/test_servicemanagementservice.py index <HASH>..<HASH> 100644 --- a/tests/test_servicemanagementservice.py +++ b/tests/test_servicemanagementservice.py @@ -555,25 +555,6 @@ class ServiceManagementServiceTest(AzureTestCase): self._wait_for_async(result.request_id) self._wait_for_role(service_name, deployment_name, role_name) - def _wait_for_reserved_ip_address(self, name, state='Created'): - count = 0 - try: - props = self.sms.get_reserved_ip_address(name) - except: - props = None - - while props is None or props.state != state: - count = count + 1 - if count > 120: - self.assertTrue( - False, 'Timed out waiting for ip address state.') - time.sleep(5) - - try: - props = self.sms.get_reserved_ip_address(name) - except: - props = None - def _create_reserved_ip_address(self): self.reserved_ip_address = getUniqueName('ip') result = self.sms.create_reserved_ip_address( @@ -1418,7 +1399,6 @@ class ServiceManagementServiceTest(AzureTestCase): self.reserved_ip_address = None # Assert - self.assertIsNone(result) self.assertFalse( self._reserved_ip_address_exists(self.reserved_ip_address))
Change create_reserved_ip_address and delete_reserved_ip_address to be async operations.
Azure_azure-sdk-for-python
train
6345ca763024c4ac98c9593e664cad0878c35e7c
diff --git a/dist/famous-angular.js b/dist/famous-angular.js index <HASH>..<HASH> 100644 --- a/dist/famous-angular.js +++ b/dist/famous-angular.js @@ -1694,7 +1694,7 @@ angular.module('famous.angular') * </fa-flipper> *``` *```javascript - * $scope.flipHandler = function() { + * $scope.flipIt = function() { * $famous.find('fa-flipper')[0].flip(); * }; *``` diff --git a/docs/unstable/directive/faFlipper/index.md b/docs/unstable/directive/faFlipper/index.md index <HASH>..<HASH> 100644 --- a/docs/unstable/directive/faFlipper/index.md +++ b/docs/unstable/directive/faFlipper/index.md @@ -64,7 +64,7 @@ In the example below, when an <code>fa-surface</code> is clicked, it calls the f &lt;fa-surface fa-background-color=&quot;&#39;yellow&#39;&quot; fa-click=&quot;flipIt()&quot;&gt;&lt;/fa-surface&gt; &lt;fa-surface fa-background-color=&quot;&#39;red&#39;&quot; fa-click=&quot;flipIt()&quot;&gt;&lt;/fa-surface&gt; &lt;/fa-flipper&gt;</code></pre> -<pre><code class="lang-javascript">$scope.flipHandler = function() { +<pre><code class="lang-javascript">$scope.flipIt = function() { $famous.find(&#39;fa-flipper&#39;)[0].flip(); };</code></pre> diff --git a/src/scripts/directives/fa-flipper.js b/src/scripts/directives/fa-flipper.js index <HASH>..<HASH> 100644 --- a/src/scripts/directives/fa-flipper.js +++ b/src/scripts/directives/fa-flipper.js @@ -28,7 +28,7 @@ * </fa-flipper> *``` *```javascript - * $scope.flipHandler = function() { + * $scope.flipIt = function() { * $famous.find('fa-flipper')[0].flip(); * }; *```
docs: fix naming typo in fa-flipper
Famous_famous-angular
train
8d725697ba77701439054224b3c3277cd82a0d27
diff --git a/lib/OpenLayers/Icon.js b/lib/OpenLayers/Icon.js index <HASH>..<HASH> 100644 --- a/lib/OpenLayers/Icon.js +++ b/lib/OpenLayers/Icon.js @@ -52,7 +52,6 @@ OpenLayers.Icon.prototype = { }, destroy: function() { - OpenLayers.Event.stopObserving(this.imageDiv.firstChild); this.imageDiv.innerHTML = ""; this.imageDiv = null; },
Erik and I discussed this, and the destroy() here actually does the wrong thing. the innerHTML still prevents the memory leak, but unregistering in this way doesn't do the right thing. remove it. git-svn-id: <URL>
openlayers_openlayers
train
cc85bea5403c52b0ade4eab44d6b4455b2042243
diff --git a/src/tools/mountainchart/mountainchart-component.js b/src/tools/mountainchart/mountainchart-component.js index <HASH>..<HASH> 100644 --- a/src/tools/mountainchart/mountainchart-component.js +++ b/src/tools/mountainchart/mountainchart-component.js @@ -151,6 +151,7 @@ // define path generator this.area = d3.svg.area() + .interpolate("basis") .x(function (d) { return _this.xScale(d.x) }) .y0(function (d) { return _this.yScale(d.y0) }) .y1(function (d) { return _this.yScale(d.y0 + d.y) }); @@ -638,9 +639,7 @@ break; }; - var RESOLUTION_PPP = 1/5; // 1 point per 5 pixels - var MIN_N_VERTICES = 100; - var MAX_N_VERTICES = 500; + var N_VERTICES = 40; this.height = parseInt(this.element.style("height"), 10) - margin.top - margin.bottom; @@ -662,15 +661,7 @@ // we need to generate the distributions based on mu, variance and scale // we span a uniform mesh across the entire X scale, - if(!meshLength) { - meshLength = this.width ? this.width * RESOLUTION_PPP : -1; - if(this.model.entities._visible.length > 100 && - !this.model.marker.group.merge && - !this.model.marker.stack.merge) MAX_N_VERTICES = 100*150/this.model.entities._visible.length; - meshLength = Math.max(MIN_N_VERTICES, meshLength); - meshLength = Math.min(MAX_N_VERTICES, meshLength); - } - + if(!meshLength) meshLength = N_VERTICES; var scaleType = this._readyOnce? this.model.marker.axis_x.scaleType : "log"; var rangeFrom = scaleType == "linear" ? this.xScale.domain()[0] : Math.log(this.xScale.domain()[0]);
Mountain chart remove manual resolution of shapes, use d3 area interpolation instead
vizabi_vizabi
train
e1f56127df58b986f0324030a88c5517bce9b0ef
diff --git a/conn_id_generator.go b/conn_id_generator.go index <HASH>..<HASH> 100644 --- a/conn_id_generator.go +++ b/conn_id_generator.go @@ -22,6 +22,8 @@ type connIDGenerator struct { retireConnectionID func(protocol.ConnectionID) replaceWithClosed func(protocol.ConnectionID, packetHandler) queueControlFrame func(wire.Frame) + + version protocol.VersionNumber } func newConnIDGenerator( @@ -33,6 +35,7 @@ func newConnIDGenerator( retireConnectionID func(protocol.ConnectionID), replaceWithClosed func(protocol.ConnectionID, packetHandler), queueControlFrame func(wire.Frame), + version protocol.VersionNumber, ) *connIDGenerator { m := &connIDGenerator{ connIDLen: initialConnectionID.Len(), @@ -43,6 +46,7 @@ func newConnIDGenerator( retireConnectionID: retireConnectionID, replaceWithClosed: replaceWithClosed, queueControlFrame: queueControlFrame, + version: version, } m.activeSrcConnIDs[0] = initialConnectionID m.initialClientDestConnID = initialClientDestConnID @@ -76,7 +80,7 @@ func (m *connIDGenerator) Retire(seq uint64, sentWithDestConnID protocol.Connect if !ok { return nil } - if connID.Equal(sentWithDestConnID) && !RetireBugBackwardsCompatibilityMode { + if connID.Equal(sentWithDestConnID) && !protocol.UseRetireBugBackwardsCompatibilityMode(RetireBugBackwardsCompatibilityMode, m.version) { return qerr.NewError(qerr.ProtocolViolation, fmt.Sprintf("tried to retire connection ID %d (%s), which was used as the Destination Connection ID on this packet", seq, connID)) } m.retireConnectionID(connID) @@ -89,7 +93,7 @@ func (m *connIDGenerator) Retire(seq uint64, sentWithDestConnID protocol.Connect } func (m *connIDGenerator) issueNewConnID() error { - if RetireBugBackwardsCompatibilityMode { + if protocol.UseRetireBugBackwardsCompatibilityMode(RetireBugBackwardsCompatibilityMode, m.version) { return nil } connID, err := protocol.GenerateConnectionID(m.connIDLen) diff --git a/conn_id_generator_test.go b/conn_id_generator_test.go index <HASH>..<HASH> 100644 --- a/conn_id_generator_test.go +++ b/conn_id_generator_test.go @@ -41,6 +41,7 @@ var _ = Describe("Connection ID Generator", func() { func(c protocol.ConnectionID) { retiredConnIDs = append(retiredConnIDs, c) }, func(c protocol.ConnectionID, h packetHandler) { replacedWithClosed[string(c)] = h }, func(f wire.Frame) { queuedFrames = append(queuedFrames, f) }, + protocol.VersionDraft29, ) }) diff --git a/internal/protocol/version.go b/internal/protocol/version.go index <HASH>..<HASH> 100644 --- a/internal/protocol/version.go +++ b/internal/protocol/version.go @@ -62,6 +62,12 @@ func (vn VersionNumber) toGQUICVersion() int { return int(10*(vn-gquicVersion0)/0x100) + int(vn%0x10) } +// UseRetireBugBackwardsCompatibilityMode says if it is necessary to use the backwards compatilibity mode. +// This is only the case if it 1. is enabled and 2. draft-29 is used. +func UseRetireBugBackwardsCompatibilityMode(enabled bool, v VersionNumber) bool { + return enabled && v == VersionDraft29 +} + // IsSupportedVersion returns true if the server supports this version func IsSupportedVersion(supported []VersionNumber, v VersionNumber) bool { for _, t := range supported { diff --git a/internal/protocol/version_test.go b/internal/protocol/version_test.go index <HASH>..<HASH> 100644 --- a/internal/protocol/version_test.go +++ b/internal/protocol/version_test.go @@ -49,6 +49,13 @@ var _ = Describe("Version", func() { } }) + It("says if backwards compatibility mode should be used", func() { + Expect(UseRetireBugBackwardsCompatibilityMode(true, VersionDraft29)).To(BeTrue()) + Expect(UseRetireBugBackwardsCompatibilityMode(true, VersionDraft32)).To(BeFalse()) + Expect(UseRetireBugBackwardsCompatibilityMode(false, VersionDraft29)).To(BeFalse()) + Expect(UseRetireBugBackwardsCompatibilityMode(false, VersionDraft32)).To(BeFalse()) + }) + Context("highest supported version", func() { It("finds the supported version", func() { supportedVersions := []VersionNumber{1, 2, 3} diff --git a/session.go b/session.go index <HASH>..<HASH> 100644 --- a/session.go +++ b/session.go @@ -268,6 +268,7 @@ var newSession = func( runner.Retire, runner.ReplaceWithClosed, s.queueControlFrame, + s.version, ) s.preSetup() s.sentPacketHandler, s.receivedPacketHandler = ackhandler.NewAckHandler( @@ -390,6 +391,7 @@ var newClientSession = func( runner.Retire, runner.ReplaceWithClosed, s.queueControlFrame, + s.version, ) s.preSetup() s.sentPacketHandler, s.receivedPacketHandler = ackhandler.NewAckHandler(
only use the conn ID backwards compatibility mode with draft-<I>
lucas-clemente_quic-go
train
ad9d14217466dffdbd52066bc46487990624ae30
diff --git a/core/server/services/apps/loader.js b/core/server/services/apps/loader.js index <HASH>..<HASH> 100644 --- a/core/server/services/apps/loader.js +++ b/core/server/services/apps/loader.js @@ -4,7 +4,7 @@ const Promise = require('bluebird'); const config = require('../../config'); const common = require('../../lib/common'); const AppProxy = require('./proxy'); -const AppSandbox = require('./sandbox'); +const Sandbox = require('./sandbox'); const AppDependencies = require('./dependencies'); const AppPermissions = require('./permissions'); @@ -27,9 +27,7 @@ function getAppRelativePath(name, relativeTo = __dirname) { // Load apps through a pseudo sandbox function loadApp(appPath) { - const sandbox = new AppSandbox(); - - return sandbox.loadApp(appPath); + return Sandbox.loadApp(appPath); } function getAppByName(name, permissions) { diff --git a/core/server/services/apps/sandbox.js b/core/server/services/apps/sandbox.js index <HASH>..<HASH> 100644 --- a/core/server/services/apps/sandbox.js +++ b/core/server/services/apps/sandbox.js @@ -1,22 +1,13 @@ const Module = require('module'); -function AppSandbox(opts) { - this.opts = opts; -} - -AppSandbox.prototype.loadApp = function loadAppSandboxed(appPath) { - // Set loaded modules parent to this - const parentModulePath = this.opts.parent || module.parent; - +module.exports.loadApp = function loadAppSandboxed(appPath) { // Resolve the modules path - const resolvedModulePath = Module._resolveFilename(appPath, parentModulePath); + const resolvedModulePath = Module._resolveFilename(appPath, module.parent); // Instantiate a Node Module class - const currentModule = new Module(resolvedModulePath, parentModulePath); + const currentModule = new Module(resolvedModulePath, module.parent); currentModule.load(currentModule.id); return currentModule.exports; }; - -module.exports = AppSandbox;
Refactored Sandbox to be singleton no-issue
TryGhost_Ghost
train