hash
stringlengths
40
40
diff
stringlengths
131
114k
message
stringlengths
7
980
project
stringlengths
5
67
split
stringclasses
1 value
58b815a6fe3f0822c8503df51248cb56e281ca4a
diff --git a/component.py b/component.py index <HASH>..<HASH> 100644 --- a/component.py +++ b/component.py @@ -182,9 +182,7 @@ class Component(object): """Returns a TextIOWrapper around the given stream that handles UTF-8 encoding/decoding. """ - if isinstance(stream, io.TextIOBase): - return stream - elif hasattr(stream, 'buffer'): + if hasattr(stream, 'buffer'): return io.TextIOWrapper(stream.buffer, encoding='utf-8') else: return io.TextIOWrapper(stream, encoding='utf-8')
Remove StringIO usage from unit tests to simplify component code and prevent a potential issue where stdin/stdout have different encodings with Python 3
pystorm_pystorm
train
7260ab698068f18e180dea0d6f2f551823243c3e
diff --git a/index.js b/index.js index <HASH>..<HASH> 100644 --- a/index.js +++ b/index.js @@ -35,7 +35,7 @@ var indexes = [ ] function mapRts (msg) { - msg.rts = Math.min(msg.timestamp, msg.value.timestamp) + msg.rts = Math.min(msg.timestamp, msg.value.timestamp) || msg.timestamp return msg } @@ -71,3 +71,7 @@ exports.init = function (ssb, config) { } + + + +
if claimed timestamp is zero, use received time instead @mmckegg @AljoschaMeyer @cryptix
ssbc_ssb-query
train
c9975f55f235de934a41b1de2e5e8106060d65ec
diff --git a/core/src/test/java/c10n/CustomAnnotationBindingTest.java b/core/src/test/java/c10n/CustomAnnotationBindingTest.java index <HASH>..<HASH> 100755 --- a/core/src/test/java/c10n/CustomAnnotationBindingTest.java +++ b/core/src/test/java/c10n/CustomAnnotationBindingTest.java @@ -66,7 +66,7 @@ public class CustomAnnotationBindingTest { @Test public void unboundAnnotationBehavesAsAFallback() { Labels msg = C10N.get(Labels.class); - Locale.setDefault(Locale.GERMAN); + Locale.setDefault(new Locale("unbound")); assertThat(msg.label(), is(equalTo("Default"))); assertThat(msg.label2("def"), is(equalTo("Default def"))); } @@ -84,7 +84,7 @@ public class CustomAnnotationBindingTest { assertThat(msg.books(0), is("ζœ¬γŒγ‚γ‚ŠγΎγ›γ‚“γ€‚")); assertThat(msg.books(3), is("本が3ζœ¬γ‚γ‚ŠγΎγ™γ€‚")); - Locale.setDefault(Locale.GERMAN); + Locale.setDefault(new Locale("unbound")); assertThat(msg.label2("def"), is(equalTo("Default def"))); }
Fixed broken test due to predefined annotations
rodionmoiseev_c10n
train
6f219f4e5d70c5f063c626855f595ee67d89944e
diff --git a/lib/monetize.rb b/lib/monetize.rb index <HASH>..<HASH> 100644 --- a/lib/monetize.rb +++ b/lib/monetize.rb @@ -92,6 +92,7 @@ module Monetize value *= currency.subunit_to_unit Money.new(value, currency) end + singleton_class.send(:alias_method, :from_integer, :from_fixnum) def self.from_float(value, currency = Money.default_currency) value = BigDecimal.new(value.to_s) diff --git a/spec/monetize_spec.rb b/spec/monetize_spec.rb index <HASH>..<HASH> 100644 --- a/spec/monetize_spec.rb +++ b/spec/monetize_spec.rb @@ -232,11 +232,11 @@ describe Monetize do end context 'parsing an instance of Numeric class' do - let(:fixnum) { 10 } + let(:integer) { 10 } let(:float) { 10.0 } let(:big_decimal) { BigDecimal.new('10') } - [:fixnum, :float, :big_decimal].each do |type| + [:integer, :float, :big_decimal].each do |type| it "returns a new Money object based on the #{type} input" do money = Monetize.parse(send(type), 'USD') @@ -386,6 +386,10 @@ describe Monetize do m = Monetize.from_fixnum(1, 'EUR') expect(m.currency).to eq Money::Currency.wrap('EUR') end + + it 'is aliased as from_integer' do + expect(Monetize.from_integer(1)).to eq(Monetize.from_fixnum(1)) + end end describe '.from_float' do
Alias from_fixnum as from_integer method (#<I>)
RubyMoney_monetize
train
790619083dc22a0e1a5c3a713a20add372de3aa5
diff --git a/src/containers/EntryPage.js b/src/containers/EntryPage.js index <HASH>..<HASH> 100644 --- a/src/containers/EntryPage.js +++ b/src/containers/EntryPage.js @@ -40,7 +40,7 @@ class EntryPage extends React.Component { }; componentDidMount() { - const { entry, newEntry, collection, slug, loadEntry } = this.props; + const { entry, newEntry, collection, slug, loadEntry, createEmptyDraft } = this.props; this.props.openSidebar(); if (newEntry) { createEmptyDraft(collection);
Fix cms hanging when going to new entry page
netlify_netlify-cms
train
e7303a870cb58c32160d4147e8c4d0eafb651cc1
diff --git a/src/asynqp/serialisation.py b/src/asynqp/serialisation.py index <HASH>..<HASH> 100644 --- a/src/asynqp/serialisation.py +++ b/src/asynqp/serialisation.py @@ -83,8 +83,8 @@ def read_bools(byte, number_of_bools): @rethrow_as(struct.error, AMQPError('failed to read a boolean')) -def read_time_stamp(stream): - return _read_time_stamp(stream)[0] +def read_timestamp(stream): + return _read_timestamp(stream)[0] def _read_table(stream): @@ -100,7 +100,7 @@ def _read_table(stream): b'I': _read_long, b'l': _read_unsigned_long_long, b'L': _read_long_long, - b'T': _read_time_stamp + b'T': _read_timestamp } consumed = 0 @@ -178,7 +178,7 @@ def _read_unsigned_long_long(stream): return x, 8 -def _read_time_stamp(stream): +def _read_timestamp(stream): x, = struct.unpack('!Q', stream.read(8)) # From datetime.fromutctimestamp converts it to a local timestamp without timezone information return datetime.fromtimestamp(x * 1e-3, timezone.utc), 8 @@ -211,7 +211,7 @@ def pack_table(d): bytes += pack_long_string(value) elif isinstance(value, datetime): bytes += b'T' - bytes += pack_time_stamp(value) + bytes += pack_timestamp(value) elif isinstance(value, int): if value < 0: if value.bit_length() < 16: @@ -276,7 +276,7 @@ def pack_bool(b): return struct.pack('!?', b) -def pack_time_stamp(timeval): +def pack_timestamp(timeval): number = int(timeval.timestamp() * 1e3) return struct.pack('!Q', number) diff --git a/test/serialisation_tests.py b/test/serialisation_tests.py index <HASH>..<HASH> 100644 --- a/test/serialisation_tests.py +++ b/test/serialisation_tests.py @@ -82,9 +82,9 @@ class WhenPackingBools: assert self.result == expected -class WhenParsingATimeStamp: +class WhenParsingATimestamp: @classmethod - def examples_of_time_stamps(cls): + def examples_of_timestamps(cls): # The timestamp should be zero relative to epoch yield b'\x00\x00\x00\x00\x00\x00\x00\x00', datetime(1970, 1, 1, tzinfo=timezone.utc) # And independent of the timezone @@ -94,36 +94,36 @@ class WhenParsingATimeStamp: # Cannot validate, that it is unsigned, as it is # yield b'\x80\x00\x00\x00\x00\x00\x00\x00', datetime(1970, 1, 1, microsecond=1000, tzinfo=timezone.utc) - def because_we_read_a_time_stamp(self, binary, _): - self.result = serialisation.read_time_stamp(BytesIO(binary)) + def because_we_read_a_timestamp(self, binary, _): + self.result = serialisation.read_timestamp(BytesIO(binary)) def it_should_read_it_correctly(self, _, expected): assert self.result == expected -class WhenWritingATimeStamp: +class WhenWritingATimestamp: @classmethod - def examples_of_time_stamps(cls): - for encoded, timeval in WhenParsingATimeStamp.examples_of_time_stamps(): + def examples_of_timestamps(cls): + for encoded, timeval in WhenParsingATimestamp.examples_of_timestamps(): yield timeval, encoded def because_I_pack_them(self, timeval, _): - self.result = serialisation.pack_time_stamp(timeval) + self.result = serialisation.pack_timestamp(timeval) def it_should_pack_them_correctly(self, _, expected): assert self.result == expected -class WhenPackingAndUnpackingATimeStamp: +class WhenPackingAndUnpackingATimestamp: # Ensure, we do not add some offset by the serialisation process @classmethod - def examples_of_time_stamps(cls): + def examples_of_timestamps(cls): yield datetime(1970, 1, 1, tzinfo=timezone.utc) yield datetime(1979, 1, 1, tzinfo=timezone(timedelta(hours=1, minutes=30))) def because_I_pack_them(self, timeval): - packed = serialisation.pack_time_stamp(timeval) - unpacked = serialisation.read_time_stamp(BytesIO(packed)) + packed = serialisation.pack_timestamp(timeval) + unpacked = serialisation.read_timestamp(BytesIO(packed)) self.result = unpacked - timeval def it_should_pack_them_correctly(self, timeval):
Rename time_stamp to timestamp, following the style in datetime
benjamin-hodgson_asynqp
train
e73f0de15c5e9fd3016d9e1008f5bda967eeb131
diff --git a/__init__.py b/__init__.py index <HASH>..<HASH> 100644 --- a/__init__.py +++ b/__init__.py @@ -12,6 +12,8 @@ from __future__ import absolute_import, division, print_function, unicode_literals DEFAULT_TX_FEE = 100000 +DEFAULT_BASE_FEE = DEFAULT_TX_FEE +DEFAULT_SMART_FEE = 400000 DEFAULT_ASSET_FEE = 100000000 DEFAULT_MATCHER_FEE = 300000 DEFAULT_LEASE_FEE = 100000 diff --git a/address.py b/address.py index <HASH>..<HASH> 100644 --- a/address.py +++ b/address.py @@ -431,8 +431,8 @@ class Address(object): return pywaves.wrapper('/transactions/broadcast', data) - def massTransferWaves(self, transfers, attachment='', timestamp=0): - txFee = 100000 + (math.ceil((len(transfers) + 1) / 2 - 0.5)) * 100000 + def massTransferWaves(self, transfers, attachment='', timestamp=0,baseFee=pywaves.DEFAULT_BASE_FEE): + txFee = baseFee + (math.ceil((len(transfers) + 1) / 2 - 0.5)) * baseFee totalAmount = 0 for i in range(0, len(transfers)): @@ -550,11 +550,11 @@ class Address(object): return pywaves.wrapper('/assets/broadcast/transfer', data) - def massTransferAssets(self, transfers, asset, attachment='', timestamp=0): - txFee = 100000 + (math.ceil((len(transfers) + 1) / 2 - 0.5)) * 100000 + def massTransferAssets(self, transfers, asset, attachment='', timestamp=0,baseFee=pywaves.DEFAULT_BASE_FEE,smartFee=pywaves.DEFAULT_SMART_FEE): + txFee = baseFee + (math.ceil((len(transfers) + 1) / 2 - 0.5)) * baseFee if (asset.isSmart()): - txFee += 400000 + txFee += smartFee totalAmount = 0 @@ -603,7 +603,7 @@ class Address(object): return pywaves.wrapper('/transactions/broadcast', data) - def dataTransaction(self, data, timestamp=0): + def dataTransaction(self, data, timestamp=0, baseFee=pywaves.DEFAULT_BASE_FEE, minimalFee=500000): if not self.privateKey: logging.error('Private key required') else: @@ -642,8 +642,8 @@ class Address(object): dataBinary += struct.pack(">H", len(d['value'])) dataBinary += crypto.str2bytes(d['value']) # check: https://stackoverflow.com/questions/2356501/how-do-you-round-up-a-number-in-python - txFee = (int(((len(crypto.str2bytes(json.dumps(data))) + 2 + 64 )) / 1000.0) + 1 ) * 100000 - txFee = max(txFee, 500000) + txFee = (int(((len(crypto.str2bytes(json.dumps(data))) + 2 + 64 )) / 1000.0) + 1 ) * baseFee + txFee = max(txFee, minimalFee) dataObject['fee'] = txFee sData = b'\x0c' + \ b'\1' + \ @@ -1080,7 +1080,6 @@ class Address(object): "proofs": [ signature ], "script": 'base64:' + script }) - print(data) req = pywaves.wrapper('/transactions/broadcast', data) if pywaves.OFFLINE: return req
Making pywaves more dynamic without breaking old functionality
PyWaves_PyWaves
train
6064c4b9b97ad40e38a8f66aa71e6c6e469091a4
diff --git a/lib/lolita/controllers/component_helpers.rb b/lib/lolita/controllers/component_helpers.rb index <HASH>..<HASH> 100644 --- a/lib/lolita/controllers/component_helpers.rb +++ b/lib/lolita/controllers/component_helpers.rb @@ -131,7 +131,7 @@ module Lolita # # component_helper_path :"lolita/list" #=> [path_to_lolita]/app/helpers/components/lolita/list_component.rb def component_helper_path component_name - @helper_paths||=$:.reject{|p| !p.match(/\/helpers$/)} + @helper_paths||=$:.reject{|p| !p.match(/\/helpers$/) rescue nil} get_path=lambda{|paths| extra_path=component_name.to_s.split("/") component=extra_path.pop
helper detection method fixed, to ignore PathName
ithouse_lolita
train
1d62e9c259eaf271ddf8bb8a6fddcc4f0e51ffa0
diff --git a/core/src/main/java/hudson/util/CopyOnWriteList.java b/core/src/main/java/hudson/util/CopyOnWriteList.java index <HASH>..<HASH> 100644 --- a/core/src/main/java/hudson/util/CopyOnWriteList.java +++ b/core/src/main/java/hudson/util/CopyOnWriteList.java @@ -44,7 +44,25 @@ public class CopyOnWriteList<E> implements Iterable<E> { return r; } + /** + * Returns an iterator. + * + * The returned iterator doesn't support the <tt>remove</tt> operation. + */ public Iterator<E> iterator() { - return core.iterator(); + final Iterator<E> itr = core.iterator(); + return new Iterator<E>() { + public boolean hasNext() { + return itr.hasNext(); + } + + public E next() { + return itr.next(); + } + + public void remove() { + throw new UnsupportedOperationException(); + } + }; } }
fixed a problem in the iterator as pointed out by Jesse. git-svn-id: <URL>
jenkinsci_jenkins
train
c63b69672eb70c8453d76a914a1ee4a1e29222c9
diff --git a/process.go b/process.go index <HASH>..<HASH> 100644 --- a/process.go +++ b/process.go @@ -66,7 +66,6 @@ func (p *process) Kill(ctx context.Context, s syscall.Signal) error { } func (p *process) Wait(ctx context.Context) (uint32, error) { - // TODO (ehazlett): add filtering for specific event eventstream, err := p.task.client.EventService().Stream(ctx, &eventsapi.StreamEventsRequest{}) if err != nil { return UnknownExitStatus, err @@ -78,15 +77,15 @@ evloop: if err != nil { return UnknownExitStatus, err } - v, err := typeurl.UnmarshalAny(evt.Event) - if err != nil { - return UnknownExitStatus, err - } - if e, ok := v.(*eventsapi.RuntimeEvent); ok { + if typeurl.Is(evt.Event, eventsapi.RuntimeEvent{}) { + v, err := typeurl.UnmarshalAny(evt.Event) + if err != nil { + return UnknownExitStatus, err + } + e := v.(*eventsapi.RuntimeEvent) if e.Type != eventsapi.RuntimeEvent_EXIT { continue evloop } - if e.ID == p.task.containerID && e.Pid == p.pid { return e.ExitStatus, nil } diff --git a/task.go b/task.go index <HASH>..<HASH> 100644 --- a/task.go +++ b/task.go @@ -160,8 +160,12 @@ func (t *task) Wait(ctx context.Context) (uint32, error) { if err != nil { return UnknownExitStatus, err } - v, err := typeurl.UnmarshalAny(evt.Event) - if e, ok := v.(*eventsapi.RuntimeEvent); ok { + if typeurl.Is(evt.Event, eventsapi.RuntimeEvent{}) { + v, err := typeurl.UnmarshalAny(evt.Event) + if err != nil { + return UnknownExitStatus, err + } + e := v.(*eventsapi.RuntimeEvent) if e.Type != eventsapi.RuntimeEvent_EXIT { continue } diff --git a/typeurl/types.go b/typeurl/types.go index <HASH>..<HASH> 100644 --- a/typeurl/types.go +++ b/typeurl/types.go @@ -2,12 +2,12 @@ package typeurl import ( "encoding/json" - "errors" "path" "reflect" "strings" "sync" + "github.com/containerd/containerd/errdefs" "github.com/gogo/protobuf/proto" "github.com/gogo/protobuf/types" ) @@ -15,10 +15,8 @@ import ( const Prefix = "types.containerd.io" var ( - mu sync.Mutex - registry = make(map[reflect.Type]string) - ErrRegistered = errors.New("typeurl: type already registred") - ErrNotExists = errors.New("typeurl: type is not registered") + mu sync.Mutex + registry = make(map[reflect.Type]string) ) // Register a type with the base url of the type @@ -27,7 +25,7 @@ func Register(v interface{}, args ...string) { mu.Lock() defer mu.Unlock() if _, ok := registry[t]; ok { - panic(ErrRegistered) + panic(errdefs.ErrAlreadyExists) } registry[t] = path.Join(append([]string{Prefix}, args...)...) } @@ -41,13 +39,21 @@ func TypeURL(v interface{}) (string, error) { // fallback to the proto registry if it is a proto message pb, ok := v.(proto.Message) if !ok { - return "", ErrNotExists + return "", errdefs.ErrNotFound } return path.Join(Prefix, proto.MessageName(pb)), nil } return u, nil } +func Is(any *types.Any, v interface{}) bool { + url, err := TypeURL(v) + if err != nil { + return false + } + return any.TypeUrl == url +} + func MarshalAny(v interface{}) (*types.Any, error) { var ( err error @@ -108,7 +114,7 @@ func getTypeByUrl(url string) (urlType, error) { isProto: true, }, nil } - return urlType{}, ErrNotExists + return urlType{}, errdefs.ErrNotFound } func tryDereference(v interface{}) reflect.Type { diff --git a/typeurl/types_test.go b/typeurl/types_test.go index <HASH>..<HASH> 100644 --- a/typeurl/types_test.go +++ b/typeurl/types_test.go @@ -7,7 +7,6 @@ import ( "testing" eventsapi "github.com/containerd/containerd/api/services/events/v1" - events "github.com/containerd/containerd/events" ) type test struct { @@ -121,9 +120,26 @@ func TestMarshalUnmarshal(t *testing.T) { } } +func TestIs(t *testing.T) { + clear() + Register(test{}, "test") + + v := &test{ + Name: "koye", + Age: 6, + } + any, err := MarshalAny(v) + if err != nil { + t.Fatal(err) + } + if !Is(any, test{}) { + t.Fatal("Is(any, test{}) should be true") + } +} + func TestMarshalEvent(t *testing.T) { for _, testcase := range []struct { - event events.Event + event interface{} url string }{ {
Add typeurl.Is to gate unmarshal
containerd_containerd
train
c7e2f24140e3f879a098fc30222cd6ba4cf6983c
diff --git a/scripts/experiments/run_experiments.py b/scripts/experiments/run_experiments.py index <HASH>..<HASH> 100644 --- a/scripts/experiments/run_experiments.py +++ b/scripts/experiments/run_experiments.py @@ -316,8 +316,9 @@ class DepParseExpParamsRunner(ExpParamsRunner): brown_cf = self.get_data(data_dir, "treebank_3/brown/cf", "PTB") brown_full = self.get_data(data_dir, "treebank_3/brown", "PTB") - conll09_dir = "/export/common/data/corpora/LDC/LDC2012T03/data" - conll09_sp_dir = os.path.join(conll09_dir, "CoNLL2009-ST-Spanish") + #conll09_dir = "/export/common/data/corpora/LDC/LDC2012T03/data" + #conll09_sp_dir = os.path.join(conll09_dir, "CoNLL2009-ST-Spanish") + conll09_sp_dir = os.path.join(data_dir, "CoNLL2009-ST-Spanish-BrownClusters") conll09_sp_dev = self.get_data(conll09_sp_dir, "CoNLL2009-ST-Spanish-train.txt") + \ DPExpParams(dataset="conll09-sp-dev", trainType="CONLL_2009",
Switching to brown clusters SRL data.
mgormley_pacaya
train
f3e8a5b6b887f8a6cb45d0a7f9de77d59cad428a
diff --git a/CHANGELOG.md b/CHANGELOG.md index <HASH>..<HASH> 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,4 +1,4 @@ -# v2.4.2 +# v2.4.3 * Fix issue with automatically loading Alchemy* credentials from the Bluemix environment # v2.4.1 diff --git a/lib/base_service.js b/lib/base_service.js index <HASH>..<HASH> 100644 --- a/lib/base_service.js +++ b/lib/base_service.js @@ -19,7 +19,6 @@ var extend = require('extend'); var vcapServices = require('vcap_services'); var helper = require('./helper'); -var omit = require('object.omit'); var request = require('request'); @@ -44,8 +43,6 @@ function BaseService(user_options) { options = this.initCredentials(options); - options = omit(options, ['version', 'username', 'password', 'use_unauthenticated', 'apikey']); - if (options.url) options.url = helper.stripTrailingSlash(options.url); diff --git a/lib/base_service_alchemy.js b/lib/base_service_alchemy.js index <HASH>..<HASH> 100644 --- a/lib/base_service_alchemy.js +++ b/lib/base_service_alchemy.js @@ -22,7 +22,7 @@ util.inherits(BaseServiceAlchemy, BaseService); * @private */ BaseServiceAlchemy.prototype.initCredentials = function(options) { - options.api_key = options.apikey || options.api_key; + options.apikey = options.apikey || options.api_key; options = extend( {}, this.getCredentialsFromBluemix('alchemy_api'), // this is the same for all Alchemy* services @@ -30,12 +30,12 @@ BaseServiceAlchemy.prototype.initCredentials = function(options) { options ); if (!options.use_unauthenticated) { - if (!options.api_key) { + if (!options.apikey) { throw new Error('Argument error: api_key was not specified'); } // Per documentation, Alchemy* services use `apikey`, but Visual Recognition uses (`api_key`) // (Either will work in most cases, but there are a few exceptions.) - options.qs = extend({ apikey : options.api_key }, options.qs); + options.qs = extend({ apikey : options.apikey }, options.qs); } return options }; @@ -48,7 +48,7 @@ BaseServiceAlchemy.prototype.initCredentials = function(options) { */ BaseServiceAlchemy.prototype.getCredentialsFromEnvironment = function(name) { return { - api_key: process.env[name.toUpperCase() + '_API_KEY'] + apikey: process.env[name.toUpperCase() + '_API_KEY'] } }; diff --git a/test/test.wrapper.js b/test/test.wrapper.js index <HASH>..<HASH> 100644 --- a/test/test.wrapper.js +++ b/test/test.wrapper.js @@ -108,12 +108,12 @@ describe('wrapper', function() { it('should use apikey (not documented) for alchemy service', function() { var service = watson.alchemy_language({ apikey: 'not-gonna-work'}); - assert.equal(service._options.api_key, 'not-gonna-work'); + assert.equal(service._options.qs.apikey, 'not-gonna-work'); }); it('should use api_key for alchemy service', function() { var service = watson.alchemy_language({ api_key: 'not-gonna-work'}); - assert.equal(service._options.api_key, 'not-gonna-work'); + assert.equal(service._options.qs.apikey, 'not-gonna-work'); }); it('should not use VCAP_SERVICES if use_vcap_services is false', function() {
more apikey/apikey stuff
watson-developer-cloud_node-sdk
train
85d6efe841da23014226bd7ad4419d037937cb65
diff --git a/example/php/index.php b/example/php/index.php index <HASH>..<HASH> 100644 --- a/example/php/index.php +++ b/example/php/index.php @@ -3,6 +3,9 @@ require_once 'vendor/autoload.php'; $bugsnag = Bugsnag\Client::make('YOUR-API-KEY-HERE'); + +$bugsnag->leaveBreadcrumb('Example breadcrumb!'); + $bugsnag->notifyError('Broken', 'Something broke', function (Bugsnag\Report $report) { $report->setMetaData(['tab' => ['paying' => true, 'object' => (object) ['key' => 'value'], 'null' => null, 'string' => 'test', 'int' => 4]]); });
Made the example leave a breadcrumb (#<I>)
bugsnag_bugsnag-php
train
ad338e98dac9de629a948ebf66cd163c39f74dc6
diff --git a/CHANGELOG b/CHANGELOG index <HASH>..<HASH> 100644 --- a/CHANGELOG +++ b/CHANGELOG @@ -1,4 +1,7 @@ += 0.1.4 - Fix avoid proxying immutable classes +- Fix concat with proxy array +- Fix merge with proxy hash = 0.1.3 - Fix for returning immutable class from CowProxy diff --git a/lib/cow_proxy/array.rb b/lib/cow_proxy/array.rb index <HASH>..<HASH> 100644 --- a/lib/cow_proxy/array.rb +++ b/lib/cow_proxy/array.rb @@ -1,6 +1,14 @@ module CowProxy class Array < WrapClass(::Array) include Indexable + + # Used for concatenating into another Array + # needs to return unwrapped Array + # + # @return [Array] wrapped object + def to_ary + __getobj__ + end end end diff --git a/lib/cow_proxy/hash.rb b/lib/cow_proxy/hash.rb index <HASH>..<HASH> 100644 --- a/lib/cow_proxy/hash.rb +++ b/lib/cow_proxy/hash.rb @@ -1,6 +1,14 @@ module CowProxy class Hash < WrapClass(::Hash) include Indexable + + # Used for merging into another Hash + # needs to return unwrapped Hash + # + # @return [Hash] wrapped object + def to_hash + __getobj__ + end end end diff --git a/test/array_test.rb b/test/array_test.rb index <HASH>..<HASH> 100644 --- a/test/array_test.rb +++ b/test/array_test.rb @@ -25,6 +25,10 @@ describe CowProxy do @var[2].must_equal @origin[2] end + it 'allow to be used with concat' do + [].concat @proxy + end + it 'copy on write on mutable methods on child' do @proxy.must_equal @origin diff --git a/test/hash_test.rb b/test/hash_test.rb index <HASH>..<HASH> 100644 --- a/test/hash_test.rb +++ b/test/hash_test.rb @@ -25,6 +25,10 @@ describe CowProxy do @var[:c].must_equal @origin[:c] end + it 'allow to be merged' do + {}.merge @proxy + end + it 'copy on write on mutable methods on child' do @proxy.must_equal @var
fix concat and merge with proxy array and hash
Programatica_cow_proxy
train
36c4f686036638dc0e91b375905e6adcf01d1201
diff --git a/lib/dialog.js b/lib/dialog.js index <HASH>..<HASH> 100644 --- a/lib/dialog.js +++ b/lib/dialog.js @@ -418,12 +418,17 @@ class Dialog extends Emitter { case 'MESSAGE': case 'PUBLISH': case 'UPDATE': - if (0 === this.listeners(eventName).length) { - res.send(200) ; - } - else { - this.emit(eventName, req, res) ; - } + + // N.B.: this is because an app may be using the Promises version + // of Srf#createUAS or Srf#createB2B and if so the 'then()' code + // may be enqueued at the back of the job queue right now if a very + // quick INFO or other request within the dialog just arrived. + // We need the dialog to be resolved in the calling app first so it + // has time to attach event handlers. + setImmediate(() => { + if (0 === this.listeners(eventName).length) res.send(200) ; + else this.emit(eventName, req, res); + }); break ; case 'SUBSCRIBE':
wrap requests within a dialog inside setImmediate (#<I>)
davehorton_drachtio-srf
train
f5e2a66d83d8de060183d379b6346825e47e1888
diff --git a/src/Plugin/DataType/StrawberryValuesFromJson.php b/src/Plugin/DataType/StrawberryValuesFromJson.php index <HASH>..<HASH> 100644 --- a/src/Plugin/DataType/StrawberryValuesFromJson.php +++ b/src/Plugin/DataType/StrawberryValuesFromJson.php @@ -84,7 +84,7 @@ class StrawberryValuesFromJson extends ItemList { } } else { - $this->processed = NULL; + $this->processed = []; } $this->computed = TRUE; }
If SBF value is empty, assume its processed and return []
esmero_strawberryfield
train
3ab89f0b665e1fcddbf985ea021fd570b089b158
diff --git a/src/main/java/eu/interedition/collatex2/implementation/alignment/Gap.java b/src/main/java/eu/interedition/collatex2/implementation/alignment/Gap.java index <HASH>..<HASH> 100644 --- a/src/main/java/eu/interedition/collatex2/implementation/alignment/Gap.java +++ b/src/main/java/eu/interedition/collatex2/implementation/alignment/Gap.java @@ -20,6 +20,7 @@ public class Gap implements IGap { this.nextMatchA = nextMatchA; } + //TODO: change to string of Gap @Override public String toString() { if (isAddition()) { diff --git a/src/test/java/eu/interedition/collatex2/alignment/TranspositionTest.java b/src/test/java/eu/interedition/collatex2/alignment/TranspositionTest.java index <HASH>..<HASH> 100644 --- a/src/test/java/eu/interedition/collatex2/alignment/TranspositionTest.java +++ b/src/test/java/eu/interedition/collatex2/alignment/TranspositionTest.java @@ -5,7 +5,6 @@ import java.util.List; import junit.framework.Assert; import org.junit.Before; -import org.junit.Ignore; import org.junit.Test; import eu.interedition.collatex2.implementation.Factory; @@ -55,14 +54,15 @@ public class TranspositionTest { Assert.assertEquals("b", matches.get(2).getNormalized()); } - @Ignore @Test public void testTransposition2Gaps() { final IWitness a = factory.createWitness("A", "d a b"); final IWitness b = factory.createWitness("B", "a c b d"); final IAlignment align = factory.createAlignment(a, b); final List<IGap> gaps = align.getGaps(); - // TODO: change to string of Gap - Assert.assertTrue(gaps.toString(), gaps.isEmpty()); + Assert.assertEquals(1, gaps.size()); + final IGap gap = gaps.get(0); + Assert.assertTrue(gap.isAddition()); + Assert.assertEquals("c", gap.getPhraseB().getNormalized()); } }
[RHD] Made transposition test 2 gaps work
interedition_collatex
train
5067043eeb13c2361a1cfedabddb9e3046f0c32b
diff --git a/morris/__init__.py b/morris/__init__.py index <HASH>..<HASH> 100644 --- a/morris/__init__.py +++ b/morris/__init__.py @@ -570,11 +570,12 @@ class boundmethod(object): return self.func(self.instance, *args, **kwargs) -class SignalTestCase(unittest.TestCase): +class SignalInterceptorMixIn: """ - A :class:`unittest.TestCase` subclass that simplifies testing uses of - the Morris signals. It provides three assertion methods and one utility - helper method for observing signal events. + A mix-in class for TestCase-like classes that adds extra methods for + working with and testing signals. This class may be of use if the base + TestCase class is not the standard ``unittest.TestCase`` class but the user + still wants to take advantage of the extra methods provided here. """ def _extend_state(self): @@ -665,6 +666,14 @@ class SignalTestCase(unittest.TestCase): (self._events_seen[idx] for idx in actual_order), 1)))) +class SignalTestCase(unittest.TestCase, SignalInterceptorMixIn): + """ + A :class:`unittest.TestCase` subclass that simplifies testing uses of + the Morris signals. It provides three assertion methods and one utility + helper method for observing signal events. + """ + + def remove_signals_listeners(instance): """ utility function that disconnects all listeners from all signals on an
Add SignalInterceptorMixIn This patch splits the SignalTestCase into two classes: the SignalInterceptorMixIn which can be mixed with a unittest.TestCase (or other similar class). One such mixture is the SignalTestCase itself. This is a backwards-compatibility feature for Plainbox.
zyga_morris
train
405e0aa06fe8a8702e32d2f181a5e5f699a4dfea
diff --git a/tests/run.py b/tests/run.py index <HASH>..<HASH> 100755 --- a/tests/run.py +++ b/tests/run.py @@ -16,23 +16,34 @@ import coverage from django.conf import settings from django.test.utils import get_runner +import colab.settings -def runtests(): +def runtests(test_suites=[]): if django.VERSION >= (1, 7, 0): django.setup() test_runner = get_runner(settings) - failures = test_runner(interactive=False, failfast=False).run_tests([]) + failures = test_runner(interactive=False, failfast=False).run_tests( + test_suites) sys.exit(failures) -def run_with_coverage(): +def run_with_coverage(test_suites=[]): if os.path.exists('.coverage'): os.remove('.coverage') coverage.process_startup() - runtests() + runtests(test_suites) if __name__ == '__main__': - run_with_coverage() + all_valid_apps = True + + for arg in sys.argv[1:]: + if arg not in colab.settings.INSTALLED_APPS: + print arg + " App not found" + print "Try colab." + arg + all_valid_apps = False + + if all_valid_apps: + run_with_coverage(sys.argv[1:])
Allowing run a specific test suite - Works for tests/run.py
colab_colab
train
4c758734ec1b58cd5c14062a8b502b485bdca286
diff --git a/genes/tests.py b/genes/tests.py index <HASH>..<HASH> 100644 --- a/genes/tests.py +++ b/genes/tests.py @@ -478,13 +478,16 @@ class APIResourceTestCase(ResourceTestCaseMixin, TestCase): self.gene2 = factory.create(Gene, {'standard_name': None, 'systematic_name': 'b34'}) - standard_name = 'ans' - factory.create(Gene, {'standard_name': standard_name}) + standard_name_prefix = 'ans' + factory.create(Gene, {'standard_name': standard_name_prefix}) # Create 26 more gene names that start with 'ans' and then have # an uppercase letter appended to it. for letter in string.ascii_uppercase: - factory.create(Gene, {'standard_name': standard_name + letter}) + factory.create( + Gene, + {'standard_name': standard_name_prefix + letter} + ) call_command('rebuild_index', interactive=False, verbosity=0)
Changing standard_name variable to standard_name_prefix in tests.py
greenelab_django-genes
train
b9286700efd422d4f0d45d6f2fc3834b7c830e52
diff --git a/pyecore/ecore.py b/pyecore/ecore.py index <HASH>..<HASH> 100644 --- a/pyecore/ecore.py +++ b/pyecore/ecore.py @@ -768,10 +768,10 @@ class EStructuralFeature(ETypedElement): class EAttribute(EStructuralFeature): def __init__(self, name=None, eType=None, default_value=None, lower=0, upper=1, changeable=True, derived=False, - unique=True): + unique=True, ordered=True): super().__init__(name, eType, lower=lower, upper=upper, derived=derived, changeable=changeable, - unique=unique) + unique=unique, ordered=ordered) self.default_value = default_value if not self.default_value and isinstance(eType, EDataType): self.default_value = eType.default_value
Add missing parameter for EAttribute (ordered) EAttribute can be collection, there is nothing that prevent that in Ecore. This commit enables the user to express that a collection is ordered or not.
pyecore_pyecore
train
15b87f9fb4c66c7d312eca8e507e852a9b514d77
diff --git a/lib/conceptql/operators/read.rb b/lib/conceptql/operators/read.rb index <HASH>..<HASH> 100644 --- a/lib/conceptql/operators/read.rb +++ b/lib/conceptql/operators/read.rb @@ -11,9 +11,16 @@ module ConceptQL argument :read_codes, type: :codelist, vocab: "Read" basic_type :selection category "Select by Clinical Codes" - default_query_columns def query(db) + oi_cdm? ? oi_cdm(db) : omopv4(db) + end + + def oi_cdm(db) + vocab_op.query(db) + end + + def omopv4(db) ops = codes_by_domain(db).map do |domain, codes| klasses[domain].new(self.nodifier, *codes) end @@ -24,7 +31,15 @@ module ConceptQL end def domains(db) - codes_by_domain(db).keys + oi_cdm? ? vocab_op.domains(db) : codes_by_domain(db).keys + end + + def table + vocab_op.table + end + + def query_cols + vocab_op.query_cols end private @@ -144,6 +159,10 @@ module ConceptQL :drug_concept_id end end + + def vocab_op + @vocab_op ||= Vocabulary.new(nodifier, *values, vocabulary: "Read") + end end end end
Read: hack in support for GDM
outcomesinsights_conceptql
train
f83e4b8bd340d1f8c32a61fe93f8142362851012
diff --git a/src/main/java/org/redisson/connection/MasterSlaveConnectionManager.java b/src/main/java/org/redisson/connection/MasterSlaveConnectionManager.java index <HASH>..<HASH> 100644 --- a/src/main/java/org/redisson/connection/MasterSlaveConnectionManager.java +++ b/src/main/java/org/redisson/connection/MasterSlaveConnectionManager.java @@ -102,19 +102,23 @@ public class MasterSlaveConnectionManager implements ConnectionManager { this.codec = new RedisCodecWrapper(cfg.getCodec()); } - public <T> FutureListener<T> createReleaseWriteListener(final int slot, final RedisConnection conn) { + public <T> FutureListener<T> createReleaseWriteListener(final int slot, + final RedisConnection conn, final Timeout timeout) { return new FutureListener<T>() { @Override public void operationComplete(io.netty.util.concurrent.Future<T> future) throws Exception { + timeout.cancel(); releaseWrite(slot, conn); } }; } - public <T> FutureListener<T> createReleaseReadListener(final int slot, final RedisConnection conn) { + public <T> FutureListener<T> createReleaseReadListener(final int slot, + final RedisConnection conn, final Timeout timeout) { return new FutureListener<T>() { @Override public void operationComplete(io.netty.util.concurrent.Future<T> future) throws Exception { + timeout.cancel(); releaseRead(slot, conn); } }; @@ -156,8 +160,8 @@ public class MasterSlaveConnectionManager implements ConnectionManager { asyncOperation.execute(promise, async); ex.set(new RedisTimeoutException()); - timer.newTimeout(timerTask, config.getTimeout(), TimeUnit.MILLISECONDS); - promise.addListener(createReleaseWriteListener(slot, connection)); + Timeout timeout = timer.newTimeout(timerTask, config.getTimeout(), TimeUnit.MILLISECONDS); + promise.addListener(createReleaseWriteListener(slot, connection, timeout)); } catch (RedisConnectionException e) { ex.set(e); timer.newTimeout(timerTask, config.getRetryInterval(), TimeUnit.MILLISECONDS); @@ -228,8 +232,8 @@ public class MasterSlaveConnectionManager implements ConnectionManager { asyncOperation.execute(promise, async); ex.set(new RedisTimeoutException()); - timer.newTimeout(timerTask, config.getTimeout(), TimeUnit.MILLISECONDS); - promise.addListener(createReleaseWriteListener(slot, connection)); + Timeout timeout = timer.newTimeout(timerTask, config.getTimeout(), TimeUnit.MILLISECONDS); + promise.addListener(createReleaseWriteListener(slot, connection, timeout)); } catch (RedisConnectionException e) { ex.set(e); timer.newTimeout(timerTask, config.getRetryInterval(), TimeUnit.MILLISECONDS); @@ -421,8 +425,8 @@ public class MasterSlaveConnectionManager implements ConnectionManager { asyncOperation.execute(promise, async); ex.set(new RedisTimeoutException()); - timer.newTimeout(timerTask, config.getTimeout(), TimeUnit.MILLISECONDS); - promise.addListener(createReleaseReadListener(slot, connection)); + Timeout timeout = timer.newTimeout(timerTask, config.getTimeout(), TimeUnit.MILLISECONDS); + promise.addListener(createReleaseReadListener(slot, connection, timeout)); } catch (RedisConnectionException e) { ex.set(e); timer.newTimeout(timerTask, config.getRetryInterval(), TimeUnit.MILLISECONDS);
Timeout cancellation. #<I>
redisson_redisson
train
b8e79f4344e7762baa4be19055c375b0c74d36f4
diff --git a/management_api.go b/management_api.go index <HASH>..<HASH> 100644 --- a/management_api.go +++ b/management_api.go @@ -134,6 +134,7 @@ func (e *Enforcer) AddPolicies(rules [][]string) (bool, error) { // Otherwise the function returns true by adding the new rule. func (e *Enforcer) AddNamedPolicy(ptype string, params ...interface{}) (bool, error) { if strSlice, ok := params[0].([]string); len(params) == 1 && ok { + strSlice = append(make([]string, 0, len(strSlice)), strSlice...) return e.addPolicy("p", ptype, strSlice) } policy := make([]string, 0)
fix: slice reference (#<I>)
casbin_casbin
train
8d1588e3a8257642f7d1ef471c3372392895510e
diff --git a/src/Role/ObjectRepositoryProvider.php b/src/Role/ObjectRepositoryProvider.php index <HASH>..<HASH> 100644 --- a/src/Role/ObjectRepositoryProvider.php +++ b/src/Role/ObjectRepositoryProvider.php @@ -49,7 +49,9 @@ class ObjectRepositoryProvider } } - $roles[] = new Role\Role($role->getRoleId(), $parents); + // ACL roles for parents read right to left. These are built + // left to right so reverse the array + $roles[] = new Role\Role($role->getRoleId(), array_reverse($parents)); } }
Reverse parent roles for FILO
API-Skeletons_zf-oauth2-doctrine-permissions-acl
train
68235e39bf2c594779791cf4499b7fad7a1855d3
diff --git a/safe/storage/raster.py b/safe/storage/raster.py index <HASH>..<HASH> 100644 --- a/safe/storage/raster.py +++ b/safe/storage/raster.py @@ -16,8 +16,13 @@ from safe.gis.numerics import ( geotransform_to_axes, grid_to_points ) -from safe.common.exceptions import ReadLayerError, WriteLayerError -from safe.common.exceptions import GetDataError, InaSAFEError +from safe.common.exceptions import ( + GetDataError, + InaSAFEError, + MetadataReadError, + ReadLayerError, + WriteLayerError +) from layer import Layer from vector import Vector @@ -204,8 +209,10 @@ class Raster(Layer): raise ReadLayerError(msg) # Look for any keywords - self.keywords = read_iso19115_metadata(filename) - # self.keywords = read_keywords(basename + '.keywords') + try: + self.keywords = read_iso19115_metadata(filename) + except MetadataReadError: + self.keywords = read_keywords(basename + '.keywords') # Determine name if 'title' in self.keywords: diff --git a/safe/storage/vector.py b/safe/storage/vector.py index <HASH>..<HASH> 100644 --- a/safe/storage/vector.py +++ b/safe/storage/vector.py @@ -31,9 +31,13 @@ except ImportError: import copy as copy_module from osgeo import ogr, gdal -from safe.common.exceptions import ReadLayerError, WriteLayerError -from safe.common.exceptions import GetDataError, InaSAFEError - +from safe.common.exceptions import ( + ReadLayerError, + WriteLayerError, + GetDataError, + InaSAFEError, + MetadataReadError +) from layer import Layer from projection import Projection from geometry import Polygon @@ -425,8 +429,10 @@ class Vector(Layer): base_name = os.path.splitext(filename)[0] # Look for any keywords - # self.keywords = read_keywords(base_name + '.keywords') - self.keywords = read_iso19115_metadata(filename) + try: + self.keywords = read_iso19115_metadata(filename) + except MetadataReadError: + self.keywords = read_keywords(base_name + '.keywords') # FIXME (Ole): Should also look for style file to populate style_info @@ -546,7 +552,7 @@ class Vector(Layer): # for more information if fields[name] == _pseudo_inf: fields[name] = float('nan') - # print 'Field', name, feature_type, j, fields[name] + # print 'Field', name, feature_type, j, fields[name] data.append(fields) # Store geometry coordinates as a compact numeric array diff --git a/safe/utilities/metadata.py b/safe/utilities/metadata.py index <HASH>..<HASH> 100644 --- a/safe/utilities/metadata.py +++ b/safe/utilities/metadata.py @@ -19,7 +19,7 @@ __date__ = '03/12/2015' __copyright__ = ('Copyright 2012, Australia Indonesia Facility for ' 'Disaster Reduction') import os -from safe.common.exceptions import MetadataReadError +from safe.common.exceptions import MetadataReadError, KeywordNotFoundError from safe.metadata import ExposureLayerMetadata, HazardLayerMetadata, \ AggregationLayerMetadata, ImpactLayerMetadata, GenericLayerMetadata @@ -79,10 +79,14 @@ def read_iso19115_metadata(layer_uri, keyword=None): elif metadata.layer_purpose == 'impact': metadata = ImpactLayerMetadata(layer_uri, xml_uri) + # dictionary comprehension + keywords = {x[0]: x[1]['value'] for x in metadata.dict['properties'].iteritems() if x[1]['value'] is not None} + if 'keyword_version' not in keywords.keys(): + raise MetadataReadError if keyword: try: - return metadata.dict['properties'][keyword]['value'] + return keywords['value'] except KeyError: - raise MetadataReadError - # dictionary comprehension - return {x[0]: x[1]['value'] for x in metadata.dict['properties'].iteritems() if x[1]['value'] is not None} \ No newline at end of file + raise KeywordNotFoundError + + return keywords \ No newline at end of file
Try to read .keywords file if the xml file is not compatible.
inasafe_inasafe
train
38c7b8b7c9706f35b9772ae955236b31316b4f16
diff --git a/lib/hooks/UnaryExpression.js b/lib/hooks/UnaryExpression.js index <HASH>..<HASH> 100644 --- a/lib/hooks/UnaryExpression.js +++ b/lib/hooks/UnaryExpression.js @@ -14,6 +14,8 @@ module.exports = function UnaryExpression(node) { endToken = endToken.next; } _br.limitAfter(endToken, 'DeleteOperator'); + } else if (node.operator === 'typeof') { + _ws.limitAfter(node.startToken, 1); } else { _ws.limit(node.startToken, 'UnaryExpressionOperator'); } diff --git a/test/compare/default/unary_expression-in.js b/test/compare/default/unary_expression-in.js index <HASH>..<HASH> 100644 --- a/test/compare/default/unary_expression-in.js +++ b/test/compare/default/unary_expression-in.js @@ -27,3 +27,6 @@ delete this.amet;delete this.ipsum; } typeof a === "number" ? x : y; + +var s = 'a string'; +console.log(typeof s); diff --git a/test/compare/default/unary_expression-out.js b/test/compare/default/unary_expression-out.js index <HASH>..<HASH> 100644 --- a/test/compare/default/unary_expression-out.js +++ b/test/compare/default/unary_expression-out.js @@ -29,3 +29,6 @@ function fn() { } typeof a === "number" ? x : y; + +var s = 'a string'; +console.log(typeof s);
fix the problem of incorrect handling for 'typeof'
millermedeiros_esformatter
train
85e4b8e14c736636705c9f01f084c4e61ce32c84
diff --git a/src/storage/shard.go b/src/storage/shard.go index <HASH>..<HASH> 100644 --- a/src/storage/shard.go +++ b/src/storage/shard.go @@ -419,37 +419,38 @@ func (s *shard) localShards() ([]string, error) { } // bestRole returns the best role for us to fill in the cluster right now. If -// all shards are currently assigned it returns ErrNoShards. If this node -// currently has too many shards assigned to it, it returns ErrOverallocated. +// no shards are available it returns ErrNoShards. func (s *shard) bestRole() (string, error) { masters, err := s.masters() - log.Printf("masters: %#v", masters) if err != nil { return "", err } - // First we check if there's a role we could fill. - result := "" + // First we check if there's an empty shard for i, master := range masters { - log.Printf("%d -> %s", i, master) if master == "" { - result = fmt.Sprintf("/pachyderm.io/pfs/%d-%d", i, int(s.modulos)) - break + return fmt.Sprintf("/pachyderm.io/pfs/%d-%d", i, int(s.modulos)), nil } } - log.Print("Result: ", result) - if result == "" { - return "", ErrNoShards - } - // Check that there isn't someone better to take this shard. + // No empty shard found but we can steal one counts := counts(masters) - log.Printf("counts: %#v", counts) - for _, count := range counts { - if count < counts[s.url] { - log.Print("Overallocated.") - return "", ErrOverallocated + maxHost := "" + max := 0 + for host, count := range counts { + if count > max { + maxHost = host + max = count } } - return result, nil + // the plus one prevents osscillations + if max > counts[s.url]+1 { + // this guy is loaded with shards, we're stealing one + for i, master := range masters { + if master == maxHost { + return fmt.Sprintf("/pachyderm.io/pfs/%d-%d", i, int(s.modulos)), nil + } + } + } + return "", ErrNoShards } func (s *shard) syncFromPeers() error {
Makes best role do stealing. This allows for more adaptive resharding.
pachyderm_pachyderm
train
a361fd050f490e550b7e2e5fbfea91b85ba3e879
diff --git a/src/service/translate.js b/src/service/translate.js index <HASH>..<HASH> 100644 --- a/src/service/translate.js +++ b/src/service/translate.js @@ -1179,11 +1179,11 @@ angular.module('pascalprecht.translate').provider('$translate', ['$STORAGE_KEY', * @returns translation created by $missingTranslationHandler or translationId is $missingTranslationHandler is * absent */ - var translateByHandler = function (translationId) { + var translateByHandler = function (translationId, interpolateParams) { // If we have a handler factory - we might also call it here to determine if it provides // a default text for a translationid that can't be found anywhere in our tables if ($missingTranslationHandlerFactory) { - var resultString = $injector.get($missingTranslationHandlerFactory)(translationId, $uses); + var resultString = $injector.get($missingTranslationHandlerFactory)(translationId, $uses, interpolateParams); if (resultString !== undefined) { return resultString; } else { @@ -1228,7 +1228,7 @@ angular.module('pascalprecht.translate').provider('$translate', ['$STORAGE_KEY', } else { // if no default translation is set and an error handler is defined, send it to the handler // and then return the result - deferred.resolve(translateByHandler(translationId)); + deferred.resolve(translateByHandler(translationId, interpolateParams)); } } return deferred.promise; @@ -1309,7 +1309,7 @@ angular.module('pascalprecht.translate').provider('$translate', ['$STORAGE_KEY', var missingTranslationHandlerTranslation; // for logging purposes only (as in $translateMissingTranslationHandlerLog), value is not returned to promise if ($missingTranslationHandlerFactory && !pendingLoader) { - missingTranslationHandlerTranslation = translateByHandler(translationId); + missingTranslationHandlerTranslation = translateByHandler(translationId, interpolateParams); } // since we couldn't translate the inital requested translation id, @@ -1366,7 +1366,7 @@ angular.module('pascalprecht.translate').provider('$translate', ['$STORAGE_KEY', var missingTranslationHandlerTranslation; // for logging purposes only (as in $translateMissingTranslationHandlerLog), value is not returned to promise if ($missingTranslationHandlerFactory && !pendingLoader) { - missingTranslationHandlerTranslation = translateByHandler(translationId); + missingTranslationHandlerTranslation = translateByHandler(translationId, interpolateParams); } // since we couldn't translate the inital requested translation id, @@ -1790,7 +1790,7 @@ angular.module('pascalprecht.translate').provider('$translate', ['$STORAGE_KEY', // Return translation of default interpolator if not found anything. result = defaultInterpolator.interpolate(translationId, interpolateParams); if ($missingTranslationHandlerFactory && !pendingLoader) { - result = translateByHandler(translationId); + result = translateByHandler(translationId, interpolateParams); } } diff --git a/test/unit/service/translate.spec.js b/test/unit/service/translate.spec.js index <HASH>..<HASH> 100644 --- a/test/unit/service/translate.spec.js +++ b/test/unit/service/translate.spec.js @@ -1454,8 +1454,8 @@ describe('pascalprecht.translate', function () { .useMissingTranslationHandler('customHandler'); $provide.factory('customHandler', function () { - return function (translationId, language) { - missingTranslations[translationId] = { lang: language }; + return function (translationId, language, params) { + missingTranslations[translationId] = { lang: language, params: params }; }; }); @@ -1473,10 +1473,23 @@ describe('pascalprecht.translate', function () { }); it('should invoke missingTranslationHandler if set and translation id doesn\'t exist', function () { - $translate('NOT_EXISTING_TRANSLATION_ID'); + $translate('NOT_EXISTING_TRANSLATION_ID', {}); expect(missingTranslations).toEqual({ 'NOT_EXISTING_TRANSLATION_ID': { - lang: 'en' + lang: 'en', + params: {} + } + }); + }); + + it('should pass on interpolationParams to missingTranslationHandler', function () { + $translate('NOT_EXISTING_TRANSLATION_ID', {name: 'name'}); + expect(missingTranslations).toEqual({ + 'NOT_EXISTING_TRANSLATION_ID': { + lang: 'en', + params: { + name: 'name' + } } }); });
feat(missingTranslationHandlerFactory): pass interpolationParams to missingTranslationHandlerFactory Sometimes these parameters are needed as they determine parts of the translation. When generating a new translation key and re-translating these are needed.
angular-translate_angular-translate
train
026ca2db87b4927d65a3ee0c52a1d0de5f6b207b
diff --git a/lib/flatiron/plugins/resourceful.js b/lib/flatiron/plugins/resourceful.js index <HASH>..<HASH> 100644 --- a/lib/flatiron/plugins/resourceful.js +++ b/lib/flatiron/plugins/resourceful.js @@ -94,6 +94,8 @@ exports.init = function (done) { app.config.get('resourceful') || {} ); + app.config.set('resourceful', options); + // // Remark: Should we accept the autoMigrate option? //
[fix] Set the `resourceful` config value in the app from provided options
flatiron_flatiron
train
ddcf7f2182f72bcc35e1ef54a6df6f091ef9d36a
diff --git a/Lib/fontbakery/testrunner.py b/Lib/fontbakery/testrunner.py index <HASH>..<HASH> 100644 --- a/Lib/fontbakery/testrunner.py +++ b/Lib/fontbakery/testrunner.py @@ -589,7 +589,10 @@ class TestRunner(object): # nestable subtests. Otherwise, a STARTTEST would end the # previous test implicitly. # We can also use it to display status updates to the user. - if summary_status < PASS: + if summary_status is None: + summary_status = ERROR + yield ERROR, ('The check {} did not yield any status'.format(test)) + elif summary_status < PASS: summary_status = ERROR # got to yield it,so we can see it in the report yield ERROR, ('The most significant status of {} was only {} but the '
[testrunner] FIX: ERROR if no status was returned by check (did break the process)
googlefonts_fontbakery
train
cce095f4be1a74994e9cb6b4f087fc58658aa48d
diff --git a/compliance_checker/__init__.py b/compliance_checker/__init__.py index <HASH>..<HASH> 100644 --- a/compliance_checker/__init__.py +++ b/compliance_checker/__init__.py @@ -1,3 +1,4 @@ -__import__('pkg_resources').declare_namespace(__name__) +from pkgutil import extend_path +__path__ = extend_path(__path__, __name__) __version__="0.1"
More correct way of doing namespace packages?
ioos_compliance-checker
train
27ec190e4362d083910bbec79c80a38adaf1d313
diff --git a/client/state/posts/test/actions.js b/client/state/posts/test/actions.js index <HASH>..<HASH> 100644 --- a/client/state/posts/test/actions.js +++ b/client/state/posts/test/actions.js @@ -570,8 +570,6 @@ describe( 'actions', () => { name: 'ribs', description: '' } ], - query: undefined, - found: undefined, postId: 13640 } ); } ); diff --git a/client/state/test/utils.js b/client/state/test/utils.js index <HASH>..<HASH> 100644 --- a/client/state/test/utils.js +++ b/client/state/test/utils.js @@ -31,28 +31,50 @@ describe( 'utils', () => { } ); describe( 'extendAction()', () => { - it( 'should return an updated action object', () => { + it( 'should return an updated action object, merging data', () => { const action = extendAction( { - type: 'ACTION_TEST' - }, { ok: true } ); + type: 'ACTION_TEST', + meta: { + preserve: true + } + }, { + meta: { + ok: true + } + } ); expect( action ).to.eql( { type: 'ACTION_TEST', - ok: true + meta: { + preserve: true, + ok: true + } } ); } ); - it( 'should return an updated action thunk', () => { + it( 'should return an updated action thunk, merging data on dispatch', () => { const dispatch = spy(); const action = extendAction( - ( thunkDispatch ) => thunkDispatch( { type: 'ACTION_TEST' } ), - { ok: true } + ( thunkDispatch ) => thunkDispatch( { + type: 'ACTION_TEST', + meta: { + preserve: true + } + } ), + { + meta: { + ok: true + } + } ); action( dispatch ); expect( dispatch ).to.have.been.calledWithExactly( { type: 'ACTION_TEST', - ok: true + meta: { + preserve: true, + ok: true + } } ); } ); } ); diff --git a/client/state/utils.js b/client/state/utils.js index <HASH>..<HASH> 100644 --- a/client/state/utils.js +++ b/client/state/utils.js @@ -2,6 +2,7 @@ * External dependencies */ import tv4 from 'tv4'; +import { merge } from 'lodash'; /** * Internal dependencies @@ -34,11 +35,11 @@ export function isValidStateWithSchema( state, schema, checkForCycles = false, b */ export function extendAction( action, data ) { if ( 'function' !== typeof action ) { - return { ...action, ...data }; + return merge( {}, action, data ); } return ( dispatch ) => { - const newDispatch = ( thunkAction ) => dispatch( { ...thunkAction, ...data } ); + const newDispatch = ( thunkAction ) => dispatch( merge( {}, thunkAction, data ) ); return action( newDispatch ); }; }
State: Merge into extended action to preserve structure
Automattic_wp-calypso
train
1ae2f1cb875e60d6b2af7605304f0eefa44da184
diff --git a/js/hitbtc.js b/js/hitbtc.js index <HASH>..<HASH> 100644 --- a/js/hitbtc.js +++ b/js/hitbtc.js @@ -322,11 +322,13 @@ module.exports = class hitbtc extends Exchange { return { 'info': response, 'id': id, - 'status': undefined, - 'fromAccount': fromAccount, - 'toAccount': toAccount, + 'timestamp': undefined, + 'datetime': undefined, 'amount': requestAmount, 'currency': code, + 'fromAccount': fromAccount, + 'toAccount': toAccount, + 'status': undefined, }; }
hitbtc unified transfer structure
ccxt_ccxt
train
76228c5654e4b7d031a9141b2974cf420b5a78cd
diff --git a/data/php b/data/php index <HASH>..<HASH> 100755 --- a/data/php +++ b/data/php @@ -53,5 +53,7 @@ if (isset($_SERVER['XDEBUG_CONFIG'])) { $env = "XDEBUG_CONFIG='" . $_SERVER['XDEBUG_CONFIG'] . "'"; } +$includePaths = array('.', $projectDirGuest . '/vendor/phpunit/phpunit'); +$arguments = array_merge(array('-d', 'include_path=' . implode(':', $includePaths)), $arguments); passthru($pipe . '"' . $env . ' php ' . implode(' ', $arguments) . '"');
Set php include_path to composer vendor phpunit
cargomedia_vagrant-phpstorm-tunnel
train
66d6331d0b1271922de6d073f452aab016be91c0
diff --git a/test/unexpected-sinon.spec.js b/test/unexpected-sinon.spec.js index <HASH>..<HASH> 100644 --- a/test/unexpected-sinon.spec.js +++ b/test/unexpected-sinon.spec.js @@ -543,7 +543,8 @@ describe('unexpected-sinon', function () { "\n" + "invocations(\n" + " stub() at theFunction (theFileName:xx:yy),\n" + - " stub() at theFunction (theFileName:xx:yy) // expected: threw { name: 'Error' }\n" + " // expected TypeError() to satisfy { name: 'Error' }\n" + + " stub() at theFunction (theFileName:xx:yy) // expected: threw { name: 'Error' }\n" + + " // expected TypeError() to satisfy { name: 'Error' }\n" + " //\n" + " // {\n" + " // message: '',\n" +
Test: Added missing newline.
unexpectedjs_unexpected-sinon
train
f31eb866b751831bc9c735d5998d31a58cf93fe6
diff --git a/src/components/validity/methods-validate.js b/src/components/validity/methods-validate.js index <HASH>..<HASH> 100644 --- a/src/components/validity/methods-validate.js +++ b/src/components/validity/methods-validate.js @@ -17,7 +17,7 @@ function isPromise (p: Object): boolean { export default function (Vue: GlobalAPI): Object { function resolveValidator (name: string): ValidatorAsset | void { - const { resolveAsset } = Vue.util + const { resolveAsset } = this.constructor.util return resolveAsset(this.$options, 'validators', name) } @@ -26,7 +26,7 @@ export default function (Vue: GlobalAPI): Object { field: string, value: any ): ValidateDescriptor | null { - const { isPlainObject } = Vue.util + const { isPlainObject } = this.constructor.util const asset: ValidatorAsset = this.resolveValidator(validator) if (!asset) {
:shirt: refactor: use vue utlity via from constructor
kazupon_vue-validator
train
6166bd2b54af9eb15cfb7c8ae2fe2e168cf0f57b
diff --git a/tests/web_api/conftest.py b/tests/web_api/conftest.py index <HASH>..<HASH> 100644 --- a/tests/web_api/conftest.py +++ b/tests/web_api/conftest.py @@ -42,12 +42,12 @@ Person = build_entity( is_person = True, ) -@pytest.fixture(scope="module") +@pytest.fixture(scope="package") def entities(): return [Household, Person] -@pytest.fixture() +@pytest.fixture(scope="package") def test_tax_benefit_system(entities): tax_benefit_system = TaxBenefitSystem(entities)
Fix // Change fixture scope to "package" to prevent recreating fixture objects for every single test
openfisca_openfisca-core
train
44bc594e5c18be991f0f08e7080ca98ece0d4f12
diff --git a/src/Connection.php b/src/Connection.php index <HASH>..<HASH> 100644 --- a/src/Connection.php +++ b/src/Connection.php @@ -113,7 +113,7 @@ class Connection $this->options[CURLOPT_HTTPHEADER] = []; } - $this->options[CURLOPT_HTTPHEADER][] = ["X-UW-ACT-AS: $user"]; + $this->options[CURLOPT_HTTPHEADER][] = "X-UW-ACT-AS: $user"; } } diff --git a/test/ConnectionTest.php b/test/ConnectionTest.php index <HASH>..<HASH> 100644 --- a/test/ConnectionTest.php +++ b/test/ConnectionTest.php @@ -115,4 +115,20 @@ class ConnectionTest extends PHPUnit_Framework_TestCase $this->assertEquals(1, $connection->getOptions()[CURLOPT_POST]); } + + public function testXUwActAs() + { + $connection = $this->makeConnection(); + + $user = "u" . (string)rand(); + + $_SERVER["REMOTE_USER"] = $user; + + $resp = $connection->execGET("person-javerage-full.json", ["first" => 1, "second" => 2]); + $resp = json_decode($resp, true); + + $this->assertEquals("James Average Student", $resp["DisplayName"]); + + $this->assertContains("X-UW-ACT-AS: $user", $connection->getOptions()[CURLOPT_HTTPHEADER]); + } } \ No newline at end of file
Test inclusion of X-UW-Act-As header.
UWEnrollmentManagement_Connection
train
9b25cdc1623188ef7f5b0ddc262409d022996d87
diff --git a/src/Cursor.js b/src/Cursor.js index <HASH>..<HASH> 100644 --- a/src/Cursor.js +++ b/src/Cursor.js @@ -17,13 +17,68 @@ export default class Cursor { * Creates cursor that writes direct to `stdout`. * * @constructor + * @param {Terminal} terminal Terminal instance to which cursor will be assigned */ - constructor() { - this._x = 0; - this._y = 0; - this._background = false; - this._foreground = false; - this._display = {bold: false, dim: false, underlined: false, blink: false, reverse: false, hidden: false}; + constructor(terminal) { + this.setTerminal(terminal); + this.setX(0); + this.setY(0); + this.setBackground(false); + this.setForeground(false); + this.setDisplay(false); + } + + getTerminal() { + return this._terminal; + } + + setTerminal(terminal) { + this._terminal = terminal; + return this; + } + + getX() { + return this._x; + } + + setX(x) { + this._x = Math.floor(x); + return this; + } + + getY() { + return this._y; + } + + setY(y) { + this._y = Math.floor(y); + } + + getBackground() { + return this._background; + } + + setBackground(background) { + this._background = Color.create(background).toRgb(); + return this; + } + + getForeground() { + return this._foreground; + } + + setForeground(foreground) { + this._foreground = Color.create(foreground).toRgb(); + return this; + } + + getDisplay() { + return this._display; + } + + setDisplay(display) { + this._display = display; + return this; } /**
refactor(cursor): Add accessors to cursor properties
kittikjs_cursor
train
17b0ed5d5d57f9f719cac8b40a23c27341899e76
diff --git a/cartoframes/viz/layer.py b/cartoframes/viz/layer.py index <HASH>..<HASH> 100644 --- a/cartoframes/viz/layer.py +++ b/cartoframes/viz/layer.py @@ -17,7 +17,9 @@ except ImportError: class Layer(object): - """Layer + """Layer to display data on a map. This class can be used as one or more + layers on :py:class`Map <cartoframes.viz.Map>` or on its own in a Jupyter + notebook to get a preview of a Layer. Args: source (str, :py:class:`Dataset <cartoframes.data.Dataset>`): @@ -45,14 +47,16 @@ class Layer(object): Example: + Create a layer with a custom popup, legend, and widget. + .. code:: from cartoframes.auth import set_default_context from cartoframes.viz import Layer set_default_context( - base_url='https://your_user_name.carto.com', - api_key='your api key' + base_url='https://cartovl.carto.com', + api_key='default_public' ) Layer( @@ -68,29 +72,51 @@ class Layer(object): }, widgets=[{ 'type': 'formula', - 'title': 'Avg $pop_max' + 'title': 'Avg $pop_max', 'value': 'viewportAvg($pop_max)' }] ) - Setting the context. + Create a layer specifically tied to a :py:class:`Context + <cartoframes.auth.Context>` and display it on a map. .. code:: from cartoframes.auth import Context - from cartoframes.viz import Layer + from cartoframes.viz import Layer, Map context = Context( base_url='https://your_user_name.carto.com', api_key='your api key' ) - Layer( + pop_layer = Layer( 'populated_places', - 'color: "red"', + 'color: red', context=context ) + Map(pop_layer) + + Preview a layer in a Jupyter notebook. Note: if in a Jupyter notebook, + it is not required to explicitly add a Layer to a :py:class:`Map + <cartoframes.viz.Map>` if only visualizing data as a single layer. + .. code:: + + from cartoframes.auth import set_default_context + from cartoframes.viz import Layer, Map + + set_default_context('https://cartoframes.carto.com') + + pop_layer = Layer( + 'brooklyn_poverty', + 'color: ramp($poverty_per_pop, sunset)', + legend={ + 'type': 'color-continuous', + 'title': 'Poverty per pop' + } + ) + pop_layer """ def __init__(self,
adds more info in docs about repr html
CartoDB_cartoframes
train
5fee81ff08c2f03e020406c97b3243aef0d1061b
diff --git a/src/Model.js b/src/Model.js index <HASH>..<HASH> 100644 --- a/src/Model.js +++ b/src/Model.js @@ -22,6 +22,8 @@ let _serialize = function (model, pojo, options) { let props = model.serializeProperties || model.properties; + props = props.filter(prop => (!model.propertyOptions[prop] || model.propertyOptions[prop].serialize !== false)); + props.forEach(key => { let obj = model[key]; @@ -593,7 +595,7 @@ Model.deserialize = function(pojo, options = {}) { let properties = newInstance.properties; properties.forEach(key => { - if (pojo[key] && (!newInstance.propertyOptions[key] || newInstance.propertyOptions[key].serialize !== false)) { + if (pojo.hasOwnProperty(key) && (!newInstance.propertyOptions[key] || newInstance.propertyOptions[key].serialize !== false)) { newInstance[key] = _deserializePOJOValue(newInstance, key, pojo[key]); } });
Fixing a tiny bug where deserialization wasn't working with empty strings
ringa-js_ringa
train
56d72dfc34037984c95f1a833b9f4867aa61a6da
diff --git a/lib/active_bugzilla/service.rb b/lib/active_bugzilla/service.rb index <HASH>..<HASH> 100644 --- a/lib/active_bugzilla/service.rb +++ b/lib/active_bugzilla/service.rb @@ -59,10 +59,10 @@ module ActiveBugzilla end def https? - URI.parse(self.bugzilla_uri).scheme == 'https' + URI.parse(bugzilla_uri).scheme == 'https' end - def initialize(bugzilla_uri, username, password, options={}) + def initialize(bugzilla_uri, username, password, options = {}) raise ArgumentError, "username and password must be set" if username.nil? || password.nil? self.bugzilla_uri = bugzilla_uri @@ -189,7 +189,7 @@ module ActiveBugzilla DEFAULT_OPTIONS = { :cgi_path => '/xmlrpc.cgi', - :timeout => 120 + :timeout => 120 } def xmlrpc_client
Fix 3 "offenses" detected by rubocop.
ManageIQ_active_bugzilla
train
3bb81d033bcd5e907af1a5a5cf3589031f6aa2c2
diff --git a/lib/oembed/provider.rb b/lib/oembed/provider.rb index <HASH>..<HASH> 100644 --- a/lib/oembed/provider.rb +++ b/lib/oembed/provider.rb @@ -126,14 +126,20 @@ module OEmbed # @deprecated *Note*: This method will be made private in the future. def raw(url, query = {}) uri = build(url, query) - + self.class.http_get(uri, query) + rescue OEmbed::UnknownFormat + # raise with format to be backward compatible + raise OEmbed::UnknownFormat, format + end + + def self.http_get(uri, options) found = false max_redirects = 4 until found http = Net::HTTP.new(uri.host, uri.port) http.use_ssl = uri.scheme == 'https' http.verify_mode = OpenSSL::SSL::VERIFY_PEER - http.read_timeout = http.open_timeout = query[:timeout] if query[:timeout] + http.read_timeout = http.open_timeout = options[:timeout] if options[:timeout] %w{scheme userinfo host port registry}.each { |method| uri.send("#{method}=", nil) } req = Net::HTTP::Get.new(uri.to_s) @@ -152,9 +158,9 @@ module OEmbed case res when Net::HTTPNotImplemented - raise OEmbed::UnknownFormat, format + raise OEmbed::UnknownFormat when Net::HTTPNotFound - raise OEmbed::NotFound, url + raise OEmbed::NotFound, uri when Net::HTTPSuccess res.body else diff --git a/lib/oembed/provider_discovery.rb b/lib/oembed/provider_discovery.rb index <HASH>..<HASH> 100644 --- a/lib/oembed/provider_discovery.rb +++ b/lib/oembed/provider_discovery.rb @@ -27,47 +27,31 @@ module OEmbed def discover_provider(url, options = {}) uri = URI.parse(url) + res = Provider.http_get(uri, options) + format = options[:format] - http = Net::HTTP.new(uri.host, uri.port) - http.use_ssl = uri.scheme == 'https' - http.verify_mode = OpenSSL::SSL::VERIFY_PEER - res = http.get(uri.request_uri) + if format.nil? || format == :json + provider_endpoint ||= /<link.*href=['"]*([^\s'"]+)['"]*.*application\/json\+oembed.*>/.match(res)[1] rescue nil + provider_endpoint ||= /<link.*application\/json\+oembed.*href=['"]*([^\s'"]+)['"]*.*>/.match(res)[1] rescue nil + format ||= :json if provider_endpoint + end + if format.nil? || format == :xml + # {The specification}[http://oembed.com/#section4] says XML discovery should have + # type="text/xml+oembed" but some providers use type="application/xml+oembed" + provider_endpoint ||= /<link.*href=['"]*([^\s'"]+)['"]*.*(application|text)\/xml\+oembed.*>/.match(res)[1] rescue nil + provider_endpoint ||= /<link.*(application|text)\/xml\+oembed.*href=['"]*([^\s'"]+)['"]*.*>/.match(res)[2] rescue nil + format ||= :xml if provider_endpoint + end - case res - when Net::HTTPNotFound + begin + provider_endpoint = URI.parse(provider_endpoint) + provider_endpoint.query = nil + provider_endpoint = provider_endpoint.to_s + rescue URI::Error raise OEmbed::NotFound, url - when Net::HTTPRedirection - options[:redirect_counter] ||= 0 - raise OEmbed::TooManyRedirects if (options[:redirect_counter] += 1) == 5 - discover_provider(res['location'], options) - when Net::HTTPSuccess - format = options[:format] - - if format.nil? || format == :json - provider_endpoint ||= /<link.*href=['"]*([^\s'"]+)['"]*.*application\/json\+oembed.*>/.match(res.body)[1] rescue nil - provider_endpoint ||= /<link.*application\/json\+oembed.*href=['"]*([^\s'"]+)['"]*.*>/.match(res.body)[1] rescue nil - format ||= :json if provider_endpoint - end - if format.nil? || format == :xml - # {The specification}[http://oembed.com/#section4] says XML discovery should have - # type="text/xml+oembed" but some providers use type="application/xml+oembed" - provider_endpoint ||= /<link.*href=['"]*([^\s'"]+)['"]*.*(application|text)\/xml\+oembed.*>/.match(res.body)[1] rescue nil - provider_endpoint ||= /<link.*(application|text)\/xml\+oembed.*href=['"]*([^\s'"]+)['"]*.*>/.match(res.body)[2] rescue nil - format ||= :xml if provider_endpoint - end - - begin - provider_endpoint = URI.parse(provider_endpoint) - provider_endpoint.query = nil - provider_endpoint = provider_endpoint.to_s - rescue URI::Error - raise OEmbed::NotFound, url - end - - Provider.new(provider_endpoint, format || OEmbed::Formatter.default) - else - raise OEmbed::UnknownResponse, res.code end + + Provider.new(provider_endpoint, format || OEmbed::Formatter.default) end end
extract http get class method and reuse in provider discovery
ruby-oembed_ruby-oembed
train
05063fb3d3b5be302ff375884ef45d5bd1e25f60
diff --git a/lib/mongoid/contexts/enumerable.rb b/lib/mongoid/contexts/enumerable.rb index <HASH>..<HASH> 100644 --- a/lib/mongoid/contexts/enumerable.rb +++ b/lib/mongoid/contexts/enumerable.rb @@ -5,7 +5,7 @@ module Mongoid #:nodoc: include Paging attr_reader :selector, :options, :documents - delegate :first, :last, :to => :documents + delegate :first, :last, :to => :execute # Return aggregation counts of the grouped documents. This will count by # the first field provided in the fields array. @@ -80,9 +80,7 @@ module Mongoid #:nodoc: # Returns: # # The first document in the +Array+ - def one - @documents.first - end + alias :one :first # Get the sum of the field values for all the documents. # diff --git a/spec/unit/mongoid/contexts/enumerable_spec.rb b/spec/unit/mongoid/contexts/enumerable_spec.rb index <HASH>..<HASH> 100644 --- a/spec/unit/mongoid/contexts/enumerable_spec.rb +++ b/spec/unit/mongoid/contexts/enumerable_spec.rb @@ -8,7 +8,7 @@ describe Mongoid::Contexts::Enumerable do @melbourne = Address.new(:number => 20, :street => "Bourke Street") @new_york = Address.new(:number => 20, :street => "Broadway") @docs = [ @london, @shanghai, @melbourne, @new_york ] - @selector = { :street => "Bond Street" } + @selector = { :street => "Bourke Street" } @options = { :fields => [ :number ] } @context = Mongoid::Contexts::Enumerable.new(@selector, @options, @docs) end @@ -41,15 +41,18 @@ describe Mongoid::Contexts::Enumerable do describe "#execute" do it "returns the matching documents from the array" do - @context.execute.should == [ @london ] + @context.execute.should == [ @melbourne ] end end describe "#first" do - it "returns the first in the enumerable" do - @context.first.should == @london + context "when a selector is present" do + + it "returns the first that matches the selector" do + @context.first.should == @melbourne + end end end @@ -98,8 +101,8 @@ describe Mongoid::Contexts::Enumerable do describe "#last" do - it "returns the last in the enumerable" do - @context.last.should == @new_york + it "returns the last matching in the enumerable" do + @context.last.should == @melbourne end end @@ -122,8 +125,8 @@ describe Mongoid::Contexts::Enumerable do describe "#one" do - it "returns the first in the enumerable" do - @context.one.should == @london + it "returns the first matching in the enumerable" do + @context.one.should == @melbourne end end
Fixing enumerable context first, one and last ignoring selector
mongodb_mongoid
train
f083a06f3f97c34079a7d37692f2968df24fe8ff
diff --git a/view/ViewableData.php b/view/ViewableData.php index <HASH>..<HASH> 100644 --- a/view/ViewableData.php +++ b/view/ViewableData.php @@ -93,7 +93,18 @@ class ViewableData extends Object implements IteratorAggregate { * @return bool */ public function __isset($property) { - return $this->hasField($property) || ($this->failover && $this->failover->hasField($property)); + // getField() isn't a field-specific getter and shouldn't be treated as such + if (strtolower($property) !== 'field' && $this->hasMethod($method = "get$property")) { + return true; + + } elseif ($this->hasField($property)) { + return true; + + } elseif ($this->failover) { + return isset($this->failover->$property); + } + + return false; } /** @@ -104,13 +115,17 @@ class ViewableData extends Object implements IteratorAggregate { * @return mixed */ public function __get($property) { - if($this->hasMethod($method = "get$property")) { + // getField() isn't a field-specific getter and shouldn't be treated as such + if (strtolower($property) !== 'field' && $this->hasMethod($method = "get$property")) { return $this->$method(); - } elseif($this->hasField($property)) { + + } elseif ($this->hasField($property)) { return $this->getField($property); - } elseif($this->failover) { + + } elseif ($this->failover) { return $this->failover->$property; } + return null; } /**
FIX: Fix ViewableData::__isset() for getXXX() getters. PHP7 is stricter about this. Manual cherry-pick of of c<I>a<I>c7f<I>ab4ce1f<I>ccbc5b<I>fcaf
silverstripe_silverstripe-framework
train
ab5e2f91c1868b2dafcece44b753ce1242f58ad7
diff --git a/robovm/src/playn/robovm/RoboAudio.java b/robovm/src/playn/robovm/RoboAudio.java index <HASH>..<HASH> 100644 --- a/robovm/src/playn/robovm/RoboAudio.java +++ b/robovm/src/playn/robovm/RoboAudio.java @@ -159,6 +159,10 @@ public class RoboAudio extends Audio { } } + void delete(RoboSoundOAL sound) { + alDeleteBuffer(sound.bufferId()); + } + void setLooping(int sourceIdx, RoboSoundOAL sound, boolean looping) { if (active[sourceIdx] == sound) { alSourcei(sources[sourceIdx], AL_LOOPING, looping ? AL_TRUE : AL_FALSE); diff --git a/robovm/src/playn/robovm/RoboSoundOAL.java b/robovm/src/playn/robovm/RoboSoundOAL.java index <HASH>..<HASH> 100644 --- a/robovm/src/playn/robovm/RoboSoundOAL.java +++ b/robovm/src/playn/robovm/RoboSoundOAL.java @@ -69,7 +69,6 @@ public class RoboSoundOAL extends SoundImpl<Integer> { @Override protected void releaseImpl() { - // TODO - // AL.DeleteBuffer(impl); + audio.delete(this); } }
Delete OAL buffers on release.
playn_playn
train
02d5dff0b2195d4e8b60ba08ec30fa6f30f78cd5
diff --git a/pom.xml b/pom.xml index <HASH>..<HASH> 100644 --- a/pom.xml +++ b/pom.xml @@ -26,7 +26,7 @@ <jdk.version>1.6</jdk.version> <release.description> \+ Added 1Ex.Trade, BitMEX, Coinsquare and EmpoEX. - \* Fixed AllCoin and CryptoFacilities. + \* Fixed AllCoin, CryptoFacilities and NXT Asset Exchange. \- Removed 796 Exchange, Banx Capital, Basebit, Bitspark, Carvitrex, CleverCoin, Coinsetter, Cointrader, Coins-E, Cryptsy and OneWorldCoin. </release.description> </properties> diff --git a/src/main/java/mobi/boilr/libdynticker/exchanges/NXTAssetExchange.java b/src/main/java/mobi/boilr/libdynticker/exchanges/NXTAssetExchange.java index <HASH>..<HASH> 100644 --- a/src/main/java/mobi/boilr/libdynticker/exchanges/NXTAssetExchange.java +++ b/src/main/java/mobi/boilr/libdynticker/exchanges/NXTAssetExchange.java @@ -6,13 +6,13 @@ import java.util.ArrayList; import java.util.Iterator; import java.util.List; +import org.codehaus.jackson.JsonNode; + import mobi.boilr.libdynticker.core.Exchange; import mobi.boilr.libdynticker.core.Pair; -import org.codehaus.jackson.JsonNode; - public final class NXTAssetExchange extends Exchange { - private static final String peer = "https://verification.secureae.com/nxt?requestType="; + private static final String peer = "http://humanoide.thican.net:7876/nxt?requestType="; public NXTAssetExchange(long expiredPeriod) { super("NXT Asset Exchange", expiredPeriod); diff --git a/src/test/java/mobi/boilr/libdynticker/exchanges/NXTAssetExchangeTest.java b/src/test/java/mobi/boilr/libdynticker/exchanges/NXTAssetExchangeTest.java index <HASH>..<HASH> 100644 --- a/src/test/java/mobi/boilr/libdynticker/exchanges/NXTAssetExchangeTest.java +++ b/src/test/java/mobi/boilr/libdynticker/exchanges/NXTAssetExchangeTest.java @@ -4,9 +4,6 @@ import java.io.File; import java.io.IOException; import java.util.List; -import mobi.boilr.libdynticker.core.ExchangeTest; -import mobi.boilr.libdynticker.core.Pair; - import org.codehaus.jackson.JsonNode; import org.codehaus.jackson.map.ObjectMapper; import org.junit.After; @@ -14,6 +11,9 @@ import org.junit.Assert; import org.junit.Before; import org.junit.Test; +import mobi.boilr.libdynticker.core.ExchangeTest; +import mobi.boilr.libdynticker.core.Pair; + public class NXTAssetExchangeTest extends ExchangeTest { @Override @Before @@ -25,12 +25,13 @@ public class NXTAssetExchangeTest extends ExchangeTest { @After public void tearDown() throws Exception {} + @Override @Test public void testGetPairs() { List<Pair> pairs; try { pairs = testExchange.getPairs(); - Assert.assertTrue(pairs.contains(new Pair("mgwBTC", "NXT"))); + Assert.assertTrue(pairs.contains(new Pair("nXtGenGHS", "NXT"))); Assert.assertFalse(pairs.contains(new Pair("Invalid", "NXT"))); } catch(IOException e) { Assert.fail();
Updated peer for NXT Asset Exchange.
drpout_libdynticker
train
54afc0e3c736157d9bfa33c2230c9f6b7fdd6259
diff --git a/mgmt/rest/rest_v1_test.go b/mgmt/rest/rest_v1_test.go index <HASH>..<HASH> 100644 --- a/mgmt/rest/rest_v1_test.go +++ b/mgmt/rest/rest_v1_test.go @@ -55,17 +55,26 @@ type restAPIInstance struct { server *Server } -func startV1API(cfg *mockConfig) *restAPIInstance { +func startV1API(cfg *mockConfig, testType string) *restAPIInstance { log.SetLevel(LOG_LEVEL) r, _ := New(cfg.RestAPI) - mockMetricManager := &fixtures.MockManagesMetrics{} - mockTaskManager := &fixtures.MockTaskManager{} - mockConfigManager := &fixtures.MockConfigManager{} - mockTribeManager := &fixtures.MockTribeManager{} - r.BindMetricManager(mockMetricManager) - r.BindTaskManager(mockTaskManager) - r.BindConfigManager(mockConfigManager) - r.BindTribeManager(mockTribeManager) + switch testType { + case "tribe": + mockTribeManager := &fixtures.MockTribeManager{} + r.BindTribeManager(mockTribeManager) + case "plugin": + mockMetricManager := &fixtures.MockManagesMetrics{} + mockConfigManager := &fixtures.MockConfigManager{} + r.BindMetricManager(mockMetricManager) + r.BindConfigManager(mockConfigManager) + case "metric": + mockMetricManager := &fixtures.MockManagesMetrics{} + r.BindMetricManager(mockMetricManager) + case "task": + mockTaskManager := &fixtures.MockTaskManager{} + r.BindTaskManager(mockTaskManager) + } + go func(ch <-chan error) { // Block on the error channel. Will return exit status 1 for an error or // just return if the channel closes. @@ -83,11 +92,9 @@ func startV1API(cfg *mockConfig) *restAPIInstance { } } -func TestV1(t *testing.T) { - r := startV1API(getDefaultMockConfig()) - Convey("Test REST API V1", t, func() { - - //////////TEST-PLUGIN-ROUTES///////////////// +func TestV1Plugin(t *testing.T) { + r := startV1API(getDefaultMockConfig(), "plugin") + Convey("Test Plugin REST API V1", t, func() { Convey("Get plugins - v1/plugins", func() { resp, err := http.Get( fmt.Sprintf("http://localhost:%d/v1/plugins", r.port)) @@ -264,9 +271,12 @@ func TestV1(t *testing.T) { string(body)) }) + }) +} - //////////TEST-METRIC-ROUTES///////////////// - +func TestV1Metric(t *testing.T) { + r := startV1API(getDefaultMockConfig(), "metric") + Convey("Test Metric REST API V1", t, func() { Convey("Get metrics - v1/metrics", func() { resp, err := http.Get( fmt.Sprintf("http://localhost:%d/v1/metrics", r.port)) @@ -296,9 +306,12 @@ func TestV1(t *testing.T) { ShouldResemble, resp1) }) + }) +} - //////////TEST-TASK-ROUTES///////////////// - +func TestV1Task(t *testing.T) { + r := startV1API(getDefaultMockConfig(), "task") + Convey("Test Task REST API V1", t, func() { Convey("Get tasks - v1/tasks", func() { resp, err := http.Get( fmt.Sprintf("http://localhost:%d/v1/tasks", r.port)) @@ -452,9 +465,12 @@ func TestV1(t *testing.T) { ShouldResemble, string(body)) }) + }) +} - //////////TEST-TRIBE-ROUTES///////////////// - +func TestV1Tribe(t *testing.T) { + r := startV1API(getDefaultMockConfig(), "tribe") + Convey("Test Tribe REST API V1", t, func() { Convey("Get tribe agreements - v1/tribe/agreements", func() { resp, err := http.Get( fmt.Sprintf("http://localhost:%d/v1/tribe/agreements", r.port)) @@ -511,6 +527,20 @@ func TestV1(t *testing.T) { string(body)) }) + Convey("Get tribe member - v1/tribe/member/:name", func() { + tribeName := "Imma_Mock" + resp, err := http.Get( + fmt.Sprintf("http://localhost:%d/v1/tribe/member/%s", r.port, tribeName)) + So(err, ShouldBeNil) + So(resp.StatusCode, ShouldEqual, 200) + body, err := ioutil.ReadAll(resp.Body) + So(err, ShouldBeNil) + So( + fmt.Sprintf(fixtures.GET_TRIBE_MEMBER_NAME), + ShouldResemble, + string(body)) + }) + Convey("Delete tribe agreement - v1/tribe/agreements/:name", func() { c := &http.Client{} tribeName := "Agree1"
Improved readability of v1 tests: - Divided Plugin, Tribe, Metric, and Config tests into separate methods. - Added missing v1 test for tribe/member/:name
intelsdi-x_snap
train
8e3fc6d7b93675755232f4c5f983786b8858d1cf
diff --git a/bundles/org.eclipse.orion.client.ui/web/orion/section.js b/bundles/org.eclipse.orion.client.ui/web/orion/section.js index <HASH>..<HASH> 100644 --- a/bundles/org.eclipse.orion.client.ui/web/orion/section.js +++ b/bundles/org.eclipse.orion.client.ui/web/orion/section.js @@ -129,6 +129,9 @@ define([ if (options.dropdown) { if (options.iconClass) { this.domNode.setAttribute("role", "button"); //$NON-NLS-1$ //$NON-NLS-0$ + if (options.tooltip) { + this.domNode.setAttribute("aria-label", options.tooltip); //$NON-NLS-0$ + } } else { this.domNode.setAttribute("role", "combobox"); //$NON-NLS-1$ //$NON-NLS-0$ this.domNode.setAttribute("aria-readonly", "true"); //$NON-NLS-1$ //$NON-NLS-0$
Git page Configuration (wrench) button needs accessible name
eclipse_orion.client
train
6d6428077897d48b4256cc1854b12072ce8a9fec
diff --git a/src/codeflask.js b/src/codeflask.js index <HASH>..<HASH> 100644 --- a/src/codeflask.js +++ b/src/codeflask.js @@ -250,7 +250,7 @@ export default class CodeFlask { } handleSelfClosingCharacters (e) { - const openChars = ['(', '[', '{', '<'] + const openChars = ['(', '[', '{', '<', '\'', '"'] const key = e.key if (!openChars.includes(key)) { @@ -273,6 +273,14 @@ export default class CodeFlask { case '<': this.closeCharacter('>') break + + case '\'': + this.closeCharacter('\'') + break + + case '"': + this.closeCharacter('"') + break } } @@ -313,10 +321,11 @@ export default class CodeFlask { closeCharacter (closeChar) { const selectionStart = this.elTextarea.selectionStart const selectionEnd = this.elTextarea.selectionEnd - const newCode = `${this.code.substring(0, selectionStart)}${closeChar}${this.code.substring(selectionEnd)}` + const selectionText = this.code.substring(selectionStart, selectionEnd) + const newCode = `${this.code.substring(0, selectionStart)}${selectionText}${closeChar}${this.code.substring(selectionEnd)}` this.updateCode(newCode) - this.elTextarea.selectionEnd = selectionEnd + this.elTextarea.selectionEnd = selectionStart } updateCode (newCode) {
wrap selected text on self closing chars
kazzkiq_CodeFlask
train
6c9a9f4a247a7a4c5b69c9ad1f6610071200fa02
diff --git a/openquake/baselib/datastore.py b/openquake/baselib/datastore.py index <HASH>..<HASH> 100644 --- a/openquake/baselib/datastore.py +++ b/openquake/baselib/datastore.py @@ -84,7 +84,7 @@ def hdf5new(datadir=None): return new -def extract_calc_id_datadir(hdf5path=None, datadir=None): +def extract_calc_id_datadir(hdf5path, datadir=None): """ Extract the calculation ID from the given hdf5path or integer: @@ -96,8 +96,6 @@ def extract_calc_id_datadir(hdf5path=None, datadir=None): ValueError: Cannot extract calc_id from /mnt/ssd/oqdata/wrong_name.hdf5 """ datadir = datadir or get_datadir() - if hdf5path is None: # use a new datastore - return get_last_calc_id(datadir) + 1, datadir try: calc_id = int(hdf5path) except ValueError: @@ -154,23 +152,29 @@ class DataStore(collections.MutableMapping): """ def __init__(self, calc_id=None, datadir=None, params=(), mode=None): datadir = datadir or get_datadir() - calc_id, datadir = extract_calc_id_datadir(calc_id, datadir) + if isinstance(calc_id, str): # passed a real path + self.hdf5path = calc_id + self.calc_id, datadir = extract_calc_id_datadir(calc_id, datadir) + else: + if calc_id is None: # use a new datastore + self.calc_id = get_last_calc_id(datadir) + 1 + elif calc_id < 0: # use an old datastore + calc_ids = get_calc_ids(datadir) + try: + self.calc_id = calc_ids[calc_id] + except IndexError: + raise IndexError( + 'There are %d old calculations, cannot ' + 'retrieve the %s' % (len(calc_ids), calc_id)) + else: # use the given datastore + self.calc_id = calc_id + self.hdf5path = os.path.join( + datadir, 'calc_%s.hdf5' % self.calc_id) if not os.path.exists(datadir): os.makedirs(datadir) - if calc_id < 0: # use an old datastore - calc_ids = get_calc_ids(datadir) - try: - self.calc_id = calc_ids[calc_id] - except IndexError: - raise IndexError('There are %d old calculations, cannot ' - 'retrieve the %s' % (len(calc_ids), calc_id)) - else: # use the given datastore - self.calc_id = calc_id self.params = params self.parent = () # can be set later self.datadir = datadir - self.calc_dir = os.path.join(datadir, 'calc_%s' % self.calc_id) - self.hdf5path = self.calc_dir + '.hdf5' self.mode = mode or ('r+' if os.path.exists(self.hdf5path) else 'w') if self.mode == 'r' and not os.path.exists(self.hdf5path): raise IOError('File not found: %s' % self.hdf5path) diff --git a/openquake/calculators/event_based.py b/openquake/calculators/event_based.py index <HASH>..<HASH> 100644 --- a/openquake/calculators/event_based.py +++ b/openquake/calculators/event_based.py @@ -198,9 +198,8 @@ class EventBasedCalculator(base.HazardCalculator): par['samples'] = self.samples_by_grp[grp_id] with monitor: rup_array = rups[start: start + nr] - ruptures = list( - RuptureGetter(hdf5cache, code2cls, rup_array, - self.grp_trt[grp_id], par['samples'])) + ruptures = RuptureGetter(hdf5cache, code2cls, rup_array, + self.grp_trt[grp_id], par['samples']) if ruptures: yield ruptures, self.sitecol, rlzs_by_gsim, par start += nr diff --git a/openquake/commands/run.py b/openquake/commands/run.py index <HASH>..<HASH> 100644 --- a/openquake/commands/run.py +++ b/openquake/commands/run.py @@ -18,6 +18,7 @@ import collections import tempfile import logging +import os.path import cProfile import pstats @@ -121,7 +122,7 @@ def _run(job_inis, concurrent_tasks, pdb, loglevel, hc, exports, params): logging.info('Total time spent: %s s', monitor.duration) logging.info('Memory allocated: %s', general.humansize(monitor.mem)) print('See the output with hdfview %s' % calc.datastore.hdf5path) - calc_path = calc.datastore.calc_dir # used for the .pstat filename + calc_path, _ = os.path.splitext(calc.datastore.hdf5path) # used below return calc
Read the ruptures from the hdf4cache [skip hazardlib]
gem_oq-engine
train
02aaa08af012dee9a2d08e852335166510f38928
diff --git a/app/models/socializer/activity_object.rb b/app/models/socializer/activity_object.rb index <HASH>..<HASH> 100644 --- a/app/models/socializer/activity_object.rb +++ b/app/models/socializer/activity_object.rb @@ -52,16 +52,17 @@ module Socializer end def like!(person) - create_activity(person.activity_object.id, 'like') - increment_like_count + success = create_activity(person.activity_object.id, 'like') + increment_like_count if success end def unlike!(person) - create_activity(person.activity_object.id, 'unlike') - decrement_like_count + success = create_activity(person.activity_object.id, 'unlike') + decrement_like_count if success end # Share the activity with an audience + # # @param actor_id [Integer] User who share the activity (current_user) # @param object_ids [Array<Integer>] List of audiences to target # @param content [String] Text with the share @@ -89,13 +90,15 @@ module Socializer private def create_activity(actor_id, verb) - Activity.create! do |a| + activity = Activity.new do |a| a.actor_id = actor_id a.activity_object_id = id a.verb = Verb.find_or_create_by(name: verb) a.audiences.build(privacy_level: :public) end + + activity.save! end def increment_like_count
return boolean from create_activity and check result before incrementing/decrementing the like count
socializer_socializer
train
dfb3c716d8a64a6d84a9828f0bd89aea431a3c0e
diff --git a/pycbc/waveform/generator.py b/pycbc/waveform/generator.py index <HASH>..<HASH> 100644 --- a/pycbc/waveform/generator.py +++ b/pycbc/waveform/generator.py @@ -28,6 +28,7 @@ This modules provides classes for generating waveforms. import functools import waveform import ringdown +from pycbc import coordinates from pycbc.waveform import parameters from pycbc.waveform.utils import apply_fd_time_shift from pycbc.detector import Detector @@ -93,11 +94,41 @@ def generator_mchirp_q_to_mass1_mass2(generator): generator.current_params['mass2'] = m2 +@add_attrs(input_params=[parameters.spin1_a, parameters.spin2_a, + parameters.spin1_azimuthal, + parameters.spin2_azimuthal, + parameters.spin1_polar, parameters.spin2_polar], + output_params=[parameters.spin1x, parameters.spin2x, + parameters.spin1y, parameters.spin2y, + parameters.spin1z, parameters.spin2z]) +def generator_spin_spherical_to_spin_cartesian(generator): + """Converts spherical spin magnitude and angles in `current_params`, + to cartesian component spins. + """ + x, y, z = coordinates.spherical_to_cartesian( + generator.current_params["spin1_a"] * + generator.current_params["mass1"]**2, + generator.current_params["spin1_azimuthal"], + generator.current_params["spin1_polar"]) + generator.current_params["spin1x"] = x + generator.current_params["spin1y"] = y + generator.current_params["spin1z"] = z + x, y, z = coordinates.spherical_to_cartesian( + generator.current_params["spin2_a"] * + generator.current_params["mass2"]**2, + generator.current_params["spin2_azimuthal"], + generator.current_params["spin2_polar"]) + generator.current_params["spin2x"] = x + generator.current_params["spin2y"] = y + generator.current_params["spin2z"] = z + + # a list of all generator functions generator_functions = [ generator_mchirp_eta_to_mass1_mass2, generator_mtotal_eta_to_mass1_mass2, generator_mchirp_q_to_mass1_mass2, + generator_spin_spherical_to_spin_cartesian, ] # @@ -221,9 +252,19 @@ class BaseCBCGenerator(BaseGenerator): # compare a set of all args of the generator to the input parameters # of the functions that do conversions and adds to list of pregenerate # functions if it is needed + params_used = set([]) for func in generator_functions: if set(func.input_params).issubset(all_args): self._add_pregenerate(func) + params_used.update(func.input_params) + # check that there are no unused parameters + all_waveform_input_args = set(parameters.td_waveform_params + + parameters.fd_waveform_params) + unused_args = all_args.difference(params_used) \ + .difference(all_waveform_input_args) + if len(unused_args): + raise ValueError("The following args are not being used: " + "{opts}".format(opts=unused_args)) class FDomainCBCGenerator(BaseCBCGenerator):
Add spin magnitude and angles to generators. (#<I>) * Add spin magnitude and angles to generators. * Use .format for string.
gwastro_pycbc
train
84aae51562c04899eda59f1e48a277388b54b01e
diff --git a/lib/mastermind/version.rb b/lib/mastermind/version.rb index <HASH>..<HASH> 100644 --- a/lib/mastermind/version.rb +++ b/lib/mastermind/version.rb @@ -1,3 +1,3 @@ module Mastermind - VERSION = "0.1.0" + VERSION = "0.1.2" end
updated version of mastermind to <I>
andela-oakinniranye_mastermind
train
63f484fc2a01d0c34f59efe4543c38fc1202a53c
diff --git a/lib/bblib/core/util/cases.rb b/lib/bblib/core/util/cases.rb index <HASH>..<HASH> 100644 --- a/lib/bblib/core/util/cases.rb +++ b/lib/bblib/core/util/cases.rb @@ -2,7 +2,7 @@ module BBLib def self.title_case(str, first_only: true) str = str.to_s unless str.is_a?(String) ignoreables = %w(a an the on upon and but or in with to) - regx = /\s+|\-|\_|(?<=\W|^)\"(?=\w|$)|(?<=\W|^)\'(?=\w|$)|\(|\)|\[|\]|\{|\}|\#/ + regx = /\s+|\-|\_|(?<=[\w\d])\.(?=[\w\d])|(?<=\W|^)\"(?=\w|$)|(?<=\W|^)\'(?=\w|$)|\(|\)|\[|\]|\{|\}|\#/ spacing = str.scan(regx).to_a words = str.split(regx).map do |word| if ignoreables.include?(word.downcase) @@ -15,7 +15,9 @@ module BBLib end # Always cap the first word words[0] = words.first.to_s.slice(0,1).to_s.upcase + words.first.to_s[1..-1].to_s - words.interleave(spacing).join + combined = words.interleave(spacing).join + combined.scan(/(?<=\.)\w(?=\.)/).each { |part| combined.sub!(".#{part}.", ".#{part}.".upcase) } + combined end def self.start_case(str, first_only: false)
Enhanced title case to support dotted character strings.
bblack16_bblib-ruby
train
62b4364a77fe5ceef30afe98497a1ea9b5ca7902
diff --git a/api/src/main/java/io/grpc/ProxyDetector.java b/api/src/main/java/io/grpc/ProxyDetector.java index <HASH>..<HASH> 100644 --- a/api/src/main/java/io/grpc/ProxyDetector.java +++ b/api/src/main/java/io/grpc/ProxyDetector.java @@ -32,7 +32,7 @@ import javax.annotation.Nullable; * underlying transport need to work together. * * <p>The {@link NameResolver} should invoke the {@link ProxyDetector} retrieved from the {@link - * NameResolver.Helper#getProxyDetector}, and pass the returned {@link ProxiedSocketAddress} to + * NameResolver.Args#getProxyDetector}, and pass the returned {@link ProxiedSocketAddress} to * {@link NameResolver.Listener#onAddresses}. The DNS name resolver shipped with gRPC is already * doing so. *
api: Fix Javadoc reference to NameResolver.Args NameResolver.Helper was a short-lived class that didn't get very far. We chose NameResolver.Args instead and didn't mirror LoadBalancer.
grpc_grpc-java
train
35884b2621e6861b0c123a0777028b7405bda37c
diff --git a/src/main/ruby/resque/jruby_worker.rb b/src/main/ruby/resque/jruby_worker.rb index <HASH>..<HASH> 100644 --- a/src/main/ruby/resque/jruby_worker.rb +++ b/src/main/ruby/resque/jruby_worker.rb @@ -25,9 +25,9 @@ module Resque def work(&block) startup work_loop(&block) - unregister_worker + worker_registry.unregister rescue Exception => exception - unregister_worker(exception) + worker_registry.unregister(exception) end def fork_for_child(job, &block) @@ -256,20 +256,29 @@ module Resque if RESQUE_2x - def register_worker - outcome = worker_registry.register - system_register_worker if JRUBY - outcome - end + WorkerRegistry.class_eval do - def unregister_worker(exception = nil) - system_unregister_worker if JRUBY - if exception - worker_registry.unregister(exception) - else - worker_registry.unregister + alias_method :do_register, :register + + def register + outcome = do_register + if @worker.is_a?(JRubyWorker) + @worker.send(:system_register_worker) if JRUBY + end + outcome end - end # removed on 2.0 [master] + + alias_method :do_unregister, :unregister + + def unregister(exception = nil) + outcome = do_unregister(exception) + if @worker.is_a?(JRubyWorker) + @worker.send(:system_unregister_worker) if JRUBY + end + outcome + end + + end else diff --git a/src/test/ruby/resque/jruby_worker_test.rb b/src/test/ruby/resque/jruby_worker_test.rb index <HASH>..<HASH> 100644 --- a/src/test/ruby/resque/jruby_worker_test.rb +++ b/src/test/ruby/resque/jruby_worker_test.rb @@ -179,7 +179,11 @@ module Resque redis.expects(:sadd).with :workers, worker redis.stubs(:set) - worker.register_worker + if RESQUE_2x + worker.worker_registry.register + else + worker.register_worker + end workers = Resque::JRubyWorker.system_registered_workers assert_include workers, worker.id @@ -198,7 +202,11 @@ module Resque redis.expects(:srem).with :workers, worker redis.stubs(:get); redis.stubs(:del) - worker.unregister_worker + if RESQUE_2x + worker.worker_registry.unregister + else + worker.unregister_worker + end workers = Resque::JRubyWorker.system_registered_workers assert_not_include workers, worker.id @@ -223,7 +231,7 @@ module Resque end else # Resque 2.x assert_nothing_raised(RuntimeError) do - worker.unregister_worker(exception) + worker.worker_registry.unregister(exception) end end end
need to monkey-patch Resque::WorkerRegistry for <I> to work as expected
kares_jruby-rack-worker
train
2927cc71ced18de78715cb655b28e9716f03f0aa
diff --git a/ospd/protocol.py b/ospd/protocol.py index <HASH>..<HASH> 100644 --- a/ospd/protocol.py +++ b/ospd/protocol.py @@ -146,6 +146,32 @@ class OspRequest: return credentials + @staticmethod + def process_alive_test_methods(cred_tree: Element, options: Dict) -> None: + """ Receive an XML object with the alive test methods to run + a scan with. Methods are added to the options Dict. + + @param + <alive_test_methods> + </icmp></icmp> + </tcp_ack></tcp_ack> + </tcp_syn></tcp_syn> + </arp></arp> + </consider_alive>0</consider_alive> + </alive_test_methods> + """ + for child in cred_tree: + if child.tag == 'icmp': + options['icmp'] = child.text + if child.tag == 'tcp_ack': + options['tcp_ack'] = child.text + if child.tag == 'tcp_syn': + options['tcp_syn'] = child.text + if child.tag == 'arp': + options['arp'] = child.text + if child.tag == 'consider_alive': + options['consider_alive'] = child.text + @classmethod def process_target_element(cls, scanner_target: Element) -> Dict: """Receive an XML object with the target, ports and credentials to run @@ -222,6 +248,9 @@ class OspRequest: ports = child.text if child.tag == 'credentials': credentials = cls.process_credentials_elements(child) + if child.tag == 'alive_test_methods': + options['alive_test_methods'] = '1' + cls.process_alive_test_methods(child, options) if child.tag == 'alive_test': options['alive_test'] = child.text if child.tag == 'alive_test_ports':
Add new interface for adding alive test methods Instead of using a bit flag which entails all alive tests we can now also use xml elements for every alive test method.
greenbone_ospd
train
3c5e576cd2f6064f8dae21d2ff9c8f8ca2687de4
diff --git a/includes/functions/functions.php b/includes/functions/functions.php index <HASH>..<HASH> 100644 --- a/includes/functions/functions.php +++ b/includes/functions/functions.php @@ -788,7 +788,7 @@ function get_relationship_name_from_path($path, Individual $person1 = null, Indi $dob1 = $person1->getBirthDate(); $dob2 = $person2->getBirthDate(); if ($dob1->isOK() && $dob2->isOK()) { - if (abs($dob1->julianDay() - $dob2->julianDay()) < 2 && !$dob1->qual1 && !$dob2->qual1) { + if (abs($dob1->julianDay() - $dob2->julianDay()) < 2 && !$dob1->minimumDate()->d !== 0 && !$dob2->minimumDate()->d !== 0) { // Exclude BEF, AFT, etc. return I18N::translate('twin sibling'); } elseif ($dob1->maximumJulianDay() < $dob2->minimumJulianDay()) {
Fix: detect twins by birth-date, not by birth-date qualifier
fisharebest_webtrees
train
825d8278b2898a8d269284bc73f30bf00eed5242
diff --git a/src/Parser/SyntaxTree/Node.php b/src/Parser/SyntaxTree/Node.php index <HASH>..<HASH> 100644 --- a/src/Parser/SyntaxTree/Node.php +++ b/src/Parser/SyntaxTree/Node.php @@ -66,6 +66,19 @@ class Node } /** + * @param int $index + * @return Node + * @throws Exception + */ + public function getChild(int $index): Node + { + if (!isset($this->childMap[$index])) { + throw new Exception("Child node at index {$index} in node {$this->getId()} is not defined"); + } + return $this->childMap[$index]; + } + + /** * @return Node[] */ public function getChildList(): array
Parser syntax tree Node::getChild() added
remorhaz_php-unilex
train
536eeff454881cfe06c6ce7a729b68af15d4e98a
diff --git a/pyontutils/qnamefix.py b/pyontutils/qnamefix.py index <HASH>..<HASH> 100755 --- a/pyontutils/qnamefix.py +++ b/pyontutils/qnamefix.py @@ -1,14 +1,22 @@ #!/usr/bin/env python3 -""" - This file should be run in NIF-Ontology/ttl - Run at NIF-Ontology 5dd555fcbacf515a475ff1fe47aed06d93cce61e +"""Set qnames based on the curies defined for a given ontology. + +Usage: + qnamefix [options] <file>... + +Options: + -h --help print this + -v --verbose do something fun! + -s --slow do not use a process pool + -n --nowrite parse the file and reserialize it but do not write changes + """ import os from glob import glob import rdflib +from docopt import docopt from pyontutils.utils import makePrefixes, PREFIXES, makeGraph -from pyontutils.process_fixed import ProcessPoolExecutor from IPython import embed PREFIXES.pop('NIFTTL') @@ -78,14 +86,12 @@ def convert(f): return f def main(): - with ProcessPoolExecutor(8) as ppe: - futures = [ppe.submit(convert, f) for f in glob('*/*.ttl') + glob('*.ttl')] - #futures = [ppe.submit(convert, f) for f in glob('generated/parcellation/*.ttl')] - #futures = [ppe.submit(convert, f) for f in glob('nif.ttl')] - for f in futures: - if f.exception(): - print(f) - #embed() + from joblib import Parallel, delayed + args = docopt(__doc__, version = "resurect-ids 0") + if args['--slow'] or len(args['<file>']) == 1: + [convert(f) for f in args['<file>']] + else: + Parallel(n_jobs=9)(delayed(convert)(f) for f in args['<file>']) if __name__ == '__main__': main() diff --git a/setup.py b/setup.py index <HASH>..<HASH> 100755 --- a/setup.py +++ b/setup.py @@ -14,6 +14,7 @@ files = [ 'pyontutils/ontload.py', 'pyontutils/obo_io.py', 'pyontutils/phenotype_namespaces.py', + 'pyontutils/qnamefix.py', 'pyontutils/scig.py', 'pyontutils/scigraph.py', 'pyontutils/scigraph_client.py', @@ -62,6 +63,7 @@ try: 'console_scripts': [ 'ilxcli=pyontutils.ilxcli:main', 'ontload=pyontutils.ontload:main', + 'qnamefix=pyontutils.qnamefix:main', 'scigraph-codegen=pyontutils.scigraph:main', 'scig=pyontutils.scig:main', 'ttlfmt=pyontutils.ttlfmt:main',
qnamefix converted to cli program and added to setup.py
tgbugs_pyontutils
train
f460d808baca3c5b12a11da8235fd2af1032e7d4
diff --git a/router.go b/router.go index <HASH>..<HASH> 100644 --- a/router.go +++ b/router.go @@ -168,7 +168,7 @@ func (da *doubleArray) lookup(path string, params []Param, idx int) (*node, []Pa indices := make([]uint64, 0, 1) for i := 0; i < len(path); i++ { if da.bc[idx].IsAnyParam() { - indices = append(indices, (uint64(i)<<32)|uint64(idx&0xffffffff)) + indices = append(indices, (uint64(i)<<32)|(uint64(idx)&0xffffffff)) } c := path[i] next := nextIndex(da.bc[idx].Base(), c)
Fix a problem that can't be built in <I>bit environment
naoina_denco
train
1e414762f357283ff7c38eea69ac53ba36660f3d
diff --git a/lib/compilers.js b/lib/compilers.js index <HASH>..<HASH> 100644 --- a/lib/compilers.js +++ b/lib/compilers.js @@ -139,7 +139,7 @@ module.exports = function(extglob) { var str = star.call(this, node); // if the extglob has a slash explicitly defined, we know the user wants - // to match slashes, so we need to change the "star" regex accordingly + // to match slashes, so we need to ensure the "star" regex allows for it if (node.parent.hasSlash && !this.options.star && this.options.slash !== false) { str = '.*?'; } diff --git a/test/test.js b/test/test.js index <HASH>..<HASH> 100644 --- a/test/test.js +++ b/test/test.js @@ -53,6 +53,7 @@ describe('extglobs', function() { }); it('should support negation (`!`) extglobs', function() { + match(['moo.cow'], '!(!(moo)).!(!(cow))', ['moo.cow']); match(['c/z/v', 'c/a/v'], 'c/!(z)/v', ['c/a/v']); match(['c/z/v', 'c/a/v'], 'c/!(z)/v', ['c/a/v']); match(['cz', 'abz', 'az'], 'a!(z)', ['abz']); @@ -72,6 +73,10 @@ describe('extglobs', function() { match(f1, '!((?:b/a))', ['a/a', 'a/b', 'a/c', 'b/b', 'b/c']); match(f1, '!(b/(a))', ['a/a', 'a/b', 'a/c', 'b/b', 'b/c']); + match(['b', 'b ', 'b ', 'c '], '@(!(a) {1,2})*', ['b ', 'b ', 'c ']); + match(['b', 'b ', 'bb', 'ccc'], '@(!(a) {1,2})*', ['b ']); + match(['b', 'a ', 'b ', 'bb', 'ccc'], '@(!(a){1,2} )*', ['b ']); + var f2 = ['a', 'b', 'aa', 'ab', 'bb', 'ac', 'aaa', 'aab', 'abb', 'ccc']; match(f2, '!(a)', ['aa', 'aaa', 'aab', 'ab', 'abb', 'ac', 'b', 'bb', 'ccc']); match(f2, '!(a*)', ['b', 'bb', 'ccc']); @@ -79,7 +84,6 @@ describe('extglobs', function() { match(f2, '!(*a)', ['aab', 'ab', 'abb', 'ac', 'b', 'bb', 'ccc']); match(f2, '!(a)*', ['b', 'bb', 'ccc']); match(f2, '!(*a)*', ['b', 'bb', 'ccc']); - match(f2, '@(!(a){1,2})*', ['b', 'bb', 'ccc']); match(f2, 'a!(b)*', ['a', 'aa', 'aaa', 'aab', 'ac']); match(['aajs', 'bajs', 'aamd', 'abmd'], 'a!(a)md', ['abmd']); match(['aajs', 'bajs', 'aamd', 'abmd'], 'a!(.)md', ['aamd', 'abmd']);
adds a few random tests, comments
micromatch_extglob
train
698ae8d7a391d7be8056bd74cf6397b7d3f9ef28
diff --git a/anchore/anchore-modules/gates/10_check_dockerfile.py b/anchore/anchore-modules/gates/10_check_dockerfile.py index <HASH>..<HASH> 100755 --- a/anchore/anchore-modules/gates/10_check_dockerfile.py +++ b/anchore/anchore-modules/gates/10_check_dockerfile.py @@ -10,27 +10,27 @@ gate_name = "DOCKERFILECHECK" triggers = { 'EXPOSE': { - 'description':'triggers if this happens', + 'description':'triggers if Dockerfile is EXPOSEing ports that are not in ALLOWEDPORTS, or are in DENIEDPORTS', 'params':'ALLOWEDPORTS,DENIEDPORTS' }, 'NOFROM': { - 'description':'triggers if that happens', + 'description':'triggers if there is no FROM line specified in the Dockerfile', 'params':'None' }, 'FROMSCRATCH': { - 'description':'triggers if that happens', + 'description':'triggers the FROM line specified "scratch" as the parent', 'params':'None' }, 'NOTAG': { - 'description':'triggers if that happens', + 'description':'triggers if the FROM container specifies a repo but no explicit, non-latest tag ', 'params':'None' }, 'SUDO': { - 'description':'triggers if that happens', + 'description':'triggers if the Dockerfile contains operations running with sudo', 'params':'None' } } diff --git a/anchore/anchore-modules/gates/98_anchoresec.py b/anchore/anchore-modules/gates/98_anchoresec.py index <HASH>..<HASH> 100755 --- a/anchore/anchore-modules/gates/98_anchoresec.py +++ b/anchore/anchore-modules/gates/98_anchoresec.py @@ -72,7 +72,7 @@ except Exception as err: traceback.print_exc() print "ERROR: could not scan image for CVEs: " + str(err) outlist = list() - outlist.append("UNSUPPORTEDDISTRO Cannot load CVE data for image distro to perform scan.") + outlist.append("UNSUPPORTEDDISTRO Cannot load CVE data for image distro to perform scan. Message from service: "+str(err)) anchore.anchore_utils.save_gate_output(imgid, gate_name, outlist) sys.exit(0) diff --git a/anchore/anchore_utils.py b/anchore/anchore_utils.py index <HASH>..<HASH> 100644 --- a/anchore/anchore_utils.py +++ b/anchore/anchore_utils.py @@ -1153,6 +1153,8 @@ def cve_load_data(image, cve_data_context=None): if cve_data_context != None and dstr not in cve_data_context: cve_data_context[dstr] = cve_data break + else: + raise ValueError(str(feeddata['msg'])) if not cve_data: raise ValueError("cannot find CVE data associated with the input container distro: ("+str(distrolist)+")")
fixing up some help strings for gate and CVE gate trigger
anchore_anchore
train
dd3faa05c44ae057c98a6fdf53c20710da2e4681
diff --git a/test/lib/search.get.js b/test/lib/search.get.js index <HASH>..<HASH> 100644 --- a/test/lib/search.get.js +++ b/test/lib/search.get.js @@ -155,18 +155,15 @@ describe('Get search form', function() { fields[0].should.eql({ var: 'first', type: 'text-single', - required: false, label: 'Given Name' }) fields[1].should.eql({ var: 'last', type: 'text-single', - required: false, label: 'Family Name' }) fields[2].var.should.equal('x-gender') fields[2].type.should.equal('list-single') - fields[2].required.should.be.false fields[2].label.should.equal('Gender') fields[2].options.length.should.equal(2) fields[2].options[0].should.eql({ @@ -187,4 +184,4 @@ describe('Get search form', function() { ) }) -}) \ No newline at end of file +})
No longer always set 'required'
xmpp-ftw_xmpp-ftw-search
train
b6f9d3ab764c40f4df44063f3e59ab7655ae0a97
diff --git a/slave/buildslave/bot.py b/slave/buildslave/bot.py index <HASH>..<HASH> 100644 --- a/slave/buildslave/bot.py +++ b/slave/buildslave/bot.py @@ -274,7 +274,7 @@ class Bot(pb.Referenceable, service.MultiService): del(self.builders[name]) for d in os.listdir(self.basedir): - if os.path.isdir(d): + if os.path.isdir(os.path.join(self.basedir, d)): if d not in wanted_dirs: log.msg("I have a leftover directory '%s' that is not " "being used by the buildmaster: you can delete " diff --git a/slave/buildslave/test/unit/test_bot.py b/slave/buildslave/test/unit/test_bot.py index <HASH>..<HASH> 100644 --- a/slave/buildslave/test/unit/test_bot.py +++ b/slave/buildslave/test/unit/test_bot.py @@ -112,12 +112,13 @@ class TestBot(unittest.TestCase): def remove_my(_): d = self.bot.callRemote("setBuilderList", [ - ('yourbld', 'yourblddir') ]) + ('yourbld', 'yourblddir2') ]) # note new builddir def check(builders): self.assertEqual(sorted(builders.keys()), sorted(['yourbld'])) # note that build dirs are not deleted.. self.assertTrue(os.path.exists(os.path.join(self.basedir, 'myblddir'))) self.assertTrue(os.path.exists(os.path.join(self.basedir, 'yourblddir'))) + self.assertTrue(os.path.exists(os.path.join(self.basedir, 'yourblddir2'))) # 'your' should still be the same slavebuilder object self.assertEqual(id(slavebuilders['your']), id(builders['yourbld'])) d.addCallback(check)
fix bug in detecting leftover directories, test changing builddirs on existing builders
buildbot_buildbot
train
aa9ee16578ef0e042f743cb6dc344a1b7314f7a1
diff --git a/plugins/org.eclipse.xtext/src/org/eclipse/xtext/parsetree/reconstr/Serializer.java b/plugins/org.eclipse.xtext/src/org/eclipse/xtext/parsetree/reconstr/Serializer.java index <HASH>..<HASH> 100755 --- a/plugins/org.eclipse.xtext/src/org/eclipse/xtext/parsetree/reconstr/Serializer.java +++ b/plugins/org.eclipse.xtext/src/org/eclipse/xtext/parsetree/reconstr/Serializer.java @@ -90,17 +90,6 @@ public class Serializer { return serialize(obj, options.toSaveOptions()); } - @Deprecated - public ReplaceRegion serializeReplacement(EObject obj, SerializerOptions options) { - TokenStringBuffer tokenStringBuffer = new TokenStringBuffer(); - try { - TreeConstructionReport report = serialize(obj, tokenStringBuffer, options); - return new ReplaceRegion(report.getPreviousLocation(), tokenStringBuffer.toString()); - } catch (IOException e) { - throw new RuntimeException(e); - } - } - public ReplaceRegion serializeReplacement(EObject obj, SaveOptions options) { TokenStringBuffer tokenStringBuffer = new TokenStringBuffer(); try {
Removed newly introduced method that was marked as deprecated right from the beginning
eclipse_xtext-core
train
bb2f31cca747969b30990e87c780e68a04196a6b
diff --git a/spec/moneta/adapter_activerecord_existing_connection_spec.rb b/spec/moneta/adapter_activerecord_existing_connection_spec.rb index <HASH>..<HASH> 100644 --- a/spec/moneta/adapter_activerecord_existing_connection_spec.rb +++ b/spec/moneta/adapter_activerecord_existing_connection_spec.rb @@ -25,7 +25,7 @@ describe 'adapter_activerecord_existing_connection' do # This is based on # https://github.com/jjb/rails/blob/ar-connection-management-guide/guides/source/active_record_connection_management.md - it "supports use on a forking web server" do + it "supports use on a forking web server", unsupported: !Process.respond_to?(:fork) do store['a'] = 'b' # Before forking, the connection pool is disconnected so that the
Specs: don't test forking where Ruby does not support it
moneta-rb_moneta
train
6cf07eaeba2020babed840d0c69b9eca3d0fdc54
diff --git a/lib/tty/table/operation/alignment_set.rb b/lib/tty/table/operation/alignment_set.rb index <HASH>..<HASH> 100644 --- a/lib/tty/table/operation/alignment_set.rb +++ b/lib/tty/table/operation/alignment_set.rb @@ -68,15 +68,9 @@ module TTY index = 0 row.map! do |cell| column_width = options[:column_widths][index] - - alignment = Alignment.new self[index] - aligned = alignment.format(cell, column_width) - - if cell.is_a?(TTY::Table::Field) - cell.value = aligned - end + alignment = Alignment.new(cell.align || self[index]) index += 1 - aligned + cell.value = alignment.format(cell, column_width) end end diff --git a/spec/tty/table/renderer/basic/alignment_spec.rb b/spec/tty/table/renderer/basic/alignment_spec.rb index <HASH>..<HASH> 100644 --- a/spec/tty/table/renderer/basic/alignment_spec.rb +++ b/spec/tty/table/renderer/basic/alignment_spec.rb @@ -49,13 +49,39 @@ describe TTY::Table, 'alignment' do end end - it 'aligns table rows' do - rows = [['aaaaa', 'a'], ['b', 'bbbbb']] - table = TTY::Table.new rows, :renderer => :basic, - :column_aligns => [:left, :right] - table.to_s.should == <<-EOS.normalize - aaaaa a - b bbbbb - EOS + context 'with individual field aligns' do + let(:header) { ['header1', 'header2', 'header3'] } + let(:column_aligns) { [:left, :center, :right] } + + it "takes individual fields over global aligns" do + options = {:header => header, :column_aligns => column_aligns, :renderer => :basic} + table = described_class.new options do |t| + t << ['a1', 'a2', 'a3'] + t << ['b1', {:value => 'b2', :align => :right}, 'b3'] + t << ['c1', 'c2', {:value => 'c3', :align => :center}] + end + table.to_s.should == <<-EOS.normalize + header1 header2 header3 + a1 a2 a3 + b1 b2 b3 + c1 c2 c3 + EOS + end + end + + context 'with aligned header' do + let(:rows) { [['aaaaa1', 'a2', 'aaa3'], ['b1', 'bbbb2', 'bb3']] } + + it "aligns headres" do + header = ['h1', {:value => 'h2', :align => :right}, {:value => 'h3', :align => :center}] + options = {:header => header, :renderer => :basic, :rows => rows } + table = described_class.new options + table.to_s.should == <<-EOS.normalize + h1 h2 h3 + aaaaa1 a2 aaa3 + b1 bbbb2 bb3 + EOS + end + end end
Assume field objects for alignment.
piotrmurach_tty
train
09e208df45ccbc6a52b573c2bebd6e344bafcbef
diff --git a/lib/gitemplate-dox/index.js b/lib/gitemplate-dox/index.js index <HASH>..<HASH> 100644 --- a/lib/gitemplate-dox/index.js +++ b/lib/gitemplate-dox/index.js @@ -54,6 +54,7 @@ function GitemplateDox() { this.builds = []; this.params = {}; + this.returns = {}; } configurable(GitemplateDox.prototype); @@ -100,11 +101,13 @@ GitemplateDox.prototype.build = function() { */ GitemplateDox.prototype.convertOne = function(md, comment) { this.prepParams(comment); + this.prepReturns(comment); this.buildHeading(md, comment); this.buildSummary(md, comment); this.buildJsBlocks(md, comment); this.buildParams(md, comment); + this.buildReturns(md, comment); }; GitemplateDox.prototype.method = function(comment) { @@ -142,6 +145,32 @@ GitemplateDox.prototype.prepParams = function(comment) { /** * @api private */ +GitemplateDox.prototype.prepReturns = function(comment) { + if (!comment.tags) { return; } + + var self = this; + var method = this.method(comment); + var collectOverflow = false; + + comment.tags.forEach(function(tag) { + if ('return' === tag.type) { + self.returns[method] = { + types: tag.types, + description: tag.description, + overflow: [] + }; + collectOverflow = true; + } else if ('' === tag.type && collectOverflow) { + self.returns[method].overflow.push(tag.string); + } else { // Ex. @see + collectOverflow = false; + } + }); +}; + +/** + * @api private + */ GitemplateDox.prototype.buildHeading = function(md, comment) { var method = this.method(comment); var heading = sprintf('%s(%s)', method, Object.keys(this.params[method]).join(', ')); @@ -169,10 +198,10 @@ GitemplateDox.prototype.buildParams = function(md, comment) { names.forEach(function(name) { var param = self.params[method][name]; var heading = sprintf( - '`{%s} %s`: %s', + '`{%s} %s`%s', param.types.join(' | '), name, - param.description + param.description ? ': ' + param.description : '' ); md.h(3, heading); @@ -188,6 +217,33 @@ GitemplateDox.prototype.buildParams = function(md, comment) { /** * @api private */ +GitemplateDox.prototype.buildReturns = function(md, comment) { + var self = this; + var method = this.method(comment); + var returns = this.returns[method]; + + if (!returns) { return; } + + md.h(2, 'Return'); + + var heading = sprintf( + '`{%s}`%s', + returns.types.join(' | '), + returns.description ? ': ' + returns.description : '' + ); + md.h(3, heading); + + if (returns.overflow.length) { + md.newline(); + returns.overflow.forEach(function(line) { + md.push(line); + }); + } +}; + +/** + * @api private + */ GitemplateDox.prototype.buildJsBlocks = function(md, comment) { if (!comment.description.body) { return; } diff --git a/test/fixture/kitchen-sink.js b/test/fixture/kitchen-sink.js index <HASH>..<HASH> 100644 --- a/test/fixture/kitchen-sink.js +++ b/test/fixture/kitchen-sink.js @@ -13,7 +13,7 @@ exports.Klass = Klass; /** - * Return a new Klass() instance. + * Create a new Klass() instance. * * @return {Klass} */ @@ -75,6 +75,7 @@ Klass.prototype.foo = function() { * Link this: `Klass#foo()` * Link this: `Klass.foo()` * + * @param {string} noSummary * @param {string} str String summary * String body 1st line * String body 2nd line @@ -85,7 +86,7 @@ Klass.prototype.foo = function() { * Return body 1st line * Return body 2nd line */ -Klass.prototype.bar = function(str, obj) { +Klass.prototype.bar = function(noSummary, str, obj) { }; /** diff --git a/test/fixture/kitchen-sink.md b/test/fixture/kitchen-sink.md index <HASH>..<HASH> 100644 --- a/test/fixture/kitchen-sink.md +++ b/test/fixture/kitchen-sink.md @@ -4,7 +4,11 @@ Klass constructor. # exports.create() -Return a new Klass() instance. +Create a new Klass() instance. + +## Return + +### `{Klass}` # exports.extend(ext) @@ -14,6 +18,10 @@ Extend `Klass.prototype` ### `{object} ext`: Methods to mix in. +## Return + +### `{object}`: Merge result. + # Klass() Klass summary @@ -44,7 +52,7 @@ Foo 2nd section: - `item`: Summary 1 - `item`: Summary 2 -# Klass.prototype.bar(str, mixed) +# Klass.prototype.bar(noSummary, str, mixed) Bat summary @@ -54,6 +62,8 @@ Link this: `Klass.foo()` ## Parameters +### `{string} noSummary` + ### `{string} str`: String summary String body 1st line @@ -63,3 +73,10 @@ String body 2nd line Mixed body 1st line Mixed body 2nd line + +## Return + +### `{array}`: Return summary + +Return body 1st line +Return body 2nd line
feat(return): Add type, description, overflow text
codeactual_apidox
train
6684642faf6a391f625805b6bb165d2a6ec60665
diff --git a/lib/mess/tree/zoomfilter.js b/lib/mess/tree/zoomfilter.js index <HASH>..<HASH> 100644 --- a/lib/mess/tree/zoomfilter.js +++ b/lib/mess/tree/zoomfilter.js @@ -67,7 +67,7 @@ tree.ZoomFilter.prototype.negate = function() { return this; }; -tree.ZoomFilter.prototype.toCSS = function(env) { +tree.ZoomFilter.prototype.toXML = function(env) { if (this.val > 22 || this.val < 0) { throw { message: 'Only zoom levels between 0 and 22 supported.',
Don't die on zoomfilters - toXML instead of toCSS
mapbox_carto
train
e6bc37c49be067027f23c8d0c53de36789d7ccb1
diff --git a/lib/dci-ruby/version.rb b/lib/dci-ruby/version.rb index <HASH>..<HASH> 100644 --- a/lib/dci-ruby/version.rb +++ b/lib/dci-ruby/version.rb @@ -1,3 +1,3 @@ module DCI - VERSION = "2.1.1" + VERSION = "2.1.2" end
bumped to version <I>
ltello_dci-ruby
train
eaf0670a90d9a11bd2c3b803f5dd8977aeb8797a
diff --git a/jbpm-human-task/jbpm-human-task-core/src/test/java/org/jbpm/services/task/identity/DBUserGroupCallbackImplTest.java b/jbpm-human-task/jbpm-human-task-core/src/test/java/org/jbpm/services/task/identity/DBUserGroupCallbackImplTest.java index <HASH>..<HASH> 100644 --- a/jbpm-human-task/jbpm-human-task-core/src/test/java/org/jbpm/services/task/identity/DBUserGroupCallbackImplTest.java +++ b/jbpm-human-task/jbpm-human-task-core/src/test/java/org/jbpm/services/task/identity/DBUserGroupCallbackImplTest.java @@ -248,7 +248,8 @@ public class DBUserGroupCallbackImplTest { } pds.getDriverProperties().put("REQUEST_HA_SESSION", "false"); pds.getDriverProperties().put("networkProtocol", "Tds"); - } else if (driverClass.startsWith("org.postgresql")) { + // com.edb is Postgres Plus. + } else if (driverClass.startsWith("org.postgresql") || driverClass.startsWith("com.edb")) { for (String propertyName : new String[]{"databaseName", "portNumber", "serverName"}) { pds.getDriverProperties().put(propertyName, dsProps.getProperty(propertyName)); } diff --git a/jbpm-persistence-jpa/src/test/java/org/jbpm/persistence/util/PersistenceUtil.java b/jbpm-persistence-jpa/src/test/java/org/jbpm/persistence/util/PersistenceUtil.java index <HASH>..<HASH> 100644 --- a/jbpm-persistence-jpa/src/test/java/org/jbpm/persistence/util/PersistenceUtil.java +++ b/jbpm-persistence-jpa/src/test/java/org/jbpm/persistence/util/PersistenceUtil.java @@ -229,7 +229,8 @@ public class PersistenceUtil { } pds.getDriverProperties().put("REQUEST_HA_SESSION", "false"); pds.getDriverProperties().put("networkProtocol", "Tds"); - } else if (driverClass.startsWith("org.postgresql")) { + // com.edb is Postgres Plus. + } else if (driverClass.startsWith("org.postgresql") || driverClass.startsWith("com.edb")) { for (String propertyName : new String[] { "databaseName", "portNumber", "serverName" }) { pds.getDriverProperties().put(propertyName, dsProps.getProperty(propertyName)); }
JBPM-<I> Persistence tests don't support Postgres Plus Added support for com.edb.Driver class to data source properties handling.
kiegroup_jbpm
train
4016240076ea217dfcd7377d1943999468e99e74
diff --git a/View/ViewHandler.php b/View/ViewHandler.php index <HASH>..<HASH> 100644 --- a/View/ViewHandler.php +++ b/View/ViewHandler.php @@ -211,7 +211,7 @@ class ViewHandler extends ContainerAware implements ViewHandlerInterface $code = isset($this->forceRedirects[$format]) ? $this->forceRedirects[$format] : $this->getStatusCodeFromView($view); - if ('html' === $format) { + if ('html' === $format && isset($this->forceRedirects[$format])) { $response = new RedirectResponse($location, $code); $response->headers->replace($view->getHeaders()); } else {
only use a RedirectResponse if redirect is forced
FriendsOfSymfony_FOSRestBundle
train
0c20b9a79e6a600b87362364717f0d6a67a2ce23
diff --git a/kernel/content/ezcontentoperationcollection.php b/kernel/content/ezcontentoperationcollection.php index <HASH>..<HASH> 100644 --- a/kernel/content/ezcontentoperationcollection.php +++ b/kernel/content/ezcontentoperationcollection.php @@ -1331,16 +1331,25 @@ class eZContentOperationCollection static public function updateAlwaysAvailable( $objectID, $newAlwaysAvailable ) { $object = eZContentObject::fetch( $objectID ); + $change = false; if ( $object->isAlwaysAvailable() & $newAlwaysAvailable == false ) { $object->setAlwaysAvailableLanguageID( false ); - eZContentCacheManager::clearContentCacheIfNeeded( $objectID ); + $change = true; } else if ( !$object->isAlwaysAvailable() & $newAlwaysAvailable == true ) { $object->setAlwaysAvailableLanguageID( $object->attribute( 'initial_language_id' ) ); + $change = true; + } + if ( $change ) + { eZContentCacheManager::clearContentCacheIfNeeded( $objectID ); + if ( !eZSearch::getEngine() instanceof eZSearchEngine ) + { + eZContentOperationCollection::registerSearchObject( $objectID ); + } } return array( 'status' => true );
Implemented: reindex object when always available flag is changed
ezsystems_ezpublish-legacy
train
48b4621dc04696d8aaf990391931f06e1661aeaf
diff --git a/ACKNOWLEDGEMENTS b/ACKNOWLEDGEMENTS index <HASH>..<HASH> 100644 --- a/ACKNOWLEDGEMENTS +++ b/ACKNOWLEDGEMENTS @@ -1,6 +1,7 @@ This is a list of people who has contributed to PyUSB 1.0 development. 1.0.0-a0: - * Thomas Reitmayr: thanks for your loads of patches to get PyUSB running with libusb 1.0. + * Thomas Reitmayr: thanks for your patches to get PyUSB running with libusb 1.0. * Carl Ritson: thanks for your patch to get minimal working of legacy layer. * Romain Aviolat: thanks for pointing out a mistake in the tutorial and to report a bug in ctrl_transfer. + * Xiaofan Chen: thanks for your effort testing PyUSB with libusb 1.0 Windows backend and on FreeBSD. diff --git a/usb/backend/libusb01.py b/usb/backend/libusb01.py index <HASH>..<HASH> 100644 --- a/usb/backend/libusb01.py +++ b/usb/backend/libusb01.py @@ -160,11 +160,11 @@ _usb_dev_handle = c_void_p _lib = None def _load_library(): - if sys.platform == 'win32': - libname = ctypes.util.find_library('libusb0') + candidates = ('usb', 'libusb0') + for candidate in candidates: + libname = ctypes.util.find_library(candidate) + if libname is not None: break else: - libname = ctypes.util.find_library('usb') - if libname is None: raise OSError('USB library could not be found') return CDLL(libname) diff --git a/usb/backend/libusb10.py b/usb/backend/libusb10.py index <HASH>..<HASH> 100644 --- a/usb/backend/libusb10.py +++ b/usb/backend/libusb10.py @@ -140,10 +140,23 @@ _init = None _libusb_device_handle = c_void_p def _load_library(): - libname = ctypes.util.find_library('usb-1.0') - if libname is None: + candidates = ('usb-1.0', 'libusb-1.0', 'usb') + for candidate in candidates: + libname = ctypes.util.find_library(candidate) + if libname is not None: break + else: raise OSError('USB library could not be found') - return CDLL(libname) + # Windows backend uses stdcall calling convention + if sys.platform == 'win32': + l = WinDLL(libname) + else: + l = CDLL(libname) + # On FreeBSD 8/9, libusb 1.0 and libusb 0.1 are in the same shared + # object libusb.so, so if we found libusb library name, we must assure + # it is 1.0 version. We just try to get some symbol from 1.0 version + if not hasattr(l, 'libusb_init'): + raise OSError('USB library could not be found') + return l def _setup_prototypes(lib): # void libusb_set_debug (libusb_context *ctx, int level)
* Implemented support for FreeBSD in the libusb <I> backend. Thanks to Xiaofan Chen. * Implemented partial support for libusb <I> Windows backend. Thanks to Xiaofan Chen. git-svn-id: <URL>
pyusb_pyusb
train
9a89f644fc56233f941f341ff176c0d0d2f538c1
diff --git a/test/mockServerLambda.test.js b/test/mockServerLambda.test.js index <HASH>..<HASH> 100644 --- a/test/mockServerLambda.test.js +++ b/test/mockServerLambda.test.js @@ -108,6 +108,27 @@ test('Lambda function invocations can be mocked', async (test) => { }); }); +test('Lambda function invocations can be mocked without specifying the request body', async (test) => { + const {lambda, mockServerClient} = test.context; + + const functionName = `test-${uuid()}`; + const expectedResponse = {response: 'result'}; + const expectedRequestBody = {test: 'value'}; + + await mockInvocation(mockServerClient, functionName, expectedResponse); + + // Verify that invocations succeed after mocking + const response = await lambda.invoke({ + FunctionName: functionName, + Payload: JSON.stringify(expectedRequestBody) + }).promise(); + + test.deepEqual(response, { + StatusCode: 200, + Payload: JSON.stringify(expectedResponse) + }); +}); + test('Lambda function invocations can be verified', async (test) => { const {lambda, mockServerClient} = test.context;
Add testcase for mock Lambda function invocations without body requirements
lifeomic_lambda-tools
train
89c6c03660a88a648bbd13b4e6696124fe46d013
diff --git a/flink-core/src/main/java/org/apache/flink/configuration/ConfigurationUtils.java b/flink-core/src/main/java/org/apache/flink/configuration/ConfigurationUtils.java index <HASH>..<HASH> 100755 --- a/flink-core/src/main/java/org/apache/flink/configuration/ConfigurationUtils.java +++ b/flink-core/src/main/java/org/apache/flink/configuration/ConfigurationUtils.java @@ -389,7 +389,7 @@ public class ConfigurationUtils { return (String) o; } else if (o.getClass() == Duration.class) { Duration duration = (Duration) o; - return String.format("%d ns", duration.toNanos()); + return TimeUtils.formatWithHighestUnit(duration); } else if (o instanceof List) { return ((List<?>) o) .stream() diff --git a/flink-core/src/test/java/org/apache/flink/configuration/ConfigurationTest.java b/flink-core/src/test/java/org/apache/flink/configuration/ConfigurationTest.java index <HASH>..<HASH> 100644 --- a/flink-core/src/test/java/org/apache/flink/configuration/ConfigurationTest.java +++ b/flink-core/src/test/java/org/apache/flink/configuration/ConfigurationTest.java @@ -340,8 +340,7 @@ public class ConfigurationTest extends TestLogger { assertEquals(listValues, configuration.toMap().get(listConfigOption.key())); assertEquals(mapValues, configuration.toMap().get(mapConfigOption.key())); - assertEquals( - duration.toNanos() + " ns", configuration.toMap().get(durationConfigOption.key())); + assertEquals("3 s", configuration.toMap().get(durationConfigOption.key())); } enum TestEnum { diff --git a/flink-core/src/test/java/org/apache/flink/configuration/ConfigurationUtilsTest.java b/flink-core/src/test/java/org/apache/flink/configuration/ConfigurationUtilsTest.java index <HASH>..<HASH> 100644 --- a/flink-core/src/test/java/org/apache/flink/configuration/ConfigurationUtilsTest.java +++ b/flink-core/src/test/java/org/apache/flink/configuration/ConfigurationUtilsTest.java @@ -22,13 +22,17 @@ import org.apache.flink.util.TestLogger; import org.junit.Test; +import java.time.Duration; +import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; +import java.util.List; import java.util.Map; import java.util.Properties; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.is; +import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertThat; /** Tests for the {@link ConfigurationUtils}. */ @@ -92,4 +96,29 @@ public class ConfigurationUtilsTest extends TestLogger { assertThat(resultKeyValuePairs, is(equalTo(expectedKeyValuePairs))); } + + @Test + public void testConvertToString() { + // String + assertEquals("Simple String", ConfigurationUtils.convertToString("Simple String")); + + // Duration + assertEquals("0 ms", ConfigurationUtils.convertToString(Duration.ZERO)); + assertEquals("123 ms", ConfigurationUtils.convertToString(Duration.ofMillis(123L))); + assertEquals("1234 s", ConfigurationUtils.convertToString(Duration.ofMillis(1_234_000L))); + assertEquals("25 h", ConfigurationUtils.convertToString(Duration.ofHours(25L))); + + // List + final List<Object> listElements = new ArrayList<>(); + listElements.add("Test;String"); + listElements.add(Duration.ZERO); + listElements.add(42); + assertEquals("'Test;String';0 ms;42", ConfigurationUtils.convertToString(listElements)); + + // Map + final Map<Object, Object> mapElements = new HashMap<>(); + mapElements.put("A:,B", "C:,D"); + mapElements.put(10, 20); + assertEquals("'''A:,B'':''C:,D''',10:20", ConfigurationUtils.convertToString(mapElements)); + } } diff --git a/flink-table/flink-sql-client/src/test/java/org/apache/flink/table/client/config/YamlConfigUtilsTest.java b/flink-table/flink-sql-client/src/test/java/org/apache/flink/table/client/config/YamlConfigUtilsTest.java index <HASH>..<HASH> 100644 --- a/flink-table/flink-sql-client/src/test/java/org/apache/flink/table/client/config/YamlConfigUtilsTest.java +++ b/flink-table/flink-sql-client/src/test/java/org/apache/flink/table/client/config/YamlConfigUtilsTest.java @@ -112,8 +112,8 @@ public class YamlConfigUtilsTest { "parallelism.default=1", "pipeline.auto-watermark-interval=99", "pipeline.max-parallelism=16", - "restart-strategy.failure-rate.delay=1000000000 ns", - "restart-strategy.failure-rate.failure-rate-interval=99000000000 ns", + "restart-strategy.failure-rate.delay=1 s", + "restart-strategy.failure-rate.failure-rate-interval=99 s", "restart-strategy.failure-rate.max-failures-per-interval=10", "restart-strategy.fixed-delay.delay=1000", "restart-strategy=failure-rate",
[FLINK-<I>][core] Format durations with highest unit When converting a configuration value to a string, durations were formatted in nanoseconds regardless of their values. This produces serialized outputs which are hard to understand for humans. The functionality of formatting in the highest unit which allows the value to be an integer already exists, thus we can simply defer to it to produce a more useful result. This closes #<I>.
apache_flink
train
8ef29713698f9a6478f65e6c4f4772f3e62018ec
diff --git a/claripy/operations.py b/claripy/operations.py index <HASH>..<HASH> 100644 --- a/claripy/operations.py +++ b/claripy/operations.py @@ -341,7 +341,11 @@ def boolean_and_simplifier(*args): if len(new_args) < len(args): return ast.all_operations.And(*new_args) - return _flatten_simplifier('And', None, *args) + def _flattening_filter(args): + # a And a == a + return tuple(set(args)) + + return _flatten_simplifier('And', _flattening_filter, *args) def boolean_or_simplifier(*args): if len(args) == 1: @@ -357,7 +361,11 @@ def boolean_or_simplifier(*args): if len(new_args) < len(args): return ast.all_operations.Or(*new_args) - return _flatten_simplifier('Or', None, *args) + def _flattening_filter(args): + # a Or a == a + return tuple(set(args)) + + return _flatten_simplifier('Or', _flattening_filter, *args) def _flatten_simplifier(op_name, filter, *args): if not any(isinstance(a, ast.Base) and a.op == op_name for a in args): @@ -416,7 +424,11 @@ def bitwise_or_simplifier(a, b): elif a is b: return a - return _flatten_simplifier('__or__', None, a, b) + def _flattening_filter(args): + # a | a == a + return tuple(set(args)) + + return _flatten_simplifier('__or__', _flattening_filter, a, b) def bitwise_and_simplifier(a, b): if (a == 2**a.size()-1).is_true(): @@ -428,7 +440,11 @@ def bitwise_and_simplifier(a, b): elif a is b: return a - return _flatten_simplifier('__and__', None, a, b) + def _flattening_filter(args): + # a & a == a + return tuple(set(args)) + + return _flatten_simplifier('__and__', _flattening_filter, a, b) def boolean_not_simplifier(body): if body.op == '__eq__':
Implement flattening argument filters for other operations.
angr_claripy
train
e8a15f267ebfdc93cc0bb94ff080ab099699c5e2
diff --git a/lib/typhoid/typhoeus_decorator.rb b/lib/typhoid/typhoeus_decorator.rb index <HASH>..<HASH> 100644 --- a/lib/typhoid/typhoeus_decorator.rb +++ b/lib/typhoid/typhoeus_decorator.rb @@ -1,26 +1,26 @@ module Typhoid class TyphoeusDecorator < Struct.new(:source) def self.decorate(typhoeus_klass) - @klass_to_decorate = typhoeus_klass + @source_klass = typhoeus_klass end - def self.klass_to_decorate - @klass_to_decorate + def self.source_klass + @source_klass end def self.new(*args, &block) if args.first.is_a?(self) args.first - elsif args.first.is_a?(klass_to_decorate) + elsif args.first.is_a?(source_klass) super else - super(klass_to_decorate.new(*args, &block)) + super(source_klass.new(*args, &block)) end end def self.method_missing(method_name, *args, &block) - if klass_to_decorate.respond_to? method_name - klass_to_decorate.public_send method_name, *args, &block + if source_klass.respond_to? method_name + source_klass.public_send method_name, *args, &block else super end
rename to source_klass
sportngin_typhoid
train
05f2618377e895738e88b13baae1ff3ecdba4621
diff --git a/core/lib/generators/refinerycms_generator.rb b/core/lib/generators/refinerycms_generator.rb index <HASH>..<HASH> 100644 --- a/core/lib/generators/refinerycms_generator.rb +++ b/core/lib/generators/refinerycms_generator.rb @@ -88,14 +88,13 @@ class RefinerycmsGenerator < ::Refinery::Generators::EngineInstaller # Seeds and migrations now need to be copied from their various engines. unless self.options[:update] -=begin existing_source_root = self.class.source_root ::Refinery::Plugins.registered.pathnames.reject{|p| !p.join('db').directory?}.each do |pathname| self.class.source_root pathname super end self.class.source_root existing_source_root -=end + super # The engine installer only installs database templates.
We do actually want migrations, parndt, come on.
refinery_refinerycms
train
cdb84f231a0180e19fbd872ded3f97eac6193ea0
diff --git a/classes/PodsData.php b/classes/PodsData.php index <HASH>..<HASH> 100644 --- a/classes/PodsData.php +++ b/classes/PodsData.php @@ -1766,9 +1766,8 @@ class PodsData { $mode = 'id'; $id = pods_absint( $row ); - if ( !is_numeric( $row ) || 0 === strpos( $row, '0' ) || $row != preg_replace( '/[^0-9]/', '', $row ) ) { - $mode = 'slug'; - $id = $row; + if ( ! is_numeric( $row ) || 0 === strpos( $row, '0' ) || $row != preg_replace( '/[^0-9]/', '', $row ) ) { + $id = $this->id; } $row = false;
*Set the id to the id property instead of setting to $row and changing the $mode
pods-framework_pods
train
9d38fb784bb6b8154c4666948efab7e0cf3867d0
diff --git a/spec/mongo/client_spec.rb b/spec/mongo/client_spec.rb index <HASH>..<HASH> 100644 --- a/spec/mongo/client_spec.rb +++ b/spec/mongo/client_spec.rb @@ -2,14 +2,6 @@ require 'spec_helper' describe Mongo::Client do - before do - if running_ssl? - allow_any_instance_of(Mongo::Server::Monitor).to receive(:ismaster) do - [{}, 1] - end - end - end - describe '#==' do let(:client) do
No need to mock Monitor when running ssl
mongodb_mongo-ruby-driver
train
bf586ddbeea4df44ebf9a21a17e12243bad0a327
diff --git a/command/sdist.py b/command/sdist.py index <HASH>..<HASH> 100644 --- a/command/sdist.py +++ b/command/sdist.py @@ -107,23 +107,23 @@ class sdist (Command): def check_metadata (self): - dist = self.distribution + metadata = self.distribution.metadata missing = [] for attr in ('name', 'version', 'url'): - if not (hasattr (dist, attr) and getattr (dist, attr)): + if not (hasattr (metadata, attr) and getattr (metadata, attr)): missing.append (attr) if missing: self.warn ("missing required meta-data: " + string.join (missing, ", ")) - if dist.author: - if not dist.author_email: + if metadata.author: + if not metadata.author_email: self.warn ("missing meta-data: if 'author' supplied, " + "'author_email' must be supplied too") - elif dist.maintainer: - if not dist.maintainer_email: + elif metadata.maintainer: + if not metadata.maintainer_email: self.warn ("missing meta-data: if 'maintainer' supplied, " + "'maintainer_email' must be supplied too") else:
Fix 'check_metadata()' so it grovels through the distribution's metadata object, rather than through the distribution itself (since I moved the meta- data out to a DistributionMetadata instance).
pypa_setuptools
train
8c9bbe375ffc7fccfe040c62cbda4cd85a88ef8a
diff --git a/src/Services/LayoutService.php b/src/Services/LayoutService.php index <HASH>..<HASH> 100644 --- a/src/Services/LayoutService.php +++ b/src/Services/LayoutService.php @@ -89,4 +89,12 @@ final class LayoutService extends Service { return $this->client()->put($data, 'layouts/{layoutId}', ['layoutId' => $layoutId]); } + + /** + * @param string $layoutId + */ + public function delete($layoutId) + { + $this->client()->delete('layouts/{layoutId}', ['layoutId' => $layoutId]); + } }
Add delete method for layouts (#<I>)
Rebilly_rebilly-php
train
34ca201ff0cd4020631c8e57ec33ef8935aa5028
diff --git a/datajoint/blob.py b/datajoint/blob.py index <HASH>..<HASH> 100644 --- a/datajoint/blob.py +++ b/datajoint/blob.py @@ -68,6 +68,7 @@ class Blob: self._squeeze = squeeze self._blob = None self._pos = 0 + self._pos_prev = 0 self.protocol = None self.is_32_bit = is_32_bit @@ -435,7 +436,13 @@ class Blob: def read_value(self, dtype=None, count=1): if dtype is None: dtype = 'uint32' if self.is_32_bit else 'uint64' - data = np.frombuffer(self._blob, dtype=dtype, count=count, offset=self._pos) + try: + data = np.frombuffer(self._blob, dtype=dtype, count=count, offset=self._pos) + except ValueError: + self.is_32_bit = True + self._pos = self._pos_prev + data = np.frombuffer(self._blob, dtype='uint32', count=self.read_value(), offset=self._pos) + self._pos_prev = self._pos self._pos += data.dtype.itemsize * data.size return data[0] if count == 1 else data @@ -468,7 +475,4 @@ def unpack(blob, squeeze=False): assert isinstance(blob, bytes) and blob.startswith((b'ZL123\0', b'mYm\0', b'dj0\0')) return blob if blob is not None: - try: - return Blob(squeeze=squeeze).unpack(blob) - except: - return Blob(squeeze=squeeze, is_32_bit=True).unpack(blob) + return Blob(squeeze=squeeze).unpack(blob) diff --git a/tests/test_blob.py b/tests/test_blob.py index <HASH>..<HASH> 100644 --- a/tests/test_blob.py +++ b/tests/test_blob.py @@ -134,11 +134,19 @@ def test_complex(): def test_insert_longblob(): - import numpy as np - # schema.Testmym.insert1({'id': 1, 'data': np.recarray(np.array([[(np.array([[np.nan, 1., 1., 0., 1., 0., np.nan]]), np.array(['llllrrl'], dtype='<U7'), np.array(['ddddddd'], dtype='<U7'), np.array(['Stage 10'], dtype='<U8'))]]), dtype=[('hits', 'O'), ('sides', 'O'), ('tasks', 'O'), ('stage', 'O')])}) - dj.conn().query("INSERT INTO djtest_test1.testmym (id, data) VALUES (1, X'6D596D00530200000001000000010000000400000068697473007369646573007461736B73007374616765004D000000410200000001000000070000000600000000000000000000000000F8FF000000000000F03F000000000000F03F0000000000000000000000000000F03F0000000000000000000000000000F8FF230000004102000000010000000700000004000000000000006C006C006C006C00720072006C002300000041020000000100000007000000040000000000000064006400640064006400640064002500000041020000000100000008000000040000000000000053007400610067006500200031003000')").fetchall() - # dj.conn().query("INSERT INTO djtest_test1.testmym (id, data) VALUES (1, X'646A300002060000000000000004000000000000000A01000104000000000000000A01000204000000000000000A01000304000000000000000A01000404000000000000000A01000504000000000000000A010006')").fetchall() - print('\n',dj.conn().query("SELECT hex(data) FROM djtest_test1.testmym").fetchall()) - print((schema.Testmym & 'id=1').fetch1()) - schema.Testmym.drop() - assert True \ No newline at end of file + query = ("INSERT INTO djtest_test1.testmym (id, data) VALUES (1, " + "X'6D596D00530200000001000000010000000400000068697473007369646573007461736B73007374" + "616765004D000000410200000001000000070000000600000000000000000000000000F8FF00000000" + "0000F03F000000000000F03F0000000000000000000000000000F03F00000000000000000000000000" + "00F8FF230000004102000000010000000700000004000000000000006C006C006C006C00720072006C" + "0023000000410200000001000000070000000400000000000000640064006400640064006400640025" + "00000041020000000100000008000000040000000000000053007400610067006500200031003000')") + dj.conn().query(query).fetchall() + data_32 = {'id': 1, 'data':np.rec.array([[( + np.array([[ + np.nan, 1., 1., 0., 1., 0., np.nan]]), + np.array(['llllrrl'], dtype='<U7'), + np.array(['ddddddd'], dtype='<U7'), + np.array(['Stage 10'], dtype='<U8'))]], + dtype=[('hits', 'O'), ('sides', 'O'), ('tasks', 'O'), ('stage', 'O')])} + assert (schema.Testmym & 'id=1').fetch1() == data_32 \ No newline at end of file
moved try catch into `read_value`
datajoint_datajoint-python
train
de6aae79af7342be09edd4a8e54d38b1e92d7bba
diff --git a/Search/Adapter/TestAdapter.php b/Search/Adapter/TestAdapter.php index <HASH>..<HASH> 100644 --- a/Search/Adapter/TestAdapter.php +++ b/Search/Adapter/TestAdapter.php @@ -87,7 +87,7 @@ class TestAdapter implements AdapterInterface public function search(SearchQuery $searchQuery) { $hits = array(); - $indexes = $searchQuery->getIndexes() ? : array_keys($this->documents); + $indexes = $searchQuery->getIndexes(); foreach ($indexes as $index) { if (!isset($this->documents[$index])) {
temporarily disabled global search feature of test adapter
massiveart_MassiveSearchBundle
train
8563dcfddf23d8b92a3daba517d49fd5350d3353
diff --git a/src/main/java/water/parser/ParseDataset.java b/src/main/java/water/parser/ParseDataset.java index <HASH>..<HASH> 100644 --- a/src/main/java/water/parser/ParseDataset.java +++ b/src/main/java/water/parser/ParseDataset.java @@ -1,17 +1,16 @@ package water.parser; + +import com.google.common.base.Throwables; +import com.google.common.io.Closeables; import java.io.IOException; import java.util.zip.*; - -import jsr166y.RecursiveAction; +import jsr166y.CountedCompleter; import water.*; import water.Jobs.Fail; import water.Jobs.Job; import water.Jobs.Progress; import water.parser.DParseTask.Pass; -import com.google.common.base.Throwables; -import com.google.common.io.Closeables; - /** * Helper class to parse an entire ValueArray data, and produce a structured * ValueArray result. @@ -79,12 +78,13 @@ public final class ParseDataset { public static Job forkParseDataset( final Key dest, final Value dataset, final CsvParser.Setup setup ) { final Job job = Jobs.start("Parse", dest); - H2O.FJP_NORM.submit(new RecursiveAction() { - @Override - protected void compute() { - parse(job, dataset, setup); - } - }); + H2O.FJP_NORM.submit(new CountedCompleter() { + @Override public void compute() { parse(job, dataset, setup); tryComplete(); } + public boolean onExceptionalCompletion( Throwable ex, CountedCompleter caller ) { + ex.printStackTrace(); + return true; + } + }); return job; }
Include stack dump from F/J tasks
h2oai_h2o-2
train
7c2e0288ef15099d45accc5fd5063ef2ea0af395
diff --git a/spec/APNS.spec.js b/spec/APNS.spec.js index <HASH>..<HASH> 100644 --- a/spec/APNS.spec.js +++ b/spec/APNS.spec.js @@ -184,7 +184,7 @@ describe('APNS', () => { 'key': 'value', 'keyAgain': 'valueAgain' }); - expect(notification.expiry).toEqual(expirationTime / 1000); + expect(notification.expiry).toEqual(Math.round(expirationTime / 1000)); expect(notification.collapseId).toEqual(collapseId); done(); }); @@ -208,7 +208,7 @@ describe('APNS', () => { let notification = APNS._generateNotification(data, { expirationTime: expirationTime, collapseId: collapseId }); - expect(notification.expiry).toEqual(expirationTime / 1000); + expect(notification.expiry).toEqual(Math.round(expirationTime / 1000)); expect(notification.collapseId).toEqual(collapseId); let stringifiedJSON = notification.compile(); @@ -307,7 +307,7 @@ describe('APNS', () => { let calledArgs = provider.send.calls.first().args; let notification = calledArgs[0]; expect(notification.aps.alert).toEqual(data.data.alert); - expect(notification.expiry).toEqual(data['expiration_time'] / 1000); + expect(notification.expiry).toEqual(Math.round(data['expiration_time'] / 1000)); expect(notification.collapseId).toEqual(data['collapse_id']); let apnDevices = calledArgs[1]; expect(apnDevices.length).toEqual(4); @@ -383,7 +383,7 @@ describe('APNS', () => { let calledArgs = provider.send.calls.first().args; let notification = calledArgs[0]; expect(notification.aps.alert).toEqual(data.data.alert); - expect(notification.expiry).toEqual(data['expiration_time'] / 1000); + expect(notification.expiry).toEqual(Math.round(data['expiration_time'] / 1000)); expect(notification.collapseId).toEqual(data['collapse_id']); let apnDevices = calledArgs[1]; expect(apnDevices.length).toBe(3); @@ -392,7 +392,7 @@ describe('APNS', () => { calledArgs = providerDev.send.calls.first().args; notification = calledArgs[0]; expect(notification.aps.alert).toEqual(data.data.alert); - expect(notification.expiry).toEqual(data['expiration_time'] / 1000); + expect(notification.expiry).toEqual(Math.round(data['expiration_time'] / 1000)); expect(notification.collapseId).toEqual(data['collapse_id']); apnDevices = calledArgs[1]; expect(apnDevices.length).toBe(2); diff --git a/src/APNS.js b/src/APNS.js index <HASH>..<HASH> 100644 --- a/src/APNS.js +++ b/src/APNS.js @@ -209,7 +209,7 @@ export class APNS { notification.payload = payload; notification.topic = headers.topic; - notification.expiry = headers.expirationTime / 1000; + notification.expiry = Math.round(headers.expirationTime / 1000); notification.collapseId = headers.collapseId; return notification; }
make sure we always send apns-expiration as integer number (#<I>) * make sure we always send integer as apns-expiration * make sure we always send apns-expiration parameter as integer
parse-community_parse-server-push-adapter
train
f7ae159bb72a667fef3755cc3b9cc056d33c9b1e
diff --git a/lib/commands/prepare.js b/lib/commands/prepare.js index <HASH>..<HASH> 100644 --- a/lib/commands/prepare.js +++ b/lib/commands/prepare.js @@ -21,7 +21,8 @@ function Prepare (options, callback) util.inherits(Prepare, Command); Prepare.prototype.start = function (packet, connection) { - connection.writePacket(new Packets.PrepareStatement(this.query).toPacket(1)); + var cmdPacket = new Packets.PrepareStatement(this.query, connection.config.charsetNumber); + connection.writePacket(cmdPacket.toPacket(1)); return Prepare.prototype.prepareHeader; }; diff --git a/lib/commands/query.js b/lib/commands/query.js index <HASH>..<HASH> 100644 --- a/lib/commands/query.js +++ b/lib/commands/query.js @@ -35,7 +35,7 @@ Query.prototype.start = function (packet, connection) { console.log(' Sending query command: %s', this.sql); } this._connection = connection; - var cmdPacket = new Packets.Query(this.sql); + var cmdPacket = new Packets.Query(this.sql, connection.config.charsetNumber); connection.writePacket(cmdPacket.toPacket(1)); return Query.prototype.resultsetHeader; }; diff --git a/lib/packets/packet.js b/lib/packets/packet.js index <HASH>..<HASH> 100644 --- a/lib/packets/packet.js +++ b/lib/packets/packet.js @@ -729,7 +729,7 @@ Packet.prototype.writeNullTerminatedString = function (s) { this.writeInt8(0); }; -Packet.prototype.writeString = function (s) { +Packet.prototype.writeString = function (s, encoding) { if (s === null) { this.writeInt8(0xfb); @@ -744,7 +744,7 @@ Packet.prototype.writeString = function (s) { // this.buffer.write(s, this.offset, bytes, 'utf8'); // this.offset += bytes; - var buf = StringParser.encode(s, 'cesu8'); + var buf = StringParser.encode(s, encoding || 'cesu8'); this.offset += buf.copy(this.buffer, this.offset); }; diff --git a/lib/packets/prepare_statement.js b/lib/packets/prepare_statement.js index <HASH>..<HASH> 100644 --- a/lib/packets/prepare_statement.js +++ b/lib/packets/prepare_statement.js @@ -3,20 +3,24 @@ var Packet = require('../packets/packet'); var CommandCodes = require('../constants/commands'); var StringParser = require('../parsers/string.js'); -function PrepareStatement (sql) +function PrepareStatement (sql, charsetNumber) { this.query = sql; + this.charsetNumber = charsetNumber; } PrepareStatement.prototype.toPacket = function () { + // TODO: use this.charsetNumber and get proper encoding type var buf = StringParser.encode(this.query, 'cesu8'); var length = 5 + buf.length; + var buffer = Buffer.allocUnsafe(length); var packet = new Packet(0, buffer, 0, length); packet.offset = 4; packet.writeInt8(CommandCodes.STMT_PREPARE); - packet.writeString(this.query); + // TODO: pass down encoding to this method too + packet.writeString(this.query, 'cesu8'); return packet; }; diff --git a/lib/packets/query.js b/lib/packets/query.js index <HASH>..<HASH> 100644 --- a/lib/packets/query.js +++ b/lib/packets/query.js @@ -11,13 +11,16 @@ function Query (sql, charsetNumber) Query.prototype.toPacket = function () { + // TODO: use this.charsetNumber and get proper encoding type var buf = StringParser.encode(this.query, 'cesu8'); var length = 5 + buf.length; + var buffer = Buffer.allocUnsafe(length); var packet = new Packet(0, buffer, 0, length); packet.offset = 4; packet.writeInt8(CommandCode.QUERY); - packet.writeString(this.query); + // TODO: pass down encoding to this method too + packet.writeString(this.query, 'cesu8'); return packet; };
added possibility of using encoding while writing strings
sidorares_node-mysql2
train
c40df3a287110bc86f8b9f559a20d0771e3b0e88
diff --git a/libcentrifugo/integration/integration_test.go b/libcentrifugo/integration/integration_test.go index <HASH>..<HASH> 100644 --- a/libcentrifugo/integration/integration_test.go +++ b/libcentrifugo/integration/integration_test.go @@ -4,6 +4,7 @@ import ( "encoding/json" "fmt" "strconv" + "sync" "testing" "time" @@ -206,26 +207,34 @@ func createTestClients(n *node.Node, nChannels, nChannelClients int, sink chan [ subscribeBytes[j] = []byte(`{"method": "subscribe", "params": {"channel": "` + fmt.Sprintf("channel-%d", j) + `"}}`) } + var wg sync.WaitGroup + + wg.Add(nChannelClients) + for i := 0; i < nChannelClients; i++ { - sess := NewTestSession() - if sink != nil { - sess.sink = sink - } - c := newTestClient(n, sess) + go func(i int) { + defer wg.Done() + sess := NewTestSession() + if sink != nil { + sess.sink = sink + } + c := newTestClient(n, sess) - connectBytes := []byte(`{"method": "connect", "params": {"user": "` + fmt.Sprintf("user-%d", i) + `"}}`) + connectBytes := []byte(`{"method": "connect", "params": {"user": "` + fmt.Sprintf("user-%d", i) + `"}}`) - err := c.Handle(connectBytes) - if err != nil { - panic(err) - } - for j := 0; j < nChannels; j++ { - err := c.Handle(subscribeBytes[j]) + err := c.Handle(connectBytes) if err != nil { panic(err) } - } + for j := 0; j < nChannels; j++ { + err := c.Handle(subscribeBytes[j]) + if err != nil { + panic(err) + } + } + }(i) } + wg.Wait() } // BenchmarkPubSubMessageReceive allows to estimate how many new messages we can convert to client JSON messages. @@ -357,8 +366,8 @@ func BenchmarkEngineMessageUnmarshal(b *testing.B) { // amount. func BenchmarkReceiveBroadcast(b *testing.B) { nChannels := 1000 - nClients := 1000 - nCommands := 10000 + nClients := 100 + nCommands := 100 nMessages := nCommands * nClients sink := make(chan []byte, nMessages) app := NewTestMemoryNode()
create clients for bench faster, update BenchmarkReceiveBroadcast
centrifugal_centrifugo
train
4f8f2087c16ec8b6d9b785edbaba1c073ad15fc3
diff --git a/src/structures/CategoryChannel.js b/src/structures/CategoryChannel.js index <HASH>..<HASH> 100644 --- a/src/structures/CategoryChannel.js +++ b/src/structures/CategoryChannel.js @@ -13,6 +13,19 @@ class CategoryChannel extends GuildChannel { get children() { return this.guild.channels.filter(c => c.parentID === this.id); } + + /** + * Sets the category parent of this channel. + * <warn>It is not currently possible to set the parent of a CategoryChannel.</warn> + * @method setParent + * @memberof CategoryChannel + * @instance + * @param {?GuildChannel|Snowflake} channel Parent channel + * @param {Object} [options={}] Options to pass + * @param {boolean} [options.lockPermissions=true] Lock the permissions to what the parent's permissions are + * @param {string} [options.reason] Reason for modifying the parent of this channel + * @returns {Promise<GuildChannel>} + */ } module.exports = CategoryChannel; diff --git a/src/structures/GuildChannel.js b/src/structures/GuildChannel.js index <HASH>..<HASH> 100644 --- a/src/structures/GuildChannel.js +++ b/src/structures/GuildChannel.js @@ -323,14 +323,15 @@ class GuildChannel extends Channel { /** * Sets the category parent of this channel. - * @param {GuildChannel|Snowflake} channel Parent channel - * @param {boolean} [options.lockPermissions] Lock the permissions to what the parent's permissions are + * @param {?GuildChannel|Snowflake} channel Parent channel + * @param {Object} [options={}] Options to pass + * @param {boolean} [options.lockPermissions=true] Lock the permissions to what the parent's permissions are * @param {string} [options.reason] Reason for modifying the parent of this channel * @returns {Promise<GuildChannel>} */ setParent(channel, { lockPermissions = true, reason } = {}) { return this.edit({ - parentID: channel.id ? channel.id : channel, + parentID: channel !== null ? channel.id ? channel.id : channel : null, lockPermissions, }, reason); }
docs/fix(setParent): docs update and nullable channel param (#<I>) * fix(setParent): no longer in GuildChannel * refactored * little bit less ugly * space/appel suggestion * docs fix * shhhhhhhh * fun docs trip * prototype thing * mark nullable
discordjs_discord.js
train
1a11697cd3404a7f308c05850c443fe4303b0a78
diff --git a/pyros/rosinterface/ros_interface.py b/pyros/rosinterface/ros_interface.py index <HASH>..<HASH> 100644 --- a/pyros/rosinterface/ros_interface.py +++ b/pyros/rosinterface/ros_interface.py @@ -449,10 +449,22 @@ class RosInterface(BaseInterface): diff_opt=True, diff_sub='~connections_diff' ) - except rocon_python_comms.ConnectionCacheProxy.InitializationTimeout as timeout_exc: + + except AttributeError as attr_exc: + # attribute error (likely rocon_python_comms doesnt have ConnectionCacheProxy) + # NOT EXPECTED System configuration problem : BE LOUD ! # timeout initializing : disabling the feature but we should be LOUD about it rospy.logwarn("Pyros.rosinterface : FAILED during initialization of Connection Cache Proxy. Disabling.") + import traceback + rospy.logwarn('Exception: {0}'.format(traceback.format_stack())) self.enable_cache = False + + except rocon_python_comms.ConnectionCacheProxy.InitializationTimeout as timeout_exc: + + # timeout initializing : disabling the feature but we should WARN about it + rospy.logwarn("Pyros.rosinterface : TIMEOUT during initialization of Connection Cache Proxy. Disabling.") + self.enable_cache = False + else: rospy.loginfo("Pyros.rosinterface : Connection Cache Optimization enabled")
now fails with explanation if ConnectionCacheProxy not available in rocon_python_comms.
pyros-dev_pyros
train
eaedde325e7137a1a865232791714910b0973965
diff --git a/core/src/main/java/com/orientechnologies/orient/core/db/ODatabaseDocumentInternal.java b/core/src/main/java/com/orientechnologies/orient/core/db/ODatabaseDocumentInternal.java index <HASH>..<HASH> 100644 --- a/core/src/main/java/com/orientechnologies/orient/core/db/ODatabaseDocumentInternal.java +++ b/core/src/main/java/com/orientechnologies/orient/core/db/ODatabaseDocumentInternal.java @@ -41,6 +41,7 @@ import com.orientechnologies.orient.core.sql.parser.OLocalResultSetLifecycleDeco import com.orientechnologies.orient.core.storage.ORecordCallback; import com.orientechnologies.orient.core.storage.OStorage; import com.orientechnologies.orient.core.tx.OTransaction; +import com.orientechnologies.orient.core.tx.OTransactionOptimistic; import java.util.Map; @@ -187,9 +188,9 @@ public interface ODatabaseDocumentInternal extends ODatabaseSession, ODatabaseIn /** * sends an execution plan to a remote node for a remote query execution * - * @param nodeName the node name - * @param executionPlan the execution plan - * @param inputParameters the input parameters for execution + * @param nodeName the node name + * @param executionPlan the execution plan + * @param inputParameters the input parameters for execution * * @return an OResultSet to fetch the results of the query execution */ @@ -197,4 +198,5 @@ public interface ODatabaseDocumentInternal extends ODatabaseSession, ODatabaseIn throw new UnsupportedOperationException(); } + void internalCommit(OTransactionOptimistic transaction); } diff --git a/core/src/main/java/com/orientechnologies/orient/core/db/document/ODatabaseDocumentAbstract.java b/core/src/main/java/com/orientechnologies/orient/core/db/document/ODatabaseDocumentAbstract.java index <HASH>..<HASH> 100755 --- a/core/src/main/java/com/orientechnologies/orient/core/db/document/ODatabaseDocumentAbstract.java +++ b/core/src/main/java/com/orientechnologies/orient/core/db/document/ODatabaseDocumentAbstract.java @@ -3125,4 +3125,8 @@ public abstract class ODatabaseDocumentAbstract extends OListenerManger<ODatabas return activeQueries.get(id); } + @Override + public void internalCommit(OTransactionOptimistic transaction) { + this.getStorage().commit(transaction, null); + } } \ No newline at end of file diff --git a/core/src/main/java/com/orientechnologies/orient/core/db/document/ODatabaseDocumentTx.java b/core/src/main/java/com/orientechnologies/orient/core/db/document/ODatabaseDocumentTx.java index <HASH>..<HASH> 100644 --- a/core/src/main/java/com/orientechnologies/orient/core/db/document/ODatabaseDocumentTx.java +++ b/core/src/main/java/com/orientechnologies/orient/core/db/document/ODatabaseDocumentTx.java @@ -44,6 +44,7 @@ import com.orientechnologies.orient.core.sql.OCommandSQLParsingException; import com.orientechnologies.orient.core.sql.executor.OResultSet; import com.orientechnologies.orient.core.storage.*; import com.orientechnologies.orient.core.tx.OTransaction; +import com.orientechnologies.orient.core.tx.OTransactionOptimistic; import com.orientechnologies.orient.core.util.OURLConnection; import com.orientechnologies.orient.core.util.OURLHelper; @@ -140,7 +141,7 @@ public class ODatabaseDocumentTx implements ODatabaseDocumentInternal { factory = (OrientDBEmbedded) embedded.get(baseUrl); if (factory == null || !factory.isOpen()) { try { - factory= OrientDBInternal.distributed(baseUrl, config); + factory = OrientDBInternal.distributed(baseUrl, config); } catch (ODatabaseException ex) { factory = (OrientDBEmbedded) OrientDBInternal.embedded(baseUrl, config); } @@ -1632,4 +1633,9 @@ public class ODatabaseDocumentTx implements ODatabaseDocumentInternal { checkOpenness(); internal.recycle(record); } + + @Override + public void internalCommit(OTransactionOptimistic transaction) { + internal.internalCommit(transaction); + } } diff --git a/core/src/main/java/com/orientechnologies/orient/core/tx/OTransactionOptimistic.java b/core/src/main/java/com/orientechnologies/orient/core/tx/OTransactionOptimistic.java index <HASH>..<HASH> 100755 --- a/core/src/main/java/com/orientechnologies/orient/core/tx/OTransactionOptimistic.java +++ b/core/src/main/java/com/orientechnologies/orient/core/tx/OTransactionOptimistic.java @@ -536,7 +536,7 @@ public class OTransactionOptimistic extends OTransactionRealAbstract { status = TXSTATUS.COMMITTING; if (!allEntries.isEmpty() || !indexEntries.isEmpty()) { - database.getStorage().commit(this, null); + database.internalCommit(this); } invokeCallbacks();
refactor to move commit logic control inside the database implementation
orientechnologies_orientdb
train
f5406a832da145ecb6bc29a2e4ea76d54c078730
diff --git a/rollbar/test/asgi_tests/test_middleware.py b/rollbar/test/asgi_tests/test_middleware.py index <HASH>..<HASH> 100644 --- a/rollbar/test/asgi_tests/test_middleware.py +++ b/rollbar/test/asgi_tests/test_middleware.py @@ -36,7 +36,7 @@ class ReporterMiddlewareTest(BaseTest): with self.assertRaises(RuntimeError): run(testapp({'type': 'http'}, None, None)) - mock_report.assert_called_once() + self.assertTrue(mock_report.called) args, kwargs = mock_report.call_args self.assertEqual(kwargs, {}) @@ -61,8 +61,8 @@ class ReporterMiddlewareTest(BaseTest): with self.assertRaises(RuntimeError): run(testapp({'type': 'http'}, None, None)) - async_report_exc_info.assert_called_once() - sync_report_exc_info.assert_not_called() + self.assertTrue(async_report_exc_info.called) + self.assertFalse(sync_report_exc_info.called) @mock.patch('rollbar.lib._async.report_exc_info', new_callable=AsyncMock) @mock.patch('rollbar.report_exc_info') @@ -79,8 +79,8 @@ class ReporterMiddlewareTest(BaseTest): with self.assertRaises(RuntimeError): run(testapp({'type': 'http'}, None, None)) - async_report_exc_info.assert_called_once() - sync_report_exc_info.assert_not_called() + self.assertTrue(async_report_exc_info.called) + self.assertFalse(sync_report_exc_info.called) @mock.patch('rollbar.lib._async.report_exc_info', new_callable=AsyncMock) @mock.patch('rollbar.report_exc_info') @@ -97,8 +97,8 @@ class ReporterMiddlewareTest(BaseTest): with self.assertRaises(RuntimeError): run(testapp({'type': 'http'}, None, None)) - sync_report_exc_info.assert_called_once() - async_report_exc_info.assert_not_called() + self.assertFalse(async_report_exc_info.called) + self.assertTrue(sync_report_exc_info.called) def test_should_support_http_only(self): from rollbar.contrib.asgi.middleware import ReporterMiddleware @@ -110,13 +110,13 @@ class ReporterMiddlewareTest(BaseTest): with self.assertRaises(RuntimeError): run(testapp({'type': 'http'}, None, None)) - mock_report.assert_called_once() + self.assertTrue(mock_report.called) with mock.patch('rollbar.report_exc_info') as mock_report: with self.assertRaises(RuntimeError): run(testapp({'type': 'websocket'}, None, None)) - mock_report.assert_not_called() + self.assertFalse(mock_report.called) def test_should_support_type_hints(self): from rollbar.contrib.asgi.types import Receive, Scope, Send
Do not use `mock.assert_called_once()` for Python<I>-
rollbar_pyrollbar
train
c6a93c6c60d471a6ea5d1520cb4b4f2d9d8693cd
diff --git a/refcycle/i_directed_graph.py b/refcycle/i_directed_graph.py index <HASH>..<HASH> 100644 --- a/refcycle/i_directed_graph.py +++ b/refcycle/i_directed_graph.py @@ -77,21 +77,24 @@ class IDirectedGraph(Container, Iterable, Sized): """ - def vertex_set(self): + @classmethod + def vertex_set(cls): """ - Return an empty object of the correct type for storing a - set of vertices. Usually a plain set will suffice, but - for the ObjectGraph we'll use an ElementTransformSet instead. + Return an empty object suitable for storing a set of vertices. + + Usually a plain set will suffice, but for the ObjectGraph we'll use an + ElementTransformSet instead. """ return set() - def vertex_dict(self): + @classmethod + def vertex_dict(cls): """ Return an empty mapping whose keys are vertices. - Usually a plain dict is good enough; for the ObjectGraph - we'll override to use KeyTransformDict instead. + Usually a plain dict is good enough; for the ObjectGraph we'll override + to use KeyTransformDict instead. """ return dict() diff --git a/refcycle/object_graph.py b/refcycle/object_graph.py index <HASH>..<HASH> 100755 --- a/refcycle/object_graph.py +++ b/refcycle/object_graph.py @@ -123,10 +123,12 @@ class ObjectGraph(IDirectedGraph): ### Set and dict overrides. ########################################################################### - def vertex_set(self): + @classmethod + def vertex_set(cls): return ElementTransformSet(transform=id) - def vertex_dict(self): + @classmethod + def vertex_dict(cls): return KeyTransformDict(transform=id) ###########################################################################
Make vertex_set and vertex_dict classmethods.
mdickinson_refcycle
train
74b98611dcbd4ac2e0c831bcd9d5436841297ec5
diff --git a/wcomponents-core/src/main/java/com/github/bordertech/wcomponents/AbstractWComponent.java b/wcomponents-core/src/main/java/com/github/bordertech/wcomponents/AbstractWComponent.java index <HASH>..<HASH> 100755 --- a/wcomponents-core/src/main/java/com/github/bordertech/wcomponents/AbstractWComponent.java +++ b/wcomponents-core/src/main/java/com/github/bordertech/wcomponents/AbstractWComponent.java @@ -1017,7 +1017,7 @@ public abstract class AbstractWComponent implements WComponent { /** * {@inheritDoc} - * @Deprecated 1.4 causes a11y issues, no replacement. + * @deprecated 1.4 causes a11y issues, no replacement. */ @Deprecated @Override @@ -1027,7 +1027,7 @@ public abstract class AbstractWComponent implements WComponent { /** * {@inheritDoc} - * @Deprecated 1.4 causes a11y issues, no replacement. + * @deprecated 1.4 causes a11y issues, no replacement. */ @Deprecated @Override diff --git a/wcomponents-core/src/main/java/com/github/bordertech/wcomponents/WComponent.java b/wcomponents-core/src/main/java/com/github/bordertech/wcomponents/WComponent.java index <HASH>..<HASH> 100755 --- a/wcomponents-core/src/main/java/com/github/bordertech/wcomponents/WComponent.java +++ b/wcomponents-core/src/main/java/com/github/bordertech/wcomponents/WComponent.java @@ -315,14 +315,14 @@ public interface WComponent extends WebComponent { * Indicates whether this component has a tab index. * * @return false - For the moment, turn off the tab index feature and see what happens. - * @Deprecated 1.4 causes a11y issues, no replacement. + * @deprecated 1.4 causes a11y issues, no replacement. */ @Deprecated boolean hasTabIndex(); /** * @return the tab index for this component. - * @Deprecated 1.4 causes a11y issues, no replacement. + * @deprecated 1.4 causes a11y issues, no replacement. */ @Deprecated int getTabIndex(); diff --git a/wcomponents-core/src/main/java/com/github/bordertech/wcomponents/WebUtilities.java b/wcomponents-core/src/main/java/com/github/bordertech/wcomponents/WebUtilities.java index <HASH>..<HASH> 100755 --- a/wcomponents-core/src/main/java/com/github/bordertech/wcomponents/WebUtilities.java +++ b/wcomponents-core/src/main/java/com/github/bordertech/wcomponents/WebUtilities.java @@ -880,7 +880,7 @@ public final class WebUtilities { * <p> * Implementation of the CodePointTranslator to throw away the matching characters. This is copied from * org.apache.commons.lang3.text.translate.NumericEntityEscaper, but has been changed to discard the characters - * rather than attempting to encode them.<p> + * rather than attempting to encode them.</p> * <p> * Discarding the characters is necessary because certain invalid characters (e.g. decimal 129) cannot be encoded * for HTML. An existing library was not available for this function because no HTML page should ever contain these
Fix Javadoc errors which cause Java8 compilation faliure. (#<I>)
BorderTech_wcomponents
train
f0f1776f40bf7d95c4e1673473e6ea89ada717ea
diff --git a/ui/helpers/constants.js b/ui/helpers/constants.js index <HASH>..<HASH> 100644 --- a/ui/helpers/constants.js +++ b/ui/helpers/constants.js @@ -6,15 +6,15 @@ import closedTreeFavicon from '../img/tree_closed.png'; export const thPlatformMap = { linux32: 'Linux', - 'linux32-devedition': 'Linux DevEdition', 'linux-shippable': 'Linux Shippable', + 'linux32-devedition': 'Linux DevEdition', + 'linux-devedition': 'Linux DevEdition', 'linux32-shippable': 'Linux Shippable', 'linux1804-32': 'Linux 18.04', 'linux1804-32-qr': 'Linux 18.04 WebRender', 'linux1804-32-shippable': 'Linux 18.04 Shippable', 'linux1804-32-shippable-qr': 'Linux 18.04 WebRender Shippable', linux64: 'Linux x64', - 'linux1804-64-tsan': 'Linux 18.04 x64 tsan', 'linux64-asan': 'Linux x64 asan', 'linux64-asan-qr': 'Linux x64 WebRender asan', 'linux64-asan-reporter': 'Linux x64 asan reporter', @@ -28,14 +28,16 @@ export const thPlatformMap = { 'linux64-noopt': 'Linux x64 NoOpt', 'linux64-aarch64': 'Linux AArch64', 'linux1804-64': 'Linux 18.04 x64', - 'linux1804-64-asan': 'Linux 18.04 x64 asan', - 'linux1804-64-asan-qr': 'Linux 18.04 x64 WebRender asan', - 'linux1804-64-devedition': 'Linux 18.04 x64 DevEdition', - 'linux1804-64-shippable-qr': 'Linux 18.04 x64 WebRender Shippable', 'linux1804-64-qr': 'Linux 18.04 x64 WebRender', 'linux1804-64-shippable': 'Linux 18.04 x64 Shippable', + 'linux1804-64-shippable-qr': 'Linux 18.04 x64 WebRender Shippable', + 'linux1804-64-devedition': 'Linux 18.04 x64 DevEdition', + 'linux1804-64-asan': 'Linux 18.04 x64 asan', + 'linux1804-64-asan-qr': 'Linux 18.04 x64 WebRender asan', + 'linux1804-64-tsan': 'Linux 18.04 x64 tsan', 'linux1804-64-ccov': 'Linux 18.04 x64 CCov', 'linux1804-64-ccov-qr': 'Linux 18.04 x64 CCov WebRender', + 'linux1804-64-clang-trunk': 'Linux 18.04 x64 Clang-Trunk', 'osx-cross': 'OS X Cross Compiled', 'osx-shippable': 'OS X Cross Compiled Shippable', 'osx-aarch64-shippable': 'OS X AArch64 Cross Compiled Shippable', @@ -67,8 +69,11 @@ export const thPlatformMap = { 'macosx1100-64-devedition-qr': 'OS X 11 WebRender DevEdition', macosx64: 'OS X', osx: 'OS X', - 'macosx64-shippable': 'OS X', + 'macosx64-shippable': 'OS X Shippable', + 'macosx64-devedition': 'OS X DevEdition', 'macosx64-aarch64': 'OS X AArch64', + 'win32-shippable': 'Windows x86 Shippable', + 'win32-devedition': 'Windows x86 DevEdition', 'windows7-32': 'Windows 7', 'windows7-32-devedition': 'Windows 7 DevEdition', 'windows7-32-shippable-qr': 'Windows 7 WebRender Shippable', @@ -81,6 +86,8 @@ export const thPlatformMap = { 'windows10-32-mingwclang': 'Windows 10 x86 MinGW', 'windows10-32-mingwclang-qr': 'Windows 10 x86 MinGW WebRender', 'windows10-64': 'Windows 10 x64', + 'win64-shippable': 'Windows x64 Shippable', + 'win64-devedition': 'Windows x64 DevEdition', 'windows10-64-asan-qr': 'Windows 10 x64 asan WebRender', 'windows10-64-ccov': 'Windows 10 x64 CCov', 'windows10-64-ccov-qr': 'Windows 10 x64 CCov WebRender', @@ -88,6 +95,7 @@ export const thPlatformMap = { 'windows10-64-pgo-qr': 'Windows 10 x64 WebRender pgo', 'windows10-64-shippable': 'Windows 10 x64 Shippable', 'windows10-64-shippable-qr': 'Windows 10 x64 WebRender Shippable', + 'windows10-64-devedition-qr': 'Windows 10 x64 WebRender DevEdition', 'windows10-64-qr': 'Windows 10 x64 WebRender', 'windows10-64-ref-hw-2017': 'Windows 10 x64 2017 Ref HW', 'windows10-64-mingwclang': 'Windows 10 x64 MinGW', @@ -190,10 +198,12 @@ export const thPlatformMap = { lint: 'Linting', doc: 'Documentation', fetch: 'Fetch', + symbols: 'Symbols', 'taskcluster-images': 'Docker Images', packages: 'Packages', toolchains: 'Toolchains', updatebot: 'Updatebot', + codeql: 'codeql', other: 'Other', };
Bug <I> - more pretty platform names and some reordering (#<I>)
mozilla_treeherder
train
a3a8c5d3c935c33aeb778a938de0c7b031ae30d4
diff --git a/src/Koldy/Route.php b/src/Koldy/Route.php index <HASH>..<HASH> 100644 --- a/src/Koldy/Route.php +++ b/src/Koldy/Route.php @@ -186,10 +186,14 @@ class Route throw new Exception("Unable to construct URL to site={$site}, site is not defined in configs/sites.php"); } - if ($uri === null) { + if ($uri === null || strlen($uri) === 0) { return $otherSite; } else { - return $otherSite . '/' . $uri; + if ($uri[0] != '/') { + $uri = '/' . $uri; + } + + return $otherSite . $uri; } }
Small fix regarding double slashes when generating full URL to other site
koldy_framework
train