hash
stringlengths
40
40
diff
stringlengths
131
114k
message
stringlengths
7
980
project
stringlengths
5
67
split
stringclasses
1 value
d1f0e7c230469ed7adc044182769aa1dc34c0748
diff --git a/citrination_client/data/tests/test_data_client.py b/citrination_client/data/tests/test_data_client.py index <HASH>..<HASH> 100644 --- a/citrination_client/data/tests/test_data_client.py +++ b/citrination_client/data/tests/test_data_client.py @@ -47,7 +47,7 @@ def test_upload_pif(): tries = 0 while True: try: - pif = client.get_pif(dataset_id, uid) + retrieved_pif = client.get_pif(dataset_id, uid) break except ResourceNotFoundException: if tries < 10: @@ -59,7 +59,19 @@ def test_upload_pif(): status = client.get_ingest_status(dataset_id) assert status == "Finished" with open("tmp.json", "r") as fp: - assert json.loads(fp.read())["uid"] == pif.uid + assert json.loads(fp.read())["uid"] == retrieved_pif.uid + + # Basic test of `get_pif_with_metadata` method + with_metadata_resp = client.get_pif_with_metadata( + dataset_id, uid + ) + with open("tmp.json", "r") as fp: + assert json.loads(fp.read())["uid"] == with_metadata_resp['pif'].uid + assert with_metadata_resp['metadata']['updated_at'] + assert with_metadata_resp['metadata']['uid'] == uid + assert with_metadata_resp['metadata']['dataset_id'] == str(dataset_id) + assert with_metadata_resp['metadata']['dataset_version'] == 1 + assert with_metadata_resp['metadata']['version'] == 1 def test_does_not_require_trailing_slash(): src_path = "{}data_holder".format(test_file_data_root) @@ -114,7 +126,8 @@ def test_dataset_update(): """ dataset_name = random_dataset_name() dataset_id = client.create_dataset(name=dataset_name).id - time.sleep(10) + # Sleep added to accommodate race condition bug + time.sleep(20) new_name = random_dataset_name() new_description = random_string() dataset = client.update_dataset(dataset_id, name=new_name, description=new_description) @@ -247,4 +260,3 @@ def test_download_pdf_files(): for f in files_list: os.remove('/'.join(['test',f.path])) os.rmdir('test') -
Add basic test coverage for DataClient#get_pif_with_metadata Also bumped sleep time for the dataset update test, that frequently fails due to a race condition bug in Citrination.
CitrineInformatics_python-citrination-client
train
43239908d36f8c1d79dc2c7ce3e6da58254ef850
diff --git a/molgenis-data/src/main/java/org/molgenis/data/annotation/RepositoryAnnotator.java b/molgenis-data/src/main/java/org/molgenis/data/annotation/RepositoryAnnotator.java index <HASH>..<HASH> 100644 --- a/molgenis-data/src/main/java/org/molgenis/data/annotation/RepositoryAnnotator.java +++ b/molgenis-data/src/main/java/org/molgenis/data/annotation/RepositoryAnnotator.java @@ -6,38 +6,49 @@ import org.molgenis.data.EntityMetaData; import java.util.Iterator; /** - * interface for annotators. - * annotators take an iterator and return an iterator with some information added or updated + * interface for annotators. annotators take an iterator and return an iterator with some information added or updated */ -public interface RepositoryAnnotator { - - Iterator<Entity> annotate (Iterator<Entity> source); - - /** - * returns an entityMetaData containing the attributes the annotator will add - * @return ouputMetadata - */ - EntityMetaData getOutputMetaData (); - - /** - * Returns a entityMetaData containing the attributes needed for the annotator to work - * @return inputMetaData; - */ - EntityMetaData getInputMetaData (); - - /** - * Returns if the annotator will work for the given metadata - * @param inputMetaData - * @return canAnnotate - */ - boolean canAnnotate(EntityMetaData inputMetaData); - - /** - * Return the name of the annotator - * @return name - */ - String getName(); - - +public interface RepositoryAnnotator +{ + + Iterator<Entity> annotate(Iterator<Entity> source); + + /** + * returns an entityMetaData containing the attributes the annotator will add + * + * @return ouputMetadata + */ + EntityMetaData getOutputMetaData(); + + /** + * Returns a entityMetaData containing the attributes needed for the annotator to work + * + * @return inputMetaData; + */ + EntityMetaData getInputMetaData(); + + /** + * Returns if the annotator will work for the given metadata + * + * @param inputMetaData + * @return canAnnotate + */ + boolean canAnnotate(EntityMetaData inputMetaData); + + /** + * Return the name of the annotator + * + * @return name + */ + String getName(); + + /** + * Checks if folder and files that were set with a runtime property actually exist, or if a webservice can be + * reached + * + * @return annotationDataExists + * */ + boolean annotationDataExists(); + }
Added a new method to the RepositoryAnnotator super class. annotationDataExists checks if the location that was set with runtime properties actually contains a file. If not, the annotator is disabled.
molgenis_molgenis
train
144693738f033d4274076dfc67fa1b98a71b73b7
diff --git a/dipper/sources/ZFIN.py b/dipper/sources/ZFIN.py index <HASH>..<HASH> 100644 --- a/dipper/sources/ZFIN.py +++ b/dipper/sources/ZFIN.py @@ -784,6 +784,8 @@ class ZFIN(Source): genotype_id = 'ZFIN:' + genotype_id.strip() env_id = 'ZFIN:' + env_id.strip() extrinsic_geno_id = self.make_id(env_id) + start_stage_id = 'ZFIN:' + start_stage_id.strip() + end_stage_id = 'ZFIN:' + end_stage_id.strip() geno = Genotype(g) geno.addGenotype(genotype_id,genotype_name) @@ -840,11 +842,11 @@ class ZFIN(Source): assoc.addAssociationNodeToGraph(g) #FIXME: Hanging the environment and stages on the G2P association for now. # Add environment to G2P association. - gu.addTriple(g,assoc,gu.object_properties['has_environment_qualifier'],env_id) + gu.addTriple(g,assoc_id,gu.object_properties['has_environment_qualifier'],env_id) # Add starting stage to G2P association. - gu.addTriple(g,assoc,gu.object_properties['has_begin_stage_qualifier'],start_stage_id) - # Add ending stage to G2P association. - gu.addTriple(g,assoc,gu.object_properties['has_end_stage_qualifier'],end_stage_id) + gu.addTriple(g,assoc_id,gu.object_properties['has_begin_stage_qualifier'],start_stage_id) + # Add ending stage to G2P association + gu.addTriple(g,assoc_id,gu.object_properties['has_end_stage_qualifier'],end_stage_id) else: # add normal phenotypes logger.warn("Found normal phenotype; skipping for now")
ZFIN.py: Fixed add enviro/stage to G2P association error.
monarch-initiative_dipper
train
367593f5105e5a05cf3d1aa1e06a1cb6fef74673
diff --git a/spec/adapter_spec.rb b/spec/adapter_spec.rb index <HASH>..<HASH> 100644 --- a/spec/adapter_spec.rb +++ b/spec/adapter_spec.rb @@ -15,10 +15,7 @@ describe "Looksee.adapter" do # def filtered_lookup_modules(object) result = @adapter.lookup_modules(object) - # Singleton classes have no name ('' in <1.9, nil in 1.9+). Use - # the inspect string instead. - names = result.map{|mod| mod.name.nil? || mod.name.empty? ? mod.inspect : mod.name} - names.select{|name| deterministic_module_name?(name)} + result.select{ |mod| deterministic_module?(mod) } end # @@ -28,7 +25,7 @@ describe "Looksee.adapter" do # This excludes ruby version dependent modules, and modules tossed # into the hierarchy by testing frameworks. # - def deterministic_module_name?(name) + def deterministic_module?(mod) junk_patterns = [ # pollution from testing libraries 'Mocha', 'Spec', @@ -43,13 +40,23 @@ describe "Looksee.adapter" do # our own pollution, 'Looksee::Object', ] + pattern = /\A(#{junk_patterns.join('|')})/ # Singleton classes of junk are junk. - while name =~ /\A#<Class:(.*)>\z/ - name = $1 + if Looksee.ruby_engine == 'rbx' + # Rubinius singleton class #inspect strings aren't formatted + # like the others. + while mod.respond_to?(:__metaclass_object__) && (object = mod.__metaclass_object__).is_a?(Class) + mod = object + end + mod.name !~ pattern + else + name = mod.to_s + while name =~ /\A#<Class:(.*)>\z/ + name = $1 + end + name !~ pattern end - - name !~ /\A(#{junk_patterns.join('|')})/ end it "should contain an entry for each module in the object's lookup path" do @@ -60,30 +67,23 @@ describe "Looksee.adapter" do include Mod1 include Mod2 end - filtered_lookup_modules(Derived.new) == %w'Derived Mod2 Mod1 Base Object Kernel' + filtered_lookup_modules(Derived.new) == [Derived, Mod2, Mod1, Base, Object, Kernel] end - it "contain an entry for the object's singleton class if it exists" do + it "should contain an entry for the object's singleton class if it exists" do object = Object.new object.singleton_class - result = filtered_lookup_modules(object) - if Looksee.ruby_engine == 'rbx' - result.shift.should =~ /\A#<Class: \#<Object:\d+>>\z/ - else - result.shift.should =~ /\A#<Class:\#<Object:0x[\da-f]+>>\z/ - end - result.should == %w"Object Kernel" + filtered_lookup_modules(object).should == [object.singleton_class, Object, Kernel] end it "should contain entries for singleton classes of all ancestors for class objects" do temporary_class :C - result = filtered_lookup_modules(C) - result.should == %w'#<Class:C> #<Class:Object> Class Module Object Kernel' + filtered_lookup_modules(C).should == [C.singleton_class, Object.singleton_class, Class, Module, Object, Kernel] end it "should work for immediate objects" do - filtered_lookup_modules(1).first.should == 'Fixnum' + filtered_lookup_modules(1).first.should == Fixnum end end
Compare classes by object id, not name, in adapter specs. This is more reliable on Rubinius, where singleton classes' #inspect doesn't look like other interpreters.
oggy_looksee
train
03fb8e79c68bc981bdcc2240257253c8f8596204
diff --git a/src/transformers/modeling_tf_longformer.py b/src/transformers/modeling_tf_longformer.py index <HASH>..<HASH> 100644 --- a/src/transformers/modeling_tf_longformer.py +++ b/src/transformers/modeling_tf_longformer.py @@ -348,7 +348,7 @@ class TFLongformerSelfAttention(tf.keras.layers.Layer): # matrix multipication # bcxd: batch_size * num_heads x chunks x 2window_overlap x head_dim # bcyd: batch_size * num_heads x chunks x 2window_overlap x head_dim - # bcxy: batch_size * num_heads x chunks x 2window_overlap x window_overlap + # bcxy: batch_size * num_heads x chunks x 2window_overlap x 2window_overlap chunked_attention_scores = tf.einsum("bcxd,bcyd->bcxy", chunked_query, chunked_key) # multiply # convert diagonals into columns
Update modeling_tf_longformer.py (#<I>) correct a very small mistake
huggingface_pytorch-pretrained-BERT
train
7895b18a2d2acde98da05ce24cee148ceb36fe91
diff --git a/monty/collections.py b/monty/collections.py index <HASH>..<HASH> 100644 --- a/monty/collections.py +++ b/monty/collections.py @@ -7,6 +7,8 @@ __maintainer__ = 'Shyue Ping Ong' __email__ = 'ongsp@ucsd.edu' __date__ = '1/24/14' +import collections + class frozendict(dict): """ @@ -88,8 +90,7 @@ class FrozenAttrDict(frozendict): class MongoDict(object): """ >>> m = MongoDict({'a': {'b': 1}, 'x': 2}) - >>> assert m.a == {'b': 1} and m.x == 2 - >>> assert m.a.b == 1 + >>> assert m.a.b == 1 and m.x == 2 >>> assert "a" in m and "b" in m.a NB: Cannot inherit from ABC collections.Mapping because otherwise
Unit tests for MongoDict
materialsvirtuallab_monty
train
2c60cce86dbf285a367e6eeba45d5efcb4625fc2
diff --git a/spec/simple_scheduler/future_job_spec.rb b/spec/simple_scheduler/future_job_spec.rb index <HASH>..<HASH> 100644 --- a/spec/simple_scheduler/future_job_spec.rb +++ b/spec/simple_scheduler/future_job_spec.rb @@ -76,7 +76,7 @@ describe SimpleScheduler::FutureJob, type: :job do it "doesn't add the job to the queue" do expect do - described_class.perform_now(task_params, (Time.now - 30.minutes).to_i) + described_class.perform_now(task_params, (Time.now - 31.minutes).to_i) end.to change(enqueued_jobs, :size).by(0) end end
Make test more clear for not queuing expired jobs
simplymadeapps_simple_scheduler
train
87cb4a7ef02cb9051d63c08f7179fd725171b9dd
diff --git a/src/io/bt.js b/src/io/bt.js index <HASH>..<HASH> 100644 --- a/src/io/bt.js +++ b/src/io/bt.js @@ -128,9 +128,17 @@ class BT extends JSONRPC { window.clearTimeout(this._discoverTimeoutID); } break; - //TODO why isn't 'user did pick peripheral' here? + case 'userDidPickPeripheral': + this._availablePeripherals[params.peripheralId] = params; + this._runtime.emit( + this._runtime.constructor.USER_PICKED_PERIPHERAL, + this._availablePeripherals + ); + if (this._discoverTimeoutID) { + window.clearTimeout(this._discoverTimeoutID); + } + break; case 'userDidNotPickPeripheral': - // this._availablePeripherals[params.peripheralId] = params; this._runtime.emit( this._runtime.constructor.PERIPHERAL_SCAN_TIMEOUT );
Add userDidPickPeripheral to bt
LLK_scratch-vm
train
41fe45c8c0abf905478098d509c324fc48d09731
diff --git a/pkg/k8s/apis/cilium.io/const.go b/pkg/k8s/apis/cilium.io/const.go index <HASH>..<HASH> 100644 --- a/pkg/k8s/apis/cilium.io/const.go +++ b/pkg/k8s/apis/cilium.io/const.go @@ -50,6 +50,9 @@ const ( // PodNamespaceLabel is the label used in kubernetes containers to // specify which namespace they belong to. PodNamespaceLabel = "io.kubernetes.pod.namespace" + // AppKubernetes is the label which is recommended by the official k8s + // documentation ad the lablel for every resource object. + AppKubernetes = "app.kubernetes.io" // CtrlPrefixPolicyStatus is the prefix used for the controllers set up // to sync the CNP with kube-apiserver. CtrlPrefixPolicyStatus = "sync-cnp-policy-status" diff --git a/pkg/labels/filter.go b/pkg/labels/filter.go index <HASH>..<HASH> 100644 --- a/pkg/labels/filter.go +++ b/pkg/labels/filter.go @@ -159,10 +159,13 @@ func defaultLabelPrefixCfg() *labelPrefixCfg { } expressions := []string{ - k8sConst.PodNamespaceLabel, // include io.kubernetes.pod.namspace + k8sConst.PodNamespaceLabel, // include io.kubernetes.pod.namespace k8sConst.PodNamespaceMetaLabels, // include all namespace labels + k8sConst.AppKubernetes, // include app.kubernetes.io "!io.kubernetes", // ignore all other io.kubernetes labels - "!.*kubernetes.io", // ignore all other kubernetes.io labels (annotation.*.k8s.io) + "!kubernetes.io", // ignore all other kubernetes.io labels + "!.*beta.kubernetes.io", // ignore all beta.kubernetes.io labels + "!k8s.io", // ignore all k8s.io labels "!pod-template-generation", // ignore pod-template-generation "!pod-template-hash", // ignore pod-template-hash "!controller-revision-hash", // ignore controller-revision-hash diff --git a/pkg/labels/filter_test.go b/pkg/labels/filter_test.go index <HASH>..<HASH> 100644 --- a/pkg/labels/filter_test.go +++ b/pkg/labels/filter_test.go @@ -33,6 +33,7 @@ func (s *LabelsPrefCfgSuite) TestFilterLabels(c *C) { "id.lizards": NewLabel("id.lizards", "web", LabelSourceContainer), "id.lizards.k8s": NewLabel("id.lizards.k8s", "web", LabelSourceK8s), "io.kubernetes.pod.namespace": NewLabel("io.kubernetes.pod.namespace", "default", LabelSourceContainer), + "app.kubernetes.io": NewLabel("app.kubernetes.io", "my-nginx", LabelSourceContainer), } dlpcfg := defaultLabelPrefixCfg() @@ -51,6 +52,9 @@ func (s *LabelsPrefCfgSuite) TestFilterLabels(c *C) { "io.kubernetes.container.terminationMessagePath": "", "io.kubernetes.pod.name": "my-nginx-3800858182-07i3n", "io.kubernetes.pod.namespace": "default", + "app.kubernetes.io": "my-nginx", + "kubernetes.io.foo": "foo", + "beta.kubernetes.io.foo": "foo", "annotation.kubectl.kubernetes.io": "foo", "annotation.hello": "world", "annotation." + k8sConst.CiliumIdentityAnnotationDeprecated: "12356", @@ -63,11 +67,11 @@ func (s *LabelsPrefCfgSuite) TestFilterLabels(c *C) { } allLabels := Map2Labels(allNormalLabels, LabelSourceContainer) filtered, _ := dlpcfg.filterLabels(allLabels) - c.Assert(len(filtered), Equals, 1) + c.Assert(len(filtered), Equals, 2) allLabels["id.lizards"] = NewLabel("id.lizards", "web", LabelSourceContainer) allLabels["id.lizards.k8s"] = NewLabel("id.lizards.k8s", "web", LabelSourceK8s) filtered, _ = dlpcfg.filterLabels(allLabels) - c.Assert(len(filtered), Equals, 3) + c.Assert(len(filtered), Equals, 4) c.Assert(filtered, checker.DeepEquals, wanted) // Making sure we are deep copying the labels allLabels["id.lizards"] = NewLabel("id.lizards", "web", "I can change this and doesn't affect any one")
labels: Do not filter out app.kubernetes.io prefix Prefix app.kubernetes.io is recommended for labels and annotations and it shouldn't be considered as a private label used internally by Kubernetes. Instead, kubernetes.io and *beta.kubernetes.io should be filtered out. Fixes #<I>
cilium_cilium
train
4b6c49a681bbdabcb494c693c1dd9bd091ddd696
diff --git a/client/lib/translator-jumpstart/index.js b/client/lib/translator-jumpstart/index.js index <HASH>..<HASH> 100644 --- a/client/lib/translator-jumpstart/index.js +++ b/client/lib/translator-jumpstart/index.js @@ -321,7 +321,7 @@ export function trackTranslatorStatus( isTranslatorEnabled ) { if ( changed && _isTranslatorEnabled !== undefined ) { debug( tracksEvent ); - recordTracksEvent( tracksEvent, { locale: i18n.getLocaleSlug } ); + recordTracksEvent( tracksEvent, { locale: i18n.getLocaleSlug() } ); } _isTranslatorEnabled = newSetting;
Fixes event prop for Community Translator event (#<I>)
Automattic_wp-calypso
train
62e8c5a0091d8819247ca5489ae4b88daa88ec0b
diff --git a/addon/components/colsconfig-dialog-content.js b/addon/components/colsconfig-dialog-content.js index <HASH>..<HASH> 100644 --- a/addon/components/colsconfig-dialog-content.js +++ b/addon/components/colsconfig-dialog-content.js @@ -32,6 +32,14 @@ export default FlexberryBaseComponent.extend({ objectlistviewEventsService: Ember.inject.service('objectlistview-events'), /** + Service for managing the state of the application. + + @property appState + @type AppStateService + */ + appState: Ember.inject.service(), + + /** Model with added DOM elements. @property modelForDOM @@ -362,7 +370,7 @@ export default FlexberryBaseComponent.extend({ @method actions.apply */ apply: function() { - this.get('objectlistviewEventsService').setLoadingState('loading'); + this.get('appState').loading(); if (!this.exportParams.isExportExcel) { let colsConfig = this._getSettings(); let settingName = Ember.$('#columnConfigurtionSettingName')[0].value.trim(); @@ -406,12 +414,11 @@ export default FlexberryBaseComponent.extend({ anchor.get(0).click(); } } - - this.get('objectlistviewEventsService').setLoadingState(''); }).catch((reason) => { - this.get('objectlistviewEventsService').setLoadingState(''); this.sendAction('close'); // close modal window this.currentController.send('handleError', reason); + }).finally(() => { + this.get('appState').reset(); }); } },
Feature colsconfig-dialog-content component update manage of app state
Flexberry_ember-flexberry
train
94b35018b06b7e9a936da3a12fd3767452a461f9
diff --git a/src/server/sockjs/session.js b/src/server/sockjs/session.js index <HASH>..<HASH> 100644 --- a/src/server/sockjs/session.js +++ b/src/server/sockjs/session.js @@ -1,13 +1,9 @@ -let Session -const util = require('util') +const Emitter = require('../../kite/emitter') -const EventEmitter = require('../../event-emitter.coffee') - -module.exports = Session = class Session extends EventEmitter { +export default class Session extends Emitter { constructor(connection) { - if (!(this instanceof Session)) { - return new Session(connection) - } + super() + this.connection = connection this.connection.on('data', message => {
Server/sockjs: fix session class issues [es6]
koding_kite.js
train
38d7f345051d97f30f0cb422b91af74eb19676f0
diff --git a/kbfsfuse/symlink.go b/kbfsfuse/symlink.go index <HASH>..<HASH> 100644 --- a/kbfsfuse/symlink.go +++ b/kbfsfuse/symlink.go @@ -25,6 +25,6 @@ func (*Symlink) Attr(a *fuse.Attr) { var _ fs.NodeReadlinker = (*Symlink)(nil) -func (a *Symlink) Readlink(ctx context.Context, req *fuse.ReadlinkRequest) (string, error) { - return a.de.SymPath, nil +func (s *Symlink) Readlink(ctx context.Context, req *fuse.ReadlinkRequest) (string, error) { + return s.de.SymPath, nil }
Consistent receiver name for Symlink
keybase_client
train
6e8b3b139ef89552a80cb39db491791a310c25a0
diff --git a/public/javascripts/activation_key.js b/public/javascripts/activation_key.js index <HASH>..<HASH> 100644 --- a/public/javascripts/activation_key.js +++ b/public/javascripts/activation_key.js @@ -199,6 +199,11 @@ KT.activation_key = function() { } }); }); + + subbutton.unbind('click').click(disableSubmit); + }, + disableSubmit = function() { + $('#subscription_submit_button').attr("disabled", "disabled"); }, goToAvailableSubscriptions = function() { var url = $('#go_to_available_subscriptions').attr('href');
a-keys - update to disable the Add/Remove button after click This commit is to avoid multiple requests to the server if the user were to click-click-click these buttons.
Katello_katello
train
fd11dafca25ff1fc0332053f5f12d2162e8dafa9
diff --git a/test/server.test.js b/test/server.test.js index <HASH>..<HASH> 100644 --- a/test/server.test.js +++ b/test/server.test.js @@ -1,5 +1,6 @@ // Copyright 2012 Mark Cavage, Inc. All rights reserved. +var assert = require('assert-plus'); var fs = require('fs'); var http = require('http'); @@ -170,6 +171,29 @@ test('rm', function (t) { }); +test('use - throws TypeError on non function as argument', function (t) { + var err = assert.AssertionError('handler (function) is required'); + + t.throws(function () { + SERVER.use('/nonfn'); + }, err); + + t.throws(function () { + SERVER.use({an:'object'}); + }, err); + + t.throws(function () { + SERVER.use( + function good() { return next() }, + '/bad', + {really:'bad'} + ); + }, err); + + t.end(); +}); + + test('405', function (t) { SERVER.post('/foo/:id', function posty(req, res, next) { t.ok(req.params);
port ce3c<I>ff<I>ec0bb<I>ed<I>d<I>cf<I>c from master
restify_plugins
train
3a0d4db6ee79862d802ee1ee4b1afe84ea39af35
diff --git a/katcp/client.py b/katcp/client.py index <HASH>..<HASH> 100644 --- a/katcp/client.py +++ b/katcp/client.py @@ -433,6 +433,11 @@ class DeviceClient(object): except Exception, e: if self._connect_failures % 5 == 0: # warn on every fifth failure + + # TODO (NM 2015-03-04) This can get a bit verbose, and typically we have + # other mechanisms for tracking failed connections. Consider doing some + # kind of exponential backoff starting at 5 times the reconnect time up to + # once per 5 minutes self._logger.warn("Failed to connect to {0!r}: {1}" .format(self._bindaddr, e)) self._connect_failures += 1
Add todo comment for exponential backoff on failed connections in client.py
ska-sa_katcp-python
train
10e887189fc0b4278fc1fdcc2a5144b23d5f636a
diff --git a/gddo-server/main.go b/gddo-server/main.go index <HASH>..<HASH> 100644 --- a/gddo-server/main.go +++ b/gddo-server/main.go @@ -60,6 +60,7 @@ const ( robotRequest queryRequest refreshRequest + apiRequest ) type crawlResult struct { @@ -84,7 +85,7 @@ func getDoc(path string, requestType int) (*doc.Package, []database.Package, err needsCrawl := false switch requestType { - case queryRequest: + case queryRequest, apiRequest: needsCrawl = nextCrawl.IsZero() && len(pkgs) == 0 case humanRequest: needsCrawl = nextCrawl.Before(time.Now()) @@ -598,7 +599,10 @@ func serveAPISearch(resp http.ResponseWriter, req *http.Request) error { var pkgs []database.Package if gosrc.IsValidRemotePath(q) || (strings.Contains(q, "/") && gosrc.IsGoRepoPath(q)) { - pdoc, _, err := getDoc(q, robotRequest) + pdoc, _, err := getDoc(q, apiRequest) + if e, ok := err.(gosrc.NotFoundError); ok && e.Redirect != "" { + pdoc, _, err = getDoc(e.Redirect, robotRequest) + } if err == nil && pdoc != nil { pkgs = []database.Package{{Path: pdoc.ImportPath, Synopsis: pdoc.Synopsis}} }
Follow redirect in search API Fixes #<I>.
golang_gddo
train
446b6ae8c94a7f2bfbcd02e16e12e43c75f74b8f
diff --git a/src/foremast/pipeline/renumerate_stages.py b/src/foremast/pipeline/renumerate_stages.py index <HASH>..<HASH> 100644 --- a/src/foremast/pipeline/renumerate_stages.py +++ b/src/foremast/pipeline/renumerate_stages.py @@ -22,9 +22,13 @@ LOG = logging.getLogger(__name__) def renumerate_stages(pipeline): """Renumber Pipeline Stage reference IDs to account for dependencies. - stage order is defined in the templates. - refId == 'a' - Any mainline required stage - refId == 'b' - Any secondary stage that should be ran in parallel + + stage order is defined in the templates. The ``refId`` field dictates + if a stage should be mainline or parallel to other stages. + + * ``master`` - A mainline required stage. Other stages depend on it + * ``branch`` - A stage that should be ran in parallel to master stages. + * ``merge`` - A stage thatis parallel but other stages still depend on it. Args: pipeline (dict): Completed Pipeline ready for renumeration. @@ -36,16 +40,20 @@ def renumerate_stages(pipeline): main_index = 0 for stage in stages: - if stage['refId'].lower() == 'master': + current_refId = stage['refId'].lower() + if current_refId == 'master': if main_index == 0: stage['requisiteStageRefIds'] = [] else: stage['requisiteStageRefIds'] = [str(main_index)] main_index += 1 stage['refId'] = str(main_index) - elif stage['refId'].lower() == 'branch': + elif current_refId == 'branch': stage['refId'] = str(main_index*100) stage['requisiteStageRefIds'] = [str(main_index)] + elif current_refId == 'merge': + # ToDo: Added logic to handle merge stages. + continue LOG.debug('step=%(name)s\trefId=%(refId)s\t' 'requisiteStageRefIds=%(requisiteStageRefIds)s', stage)
updated docstrings as per #<I> review
foremast_foremast
train
a12900ffdf1da60cfa085c7d7b93bee2aa19dd61
diff --git a/lib/imageruby/pureruby.rb b/lib/imageruby/pureruby.rb index <HASH>..<HASH> 100644 --- a/lib/imageruby/pureruby.rb +++ b/lib/imageruby/pureruby.rb @@ -151,7 +151,7 @@ public (0..draw_width-1).each do |x_orig| color = orig_pixel_data[origpointer..origpointer+2] - alpha = image.alpha_data[y_orig*image.width+x_orig] + alpha = image.alpha_data[y_orig*image.width+x_orig].ord if alpha < 255 if alpha > 0
fixed error on alpha decoding when reading ordinal
tario_imageruby
train
ec7000fcf89d5a2094051967d7f955fd0fae4d32
diff --git a/lib/fluent/plugin/in_forward.rb b/lib/fluent/plugin/in_forward.rb index <HASH>..<HASH> 100644 --- a/lib/fluent/plugin/in_forward.rb +++ b/lib/fluent/plugin/in_forward.rb @@ -151,7 +151,10 @@ module Fluent end @on_message = on_message @log = log - @log.trace { "accepted fluent socket object_id=#{self.object_id}" } + @log.trace { + remote_port, remote_addr = *Socket.unpack_sockaddr_in(@_io.getpeername) rescue nil + "accepted fluent socket from '#{remote_addr}:#{remote_port}': object_id=#{self.object_id}" + } end def on_connect diff --git a/lib/fluent/plugin/in_stream.rb b/lib/fluent/plugin/in_stream.rb index <HASH>..<HASH> 100644 --- a/lib/fluent/plugin/in_stream.rb +++ b/lib/fluent/plugin/in_stream.rb @@ -112,7 +112,10 @@ module Fluent end @on_message = on_message @log = log - @log.trace { "accepted fluent socket object_id=#{self.object_id}" } + @log.trace { + remote_port, remote_addr = *Socket.unpack_sockaddr_in(@_io.getpeername) rescue nil + "accepted fluent socket from '#{remote_addr}:#{remote_port}': object_id=#{self.object_id}" + } end def on_connect
Print remote address and port to trace who sends invalid logs.
fluent_fluentd
train
835559e292005f1a1fa3cee57227f3a90229abb6
diff --git a/drf_auto_endpoint/adapters.py b/drf_auto_endpoint/adapters.py index <HASH>..<HASH> 100644 --- a/drf_auto_endpoint/adapters.py +++ b/drf_auto_endpoint/adapters.py @@ -92,6 +92,15 @@ class EmberAdapter(BaseAdapter): MetaDataInfo('search_enabled', PROPERTY, False), ] + def render_root(self, config): + config['applications'] = [ + { + 'name': app['name'].replace('_', '-'), + 'models': app['models'] + } for app in config['applications'] + ] + return config + @classmethod def adapt_field(cls, field): new_field = {
:bug: application names in root_render for ember adapter
drf-forms_drf-schema-adapter
train
fe9b83cea35a322e0f9e715cadb7245d27d94117
diff --git a/Doctrine/Orm/AbstractFilter.php b/Doctrine/Orm/AbstractFilter.php index <HASH>..<HASH> 100644 --- a/Doctrine/Orm/AbstractFilter.php +++ b/Doctrine/Orm/AbstractFilter.php @@ -12,7 +12,6 @@ namespace Dunglas\ApiBundle\Doctrine\Orm; use Doctrine\Common\Persistence\ManagerRegistry; -use Doctrine\ORM\QueryBuilder; use Dunglas\ApiBundle\Api\IriConverterInterface; use Dunglas\ApiBundle\Api\ResourceInterface; use Symfony\Component\HttpFoundation\Request; diff --git a/Doctrine/Orm/DateFilter.php b/Doctrine/Orm/DateFilter.php index <HASH>..<HASH> 100644 --- a/Doctrine/Orm/DateFilter.php +++ b/Doctrine/Orm/DateFilter.php @@ -29,11 +29,6 @@ class DateFilter extends AbstractFilter private $properties; /** - * @var string Keyword used to retrieve the value. - */ - private $dateParameter; - - /** * @param ManagerRegistry $managerRegistry * @param array|null $properties List of property names on which the filter will be enabled. */
Fixed some SensioLabs Insight issues.
api-platform_core
train
0bc14be98b90def2057258296f10e0369e7d9964
diff --git a/chef/lib/chef/provider/package.rb b/chef/lib/chef/provider/package.rb index <HASH>..<HASH> 100644 --- a/chef/lib/chef/provider/package.rb +++ b/chef/lib/chef/provider/package.rb @@ -43,6 +43,7 @@ class Chef elsif @current_resource.version == nil install_version = candidate_version else + Chef::Log.debug("#{@new_resource} is already installed - nothing to do") return end @@ -50,7 +51,6 @@ class Chef raise(Chef::Exceptions::Package, "No version specified, and no candidate version available for #{@new_resource.package_name}") end - Chef::Log.info("Installing #{@new_resource} version #{install_version}") # We need to make sure we handle the preseed file if @new_resource.response_file @@ -61,25 +61,29 @@ class Chef if status @new_resource.updated_by_last_action(true) end + Chef::Log.info("#{@new_resource} installed version #{install_version}") end def action_upgrade if @current_resource.version != candidate_version orig_version = @current_resource.version || "uninstalled" - Chef::Log.info("Upgrading #{@new_resource} version from #{orig_version} to #{candidate_version}") status = upgrade_package(@new_resource.package_name, candidate_version) if status @new_resource.updated_by_last_action(true) end + Chef::Log.info("#{@new_resource} upgraded from #{orig_version} to #{candidate_version}") + else + Chef::Log.debug("#{@new_resource} is at the latest version - nothing to do") end end def action_remove if removing_package? - Chef::Log.info("Removing #{@new_resource}") remove_package(@current_resource.package_name, @new_resource.version) @new_resource.updated_by_last_action(true) + Chef::Log.info("#{@new_resource} removed") else + Chef::Log.debug("#{@new_resource} package does not exist - nothing to do") end end @@ -97,9 +101,9 @@ class Chef def action_purge if removing_package? - Chef::Log.info("Purging #{@new_resource}") purge_package(@current_resource.package_name, @new_resource.version) @new_resource.updated_by_last_action(true) + Chef::Log.info("#{@new_resource} purged") end end @@ -125,8 +129,8 @@ class Chef def get_preseed_file(name, version) resource = preseed_resource(name, version) - Chef::Log.debug("Fetching preseed file to #{resource.path}") resource.run_action('create') + Chef::Log.debug("#{@new_resource} fetched preseed file to #{resource.path}") if resource.updated_by_last_action? resource.path @@ -141,7 +145,7 @@ class Chef # The full path where the preseed file will be stored cache_seed_to = "#{file_cache_dir}/#{name}-#{version}.seed" - Chef::Log.debug("Fetching preseed file to #{cache_seed_to}") + Chef::Log.debug("#{@new_resource} fetching preseed file to #{cache_seed_to}") remote_file = Chef::Resource::CookbookFile.new(cache_seed_to, run_context) remote_file.cookbook_name = @new_resource.cookbook_name
Updating logging for the package provider
chef_chef
train
20160073f55cb6a46f568a5f8d9ab7e43b3740c6
diff --git a/lib/runcible/instance.rb b/lib/runcible/instance.rb index <HASH>..<HASH> 100644 --- a/lib/runcible/instance.rb +++ b/lib/runcible/instance.rb @@ -34,7 +34,6 @@ module Runcible @@extension_classes end - attr_accessor :resources attr_accessor :extensions @@ -72,6 +71,10 @@ module Runcible @config[key] = value end + def config + @config + end + private def initialize_wrappers(config) @@ -105,7 +108,6 @@ module Runcible end - #Wrapper class to provide access to instances class Wrapper @@ -124,6 +126,5 @@ module Runcible end end - end
adding a config method for retrieving current configuration
Katello_runcible
train
2de39b84cfaf51ac38ec07a183ac9eaf9ef094fb
diff --git a/manticore/native/cpu/x86.py b/manticore/native/cpu/x86.py index <HASH>..<HASH> 100644 --- a/manticore/native/cpu/x86.py +++ b/manticore/native/cpu/x86.py @@ -5882,6 +5882,31 @@ class X86Cpu(Cpu): dest.write(Operators.CONCAT(8 * len(result), *result)) @instruction + def PSUBQ(cpu, dest, src): + """ + PSUBQ: Packed add with quadruple words + Packed subtract with quad + + Subtracts the second operand (source operand) from the first operand (destination operand) and stores + the result in the destination operand. When packed quadword operands are used, a SIMD subtract is performed. + When a quadword result is too large to be represented in 64 bits (overflow), the result is wrapped around + and the low 64 bits are written to the destination element (that is, the carry is ignored). + + :param cpu: current CPU. + :param dest: destination operand. + :param src: source operand. + """ + result = [] + value_a = dest.read() + value_b = src.read() + + for i in reversed(range(0, dest.size, 64)): + a = Operators.EXTRACT(value_a, i, 64) + b = Operators.EXTRACT(value_b, i, 64) + result.append(a - b) + dest.write(Operators.CONCAT(dest.size, *result)) + + @instruction def POR(cpu, dest, src): """ Performs a bitwise logical OR operation on the source operand (second operand) and the destination operand diff --git a/tests/native/test_x86.py b/tests/native/test_x86.py index <HASH>..<HASH> 100644 --- a/tests/native/test_x86.py +++ b/tests/native/test_x86.py @@ -22314,6 +22314,70 @@ class CPUTest(unittest.TestCase): self.assertEqual(cpu.XMM0, 0) self.assertEqual(cpu.EBP, 4294948352) + def test_PSUBQ_1(self): + mem = Memory32() + cpu = I386Cpu(mem) + mem.mmap(0x08065000, 0x1000, "rwx") + + # psubq xmm0, xmm1 + mem[0x08065000] = "\x66" + mem[0x08065001] = "\x0f" + mem[0x08065002] = "\xfb" + mem[0x08065003] = "\xc1" + cpu.EIP = 0x8065000 + cpu.XMM0 = 0xDEADBEEFCAFEBABE0000000000000000 + cpu.XMM1 = 0xDEADBEEFCAFEBABE0000000000000001 + cpu.execute() + + self.assertEqual(mem[0x8065000], "\x66") + self.assertEqual(mem[0x8065001], "\x0f") + self.assertEqual(mem[0x8065002], "\xfb") + self.assertEqual(mem[0x8065003], "\xc1") + self.assertEqual(cpu.EIP, 0x08065004) + self.assertEqual(cpu.XMM0, 0x0000000000000000FFFFFFFFFFFFFFFF) + self.assertEqual(cpu.XMM1, 0xDEADBEEFCAFEBABE0000000000000001) + + def test_PSUBQ_2(self): + mem = Memory32() + cpu = I386Cpu(mem) + mem.mmap(0x08065000, 0x1000, "rwx") + mem.mmap(0xFFFFB000, 0x1000, "rwx") + + # psubq xmm0, xmmword ptr [ebp] + mem.write(0x08065000, "f\x0f\xfbE\x00") + mem.write(0xFFFFB600, (0xDEADBEEFCAFEBABE0000000000000001).to_bytes(16, "little")) + + cpu.EIP = 0x08065000 + cpu.XMM0 = 0xDEADBEEFCAFEBABE0000000000000000 + cpu.EBP = 0xFFFFB600 + cpu.execute() + + self.assertEqual(mem[0x08065000:0x08065005], [b"f", b"\x0f", b"\xfb", b"E", b"\x00"]) + self.assertEqual( + mem[0xFFFFB600:0xFFFFB610], + [ + b"\x01", + b"\x00", + b"\x00", + b"\x00", + b"\x00", + b"\x00", + b"\x00", + b"\x00", + b"\xBE", + b"\xBA", + b"\xFE", + b"\xCA", + b"\xEF", + b"\xBE", + b"\xAD", + b"\xDE", + ], + ) + self.assertEqual(cpu.EIP, 0x08065005) + self.assertEqual(cpu.XMM0, 0x0000000000000000FFFFFFFFFFFFFFFF) + self.assertEqual(cpu.EBP, 0xFFFFB600) + def test_PTEST_1(self): """Instruction PTEST_1 Groups: sse41
Add `psubq` instruction (x<I>) (#<I>) * psubq tests
trailofbits_manticore
train
9c66b1f190bff8de14856229b232b51a037dd63e
diff --git a/tasks/gh-pages.js b/tasks/gh-pages.js index <HASH>..<HASH> 100644 --- a/tasks/gh-pages.js +++ b/tasks/gh-pages.js @@ -62,16 +62,28 @@ module.exports = function(grunt) { grunt.fatal(new Error('Unexpected config: ' + String(data))); } - var options = this.options({ + var defaults = { git: 'git', clone: path.join('.grunt', pkg.name, this.name, this.target), branch: 'gh-pages', remote: 'origin', base: process.cwd(), - only: grunt.option(pkg.name + '-only') || '.', + only: '.', push: true, message: 'Updates' - }); + }; + + // override defaults with any task options + var options = this.options(defaults); + + // allow command line options to override + var value; + for (var option in defaults) { + value = grunt.option(pkg.name + '-' + option); + if (value !== undefined) { + options[option] = value; + } + } if (!grunt.file.isDir(options.base)) { grunt.fatal(new Error('The "base" option must be an existing directory'));
Allow command line options to override task options
tschaub_grunt-gh-pages
train
dd9a29fc83171178ebdfb67fc97e01752cd35589
diff --git a/wsgiservice/resource.py b/wsgiservice/resource.py index <HASH>..<HASH> 100644 --- a/wsgiservice/resource.py +++ b/wsgiservice/resource.py @@ -389,7 +389,7 @@ class Resource(object): rules = self._get_validation(method, param) if not rules: return - if value is None or len(str(value)) == 0: + if value is None or (isinstance(value, basestring) and len(value) == 0): raise ValidationException( "Value for {0} must not be empty.".format(param)) elif 're' in rules and rules['re']:
resource.py (Resource.validate_param): Make isinstance check more robust for the case when value is a unicode string.
pneff_wsgiservice
train
964e22487af8f652fd03b1f140024d1746c4113b
diff --git a/core/src/main/java/jenkins/SlaveToMasterFileCallable.java b/core/src/main/java/jenkins/SlaveToMasterFileCallable.java index <HASH>..<HASH> 100644 --- a/core/src/main/java/jenkins/SlaveToMasterFileCallable.java +++ b/core/src/main/java/jenkins/SlaveToMasterFileCallable.java @@ -8,6 +8,7 @@ import org.jenkinsci.remoting.RoleChecker; * {@link FileCallable}s that can be executed on the master, sent by the agent. * * @since 1.587 / 1.580.1 + * @param <T> the return type; note that this must either be defined in your plugin or included in the stock JEP-200 whitelist */ public abstract class SlaveToMasterFileCallable<T> implements FileCallable<T> { @Override diff --git a/core/src/main/java/jenkins/security/SlaveToMasterCallable.java b/core/src/main/java/jenkins/security/SlaveToMasterCallable.java index <HASH>..<HASH> 100644 --- a/core/src/main/java/jenkins/security/SlaveToMasterCallable.java +++ b/core/src/main/java/jenkins/security/SlaveToMasterCallable.java @@ -9,6 +9,7 @@ import org.jenkinsci.remoting.RoleChecker; * * @author Kohsuke Kawaguchi * @since 1.587 / 1.580.1 + * @param <V> the return type; note that this must either be defined in your plugin or included in the stock JEP-200 whitelist */ public abstract class SlaveToMasterCallable<V, T extends Throwable> implements Callable<V,T> { @Override
Reminder about JEP-<I> impacts on slave → master callables.
jenkinsci_jenkins
train
3c720116c31ed69b944011420f2fd70c70f143e3
diff --git a/spring-cloud-sleuth-core/src/main/java/org/springframework/cloud/sleuth/instrument/web/TraceFilter.java b/spring-cloud-sleuth-core/src/main/java/org/springframework/cloud/sleuth/instrument/web/TraceFilter.java index <HASH>..<HASH> 100644 --- a/spring-cloud-sleuth-core/src/main/java/org/springframework/cloud/sleuth/instrument/web/TraceFilter.java +++ b/spring-cloud-sleuth-core/src/main/java/org/springframework/cloud/sleuth/instrument/web/TraceFilter.java @@ -250,8 +250,8 @@ public class TraceFilter extends GenericFilterBean { if (response.getStatus() == 0) { return false; } - HttpStatus httpStatus = HttpStatus.valueOf(response.getStatus()); - return httpStatus.is1xxInformational() || httpStatus.is2xxSuccessful() || httpStatus.is3xxRedirection(); + HttpStatus.Series httpStatusSeries = HttpStatus.Series.valueOf(response.getStatus()); + return httpStatusSeries == HttpStatus.Series.SUCCESSFUL || httpStatusSeries == HttpStatus.Series.REDIRECTION; } private Span getSpanFromAttribute(HttpServletRequest request) { diff --git a/spring-cloud-sleuth-core/src/test/java/org/springframework/cloud/sleuth/instrument/web/TraceFilterTests.java b/spring-cloud-sleuth-core/src/test/java/org/springframework/cloud/sleuth/instrument/web/TraceFilterTests.java index <HASH>..<HASH> 100644 --- a/spring-cloud-sleuth-core/src/test/java/org/springframework/cloud/sleuth/instrument/web/TraceFilterTests.java +++ b/spring-cloud-sleuth-core/src/test/java/org/springframework/cloud/sleuth/instrument/web/TraceFilterTests.java @@ -328,6 +328,32 @@ public class TraceFilterTests { } @Test + public void closesSpanWhenResponseStatusIs2xx() throws Exception { + this.request = builder().header(Span.SPAN_ID_NAME, PARENT_ID) + .header(Span.TRACE_ID_NAME, 20L).buildRequest(new MockServletContext()); + TraceFilter filter = new TraceFilter(this.tracer, this.traceKeys, this.spanReporter, + this.spanExtractor, this.httpTraceKeysInjector); + this.response.setStatus(200); + + filter.doFilter(this.request, this.response, this.filterChain); + + then(TestSpanContextHolder.getCurrentSpan()).isNull(); + } + + @Test + public void closesSpanWhenResponseStatusIs3xx() throws Exception { + this.request = builder().header(Span.SPAN_ID_NAME, PARENT_ID) + .header(Span.TRACE_ID_NAME, 20L).buildRequest(new MockServletContext()); + TraceFilter filter = new TraceFilter(this.tracer, this.traceKeys, this.spanReporter, + this.spanExtractor, this.httpTraceKeysInjector); + this.response.setStatus(302); + + filter.doFilter(this.request, this.response, this.filterChain); + + then(TestSpanContextHolder.getCurrentSpan()).isNull(); + } + + @Test public void returns400IfSpanIsMalformedAndCreatesANewSpan() throws Exception { this.request = builder().header(Span.SPAN_ID_NAME, "asd") .header(Span.TRACE_ID_NAME, 20L).buildRequest(new MockServletContext());
Custom HTTP status codes support (#<I>) Provides custom HTTP status codes support without this change applications using custom HTTP status codes are currently having issues with Spring Cloud Sleuth. TraceFilter.httpStatusSuccessful() is throwing an IllegalArgumentException on HttpStatus.valueOf(response.getStatus()). with this change that gets fixed
spring-cloud_spring-cloud-sleuth
train
c1fecba0e1d37b96cd45219c43522ce1f42edc81
diff --git a/spec/opal/filters/bugs/array.rb b/spec/opal/filters/bugs/array.rb index <HASH>..<HASH> 100644 --- a/spec/opal/filters/bugs/array.rb +++ b/spec/opal/filters/bugs/array.rb @@ -1,8 +1,5 @@ opal_filter "Array" do fails "Array#clone copies singleton methods" - fails "Array#clone creates a new array containing all elements or the original" - - fails "Array#collect! returns an Enumerator when no block given, and the enumerator can modify the original array" fails "Array#combination generates from a defensive copy, ignoring mutations" fails "Array#combination yields a partition consisting of only singletons"
Remove old filtes for Array#clone and #collect!
opal_opal
train
1de8eaf3fe31ffb786def1b7511e719184d0ed46
diff --git a/openid/consumer.py b/openid/consumer.py index <HASH>..<HASH> 100644 --- a/openid/consumer.py +++ b/openid/consumer.py @@ -42,11 +42,15 @@ def normalize_url(url): class SimpleHTTPClient(object): def get(self, url): - f = urllib2.urlopen(url) try: - data = f.read() - finally: - f.close() + f = urllib2.urlopen(url) + try: + data = f.read() + finally: + f.close() + except urllib2.HTTPError, why: + why.close() + return None return (f.geturl(), data) @@ -59,21 +63,14 @@ class SimpleHTTPClient(object): finally: f.close() except urllib2.HTTPError, why: - if why.code == 400: - try: + try: + if why.code == 400: data = why.read() - finally: - why.close() - args = parsekv(data) - error = args.get('error') - if error is None: - raise ProtocolError("Unspecified Server Error: %r" % - (args,)) else: - raise ProtocolError("Server Response: %r" % (error,)) - else: - raise - + return None + finally: + why.close() + return (f.geturl(), data) @@ -185,7 +182,11 @@ class OpenIDConsumer(object): identity = cgi.parse_qs(post_data)['openid.identity'][0] return ValidLogin(self, identity) else: - return InvalidLogin() + error = results.get('error') + if error is None: + return InvalidLogin() + else: + return ErrorFromServer("Server Response: %r" % (error,)) def do_id_res(self, req): if not self.verify_return_to(req.return_to):
[project @ Simplify error handling in the HTTPClient classes]
necaris_python3-openid
train
35e98bfea0ded24038f7a58177b7baa900ad1208
diff --git a/spec/flipper/middleware/memoizer_spec.rb b/spec/flipper/middleware/memoizer_spec.rb index <HASH>..<HASH> 100644 --- a/spec/flipper/middleware/memoizer_spec.rb +++ b/spec/flipper/middleware/memoizer_spec.rb @@ -218,6 +218,39 @@ RSpec.describe Flipper::Middleware::Memoizer do end end + context 'with multiple instances' do + let(:app) do + # ensure scoped for builder block, annoying... + instance = flipper + middleware = described_class + + Rack::Builder.new do + use middleware, preload: %i(stats) + # Second instance should be a noop + use middleware, preload: true + + map '/' do + run ->(_env) { [200, {}, []] } + end + + map '/fail' do + run ->(_env) { raise 'FAIL!' } + end + end.to_app + end + + include_examples 'flipper middleware' + + it 'does not call preload in second instance' do + expect(flipper).not_to receive(:preload_all) + + get '/', {}, 'flipper' => flipper + + expect(adapter.count(:get_multi)).to be(1) + expect(adapter.last(:get_multi).args).to eq([[flipper[:stats]]]) + end + end + context 'when an app raises an exception' do it 'resets memoize' do begin
Spec for duplicate calls to Memoizer
jnunemaker_flipper
train
b5c0d96b5ea44c2316b3b0c2f799d71969f446b1
diff --git a/test/functional/engine_helper.rb b/test/functional/engine_helper.rb index <HASH>..<HASH> 100644 --- a/test/functional/engine_helper.rb +++ b/test/functional/engine_helper.rb @@ -52,8 +52,8 @@ else uses the in-memory Ruote::Engine (fastest, but no persistence at all) exit 0 end - application_context[:persist_as_yaml] = true if ARGV.include?('-y') - application_context[:no_expstorage_cache] = true if ARGV.include?('-C') + application_context[:persist_as_yaml] = ARGV.include?('-y') + application_context[:no_expstorage_cache] = ARGV.include?('-C') klass = $ruote_engine_class
fixed caching / no caching switch for functional tests
jmettraux_ruote
train
3cea26eb2ed00f55ba4ddf9cf4c873f11fb8f849
diff --git a/docs/assets/js/app.js b/docs/assets/js/app.js index <HASH>..<HASH> 100644 --- a/docs/assets/js/app.js +++ b/docs/assets/js/app.js @@ -218,6 +218,8 @@ NavController.$inject = ['$scope', '$state', '$window']; function NavController($scope, $state, $window) { + var routes = angular.copy($window.BaseAppsRoutes); + $scope.current = $state.current.name; //setup autocomplete @@ -225,7 +227,7 @@ $scope.typedText = ''; if($window.BaseAppsRoutes) { - angular.forEach(angular.copy($window.BaseAppsRoutes), function(r) { + angular.forEach(routes, function(r) { var title = r.title || r.name.replace('.', ' '); //use title if possible $scope.routing.push(title); });
fix search box resolves <URL>
base-apps_angular-base-apps
train
ad38a3e987cc0f0c5792eaf8f782748ed258e0f7
diff --git a/mongoctl/tests/test_suite.py b/mongoctl/tests/test_suite.py index <HASH>..<HASH> 100644 --- a/mongoctl/tests/test_suite.py +++ b/mongoctl/tests/test_suite.py @@ -38,8 +38,7 @@ all_suites = [ unittest.TestLoader().loadTestsFromTestCase(MasterSlaveTest), unittest.TestLoader().loadTestsFromTestCase(ReplicasetTest), unittest.TestLoader().loadTestsFromTestCase(AuthReplicasetTest), - unittest.TestLoader().loadTestsFromTestCase(MiscTest), - unittest.TestLoader().loadTestsFromTestCase(InstallTest) + unittest.TestLoader().loadTestsFromTestCase(MiscTest) ] ############################################################################### # booty
Temporarily remove "install_test" since it currently can uninstall from test suite until we figure out how to fix it
mongolab_mongoctl
train
922c1b7b5c3f12e29bd64d7a2420e2a8d0d71562
diff --git a/python/bigdl/dllib/optim/optimizer.py b/python/bigdl/dllib/optim/optimizer.py index <HASH>..<HASH> 100644 --- a/python/bigdl/dllib/optim/optimizer.py +++ b/python/bigdl/dllib/optim/optimizer.py @@ -690,6 +690,31 @@ class Optimizer(JavaValue): callBigDlFunc(self.bigdl_type, "setCheckPoint", self.value, checkpoint_trigger, checkpoint_path, isOverWrite) + def set_gradclip_const(self, min_value, max_value): + """ + Configure constant clipping settings. + + + :param min_value: the minimum value to clip by + :param max_value: the maxmimum value to clip by + """ + callBigDlFunc(self.bigdl_type, "setConstantClip", self.value, min_value, max_value) + + def set_gradclip_l2norm(self, clip_norm): + """ + Configure L2 norm clipping settings. + + + :param clip_norm: gradient L2-Norm threshold + """ + callBigDlFunc(self.bigdl_type, "setL2NormClip", self.value, clip_norm) + + def disable_gradclip(self): + """ + disable clipping. + """ + callBigDlFunc(self.bigdl_type, "disableClip", self.value) + # return a module def optimize(self): """
Support gradient clipping (#<I>) support constant clip and l2norm clipping
intel-analytics_BigDL
train
86e542e6ec65db039c80d071e4a140e642cf4ab7
diff --git a/lib/git.js b/lib/git.js index <HASH>..<HASH> 100644 --- a/lib/git.js +++ b/lib/git.js @@ -74,7 +74,7 @@ Git.prototype.cmd = function(payload, options, done) { // Build create options. var createOpts = this.kbox.util.docker.CreateOpts() - .workingDir('/code') + .workingDir(workingDir) .env('GITUSER', gitUser) .env('GITEMAIL', gitEmail) .volumeFrom(this.app.dataContainerName)
#<I>: Switch back to dynamic cwd
pirog_kalabox-plugin-git
train
6fdabe9e6f411c336e6b6b55fc582a3a8b78da9d
diff --git a/src/angular-multi-select.js b/src/angular-multi-select.js index <HASH>..<HASH> 100644 --- a/src/angular-multi-select.js +++ b/src/angular-multi-select.js @@ -209,6 +209,30 @@ angular_multi_select.directive('angularMultiSelect', ['$rootScope', '$sce', '$ti return $scope.baseExtend(dst, [].slice.call(arguments, 1), true); }; + $scope.deepCompare = function(x, y){ + if (x === null || x === undefined || y === null || y === undefined) { return x === y; } + // after this just checking type of one would be enough + if (x.constructor !== y.constructor) { return false; } + // if they are functions, they should exactly refer to same one (because of closures) + if (x instanceof Function) { return x === y; } + // if they are regexps, they should exactly refer to same one (it is hard to better equality check on current ES) + if (x instanceof RegExp) { return x === y; } + if (x === y || x.valueOf() === y.valueOf()) { return true; } + if (Array.isArray(x) && x.length !== y.length) { return false; } + + // if they are dates, they must had equal valueOf + if (x instanceof Date) { return false; } + + // if they are strictly equal, they both need to be object at least + if (!(x instanceof Object)) { return false; } + if (!(y instanceof Object)) { return false; } + + // recursive object equality check + var p = Object.keys(x); + return Object.keys(y).every(function (i) { return p.indexOf(i) !== -1; }) && + p.every(function (i) { return $scope.deepCompare(x[i], y[i]); }); + }; + /** * Helper function to inverse the result of a function called by a filter from a template * @param f
Add a helper function that deeply compares two objects
alexandernst_angular-multi-select
train
2bb8b0290f14c4fbbe9e20f9cd8a2a761af2a8ca
diff --git a/netmiko/huawei/huawei.py b/netmiko/huawei/huawei.py index <HASH>..<HASH> 100644 --- a/netmiko/huawei/huawei.py +++ b/netmiko/huawei/huawei.py @@ -97,7 +97,7 @@ class HuaweiSSH(HuaweiBase): output = self.read_until_prompt_or_pattern(password_change_prompt) if re.search(password_change_prompt, output): self.write_channel("N\n") - self._read_channel_expect(pattern="N\n") + self.clear_buffer() return output
Minor Huawei Fix (#<I>)
ktbyers_netmiko
train
f253753e7904a7596f4050d1e53141f5eaedb801
diff --git a/dispatch/api/views.py b/dispatch/api/views.py index <HASH>..<HASH> 100644 --- a/dispatch/api/views.py +++ b/dispatch/api/views.py @@ -258,7 +258,7 @@ class PollViewSet(DispatchModelViewSet): queryset = Poll.objects.all() q = self.request.query_params.get('q', None) if q is not None: - queryset = queryset.filter(question__icontains=q) + queryset = queryset.filter(Q(name__icontains=q) | Q(question__icontains=q) ) return queryset class PollVoteViewSet(DispatchModelViewSet):
can search polls by name or by question
ubyssey_dispatch
train
4b355fd6f810344866e50370ad9fc5ebded52ea5
diff --git a/examples/__tests__/SimpleSlider.test.js b/examples/__tests__/SimpleSlider.test.js index <HASH>..<HASH> 100644 --- a/examples/__tests__/SimpleSlider.test.js +++ b/examples/__tests__/SimpleSlider.test.js @@ -4,6 +4,9 @@ import SimpleSlider from '../SimpleSlider'; import { repeatClicks } from '../../test-helpers'; import { html as beautify_html } from 'js-beautify' +import { getReactSlickDetails } from '../../__tests__/reactSlickUtils' +import { getJQuerySlickDetails } from '../../__tests__/jQSlickUtils' + describe('Simple Slider', function () { it('should have 13 slides (1(preclone) + 6(actual) + 6(postclone))', function () { const wrapper = mount(<SimpleSlider />); @@ -92,3 +95,62 @@ describe("Simple Slider Snapshots", function () { expect(beautify_html(wrapper.html())).toMatchSnapshot() }) }); + +export function testWithParams(settings, actions, keys) { + let reactDetails = getReactSlickDetails(settings, actions, keys) + let jQueryDetails = getJQuerySlickDetails(settings, actions, keys) + test('currentSlide', () => { + expect(reactDetails.currentSlide).toEqual(jQueryDetails.currentSlide) + }) + test('activeSlides', () => { + expect(reactDetails.activeSlides).toEqual(jQueryDetails.activeSlides) + }) + test('allSlides', () => { + expect(reactDetails.allSlides).toEqual(jQueryDetails.allSlides) + }) + test('activeSlides', () => { + expect(reactDetails.clonedSlides).toEqual(jQueryDetails.clonedSlides) + }) +} + +describe('Simple Slider React Vs jQuery', () => { + + let settings = { + noOfSlides: 5, + infinite: true, + speed: 0, + useCSS: false, + slidesToShow: 1, + slidesToScroll: 1 + } + let actions = {} + let keys = { + currentSlide: true, + activeSlides: true, + clonedSlides: true, + allSlides: true, + visibleSlides: true + } + + // first section + testWithParams(settings, actions, keys) + + // second section + actions = { + clickNext: 6 + } + testWithParams(settings, actions, keys) + + // third section + actions = { + clickPrev: 6 + } + testWithParams(settings, actions, keys) + + // fourth section + actions = { + clickSequence: 'nnpnnnnppnnnnnn' + } + testWithParams(settings, actions, keys) + +}) \ No newline at end of file
react vs jquery tests added for simple slider
akiran_react-slick
train
a8d79f7a4ffd770bfa3df28a1609bb39da595dbf
diff --git a/src/Propel/Runtime/Connection/ConnectionInterface.php b/src/Propel/Runtime/Connection/ConnectionInterface.php index <HASH>..<HASH> 100644 --- a/src/Propel/Runtime/Connection/ConnectionInterface.php +++ b/src/Propel/Runtime/Connection/ConnectionInterface.php @@ -99,7 +99,7 @@ interface ConnectionInterface * object, depending on the underlying driver. For example, PDO_PGSQL() * requires you to specify the name of a sequence object for the name parameter. * - * @param string $name Name of the sequence object from which the ID should be + * @param string|null $name Name of the sequence object from which the ID should be * returned. * * @return string If a sequence name was not specified for the name parameter, @@ -109,7 +109,7 @@ interface ConnectionInterface * a string representing the last value retrieved from the specified * sequence object. */ - public function lastInsertId(?string $name = null); + public function lastInsertId($name = null); /** * @param $data diff --git a/src/Propel/Runtime/Connection/ConnectionWrapper.php b/src/Propel/Runtime/Connection/ConnectionWrapper.php index <HASH>..<HASH> 100644 --- a/src/Propel/Runtime/Connection/ConnectionWrapper.php +++ b/src/Propel/Runtime/Connection/ConnectionWrapper.php @@ -496,7 +496,7 @@ class ConnectionWrapper implements ConnectionInterface, LoggerAwareInterface * object, depending on the underlying driver. For example, PDO_PGSQL() * requires you to specify the name of a sequence object for the name parameter. * - * @param string $name Name of the sequence object from which the ID should be + * @param string|null $name Name of the sequence object from which the ID should be * returned. * * @return string If a sequence name was not specified for the name parameter,
Use adapter for PHP7+PHP8
propelorm_Propel2
train
d4f9eca8a0eaa05d325c23fef6cfc4d665f30eab
diff --git a/src/InfoViz/Native/FieldSelector/index.js b/src/InfoViz/Native/FieldSelector/index.js index <HASH>..<HASH> 100644 --- a/src/InfoViz/Native/FieldSelector/index.js +++ b/src/InfoViz/Native/FieldSelector/index.js @@ -212,8 +212,12 @@ function fieldSelector(publicAPI, model) { const { color, shape } = model.provider.getLegend(fieldName); legendCell.html(`<svg class='${ style.legendSvg - }' width='${legendSize}' height='${legendSize}' - fill='${color}' stroke='black'><use xlink:href='${shape}'/></svg>`); + }' width='${legendSize}' height='${legendSize}' viewBox='${ + shape.viewBox + }' + fill='${color}' stroke='black'><use xlink:href='#${ + shape.id + }'/></svg>`); } else { legendCell .html('<i></i>')
fix(FieldSelector): Expect new SVG loader behavior
Kitware_paraviewweb
train
2f7bf97c7827379444559097d10298ea565fae6f
diff --git a/library/CM/Paging/StreamSubscribe/AdapterType.php b/library/CM/Paging/StreamSubscribe/AdapterType.php index <HASH>..<HASH> 100644 --- a/library/CM/Paging/StreamSubscribe/AdapterType.php +++ b/library/CM/Paging/StreamSubscribe/AdapterType.php @@ -6,23 +6,9 @@ class CM_Paging_StreamSubscribe_AdapterType extends CM_Paging_StreamSubscribe_Ab * @param int $adapterType */ public function __construct($adapterType) { + $adapterType = (int) $adapterType; $source = new CM_PagingSource_Sql(TBL_CM_STREAM_SUBSCRIBE . '.`id`', TBL_CM_STREAM_SUBSCRIBE, '`adapterType` = ' . $adapterType, null, 'JOIN ' . TBL_CM_STREAMCHANNEL . ' ON ' . TBL_CM_STREAM_SUBSCRIBE . '.channelId = ' . TBL_CM_STREAMCHANNEL . '.id'); $source->enableCache(); return parent::__construct($source); } - - /** - * @param string $key - * @return CM_Model_Stream_Subscribe|null - */ - public function findKey($key) { - $key = (string) $key; - /** @var CM_Model_Stream_Subscribe $streamSubscribe */ - foreach ($this as $streamSubscribe) { - if ($streamSubscribe->getKey() == $key) { - return $streamSubscribe; - } - } - return null; - } }
Adjust Stream_Subscribe Paging
cargomedia_cm
train
e239a3b650c04e22b4068e392197af188acee973
diff --git a/src/Behavior.php b/src/Behavior.php index <HASH>..<HASH> 100644 --- a/src/Behavior.php +++ b/src/Behavior.php @@ -30,7 +30,7 @@ class Behavior extends \yii\base\Behavior /** * @var LoaderInterface */ - private $_loader; + private $_loader = []; /** * @inheritdoc @@ -66,11 +66,21 @@ class Behavior extends \yii\base\Behavior /** * @return LoaderInterface + * + * @throws InvalidConfigException */ public function getLoader() { - if ($this->_loader === null) { - $this->setLoader(['class' => 'ischenko\yii2\jsloader\RequireJs']); + if (is_array($this->_loader)) { + if (empty($this->_loader['class'])) { + $this->_loader['class'] = 'ischenko\yii2\jsloader\RequireJs'; + } + + $this->_loader = \Yii::createObject($this->_loader, [$this->ensureView($this->owner)]); + } + + if (!($this->_loader instanceof LoaderInterface)) { + throw new InvalidConfigException("Unable to instantiate new loader please check configuration"); } return $this->_loader; @@ -83,12 +93,8 @@ class Behavior extends \yii\base\Behavior */ public function setLoader($loader) { - if (is_array($loader)) { - $loader = \Yii::createObject($loader, [$this->ensureView($this->owner)]); - } - - if (!($loader instanceof LoaderInterface)) { - throw new InvalidParamException("Argument is not an object that implements loader interface"); + if (!is_array($loader) && !($loader instanceof LoaderInterface)) { + throw new InvalidParamException("Argument should be an array or implement LoaderInterface"); } $this->_loader = $loader; diff --git a/src/base/Config.php b/src/base/Config.php index <HASH>..<HASH> 100644 --- a/src/base/Config.php +++ b/src/base/Config.php @@ -83,7 +83,6 @@ abstract class Config extends Object implements ConfigInterface return $this; } - /** * @return \ArrayObject an object that used as internal storage */ diff --git a/tests/unit/BehaviorTest.php b/tests/unit/BehaviorTest.php index <HASH>..<HASH> 100644 --- a/tests/unit/BehaviorTest.php +++ b/tests/unit/BehaviorTest.php @@ -79,8 +79,16 @@ class BehaviorTest extends \Codeception\Test\Unit $this->behavior->attach($this->tester->mockView()); + $this->specify('it accepts array as argument', function() { + $stub = $this->tester->mockBaseLoader(); + + $this->behavior->setLoader(['class' => get_class($stub)]); + + verify($this->behavior->getLoader())->isInstanceOf(get_class($stub)); + }); + $this->specify('setter throws an exception', function () { - $this->specify('if argument is not an object that implements loader interface', function ($value) { + $this->specify('if argument is not an array or an object that implements loader interface', function ($value) { $this->behavior->setLoader($value); }, [ 'examples' => [ @@ -92,22 +100,13 @@ class BehaviorTest extends \Codeception\Test\Unit ], 'throws' => 'yii\base\InvalidParamException' ]); - - $this->specify('if argument is not a valid configuration array', function () { - $this->specify('class element is missing', function () { - $this->behavior->setLoader([]); - }, ['throws' => 'yii\base\InvalidConfigException']); - - $this->specify('class does not exist', function () { - $this->behavior->setLoader(['class' => uniqid('test_')]); - }, ['throws' => 'ReflectionException']); - - $this->specify('class does not implement loader interface', function () { - $this->behavior->setLoader(['class' => 'yii\web\View']); - }, ['throws' => 'yii\base\InvalidParamException']); - }); }); + $this->specify('getter throws an exception if object does not implement LoaderInterface', function () { + $this->behavior->setLoader(['class' => '\ArrayObject']); + $this->behavior->getLoader(); + }, ['throws' => 'yii\base\InvalidConfigException']); + $this->specify('getter returns an instance of requirejs loader by default', function () { verify($this->behavior->getLoader())->isInstanceOf('ischenko\yii2\jsloader\RequireJs'); });
Fixed issue when the Behavior throws an exception upon application bootstrap
ischenko_yii2-jsloader
train
e69b8a8c37eedad34cbe5358bb259e1348641df5
diff --git a/samples/flushfs/flush_fs.go b/samples/flushfs/flush_fs.go index <HASH>..<HASH> 100644 --- a/samples/flushfs/flush_fs.go +++ b/samples/flushfs/flush_fs.go @@ -90,6 +90,29 @@ func (fs *flushFS) barAttributes() fuseops.InodeAttributes { } } +// LOCKS_REQUIRED(fs.mu) +func (fs *flushFS) getAttributes(id fuseops.InodeID) ( + attrs fuseops.InodeAttributes, + err error) { + switch id { + case fuseops.RootInodeID: + attrs = fs.rootAttributes() + return + + case fooID: + attrs = fs.fooAttributes() + return + + case barID: + attrs = fs.barAttributes() + return + + default: + err = fuse.ENOENT + return + } +} + //////////////////////////////////////////////////////////////////////// // FileSystem methods //////////////////////////////////////////////////////////////////////// @@ -134,23 +157,20 @@ func (fs *flushFS) GetInodeAttributes( fs.mu.Lock() defer fs.mu.Unlock() - switch op.Inode { - case fuseops.RootInodeID: - op.Attributes = fs.rootAttributes() - return + op.Attributes, err = fs.getAttributes(op.Inode) + return +} - case fooID: - op.Attributes = fs.fooAttributes() - return +func (fs *flushFS) SetInodeAttributes( + ctx context.Context, + op *fuseops.SetInodeAttributesOp) (err error) { + fs.mu.Lock() + defer fs.mu.Unlock() - case barID: - op.Attributes = fs.barAttributes() - return + // Ignore any changes and simply return existing attributes. + op.Attributes, err = fs.getAttributes(op.Inode) - default: - err = fuse.ENOENT - return - } + return } func (fs *flushFS) OpenFile(
Implement setattr; otherwise closing after writing fails.
jacobsa_fuse
train
c02a7c7913970c64694d136285b4379da1bda0ce
diff --git a/qbit/core/src/test/java/io/advantageous/qbit/service/ServiceBundleBuilderTest.java b/qbit/core/src/test/java/io/advantageous/qbit/service/ServiceBundleBuilderTest.java index <HASH>..<HASH> 100644 --- a/qbit/core/src/test/java/io/advantageous/qbit/service/ServiceBundleBuilderTest.java +++ b/qbit/core/src/test/java/io/advantageous/qbit/service/ServiceBundleBuilderTest.java @@ -92,7 +92,7 @@ public class ServiceBundleBuilderTest { serviceBundle.addService(new MyService()); final IMyService proxy = serviceBundle.createLocalProxy(IMyService.class, "A"); - for (int index = 0; index < 1_000_000; index++) { + for (int index = 0; index < 1_000; index++) { proxy.foo(); timer.seconds(6); @@ -101,7 +101,7 @@ public class ServiceBundleBuilderTest { } - Sys.sleep(10_000); + Sys.sleep(1_000); assertTrue(stats.containsKey("A.queueRequestSize")); @@ -109,7 +109,7 @@ public class ServiceBundleBuilderTest { assertTrue(stats.containsKey("A.startBatchCount")); - for (int index = 0; index < 1_000_000; index++) { + for (int index = 0; index < 1_000; index++) { proxy.foo(); timer.seconds(6); @@ -118,7 +118,7 @@ public class ServiceBundleBuilderTest { } - Sys.sleep(2000); + Sys.sleep(1_000); } } \ No newline at end of file
travis is so under powered. It used to be cooler.
advantageous_qbit
train
4c0f7ff48e2c9f71ebd6a761d7ea82b13fe27a4e
diff --git a/src/Crypt.php b/src/Crypt.php index <HASH>..<HASH> 100644 --- a/src/Crypt.php +++ b/src/Crypt.php @@ -45,10 +45,10 @@ class Crypt public function __construct(CipherInterface $cipher = null, Key $key = null) { // Set the encryption cipher. - $this->cipher = $cipher !== null ? $cipher : new Crypto; + $this->cipher = $cipher ?: new Crypto; // Set the encryption key[/pair)]. - $this->key = $key !== null ? $key : $this->generateKey(); + $this->key = $key ?: $this->generateKey(); } /**
Change, according to @mbabker's suggestion
joomla-framework_crypt
train
9f55547f9b5e2a03cf60b58a6a4df9429cb18fac
diff --git a/history.go b/history.go index <HASH>..<HASH> 100644 --- a/history.go +++ b/history.go @@ -88,6 +88,11 @@ func (o *opHistory) HistoryRewrite() { } buf.Flush() + // replace history file + if err = os.Rename(tmpFile, o.cfg.HistoryFile); err != nil { + return + } + if o.fd != nil { o.fd.Close() }
fix history rewrite replace origin file
chzyer_readline
train
8c9582f3d0a75dd7b8dd28613649f2aa2dabecfe
diff --git a/src/com/google/javascript/jscomp/CheckProvides.java b/src/com/google/javascript/jscomp/CheckProvides.java index <HASH>..<HASH> 100644 --- a/src/com/google/javascript/jscomp/CheckProvides.java +++ b/src/com/google/javascript/jscomp/CheckProvides.java @@ -110,6 +110,11 @@ class CheckProvides implements HotSwapCompilerPass { String ctor = ctorEntry.getKey(); int index = -1; boolean found = false; + + if (ctor.startsWith("$jscomp.scope.")) { + continue; + } + do { index = ctor.indexOf('.', index + 1); String provideKey = index == -1 ? ctor : ctor.substring(0, index); diff --git a/test/com/google/javascript/jscomp/CheckProvidesTest.java b/test/com/google/javascript/jscomp/CheckProvidesTest.java index <HASH>..<HASH> 100644 --- a/test/com/google/javascript/jscomp/CheckProvidesTest.java +++ b/test/com/google/javascript/jscomp/CheckProvidesTest.java @@ -62,6 +62,12 @@ public class CheckProvidesTest extends CompilerTestCase { test(js, js, null, MISSING_PROVIDE_WARNING, warning); } + public void testMissingGoogProvideWithinGoogScope(){ + String[] js = new String[]{ + "/** @constructor */ $jscomp.scope.bar = function() {};"}; + test(js, js); + } + public void testGoogProvideInWrongFileShouldCreateWarning(){ String bad = "/** @constructor */ X = function(){};"; String good = "goog.provide('X'); goog.provide('Y');" +
Don't require that local type definitions within a goog.module/goog.scope be provided. ------------- Created by MOE: <URL>
google_closure-compiler
train
c6865ded3e285a0257c2b367e3901b45d17b38a1
diff --git a/test_duct.py b/test_duct.py index <HASH>..<HASH> 100644 --- a/test_duct.py +++ b/test_duct.py @@ -117,9 +117,9 @@ def test_nonzero_status_throws(): def test_ignore(): - assert 0 == false.ignore().run().returncode + assert 0 == false().ignore().run().status with raises(StatusError) as e: - false.run() + false().run() assert e.value.result.status @@ -147,7 +147,7 @@ def test_pipe_SIGPIPE(): def test_then(): print_a = cmd('python', '-c', 'print("A")') assert 'A' == true().then(print_a).read() - assert '' == false().then(print_a).read(check=False) + assert '' == false().then(print_a).ignore().read() def test_nesting():
[rusty rewrite] tests pass!!!
oconnor663_duct.py
train
e7cb9daeac2bb59e5d2c13c64ca6766bf9ac6f5c
diff --git a/db.js b/db.js index <HASH>..<HASH> 100644 --- a/db.js +++ b/db.js @@ -39,9 +39,20 @@ module.exports = function (name, cb) { //don't give each database the same hash, //that will reveal that they are on the same server to attackers. var id = shasum(udid + name) - LevelScuttlebutt(db, id, schema) + //just a simple count of all items. + db.scuttlebutt.addMapReduce({ + name: 'all', + map: function (key, model, emit) { + emit(model.name, 1) + }, + reduce: function (acc, item) { + return Number(acc) + Number(item) + }, + initial: 0 + }) + dbs[name] = db whenReady(dbs[name], cb)
until we can run custom queries, just include a default query
dominictarr_rumours
train
804334d63e36f88b5340aa8faac2d0db5adf5acf
diff --git a/src/plugin/regions.js b/src/plugin/regions.js index <HASH>..<HASH> 100644 --- a/src/plugin/regions.js +++ b/src/plugin/regions.js @@ -153,7 +153,7 @@ class Region { this.style(handleLeft, css); this.style(handleRight, css); this.style(handleRight, { - left: '100%' + right: '0px' }); }
regions plugin: change region end handler position (#<I>)
katspaugh_wavesurfer.js
train
60c9699b554a61f85ee9faa946e73fb33b761257
diff --git a/luigi/contrib/ssh.py b/luigi/contrib/ssh.py index <HASH>..<HASH> 100644 --- a/luigi/contrib/ssh.py +++ b/luigi/contrib/ssh.py @@ -40,6 +40,7 @@ import contextlib import os import random import subprocess +import posixpath import luigi import luigi.format @@ -173,7 +174,7 @@ class RemoteFileSystem(luigi.target.FileSystem): def put(self, local_path, path): # create parent folder if not exists - normpath = os.path.normpath(path) + normpath = posixpath.normpath(path) folder = os.path.dirname(normpath) if folder and not self.exists(folder): self.remote_context.check_output(['mkdir', '-p', folder])
Fix for #<I>: Normalize remote paths with posixpath On Windows clients, RemoteFileSystem normalizes paths Windows-style. This leads to wrong path names on the remote Linux side. Explicitly using posixpath.normpath instead of os.path.normpath fixes the problem.
spotify_luigi
train
47b4d4d6089b8077e1a92e9a3aa0e1842e75ebba
diff --git a/AegeanTools/wcs_helpers.py b/AegeanTools/wcs_helpers.py index <HASH>..<HASH> 100644 --- a/AegeanTools/wcs_helpers.py +++ b/AegeanTools/wcs_helpers.py @@ -479,7 +479,10 @@ class WCSHelper(object): return None return Beam(psf[0], psf[1], psf[2]) - return Beam(*self.get_psf_sky2sky(ra, dec)) + a, b, pa = self.get_psf_sky2sky(ra, dec) + if not np.all(np.isfinite((a, b, pa))): + return None + return Beam(a, b, pa) def get_beamarea_deg2(self, ra, dec): """
get_skybeam returns None when ra/dec are nan, or when the resulting a/b/pa would be nan.
PaulHancock_Aegean
train
318fdeaca26f0238e8b767f5806690680d353ace
diff --git a/src/Eventually.php b/src/Eventually.php index <HASH>..<HASH> 100644 --- a/src/Eventually.php +++ b/src/Eventually.php @@ -69,7 +69,7 @@ class Eventually extends Monad */ public function bind(callable $codeBlock) { - assert($this->result === null, "'Eventually' instance may not be mutated after being getped."); + assert($this->result === null, "'Eventually' instance may not be mutated after code-block execution."); return static::unit(function ($success) use ($codeBlock) { $this->run(function ($value) use ($codeBlock, $success) {
fixed search&replace typo within Eventually assert
shrink0r_monatic
train
46a5b269edb4d8b50bdf51e848e2887ca8e600f8
diff --git a/Gruntfile.js b/Gruntfile.js index <HASH>..<HASH> 100644 --- a/Gruntfile.js +++ b/Gruntfile.js @@ -114,7 +114,7 @@ module.exports = function(grunt) { ]); // Build examples. - grunt.registerTask('sub', [ + grunt.registerTask('examples', [ 'subgrunt:examples' ]);
renamed to 'examples'
assemble_grunt-assemble
train
82944537e9ab37c8de236f839fce0e30bc1647e9
diff --git a/packages/create-instance/add-slots.js b/packages/create-instance/add-slots.js index <HASH>..<HASH> 100644 --- a/packages/create-instance/add-slots.js +++ b/packages/create-instance/add-slots.js @@ -4,16 +4,6 @@ import { compileToFunctions } from 'vue-template-compiler' import { throwError } from 'shared/util' import { validateSlots } from './validate-slots' -function isSingleElement (slotValue: string): boolean { - const _slotValue = slotValue.trim() - if (_slotValue[0] !== '<' || _slotValue[_slotValue.length - 1] !== '>') { - return false - } - const domParser = new window.DOMParser() - const _document = domParser.parseFromString(slotValue, 'text/html') - return _document.body.childElementCount === 1 -} - // see https://github.com/vuejs/vue-test-utils/pull/274 function createVNodes (vm: Component, slotValue: string) { const compiledResult = compileToFunctions(`<div>${slotValue}{{ }}</div>`) @@ -40,11 +30,7 @@ function addSlotToVm (vm: Component, slotName: string, slotValue: SlotValue): vo let elem if (typeof slotValue === 'string') { validateEnvironment() - if (isSingleElement(slotValue)) { - elem = vm.$createElement(compileToFunctions(slotValue)) - } else { - elem = createVNodes(vm, slotValue) - } + elem = createVNodes(vm, slotValue) } else { elem = vm.$createElement(slotValue) } diff --git a/packages/create-instance/create-instance.js b/packages/create-instance/create-instance.js index <HASH>..<HASH> 100644 --- a/packages/create-instance/create-instance.js +++ b/packages/create-instance/create-instance.js @@ -86,6 +86,9 @@ export default function createInstance ( const vm = new Constructor(instanceOptions) + // Workaround for Vue < 2.5 + vm._staticTrees = [] + addAttrs(vm, options.attrs) addListeners(vm, options.listeners) diff --git a/test/specs/mounting-options/slots.spec.js b/test/specs/mounting-options/slots.spec.js index <HASH>..<HASH> 100644 --- a/test/specs/mounting-options/slots.spec.js +++ b/test/specs/mounting-options/slots.spec.js @@ -36,6 +36,35 @@ describeWithMountingMethods('options.slots', (mountingMethod) => { } }) + itDoNotRunIf( + mountingMethod.name === 'shallowMount' || + isRunningPhantomJS || + process.env.TEST_ENV === 'node', + 'mounts component with default slot if passed component as string in slot object', () => { + const CustomComponent = { + render: h => h('time') + } + const TestComponent = { + template: '<div><slot /></div>', + components: { + 'custom-component': CustomComponent + } + } + const wrapper = mountingMethod(TestComponent, { + slots: { + default: '<custom-component />' + }, + components: { + 'custom-component': CustomComponent + } + }) + if (mountingMethod.name === 'renderToString') { + expect(wrapper).contains('<time>') + } else { + expect(wrapper.contains('time')).to.equal(true) + } + }) + it('mounts component with default slot if passed component in array in slot object', () => { const wrapper = mountingMethod(ComponentWithSlots, { slots: { default: [Component] }}) if (mountingMethod.name === 'renderToString') {
feat: support component slot string (#<I>)
vuejs_vue-test-utils
train
984b6d1a0ae5d1ecf6d718f4e990883d281ba3b8
diff --git a/doc.go b/doc.go index <HASH>..<HASH> 100644 --- a/doc.go +++ b/doc.go @@ -18,22 +18,26 @@ Example: func main () { text := slug.Make("Hellö Wörld хелло ворлд") - fmt.Println(text) // Will print hello-world-khello-vorld + fmt.Println(text) // Will print: "hello-world-khello-vorld" someText := slug.Make("影師") - fmt.Println(someText) // Will print: ying-shi + fmt.Println(someText) // Will print: "ying-shi" enText := slug.MakeLang("This & that", "en") - fmt.Println(enText) // Will print 'this-and-that' + fmt.Println(enText) // Will print: "this-and-that" deText := slug.MakeLang("Diese & Dass", "de") - fmt.Println(deText) // Will print 'diese-und-dass' + fmt.Println(deText) // Will print: "diese-und-dass" + + slug.Lowercase = false // Keep uppercase characters + deUppercaseText := slug.MakeLang("Diese & Dass", "de") + fmt.Println(deUppercaseText) // Will print: "Diese-und-Dass" slug.CustomSub = map[string]string{ "water": "sand", } textSub := slug.Make("water is hot") - fmt.Println(textSub) // Will print 'sand-is-hot' + fmt.Println(textSub) // Will print: "sand-is-hot" } Requests or bugs?
Update doc.go with new Lowercase variable
gosimple_slug
train
a04b11c261a77c989c53774253c5f6df09c70226
diff --git a/WPEloquent/Model/Term/Taxonomy.php b/WPEloquent/Model/Term/Taxonomy.php index <HASH>..<HASH> 100644 --- a/WPEloquent/Model/Term/Taxonomy.php +++ b/WPEloquent/Model/Term/Taxonomy.php @@ -6,6 +6,6 @@ class Taxonomy extends \Illuminate\Database\Eloquent\Model { protected $table = 'term_taxonomy'; public function term() { - return $this->belongsTo(\WPEloquent\Model\Term::class); + return $this->belongsTo(\WPEloquent\Model\Term::class, 'term_id', 'term_id'); } }
term will be null otherwise - relationship
drewjbartlett_wordpress-eloquent
train
9587398ebe76a07933dde2de14bf9da658393513
diff --git a/src/audio/audio.js b/src/audio/audio.js index <HASH>..<HASH> 100644 --- a/src/audio/audio.js +++ b/src/audio/audio.js @@ -204,7 +204,12 @@ } sound.volume(typeof(volume) === "number" ? volume.clamp(0.0, 1.0) : Howler.volume(), instance_id); if (typeof(onend) === "function") { - sound.once("end", onend, instance_id); + if (loop === true) { + sound.on("end", onend, instance_id); + } + else { + sound.once("end", onend, instance_id); + } } return instance_id; } diff --git a/src/vendors/howler.core.js b/src/vendors/howler.core.js index <HASH>..<HASH> 100755 --- a/src/vendors/howler.core.js +++ b/src/vendors/howler.core.js @@ -440,11 +440,11 @@ var seek = sound._seek > 0 ? sound._seek : self._sprite[sprite][0] / 1000; var duration = ((self._sprite[sprite][0] + self._sprite[sprite][1]) / 1000) - seek; - // Should this sound loop? - var loop = !!(sound._loop || self._sprite[sprite][2]); - // Create a timer to fire at the end of playback or the start of a new loop. var ended = function() { + // Should this sound loop? + var loop = !!(sound._loop || self._sprite[sprite][2]); + // Fire the ended event. self._emit('end', sound._id); @@ -486,7 +486,7 @@ sound._seek = seek; sound._start = self._sprite[sprite][0] / 1000; sound._stop = (self._sprite[sprite][0] + self._sprite[sprite][1]) / 1000; - sound._loop = loop; + sound._loop = !!(sound._loop || self._sprite[sprite][2]); // Begin the actual playback. var node = sound._node; @@ -921,6 +921,9 @@ if (sound) { sound._loop = loop; + if (self._webAudio && sound._node) { + sound._node.bufferSource.loop = loop; + } } }
Fix regression in audio looping - This is actually a bug in Howler: <URL>
melonjs_melonJS
train
a7dda94e234a9a63e6cb1c339ff441d33b6a0c2c
diff --git a/packages/components/bolt-pagination/__tests__/pagination.js b/packages/components/bolt-pagination/__tests__/pagination.js index <HASH>..<HASH> 100644 --- a/packages/components/bolt-pagination/__tests__/pagination.js +++ b/packages/components/bolt-pagination/__tests__/pagination.js @@ -6,9 +6,7 @@ import { const { readYamlFileSync } = require('@bolt/build-tools/utils/yaml'); const { join } = require('path'); const schema = readYamlFileSync(join(__dirname, '../pagination.schema.yml')); -const { - align -} = schema.properties; +const { align } = schema.properties; async function renderTwig(template, data) { return await render(template, data, true); @@ -27,39 +25,42 @@ describe('<bolt-pagination> Component', async () => { // Basic Usage test('Basic usage', async () => { - const results = await renderTwig('@bolt-components-pagination/pagination.twig', { - current: 5, - total: 10, - first: { - href: '#!' - }, - previous: { - href: '#!' - }, - pages: { - 3: { - href: '#!' + const results = await renderTwig( + '@bolt-components-pagination/pagination.twig', + { + current: 5, + total: 10, + first: { + href: '#!', + }, + previous: { + href: '#!', }, - 4: { - href: '#!' + pages: { + 3: { + href: '#!', + }, + 4: { + href: '#!', + }, + 5: { + href: '#!', + }, + 6: { + href: '#!', + }, + 7: { + href: '#!', + }, }, - 5: { - href: '#!' + next: { + href: '#!', }, - 6: { - href: '#!' + last: { + href: '#!', }, - 7: { - href: '#!' - } - }, - next: { - href: '#!' }, - last: { - href: '#!' - } - }); + ); expect(results.ok).toBe(true); expect(results.html).toMatchSnapshot(); }); @@ -67,34 +68,37 @@ describe('<bolt-pagination> Component', async () => { // Props align.enum.forEach(async alignChoice => { test(`Horizontal alignment: ${alignChoice}`, async () => { - const results = await renderTwig('@bolt-components-pagination/pagination.twig', { - align: alignChoice, - current: 1, - total: 5, - pages: { - 1: { - href: '#!' - }, - 2: { - href: '#!' + const results = await renderTwig( + '@bolt-components-pagination/pagination.twig', + { + align: alignChoice, + current: 1, + total: 5, + pages: { + 1: { + href: '#!', + }, + 2: { + href: '#!', + }, + 3: { + href: '#!', + }, + 4: { + href: '#!', + }, + 5: { + href: '#!', + }, }, - 3: { - href: '#!' + next: { + href: '#!', }, - 4: { - href: '#!' + last: { + href: '#!', }, - 5: { - href: '#!' - } }, - next: { - href: '#!' - }, - last: { - href: '#!' - } - }); + ); expect(results.ok).toBe(true); expect(results.html).toMatchSnapshot(); });
fix: lint js
bolt-design-system_bolt
train
8e6c0a54899e7cf56a9b3112f4a9eff84523eedc
diff --git a/src/MaxMind/MinFraud.php b/src/MaxMind/MinFraud.php index <HASH>..<HASH> 100644 --- a/src/MaxMind/MinFraud.php +++ b/src/MaxMind/MinFraud.php @@ -352,8 +352,7 @@ class MinFraud } catch (ValidationExceptionInterface $exception) { throw new InvalidInputException( $exception->getMessage(), - $exception->getCode(), - $exception + $exception->getCode() ); } }
Don't pass previous exception as it leaks too many implementation details
maxmind_minfraud-api-php
train
eac321899b7a5e552d62f08e49894eb254a3b8f2
diff --git a/client/request.go b/client/request.go index <HASH>..<HASH> 100644 --- a/client/request.go +++ b/client/request.go @@ -62,7 +62,7 @@ type request struct { header http.Header query url.Values formFields url.Values - fileFields map[string]*os.File + fileFields map[string]runtime.NamedReadCloser payload interface{} timeout time.Duration } @@ -236,17 +236,19 @@ func (r *request) SetPathParam(name string, value string) error { } // SetFileParam adds a file param to the request -func (r *request) SetFileParam(name string, file *os.File) error { - fi, err := os.Stat(file.Name()) - if err != nil { - return err - } - if fi.IsDir() { - return fmt.Errorf("%q is a directory, only files are supported", file.Name()) +func (r *request) SetFileParam(name string, file runtime.NamedReadCloser) error { + if actualFile, ok := file.(*os.File); ok { + fi, err := os.Stat(actualFile.Name()) + if err != nil { + return err + } + if fi.IsDir() { + return fmt.Errorf("%q is a directory, only files are supported", file.Name()) + } } if r.fileFields == nil { - r.fileFields = make(map[string]*os.File) + r.fileFields = make(map[string]runtime.NamedReadCloser) } if r.formFields == nil { r.formFields = make(url.Values) diff --git a/client_request.go b/client_request.go index <HASH>..<HASH> 100644 --- a/client_request.go +++ b/client_request.go @@ -15,7 +15,7 @@ package runtime import ( - "os" + "io" "time" "github.com/go-openapi/strfmt" @@ -45,9 +45,15 @@ type ClientRequest interface { SetPathParam(string, string) error - SetFileParam(string, *os.File) error + SetFileParam(string, NamedReadCloser) error SetBodyParam(interface{}) error SetTimeout(time.Duration) error } + +// NamedReadCloser represents a named ReadCloser interface +type NamedReadCloser interface { + io.ReadCloser + Name() string +} diff --git a/client_request_test.go b/client_request_test.go index <HASH>..<HASH> 100644 --- a/client_request_test.go +++ b/client_request_test.go @@ -16,7 +16,6 @@ package runtime import ( "net/http" - "os" "testing" "time" @@ -43,7 +42,7 @@ func (t *trw) SetFormParam(_ string, _ ...string) error { return nil } func (t *trw) SetPathParam(_ string, _ string) error { return nil } -func (t *trw) SetFileParam(_ string, _ *os.File) error { return nil } +func (t *trw) SetFileParam(_ string, _ NamedReadCloser) error { return nil } func (t *trw) SetBodyParam(body interface{}) error { t.Body = body
replace request's os.File with NamedReadCloser
go-openapi_runtime
train
2991aa809e4e5d32825aa5cf21097e5e8fa501f6
diff --git a/mp3-parser.js b/mp3-parser.js index <HASH>..<HASH> 100644 --- a/mp3-parser.js +++ b/mp3-parser.js @@ -154,21 +154,35 @@ // UCS-2 version of `readStr`. UCS-2 is the fixed-width two-byte subset of // Unicode that can only express values inside the 'Basic Multilingual Plane' (BMP). Note - // that this method is generally unsuitable for parsing non-trivial UTF-16 strings. This - // of course is only marginally related as, according to ID3v2, all Unicode strings are - // UCS-2. Further info: + // that this method is generally unsuitable for parsing non-trivial UTF-16 strings + // (containing surrogate pairs). [This is only marginally related as, according to ID3v2, + // all Unicode strings are UCS-2.] Further info: // // * [How to convert ArrayBuffer to and from String](http://updates.html5rocks.com/2012/06/How-to-convert-ArrayBuffer-to-and-from-String) // * [The encoding spec](http://encoding.spec.whatwg.org/) // * [stringencoding shim](https://code.google.com/p/stringencoding/) + // + // About the BOM: The current implementation removes the leading BOM from given buffer to + // avoid invisible characters that mess up the resulting strings. Tests performed with + // UCS-2 LE encoded frames indicate that String.fromCharCode correctly converts byte array + // to string but no tests have been made for UCS-2 BE. (Kid3, the ID3v2 Tag generator used + // at the time of this writing, goes totally weird when switched to BE) readStrUcs2 = function (buffer, offset, length) { + // Tweak offset to remove the BOM (LE: FF FE / BE: FE FF) + if (buffer.getUint16(offset) === 0xFFFE || buffer.getUint16(offset) === 0xFEFF) { + offset += 2; + length -= 2; + } + buffer = buffer.buffer; + // When offset happens to be an even number of octets, the array-buffer may be wrapped // in a Uint16Array. In the event that it's _not_, an actual copy has to be made if (offset % 2 === 1) { buffer = buffer.slice(offset, offset + length); offset = 0; } + return String.fromCharCode.apply(null, new Uint16Array(buffer, offset, length / 2)); },
Remove BOM when parsing UCS-2 encoded strings
biril_mp3-parser
train
001685d8bc8037b28c2065d9973c8005d2e99b55
diff --git a/src/php/main/Nohex/Eix/Core/Application.php b/src/php/main/Nohex/Eix/Core/Application.php index <HASH>..<HASH> 100755 --- a/src/php/main/Nohex/Eix/Core/Application.php +++ b/src/php/main/Nohex/Eix/Core/Application.php @@ -51,8 +51,10 @@ abstract class Application Logger::get()->debug('Starting Eix application...'); // Divert PHP errors to custom handlers. - set_error_handler(array($this, 'handleError')); - set_exception_handler(array($this, 'handleException')); + if (@$settings->application->rawErrors !== 'on') { + set_error_handler(array($this, 'handleError')); + set_exception_handler(array($this, 'handleException')); + } try { // Load the application's settings. @@ -163,7 +165,7 @@ abstract class Application * This function should be overridden in descendant classes to provide * application-wide response alterations. */ - protected function alterResponse(Response &$response) + public function alterResponse(Response &$response) { // Do nothing. } diff --git a/src/php/test/Nohex/Eix/Core/ApplicationTest.php b/src/php/test/Nohex/Eix/Core/ApplicationTest.php index <HASH>..<HASH> 100755 --- a/src/php/test/Nohex/Eix/Core/ApplicationTest.php +++ b/src/php/test/Nohex/Eix/Core/ApplicationTest.php @@ -19,4 +19,22 @@ class ApplicationTest extends \PHPUnit_Framework_TestCase $this->assertSame($applicationA, $applicationB); } + + public function testRawErrorsOn() { + $settings = new MockSettings; + $settings->application->rawErrors = 'off'; + $application = new Application($settings); + } + + public function testRawErrorsOff() { + $settings = new MockSettings; + $settings->application->rawErrors = 'off'; + $application = new Application($settings); + } + + public function testNoRawErrors() { + $settings = new MockSettings; + unset($settings->application->rawErrors); + $application = new Application($settings); + } }
Application error handler can now be disabled.
eix_core
train
00ef12f3cca765dce5bc9612e7ef7db5f93d96bb
diff --git a/h2o-algos/src/test/java/hex/tree/drf/DRFTest.java b/h2o-algos/src/test/java/hex/tree/drf/DRFTest.java index <HASH>..<HASH> 100755 --- a/h2o-algos/src/test/java/hex/tree/drf/DRFTest.java +++ b/h2o-algos/src/test/java/hex/tree/drf/DRFTest.java @@ -877,6 +877,7 @@ public class DRFTest extends TestUtil { } } + @Ignore @Test public void testNFold() { Frame tfr = null, vfr = null; @@ -908,7 +909,8 @@ public class DRFTest extends TestUtil { drf = job.trainModel().get(); ModelMetricsBinomial mm = (ModelMetricsBinomial)drf._output._validation_metrics; - assertEquals(0.7252305790568023, mm.auc()._auc, 1e-8); + assertEquals(0.7252305790568023, mm.auc()._auc, 1e-8); // 1 node + assertEquals(0.7330846346541204, mm.auc()._auc, 1e-8); // 5 nodes assertEquals(0.21258514360090627, mm.mse(), 1e-8); assertEquals(0.14751832396119646, mm.r2(), 1e-6); assertEquals(0.6133063511996262, mm.logloss(), 1e-6);
PUBDEV-<I>: Ignore DRF N-fold CV Junit for now as results differ between 1 and 5 nodes.
h2oai_h2o-3
train
9808c0732c97b26c56145e7d9b03e415f5b9b1fd
diff --git a/spec/example_app/app/dashboards/customer_dashboard.rb b/spec/example_app/app/dashboards/customer_dashboard.rb index <HASH>..<HASH> 100644 --- a/spec/example_app/app/dashboards/customer_dashboard.rb +++ b/spec/example_app/app/dashboards/customer_dashboard.rb @@ -7,7 +7,7 @@ class CustomerDashboard < Administrate::BaseDashboard email_subscriber: Field::Boolean, lifetime_value: Field::Number.with_options(prefix: "$", decimals: 2), name: Field::String, - orders: Field::HasMany.with_options(limit: 2), + orders: Field::HasMany.with_options(limit: 2, sort_by: :id), updated_at: Field::DateTime, kind: Field::Select.with_options(collection: Customer::KINDS), country: Field::BelongsTo.with_options( diff --git a/spec/features/show_page_spec.rb b/spec/features/show_page_spec.rb index <HASH>..<HASH> 100644 --- a/spec/features/show_page_spec.rb +++ b/spec/features/show_page_spec.rb @@ -1,7 +1,7 @@ require "rails_helper" RSpec.describe "customer show page" do - describe "displays the customers orders paginated" do + describe "paginates customers' orders" do it "displays the first page by default, other pages when specified" do customer = create(:customer) orders = create_list(:order, 4, customer: customer)
Ensure persistent order in pagination spec (#<I>) * Improve the `it` description. * Order the results before referring to them.
thoughtbot_administrate
train
b74281ddd7594c52c12ae46d1fbf4e12fad22a06
diff --git a/extensions/dna-connector-svn/src/main/java/org/jboss/dna/connector/svn/SVNRepositoryRequestProcessor.java b/extensions/dna-connector-svn/src/main/java/org/jboss/dna/connector/svn/SVNRepositoryRequestProcessor.java index <HASH>..<HASH> 100644 --- a/extensions/dna-connector-svn/src/main/java/org/jboss/dna/connector/svn/SVNRepositoryRequestProcessor.java +++ b/extensions/dna-connector-svn/src/main/java/org/jboss/dna/connector/svn/SVNRepositoryRequestProcessor.java @@ -227,7 +227,7 @@ public class SVNRepositoryRequestProcessor extends RequestProcessor { SVNDirEntry entry = getEntryInfo(parent.getString(getExecutionContext().getNamespaceRegistry())); Date lastModified = entry.getDate(); if (lastModified != null) { - Property jcrLastModifiedProperty = propertyFactory().create(JcrLexicon.LAST_MODIFIED, lastModified.toString()); + Property jcrLastModifiedProperty = propertyFactory().create(JcrLexicon.LAST_MODIFIED, dateFactory().create(lastModified)); properties.add(jcrLastModifiedProperty); } if (os.toByteArray().length > 0) {
a small impl. for the read all children and read all properties request processing git-svn-id: <URL>
ModeShape_modeshape
train
d33c67ec37edc3933048d8b0e2b3eff4e5fda330
diff --git a/CHANGES.md b/CHANGES.md index <HASH>..<HASH> 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -3,6 +3,11 @@ OSRFramework Changelog For more information, check the README.md in <http://github.com/i3visio/osrframework>. For the ToDo list and the known issues, scroll down till the end of this file. +0.12.1, 2016/07/07 -- Fixed issues in Favstar and mailfy.py. +- Fixed issue #145. Favstar platform returns false positives in usufy when looking for long usernames. +- Fixed issue #144. mailfy.py returns error with specific domains. The error seemed to be a problem when no mail was loaded. +- Fixed issue #130. Removing obsolete warning of not properly working in Windows mailfy. + 0.12.0, 2016/06/12 -- Fixed issues in 8 platforms when making use of usernames with a ".". URL can be automatically opened in the current web browser. Added 3 new mailfy platforms. - Important change in the way of validating the nicknames. Valid expressions are matched now as ".+". - Addressed issue #129: Open found URL in the current webbrowser. diff --git a/README.md b/README.md index <HASH>..<HASH> 100644 --- a/README.md +++ b/README.md @@ -84,5 +84,6 @@ If you want to extend the functionalities of OSRFramework and you do not know wh More details about the authors in the [AUTHORS.md](AUTHORS.md) file. Bitcoin Address: [3JJJZU5UvdN2AQrUAeiPM6i7JfRBZNPLhS](bitcoin:1FEdwYGDiuKRfuVCu9reUVS5t6ViGsFJLP?amount=0.01000000&label=3JJJZU5UvdN2AQrUAeiPM6i7JfRBZNPLhS&message=Donate%20Bitcoin%20to%20OSRFramework%20Project) + ![Bitcoin donations to OSRFramework](http://i3visio.com/OSRFramework-donations.png "Donate Bitcoin to OSRFramework developers.") diff --git a/osrframework/__init__.py b/osrframework/__init__.py index <HASH>..<HASH> 100644 --- a/osrframework/__init__.py +++ b/osrframework/__init__.py @@ -23,4 +23,4 @@ import osrframework.utils.logger # Calling the logger when being imported osrframework.utils.logger.setupLogger(loggerName="osrframework") -__version__="0.12.0" +__version__="0.12.1b" diff --git a/osrframework/mailfy.py b/osrframework/mailfy.py index <HASH>..<HASH> 100644 --- a/osrframework/mailfy.py +++ b/osrframework/mailfy.py @@ -29,7 +29,7 @@ __author__ = "Felix Brezo, Yaiza Rubio " __copyright__ = "Copyright 2016, i3visio" __credits__ = ["Felix Brezo", "Yaiza Rubio"] __license__ = "GPLv3+" -__version__ = "v3.2" +__version__ = "v3.3" __maintainer__ = "Felix Brezo, Yaiza Rubio" __email__ = "contacto@i3visio.com" @@ -228,6 +228,10 @@ def performSearch(emails=[], nThreads=16): for e in emails: if weCanCheckTheseDomains(e): args.append((e)) + + # Returning None if no valid domain has been returned + if len(args) == 0: + return results # If the process is executed by the current app, we use the Processes. It is faster than pools. if nThreads <= 0 or nThreads > len(args): diff --git a/osrframework/wrappers/favstar.py b/osrframework/wrappers/favstar.py index <HASH>..<HASH> 100644 --- a/osrframework/wrappers/favstar.py +++ b/osrframework/wrappers/favstar.py @@ -73,7 +73,7 @@ class Favstar(Platform): self.validQuery = {} # The regular expression '.+' will match any query. #self.validQuery["phonefy"] = re.compile(".*") - self.validQuery["usufy"] = re.compile("[a-zA-Z0-9_]+") + self.validQuery["usufy"] = re.compile("[a-zA-Z0-9_]{1,19}") #self.validQuery["searchfy"] = re.compile(".*") ###################
Fixed issues in Favstar and mailfy.py.
i3visio_osrframework
train
768af0e8acba65677e787d2d4a6e4e9fac01f420
diff --git a/test/cli/run-options.test.js b/test/cli/run-options.test.js index <HASH>..<HASH> 100644 --- a/test/cli/run-options.test.js +++ b/test/cli/run-options.test.js @@ -18,4 +18,11 @@ describe('CLI run options', function () { done(); }); }); + + it('should fail a collection run with undefined test cases', function (done) { + exec('node ./bin/newman.js run test/fixtures/run/undefined-test-checks.json', function (code) { + expect(code).be(1); + done(); + }); + }); });
Added CLI test for undefined collection test cases
postmanlabs_newman
train
38dccf9e1223cc87fcf549ae17e9a34fd4782ba8
diff --git a/superset/utils/decorators.py b/superset/utils/decorators.py index <HASH>..<HASH> 100644 --- a/superset/utils/decorators.py +++ b/superset/utils/decorators.py @@ -51,6 +51,7 @@ def etag_cache( check_perms: Callable[..., Any], get_last_modified: Optional[Callable[..., Any]] = None, skip: Optional[Callable[..., Any]] = None, + must_revalidate: Optional[bool] = False, ) -> Callable[..., Any]: """ A decorator for caching views and handling etag conditional requests. @@ -78,6 +79,8 @@ def etag_cache( return f(*args, **kwargs) response = None + last_modified = get_last_modified and get_last_modified(*args, **kwargs) + if cache: try: # build the cache key from the function arguments and any @@ -94,32 +97,37 @@ def etag_cache( raise logger.exception("Exception possibly due to cache backend.") - # if cache is stale? - if get_last_modified: - content_changed_time = get_last_modified(*args, **kwargs) + # if cache is stale? if ( response + and last_modified and response.last_modified - and response.last_modified.timestamp() - < content_changed_time.timestamp() + and response.last_modified < last_modified ): response = None - else: - # if caller didn't provide content's last_modified time, assume - # its cache won't be stale. - content_changed_time = datetime.utcnow() - # if no response was cached, compute it using the wrapped function if response is None: + # if no response was cached, compute it using the wrapped function response = f(*args, **kwargs) - # add headers for caching: Last Modified, Expires and ETag - response.cache_control.public = True - response.last_modified = content_changed_time + # set expiration headers: + # Last-Modified, Expires, Cache-Control, ETag + response.last_modified = last_modified or datetime.utcnow() expiration = max_age if max_age != 0 else FAR_FUTURE response.expires = response.last_modified + timedelta( seconds=expiration ) + + # when needed, instruct the browser to always revalidate cache + if must_revalidate: + # `Cache-Control: no-cache` asks the browser to always store + # the cache, but also must validate it with the server. + response.cache_control.no_cache = True + else: + # `Cache-Control: Public` asks the browser to always store + # the cache. + response.cache_control.public = True + response.add_etag() # if we have a cache, store the response from the request diff --git a/superset/views/core.py b/superset/views/core.py index <HASH>..<HASH> 100755 --- a/superset/views/core.py +++ b/superset/views/core.py @@ -171,6 +171,13 @@ class Superset(BaseSupersetView): # pylint: disable=too-many-public-methods logger = logging.getLogger(__name__) + def __repr__(self) -> str: + """Determinate string representation of the view instance for etag_cache.""" + return "Superset.views.core.Superset@v{}{}".format( + self.appbuilder.app.config["VERSION_STRING"], + self.appbuilder.app.config["VERSION_SHA"], + ) + @has_access_api @expose("/datasources/") def datasources(self) -> FlaskResponse: @@ -1605,6 +1612,7 @@ class Superset(BaseSupersetView): # pylint: disable=too-many-public-methods skip=lambda _self, dashboard_id_or_slug: not is_feature_enabled( "ENABLE_DASHBOARD_ETAG_HEADER" ), + must_revalidate=True, ) @expose("/dashboard/<dashboard_id_or_slug>/") def dashboard( # pylint: disable=too-many-locals
fix: enable consistent etag across workers and force no-cache for dashboards (#<I>) * fix: enable consistent etag across workers * Use CACHE_DEFAULT_TIMEOUT instead of 0 * Change timeout to 0 and set expires header even for no-cache * Reduce number of if branches to appease Pylint * Fix mypy error
apache_incubator-superset
train
905ff3aee31775e3fff3ebf8a2eaa6bb2cf0f431
diff --git a/lib/puppet/application/interface_base.rb b/lib/puppet/application/interface_base.rb index <HASH>..<HASH> 100644 --- a/lib/puppet/application/interface_base.rb +++ b/lib/puppet/application/interface_base.rb @@ -52,7 +52,12 @@ class Puppet::Application::InterfaceBase < Puppet::Application # Override this if you need custom rendering. def render(result) render_method = Puppet::Network::FormatHandler.format(format).render_method - result.send(render_method) + if render_method == "to_pson" + jj result + exit(0) + else + result.send(render_method) + end end def setup
Pretty-printing json using "jj"
puppetlabs_puppet
train
6ad558bbdb3ed8cbba6536bd754552beda45f880
diff --git a/lib/mongo/server/connection.rb b/lib/mongo/server/connection.rb index <HASH>..<HASH> 100644 --- a/lib/mongo/server/connection.rb +++ b/lib/mongo/server/connection.rb @@ -123,6 +123,14 @@ module Mongo options[:generation] end + # The connection pool from which this connection was created. + # May be nil. + # + # @api private + def connection_pool + options[:connection_pool] + end + # Whether the connection was closed. # # Closed connections should no longer be used. Instead obtain a new @@ -151,7 +159,7 @@ module Mongo def connect! if closed? if Lint.enabled? - raise Error::LintError, "Reconnecting closed connections is no longer supported" + raise Error::LintError, "Reconnecting closed connections is no longer supported (for #{address})" else log_warn("Reconnecting closed connections is deprecated (for #{address})") end @@ -290,7 +298,7 @@ module Mongo def handshake!(socket) unless socket - raise Error::HandshakeError, "Cannot handshake because there is no usable socket" + raise Error::HandshakeError, "Cannot handshake because there is no usable socket (for #{address})" end response = average_rtt = nil diff --git a/lib/mongo/server/connection_pool.rb b/lib/mongo/server/connection_pool.rb index <HASH>..<HASH> 100644 --- a/lib/mongo/server/connection_pool.rb +++ b/lib/mongo/server/connection_pool.rb @@ -357,17 +357,21 @@ module Mongo # @since 2.9.0 def check_in(connection) @lock.synchronize do - unless @checked_out_connections.include?(connection) - raise ArgumentError, "Trying to check in a connection which is not currently checked out by this pool: #{connection}" + unless connection.connection_pool == self + raise ArgumentError, "Trying to check in a connection which was not checked out by this pool: #{connection} checked out from pool #{connection.connection_pool} (for #{self})" end - @checked_out_connections.delete(connection) + unless @checked_out_connections.include?(connection) + raise ArgumentError, "Trying to check in a connection which is not currently checked out by this pool: #{connection} (for #{self})" + end # Note: if an event handler raises, resource will not be signaled. # This means threads waiting for a connection to free up when # the pool is at max size may time out. # Threads that begin waiting after this method completes (with # the exception) should be fine. + + @checked_out_connections.delete(connection) publish_cmap_event( Monitoring::Event::Cmap::ConnectionCheckedIn.new(@server.address, connection.id) ) @@ -629,7 +633,8 @@ module Mongo private def create_connection - Connection.new(@server, options.merge(generation: generation)) + connection = Connection.new(@server, options.merge(generation: generation, + connection_pool: self)) end # Create a connection, connect it, and add it to the pool. diff --git a/spec/mongo/server/connection_pool_spec.rb b/spec/mongo/server/connection_pool_spec.rb index <HASH>..<HASH> 100644 --- a/spec/mongo/server/connection_pool_spec.rb +++ b/spec/mongo/server/connection_pool_spec.rb @@ -369,8 +369,6 @@ describe Mongo::Server::ConnectionPool do end context 'when pool is closed' do - let(:connection) { pool.check_out } - before do connection pool.close @@ -384,6 +382,29 @@ describe Mongo::Server::ConnectionPool do expect(pool.instance_variable_get('@available_connections').length).to eq(0) end end + + context 'when connection is checked in twice' do + it 'raises an ArgumentError and does not change pool state' do + pool.check_in(connection) + expect do + pool.check_in(connection) + end.to raise_error(ArgumentError, /Trying to check in a connection which is not currently checked out by this pool.*/) + expect(pool.size).to eq(1) + expect(pool.check_out).to eq(connection) + end + end + + context 'when connection is checked in to a different pool' do + it 'raises an ArgumentError and does not change the state of either pool' do + pool_other = register_pool(described_class.new(server)) + + expect do + pool_other.check_in(connection) + end.to raise_error(ArgumentError, /Trying to check in a connection which was not checked out by this pool.*/) + expect(pool.size).to eq(1) + expect(pool_other.size).to eq(0) + end + end end describe '#check_out' do diff --git a/spec/mongo/server/connection_spec.rb b/spec/mongo/server/connection_spec.rb index <HASH>..<HASH> 100644 --- a/spec/mongo/server/connection_spec.rb +++ b/spec/mongo/server/connection_spec.rb @@ -561,7 +561,7 @@ describe Mongo::Server::Connection, retry: 3 do expect do connection.dispatch([ query_alice ]).documents - end.to raise_error(Mongo::Error::LintError, 'Reconnecting closed connections is no longer supported') + end.to raise_error(Mongo::Error::LintError, /Reconnecting closed connections is no longer supported.*/) end end
RUBY-<I> Associate connections with pools (#<I>) * maintain pool id in connection to distinguish connections checked out by different pools * add address label to some errors in connection * correctly assert on pool error messages in tests * error when a connection is checked into a pool twice * use register_pool in connection pool spec * update documentation in connection
mongodb_mongo-ruby-driver
train
973e171e0e0f4cb37b32b18aa70404b0fa2f67c3
diff --git a/lib/assets/Css.js b/lib/assets/Css.js index <HASH>..<HASH> 100644 --- a/lib/assets/Css.js +++ b/lib/assets/Css.js @@ -86,7 +86,7 @@ extendWithGettersAndSetters(Css.prototype, { // Emulate postcss' PreviousMap class, but take the source from memory: // CSSOM gets the @charset declaration mixed up with the first selector: var nonInlineAncestor = this.nonInlineAncestor; - var sourceUrl = (nonInlineAncestor && nonInlineAncestor.url) || this.url || 'standalone-' + this.id + '.js'; + var sourceUrl = this.sourceUrl || (nonInlineAncestor && nonInlineAncestor.url) || this.url || 'standalone-' + this.id + '.js'; try { this._parseTree = postcss.parse(this.text, { // TODO: jsdom 6.4.0+ supports jsdom.nodeLocation, which might help us map this diff --git a/lib/transforms/compileLessToCss.js b/lib/transforms/compileLessToCss.js index <HASH>..<HASH> 100644 --- a/lib/transforms/compileLessToCss.js +++ b/lib/transforms/compileLessToCss.js @@ -52,7 +52,11 @@ module.exports = function (queryObj) { sourceMap.sourcesContent = undefined; } } - var cssAsset = new AssetGraph.Css({text: data.result, sourceMap: sourceMap}); + var cssAsset = new AssetGraph.Css({ + text: data.result, + sourceMap: sourceMap, + sourceUrl: asset.url + }); if (asset.url) { cssAsset.url = asset.url.replace( /\.less$|$/,
compileLessToCss: See to it that the .less source url gets passed along.
assetgraph_assetgraph
train
91e8de472b889b1a4a978ba7170a0dc1e1b62559
diff --git a/evm/vm/memory.py b/evm/vm/memory.py index <HASH>..<HASH> 100644 --- a/evm/vm/memory.py +++ b/evm/vm/memory.py @@ -17,7 +17,7 @@ class Memory(object): """ VM Memory """ - _bytes = None # type: bytearray + __slots__ = ['_bytes'] logger = logging.getLogger('evm.vm.memory.Memory') def __init__(self): diff --git a/evm/vm/message.py b/evm/vm/message.py index <HASH>..<HASH> 100644 --- a/evm/vm/message.py +++ b/evm/vm/message.py @@ -17,20 +17,8 @@ class Message(object): """ A message for VM computation. """ - to = None - sender = None - value = None - data = None - gas = None # type: int - depth = None - - code = None - _code_address = None - - create_address = None - - should_transfer_value = None - is_static = None + __slots__ = ['to', 'sender', 'value', 'data', 'depth', 'gas', 'code', '_code_address', + 'create_address', 'should_transfer_value', 'is_static', '_storage_address'] logger = logging.getLogger('evm.vm.message.Message') @@ -47,7 +35,7 @@ class Message(object): should_transfer_value=True, is_static=False): validate_uint256(gas, title="Message.gas") - self.gas = gas + self.gas = gas # type: int if to != CREATE_CONTRACT_ADDRESS: validate_canonical_address(to, title="Message.to") diff --git a/evm/vm/stack.py b/evm/vm/stack.py index <HASH>..<HASH> 100644 --- a/evm/vm/stack.py +++ b/evm/vm/stack.py @@ -19,7 +19,7 @@ class Stack(object): """ VM Stack """ - values = None + __slots__ = ['values'] logger = logging.getLogger('evm.vm.stack.Stack') def __init__(self): diff --git a/evm/vm/state.py b/evm/vm/state.py index <HASH>..<HASH> 100644 --- a/evm/vm/state.py +++ b/evm/vm/state.py @@ -49,8 +49,7 @@ class BaseState(Configurable, metaclass=ABCMeta): # # Set from __init__ # - _db = None - execution_context = None + __slots__ = ['_db', 'execution_context', 'account_db'] computation_class = None # type: Type[BaseComputation] transaction_context_class = None # type: Type[BaseTransactionContext] diff --git a/evm/vm/transaction_context.py b/evm/vm/transaction_context.py index <HASH>..<HASH> 100644 --- a/evm/vm/transaction_context.py +++ b/evm/vm/transaction_context.py @@ -11,9 +11,7 @@ class BaseTransactionContext: This immutable object houses information that remains constant for the entire context of the VM execution. """ - _gas_price = None - _origin = None - _log_counter = None + __slots__ = ['_gas_price', '_origin', '_log_counter'] def __init__(self, gas_price, origin): validate_uint256(gas_price, title="TransactionContext.gas_price")
add __slots__ into classes under the Computation class
ethereum_py-evm
train
225c4e0b39064d536b6ae1d0134d787c57644ef5
diff --git a/lib/proxy.js b/lib/proxy.js index <HASH>..<HASH> 100644 --- a/lib/proxy.js +++ b/lib/proxy.js @@ -353,9 +353,14 @@ function prepareUrl(url){ function getCertData(pathname){ var fs = require('fs'); - // Support input as Buffer, Stream or Pathname. - if(pathname && fs.existsSync(pathname)){ - return fs.readFileSync(pathname, 'utf8') + // TODO: Support input as Buffer, Stream or Pathname. + + if(pathname){ + if(_.isArray(pathname)){ + return _.map(pathname, getCertData); + }else if(fs.existsSync(pathname)){ + return fs.readFileSync(pathname, 'utf8') + } } }
fixed so that it is possible to give an array of credentials per ssl file.
OptimalBits_redbird
train
01a80d619fd42177061787319c6e391ecb367d02
diff --git a/src/pandoc_exporter.js b/src/pandoc_exporter.js index <HASH>..<HASH> 100644 --- a/src/pandoc_exporter.js +++ b/src/pandoc_exporter.js @@ -177,14 +177,14 @@ PandocExporter.Prototype = function() { ]; } - var img = node.getImage(); + var url = node.url; var output = { contents: [ { contents: [ caption, [ - img.url, + url, "fig:" ] ], diff --git a/src/pandoc_importer.js b/src/pandoc_importer.js index <HASH>..<HASH> 100644 --- a/src/pandoc_importer.js +++ b/src/pandoc_importer.js @@ -298,22 +298,14 @@ PandocImporter.Prototype = function() { this.figure = function(state, input) { var doc = state.doc; - var img_id = state.nextId("image"); - var url = input[1][0]; - var img = { - id: img_id, - type: "image", - url: url - }; - doc.create(img); - var caption = this.text(state, input[0]); + var url = input[1][0]; var id = state.nextId("figure"); var node = { id: id, type: "figure", - image: img_id, + url: url, caption: caption.id }; diff --git a/tests/pandoc_importer_test.js b/tests/pandoc_importer_test.js index <HASH>..<HASH> 100644 --- a/tests/pandoc_importer_test.js +++ b/tests/pandoc_importer_test.js @@ -197,7 +197,7 @@ var PandocImporterTest = function () { var doc = this.importer.import(input); var p1 = doc.get("text_1"); - var img = doc.get("image_1"); + var img = doc.get("figure_1"); var caption = doc.get("text_2"); var p2 = doc.get("text_3");
Fix pandoc converter to reflect change in Figure node.
substance_converter
train
8de9d35d8614f01f9dbe095e06475b3560c87978
diff --git a/setup.py b/setup.py index <HASH>..<HASH> 100644 --- a/setup.py +++ b/setup.py @@ -108,7 +108,7 @@ setup( install_requires=["numpy>=1.14.3", "requests", "ruamel.yaml>=0.15.6", "monty>=3.0.2", "scipy>=1.0.1", "pydispatcher>=2.0.5", "tabulate", "spglib>=1.9.9.44", "networkx>=2.2", - "matplotlib>=1.5", "palettable>=3.1.1", "sympy", "pandas"], + "matplotlib>=1.5", "palettable>=3.1.1", "sympy", "pandas<1.0"], extras_require={ "provenance": ["pybtex"], "ase": ["ase>=3.3"],
Trying to fix travis problem with pandas
materialsproject_pymatgen
train
ee9edf8fbbcb0f432f53024571d2ad52df9f6f59
diff --git a/core/src/main/java/hudson/slaves/NodeProvisioner.java b/core/src/main/java/hudson/slaves/NodeProvisioner.java index <HASH>..<HASH> 100644 --- a/core/src/main/java/hudson/slaves/NodeProvisioner.java +++ b/core/src/main/java/hudson/slaves/NodeProvisioner.java @@ -174,9 +174,12 @@ public class NodeProvisioner { lastSuggestedReview = System.currentTimeMillis(); Computer.threadPoolForRemoting.submit(new Runnable() { public void run() { + LOGGER.fine(() -> "running suggested review for " + label); update(); } }); + } else { + LOGGER.fine(() -> "ignoring suggested review for " + label); } } @@ -188,6 +191,7 @@ public class NodeProvisioner { * instance of this provisioner is running at a time) and then a lock on {@link Queue#lock} */ private void update() { + long start = LOGGER.isLoggable(Level.FINER) ? System.nanoTime() : 0; provisioningLock.lock(); try { lastSuggestedReview = System.currentTimeMillis(); @@ -327,6 +331,9 @@ public class NodeProvisioner { } finally { provisioningLock.unlock(); } + if (LOGGER.isLoggable(Level.FINER)) { + LOGGER.finer(() -> "ran update on " + label + " in " + (System.nanoTime() - start) / 1_000_000 + "ms"); + } }
Improved logging for NodeProvisioner.
jenkinsci_jenkins
train
0b1b37366f7128a08dd7e155f68d5dd4af55ad66
diff --git a/publish.py b/publish.py index <HASH>..<HASH> 100755 --- a/publish.py +++ b/publish.py @@ -233,7 +233,7 @@ if __name__ == "__main__": routine(None, 'Please commit your changes, push and wait if Travis tests build successfully. ' 'Only then merge them into the master.', - 'Build successful. Publish and upload now.', 'Exit.') + 'Build successful. try packaging.') # TODO do this automatically, problem are the commit messages (often the same as changelog) # git commit --message @@ -254,7 +254,7 @@ if __name__ == "__main__": # routine("python3 setup.py sdist bdist_wheel upload", 'Uploading the package now.') # deprecated # new twine publishing routine: # https://packaging.python.org/tutorials/packaging-projects/ - routine("python3 setup.py sdist bdist_wheel", 'building the package now.') + routine("python3 setup.py sdist bdist_wheel", 'building the package now.', 'packaging done. try publishing.') path = abspath(join(__file__, pardir, 'dist')) all_archives_this_version = [f for f in os.listdir(path) if isfile(join(path, f)) and version_str in f] @@ -262,7 +262,7 @@ if __name__ == "__main__": command = "twine upload --repository-url https://test.pypi.org/legacy/ " + ' '.join(paths2archives) # upload all archives of this version - routine(virt_env_act_command + command, 'testing if upload works.') + routine(virt_env_act_command + command, 'testing if upload works.', 'publishing test done. start real publishing.') command = "twine upload " + ' '.join(paths2archives) routine(virt_env_act_command + command, 'real upload to PyPI.') diff --git a/setup.py b/setup.py index <HASH>..<HASH> 100755 --- a/setup.py +++ b/setup.py @@ -1,8 +1,4 @@ # -*- coding:utf-8 -*- -from setuptools import setup - -from timezonefinder.global_settings import DATA_FILES_LOCAL - setup( name='timezonefinder', packages=['timezonefinder'], @@ -25,9 +21,10 @@ setup( classifiers=[ 'Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', + 'Intended Audience :: Information Technology', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', - 'Natural Language:: English', + 'Natural Language :: English', 'Programming Language :: Python', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3 :: Only', @@ -45,3 +42,7 @@ setup( # TODO data extras, oceans, test extras_require={'numba': ["numba>=0.48"]}, ) +from setuptools import setup + +from timezonefinder.global_settings import DATA_FILES_LOCAL +
fix classifiers in order to make pypi upload work
MrMinimal64_timezonefinder
train
913e56ac6617daa91bb300b6677c67ec0334217e
diff --git a/lib/cli.js b/lib/cli.js index <HASH>..<HASH> 100644 --- a/lib/cli.js +++ b/lib/cli.js @@ -1,8 +1,6 @@ var fs = require('fs') var program = require('commander') -var RSVP = require('rsvp') var copyDereferenceSync = require('copy-dereference').sync -var ncp = require('ncp') var broccoli = require('./index')
Clean up stray require calls; thanks JSHint
broccolijs_broccoli
train
e564b27414fea93dbdb6216601249a2246069183
diff --git a/libs/verysimple/Phreeze/GenericRouter.php b/libs/verysimple/Phreeze/GenericRouter.php index <HASH>..<HASH> 100644 --- a/libs/verysimple/Phreeze/GenericRouter.php +++ b/libs/verysimple/Phreeze/GenericRouter.php @@ -151,10 +151,10 @@ class GenericRouter implements IRouter /** * @inheritdocs */ - public function GetUrl( $controller, $method, $params = '' ) + public function GetUrl( $controller, $method, $params = '', $requestMethod = "" ) { $found = false; - $requestMethod = RequestUtil::GetMethod(); + // $requestMethod = RequestUtil::GetMethod(); if ($params == '') $params = array(); @@ -174,7 +174,8 @@ class GenericRouter implements IRouter $keyRequestMethodArr = explode(":",$key,2); $keyRequestMethod = $keyRequestMethodArr[0]; - if( ($routeController == $controller) && ($routeMethod == $method) && ($keyRequestMethod == $requestMethod) && + // echo "$routeController:$controller $routeMethod:$method $keyRequestMethod:$requestMethod)<br/>"; + if( ($routeController == $controller) && ($routeMethod == $method) && ($requestMethod == "" || ($keyRequestMethod == $requestMethod)) && (! array_key_exists("params",$value) || count($params) == count($value["params"]) ) ) { @@ -209,7 +210,7 @@ class GenericRouter implements IRouter // we stripped this at the beginning, need to add it back if( ! $found ) // $url = $url . "/"; - throw new Exception("404 - Page Not Found"); + throw new Exception("Unknown route specified."); return $url; }
Fixed router to use the correct request method
jasonhinkle_phreeze
train
784e1f3b7ee00b37591b34e9524e65620c90a9bc
diff --git a/lib/wool/advice/comment_advice.rb b/lib/wool/advice/comment_advice.rb index <HASH>..<HASH> 100644 --- a/lib/wool/advice/comment_advice.rb +++ b/lib/wool/advice/comment_advice.rb @@ -29,8 +29,7 @@ module Wool # with the implications of comments in their source can safely # discard them. Uses Ripper to look for comment tokens. def comment_removing_twiddler(body = self.body, context = nil, settings = {}) - body = split_on_token(body, :on_comment).first - [body, context, settings] + [split_on_token(body, :on_comment).first.rstrip, context, settings] end end end diff --git a/lib/wool/lexical_analysis.rb b/lib/wool/lexical_analysis.rb index <HASH>..<HASH> 100644 --- a/lib/wool/lexical_analysis.rb +++ b/lib/wool/lexical_analysis.rb @@ -53,7 +53,7 @@ module Wool def split_on_token(body, *tokens) comment_token = find_token(body, *tokens) - max = comment_token ? [0, comment_token[0][1] - 1].max : body.size + max = comment_token ? [0, comment_token[0][1]].max : body.size return body[0,max], body[max..-1] end end diff --git a/lib/wool/warnings/line_length.rb b/lib/wool/warnings/line_length.rb index <HASH>..<HASH> 100644 --- a/lib/wool/warnings/line_length.rb +++ b/lib/wool/warnings/line_length.rb @@ -48,7 +48,7 @@ class Wool::GenericLineLengthWarning < Wool::LineWarning end def handle_long_comments(line) - code, comment = split_on_char_outside_literal(line, /#/) + code, comment = split_on_token(line, :on_comment) return nil if comment.empty? indent, code = code.match(/^(\s*)(.*)$/)[1..2] hashes, comment = comment.match(/^(#+\s*)(.*)$/)[1..2]
Refactoring to get rid of old "split_on_char_outside_literal" method.
michaeledgar_laser
train
1dd519d292ba924439d5f15f362124cb598adccb
diff --git a/aws/resource_aws_backup_region_settings_test.go b/aws/resource_aws_backup_region_settings_test.go index <HASH>..<HASH> 100644 --- a/aws/resource_aws_backup_region_settings_test.go +++ b/aws/resource_aws_backup_region_settings_test.go @@ -4,6 +4,7 @@ import ( "testing" "github.com/aws/aws-sdk-go/service/backup" + "github.com/aws/aws-sdk-go/service/fsx" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" "github.com/hashicorp/terraform-plugin-sdk/v2/terraform"
Update aws/resource_aws_backup_region_settings_test.go
terraform-providers_terraform-provider-aws
train
bc55e4fc9dd0a5381da2c487de943dbe303e8430
diff --git a/lib/nestful/request.rb b/lib/nestful/request.rb index <HASH>..<HASH> 100644 --- a/lib/nestful/request.rb +++ b/lib/nestful/request.rb @@ -112,7 +112,7 @@ module Nestful def callback(type, *args) procs = self.class.callbacks(type) + callbacks(type) - procs.each {|c| c.call(*args) } + procs.compact.each {|c| c.call(*args) } end end
make sure we do not try and execute nils
maccman_nestful
train
9c6dd8b7cb2f1265cd7c9bbf3722ce554514d228
diff --git a/news-bundle/contao/News.php b/news-bundle/contao/News.php index <HASH>..<HASH> 100644 --- a/news-bundle/contao/News.php +++ b/news-bundle/contao/News.php @@ -135,7 +135,7 @@ class News extends \Frontend } // Parse the items - if ($objArticle === null) + if ($objArticle !== null) { $arrUrls = array(); @@ -151,7 +151,7 @@ class News extends \Frontend } $strUrl = $arrUrls[$jumpTo]; - $objItem = new FeedItem(); + $objItem = new \FeedItem(); $objItem->title = $objArticle->headline; $objItem->link = (($objArticle->source == 'external') ? '' : $strLink) . $this->getLink($objArticle, $strUrl); @@ -191,7 +191,7 @@ class News extends \Frontend } // Create the file - $objRss = new File('share/' . $strFile . '.xml'); + $objRss = new \File('share/' . $strFile . '.xml'); $objRss->write($this->replaceInsertTags($objFeed->$strType())); $objRss->close(); }
[News] Fixed the issue with news feeds being empty (see #<I>)
contao_contao
train
d55def28016ecb7ec834ca152a254fb35700193e
diff --git a/bingo/image.py b/bingo/image.py index <HASH>..<HASH> 100644 --- a/bingo/image.py +++ b/bingo/image.py @@ -66,7 +66,7 @@ def get_texts(bingo_fields, font): if bingo_field.is_middle(): text += _("\n{time}\nBingo #{board_id}").format( time=bingo_field.board.get_created(), - board_id=bingo_field.board.id) + board_id=bingo_field.board.board_id) texts.append(Text(draw, font, text)) return texts
fix: show the correct board_id on the images. The correct id is board.board_id and not board.id, as "id" is the internal id assigned by django, and "board_id" is the board number on the current site.
allo-_django-bingo
train
f1324a9fc13e9276c796053ac50b19d10677df74
diff --git a/libcontainer/console_linux.go b/libcontainer/console_linux.go index <HASH>..<HASH> 100644 --- a/libcontainer/console_linux.go +++ b/libcontainer/console_linux.go @@ -5,8 +5,6 @@ import ( "os" "syscall" "unsafe" - - "github.com/opencontainers/runc/libcontainer/label" ) // newConsole returns an initialized console that can be used within a container by copying bytes @@ -63,12 +61,9 @@ func (c *linuxConsole) Close() error { // mount initializes the console inside the rootfs mounting with the specified mount label // and applying the correct ownership of the console. -func (c *linuxConsole) mount(mountLabel string) error { +func (c *linuxConsole) mount() error { oldMask := syscall.Umask(0000) defer syscall.Umask(oldMask) - if err := label.SetFileLabel(c.slavePath, mountLabel); err != nil { - return err - } f, err := os.Create("/dev/console") if err != nil && !os.IsExist(err) { return err diff --git a/libcontainer/init_linux.go b/libcontainer/init_linux.go index <HASH>..<HASH> 100644 --- a/libcontainer/init_linux.go +++ b/libcontainer/init_linux.go @@ -178,7 +178,7 @@ func setupConsole(pipe *os.File, config *initConfig, mount bool) error { // Mount the console inside our rootfs. if mount { - if err := linuxConsole.mount(config.ProcessLabel); err != nil { + if err := linuxConsole.mount(); err != nil { return err } }
Don't label the console as it already has the right label [@cyphar: removed mountLabel argument from .mount().]
opencontainers_runc
train
d11a9314bd003715ae3df7907406f586a6bf75d3
diff --git a/app/helpers/matestack/ui/core/application_helper.rb b/app/helpers/matestack/ui/core/application_helper.rb index <HASH>..<HASH> 100644 --- a/app/helpers/matestack/ui/core/application_helper.rb +++ b/app/helpers/matestack/ui/core/application_helper.rb @@ -14,12 +14,12 @@ module Matestack def render(*args) if (matestack_class = args.first).is_a?(Class) && (matestack_class < Matestack::Ui::Page) options_hash = args[1].is_a?(Hash) ? args[1] : {} - Rendering::MainRenderer.render(self, matestack_class, options_hash, params) + Rendering::MainRenderer.render(self, matestack_class, options_hash) elsif (options = args.first).is_a?(Hash) && (matestack_arg = options[:matestack]) && matestack_arg.is_a?(Class) && (matestack_arg < Matestack::Ui::Page) - Rendering::MainRenderer.render(self, matestack_arg, options, params) + Rendering::MainRenderer.render(self, matestack_arg, options) else super end diff --git a/app/lib/matestack/ui/core/rendering/main_renderer.rb b/app/lib/matestack/ui/core/rendering/main_renderer.rb index <HASH>..<HASH> 100644 --- a/app/lib/matestack/ui/core/rendering/main_renderer.rb +++ b/app/lib/matestack/ui/core/rendering/main_renderer.rb @@ -2,81 +2,34 @@ module Matestack::Ui::Core::Rendering::MainRenderer module_function - # Instead of rendering without an app class, we always have an "empty" app class - # to fall back to - DEFAULT_APP_CLASS = Matestack::Ui::Core::App::App - - def render(controller_instance, page_class, options, params) + def render(controller_instance, page_class, options) app_class = get_app_class(page_class) - # controller related data - view_context = controller_instance.view_context params = controller_instance.params - request = controller_instance.request + # My initial thinking was to have different renderer classes for these, but with rendering this easy + # they're probably not needed if params[:only_page] page_instance = page_class.new(controller_instance: controller_instance) page_instance.prepare page_instance.response controller_instance.render html: page_instance.show + # TODO: elsif looking for new component/async/isolate or what not calls goes here + # and then has to look for the component class based on the given names + # CAREFUL/SECURITY: Make sure not just every object can be instantiated ("common" attack vector) + # specifically we might have to think about the scenario again where maybe a page includes + # admin only content - a normal user shouldn't be able to just send it the AdminOnlyComponent with + # some data and get a result back --> we probably need to give isolated components access to controller + # instance variables or controller context as well (so that the component can check current_user or similar of the controller/request) else app_instance = app_class.new(page_class, controller_instance) controller_instance.render html: app_instance.show, layout: true end end - def other_render_stuff - unless params[:component_key].blank? - # TODO: why is this plain and not html? - controller_instance.render plain: render_component(page_class, params[:component_key]) - return - end - if params[:only_page] - controller_instance.render html: render_page(controller_instance, page_class, true) - else - controller_instance.render html: render_page(controller_instance, page_class), layout: true - end - - # render mode dispatch extracted from Page, actual dispatch should happen here now - - # TODO this is likely broken if someone named a component Isolate or name space - return resolve_isolated_component(component_key) if !component_key.nil? && component_key.include?("isolate") - render_mode = nil - render_mode = :only_page if only_page == true - render_mode = :render_page_with_app if !@app_class.nil? && only_page == false - render_mode = :only_page if @app_class.nil? && only_page == false - render_mode = :render_component if !component_key.nil? - - case render_mode - - when :only_page - render :page - when :render_page_with_app - concept(@app_class).call(:show, @page_id, @nodes) - when :render_component - begin - # TODO when is this called and make it good again - render_child_component component_key - rescue => e - raise "Component '#{component_key}' could not be resolved, because of #{e},\n#{e.backtrace.join("\n")}" - end - end - end - - def render_page(controller_instance, page_class, only_page=false) - page_class.new(nil, context: { - params: params, - request: request, - view_context: view_context - }, controller_instance: controller_instance).call(:show, nil, only_page) - end - - def render_component(controller_instance, page_class, component_key) - page_class.new(nil, context: { - params: params, - request: request - }, controller_instance: controller_instance).call(:show, component_key) - end + # Instead of rendering without an app class, we always have an "empty" app class + # to fall back to + DEFAULT_APP_CLASS = Matestack::Ui::Core::App::App # See #382 for how this shall change in the future # TLDR; we should get it more or less explicitly from the controller
Remove unused render code + add security warning for isolate The old code was just still there as an orientation help for rendering, not needed anymore. New code is/should be much more intuitive and already points out where the remaining things should go. Also added a security notice that occurred to me while thinking about the isolate component and ways in which it mgiht break/ be a security vulnerability as letting the front end tell you which (Ruby) class to render is an inherent security risk and we might need to come up with safeguards/other concepts around that.
basemate_matestack-ui-core
train
c806261830251fd0739974b21f1c93e90d96ed62
diff --git a/src/Versioned.php b/src/Versioned.php index <HASH>..<HASH> 100644 --- a/src/Versioned.php +++ b/src/Versioned.php @@ -191,7 +191,7 @@ class Versioned extends DataExtension implements TemplateGlobalProvider, Resetta * * or programatically: * - * Config::inst()->update($this->owner->class, 'versionableExtensions', + * Config::modify()->merge($this->owner->class, 'versionableExtensions', * array('Extension1' => 'suffix1', 'Extension2' => array('suffix2', 'suffix3'))); * * diff --git a/tests/php/VersionedTest.php b/tests/php/VersionedTest.php index <HASH>..<HASH> 100644 --- a/tests/php/VersionedTest.php +++ b/tests/php/VersionedTest.php @@ -1168,7 +1168,7 @@ class VersionedTest extends SapphireTest { Config::inst()->remove(VersionedTest\RelatedWithoutversion::class, 'db', 'Name', 'Varchar'); - Config::inst()->update( + Config::modify()->merge( VersionedTest\RelatedWithoutversion::class, 'db', [
FIX Use merge instead of update for config calls
silverstripe_silverstripe-versioned
train
8a91a0bd375c7c3bc731a62ae94648d5082f0b00
diff --git a/war/src/main/webapp/scripts/hudson-behavior.js b/war/src/main/webapp/scripts/hudson-behavior.js index <HASH>..<HASH> 100644 --- a/war/src/main/webapp/scripts/hudson-behavior.js +++ b/war/src/main/webapp/scripts/hudson-behavior.js @@ -1515,6 +1515,10 @@ function refreshPart(id,url) { window.clearInterval(intervalID); return; } + if (!rsp.responseText) { + console.log("Failed to retrieve response for ID " + id + ", perhaps Jenkins is unavailable"); + return; + } var p = hist.up(); var div = document.createElement('div');
JENKINS-<I> - don't process empty responseText The goal of this function appears to be to replace one content tree with another content tree. If the response is empty, that doesn't result in a content tree, and thus one can't use replaceChild.
jenkinsci_jenkins
train
293847c96f29058705f12de3ecf623378babc7f1
diff --git a/djsld/generator.py b/djsld/generator.py index <HASH>..<HASH> 100644 --- a/djsld/generator.py +++ b/djsld/generator.py @@ -314,10 +314,7 @@ def _as_classification(classification, queryset, field, nclasses, geofield='geom title = '<= %s' % qbin rule = fts.create_rule(title, symbolizer=symbolizer) - shade = float(i) / (q.k - 1.0) * 255 - if i == q.k: - shade = 255 - + shade = (float(q.k - i) / q.k ) * 255 shade = '#%02x%02x%02x' % (shade, shade, shade,) if symbolizer == PointSymbolizer:
Fix grayscale direction bug If the user created SLDs, the grayscale coloring was the reverse of what was expected. SLDs should now indicate higher values with darker shades of gray.
azavea_django-sld
train
20f10ca27bc77ebc43e02b3c77094c217281fd7e
diff --git a/impl/src/main/java/org/jboss/arquillian/persistence/data/dbunit/dataset/excel/ExcelDataSetBuilder.java b/impl/src/main/java/org/jboss/arquillian/persistence/data/dbunit/dataset/excel/ExcelDataSetBuilder.java index <HASH>..<HASH> 100644 --- a/impl/src/main/java/org/jboss/arquillian/persistence/data/dbunit/dataset/excel/ExcelDataSetBuilder.java +++ b/impl/src/main/java/org/jboss/arquillian/persistence/data/dbunit/dataset/excel/ExcelDataSetBuilder.java @@ -30,7 +30,7 @@ public class ExcelDataSetBuilder extends DataSetBuilder @Override public IDataSet build(String file) { - InputStream xlsStream = getClass().getClassLoader().getResourceAsStream(file); + InputStream xlsStream = Thread.currentThread().getContextClassLoader().getResourceAsStream(file); IDataSet dataSet = null; try { diff --git a/impl/src/main/java/org/jboss/arquillian/persistence/data/dbunit/dataset/xml/XmlDataSetBuilder.java b/impl/src/main/java/org/jboss/arquillian/persistence/data/dbunit/dataset/xml/XmlDataSetBuilder.java index <HASH>..<HASH> 100644 --- a/impl/src/main/java/org/jboss/arquillian/persistence/data/dbunit/dataset/xml/XmlDataSetBuilder.java +++ b/impl/src/main/java/org/jboss/arquillian/persistence/data/dbunit/dataset/xml/XmlDataSetBuilder.java @@ -31,7 +31,7 @@ public class XmlDataSetBuilder extends DataSetBuilder @Override public IDataSet build(String file) { - URL fileLocation = getClass().getClassLoader().getResource(file); + URL fileLocation = Thread.currentThread().getContextClassLoader().getResource(file); FlatXmlDataSetBuilder flatXmlDataSetBuilder = new FlatXmlDataSetBuilder(); IDataSet dataSet = null; try diff --git a/impl/src/main/java/org/jboss/arquillian/persistence/data/dbunit/dataset/yaml/YamlDataSetBuilder.java b/impl/src/main/java/org/jboss/arquillian/persistence/data/dbunit/dataset/yaml/YamlDataSetBuilder.java index <HASH>..<HASH> 100644 --- a/impl/src/main/java/org/jboss/arquillian/persistence/data/dbunit/dataset/yaml/YamlDataSetBuilder.java +++ b/impl/src/main/java/org/jboss/arquillian/persistence/data/dbunit/dataset/yaml/YamlDataSetBuilder.java @@ -30,7 +30,7 @@ public class YamlDataSetBuilder extends DataSetBuilder @Override public IDataSet build(String file) { - InputStream inputStream = getClass().getClassLoader().getResourceAsStream(file); + InputStream inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream(file); IDataSet dataSet = null; try {
Changed class loader to the context class loader for loading data sets.
arquillian_arquillian-extension-persistence
train
22889c54cdfa2351816989fe1e259f62ffe341ba
diff --git a/core/cas-server-core-services-authentication/src/main/java/org/apereo/cas/authentication/principal/WebApplicationServiceFactory.java b/core/cas-server-core-services-authentication/src/main/java/org/apereo/cas/authentication/principal/WebApplicationServiceFactory.java index <HASH>..<HASH> 100644 --- a/core/cas-server-core-services-authentication/src/main/java/org/apereo/cas/authentication/principal/WebApplicationServiceFactory.java +++ b/core/cas-server-core-services-authentication/src/main/java/org/apereo/cas/authentication/principal/WebApplicationServiceFactory.java @@ -111,7 +111,9 @@ public class WebApplicationServiceFactory extends AbstractServiceFactory<WebAppl .map(entry -> Pair.of(entry.getKey(), CollectionUtils.toCollection(entry.getValue(), ArrayList.class))) .collect(Collectors.toMap(Pair::getKey, Pair::getValue)); - if (UrlValidator.getInstance().isValid(service.getOriginalUrl())) { + LOGGER.trace("Collected request parameters [{}] as service attributes", attributes); + val validator = new UrlValidator(UrlValidator.ALLOW_LOCAL_URLS); + if (validator.isValid(service.getOriginalUrl())) { new URIBuilder(service.getOriginalUrl()).getQueryParams() .forEach(pair -> attributes.put(pair.getName(), CollectionUtils.wrapArrayList(pair.getValue()))); } diff --git a/support/cas-server-support-saml-idp/src/test/java/org/apereo/cas/support/saml/services/SamlIdPServicesManagerRegisteredServiceLocatorTests.java b/support/cas-server-support-saml-idp/src/test/java/org/apereo/cas/support/saml/services/SamlIdPServicesManagerRegisteredServiceLocatorTests.java index <HASH>..<HASH> 100644 --- a/support/cas-server-support-saml-idp/src/test/java/org/apereo/cas/support/saml/services/SamlIdPServicesManagerRegisteredServiceLocatorTests.java +++ b/support/cas-server-support-saml-idp/src/test/java/org/apereo/cas/support/saml/services/SamlIdPServicesManagerRegisteredServiceLocatorTests.java @@ -276,4 +276,40 @@ public class SamlIdPServicesManagerRegisteredServiceLocatorTests extends BaseSam assertNull(res1); } } + + @Test + public void verifyWithSelectionStrategy() { + val prefix = "http://localhost:8443/cas"; + val callbackUrl = prefix + SamlIdPConstants.ENDPOINT_SAML2_SSO_PROFILE_POST_CALLBACK; + + val service0 = RegisteredServiceTestUtils.getRegisteredService(callbackUrl + ".*"); + service0.setEvaluationOrder(0); + + val service1 = getSamlRegisteredServiceFor("https://sp.testshib.org/shibboleth-sp"); + service1.setEvaluationOrder(100); + + val service2 = getSamlRegisteredServiceFor(".+"); + service2.setMetadataLocation("https://example.org"); + service2.setEvaluationOrder(1000); + + val candidateServices = CollectionUtils.wrapList(service0, service1, service2); + servicesManager.save(candidateServices.toArray(new RegisteredService[0])); + + Collections.sort(candidateServices); + + val url = new URIBuilder(callbackUrl + "?entityId=https%3A%2F%2Fsp.testshib.org%2Fshibboleth-sp"); + val request = new MockHttpServletRequest(); + request.setRequestURI(callbackUrl); + url.getQueryParams().forEach(param -> request.addParameter(param.getName(), param.getValue())); + RequestContextHolder.setRequestAttributes(new ServletRequestAttributes(request, new MockHttpServletResponse())); + val service = webApplicationServiceFactory.createService(url.toString()); + assertFalse(service.getAttributes().isEmpty()); + val selectionStrategy = new SamlIdPEntityIdAuthenticationServiceSelectionStrategy(servicesManager, webApplicationServiceFactory, prefix); + val extracted = selectionStrategy.resolveServiceFrom(service); + assertNotNull(extracted); + assertFalse(extracted.getAttributes().isEmpty()); + + val result = servicesManager.findServiceBy(extracted); + assertEquals(service1, result); + } }
allow localhost to be authorized when collecting request params (cherry picked from commit d<I>f<I>b<I>bbdc<I>d4ff<I>b<I>bbd<I>)
apereo_cas
train
0fc0967462da0f020a7675a79818df0a65bf6b42
diff --git a/internal/service/autoscaling/group.go b/internal/service/autoscaling/group.go index <HASH>..<HASH> 100644 --- a/internal/service/autoscaling/group.go +++ b/internal/service/autoscaling/group.go @@ -1,6 +1,6 @@ package autoscaling -import ( // nosemgrep: aws-sdk-go-multiple-service-imports +import ( "bytes" "context" "fmt" diff --git a/internal/service/autoscaling/group_waiting.go b/internal/service/autoscaling/group_waiting.go index <HASH>..<HASH> 100644 --- a/internal/service/autoscaling/group_waiting.go +++ b/internal/service/autoscaling/group_waiting.go @@ -1,6 +1,6 @@ package autoscaling -import ( +import ( // nosemgrep: aws-sdk-go-multiple-service-imports "fmt" "log" "strconv"
Fix semgrep 'aws-sdk-go-multiple-service-imports' errors.
terraform-providers_terraform-provider-aws
train
c46d9874d46db91ff9527a423fb8e7d3e45dce4a
diff --git a/test_maya.py b/test_maya.py index <HASH>..<HASH> 100644 --- a/test_maya.py +++ b/test_maya.py @@ -1,3 +1,6 @@ +import pytest +from datetime import datetime + import maya @@ -43,10 +46,29 @@ def test_dt_tz_naive(): def test_random_date(): - d = maya.when('11-17-11') + d = maya.when('11-17-11 08:09:10') assert d.year == 2011 assert d.month == 11 assert d.day == 17 + assert d.hour == 8 + assert d.minute == 9 + assert d.second == 10 + assert d.microsecond == 0 + + +def test_print_date(capsys): + d = maya.when('11-17-11') + + print(d) + out, err = capsys.readouterr() + assert out == '<MayaDT epoch=1321488000.0>\n' + + assert type(d.__format__()) is datetime + + +def test_invalid_date(): + with pytest.raises(ValueError): + d = maya.when('another day') def test_slang_date():
Just add some tests to have full coverage Now it's 💯 % coverage, i don't if it's good or bad but it was easy :)
kennethreitz_maya
train
303ed6f916e2f4825181b3c48d473cfd43e267f8
diff --git a/line-bot-model/src/main/java/com/linecorp/bot/model/response/NarrowcastProgressResponse.java b/line-bot-model/src/main/java/com/linecorp/bot/model/response/NarrowcastProgressResponse.java index <HASH>..<HASH> 100644 --- a/line-bot-model/src/main/java/com/linecorp/bot/model/response/NarrowcastProgressResponse.java +++ b/line-bot-model/src/main/java/com/linecorp/bot/model/response/NarrowcastProgressResponse.java @@ -16,6 +16,8 @@ package com.linecorp.bot.model.response; +import java.time.Instant; + import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.fasterxml.jackson.databind.annotation.JsonPOJOBuilder; @@ -67,6 +69,17 @@ public class NarrowcastProgressResponse { */ Long errorCode; + /** + * Narrowcast message request accepted time in milliseconds. + */ + Instant acceptedTime; + + /** + * Processing of narrowcast message request completion time in milliseconds. Returned when the phase + * property is succeeded or failed. + */ + Instant completedTime; + public enum Phase { /** * Messages are not yet ready to be sent. They are currently being filtered or processed in some way. diff --git a/sample-manage-audience/src/main/java/com/linecorp/bot/messagingapidemoapp/controller/message/NarrowcastController.java b/sample-manage-audience/src/main/java/com/linecorp/bot/messagingapidemoapp/controller/message/NarrowcastController.java index <HASH>..<HASH> 100644 --- a/sample-manage-audience/src/main/java/com/linecorp/bot/messagingapidemoapp/controller/message/NarrowcastController.java +++ b/sample-manage-audience/src/main/java/com/linecorp/bot/messagingapidemoapp/controller/message/NarrowcastController.java @@ -130,7 +130,7 @@ public class NarrowcastController { ).build() ); } - Recipient recipientObject = recipient != null + Recipient recipientObject = StringUtils.isNotBlank(recipient) ? objectMapper.readValue(recipient, Recipient.class) : null; diff --git a/sample-manage-audience/src/main/resources/templates/message/narrowcast/progress.ftlh b/sample-manage-audience/src/main/resources/templates/message/narrowcast/progress.ftlh index <HASH>..<HASH> 100644 --- a/sample-manage-audience/src/main/resources/templates/message/narrowcast/progress.ftlh +++ b/sample-manage-audience/src/main/resources/templates/message/narrowcast/progress.ftlh @@ -62,6 +62,18 @@ <td>${progress.errorCode!"-"}</td> <td>A brief summary of the error.</td> </tr> + <tr> + <td>acceptedTime</td> + <td>${progress.acceptedTime!"-"}</td> + <td>Narrowcast message request accepted time in milliseconds.</td> + </tr> + <tr> + <td>completedTime</td> + <td>${progress.completedTime!"-"}</td> + <td>Processing of narrowcast message request completion time in milliseconds. Returned when the + phase property is succeeded or failed. + </td> + </tr> </table> </@wrapper.main>
Add acceptedTime and completedTime fields in response of the narrowcast progress API. (#<I>)
line_line-bot-sdk-java
train
cde2927cbf8e298527bb698228c36f81bfb4619b
diff --git a/hydpy/core/parametertools.py b/hydpy/core/parametertools.py index <HASH>..<HASH> 100644 --- a/hydpy/core/parametertools.py +++ b/hydpy/core/parametertools.py @@ -260,14 +260,14 @@ class Parameter(objecttools.ValueMath): """The parameter time step size new parameter values might be related to. """ - if self._parameterstep is None: + if Parameter._parameterstep is None: raise RuntimeError('The general parameter time step has not been ' 'defined so far.') else: return self._parameterstep def _setparameterstep(self, value): try: - self._parameterstep = timetools.Period(value) + Parameter._parameterstep = timetools.Period(value) except Exception: objecttools.augmentexcmessage('While trying to set the general ' 'parameter time step') @@ -280,8 +280,14 @@ class Parameter(objecttools.ValueMath): try: return pub.timegrids.stepsize except AttributeError: - return self._simulationstep - simulationstep = property(_getsimulationstep) + return Parameter._simulationstep + def _setsimulationstep(self, value): + try: + Parameter._simulationstep = timetools.Period(value) + except Exception: + objecttools.augmentexcmessage('While trying to set the general ' + 'simulation time step') + simulationstep = property(_getsimulationstep, _setsimulationstep) def _gettimefactor(self): """Factor to adapt a new parameter value related to
Improve properties "simulationstep" and "parameterstep" of the Parameter class (paramtertools). - "simulationstep" is now a setable property - the underlying attributes "_simulationstep" and "_parameterstep" are now handled as class attributes consistently.
hydpy-dev_hydpy
train
c09744676b11f8c84dbe61849305d5cafa51575f
diff --git a/src/Cartalyst/Sentry/Facades/CI/Sentry.php b/src/Cartalyst/Sentry/Facades/CI/Sentry.php index <HASH>..<HASH> 100644 --- a/src/Cartalyst/Sentry/Facades/CI/Sentry.php +++ b/src/Cartalyst/Sentry/Facades/CI/Sentry.php @@ -85,7 +85,7 @@ class Sentry { } return new BaseSentry( - new UserProvider(new NativeHasher), + $userProvider = new UserProvider(new NativeHasher), new GroupProvider, new ThrottleProvider($userProvider), new CISession($ci->session), diff --git a/src/Cartalyst/Sentry/Facades/Facade.php b/src/Cartalyst/Sentry/Facades/Facade.php index <HASH>..<HASH> 100644 --- a/src/Cartalyst/Sentry/Facades/Facade.php +++ b/src/Cartalyst/Sentry/Facades/Facade.php @@ -46,13 +46,6 @@ abstract class Facade { } /** - * Creates a new instance of Sentry. - * - * @return Cartalyst\Sentry\Sentry - */ - public static function createSentry(); - - /** * Handle dynamic, static calls to the object. * * @param string $method @@ -63,6 +56,8 @@ abstract class Facade { { $instance = static::instance(); + var_dump($instance); + switch (count($args)) { case 0: diff --git a/src/Cartalyst/Sentry/Facades/FuelPHP/Sentry.php b/src/Cartalyst/Sentry/Facades/FuelPHP/Sentry.php index <HASH>..<HASH> 100644 --- a/src/Cartalyst/Sentry/Facades/FuelPHP/Sentry.php +++ b/src/Cartalyst/Sentry/Facades/FuelPHP/Sentry.php @@ -61,7 +61,7 @@ class Sentry extends Facade { } return new BaseSentry( - new UserProvider(new NativeHasher), + $userProvider = new UserProvider(new NativeHasher), new GroupProvider, new ThrottleProvider($userProvider), new FuelPHPSession(Session::instance()), diff --git a/src/Cartalyst/Sentry/Facades/Native/Sentry.php b/src/Cartalyst/Sentry/Facades/Native/Sentry.php index <HASH>..<HASH> 100644 --- a/src/Cartalyst/Sentry/Facades/Native/Sentry.php +++ b/src/Cartalyst/Sentry/Facades/Native/Sentry.php @@ -35,7 +35,7 @@ use Cartalyst\Sentry\Users\ProviderInterface as UserProviderInterface; use Illuminate\Database\Eloquent\Model as Eloquent; use PDO; -class Sentry { +class Sentry extends Facade { /** * Creates a Sentry instance. @@ -56,8 +56,10 @@ class Sentry { $ipAddress = null ) { + $userProvider = $userProvider ?: new UserProvider(new NativeHasher); + return new BaseSentry( - $userProvider ?: new UserProvider(new NativeHasher), + $userProvider, $groupProvider ?: new GroupProvider, $throttleProvider ?: new ThrottleProvider($userProvider), $session ?: new NativeSession,
Fixing Facades, aiming for #<I>.
cartalyst_sentry
train