hash
stringlengths
40
40
diff
stringlengths
131
114k
message
stringlengths
7
980
project
stringlengths
5
67
split
stringclasses
1 value
031674681b49f9af502bcd28bdbffd36ab4da244
diff --git a/src/index.js b/src/index.js index <HASH>..<HASH> 100644 --- a/src/index.js +++ b/src/index.js @@ -162,7 +162,7 @@ export default class TimeAgo extends Component<DefaultProps, Props, void> { ? [Math.round(seconds / MONTH), 'month'] : [Math.round(seconds / YEAR), 'year'] - const props = Object.assign({}, this.props) + const props = {...this.props} props.title = props.title || typeof props.date === 'string' ? props.date : (new Date(props.date)).toISOString().substr(0, 16).replace('T', ' ')
Use object spread syntax instead of Object.assign() Fixes react-timeago in IE<I> and anything else which doesn't implement `Object.assign()` natively This should also close #<I>
nmn_react-timeago
train
26758a8bde28df0a8b0956aa36d40f6db60ddaa6
diff --git a/lib/cli.js b/lib/cli.js index <HASH>..<HASH> 100644 --- a/lib/cli.js +++ b/lib/cli.js @@ -51,13 +51,12 @@ module.exports = function(){ }, // get version ver: ['cc', function(next, res){ - console.log(res) gitTag.latest(function(ver){ if (!semver.valid(ver)) ver = '0.0.0' if (!semver.valid(info.pkg.json.version)) info.pkg.json.version = '0.0.1' if (semver.gt(info.pkg.json.version, ver)) { - res.update = true + info.update = true ver = info.pkg.json.version } else { var vers = ver.split('.') @@ -68,9 +67,7 @@ module.exports = function(){ }) }], pkg: ['ver', function(next, res){ - console.log(res) - return next('aa') - if (res.update) { + if (info.update) { info.pkg.json.ver = res.ver var space = info.pkg.file.match(/^{(\s+)"/)[1].replace(/[^ ]/g,'') fs.writeFileSync('./package.json', JSON.stringify(info.pkg.json, null, space), 'utf8')
auto commit by npm-git
cutsin_npm-git
train
59476a2d03304be2ee7a2e0077f49321aee545c4
diff --git a/lib/assets.js b/lib/assets.js index <HASH>..<HASH> 100644 --- a/lib/assets.js +++ b/lib/assets.js @@ -121,8 +121,6 @@ module.exports = { // Full paths to assets as computed by pushAsset self._assets = { stylesheets: [], scripts: [], templates: [] }; - var alreadyPushed = {}; - // `self.pushAsset('stylesheet', 'foo', { dir: __dirname, web: '/apos-mymodule', when: 'always' })` will preload // `/apos-mymodule/css/foo.css` at all times. // @@ -179,13 +177,6 @@ module.exports = { // bc when = 'always'; } - var key = type + ':' + name + ':' + fs + ':' + web; - if (type !== 'template') { - if (alreadyPushed[key]) { - return; - } - alreadyPushed[key] = true; - } // Careful with the defaults on this, '' is not false for this purpose if (typeof(fs) !== 'string') { fs = __dirname + '/..'; @@ -344,16 +335,35 @@ module.exports = { // Part of the implementation of apos.endAssets, this method // returns only the assets that are suitable for the specified - // scenario (`user` or `anon`). + // scenario (`user` or `anon`). Duplicates are suppressed automatically + // for anything rendered from a file (we can't do that for things + // rendered by a function). self.filterAssets = function(assets, when) { // Support older layouts if (!when) { throw new Error('You must specify the "when" argument (usually either anon or user)'); } - return _.filter(assets, function(asset) { - return (asset.when === 'always') || (when === 'all') || (asset.when === when); + // Always stomp duplicates so that devs don't have to worry about whether + // someone else pushed the same asset. + var once = {}; + var results = _.filter(assets, function(asset) { + var relevant = (asset.when === 'always') || (when === 'all') || (asset.when === when); + if (!relevant) { + return false; + } + if (asset.call) { + // We can't stomp duplicates for templates rendered by functions + return true; + } + var key = asset.name + ':' + asset.fs + ':' + asset.web; + if (once[key]) { + return false; + } + once[key] = true; + return true; }); + return results; }; // This mixin adds methods to the specified module object. Should be called only
Stomp duplicate assets in filterAssets, rather than in pushAsset. That way, we can allow the same asset to be pushed for 'user' and 'always', and send it just for the first one.
apostrophecms_apostrophe
train
5511a622d857f44776a0aa55e22b3a151543c1f4
diff --git a/goblin.go b/goblin.go index <HASH>..<HASH> 100644 --- a/goblin.go +++ b/goblin.go @@ -171,10 +171,15 @@ func runIt (g *G, h interface{}) { g.currentIt.isAsync = true // the test is asynchronous g.shouldContinue = make(chan bool) + doneCalled := 0 call(func(msg ...interface{}) { if len(msg) > 0 { g.Fail(msg) } else { + doneCalled++ + if doneCalled > 1 { + g.Fail("Done called multiple times") + } g.shouldContinue <- true } }) diff --git a/goblin_test.go b/goblin_test.go index <HASH>..<HASH> 100644 --- a/goblin_test.go +++ b/goblin_test.go @@ -74,12 +74,10 @@ func TestMultipleDescribes(t *testing.T) { g := Goblin(&fakeTest) - count := 0 g.Describe("Numbers", func() { g.Describe("Addition", func() { g.It("Should add numbers", func() { - count++ sum := 1+1 g.Assert(sum).Equal(2) }) @@ -87,7 +85,6 @@ func TestMultipleDescribes(t *testing.T) { g.Describe("Substraction", func() { g.It("Should substract numbers ", func() { - count++ sub := 5-5 g.Assert(sub).Equal(1) }) @@ -95,7 +92,7 @@ func TestMultipleDescribes(t *testing.T) { }) - if count != 2 { + if !fakeTest.Failed() { t.Fatal() } }
Add check to see if done has been called more than once in async test
franela_goblin
train
bbd6ffca3b9847b8a5659903de601102ceaf6e5e
diff --git a/lib/plugins/vusion-tree-shaking.js b/lib/plugins/vusion-tree-shaking.js index <HASH>..<HASH> 100644 --- a/lib/plugins/vusion-tree-shaking.js +++ b/lib/plugins/vusion-tree-shaking.js @@ -27,6 +27,7 @@ class VusionTreeShakingPlugin { const entryModule = chunk.entryModule; targetModule = modules.find((e) => e.rawRequest === target); + this.markModuleUnDead(entryModule); if (!targetModule) return; @@ -44,7 +45,6 @@ class VusionTreeShakingPlugin { unDeadLibModules = [...unDeadLibModules.values()]; this.findUndeadStyles(unDeadLibModules); unDeadLibModules.forEach((module) => this.markModuleUnDead(module)); - this.markModuleUnDead(entryModule); targetModule.isUnDead = true; this.markModuleNeedToBeRemoved(targetModule); @@ -56,6 +56,8 @@ class VusionTreeShakingPlugin { }); }); compilation.plugin('optimize-module-ids', (modules) => { + if (!targetModule) + return; // set unused module's id to undead module id const undeadId = modules.find((module) => module.isUnDead).id; modules.forEach((module) => { @@ -105,7 +107,7 @@ class VusionTreeShakingPlugin { module.isUnDead = true; // dependency depth > 3 means the style of module depend on its parent styles, we should remove its parent styles if they are dead - if (depth > 3 && resource.endsWith('.css') && resource.includes('node_modules') && !unDeadStyles.includes(resource)) + if (depth > 3 && resource.endsWith('.css') && resource.includes('node_modules') && unDeadStyles && !unDeadStyles.includes(resource)) module.isUnDead = false; if (hasImportDep) { module.dependencies.forEach((dep) => {
:bug: unexpected entry module removed by force shaking when using with webpack common chunks plugin
vusion_vusion-cli
train
7e41a95462bc79b53b7cc88823b139aba9012291
diff --git a/src/Sonata/Component/Basket/Loader.php b/src/Sonata/Component/Basket/Loader.php index <HASH>..<HASH> 100644 --- a/src/Sonata/Component/Basket/Loader.php +++ b/src/Sonata/Component/Basket/Loader.php @@ -58,7 +58,7 @@ class Loader * @throws \RuntimeException * @return \Sonata\Component\Basket\BasketInterface */ - private function getBasketInstance() + protected function getBasketInstance() { $basket = $this->session->get('sonata/basket');
Changing the visibility of the method "getBasketInstance" (private > protected)
sonata-project_ecommerce
train
b75a229195d11ea56d1f383c1bb3e8cdccfd6447
diff --git a/addon/utils/attr.js b/addon/utils/attr.js index <HASH>..<HASH> 100644 --- a/addon/utils/attr.js +++ b/addon/utils/attr.js @@ -71,9 +71,11 @@ export default function attr(type = 'any', mutable = true) { this.set('attributes.' + key, value); if (!this.get('isNew')) { this._attributes[key] = this._attributes[key] || {}; + if (this._attributes[key].previous === undefined) { + this._attributes[key].previous = lastValue; + } this._attributes[key].changed = value; - this._attributes[key].previous = lastValue; - const service = this.get('service'); + let service = this.get('service'); if (service) { service.trigger('attributeChanged', this); } diff --git a/tests/unit/models/resource-test.js b/tests/unit/models/resource-test.js index <HASH>..<HASH> 100644 --- a/tests/unit/models/resource-test.js +++ b/tests/unit/models/resource-test.js @@ -208,11 +208,11 @@ test('#rollbackAttributes resets attributes based on #previousAttributes', funct test('#rollbackRelationships resets relationships', function(assert) { let post = createPostWithRelationships.call(this); - let ogAuthorId = post.get('relationships.author.data.id'); + const ogAuthorId = post.get('relationships.author.data.id'); let relationships = post.get('relationships'); post.addRelationship('author', '5'); - assert.notEqual(relationships.author.id, ogAuthorId, 'author changed'); + assert.notEqual(relationships.author.data.id, ogAuthorId, 'author changed'); assert.equal(relationships.comments.data.length, 1, 'one comment'); post.removeRelationships('comments', ['3']); @@ -221,6 +221,19 @@ test('#rollbackRelationships resets relationships', function(assert) { let changes = post.get('changedRelationships'); assert.equal(changes.length, 2, 'two relationships were changed'); + post.addRelationship('author', '6'); + assert.equal(relationships.author.data.id, 6, 'author changed'); + post.addRelationships('comments', ['4', '5']); + assert.equal(relationships.comments.data.length, 2, 'two comments added'); + + changes = post.get('changedRelationships'); + assert.equal(changes.length, 2, 'two relationships were changed'); + + post.removeRelationship('author'); + assert.equal(relationships.author.id, null, 'no author'); + changes = post.get('changedRelationships'); + assert.equal(changes.length, 2, 'two relationships were changed'); + post.rollbackRelationships(); changes = post.get('changedRelationships');
Update rollback methods, not to behave like undo Fix behavior for rollbackAttributes. The intent is to rollback to the value fetched from the persistence layer; not to stash an attribute’s value on every call to `.set()`. - Fix failing tests for previousAttributes and rollbackAttributes - Update `attr()` `set()` method to only assign to `.previous` once
pixelhandler_ember-jsonapi-resources
train
3488d10608698c6547d9051a6665926d9117cade
diff --git a/src/actions/breakpoints.js b/src/actions/breakpoints.js index <HASH>..<HASH> 100644 --- a/src/actions/breakpoints.js +++ b/src/actions/breakpoints.js @@ -165,10 +165,16 @@ export function enableBreakpoint(location: Location) { return; } + // To instantly reflect in the UI, we optimistically enable the breakpoint + const enabledBreakpoint = { + ...breakpoint, + disabled: false + }; + return dispatch( ({ type: "ENABLE_BREAKPOINT", - breakpoint, + breakpoint: enabledBreakpoint, [PROMISE]: addBreakpointPromise( getState, client,
Optimitically enable breakpoint in UI (#<I>)
firefox-devtools_debugger
train
37a1e330f67c74773fe549dacd5851c323896347
diff --git a/src/django_future/__init__.py b/src/django_future/__init__.py index <HASH>..<HASH> 100644 --- a/src/django_future/__init__.py +++ b/src/django_future/__init__.py @@ -60,12 +60,12 @@ def run_jobs(delete_completed=False, ignore_errors=False, now=None): raise ValueError('jobs in progress found; aborting') if now is None: now = datetime.datetime.now() + # Expire jobs. expired_jobs = ScheduledJob.objects.filter(status='scheduled', time_slot_end__lt=now) - for job in expired_jobs: - job.status = 'expired' - job.save() + expired_jobs.update(status='expired') + # Get scheduled jobs. jobs = ScheduledJob.objects.filter(status='scheduled', time_slot_start__lte=now)
Expire jobs in one SQL statement.
shrubberysoft_django-future
train
9b865d86a9606b46e2299be7f8088d12d4f544d2
diff --git a/remotes/docker/pusher.go b/remotes/docker/pusher.go index <HASH>..<HASH> 100644 --- a/remotes/docker/pusher.go +++ b/remotes/docker/pusher.go @@ -155,9 +155,18 @@ func (p dockerPusher) Push(ctx context.Context, desc ocispec.Descriptor) (conten location := resp.Header.Get("Location") // Support paths without host in location if strings.HasPrefix(location, "/") { - u := p.base - u.Path = location - location = u.String() + // Support location string containing path and query + qmIndex := strings.Index(location, "?") + if qmIndex > 0 { + u := p.base + u.Path = location[:qmIndex] + u.RawQuery = location[qmIndex+1:] + location = u.String() + } else { + u := p.base + u.Path = location + location = u.String() + } } req, err = http.NewRequest(http.MethodPut, location, nil)
docker/pusher: handle location string containing path and query
containerd_containerd
train
c5d99d15891674e86606f6ff4f8d53e057c141f6
diff --git a/lib/html_mockup/release.rb b/lib/html_mockup/release.rb index <HASH>..<HASH> 100644 --- a/lib/html_mockup/release.rb +++ b/lib/html_mockup/release.rb @@ -277,7 +277,8 @@ module HtmlMockup end - # Nothing genius -> it came from the blogz, however, do we really want to load activesupport for this + # Nothing genius adjusted from: + # http://stackoverflow.com/questions/9524457/converting-string-from-snake-case-to-camel-case-in-ruby def camel_case(string) return string if string !~ /_/ && string =~ /[A-Z]+.*/ string.split('_').map{|e| e.capitalize}.join
Add source in comment for camel_case function
DigitPaint_html_mockup
train
7d289f25f207d8ae9e4bb1ff1a6e12b646c4044e
diff --git a/insights/parsers/mongod_conf.py b/insights/parsers/mongod_conf.py index <HASH>..<HASH> 100644 --- a/insights/parsers/mongod_conf.py +++ b/insights/parsers/mongod_conf.py @@ -147,7 +147,7 @@ class MongodbConf(Parser, LegacyItemAccess): if a key-value pair conf. """ if self.is_yaml: - return self.get('storage', {}).get('dbPath') + return self.get('storage', {}).get('dbPath') or self.get('storage.dbPath') else: return self.get('dbpath') diff --git a/insights/parsers/tests/test_mongod_conf.py b/insights/parsers/tests/test_mongod_conf.py index <HASH>..<HASH> 100644 --- a/insights/parsers/tests/test_mongod_conf.py +++ b/insights/parsers/tests/test_mongod_conf.py @@ -90,6 +90,11 @@ systemLog: """.strip() +YAML_CONF_FORMAT_2 = """ +storage.dbPath: /var/lib/mongodb +storage.journal.enabled: true +""" + def test_mongodb_conf(): @@ -119,6 +124,10 @@ def test_mongodb_conf(): assert result.get("abc") == '' assert result.get("def") is None + result = MongodbConf(context_wrap(YAML_CONF_FORMAT_2)) + assert result.is_yaml + assert result.dbpath == '/var/lib/mongodb' + result = MongodbConf(context_wrap(NORMAL_CONF_V1)) assert result.is_yaml is False assert len(result.data) == 2
Update parser MongodbConf to support another dbPath format (#<I>)
RedHatInsights_insights-core
train
2567adca26fe3706bc93dfd107269d6a6c7e2c48
diff --git a/modules/pulsestorm/magento2/cli/generate/config_helper/module.php b/modules/pulsestorm/magento2/cli/generate/config_helper/module.php index <HASH>..<HASH> 100644 --- a/modules/pulsestorm/magento2/cli/generate/config_helper/module.php +++ b/modules/pulsestorm/magento2/cli/generate/config_helper/module.php @@ -6,10 +6,13 @@ pestle_import('Pulsestorm\Pestle\Library\input'); pestle_import('Pulsestorm\Pestle\Library\output'); /** -* Short Description -* Long -* Description +* Generates a help class for reading Magento's configuration +* +* This command will generate the necessary files and configuration +* needed for reading Magento 2's configuration values. +* * @command generate_config_helper +* @todo needs to be implemented */ function pestle_cli($argv) { diff --git a/modules/pulsestorm/magento2/cli/generate/layout_xml/module.php b/modules/pulsestorm/magento2/cli/generate/layout_xml/module.php index <HASH>..<HASH> 100644 --- a/modules/pulsestorm/magento2/cli/generate/layout_xml/module.php +++ b/modules/pulsestorm/magento2/cli/generate/layout_xml/module.php @@ -7,10 +7,14 @@ pestle_import('Pulsestorm\Pestle\Library\output'); /** * One Line Description +* This command will generate the layout handle XML +* files needed to add a block to Magento's page +* layout * * @command generate_layout_xml +* @todo implement me please */ function pestle_cli($argv) { - output("Hello"); + output("Needs to be implemented"); } \ No newline at end of file diff --git a/modules/pulsestorm/magento2/cli/generate/psr_log_level/module.php b/modules/pulsestorm/magento2/cli/generate/psr_log_level/module.php index <HASH>..<HASH> 100644 --- a/modules/pulsestorm/magento2/cli/generate/psr_log_level/module.php +++ b/modules/pulsestorm/magento2/cli/generate/psr_log_level/module.php @@ -5,7 +5,11 @@ pestle_import('Pulsestorm\Pestle\Library\output'); pestle_import('Pulsestorm\Pestle\Library\getZendPsrLogLevelMap'); /** -* Converts Zend Log Level into PSR Log Level +* For conversion of Zend Log Level into PSR Log Level +* +* This command generates a list of Magento 1 log levels, +* and their PSR log level equivalents. +* * @command generate_psr_log_level */ function pestle_cli($argv)
First pass at generate docs complete.
astorm_pestle
train
95e08ef86c98cd172b5b8630c419309664876d76
diff --git a/core/src/main/java/org/bitcoinj/core/PeerGroup.java b/core/src/main/java/org/bitcoinj/core/PeerGroup.java index <HASH>..<HASH> 100644 --- a/core/src/main/java/org/bitcoinj/core/PeerGroup.java +++ b/core/src/main/java/org/bitcoinj/core/PeerGroup.java @@ -2208,37 +2208,29 @@ public class PeerGroup implements TransactionBroadcaster { // Make sure we don't select a peer if there is no consensus about block height. if (mostCommonChainHeight == 0) return null; - // Make sure we don't select a peer that is behind/synchronizing itself or announces an unrealistic height. - List<Peer> candidates = new ArrayList<>(); + + // Only select peers that announce the minimum protocol and services and that we think is fully synchronized. + List<Peer> candidates = new LinkedList<>(); + final int MINIMUM_VERSION = params.getProtocolVersionNum(NetworkParameters.ProtocolVersion.WITNESS_VERSION); for (Peer peer : peers) { - if (!peer.getPeerVersionMessage().hasBlockChain()) + final VersionMessage versionMessage = peer.getPeerVersionMessage(); + if (versionMessage.clientVersion < MINIMUM_VERSION) + continue; + if (!versionMessage.hasBlockChain()) + continue; + if (!versionMessage.isWitnessSupported()) continue; final long peerHeight = peer.getBestHeight(); if (peerHeight < mostCommonChainHeight || peerHeight > mostCommonChainHeight + 1) continue; candidates.add(peer); } - // Of the candidates, find the peers that meet the minimum protocol version we want to target. We could select - // the highest version we've seen on the assumption that newer versions are always better but we don't want to - // zap peers if they upgrade early. If we can't find any peers that have our preferred protocol version or - // better then we'll settle for the highest we found instead. - int highestVersion = 0, preferredVersion = 0; - // If/when PREFERRED_VERSION is not equal to vMinRequiredProtocolVersion, reenable the last test in PeerGroupTest.downloadPeerSelection - final int PREFERRED_VERSION = params.getProtocolVersionNum(NetworkParameters.ProtocolVersion.BLOOM_FILTER); - for (Peer peer : candidates) { - highestVersion = Math.max(peer.getPeerVersionMessage().clientVersion, highestVersion); - preferredVersion = Math.min(highestVersion, PREFERRED_VERSION); - } - ArrayList<Peer> candidates2 = new ArrayList<>(candidates.size()); - for (Peer peer : candidates) { - if (peer.getPeerVersionMessage().clientVersion >= preferredVersion) { - candidates2.add(peer); - } - } - if (candidates2.isEmpty()) + if (candidates.isEmpty()) return null; - int index = (int) (Math.random() * candidates2.size()); - return candidates2.get(index); + + // Random poll. + int index = (int) (Math.random() * candidates.size()); + return candidates.get(index); } /** diff --git a/core/src/test/java/org/bitcoinj/core/PeerGroupTest.java b/core/src/test/java/org/bitcoinj/core/PeerGroupTest.java index <HASH>..<HASH> 100644 --- a/core/src/test/java/org/bitcoinj/core/PeerGroupTest.java +++ b/core/src/test/java/org/bitcoinj/core/PeerGroupTest.java @@ -469,11 +469,11 @@ public class PeerGroupTest extends TestWithPeerGroup { public void downloadPeerSelection() throws Exception { peerGroup.start(); VersionMessage v1 = new VersionMessage(UNITTEST, 2); - v1.clientVersion = NetworkParameters.ProtocolVersion.BLOOM_FILTER.getBitcoinProtocolVersion(); - v1.localServices = VersionMessage.NODE_NETWORK; + v1.clientVersion = NetworkParameters.ProtocolVersion.WITNESS_VERSION.getBitcoinProtocolVersion(); + v1.localServices = VersionMessage.NODE_NETWORK | VersionMessage.NODE_BLOOM | VersionMessage.NODE_WITNESS; VersionMessage v2 = new VersionMessage(UNITTEST, 4); - v2.clientVersion = NetworkParameters.ProtocolVersion.BLOOM_FILTER.getBitcoinProtocolVersion(); - v2.localServices = VersionMessage.NODE_NETWORK; + v2.clientVersion = NetworkParameters.ProtocolVersion.WITNESS_VERSION.getBitcoinProtocolVersion(); + v2.localServices = VersionMessage.NODE_NETWORK | VersionMessage.NODE_BLOOM | VersionMessage.NODE_WITNESS; assertNull(peerGroup.getDownloadPeer()); Peer p1 = connectPeer(0, v1).peer; diff --git a/core/src/test/java/org/bitcoinj/testing/TestWithPeerGroup.java b/core/src/test/java/org/bitcoinj/testing/TestWithPeerGroup.java index <HASH>..<HASH> 100644 --- a/core/src/test/java/org/bitcoinj/testing/TestWithPeerGroup.java +++ b/core/src/test/java/org/bitcoinj/testing/TestWithPeerGroup.java @@ -61,8 +61,10 @@ public class TestWithPeerGroup extends TestWithNetworkConnections { super.setUp(blockStore); remoteVersionMessage = new VersionMessage(UNITTEST, 1); - remoteVersionMessage.localServices = VersionMessage.NODE_NETWORK; - remoteVersionMessage.clientVersion = NotFoundMessage.MIN_PROTOCOL_VERSION; + remoteVersionMessage.localServices = + VersionMessage.NODE_NETWORK | VersionMessage.NODE_BLOOM | VersionMessage.NODE_WITNESS; + remoteVersionMessage.clientVersion = + NetworkParameters.ProtocolVersion.WITNESS_VERSION.getBitcoinProtocolVersion(); blockJobs = false; initPeerGroup(); }
PeerGroup: Require SegWit protocol and service when selecting a download peer. Those nodes are extremely common now.
bitcoinj_bitcoinj
train
73bf781ffced631fb070ba3947df52812dfa6358
diff --git a/lib/event_socket.js b/lib/event_socket.js index <HASH>..<HASH> 100644 --- a/lib/event_socket.js +++ b/lib/event_socket.js @@ -146,6 +146,9 @@ EventSocket.prototype.send = function(topic, data) { // used for _peer/connect _peer/disconnect if (Object.keys(data).length === 1 && typeof data.peer === 'object') { + if(topic instanceof StreamTopic) { + topic = topic.hash(); + } data = ObjectStream.format(topic, data.peer.properties()); }
Fix for older peer websocket streams.
zettajs_zetta
train
48a58b0294f0271c7f7249721ba705f14df05d62
diff --git a/salt/runners/doc.py b/salt/runners/doc.py index <HASH>..<HASH> 100644 --- a/salt/runners/doc.py +++ b/salt/runners/doc.py @@ -32,8 +32,7 @@ def runner(): ''' client = salt.runner.RunnerClient(__opts__) ret = client.get_docs() - salt.output.display_output(ret, '', __opts__) - return ret + return salt.output.out_format(ret, '', __opts__) def wheel(): @@ -48,8 +47,7 @@ def wheel(): ''' client = salt.wheel.Wheel(__opts__) ret = client.get_docs() - salt.output.display_output(ret, '', __opts__) - return ret + return salt.output.out_format(ret, '', __opts__) def execution(): @@ -72,8 +70,7 @@ def execution(): i = itertools.chain.from_iterable([i.items() for i in docs.itervalues()]) ret = dict(list(i)) - salt.output.display_output(ret, '', __opts__) - return ret + return salt.output.out_format(ret, '', __opts__) # Still need to modify some of the backend for auth checks to make this work
Use event output in doc runner
saltstack_salt
train
65cc058b40c97b27e583e9c1ab7112b06793cdfc
diff --git a/cli/utils/ts-linter.js b/cli/utils/ts-linter.js index <HASH>..<HASH> 100644 --- a/cli/utils/ts-linter.js +++ b/cli/utils/ts-linter.js @@ -22,18 +22,16 @@ function lintSync() { // Convert buffers to strings. let output = []; - if (spawnResult.output) { - spawnResult.output.forEach((buffer) => { - if (buffer === null) { - return; - } - - const str = buffer.toString().trim(); - if (str) { - output.push(str); - } - }); - } + spawnResult.output.forEach((buffer) => { + if (buffer === null) { + return; + } + + const str = buffer.toString().trim(); + if (str) { + output.push(str); + } + }); // Convert multi-line errors into single errors. let errors = []; diff --git a/config/karma/shared.karma.conf.js b/config/karma/shared.karma.conf.js index <HASH>..<HASH> 100644 --- a/config/karma/shared.karma.conf.js +++ b/config/karma/shared.karma.conf.js @@ -42,6 +42,8 @@ function getConfig(config) { const minimist = require('minimist'); const argv = minimist(process.argv.slice(2)); const path = require('path'); + const srcPath = path.join(process.cwd(), 'src'); + let testWebpackConfig = require('../webpack/test.webpack.config'); let remapIstanbul = require('remap-istanbul'); @@ -96,12 +98,17 @@ function getConfig(config) { // trigger the `invalid` event, causing karma to constantly re-rerun // the tests. This is a by-product of using `require.context`. // https://github.com/webpack-contrib/karma-webpack/issues/253#issuecomment-335545430 + // By using require.context in our @skyux/i18n library ALL project files are watched by default. + // The function below ignores all files execpt the `src` directory. webpackMiddleware: { watchOptions: { - ignored: [ - '**/coverage/**', - '**/.skypageslocales/**' - ] + // Returning `true` means the file should be ignored. + // Fat-Arrow functions do not work as chokidar will inspect this method. + ignored: function (item) { + const resolvedPath = path.resolve(item); + const ignore = (resolvedPath.indexOf(srcPath) === -1); + return ignore; + } } }, diff --git a/test/config-karma-shared.spec.js b/test/config-karma-shared.spec.js index <HASH>..<HASH> 100644 --- a/test/config-karma-shared.spec.js +++ b/test/config-karma-shared.spec.js @@ -1,6 +1,7 @@ /*jshint jasmine: true, node: true */ 'use strict'; +const path = require('path'); const mock = require('mock-require'); describe('config karma shared', () => { @@ -125,4 +126,31 @@ describe('config karma shared', () => { }); }); + it('should ignore anything outside the src directory in webpackMiddleware', () => { + mock('../config/sky-pages/sky-pages.config.js', { + getSkyPagesConfig: () => ({ + skyux: {} + }) + }); + + mock(testConfigFilename, { + getWebpackConfig: () => {} + }); + + spyOn(path, 'resolve').and.callThrough(); + + mock.reRequire('../config/karma/shared.karma.conf')({ + set: (config) => { + const filter = config.webpackMiddleware.watchOptions.ignored; + expect(filter).toBeDefined(); + + expect(path.resolve).toHaveBeenCalled(); + expect(filter(path.join(process.cwd(), 'src'))).toBe(false); + expect(filter(path.join(process.cwd(), 'node_modules'))).toBe(true); + expect(filter(path.join(process.cwd(), '.skypageslocales'))).toBe(true); + expect(filter(path.join(process.cwd(), 'coverage'))).toBe(true); + } + }); + }); + });
Using different technique to ignore file changes. (#<I>)
blackbaud_skyux-builder
train
4f701edf0661913947ae45dd09e4846e0b66bf7b
diff --git a/lib/sup/modes/edit-message-mode.rb b/lib/sup/modes/edit-message-mode.rb index <HASH>..<HASH> 100644 --- a/lib/sup/modes/edit-message-mode.rb +++ b/lib/sup/modes/edit-message-mode.rb @@ -105,7 +105,9 @@ EOS def edit_message_or_field lines = DECORATION_LINES + @selectors.size - if (curpos - lines) >= @header_lines.length + if lines > curpos + return + elsif (curpos - lines) >= @header_lines.length edit_message else edit_field @header_lines[curpos - lines]
edit-message-mode bugfix: edit_message_or_header shouldn't do anything on decoration and horizontal-selector lines git-svn-id: svn://rubyforge.org/var/svn/sup/trunk@<I> 5c8cc<I>c-5e<I>-4d<I>-b<I>a-d8db<I>a<I>
sup-heliotrope_sup
train
7b584f9a788fd044d886c18d699d0bf778c63e6b
diff --git a/core/Session/SessionAuth.php b/core/Session/SessionAuth.php index <HASH>..<HASH> 100644 --- a/core/Session/SessionAuth.php +++ b/core/Session/SessionAuth.php @@ -137,7 +137,7 @@ class SessionAuth implements Auth return new AuthResult($code, $user['login'], $user['token_auth']); } - private function initNewBlankSession(SessionFingerprint $sessionFingerprint) + protected function initNewBlankSession(SessionFingerprint $sessionFingerprint) { // this user should be using a different session, so generate a new ID // NOTE: Zend_Session cannot be used since it will destroy the old @@ -152,7 +152,7 @@ class SessionAuth implements Auth $sessionFingerprint->clear(); } - private function destroyCurrentSession(SessionFingerprint $sessionFingerprint) + protected function destroyCurrentSession(SessionFingerprint $sessionFingerprint) { // Note: Piwik will attempt to create another session in the LoginController // when rendering the login form (the nonce for the form is stored in the session).
Make two SessionAuth private methods protected. (#<I>)
matomo-org_matomo
train
285219f34d6237f7a879754ba1f998eb107d81f5
diff --git a/api/facadeversions.go b/api/facadeversions.go index <HASH>..<HASH> 100644 --- a/api/facadeversions.go +++ b/api/facadeversions.go @@ -9,7 +9,7 @@ package api // This map should be updated whenever the API server exposes a new version (so // that the client will use it whenever it is available). var facadeVersions = map[string]int{ - "Agent": 0, + "Agent": 1, "AllWatcher": 0, "Backups": 0, "Deployer": 0,
Forgot to change agent version in api package.
juju_juju
train
6f22ed5d082ec7c406ec3fe824ad0ab5caae2fd7
diff --git a/plugins/localfile.js b/plugins/localfile.js index <HASH>..<HASH> 100644 --- a/plugins/localfile.js +++ b/plugins/localfile.js @@ -21,8 +21,10 @@ var localfile = function(ctx, next) { title: path.basename(filePath) } }; - http.createServer(function(req, res) { + res.writeHead(200, { + 'Access-Control-Allow-Origin': '*' + }); fs.createReadStream(filePath).pipe(res); }).listen(port); next(); diff --git a/plugins/transcode.js b/plugins/transcode.js index <HASH>..<HASH> 100644 --- a/plugins/transcode.js +++ b/plugins/transcode.js @@ -13,6 +13,9 @@ var transcode = function(ctx, next) { ctx.options.type = 'video/mp4'; ctx.options.disableTimeline = true; http.createServer(function(req, res) { + res.writeHead(200, { + 'Access-Control-Allow-Origin': '*' + }); new Transcoder(got(orgPath)) .videoCodec('h264') .format('mp4')
added cross origin headers to localfile and transcode, this makes subtitles work
xat_castnow
train
35e7a4c684fe88e2a7c224f4c8d28dc85de831c1
diff --git a/boot.js b/boot.js index <HASH>..<HASH> 100644 --- a/boot.js +++ b/boot.js @@ -293,16 +293,6 @@ if (!gpf.ASSERT) { /*#ifndef(UMD)*/ -function _safeEval(src, content) { - try { - /*jslint evil: true*/ - eval(content); - /*jslint evil: false*/ - } catch (e) { - console.error("eval failed on '" + src + "'\n" + e.message); - } -} - /* * Loading sources occurs here because the release version will have * everything embedded. @@ -314,47 +304,50 @@ if ("wscript" === _gpfHost) { (function () { var fso = new ActiveXObject("Scripting.FileSystemObject"), - include = function (src) { + read = function (src) { /*global gpfSourcesPath*/ // Tested below if ("undefined" !== typeof gpfSourcesPath) { src = gpfSourcesPath + src; } - var srcFile = fso.OpenTextFile(src); + var srcFile = fso.OpenTextFile(src), + result; // No other choice to evaluate in the current context - _safeEval(src, srcFile.ReadAll()); + result = srcFile.ReadAll(); srcFile.Close(); + return result; }, sources, - idx; - include("sources.js"); + idx, + code = []; + /*jslint evil: true*/ + eval(read("sources.js")); + /*jslint evil: false*/ sources = gpf.sources().split(","); for (idx = 0; idx < sources.length; ++idx) { - include(sources[idx] + ".js"); + code.push(read(sources[idx] + ".js")); } + /*jslint evil: true*/ + eval(code.join("")); + /*jslint evil: false*/ _gpfFinishLoading(); }()); } else if (_gpfInNode) { - /* - * This is probably the simplest part: use require - */ - require("./sources.js"); + require("./sources.js"); // Get sources (function () { var + fs = require("fs"), sources = gpf.sources().split(","), idx, - fs = require("fs"), - src; + src, + code = []; for (idx = 0; idx < sources.length; ++idx) { src = sources[idx] + ".js"; - /** - * require create private scopes. - * I changed my mind and remove the IIFE structure around sources - * so that I can share 'internal' variables. - * That's why I need to load the source and evaluate it here - */ - _safeEval(src, fs.readFileSync(__dirname + "/" + src).toString()); + code.push(fs.readFileSync(__dirname + "/" + src).toString()); } + /*jslint evil: true*/ + eval(code.join("")); + /*jslint evil: false*/ _gpfFinishLoading(); }());
All sources are loaded at once to solve issues
ArnaudBuchholz_gpf-js
train
e2d1b1a4fa8b696ed68f133ad6d4f7212beff379
diff --git a/packages/selenium-ide/src/api/v1/record.js b/packages/selenium-ide/src/api/v1/record.js index <HASH>..<HASH> 100644 --- a/packages/selenium-ide/src/api/v1/record.js +++ b/packages/selenium-ide/src/api/v1/record.js @@ -15,15 +15,30 @@ // specific language governing permissions and limitations // under the License. +import browser from "webextension-polyfill"; import Router from "../../router"; import { recordCommand } from "../../neo/IO/SideeX/record"; import { select } from "../../neo/IO/SideeX/find-select"; +import { extCommand } from "../../neo/IO/SideeX/playback"; const router = new Router(); +router.get("/tab", (req, res) => { + browser.tabs.query({ + active: true, + windowId: extCommand.getContentWindowId() + }).then((tabs) => { + if (!tabs.length) { + res({error: "No active tab found"}); + } else { + res({id: tabs[0].id}); + } + }); +}); + router.post("/command", (req, res) => { recordCommand(req.command, req.target, req.value, undefined, req.select); - if (select) { + if (req.select) { select(); } res(true);
allow querying which tab is being recorded
SeleniumHQ_selenium-ide
train
9a87c52aa42fd163b24775546793bf96d56a7492
diff --git a/packages/input-phone/src/PhoneInput.styled.js b/packages/input-phone/src/PhoneInput.styled.js index <HASH>..<HASH> 100644 --- a/packages/input-phone/src/PhoneInput.styled.js +++ b/packages/input-phone/src/PhoneInput.styled.js @@ -7,7 +7,7 @@ export const PopoverWrapper = styled.div` flex-direction: column; height: 100%; min-height: 340px; - min-width: 300px; + min-width: 280px; `; export const CountryListWrapper = styled.ul`
fix(input-phone): reduce popover min-width to fit <I>px viewports affects: @crave/farmblocks-input-phone
CraveFood_farmblocks
train
b7b2b31f93fcf01b79d148d2296726de73d4b1e8
diff --git a/datadog_checks_dev/datadog_checks/dev/tooling/commands/run.py b/datadog_checks_dev/datadog_checks/dev/tooling/commands/run.py index <HASH>..<HASH> 100644 --- a/datadog_checks_dev/datadog_checks/dev/tooling/commands/run.py +++ b/datadog_checks_dev/datadog_checks/dev/tooling/commands/run.py @@ -14,7 +14,7 @@ from .console import UNKNOWN_OPTIONS @click.pass_context def run(ctx, args): """Run commands in the proper repo.""" - if not args or '-h' in args or '--help' in args: + if not args or (len(args) == 1 and args[0] in ('-h', '--help')): click.echo(ctx.get_help()) return
Fix "Allow help options to ddev run command" (#<I>) * Revert "Allow help options to ddev run command (#<I>)" This reverts commit <I>f1e<I>c2a<I>b<I>e<I>a5cb2ea7b6d<I>. * meh, not a fan
DataDog_integrations-core
train
037342a6aa73ab5c683a6abbcf088f089815ec25
diff --git a/lib/resqued/listener_pool.rb b/lib/resqued/listener_pool.rb index <HASH>..<HASH> 100644 --- a/lib/resqued/listener_pool.rb +++ b/lib/resqued/listener_pool.rb @@ -25,6 +25,11 @@ module Resqued @listener_proxies.size end + # Public: Are the listeners all gone? + def empty? + @listener_proxies.empty? + end + # Public: Initialize a new listener, run it, and record it as the current listener. Returns its ListenerProxy. def start! listener_state = ListenerState.new diff --git a/lib/resqued/master.rb b/lib/resqued/master.rb index <HASH>..<HASH> 100644 --- a/lib/resqued/master.rb +++ b/lib/resqued/master.rb @@ -209,6 +209,8 @@ module Resqued end write_procline + + return if @listeners.empty? rescue Errno::ECHILD return end
Exit when listeners are all gone
spraints_resqued
train
bc1336d53376c9f07777121d1dc326abbb21072d
diff --git a/index.js b/index.js index <HASH>..<HASH> 100644 --- a/index.js +++ b/index.js @@ -118,6 +118,11 @@ function Domt(parent) { this.reExpr = new RegExp(start + '([^' + start + end + ']+)' + end, "g"); }; +Domt.prototype.empty = function() { + this.merge(null, {empty:true}); + return this; +}; + Domt.prototype.merge = function(obj, opts) { var node, current, holder, container, path, i, len, parentNode, curNode; parent = this.parent; @@ -135,22 +140,22 @@ Domt.prototype.merge = function(obj, opts) { path = holder.repeat; // get data current = find(obj, path); + parentNode = container.parentNode; + if (opts.empty) { + if (holder.invert) { + while ((curNode = container.nextSibling) && !curNode.hasAttribute(REPEAT + '-tail')) { + parentNode.removeChild(curNode); + } + } else { + while ((curNode = container.previousSibling) && !curNode.hasAttribute(REPEAT + '-tail')) { + parentNode.removeChild(curNode); + } + } + } if (current.value === undefined) { // nothing to repeat, merge and restore repeat Domt(holder.template).merge(obj, {norepeat: true}); } else { - parentNode = container.parentNode; - if (opts.empty) { - if (holder.invert) { - while ((curNode = container.nextSibling) && !curNode.hasAttribute(REPEAT + '-tail')) { - parentNode.removeChild(curNode); - } - } else { - while ((curNode = container.previousSibling) && !curNode.hasAttribute(REPEAT + '-tail')) { - parentNode.removeChild(curNode); - } - } - } iterate(current.value, function(key, val) { var clone = holder.template.cloneNode(); Domt(clone).merge(val, {strip: true});
Add this.empty() method to empty all repeated nodes (and fix it)
kapouer_domt
train
b5ba4c113b2fd028d55060fd460e47190271ce35
diff --git a/src-gwt/org/opencms/ade/sitemap/client/CmsSitemapView.java b/src-gwt/org/opencms/ade/sitemap/client/CmsSitemapView.java index <HASH>..<HASH> 100644 --- a/src-gwt/org/opencms/ade/sitemap/client/CmsSitemapView.java +++ b/src-gwt/org/opencms/ade/sitemap/client/CmsSitemapView.java @@ -500,6 +500,7 @@ implements I_CmsSitemapChangeHandler, I_CmsSitemapLoadHandler { parentModel.getSitePath() != null); m_parentModelPageTreeItems.put(parentModel.getStructureId(), treeItem); m_parentModelPageRoot.addChild(treeItem); + m_modelPageData.put(parentModel.getStructureId(), parentModel); } if (m_parentModelPageRoot.getChildren().getWidgetCount() > 0) { m_modelPageTree.add(m_parentModelPageRoot);
Fixing issue where parent template models could not be copied.
alkacon_opencms-core
train
a792a6f53c57e5f6ace0dbfc2df9ca195a0bbce5
diff --git a/fedmsg/meta/base.py b/fedmsg/meta/base.py index <HASH>..<HASH> 100644 --- a/fedmsg/meta/base.py +++ b/fedmsg/meta/base.py @@ -109,8 +109,21 @@ class BaseProcessor(object): 'packages': ['ghc', 'nethack', ... ], 'topics': ['org.fedoraproject.prod.git.receive'], 'categories': ['git'], - 'msg_ids': ['2014-abcde', '2014-bcdef', '2014-cdefg', ... ], - }, + 'msg_ids': { + '2014-abcde': { + 'subtitle': 'relrod pushed some commits to ghc', + 'title': 'git.receive', + 'link': 'http://...', + 'icon': 'http://...', + }, + '2014-bcdef': { + 'subtitle': 'relrod pushed some commits to nethack', + 'title': 'git.receive', + 'link': 'http://...', + 'icon': 'http://...', + }, + }, + } The telltale sign that an entry in a list of messages represents a conglomerate message is the presence of the plural ``msg_ids`` field. @@ -262,12 +275,29 @@ class BaseConglomerator(object): topics = set([msg['topic'] for msg in constituents]) categories = set([t.split('.')[3] for t in topics]) + # Avoid circular import + import fedmsg.meta as fm + + # Include metadata about constituent messages in the aggregate + # http://da.gd/12Eso + msg_ids = dict([ + (msg['msg_id'], { + 'title': fm.msg2title(msg, **config), + 'subtitle': fm.msg2subtitle(msg, **config), + 'link': fm.msg2link(msg, **config), + 'icon': fm.msg2icon(msg, **config), + 'secondary_icon': fm.msg2secondary_icon(msg, **config), + 'usernames': fm.msg2usernames(msg, **config), + 'packages': fm.msg2packages(msg, **config), + 'objects': fm.msg2objects(msg, **config), + }) for msg in constituents]) + return { 'start_time': min(timestamps), 'end_time': max(timestamps), 'timestamp': average_timestamp, 'human_time': arrow.get(average_timestamp).humanize(), - 'msg_ids': [msg['msg_id'] for msg in constituents], + 'msg_ids': msg_ids, 'usernames': usernames, 'packages': packages, 'topics': topics,
Include constituent metadata in the conglomerate message.
fedora-infra_fedmsg
train
9290cc97d1cb608503a83b7c3945832158a4bddb
diff --git a/test/select.spec.js b/test/select.spec.js index <HASH>..<HASH> 100644 --- a/test/select.spec.js +++ b/test/select.spec.js @@ -8,7 +8,7 @@ describe('ui-select tests', function() { $rootScope = _$rootScope_; scope = $rootScope.$new(); $compile = _$compile_; - scope.selection = {} + scope.selection = {} scope.getGroupLabel = function(person) { return person.age % 2 ? 'even' : 'odd'; }; @@ -23,6 +23,18 @@ describe('ui-select tests', function() { { name: 'Nicole', email: 'nicole@email.com', group: 'bar', age: 43 }, { name: 'Natasha', email: 'natasha@email.com', group: 'Baz', age: 54 } ]; + + scope.someObject = {}; + scope.someObject.people = [ + { name: 'Adam', email: 'adam@email.com', group: 'Foo', age: 12 }, + { name: 'Amalie', email: 'amalie@email.com', group: 'Foo', age: 12 }, + { name: 'Estefanía', email: 'estefanía@email.com', group: 'Foo', age: 21 }, + { name: 'Adrian', email: 'adrian@email.com', group: 'Foo', age: 21 }, + { name: 'Wladimir', email: 'wladimir@email.com', group: 'Foo', age: 30 }, + { name: 'Samantha', email: 'samantha@email.com', group: 'bar', age: 30 }, + { name: 'Nicole', email: 'nicole@email.com', group: 'bar', age: 43 }, + { name: 'Natasha', email: 'natasha@email.com', group: 'Baz', age: 54 } + ]; })); @@ -305,7 +317,7 @@ describe('ui-select tests', function() { ); }).toThrow(new Error('[ui.select:transcluded] Expected 1 .ui-select-match but got \'0\'.')); }); - + it('should format the model correctly using alias', function() { var el = compileTemplate( '<ui-select ng-model="selection.selected"> \ @@ -317,7 +329,7 @@ describe('ui-select tests', function() { </ui-select>' ); clickItem(el, 'Samantha'); - expect(scope.selection.selected).toBe(scope.people[5]); + expect(scope.selection.selected).toBe(scope.people[5]); }); it('should parse the model correctly using alias', function() { @@ -346,7 +358,7 @@ describe('ui-select tests', function() { </ui-select>' ); clickItem(el, 'Samantha'); - expect(scope.selection.selected).toBe('Samantha'); + expect(scope.selection.selected).toBe('Samantha'); }); it('should parse the model correctly using property of alias', function() { @@ -364,6 +376,7 @@ describe('ui-select tests', function() { expect(getMatchLabel(el)).toEqual('Samantha'); }); + //TODO Is this really something we should expect? it('should parse the model correctly using property of alias but passed whole object', function() { var el = compileTemplate( '<ui-select ng-model="selection.selected"> \ @@ -382,7 +395,7 @@ describe('ui-select tests', function() { it('should format the model correctly without alias', function() { var el = createUiSelect(); clickItem(el, 'Samantha'); - expect(scope.selection.selected).toBe(scope.people[5]); + expect(scope.selection.selected).toBe(scope.people[5]); }); it('should parse the model correctly without alias', function() { @@ -391,4 +404,34 @@ describe('ui-select tests', function() { scope.$digest(); expect(getMatchLabel(el)).toEqual('Samantha'); }); + + it('should display choices correctly with child array', function() { + var el = compileTemplate( + '<ui-select ng-model="selection.selected"> \ + <ui-select-match placeholder="Pick one...">{{$select.selected.name}}</ui-select-match> \ + <ui-select-choices repeat="person in someObject.people | filter: $select.search"> \ + <div ng-bind-html="person.name | highlight: $select.search"></div> \ + <div ng-bind-html="person.email | highlight: $select.search"></div> \ + </ui-select-choices> \ + </ui-select>' + ); + scope.selection.selected = scope.people[5]; + scope.$digest(); + expect(getMatchLabel(el)).toEqual('Samantha'); + }); + + it('should format the model correctly using property of alias and when using child array for choices', function() { + var el = compileTemplate( + '<ui-select ng-model="selection.selected"> \ + <ui-select-match placeholder="Pick one...">{{$select.selected.name}}</ui-select-match> \ + <ui-select-choices repeat="person.name as person in someObject.people | filter: $select.search"> \ + <div ng-bind-html="person.name | highlight: $select.search"></div> \ + <div ng-bind-html="person.email | highlight: $select.search"></div> \ + </ui-select-choices> \ + </ui-select>' + ); + clickItem(el, 'Samantha'); + expect(scope.selection.selected).toBe('Samantha'); + }); + });
test(choices): should work correctly with child array as choices
angular-ui_ui-select
train
bf3bc0ed6bdc239e31e2a78486d5699d7fcbde22
diff --git a/lease/lessor.go b/lease/lessor.go index <HASH>..<HASH> 100644 --- a/lease/lessor.go +++ b/lease/lessor.go @@ -26,6 +26,15 @@ var ( minLeaseTerm = 5 * time.Second ) +// DeleteableRange defines an interface with DeleteRange method. +// We define this interface only for lessor to limit the number +// of methods of storage.KV to what lessor actually needs. +// +// Having a minimum interface makes testing easy. +type DeleteableRange interface { + DeleteRange(key, end []byte) (int64, int64) +} + // a lessor is the owner of leases. It can grant, revoke, // renew and modify leases for lessee. // TODO: persist lease on to stable backend for failure recovery. @@ -40,12 +49,18 @@ type lessor struct { // FindExpired and Renew should be the most frequent operations. leaseMap map[uint64]*lease + // A DeleteableRange the lessor operates on. + // When a lease expires, the lessor will delete the + // leased range (or key) from the DeleteableRange. + dr DeleteableRange + idgen *idutil.Generator } -func NewLessor(lessorID uint8) *lessor { +func NewLessor(lessorID uint8, dr DeleteableRange) *lessor { return &lessor{ leaseMap: make(map[uint64]*lease), + dr: dr, idgen: idutil.NewGenerator(lessorID, time.Now()), } } @@ -62,7 +77,7 @@ func (le *lessor) Grant(expiry time.Time) *lease { le.mu.Lock() defer le.mu.Unlock() - l := &lease{id: id, expiry: expiry} + l := &lease{id: id, expiry: expiry, itemSet: make(map[leaseItem]struct{})} if _, ok := le.leaseMap[id]; ok { panic("lease: unexpected duplicate ID!") } @@ -85,7 +100,10 @@ func (le *lessor) Revoke(id uint64) error { delete(le.leaseMap, l.id) - // TODO: remove attached items + for item := range l.itemSet { + le.dr.DeleteRange([]byte(item.key), []byte(item.endRange)) + } + return nil } diff --git a/lease/lessor_test.go b/lease/lessor_test.go index <HASH>..<HASH> 100644 --- a/lease/lessor_test.go +++ b/lease/lessor_test.go @@ -24,7 +24,7 @@ import ( // The granted lease should have a unique ID with a term // that is greater than minLeaseTerm. func TestLessorGrant(t *testing.T) { - le := NewLessor(1) + le := NewLessor(1, &fakeDeleteable{}) l := le.Grant(time.Now().Add(time.Second)) gl := le.get(l.id) @@ -43,15 +43,28 @@ func TestLessorGrant(t *testing.T) { } // TestLessorRevoke ensures Lessor can revoke a lease. +// The items in the revoked lease should be removed from +// the DeleteableKV. // The revoked lease cannot be got from Lessor again. func TestLessorRevoke(t *testing.T) { - le := NewLessor(1) + fd := &fakeDeleteable{} + le := NewLessor(1, fd) // grant a lease with long term (100 seconds) to // avoid early termination during the test. l := le.Grant(time.Now().Add(100 * time.Second)) - err := le.Revoke(l.id) + items := []leaseItem{ + {"foo", ""}, + {"bar", "zar"}, + } + + err := le.Attach(l.id, items) + if err != nil { + t.Fatalf("failed to attach items to the lease: %v", err) + } + + err = le.Revoke(l.id) if err != nil { t.Fatal("failed to revoke lease:", err) } @@ -59,11 +72,16 @@ func TestLessorRevoke(t *testing.T) { if le.get(l.id) != nil { t.Errorf("got revoked lease %x", l.id) } + + wdeleted := []string{"foo_", "bar_zar"} + if !reflect.DeepEqual(fd.deleted, wdeleted) { + t.Errorf("deleted= %v, want %v", fd.deleted, wdeleted) + } } // TestLessorRenew ensures Lessor can renew an existing lease. func TestLessorRenew(t *testing.T) { - le := NewLessor(1) + le := NewLessor(1, &fakeDeleteable{}) l := le.Grant(time.Now().Add(5 * time.Second)) le.Renew(l.id, time.Now().Add(100*time.Second)) @@ -73,3 +91,12 @@ func TestLessorRenew(t *testing.T) { t.Errorf("failed to renew the lease for 100 seconds") } } + +type fakeDeleteable struct { + deleted []string +} + +func (fd *fakeDeleteable) DeleteRange(key, end []byte) (int64, int64) { + fd.deleted = append(fd.deleted, string(key)+"_"+string(end)) + return 0, 0 +}
lease: delete items when the lease is revoked. Add minimum KV interface and implmement the deleting mechanism for revoking lease.
etcd-io_etcd
train
01d5fbc2e06d76db1501ad3e24691c2643a9acd7
diff --git a/core/src/main/java/hudson/model/UpdateSite.java b/core/src/main/java/hudson/model/UpdateSite.java index <HASH>..<HASH> 100644 --- a/core/src/main/java/hudson/model/UpdateSite.java +++ b/core/src/main/java/hudson/model/UpdateSite.java @@ -597,6 +597,12 @@ public class UpdateSite { @Exported public final Map<String,String> dependencies = new HashMap<String,String>(); + /** + * Optional dependencies of this plugin. + */ + @Exported + public final Map<String,String> optionalDependencies = new HashMap<String,String>(); + @DataBoundConstructor public Plugin(String sourceId, JSONObject o) { super(sourceId, o, UpdateSite.this.url); @@ -611,9 +617,12 @@ public class UpdateSite { // Make sure there's a name attribute, that that name isn't maven-plugin - we ignore that one - // and that the optional value isn't true. if (get(depObj,"name")!=null - && !get(depObj,"name").equals("maven-plugin") - && get(depObj,"optional").equals("false")) { - dependencies.put(get(depObj,"name"), get(depObj,"version")); + && !get(depObj,"name").equals("maven-plugin")) { + if (get(depObj, "optional").equals("false")) { + dependencies.put(get(depObj, "name"), get(depObj, "version")); + } else { + optionalDependencies.put(get(depObj, "name"), get(depObj, "version")); + } } } @@ -691,6 +700,22 @@ public class UpdateSite { } } + for(Map.Entry<String,String> e : optionalDependencies.entrySet()) { + Plugin depPlugin = Jenkins.getInstance().getUpdateCenter().getPlugin(e.getKey()); + if (depPlugin == null) { + continue; + } + VersionNumber requiredVersion = new VersionNumber(e.getValue()); + + PluginWrapper current = depPlugin.getInstalled(); + + // If the optional dependency plugin is installed, is the version we depend on newer than + // what's installed? If so, upgrade. + if (current != null && current.isOlderThan(requiredVersion)) { + deps.add(depPlugin); + } + } + return deps; }
[FIXED JENKINS-<I>] Installing a plugin with optional dependencies doesn't upgrade the optional dependencies when needed
jenkinsci_jenkins
train
f9377e8fdd9cfa3533d45a07c9a81b06800c91ef
diff --git a/lib/depject/gathering/sheet/edit.js b/lib/depject/gathering/sheet/edit.js index <HASH>..<HASH> 100644 --- a/lib/depject/gathering/sheet/edit.js +++ b/lib/depject/gathering/sheet/edit.js @@ -131,7 +131,7 @@ exports.create = function (api) { publiclyEditable: true, value: { author: api.keys.sync.id(), - private: true, + private: false, // patchwork can only make public gatherings content: { type: 'gathering', recps: participants
fix: don't show gatherings as private in the preview
ssbc_patchwork
train
74084f3967e36364470576549e1837a8c606c31b
diff --git a/snmp/datadog_checks/snmp/snmp.py b/snmp/datadog_checks/snmp/snmp.py index <HASH>..<HASH> 100644 --- a/snmp/datadog_checks/snmp/snmp.py +++ b/snmp/datadog_checks/snmp/snmp.py @@ -129,15 +129,10 @@ class SnmpCheck(AgentCheck): else: return None - def discover_instances(self): - # type: () -> None + def discover_instances(self, interval): + # type: (float) -> None config = self._config - if config.ip_network is None: - raise RuntimeError("Expected config.ip_network to be set to start discovery") - - discovery_interval = config.instance.get('discovery_interval', 3600) - while self._running: start_time = time.time() for host in config.network_hosts(): @@ -171,8 +166,8 @@ class SnmpCheck(AgentCheck): write_persistent_cache(self.check_id, json.dumps(list(config.discovered_instances))) time_elapsed = time.time() - start_time - if discovery_interval - time_elapsed > 0: - time.sleep(discovery_interval - time_elapsed) + if interval - time_elapsed > 0: + time.sleep(interval - time_elapsed) def raise_on_error_indication(self, error_indication, ip_address): # type: (Any, Optional[str]) -> None @@ -356,7 +351,14 @@ class SnmpCheck(AgentCheck): host_config = self._build_config(instance) self._config.discovered_instances[host] = host_config - self._thread = threading.Thread(target=self.discover_instances, name=self.name) + raw_discovery_interval = self._config.instance.get('discovery_interval', 3600) + try: + discovery_interval = float(raw_discovery_interval) + except (ValueError, TypeError): + message = 'discovery_interval could not be parsed as a number: {!r}'.format(raw_discovery_interval) + raise ConfigurationError(message) + + self._thread = threading.Thread(target=self.discover_instances, args=(discovery_interval,), name=self.name) self._thread.daemon = True self._thread.start() self._executor = futures.ThreadPoolExecutor(max_workers=self._config.workers) diff --git a/snmp/tests/test_unit.py b/snmp/tests/test_unit.py index <HASH>..<HASH> 100644 --- a/snmp/tests/test_unit.py +++ b/snmp/tests/test_unit.py @@ -215,6 +215,20 @@ def test_removing_host(): assert warnings == [msg, msg, msg] +def test_invalid_discovery_interval(): + instance = common.generate_instance_config(common.SUPPORTED_METRIC_TYPES) + + # Trigger autodiscovery. + instance.pop('ip_address') + instance['network_address'] = '192.168.0.0/24' + + instance['discovery_interval'] = 'not_parsable_as_a_float' + + check = SnmpCheck('snmp', {}, [instance]) + with pytest.raises(ConfigurationError): + check.check(instance) + + @mock.patch("datadog_checks.snmp.snmp.read_persistent_cache") def test_cache_discovered_host(read_mock): instance = common.generate_instance_config(common.SUPPORTED_METRIC_TYPES) @@ -346,7 +360,6 @@ def test_discovery_tags(): instance.pop('ip_address') instance['network_address'] = '192.168.0.0/29' - instance['discovery_interval'] = 0 instance['tags'] = ['test:check'] check = SnmpCheck('snmp', {}, [instance]) @@ -361,7 +374,7 @@ def test_discovery_tags(): check.fetch_sysobject_oid = mock_fetch - check.discover_instances() + check.discover_instances(interval=0) config = check._config.discovered_instances['192.168.0.2'] assert set(config.tags) == {'snmp_device:192.168.0.2', 'test:check'}
Validate and cast `discovery_interval` to a number (#<I>) * Validate and parse `discovery_interval` as an integer * Switch to float, fix unit test * Pass args to Thread
DataDog_integrations-core
train
7ce5df192358d4cdc64136360d9cbdeeac33aac0
diff --git a/lib/fuzz/cache.rb b/lib/fuzz/cache.rb index <HASH>..<HASH> 100644 --- a/lib/fuzz/cache.rb +++ b/lib/fuzz/cache.rb @@ -2,7 +2,7 @@ require "fileutils" class Fuzz::Cache def initialize(cache_file) - @cache_file = cache_file + @cache_file = File.expand_path(cache_file) @entries = cache_entries(@cache_file) end diff --git a/lib/fuzz/version.rb b/lib/fuzz/version.rb index <HASH>..<HASH> 100644 --- a/lib/fuzz/version.rb +++ b/lib/fuzz/version.rb @@ -1,3 +1,3 @@ module Fuzz - VERSION = "0.1.0" + VERSION = "0.1.1" end
Expand cache file path This lets us use `~` and other shortcuts in our cache paths.
hrs_fuzz
train
dc26025a160bf0d981ef939db172a3dbe2d52488
diff --git a/lib/parser/juttle-parser.js b/lib/parser/juttle-parser.js index <HASH>..<HASH> 100644 --- a/lib/parser/juttle-parser.js +++ b/lib/parser/juttle-parser.js @@ -179,6 +179,16 @@ function parse(mainSource, options) { } } + function resolveImport(import_) { + return options.moduleResolver(import_.modulename.value, import_.localname) + .catch(function(err) { + throw errors.compileError('RT-MODULE-NOT-FOUND', { + module: import_.modulename.value, + location: import_.location + }); + }); + } + options = processOptions(options, defaultResolver); var asts = {}; @@ -199,13 +209,7 @@ function parse(mainSource, options) { _.each(imports, checkImportNode); return Promise.map(imports, function(imp) { - return options.moduleResolver(imp.modulename.value, imp.localname) - .catch(function(err) { - throw errors.compileError('RT-MODULE-NOT-FOUND', { - module: imp.modulename.value, - location: imp.location - }); - }) + return resolveImport(imp) .then(function(res) { return parse_(res.source, res.name); });
parser.parse: Extract `resolveImport` This makes the code slightly more readable.
juttle_juttle
train
98ead7821d77c59c4ef711fcbee597de8bf01d74
diff --git a/src/NestedForm.js b/src/NestedForm.js index <HASH>..<HASH> 100644 --- a/src/NestedForm.js +++ b/src/NestedForm.js @@ -17,7 +17,7 @@ class NestedForm extends React.Component { name: PropTypes.string.isRequired, schema: PropTypes.object, errors: PropTypes.object, - onError: PropTypes.func.isRequired, + onError: PropTypes.func, meta: PropTypes.shape({ errors: PropTypes.object.isRequired, onError: PropTypes.func.isRequired,
fix: do not require onError in NestedForm (#<I>)
jquense_react-formal
train
41ba49ccec3def19e05ec8e2f867e81e20371601
diff --git a/create.js b/create.js index <HASH>..<HASH> 100644 --- a/create.js +++ b/create.js @@ -5,7 +5,7 @@ var isExtensible = require('es5-ext/array/_is-extensible') , validArray = require('es5-ext/array/valid-array') , isCopy = require('es5-ext/array/#/is-copy') , validFunction = require('es5-ext/function/valid-function') - , toInt = require('es5-ext/number/to-int') + , toInteger = require('es5-ext/number/to-integer') , eq = require('es5-ext/object/eq') , mixin = require('es5-ext/object/mixin-prototypes') , setPrototypeOf = require('es5-ext/object/set-prototype-of') @@ -118,8 +118,8 @@ module.exports = memoize(function (Constructor) { var result, l = arguments.length, items; if (!l) return []; if (l <= 2) { - if (toInt(start) >= this.length) return []; - if (toInt(deleteCount) <= 0) return []; + if (toInteger(start) >= this.length) return []; + if (toInteger(deleteCount) <= 0) return []; } else { items = slice.call(arguments, 2); } diff --git a/filter-map-slice-sorted.js b/filter-map-slice-sorted.js index <HASH>..<HASH> 100644 --- a/filter-map-slice-sorted.js +++ b/filter-map-slice-sorted.js @@ -6,7 +6,7 @@ var aFrom = require('es5-ext/array/from') , remove = require('es5-ext/array/#/remove') , invoke = require('es5-ext/function/invoke') , validFunction = require('es5-ext/function/valid-function') - , toInt = require('es5-ext/number/to-int') + , toInteger = require('es5-ext/number/to-integer') , eq = require('es5-ext/object/eq') , callable = require('es5-ext/object/valid-callable') , value = require('es5-ext/object/valid-value') @@ -170,8 +170,8 @@ module.exports = memoize(function (ObservableArray) { }.bind(this)) }); return result; - }, { resolvers: [toInt, - function (val) { return (val === undefined) ? Infinity : toInt(val); }], + }, { resolvers: [toInteger, + function (val) { return (val === undefined) ? Infinity : toInteger(val); }], refCounter: true, dispose: invokeDispose }), filter: d(function (callbackFn/*, thisArg*/) { @@ -326,7 +326,7 @@ module.exports = memoize(function (ObservableArray) { } else if (type === 'shift') { result.emit('change', { type: 'shift', value: shift.call(result) }); } else if (type === 'splice') { - i = toInt(event.arguments[0]); + i = toInteger(event.arguments[0]); if (i < 0) i = this.length - i; args = map.call(event.arguments, function (val, j) { if (j < 2) return val;
Update up to changes in es5-ext
medikoo_observable-array
train
f17a8a3c01210c10cedeba39fbcc569393de1ec8
diff --git a/regulargrid/cartesiangrid.py b/regulargrid/cartesiangrid.py index <HASH>..<HASH> 100644 --- a/regulargrid/cartesiangrid.py +++ b/regulargrid/cartesiangrid.py @@ -1,5 +1,5 @@ import numpy -import itertools +import scipy.ndimage class CartesianGrid(object): """ @@ -9,45 +9,13 @@ class CartesianGrid(object): def __init__(self, limits, values): self.values = values self.limits = limits - self.highestindex = numpy.array(self.values.shape) - 1 def __call__(self, *coords): - """ - interpolation at coordinates, which are already [0,size) - """ - # find relevant edges between which coords is situated - #print coords, - for c in coords: - assert numpy.shape(c) != (), ('need array of coordinates, not just one', coords) + # transform coords into pixel values coords = [(c - lo) * (n - 1) / (hi - lo) for (lo, hi), c, n in zip(self.limits, coords, self.values.shape)] - indices = numpy.floor(coords).astype(int) - for j, i in enumerate(indices): - mask = i == self.highestindex[j] - indices[j][mask] = self.highestindex[j] - 1 - - norm_distances = numpy.asarray(coords) - indices - neg_norm_distances = 1 - norm_distances - edges = numpy.array([[i, i + 1] for i in indices]) - #print edges.shape - #edges = edges.reshape([edges.shape[0]] + list(edges.shape)[2:]) - - # find relevant values - # each i and i+1 represents a edge - value = 0. - #print 'edges', edges.shape, edges - for edge_indices in itertools.product(*edges): - #print 'ei', edge_indices, 'indices', indices - weight = numpy.where(edge_indices == indices, neg_norm_distances, norm_distances) - - #assert (edge_indices == indices).shape == numpy.asarray(edge_indices).shape - #assert (edge_indices == indices).shape == indices.shape - #print 'weight', weight.shape, weight.prod(axis=0).shape, weight - #print 'edges', numpy.asarray(edge_indices).shape, 'values', self.values[edge_indices], - value += self.values[edge_indices] * weight.prod(axis=0) - #print 'weights:', edge_indices, self.values[edge_indices], weight - #print value - return value + return scipy.ndimage.map_coordinates(self.values, coords, + cval=numpy.nan, order=1) __doc__ = CartesianGrid.__doc__
even faster implementation based on scipy.ndimage.map_coordinates
JohannesBuchner_regulargrid
train
ee12bb52381e8f0583c61fc25d43de1f55b80a87
diff --git a/src/main/java/org/codehaus/groovy/vmplugin/v8/Selector.java b/src/main/java/org/codehaus/groovy/vmplugin/v8/Selector.java index <HASH>..<HASH> 100644 --- a/src/main/java/org/codehaus/groovy/vmplugin/v8/Selector.java +++ b/src/main/java/org/codehaus/groovy/vmplugin/v8/Selector.java @@ -932,11 +932,12 @@ public abstract class Selector { test = IS_NULL.asType(MethodType.methodType(boolean.class, paramType)); if (LOG_ENABLED) LOG.info("added null argument check at pos " + i); } else { - Class<?> argClass = arg.getClass(); - if (paramType.isPrimitive()) continue; - //if (Modifier.isFinal(argClass.getModifiers()) && TypeHelper.argumentClassIsParameterClass(argClass,pt[i])) continue; + if (Modifier.isFinal(paramType.getModifiers())) { + // primitive types are also `final` + continue; + } test = SAME_CLASS. - bindTo(argClass). + bindTo(arg.getClass()). asType(MethodType.methodType(boolean.class, paramType)); if (LOG_ENABLED) LOG.info("added same class check at pos " + i); }
Avoid unnecessary guards for receiver and parameter of `final` type
apache_groovy
train
790170c355ec630907c0568d62e63fa1b418f860
diff --git a/src/main/java/com/networknt/schema/OneOfValidator.java b/src/main/java/com/networknt/schema/OneOfValidator.java index <HASH>..<HASH> 100644 --- a/src/main/java/com/networknt/schema/OneOfValidator.java +++ b/src/main/java/com/networknt/schema/OneOfValidator.java @@ -18,14 +18,15 @@ package com.networknt.schema; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; + import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.ArrayList; import java.util.HashSet; +import java.util.Iterator; import java.util.List; import java.util.Set; -import java.util.stream.Collectors; public class OneOfValidator extends BaseJsonValidator implements JsonValidator { private static final Logger logger = LoggerFactory.getLogger(RequiredValidator.class); @@ -46,13 +47,13 @@ public class OneOfValidator extends BaseJsonValidator implements JsonValidator { debug(logger, node, rootNode, at); int numberOfValidSchema = 0; - Set<ValidationMessage> errors = new HashSet<>(); + Set<ValidationMessage> errors = new HashSet<ValidationMessage>(); for (JsonSchema schema : schemas) { Set<ValidationMessage> schemaErrors = schema.validate(node, rootNode, at); if (schemaErrors.isEmpty()) { numberOfValidSchema++; - errors = new HashSet<>(); + errors = new HashSet<ValidationMessage>(); } if(numberOfValidSchema == 0){ errors.addAll(schemaErrors); @@ -63,13 +64,17 @@ public class OneOfValidator extends BaseJsonValidator implements JsonValidator { } if (numberOfValidSchema == 0) { - errors = errors.stream() - .filter(msg -> !ValidatorTypeCode.ADDITIONAL_PROPERTIES - .equals(ValidatorTypeCode.fromValue(msg.getType()))) - .collect(Collectors.toSet()); + for (Iterator<ValidationMessage> it = errors.iterator(); it.hasNext();) { + ValidationMessage msg = it.next(); + + if (ValidatorTypeCode.ADDITIONAL_PROPERTIES.equals(ValidatorTypeCode.fromValue(msg + .getType()))) { + it.remove(); + } + } } if (numberOfValidSchema > 1) { - errors = new HashSet<>(); + errors = new HashSet<ValidationMessage>(); errors.add(buildValidationMessage(at, "")); }
backport 5 of <I> source lines that prevent compiling for java <I>
networknt_json-schema-validator
train
ea5d6b69e5ec9cda11c0996de0d48f25d2c386e5
diff --git a/sonar-plugin-api/src/test/java/org/sonar/api/server/ws/WebServiceTest.java b/sonar-plugin-api/src/test/java/org/sonar/api/server/ws/WebServiceTest.java index <HASH>..<HASH> 100644 --- a/sonar-plugin-api/src/test/java/org/sonar/api/server/ws/WebServiceTest.java +++ b/sonar-plugin-api/src/test/java/org/sonar/api/server/ws/WebServiceTest.java @@ -461,12 +461,7 @@ public class WebServiceTest { .setDescription("Show metric") .setSince("4.2") .setResponseExample(getClass().getResource("WebServiceTest/response-example.txt")) - .setHandler(new RequestHandler() { - @Override - public void handle(Request request, Response response) { - show(request, response); - } - }); + .setHandler(this::show); newController.createAction("create") .setDescription("Create metric") @@ -479,12 +474,7 @@ public class WebServiceTest { new Changelog("6.4", "Last event"), new Changelog("6.0", "Old event"), new Changelog("4.5.6", "Very old event")) - .setHandler(new RequestHandler() { - @Override - public void handle(Request request, Response response) { - create(request, response); - } - }); + .setHandler(this::create); newController.done(); }
Replace anonymous classes with method reference in WebServiceTest
SonarSource_sonarqube
train
c066c1124e68ea4f1367c4a8edd796ba63a7d4fb
diff --git a/tests/maskers/_fixed_composite.py b/tests/maskers/_fixed_composite.py index <HASH>..<HASH> 100644 --- a/tests/maskers/_fixed_composite.py +++ b/tests/maskers/_fixed_composite.py @@ -3,7 +3,8 @@ def test_fixed_composite_masker_call(): import numpy as np - from transformers import AutoTokenizer + from transformers import AutoTokenizer, AutoModelForCausalLM + import shap from shap import maskers args=("This is a test statement for fixed composite masker",) @@ -15,7 +16,7 @@ def test_fixed_composite_masker_call(): fixed_composite_masker = maskers.FixedComposite(masker) - expected_fixed_composite_masked_output = [(np.array(['']), np.array(["This is a test statement for fixed composite masker"]))] + expected_fixed_composite_masked_output = (np.array(['']), np.array(["This is a test statement for fixed composite masker"])) fixed_composite_masked_output = fixed_composite_masker(mask, *args) - assert fixed_composite_masked_output == expected_fixed_composite_masked_output \ No newline at end of file + assert fixed_composite_masked_output == expected_fixed_composite_masked_output
Updated test for fixed composite masker
slundberg_shap
train
d5f7dd3c8538fb035f1c769be27798512d833266
diff --git a/src/test/java/com/shippo/model/CustomsDeclarationTest.java b/src/test/java/com/shippo/model/CustomsDeclarationTest.java index <HASH>..<HASH> 100644 --- a/src/test/java/com/shippo/model/CustomsDeclarationTest.java +++ b/src/test/java/com/shippo/model/CustomsDeclarationTest.java @@ -50,7 +50,11 @@ public class CustomsDeclarationTest extends ShippoTest { addressImporterMap.put("country", "US"); objectMap.put("address_importer", addressImporterMap); + Map<String, Object> taxIdMap = new HashMap<String, Object>(); + taxIdMap.put("number", "123456789"); + taxIdMap.put("type", "EIN"); Map<String, Object> exporterIdentificationMap = new HashMap<String, Object>(); + exporterIdentificationMap.put("tax_id", taxIdMap); exporterIdentificationMap.put("eori_number", "PL123456789"); objectMap.put("exporter_identification", exporterIdentificationMap); }
Updating tax id field in tests
goshippo_shippo-java-client
train
8dc2803447114f23fc5923a457d88dd8f0062b7e
diff --git a/classes/fields/file.php b/classes/fields/file.php index <HASH>..<HASH> 100644 --- a/classes/fields/file.php +++ b/classes/fields/file.php @@ -1249,7 +1249,12 @@ class PodsField_File extends PodsField { } // Upload file. - $attachment_id = media_handle_upload( 'Filedata', $params->item_id ); + $post_id = 0; + if ( 'post_type' === pods_v( 'type', $pod, null ) ) { + $post_id = $params->item_id; + } + + $attachment_id = media_handle_upload( 'Filedata', $post_id ); // End custom directory. if ( 'wp' !== $upload_dir ) {
Only pass item ID if it's a Post WordPress's `media_handle_upload()` can only accept a Post ID.
pods-framework_pods
train
50c988f4c7901a8c2252455bd15a418de84eb588
diff --git a/Gruntfile.js b/Gruntfile.js index <HASH>..<HASH> 100644 --- a/Gruntfile.js +++ b/Gruntfile.js @@ -100,7 +100,7 @@ module.exports = function(grunt) { // By default, lint and run all tests. grunt.registerTask('default', [ 'clean', - 'processhtml:dist', + 'processhtml:dist', 'copy:dist', 'uncss:dist', 'compare_size' diff --git a/README.md b/README.md index <HASH>..<HASH> 100644 --- a/README.md +++ b/README.md @@ -4,11 +4,9 @@ A grunt task for generating CSS files containing only those styles used in your ## Preview -Taking a Bootstrap project using >120KB of CSS down to 20KB. The trimming process does not yet generate 1:1 expected output, but it's close. +Taking a Bootstrap project using >120KB of CSS down to 11KB. The trimming process does not yet generate 1:1 expected output, but it's very close. -![](http://i.imgur.com/0QhdbOd.gif) - -Issues are largely to do with pseudo-selector support in the parser used. +![](http://i.imgur.com/uhWMALH.gif) ## The problem @@ -24,13 +22,7 @@ I am currently also investigating [mincss](http://www.peterbe.com/plog/mincss) w ## Limitations -This project currently has a number of important limitations. `uncss` currently doesn't run with PhantomJS, meaning styles that are dynamically added via JavaScript are not taken into account. - -A potentially better solution to this would be hooking into `helium` (mentioned earlier). Unfortunately, getting it working as a module we can use via grunt is non-trivial work, however this is currently being tackled as part of the [helium-cli](https://github.com/villadora/helium-cli) project. - -Once it has been released and is in a stable state I intend on moving this project over to using it. - -Update: uncss is also currently exploring a PhantomJS implementation. +`uncss` currently doesn't run with PhantomJS, but will support this soon. ## Configuration @@ -38,14 +30,15 @@ Sample configuration: ```shell uncss: { - bootstrap: { + dist: { files: { - 'dist/css/tidy.css': [ - 'app/index.html', - 'app/about.html'] + 'dist/css/tidy.css': ['app/index.html','app/about.html'] + } + }, + options: { + compress:true } - } -} +}, ``` Which you can then use alongside a processor like `processhtml` to @@ -73,6 +66,12 @@ processhtml: { } ``` +Options supported include `compress` which will compress the generated CSS and `ignore` which allows you to tell the parser to ignore specific selectors. E.g: + +```javascript +ignore: ['#added_at_runtime', '.created_by_jQuery'] +``` + There is a test project included under the `app` directory which you can build by running `grunt` after an `npm install`. It also includes a `grunt compare_size` task for getting a feel of the before and after CSS sizes: ![](http://i.imgur.com/bUseCPh.png) diff --git a/tasks/uncss.js b/tasks/uncss.js index <HASH>..<HASH> 100644 --- a/tasks/uncss.js +++ b/tasks/uncss.js @@ -39,6 +39,7 @@ module.exports = function (grunt) { uncss(src, options, function (output) { grunt.file.write(f.dest, output); }); + done(); } catch (e) { console.log(e); var err = new Error('Uncss failed.');
Updates to readme, Gruntfile, task to call done
uncss_grunt-uncss
train
3e6e946eaa02d6bd32669db202e8f2b8f226dff0
diff --git a/lib/kappa/team.rb b/lib/kappa/team.rb index <HASH>..<HASH> 100644 --- a/lib/kappa/team.rb +++ b/lib/kappa/team.rb @@ -2,10 +2,10 @@ module Kappa class TeamBase include IdEquality - def initialize(hash) - parse(hash) - end - + # + # GET /teams/:team + # https://github.com/justintv/Twitch-API/blob/master/v2_resources/teams.md#get-teamsteam + # def self.get(team_name) json = connection.get("teams/#{team_name}") if json['status'] == 404 @@ -20,24 +20,8 @@ end module Kappa::V2 class Team < Kappa::TeamBase include Connection - - # - # GET /teams/:team - # https://github.com/justintv/Twitch-API/blob/master/v2_resources/teams.md#get-teamsteam - # - - attr_reader :id - attr_reader :info - attr_reader :background_url - attr_reader :banner_url - attr_reader :logo_url - attr_reader :name - attr_reader :display_name - attr_reader :updated_at - attr_reader :created_at - private - def parse(hash) + def initialize(hash) @id = hash['_id'] @info = hash['info'] @background_url = hash['background'] @@ -48,6 +32,16 @@ module Kappa::V2 @updated_at = DateTime.parse(hash['updated_at']) @created_at = DateTime.parse(hash['created_at']) end + + attr_reader :id + attr_reader :info + attr_reader :background_url + attr_reader :banner_url + attr_reader :logo_url + attr_reader :name + attr_reader :display_name + attr_reader :updated_at + attr_reader :created_at end class Teams
Replacing Team#parse with Team#initialize to follow common pattern.
schmich_kappa
train
e5308d12793d0490352489ccf8deb75bd8c44171
diff --git a/bin/webpack.js b/bin/webpack.js index <HASH>..<HASH> 100755 --- a/bin/webpack.js +++ b/bin/webpack.js @@ -343,9 +343,8 @@ function processOptions(options) { }); } } - if(options.watch) { - var primaryOptions = !Array.isArray(options) ? options : options[0]; - var watchOptions = primaryOptions.watchOptions || primaryOptions.watch || {}; + if(firstOptions.watch) { + var watchOptions = firstOptions.watchOptions || firstOptions.watch || {}; if(watchOptions.stdin) { process.stdin.on("end", function() { process.exit(0); // eslint-disable-line
Fix watch when config is an array of objects
webpack_webpack
train
a637fa21014e513ab7666e199c11987a3a76914d
diff --git a/internal/service/s3/bucket_replication_configuration_test.go b/internal/service/s3/bucket_replication_configuration_test.go index <HASH>..<HASH> 100644 --- a/internal/service/s3/bucket_replication_configuration_test.go +++ b/internal/service/s3/bucket_replication_configuration_test.go @@ -1594,7 +1594,10 @@ resource "aws_s3_bucket_versioning" "source" { } resource "aws_s3_bucket_replication_configuration" "test" { - depends_on = [aws_s3_bucket_versioning.source] + depends_on = [ + aws_s3_bucket_versioning.source, + aws_s3_bucket_versioning.destination + ] bucket = aws_s3_bucket.source.id role = aws_iam_role.test.arn @@ -1671,7 +1674,10 @@ resource "aws_s3_bucket_versioning" "source" { } resource "aws_s3_bucket_replication_configuration" "test" { - depends_on = [aws_s3_bucket_versioning.source] + depends_on = [ + aws_s3_bucket_versioning.source, + aws_s3_bucket_versioning.destination + ] bucket = aws_s3_bucket.source.id role = aws_iam_role.test.arn
add dependency on destination acl as well
terraform-providers_terraform-provider-aws
train
8860a60ea5a6ddba06b7088bd3580ba753c2b012
diff --git a/src/Table/Table.spec.js b/src/Table/Table.spec.js index <HASH>..<HASH> 100644 --- a/src/Table/Table.spec.js +++ b/src/Table/Table.spec.js @@ -44,4 +44,9 @@ describe('<Table />', () => { const wrapper = shallow(<Table>{children}</Table>); assert.strictEqual(wrapper.childAt(0).equals(children), true); }); + + it('should define table in the child context', () => { + const wrapper = shallow(<Table />); + assert.deepStrictEqual(wrapper.instance().getChildContext().table, {}); + }); }); diff --git a/src/Table/TableBody.spec.js b/src/Table/TableBody.spec.js index <HASH>..<HASH> 100644 --- a/src/Table/TableBody.spec.js +++ b/src/Table/TableBody.spec.js @@ -35,4 +35,9 @@ describe('<TableBody />', () => { const wrapper = shallow(<TableBody>{children}</TableBody>); assert.strictEqual(wrapper.childAt(0).equals(children), true); }); + + it('should define table.body in the child context', () => { + const wrapper = shallow(<TableBody />); + assert.strictEqual(wrapper.instance().getChildContext().table.body, true); + }); }); diff --git a/src/Table/TableHead.spec.js b/src/Table/TableHead.spec.js index <HASH>..<HASH> 100644 --- a/src/Table/TableHead.spec.js +++ b/src/Table/TableHead.spec.js @@ -35,4 +35,9 @@ describe('<TableHead />', () => { const wrapper = shallow(<TableHead>{children}</TableHead>); assert.strictEqual(wrapper.childAt(0).equals(children), true); }); + + it('should define table.head in the child context', () => { + const wrapper = shallow(<TableHead />); + assert.strictEqual(wrapper.instance().getChildContext().table.head, true); + }); });
[Table] Increase test coverage. (#<I>)
mui-org_material-ui
train
2b9b28c7d050ee77c2273516c6581bf11fa63944
diff --git a/array_connection.go b/array_connection.go index <HASH>..<HASH> 100644 --- a/array_connection.go +++ b/array_connection.go @@ -4,6 +4,7 @@ import ( "encoding/base64" "errors" "fmt" + "reflect" "strconv" "strings" ) @@ -141,7 +142,7 @@ func CursorForObjectInConnection(data []interface{}, object interface{}) Connect offset := -1 for i, d := range data { // TODO: better object comparison - if d == object { + if reflect.DeepEqual(d, object) { offset = i break }
use reflect.DeepEqual for better object comparison
graphql-go_relay
train
1619f84bc86c4ed0ed8ce3caffec14070699033c
diff --git a/framework/core/src/Api/Actions/BaseAction.php b/framework/core/src/Api/Actions/BaseAction.php index <HASH>..<HASH> 100644 --- a/framework/core/src/Api/Actions/BaseAction.php +++ b/framework/core/src/Api/Actions/BaseAction.php @@ -13,8 +13,6 @@ use Response; abstract class BaseAction extends Action { - abstract protected function run(ApiParams $params); - public function __construct(Actor $actor, Dispatcher $bus) { $this->actor = $actor; @@ -40,6 +38,15 @@ abstract class BaseAction extends Action return $this->run($params); } + /** + * @param ApiParams $params + * @return mixed + */ + protected function run(ApiParams $params) + { + // Should be implemented by subclasses + } + public function hydrate($object, $params) { foreach ($params as $k => $v) {
Provide empty run() method. This allows me to override the handle() method in subclasses (where I need access to the request object) without having to overwrite run(), too. The class is still abstract.
flarum_core
train
4d66178177aeabd31f3ae01e7196316e8055838a
diff --git a/tests/filesystem.go b/tests/filesystem.go index <HASH>..<HASH> 100644 --- a/tests/filesystem.go +++ b/tests/filesystem.go @@ -93,6 +93,7 @@ func runIgnition(t *testing.T, stage, root, cwd string, appendEnv []string, expe cmd.Dir = cwd cmd.Env = append(os.Environ(), appendEnv...) out, err := cmd.CombinedOutput() + t.Logf("PID: %d", cmd.Process.Pid) if err != nil && !expectFail { t.Fatal(args, err, string(out)) }
tests: print pid of ignition when running bb tests Print Ignition's PID when running blackbox tests to make retrieving logs from journald from a particular test easier.
coreos_ignition
train
e187f4af32e423fe211f38bb366759c1966105f0
diff --git a/src/core/utils/index.js b/src/core/utils/index.js index <HASH>..<HASH> 100644 --- a/src/core/utils/index.js +++ b/src/core/utils/index.js @@ -331,10 +331,25 @@ export const assign = (target: Object, ...others: any[]) => { return to; }; +let id = 0; +let idTemplate = '{id}'; + /** * Generates a unique id. */ -export const uniqId = (): string => `_${Math.random().toString(36).substr(2, 9)}`; +export const uniqId = (): string => { + // handle too many uses of uniqId, although unlikely. + if (id >= 9999) { + id = 0; + // shift the template. + idTemplate.replace('{id}', '_{id}'); + } + + id++; + const newId = idTemplate.replace('{id}', String(id)); + + return newId; +}; /** * finds the first element that satisfies the predicate callback, polyfills array.find
make uniqId more deterministic closes #<I>
baianat_vee-validate
train
c07c2205ec8b3ee9395d66c289e3f3e14a80c409
diff --git a/cherrypy/_cpconfig.py b/cherrypy/_cpconfig.py index <HASH>..<HASH> 100644 --- a/cherrypy/_cpconfig.py +++ b/cherrypy/_cpconfig.py @@ -248,7 +248,29 @@ Config.namespaces["server"] = _server_namespace_handler def _engine_namespace_handler(k, v): """Backward compatibility handler for the "engine" namespace.""" engine = cherrypy.engine - if k == 'SIGHUP': + + deprecated = {'autoreload_on': 'autoreload.on', 'autoreload_frequency': 'autoreload.frequency', + 'autoreload_match': 'autoreload.match', 'reload_files': 'autoreload.files', + 'deadlock_poll_freq': 'timeout_monitor.frequency'} + + if k in deprecated: + engine.log('WARNING: Use of engine.%s is deprecated and will be removed in ' + 'a future version. Use engine.%s instead.' % (k, deprecated[k])) + + if k == 'autoreload_on': + if v: + engine.autoreload.subscribe() + else: + engine.autoreload.unsubscribe() + elif k == 'autoreload_frequency': + engine.autoreload.frequency = v + elif k == 'autoreload_match': + engine.autoreload.match = v + elif k == 'reload_files': + engine.autoreload.files = set(v) + elif k == 'deadlock_poll_freq': + engine.timeout_monitor.frequency = v + elif k == 'SIGHUP': engine.listeners['SIGHUP'] = set([v]) elif k == 'SIGTERM': engine.listeners['SIGTERM'] = set([v])
Added aliases back in, but with deprecation warning.
cherrypy_cheroot
train
260b448dc7ff5302395c3587b9066492f89c610f
diff --git a/lib/function/algebra/derivative.js b/lib/function/algebra/derivative.js index <HASH>..<HASH> 100644 --- a/lib/function/algebra/derivative.js +++ b/lib/function/algebra/derivative.js @@ -5,6 +5,7 @@ function factory (type, config, load, typed) { var simplify = load(require('./simplify')); var equal = load(require('../relational/equal')); var isZero = load(require('../utils/isZero')); + var getType = load(require('../utils/typeof')); var numeric = load(require('../../type/numeric')); var ConstantNode = load(require('../../expression/node/ConstantNode')); var FunctionNode = load(require('../../expression/node/FunctionNode')); @@ -106,14 +107,14 @@ function factory (type, config, load, typed) { // NOTE: the optional "order" parameter here is currently unused var _derivTex = typed('_derivTex', { 'Node, SymbolNode': function (expr, x) { - if(type.isConstantNode(expr) && expr.valueType == 'string') { + if(type.isConstantNode(expr) && getType(expr.value) == 'string') { return _derivTex(parse(expr.value).toString(), x.toString(), 1); } else { return _derivTex(expr.toString(), x.toString(), 1); } }, 'Node, ConstantNode': function (expr, x) { - if(x.valueType == 'string') { + if(getType(x.value) == 'string') { return _derivTex(expr, parse(x.value)); } else { throw new Error("The second parameter to 'derivative' is a non-string constant");
Use getType insead of using to removed valueType in derivative
josdejong_mathjs
train
7393271f0d7b404b330fef76da13b41b1a813e7b
diff --git a/src/callback/Binding.js b/src/callback/Binding.js index <HASH>..<HASH> 100644 --- a/src/callback/Binding.js +++ b/src/callback/Binding.js @@ -71,7 +71,7 @@ define([ var parentModel = null; - this.applyBinding = function(scope, name, model) { + function applyBinding(scope, name, model) { parentModel = model; @@ -79,15 +79,15 @@ define([ bindings[i].applyBinding(scope, name, model); } - }; + } - this.removeBinding = function() { + function removeBinding() { for (var i = 0; i < bindings.length; i++) { bindings[i].removeBinding(); } - }; + } var test = {}; @@ -99,7 +99,12 @@ define([ }; }); - this.test = test; + return { + + applyBinding: applyBinding, + removeBinding: removeBinding, + test: test + }; } return Binding; diff --git a/src/root/BindingRoot.js b/src/root/BindingRoot.js index <HASH>..<HASH> 100644 --- a/src/root/BindingRoot.js +++ b/src/root/BindingRoot.js @@ -50,9 +50,14 @@ define([ var domWatcher = new DOMWatcher(document.body); - this.disconnect = function() { + function disconnect() { domWatcher.disconnect(); + } + + return { + + disconnect: disconnect }; }
Remove uses of 'this' from public classes.
MartinRixham_Datum
train
fb16302568e4de46392695001271a4c4c348a6c7
diff --git a/draw2d/src/pkg/draw2d/arc.go b/draw2d/src/pkg/draw2d/arc.go index <HASH>..<HASH> 100644 --- a/draw2d/src/pkg/draw2d/arc.go +++ b/draw2d/src/pkg/draw2d/arc.go @@ -2,6 +2,10 @@ // created: 21/11/2010 by Laurent Le Goff package draw2d +import ( + "freetype-go.googlecode.com/hg/freetype/raster" +) + func arc(t VertexConverter, x, y, rx, ry, start, angle, scale float) (lastX, lastY float) { end := start + angle clockWise := true @@ -30,3 +34,34 @@ func arc(t VertexConverter, x, y, rx, ry, start, angle, scale float) (lastX, las } return curX, curY } + + +func arcAdder(adder raster.Adder, x, y, rx, ry, start, angle, scale float) (raster.Point) { + end := start + angle + clockWise := true + if angle < 0 { + clockWise = false + } + ra := (fabs(rx) + fabs(ry)) / 2 + da := acos(ra/(ra+0.125/scale)) * 2 + //normalize + if !clockWise { + da = -da + } + angle = start + da + var curX, curY float + for { + if (angle < end-da/4) != clockWise { + curX = x + cos(end)*rx + curY = y + sin(end)*ry + return floatToPoint(curX, curY) + } + curX = x + cos(angle)*rx + curY = y + sin(angle)*ry + + angle += da + adder.Add1(floatToPoint(curX, curY)) + } + return floatToPoint(curX, curY) +} + diff --git a/draw2d/src/pkg/draw2d/path_adder.go b/draw2d/src/pkg/draw2d/path_adder.go index <HASH>..<HASH> 100644 --- a/draw2d/src/pkg/draw2d/path_adder.go +++ b/draw2d/src/pkg/draw2d/path_adder.go @@ -34,3 +34,55 @@ func (vertexAdder *VertexAdder) Vertex(x, y float) { } vertexAdder.command = VertexNoCommand } + + +type PathAdder struct { + adder raster.Adder + lastPoint raster.Point + ApproximationScale float +} + +func NewPathAdder(adder raster.Adder) (* PathAdder) { + return &PathAdder{adder, raster.Point{0,0}, 1} +} + + +func (pathAdder *PathAdder) Convert(paths ...*PathStorage) { + for _, path := range paths { + j := 0 + for _, cmd := range path.commands { + j = j + pathAdder.ConvertCommand(cmd, path.vertices[j:]...) + } + } +} + + +func (pathAdder *PathAdder) ConvertCommand(cmd PathCmd, vertices ...float) int { + switch cmd { + case MoveTo: + pathAdder.lastPoint = floatToPoint(vertices[0], vertices[1]) + pathAdder.adder.Start(pathAdder.lastPoint) + return 2 + case LineTo: + pathAdder.lastPoint = floatToPoint(vertices[0], vertices[1]) + pathAdder.adder.Add1(pathAdder.lastPoint) + return 2 + case QuadCurveTo: + pathAdder.lastPoint = floatToPoint(vertices[2], vertices[3]) + pathAdder.adder.Add2(floatToPoint(vertices[0], vertices[1]), pathAdder.lastPoint) + return 4 + case CubicCurveTo: + pathAdder.lastPoint = floatToPoint(vertices[4], vertices[5]) + pathAdder.adder.Add3(floatToPoint(vertices[0], vertices[1]), floatToPoint(vertices[2], vertices[3]), pathAdder.lastPoint) + return 6 + case ArcTo: + pathAdder.lastPoint = arcAdder(pathAdder.adder,vertices[0], vertices[1], vertices[2], vertices[3], vertices[4], vertices[5], pathAdder.ApproximationScale) + pathAdder.adder.Add1(pathAdder.lastPoint) + return 6 + case Close: + pathAdder.adder.Add1(pathAdder.lastPoint) + return 0 + } + return 0 +} +
add path adder for comparing with freetype decomposition algorithm
llgcode_draw2d
train
f6f60b55c56bdeddf2a08354ef1f307e619fcbf8
diff --git a/core/ViewDataTable/Request.php b/core/ViewDataTable/Request.php index <HASH>..<HASH> 100644 --- a/core/ViewDataTable/Request.php +++ b/core/ViewDataTable/Request.php @@ -101,11 +101,11 @@ class Request } if ($this->requestConfig->disable_generic_filters) { - $requestArray['disable_generic_filters'] = '0'; + $requestArray['disable_generic_filters'] = '1'; } if ($this->requestConfig->disable_queued_filters) { - $requestArray['disable_queued_filters'] = 0; + $requestArray['disable_queued_filters'] = 1; } return $requestArray;
Disabling filter did not work as wrong values were set
matomo-org_matomo
train
ece4adfa285dc623b5a5914e8d697e6178a1e4be
diff --git a/cflib/crazyflie/param.py b/cflib/crazyflie/param.py index <HASH>..<HASH> 100644 --- a/cflib/crazyflie/param.py +++ b/cflib/crazyflie/param.py @@ -368,13 +368,13 @@ class Param(): argument on success and with `False` as an argument on failure. @param complete_name The 'group.name' name of the parameter to store - @param callback Optional callback should take boolean status as arg + @param callback Optional callback should take `complete_name` and boolean status as arguments """ element = self.toc.get_element_by_complete_name(complete_name) def new_packet_cb(pk): if pk.channel == MISC_CHANNEL and pk.data[0] == MISC_PERSISTENT_CLEAR: - callback(pk.data[3] == 0) + callback(complete_name, pk.data[3] == 0) self.cf.remove_port_callback(CRTPPort.PARAM, new_packet_cb) if callback is not None: @@ -392,13 +392,13 @@ class Param(): argument on success, and with `False` as an argument on failure. @param complete_name The 'group.name' name of the parameter to store - @param callback Optional callback should take boolean status as arg + @param callback Optional callback should take `complete_name` and boolean status as arguments """ element = self.toc.get_element_by_complete_name(complete_name) def new_packet_cb(pk): if pk.channel == MISC_CHANNEL and pk.data[0] == MISC_PERSISTENT_STORE: - callback(pk.data[3] == 0) + callback(complete_name, pk.data[3] == 0) self.cf.remove_port_callback(CRTPPort.PARAM, new_packet_cb) if callback is not None: @@ -424,14 +424,14 @@ class Param(): | `stored_value` | Value stored in eeprom, None if `not is_stored` | @param complete_name The 'group.name' name of the parameter to store - @param callback Callback, takes PersistentParamState namedtuple as arg + @param callback Callback, takes `complete_name` and PersistentParamState namedtuple as arg """ element = self.toc.get_element_by_complete_name(complete_name) def new_packet_cb(pk): if pk.channel == MISC_CHANNEL and pk.data[0] == MISC_PERSISTENT_GET_STATE: if pk.data[3] == errno.ENOENT: - callback(None) + callback(complete_name, None) self.cf.remove_port_callback(CRTPPort.PARAM, new_packet_cb) return @@ -441,11 +441,13 @@ class Param(): else: default_value, stored_value = struct.unpack(f'<{element.pytype}*2') - callback(PersistentParamState( - is_stored, - default_value, - None if not is_stored else stored_value - )) + callback(complete_name, + PersistentParamState( + is_stored, + default_value, + None if not is_stored else stored_value + ) + ) self.cf.remove_port_callback(CRTPPort.PARAM, new_packet_cb) self.cf.add_port_callback(CRTPPort.PARAM, new_packet_cb)
param.py: Add complete name to callbacks So that the same callback can multiplex for a lot of parameters.
bitcraze_crazyflie-lib-python
train
63d125925003f646de983ba4fb5dacbe81c5d7e3
diff --git a/lib/action_kit_rest/api.rb b/lib/action_kit_rest/api.rb index <HASH>..<HASH> 100644 --- a/lib/action_kit_rest/api.rb +++ b/lib/action_kit_rest/api.rb @@ -28,7 +28,7 @@ module ActionKitRest def default_options { user_agent: 'ActionKitRestGem', - prefix: '/rest/v1/', + prefix: '/rest/v1', content_type: 'application/json; charset=utf-8' } end diff --git a/spec/spec_helper.rb b/spec/spec_helper.rb index <HASH>..<HASH> 100644 --- a/spec/spec_helper.rb +++ b/spec/spec_helper.rb @@ -37,8 +37,7 @@ def stub_put(path) end def stub_action_kit_request(method, path) - prefix = ActionKitRest.new.connection.configuration.prefix.to_s - stub_request(method, 'https://test.com' + prefix + path) + stub_request(method, 'https://test.com/rest/v1/' + path) end def fixture_path @@ -47,4 +46,4 @@ end def fixture(file) File.new(File.join(fixture_path, '/', file)) -end \ No newline at end of file +end
fix repeated path divider in url construction.
controlshift_action_kit_rest
train
16d731dd2417d6586d79085b8316e7b06705b10f
diff --git a/src/components/menus/Menu.js b/src/components/menus/Menu.js index <HASH>..<HASH> 100644 --- a/src/components/menus/Menu.js +++ b/src/components/menus/Menu.js @@ -154,6 +154,7 @@ export default { methods: { activate () { this.initWindow() + this.getTiles() this.updateDimensions() this.$nextTick(this.startTransition) }, @@ -181,7 +182,7 @@ export default { on: { keydown: e => { if (e.keyCode === 27) this.isActive = false - if ([40, 38].includes(e.keyCode)) this.changeListIndex(e) + else this.changeListIndex(e) } } } diff --git a/src/components/menus/mixins/keyable.js b/src/components/menus/mixins/keyable.js index <HASH>..<HASH> 100644 --- a/src/components/menus/mixins/keyable.js +++ b/src/components/menus/mixins/keyable.js @@ -1,26 +1,37 @@ export default { data: () => ({ - listIndex: 0, - isUsingKeys: false + listIndex: -1, + isUsingKeys: false, + tiles: [] }), watch: { - listIndex () { - this.isUsingKeys = true + isActive (val) { + if (!val) this.listIndex = -1 + }, + listIndex (next, prev) { + // For infinite scroll, re-evaluate children + next === this.tiles.length - 1 && this.getTiles() + + if (next !== -1) { + this.tiles[next].classList.add('list__tile--highlighted') + this.$refs.content.scrollTop = next * 48 + } + + prev !== -1 && this.tiles[prev].classList.remove('list__tile--highlighted') } }, methods: { changeListIndex (e) { - if (e.keyCode === 40 && this.listIndex > 0) { - e.preventDefault() - this.listIndex-- - } - if (e.keyCode === 38 && this.listIndex < this.tileLength - 1) { - e.preventDefault() - this.listIndex++ - } - console.log(this.listIndex) + e.preventDefault() + + if (e.keyCode === 40 && this.listIndex < this.tiles.length - 1) this.listIndex++ + if (e.keyCode === 38 && this.listIndex > 0) this.listIndex-- + if (e.keyCode === 13 && this.listIndex !== -1) this.tiles[this.listIndex].click() + }, + getTiles () { + this.tiles = this.$refs.content.querySelectorAll('.list__tile') } } } diff --git a/src/components/menus/mixins/position.js b/src/components/menus/mixins/position.js index <HASH>..<HASH> 100644 --- a/src/components/menus/mixins/position.js +++ b/src/components/menus/mixins/position.js @@ -22,10 +22,7 @@ export default { calcTopAuto () { if (!this.$refs.content) return this.calcTop(true) - const tiles = this.$refs.content.querySelectorAll('.list__tile') - const selectedIndex = Array.from(tiles).findIndex(n => n.classList.contains('list__tile--active')) - - this.tileLength = tiles.length + const selectedIndex = Array.from(this.tiles).findIndex(n => n.classList.contains('list__tile--active')) if (selectedIndex === -1) { this.selectedIndex = null @@ -37,7 +34,7 @@ export default { let actingIndex = selectedIndex let offsetPadding = -16 - this.stopIndex = tiles.length - 4 + this.stopIndex = this.tiles.length - 4 if (selectedIndex > this.startIndex && selectedIndex < this.stopIndex) { actingIndex = 2 offsetPadding = 24 diff --git a/src/components/selects/Select.js b/src/components/selects/Select.js index <HASH>..<HASH> 100644 --- a/src/components/selects/Select.js +++ b/src/components/selects/Select.js @@ -185,7 +185,7 @@ export default { on: { keydown: e => { if (e.keyCode === 27) this.$refs.menu.isActive = false - if ([40, 38].includes(e.keyCode)) this.$refs.menu.changeListIndex(e) + else this.$refs.menu.changeListIndex(e) } } })
added keyboard functionality to selects/menu
vuetifyjs_vuetify
train
5e8b18db4358ede703529657f378485f91e7738f
diff --git a/db/src/main/java/org/syphr/mythtv/db/schema/impl/_0_24/Recorded1264.java b/db/src/main/java/org/syphr/mythtv/db/schema/impl/_0_24/Recorded1264.java index <HASH>..<HASH> 100644 --- a/db/src/main/java/org/syphr/mythtv/db/schema/impl/_0_24/Recorded1264.java +++ b/db/src/main/java/org/syphr/mythtv/db/schema/impl/_0_24/Recorded1264.java @@ -160,7 +160,7 @@ public class Recorded1264 implements Recorded @Override public void setId(RecordedId id) { - if (id != null && !(id instanceof Recorded1264)) + if (id != null && !(id instanceof RecordedId1264)) { throw new IllegalArgumentException("Invalid ID type: " + id.getClass().getName()); }
fixed a typo that would have caused an incorrect exception on a valid ID object
syphr42_libmythtv-java
train
514d839c9eb2010b1c7f9dc2b3af73737a1ab5ad
diff --git a/lib/collections/VoiceConnectionCollection.js b/lib/collections/VoiceConnectionCollection.js index <HASH>..<HASH> 100644 --- a/lib/collections/VoiceConnectionCollection.js +++ b/lib/collections/VoiceConnectionCollection.js @@ -134,9 +134,10 @@ class VoiceConnectionCollection extends Array { } }); - discordie.Dispatcher.on(Events.ANY_GATEWAY_READY, - e => this._gateways.add(e.socket) - ); + discordie.Dispatcher.on(Events.GATEWAY_DISPATCH, e => { + if (e.type !== "READY" && e.type !== "RESUMED") return; + this._gateways.add(e.socket) + }); discordie.Dispatcher.on(Events.GATEWAY_DISCONNECT, e => { Array.from(this._pendingConnections.keys()).forEach(guildId => { var pending = this._pendingConnections.get(guildId);
Fix gateway tracking for voice connections on RESUME
qeled_discordie
train
3e254f400e3346b15d5a2636bad9d0b5ddbb45fe
diff --git a/pkg/service/service_test.go b/pkg/service/service_test.go index <HASH>..<HASH> 100644 --- a/pkg/service/service_test.go +++ b/pkg/service/service_test.go @@ -170,11 +170,11 @@ func (m *ManagerTestSuite) TestSyncWithK8sFinished(c *C) { c.Assert(err, IsNil) c.Assert(len(m.svc.svcByID), Equals, 2) - // Imitate a situation where svc2 was deleted while we were down. + // Imitate a situation where svc1 was deleted while we were down. // In real life, the following upsert is called by k8s_watcher during // the sync period of the cilium-agent's k8s service cache which happens // during the initialization of cilium-agent. - _, id1, err := m.svc.UpsertService(frontend2, backends2, lb.SVCTypeClusterIP) + _, id2, err := m.svc.UpsertService(frontend2, backends2, lb.SVCTypeClusterIP) c.Assert(err, IsNil) // cilium-agent finished the initialization, and thus SyncWithK8sFinished @@ -182,8 +182,8 @@ func (m *ManagerTestSuite) TestSyncWithK8sFinished(c *C) { err = m.svc.SyncWithK8sFinished() c.Assert(err, IsNil) - // svc2 should be removed from cilium + // svc1 should be removed from cilium c.Assert(len(m.svc.svcByID), Equals, 1) - _, found := m.svc.svcByID[id1] + _, found := m.svc.svcByID[id2] c.Assert(found, Equals, true) }
service: Fix description of TestSyncWithK8sFinished The description of TestSyncWithK8sFinished claims to remove svc2, while the code actually removes svc1 by updating svc2.
cilium_cilium
train
a6cc028413fd2da0085e08d28fb317837f7d1770
diff --git a/src/Transformers/Adminarea/TagTransformer.php b/src/Transformers/Adminarea/TagTransformer.php index <HASH>..<HASH> 100644 --- a/src/Transformers/Adminarea/TagTransformer.php +++ b/src/Transformers/Adminarea/TagTransformer.php @@ -19,6 +19,7 @@ class TagTransformer extends TransformerAbstract { return $this->escape([ 'id' => (string) $tag->getRouteKey(), + 'DT_RowId' => 'row_'.$tag->getRouteKey(), 'name' => (string) $tag->name, 'group' => (string) $tag->group, 'created_at' => (string) $tag->created_at,
Add DT_RowId field to datatables
rinvex_cortex-tags
train
f41294a2b831748cd354224b89fde8b99510b879
diff --git a/dataviews/interface/pandas.py b/dataviews/interface/pandas.py index <HASH>..<HASH> 100644 --- a/dataviews/interface/pandas.py +++ b/dataviews/interface/pandas.py @@ -18,14 +18,39 @@ except: import param -from .. import Dimension +from .. import Dimension, NdMapping from ..dataviews import HeatMap, DataStack, Table, TableStack from ..options import options, PlotOpts -from ..views import View, Overlay, Stack, Annotation, Grid +from ..views import View, Overlay, Stack, Annotation, Grid, GridLayout +class DFrameLayer(View): + """ + Abstract class implements common methods for all Pandas dframe + based View types. + """ + + def __mul__(self, other): + if isinstance(other, DFrameStack): + items = [(k, self * v) for (k, v) in other.items()] + return other.clone(items=items) + elif isinstance(self, DFrameOverlay): + if isinstance(other, DFrameOverlay): + overlays = self.data + other.data + else: + overlays = self.data + [other] + elif isinstance(other, DFrameOverlay): + overlays = [self] + other.data + elif isinstance(other, DataFrameView): + overlays = [self, other] + else: + raise TypeError('Can only create an overlay of DFrameLayers.') + + return DFrameOverlay(overlays) -class DataFrameView(View): + + +class DataFrameView(DFrameLayer): """ DataFrameView provides a convenient compatibility wrapper around Pandas DataFrames. It provides several core functions: @@ -153,24 +178,6 @@ class DataFrameView(View): """ return self._split_dimensions(dimensions, DFrameStack) - def __mul__(self, other): - if isinstance(other, DFrameStack): - items = [(k, self * v) for (k, v) in other.items()] - return other.clone(items=items) - elif isinstance(self, DFrameOverlay): - if isinstance(other, DFrameOverlay): - overlays = self.data + other.data - else: - overlays = self.data + [other] - elif isinstance(other, DFrameOverlay): - overlays = [self] + other.data - elif isinstance(other, DataFrameView): - overlays = [self, other] - else: - raise TypeError('Can only create an overlay of DFViews.') - - return DFrameOverlay(overlays) - class DFrame(DataFrameView): @@ -301,7 +308,7 @@ class DFrame(DataFrameView): -class DFrameOverlay(Overlay): +class DFrameOverlay(Overlay, DFrameLayer): """ DFrameOverlay provides a compatibility layer to overlay Pandas Views. Required to allow isinstance checks to work.
Factored Pandas View mul method out to base class
pyviz_holoviews
train
fa3d736d66505823cbc41a66d167bdca272ee36e
diff --git a/src/Model/AbstractModel.php b/src/Model/AbstractModel.php index <HASH>..<HASH> 100644 --- a/src/Model/AbstractModel.php +++ b/src/Model/AbstractModel.php @@ -206,7 +206,7 @@ abstract class AbstractModel extends \RedBean_SimpleModel $fields = $this->bean->export(); foreach ($fields as &$field) { - is_string($field) && $field = strip_tags($field); + is_string($field) && $field = trim(strip_tags($field)); } $errors = App::getInstance()['validator']->validateValue(
now trimming values before validation to ensure whitespaces don't count as content
neemzy_patchwork-core
train
5c322abdea045b3e17f49e63bf11f5778ad5529b
diff --git a/setup.py b/setup.py index <HASH>..<HASH> 100644 --- a/setup.py +++ b/setup.py @@ -38,7 +38,6 @@ setup_params = dict( 'six', 'requests', "popquotes>=1.3", - "excuses>=1.1.2", "pyyaml", "feedparser", "pytz", diff --git a/tests/unit/test_commands.py b/tests/unit/test_commands.py index <HASH>..<HASH> 100644 --- a/tests/unit/test_commands.py +++ b/tests/unit/test_commands.py @@ -568,11 +568,6 @@ class TestCommands(object): assert res == ("Quiet bitching is useless, foo'. Do something about " "it.") - def test_excuse(self): - import excuses - gen = excuses.RandomExcuseGenerator.create_local() - gen.pmxbot_excuse(c, e, '#test', 'testrunner', '') - def test_popquotes(self): popquotes.pmxbot.install_commands() res = popquotes.pmxbot.bender(c, e, '#test', 'testrunner', '')
Excuses are no longer included by default (just require excuses in deployment).
yougov_pmxbot
train
1f08b992328dcbfef7dfe5a78c2784072aa8e7e7
diff --git a/src/Auth/OnlineFederation.php b/src/Auth/OnlineFederation.php index <HASH>..<HASH> 100644 --- a/src/Auth/OnlineFederation.php +++ b/src/Auth/OnlineFederation.php @@ -19,6 +19,7 @@ namespace AlexaCRM\CRMToolkit\Auth; use AlexaCRM\CRMToolkit\Client; use AlexaCRM\CRMToolkit\SecurityToken; +use AlexaCRM\CRMToolkit\Settings; use DOMDocument; /** @@ -27,6 +28,23 @@ use DOMDocument; class OnlineFederation extends Authentication { /** + * Create a new instance of the AlexaCRM\CRMToolkit\AlexaSDK + * + * @param Settings $settings + * @param Client $client + * + * @throws \Exception Thrown if TLS 1.2 is not supported by the environment. + */ + public function __construct( Settings $settings, Client $client ) { + parent::__construct( $settings, $client ); + + $curlVersion = curl_version(); + if ( version_compare( $curlVersion['version'], '7.34', '<' ) || !defined( 'CURL_SSLVERSION_TLSv1_2' ) ) { + throw new \Exception( 'curl version < 7.34 and TLS 1.2 is not supported. Please upgrade curl and/or the TLS library of your choice' ); + } + } + + /** * Retrieves the security token from the STS. * * @param string $service @@ -230,6 +248,14 @@ XML; return $loginSoapRequest->saveXML( $loginEnvelope ); } + /** + * Retrieves the correct STS endpoint URL. Useful for federated AAD configurations. + * + * @param $login string + * + * @return null|string + * @throws \Exception + */ protected function getSTSUrl( $login ) { $content = [ 'login' => $this->settings->username, 'xml' => 1 ]; @@ -247,6 +273,8 @@ XML; curl_setopt( $cURLHandle, CURLOPT_SSL_VERIFYHOST, 0 ); } + curl_setopt( $cURLHandle, CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1_2 ); + if( $this->settings->proxy ) { curl_setopt( $cURLHandle, CURLOPT_PROXY, $this->settings->proxy ); } diff --git a/src/Client.php b/src/Client.php index <HASH>..<HASH> 100644 --- a/src/Client.php +++ b/src/Client.php @@ -1059,6 +1059,11 @@ class Client extends AbstractClient { curl_setopt( $cURLHandle, CURLOPT_SSL_VERIFYHOST, 0 ); } + // enforce TLS1.2 for Online deployments + if ( $this->settings->authMode === 'OnlineFederation' ) { + curl_setopt( $cURLHandle, CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1_2 ); + } + if( $this->settings->proxy ) { curl_setopt( $cURLHandle, CURLOPT_PROXY, $this->settings->proxy ); } @@ -1959,6 +1964,11 @@ class Client extends AbstractClient { curl_setopt( $wsdlCurl, CURLOPT_SSL_VERIFYHOST, 0 ); } + // enforce TLS1.2 for Online deployments + if ( $this->settings->authMode === 'OnlineFederation' ) { + curl_setopt( $wsdlCurl, CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1_2 ); + } + if( $this->settings->proxy ) { curl_setopt( $wsdlCurl, CURLOPT_PROXY, $this->settings->proxy ); }
Online deployments must connect over TLS<I>
AlexaCRM_php-crm-toolkit
train
82daee576a05d5ae41364bc7e528816bbf4be808
diff --git a/src/structures/GuildEmoji.js b/src/structures/GuildEmoji.js index <HASH>..<HASH> 100644 --- a/src/structures/GuildEmoji.js +++ b/src/structures/GuildEmoji.js @@ -152,7 +152,7 @@ class GuildEmoji extends BaseGuildEmoji { /** * Whether this emoji is the same as another one. * @param {GuildEmoji|APIEmoji} other The emoji to compare it to - * @returns {boolean} Whether the emoji is equal to the given emoji or not + * @returns {boolean} */ equals(other) { if (other instanceof GuildEmoji) { diff --git a/src/structures/Sticker.js b/src/structures/Sticker.js index <HASH>..<HASH> 100644 --- a/src/structures/Sticker.js +++ b/src/structures/Sticker.js @@ -204,7 +204,7 @@ class Sticker extends Base { /** * Whether this sticker is the same as another one. * @param {Sticker|APISticker} other The sticker to compare it to - * @returns {boolean} Whether the sticker is equal to the given sticker or not + * @returns {boolean} */ equals(other) { if (other instanceof Sticker) { diff --git a/src/structures/TextChannel.js b/src/structures/TextChannel.js index <HASH>..<HASH> 100644 --- a/src/structures/TextChannel.js +++ b/src/structures/TextChannel.js @@ -162,7 +162,7 @@ class TextChannel extends GuildChannel { * Creates a webhook for the channel. * @param {string} name The name of the webhook * @param {ChannelWebhookCreateOptions} [options] Options for creating the webhook - * @returns {Promise<Webhook>} webhook The created webhook + * @returns {Promise<Webhook>} Returns the created Webhook * @example * // Create a webhook for the current channel * channel.createWebhook('Snek', { diff --git a/src/structures/interfaces/TextBasedChannel.js b/src/structures/interfaces/TextBasedChannel.js index <HASH>..<HASH> 100644 --- a/src/structures/interfaces/TextBasedChannel.js +++ b/src/structures/interfaces/TextBasedChannel.js @@ -284,7 +284,7 @@ class TextBasedChannel { * @param {Collection<Snowflake, Message>|MessageResolvable[]|number} messages * Messages or number of messages to delete * @param {boolean} [filterOld=false] Filter messages to remove those which are older than two weeks automatically - * @returns {Promise<Collection<Snowflake, Message>>} Deleted messages + * @returns {Promise<Collection<Snowflake, Message>>} Returns the deleted messages * @example * // Bulk delete messages * channel.bulkDelete(5)
docs: Refactor a few `@returns` descriptions (#<I>)
discordjs_discord.js
train
d2a0def71daf365fdf9f7e53dcbc2350ee8fb0cd
diff --git a/src/main/java/com/github/jleyba/dossier/HtmlDocWriter.java b/src/main/java/com/github/jleyba/dossier/HtmlDocWriter.java index <HASH>..<HASH> 100644 --- a/src/main/java/com/github/jleyba/dossier/HtmlDocWriter.java +++ b/src/main/java/com/github/jleyba/dossier/HtmlDocWriter.java @@ -962,7 +962,8 @@ class HtmlDocWriter implements DocWriter { parameter = jsdoc.getParameters().get(i); } - Dossier.Function.Detail.Builder detail = Dossier.Function.Detail.newBuilder(); + Dossier.Function.Detail.Builder detail = Dossier.Function.Detail.newBuilder() + .setName("arg" + i); // If the compiler hasn't determined a type yet, try to map back to the jsdoc. Node parameterNode = parameterNodes.get(i);
Generate stub argument names if we can't find them in the source node or jsdoc.
jleyba_js-dossier
train
e1d68fe4d7aabd6ae7aed0933873c4ec93544284
diff --git a/src/Collection/FirstHelper.php b/src/Collection/FirstHelper.php index <HASH>..<HASH> 100644 --- a/src/Collection/FirstHelper.php +++ b/src/Collection/FirstHelper.php @@ -43,7 +43,11 @@ class FirstHelper implements HelperInterface '"first" helper expects exactly one argument.' ); } + $collection = $context->get($parsed_args[0]); + if (!is_array($collection) && !($collection instanceof \Traversable)) { + throw new \InvalidArgumentException('Wrong type of the argument in the "first" helper.'); + } return reset($collection); } diff --git a/tests/Collection/FirstHelperTest.php b/tests/Collection/FirstHelperTest.php index <HASH>..<HASH> 100644 --- a/tests/Collection/FirstHelperTest.php +++ b/tests/Collection/FirstHelperTest.php @@ -63,7 +63,7 @@ class FirstHelperTest extends \PHPUnit_Framework_TestCase * Tests that exception is thrown if wrong number of arguments is used. * * @expectedException InvalidArgumentException - * @dataProvider wrongArgumentsProvider + * @dataProvider wrongArgumentsCountProvider */ public function testArgumentsCount($template) { @@ -76,7 +76,7 @@ class FirstHelperTest extends \PHPUnit_Framework_TestCase /** * A data provider for testArgumentsCount method. */ - public function wrongArgumentsProvider() + public function wrongArgumentsCountProvider() { return array( // Not enough arguments @@ -85,4 +85,30 @@ class FirstHelperTest extends \PHPUnit_Framework_TestCase array('{{first "Arg" "ANOTHER ARG"}}'), ); } + + /** + * Tests invalid arguments type. + * + * @expectedException InvalidArgumentException + * @dataProvider invalidArgumentsProvider + */ + public function testInvalidArguments($collection) + { + $helpers = new \Handlebars\Helpers(array('first' => new FirstHelper())); + $engine = new \Handlebars\Handlebars(array('helpers' => $helpers)); + + $engine->render('{{first collection}}', array('collection' => $collection)); + } + + /** + * A data provider for testInvalidArguments method. + */ + public function invalidArgumentsProvider() + { + return array( + array('a string'), + array(42), + array(new \stdClass()), + ); + } }
Add type check to "first" helper
JustBlackBird_handlebars.php-helpers
train
1bc367f54be07fed0fc0ef39d718dc040b7927d4
diff --git a/albumentations/augmentations/transforms.py b/albumentations/augmentations/transforms.py index <HASH>..<HASH> 100644 --- a/albumentations/augmentations/transforms.py +++ b/albumentations/augmentations/transforms.py @@ -1881,19 +1881,32 @@ class GaussNoise(ImageOnlyTransform): Args: var_limit ((float, float) or float): variance range for noise. If var_limit is a single float, the range - will be (-var_limit, var_limit). Default: (10., 50.). + will be (0, var_limit). Default: (10.0, 50.0). + mean (float): mean of the noise. Default: 0 p (float): probability of applying the transform. Default: 0.5. Targets: image Image types: - uint8 + uint8, float32 """ - def __init__(self, var_limit=(10., 50.), always_apply=False, p=0.5): + def __init__(self, var_limit=(10.0, 50.0), mean=None, always_apply=False, p=0.5): super(GaussNoise, self).__init__(always_apply, p) - self.var_limit = to_tuple(var_limit) + if isinstance(var_limit, tuple): + if var_limit[0] < 0: + raise ValueError("Lower var_limit should be non negative.") + if var_limit[1] < 0: + raise ValueError("Upper var_limit should be non negative.") + self.var_limit = var_limit + elif isinstance(var_limit, (int, float)): + if var_limit < 0: + raise ValueError(" var_limit should be non negative.") + + self.var_limit = (0, var_limit) + + self.mean = mean def apply(self, img, gauss=None, **params): return F.gauss_noise(img, gauss=gauss) @@ -1901,10 +1914,14 @@ class GaussNoise(ImageOnlyTransform): def get_params_dependent_on_targets(self, params): image = params['image'] var = random.uniform(self.var_limit[0], self.var_limit[1]) - mean = var sigma = var ** 0.5 random_state = np.random.RandomState(random.randint(0, 2 ** 32 - 1)) - gauss = random_state.normal(mean, sigma, image.shape) + + if self.mean is None: + DeprecationWarning('In the version 0.4.0 default behavior of GaussNoise mean will be changed to 0.') + self.mean = var + + gauss = random_state.normal(self.mean, sigma, image.shape) return { 'gauss': gauss }
Bugfix in GaussNoise (#<I>) * Bugfix in GaussNoise * Added check for variance of gaussian noise to be non negative * var_limit it GaussNoise should be non negative * bugfix. var can be int
albu_albumentations
train
2b53636efe8da975affe13ce83f6efb0b512d27c
diff --git a/src/Console/ConsoleServiceProvider.php b/src/Console/ConsoleServiceProvider.php index <HASH>..<HASH> 100644 --- a/src/Console/ConsoleServiceProvider.php +++ b/src/Console/ConsoleServiceProvider.php @@ -8,6 +8,7 @@ use Illuminate\Auth\Console\ClearResetsCommand; use Illuminate\Cache\Console\CacheTableCommand; use Illuminate\Queue\Console\FailedTableCommand; use Illuminate\Database\Console\Seeds\SeedCommand; +use Illuminate\Contracts\Support\DeferrableProvider; use Illuminate\Database\Console\Seeds\SeederMakeCommand; use Illuminate\Database\Console\Migrations\MigrateCommand; use Illuminate\Queue\Console\WorkCommand as QueueWorkCommand; @@ -27,16 +28,9 @@ use Illuminate\Database\Console\Migrations\InstallCommand as MigrateInstallComma use Illuminate\Database\Console\Migrations\RefreshCommand as MigrateRefreshCommand; use Illuminate\Database\Console\Migrations\RollbackCommand as MigrateRollbackCommand; -class ConsoleServiceProvider extends ServiceProvider +class ConsoleServiceProvider extends ServiceProvider implements DeferrableProvider { /** - * Indicates if loading of the provider is deferred. - * - * @var bool - */ - protected $defer = true; - - /** * The commands to be registered. * * @var array
[<I>] Update ConsoleServiceProvider to implement the DeferrableProvider contract
orchestral_lumen
train
61137ff24afdca4992e2351a95ea41c7e517e49f
diff --git a/lxd/cluster/gateway.go b/lxd/cluster/gateway.go index <HASH>..<HASH> 100644 --- a/lxd/cluster/gateway.go +++ b/lxd/cluster/gateway.go @@ -405,8 +405,7 @@ func (g *Gateway) init() error { raft.FSM(), raft.Raft(), dqlite.LogFunc(dqliteLog(g.options.logLevel)), - dqlite.LogLevel(g.options.logLevel), - dqlite.AutoCheckpoint(10000000)) + dqlite.LogLevel(g.options.logLevel)) if err != nil { return errors.Wrap(err, "failed to create dqlite driver") }
Drop AutoCheckpoint setting for the dqlite driver
lxc_lxd
train
0d7f3c0064dddc24367cb92af601bb3508f7e9ae
diff --git a/src/main/java/com/github/alexcojocaru/mojo/elasticsearch/v2/client/ElasticsearchClient.java b/src/main/java/com/github/alexcojocaru/mojo/elasticsearch/v2/client/ElasticsearchClient.java index <HASH>..<HASH> 100644 --- a/src/main/java/com/github/alexcojocaru/mojo/elasticsearch/v2/client/ElasticsearchClient.java +++ b/src/main/java/com/github/alexcojocaru/mojo/elasticsearch/v2/client/ElasticsearchClient.java @@ -56,7 +56,7 @@ public class ElasticsearchClient cm.setValidateAfterInactivity(1); cm.setDefaultSocketConfig(SocketConfig.custom() - .setSoTimeout(1000) + .setSoTimeout(5000) .setSoLinger(0) .setTcpNoDelay(true) .build()); @@ -67,8 +67,8 @@ public class ElasticsearchClient private static HttpClient buildHttpClient() { RequestConfig requestConfig = RequestConfig.custom() - .setConnectTimeout(1000) - .setConnectionRequestTimeout(1000) + .setConnectTimeout(1500) + .setConnectionRequestTimeout(1500) .build(); CloseableHttpClient httpClient = HttpClients.custom()
issue #<I> - update the HTTP client config to allow for slower ES
alexcojocaru_elasticsearch-maven-plugin
train
1fda272630fa3631664f5730c41ececd78abf3a6
diff --git a/library/src/main/java/trikita/anvil/BaseAttrs.java b/library/src/main/java/trikita/anvil/BaseAttrs.java index <HASH>..<HASH> 100644 --- a/library/src/main/java/trikita/anvil/BaseAttrs.java +++ b/library/src/main/java/trikita/anvil/BaseAttrs.java @@ -17,6 +17,8 @@ import android.widget.TextView; import android.text.TextWatcher; import android.text.Editable; import java.lang.ref.WeakReference; +import android.widget.RelativeLayout; +import android.util.Pair; /** * This is a utility class with some handy attribute generators. It servers as @@ -148,6 +150,31 @@ public class BaseAttrs extends Nodes { public final static int START = 0x00800003; public final static int END = 0x00800005; + // relative layout constants + public final static int ALIGN_BASELINE = RelativeLayout.ALIGN_BASELINE; + public final static int ALIGN_BOTTOM = RelativeLayout.ALIGN_BOTTOM; + public final static int ALIGN_END = RelativeLayout.ALIGN_END; + public final static int ALIGN_LEFT = RelativeLayout.ALIGN_LEFT; + public final static int ALIGN_PARENT_BOTTOM = RelativeLayout.ALIGN_PARENT_BOTTOM; + public final static int ALIGN_PARENT_END = RelativeLayout.ALIGN_PARENT_END; + public final static int ALIGN_PARENT_LEFT = RelativeLayout.ALIGN_PARENT_LEFT; + public final static int ALIGN_PARENT_RIGHT = RelativeLayout.ALIGN_PARENT_RIGHT; + public final static int ALIGN_PARENT_START = RelativeLayout.ALIGN_PARENT_START; + public final static int ALIGN_PARENT_TOP = RelativeLayout.ALIGN_PARENT_TOP; + public final static int ALIGN_RIGHT = RelativeLayout.ALIGN_RIGHT; + public final static int ALIGN_START = RelativeLayout.ALIGN_START; + public final static int ALIGN_TOP = RelativeLayout.ALIGN_TOP; + public final static int ALIGN_CENTER_HORIZONTAL = RelativeLayout.CENTER_HORIZONTAL; + public final static int ALIGN_CENTER_IN_PARENT = RelativeLayout.CENTER_IN_PARENT; + public final static int ALIGN_CENTER_VERTICAL = RelativeLayout.CENTER_VERTICAL; + public final static int ABOVE = RelativeLayout.ABOVE; + public final static int BELOW = RelativeLayout.BELOW; + public final static int END_OF = RelativeLayout.END_OF; + public final static int LEFT_OF = RelativeLayout.LEFT_OF; + public final static int RIGHT_OF = RelativeLayout.RIGHT_OF; + public final static int START_OF = RelativeLayout.START_OF; + public final static int TRUE = RelativeLayout.TRUE; + /** Attribute node that adjusts the LayoutParams of the view */ public static class LayoutNode implements AttrNode { int width; @@ -157,6 +184,11 @@ public class BaseAttrs extends Nodes { int column; int span; int[] margin = new int[4]; + List<Pair<Integer,Integer>> rules = new ArrayList<>(); + + public LayoutNode() { + this(Integer.MIN_VALUE, Integer.MIN_VALUE); + } public LayoutNode(int width, int height) { this.width = width; @@ -199,10 +231,23 @@ public class BaseAttrs extends Nodes { return this; } + public LayoutNode align(int verb) { + return this.align(verb, -1); + } + + public LayoutNode align(int verb, int anchor) { + this.rules.add(new Pair<>(verb, anchor)); + return this; + } + public void apply(View v) { ViewGroup.LayoutParams p = v.getLayoutParams(); - p.width = width; - p.height = height; + if (width != Integer.MIN_VALUE) { + p.width = width; + } + if (height != Integer.MIN_VALUE) { + p.height = height; + } if (p instanceof ViewGroup.MarginLayoutParams) { ((ViewGroup.MarginLayoutParams) p).leftMargin = this.margin[0]; ((ViewGroup.MarginLayoutParams) p).topMargin = this.margin[1]; @@ -220,6 +265,11 @@ public class BaseAttrs extends Nodes { ((TableRow.LayoutParams) p).column = this.column; ((TableRow.LayoutParams) p).span = this.span; } + if (p instanceof RelativeLayout.LayoutParams) { + for (Pair<Integer, Integer> rule : rules) { + ((RelativeLayout.LayoutParams) p).addRule(rule.first, rule.second); + } + } v.setLayoutParams(p); } @@ -253,6 +303,14 @@ public class BaseAttrs extends Nodes { } /** + * Creates a new LayoutParam generator chain with default width/height + * @return layout node + */ + public static LayoutNode size() { + return new LayoutNode(); + } + + /** * A helper for padding when each side padding is the same * @param p padding * @return padding node
added relative layout params, added layout params builder that doesn't override current width/height
zserge_anvil
train
355364ff0c21a220ff355d40d436b066bbaa0f53
diff --git a/tests/CfdiUtilsTests/CadenaOrigen/SaxonbCliBuilderTest.php b/tests/CfdiUtilsTests/CadenaOrigen/SaxonbCliBuilderTest.php index <HASH>..<HASH> 100644 --- a/tests/CfdiUtilsTests/CadenaOrigen/SaxonbCliBuilderTest.php +++ b/tests/CfdiUtilsTests/CadenaOrigen/SaxonbCliBuilderTest.php @@ -9,7 +9,11 @@ class SaxonbCliBuilderTest extends GenericBuilderTestCase { protected function createBuilder(): XsltBuilderInterface { - return new SaxonbCliBuilder('/usr/bin/saxonb-xslt'); + $executable = '/usr/bin/saxonb-xslt'; + if (! is_executable($executable)) { + $this->markTestIncomplete("Cannot test since $executable is missing"); + } + return new SaxonbCliBuilder($executable); } public function testConstructorWithEmptyExecutable()
Skip test if no saxonb-xslt is available
eclipxe13_CfdiUtils
train
584fd585eca1159e441c640e3366df8257cce8af
diff --git a/pre_commit/commands/hook_impl.py b/pre_commit/commands/hook_impl.py index <HASH>..<HASH> 100644 --- a/pre_commit/commands/hook_impl.py +++ b/pre_commit/commands/hook_impl.py @@ -70,6 +70,7 @@ def _ns( *, all_files: bool = False, remote_branch: Optional[str] = None, + local_branch: Optional[str] = None, from_ref: Optional[str] = None, to_ref: Optional[str] = None, remote_name: Optional[str] = None, @@ -82,6 +83,7 @@ def _ns( color=color, hook_stage=hook_type.replace('pre-', ''), remote_branch=remote_branch, + local_branch=local_branch, from_ref=from_ref, to_ref=to_ref, remote_name=remote_name, @@ -110,7 +112,7 @@ def _pre_push_ns( remote_url = args[1] for line in stdin.decode().splitlines(): - _, local_sha, remote_branch, remote_sha = line.split() + local_branch, local_sha, remote_branch, remote_sha = line.split() if local_sha == Z40: continue elif remote_sha != Z40 and _rev_exists(remote_sha): @@ -118,6 +120,7 @@ def _pre_push_ns( 'pre-push', color, from_ref=remote_sha, to_ref=local_sha, remote_branch=remote_branch, + local_branch=local_branch, remote_name=remote_name, remote_url=remote_url, ) else: @@ -139,6 +142,7 @@ def _pre_push_ns( all_files=True, remote_name=remote_name, remote_url=remote_url, remote_branch=remote_branch, + local_branch=local_branch, ) else: rev_cmd = ('git', 'rev-parse', f'{first_ancestor}^') @@ -148,6 +152,7 @@ def _pre_push_ns( from_ref=source, to_ref=local_sha, remote_name=remote_name, remote_url=remote_url, remote_branch=remote_branch, + local_branch=local_branch, ) # nothing to push diff --git a/pre_commit/commands/run.py b/pre_commit/commands/run.py index <HASH>..<HASH> 100644 --- a/pre_commit/commands/run.py +++ b/pre_commit/commands/run.py @@ -371,7 +371,11 @@ def run( environ['PRE_COMMIT_FROM_REF'] = args.from_ref environ['PRE_COMMIT_TO_REF'] = args.to_ref - if args.remote_name and args.remote_url and args.remote_branch: + if ( + args.remote_name and args.remote_url and + args.remote_branch and args.local_branch + ): + environ['PRE_COMMIT_LOCAL_BRANCH'] = args.local_branch environ['PRE_COMMIT_REMOTE_BRANCH'] = args.remote_branch environ['PRE_COMMIT_REMOTE_NAME'] = args.remote_name environ['PRE_COMMIT_REMOTE_URL'] = args.remote_url diff --git a/pre_commit/main.py b/pre_commit/main.py index <HASH>..<HASH> 100644 --- a/pre_commit/main.py +++ b/pre_commit/main.py @@ -100,6 +100,9 @@ def _add_run_options(parser: argparse.ArgumentParser) -> None: '--remote-branch', help='Remote branch ref used by `git push`.', ) parser.add_argument( + '--local-branch', help='Local branch ref used by `git push`.', + ) + parser.add_argument( '--from-ref', '--source', '-s', help=( '(for usage with `--from-ref`) -- this option represents the ' diff --git a/testing/util.py b/testing/util.py index <HASH>..<HASH> 100644 --- a/testing/util.py +++ b/testing/util.py @@ -62,6 +62,7 @@ def run_opts( verbose=False, hook=None, remote_branch='', + local_branch='', from_ref='', to_ref='', remote_name='', @@ -81,6 +82,7 @@ def run_opts( verbose=verbose, hook=hook, remote_branch=remote_branch, + local_branch=local_branch, from_ref=from_ref, to_ref=to_ref, remote_name=remote_name, diff --git a/tests/commands/run_test.py b/tests/commands/run_test.py index <HASH>..<HASH> 100644 --- a/tests/commands/run_test.py +++ b/tests/commands/run_test.py @@ -487,6 +487,7 @@ def test_all_push_options_ok(cap_out, store, repo_with_passing_hook): args = run_opts( from_ref='master', to_ref='master', remote_branch='master', + local_branch='master', remote_name='origin', remote_url='https://example.com/repo', ) ret, printed = _do_run(cap_out, store, repo_with_passing_hook, args)
Expose local branch ref as an environment variable
pre-commit_pre-commit
train
f49ab1136c096d2b32bd68b25d52dd4717a55d55
diff --git a/src/zoom.js b/src/zoom.js index <HASH>..<HASH> 100644 --- a/src/zoom.js +++ b/src/zoom.js @@ -33,7 +33,9 @@ export default function(started) { gestures = [], listeners = dispatch("start", "zoom", "end").on("start", started), mousemoving, + touchstarting, touchending, + touchDelay = 500, wheelTimer, wheelDelay = 150; @@ -255,7 +257,6 @@ export default function(started) { else select(this).call(zoom.transform, t1); } - // TODO dbltap zoom-in function touchstarted() { if (!filter.apply(this, arguments)) return; var g = gesture(this, arguments), @@ -269,8 +270,15 @@ export default function(started) { if (!g.touch0) g.touch0 = p; else if (!g.touch1) g.touch1 = p; } - interrupt(this); - g.start(); + if (touchstarting) { + touchstarting = clearTimeout(touchstarting); + if (!g.touch1) return g.end(), dblclicked.apply(this, arguments); + } + if (event.touches.length === n) { + touchstarting = setTimeout(function() { touchstarting = null; }, touchDelay); + interrupt(this); + g.start(); + } } function touchmoved() { @@ -279,6 +287,7 @@ export default function(started) { n = touches.length, i, t, p, l; noevent(); + if (touchstarting) touchstarting = clearTimeout(touchstarting); for (i = 0; i < n; ++i) { t = touches[i], p = touch(this, touches, t.identifier); if (g.touch0 && g.touch0[2] === t.identifier) g.touch0[0] = p; @@ -306,7 +315,7 @@ export default function(started) { nopropagation(); if (touchending) clearTimeout(touchending); - touchending = setTimeout(function() { touchending = null; }, 500); // Ghost clicks are delayed! + touchending = setTimeout(function() { touchending = null; }, touchDelay); for (i = 0; i < n; ++i) { t = touches[i]; if (g.touch0 && g.touch0[2] === t.identifier) delete g.touch0;
Fix #<I> - double-tap to zoom-in. Also fixes a bug where the end event wasn’t emitted because we were erroneously not considering secondary touches as part of the same gesture.
d3_d3-zoom
train
60b105e05473bd03b6dc267e8759f6072f02dd1b
diff --git a/tasks/twigRender.js b/tasks/twigRender.js index <HASH>..<HASH> 100644 --- a/tasks/twigRender.js +++ b/tasks/twigRender.js @@ -217,8 +217,8 @@ module.exports = function(grunt) { }); } catch(err) { // Fail the build if Twig.Error was thrown - grunt.fail.fatal(err); + grunt.fail.fatal(err.type + ' in file "' + err.file + '": ' + err.message ); } }); -}; \ No newline at end of file +};
adjust error message to get a clue where the error occures
stefanullinger_grunt-twig-render
train
1289d2f7a8fd7a6769de8cedd3c7801a56dd3708
diff --git a/karyon-core/src/main/java/com/netflix/karyon/server/ServerBootstrap.java b/karyon-core/src/main/java/com/netflix/karyon/server/ServerBootstrap.java index <HASH>..<HASH> 100644 --- a/karyon-core/src/main/java/com/netflix/karyon/server/ServerBootstrap.java +++ b/karyon-core/src/main/java/com/netflix/karyon/server/ServerBootstrap.java @@ -111,18 +111,6 @@ public class ServerBootstrap { logger.info("Creating a new governator classpath scanner with base packages: " + allBasePackages); classpathScanner = LifecycleInjector.createStandardClasspathScanner(allBasePackages, annotations); } - - private Set<String> readBasePackages() { - Set<String> _allBasePackages = new HashSet<String>(); - _allBasePackages.add("com.netflix"); - - Collection<String> basePackages = getBasePackages(); - if (null != basePackages) { - _allBasePackages.addAll(basePackages); - } - - return _allBasePackages; - } /** * @@ -185,6 +173,13 @@ public class ServerBootstrap { * @param builderToBeUsed The builder to be used for creating an injector. This builder can be modified/configured * as required. */ + protected void beforeInjectorCreation(@SuppressWarnings("unused") LifecycleInjectorBuilder builderToBeUsed) { + // No op by default + } + + /** + * create the main application injector + */ protected Injector createInjector(LifecycleInjectorBuilder builder) { LifecycleInjector lifecycleInjector = builder.build(); Injector injector = lifecycleInjector.createInjector(); @@ -253,7 +248,19 @@ public class ServerBootstrap { protected ClasspathScanner getClasspathScanner() { return classpathScanner; } + + private Set<String> readBasePackages() { + Set<String> _allBasePackages = new HashSet<String>(); + _allBasePackages.add("com.netflix"); + Collection<String> basePackages = getBasePackages(); + if (null != basePackages) { + _allBasePackages.addAll(basePackages); + } + + return _allBasePackages; + } + protected class KaryonBootstrapModule implements BootstrapModule { @Override
restore no-op beforeInjectorCreation() method for binary compatibility
Netflix_karyon
train
bffa40a7118dd979b296246f9e4fdbea47023a1b
diff --git a/ipyrad/plotting/baba_panel_plot.py b/ipyrad/plotting/baba_panel_plot.py index <HASH>..<HASH> 100644 --- a/ipyrad/plotting/baba_panel_plot.py +++ b/ipyrad/plotting/baba_panel_plot.py @@ -8,12 +8,32 @@ a panel plot function for baba results from __future__ import print_function import numpy as np -import toyplot -import toytree import itertools # pylint: disable=W0212 +# import tested at call time +try: + import toytree +except ImportError: + pass +_TOYTREE_IMPORT = """ +This ipyrad analysis tool requires +You can install it with the following command: + + conda install toytree -c eaton-lab +""" +try: + import toyplot +except ImportError: + pass +_TOYPLOT_IMPORT = """ +This ipyrad analysis tool requires the toyplot package. +You can install it with the following command: + + conda install toyplot -c eaton-lab +""" + ## color palette COLORS = { "p1": toyplot.color.Palette()[0], @@ -23,7 +43,6 @@ COLORS = { } - ## the main function. def baba_panel_plot( ttree, @@ -41,6 +60,11 @@ def baba_panel_plot( """ signature... """ + # check external imports + if not sys.modules.get("toytree"): + raise ImportError(_TOYTREE_IMPORT) + if not sys.modules.get("toyplot"): + raise ImportError(_TOYPLOT_IMPORT) ## create Panel plot object and set height & width bootsarr = np.array(boots) @@ -68,8 +92,6 @@ def baba_panel_plot( return canvas, axes, panel - - class Panel(object): def __init__(self, ttree, tests, boots, alpha): #tree, edges, verts, names, tests, boots, alpha):
fix import checking for baba_panel_plot.py
dereneaton_ipyrad
train
62ebb760ae1fb9a4462c2d607b7fa29f2a7e6331
diff --git a/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/process/traversal/step/map/SumGlobalStep.java b/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/process/traversal/step/map/SumGlobalStep.java index <HASH>..<HASH> 100644 --- a/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/process/traversal/step/map/SumGlobalStep.java +++ b/gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/process/traversal/step/map/SumGlobalStep.java @@ -18,14 +18,14 @@ */ package org.apache.tinkerpop.gremlin.process.traversal.step.map; -import org.apache.tinkerpop.gremlin.process.traversal.Traversal; -import org.apache.tinkerpop.gremlin.process.traversal.Traverser; import org.apache.tinkerpop.gremlin.process.computer.KeyValue; import org.apache.tinkerpop.gremlin.process.computer.MapReduce; import org.apache.tinkerpop.gremlin.process.computer.traversal.TraversalVertexProgram; import org.apache.tinkerpop.gremlin.process.computer.util.StaticMapReduce; -import org.apache.tinkerpop.gremlin.process.traversal.step.util.ReducingBarrierStep; +import org.apache.tinkerpop.gremlin.process.traversal.Traversal; +import org.apache.tinkerpop.gremlin.process.traversal.Traverser; import org.apache.tinkerpop.gremlin.process.traversal.step.MapReducer; +import org.apache.tinkerpop.gremlin.process.traversal.step.util.ReducingBarrierStep; import org.apache.tinkerpop.gremlin.process.traversal.traverser.TraverserRequirement; import org.apache.tinkerpop.gremlin.process.traversal.traverser.util.TraverserSet; import org.apache.tinkerpop.gremlin.structure.Vertex; @@ -127,11 +127,7 @@ public final class SumGlobalStep extends ReducingBarrierStep<Number, Double> imp @Override public Number generateFinalResult(final Iterator<KeyValue<NullObject, Number>> keyValues) { - double sum = 0.0d; - while (keyValues.hasNext()) { - sum = sum + keyValues.next().getValue().doubleValue(); - } - return sum; + return keyValues.hasNext() ? keyValues.next().getValue() : 0.0d; } public static final SumGlobalMapReduce instance() {
Reverting SumMapReduce to the proper way to deal with generatingFinalResult.
apache_tinkerpop
train
f5cd0ec302a8c0fca515f3e4b6d7d014129ec3de
diff --git a/config/src/integration-test/java/org/springframework/security/config/ldap/LdapServerBeanDefinitionParserTests.java b/config/src/integration-test/java/org/springframework/security/config/ldap/LdapServerBeanDefinitionParserTests.java index <HASH>..<HASH> 100644 --- a/config/src/integration-test/java/org/springframework/security/config/ldap/LdapServerBeanDefinitionParserTests.java +++ b/config/src/integration-test/java/org/springframework/security/config/ldap/LdapServerBeanDefinitionParserTests.java @@ -99,17 +99,8 @@ public class LdapServerBeanDefinitionParserTests { } private int getDefaultPort() throws IOException { - ServerSocket server = null; - try { - server = new ServerSocket(0); + try (ServerSocket server = new ServerSocket(0)) { return server.getLocalPort(); } - finally { - try { - server.close(); - } - catch (IOException e) { - } - } } } diff --git a/core/src/test/java/org/springframework/security/core/JavaVersionTests.java b/core/src/test/java/org/springframework/security/core/JavaVersionTests.java index <HASH>..<HASH> 100644 --- a/core/src/test/java/org/springframework/security/core/JavaVersionTests.java +++ b/core/src/test/java/org/springframework/security/core/JavaVersionTests.java @@ -38,21 +38,13 @@ public class JavaVersionTests { private void assertClassVersion(Class<?> clazz) throws Exception { String classResourceName = clazz.getName().replaceAll("\\.", "/") + ".class"; - InputStream input = Thread.currentThread().getContextClassLoader() - .getResourceAsStream(classResourceName); - try { + try (InputStream input = Thread.currentThread().getContextClassLoader() + .getResourceAsStream(classResourceName)) { DataInputStream data = new DataInputStream(input); data.readInt(); data.readShort(); // minor int major = data.readShort(); assertThat(major).isEqualTo(JDK8_CLASS_VERSION); } - finally { - try { - input.close(); - } - catch (Exception e) { - } - } } } diff --git a/ldap/src/integration-test/java/org/springframework/security/ldap/ApacheDSServerIntegrationTests.java b/ldap/src/integration-test/java/org/springframework/security/ldap/ApacheDSServerIntegrationTests.java index <HASH>..<HASH> 100644 --- a/ldap/src/integration-test/java/org/springframework/security/ldap/ApacheDSServerIntegrationTests.java +++ b/ldap/src/integration-test/java/org/springframework/security/ldap/ApacheDSServerIntegrationTests.java @@ -114,19 +114,8 @@ public final class ApacheDSServerIntegrationTests { */ private static int getAvailablePort() throws IOException { - ServerSocket serverSocket = null; - try { - serverSocket = new ServerSocket(0); + try (ServerSocket serverSocket = new ServerSocket(0)) { return serverSocket.getLocalPort(); } - finally { - if (serverSocket != null) { - try { - serverSocket.close(); - } - catch (IOException e) { - } - } - } } }
Use try-with-resources instead of try-finally
spring-projects_spring-security
train
ccc3b9dbb4cfe0d830d9a2b4e6fdd01c8f6df10a
diff --git a/lib/Cake/Utility/Sanitize.php b/lib/Cake/Utility/Sanitize.php index <HASH>..<HASH> 100644 --- a/lib/Cake/Utility/Sanitize.php +++ b/lib/Cake/Utility/Sanitize.php @@ -141,7 +141,7 @@ class Sanitize { * Strips scripts and stylesheets from output * * @param string $str String to sanitize - * @return string String with <script>, <style>, <link> elements removed. + * @return string String with <script>, <style>, <link>, <img> elements removed. */ public static function stripScripts($str) { return preg_replace('/(<link[^>]+rel="[^"]*stylesheet"[^>]*>|<img[^>]*>|style="[^"]*")|<script[^>]*>.*?<\/script>|<style[^>]*>.*?<\/style>|<!--.*?-->/is', '', $str);
Updating docblock for Sanitize::stripScripts()
cakephp_cakephp
train
ce952b677ea468b009dabc5f4dd4c2a05e4256f4
diff --git a/ford/__init__.py b/ford/__init__.py index <HASH>..<HASH> 100644 --- a/ford/__init__.py +++ b/ford/__init__.py @@ -46,7 +46,7 @@ __appname__ = "FORD" __author__ = "Chris MacMackin, Jacob Williams, Marco Restelli, Iain Barrass, Jérémie Burgalat" __credits__ = ["Stefano Zhagi", "Izaak Beekman", "Gavin Huttley"] __license__ = "GPLv3" -__version__ = "4.5.0" +__version__ = "4.5.1" __maintainer__ = "Chris MacMackin" __status__ = "Production" diff --git a/ford/fortran_project.py b/ford/fortran_project.py index <HASH>..<HASH> 100644 --- a/ford/fortran_project.py +++ b/ford/fortran_project.py @@ -229,7 +229,7 @@ class Project(object): for subroutine in program.subroutines: self.procedures.append(subroutine) for interface in program.interfaces: - self.procedures.append(interfaces) + self.procedures.append(interface) for absint in program.absinterfaces: self.absinterfaces.append(absint) for dtype in program.types: diff --git a/setup.py b/setup.py index <HASH>..<HASH> 100644 --- a/setup.py +++ b/setup.py @@ -12,13 +12,13 @@ setup( name = 'FORD', packages = ['ford'], include_package_data = True, - version = '4.5.0', + version = '4.5.1', description = 'FORD, standing for FORtran Documenter, is an automatic documentation generator for modern Fortran programs.', long_description = long_description, author = 'Chris MacMackin', author_email = 'cmacmackin@gmail.com', url = 'https://github.com/cmacmackin/ford/', - download_url = 'https://github.com/cmacmackin/ford/tarball/4.5.0', + download_url = 'https://github.com/cmacmackin/ford/tarball/4.5.1', keywords = ['Markdown', 'Fortran', 'documentation', 'comments'], classifiers=[ # How mature is this project? Common values are
Fixed typo causing crash when correlating interfaces within programs.
Fortran-FOSS-Programmers_ford
train
2d32754611ef1b7ccd774467f316878daa74d7f3
diff --git a/c7n/actions.py b/c7n/actions.py index <HASH>..<HASH> 100644 --- a/c7n/actions.py +++ b/c7n/actions.py @@ -865,11 +865,14 @@ class ModifyPolicyBase(BaseAction): ) def __init__(self, data=None, manager=None): - config_args = { - 'account_id': manager.config.account_id, - 'region': manager.config.region - } - self.data = utils.format_string_values(data, **config_args) + if manager is not None: + config_args = { + 'account_id': manager.config.get('account_id'), + 'region': manager.config.get('region') + } + self.data = utils.format_string_values(data, **config_args) + else: + self.data = utils.format_string_values(data) self.manager = manager def add_statements(self, policy_statements):
sns - cross-access filter validation fixes (#<I>)
cloud-custodian_cloud-custodian
train
5073171308a2bcb2192833c797d5b1c4029cd8b8
diff --git a/tools/diagnose.py b/tools/diagnose.py index <HASH>..<HASH> 100644 --- a/tools/diagnose.py +++ b/tools/diagnose.py @@ -110,6 +110,8 @@ def check_mxnet(): print('Commit Hash :', ch) except ImportError: print('No MXNet installed.') + except FileNotFoundError: + print('Hashtag not found. Not installed from pre-built package.') except Exception as e: import traceback if not isinstance(e, IOError):
fix diagnose if hashtag not found. (#<I>)
apache_incubator-mxnet
train
71745d78b5abe4dbbee32e950282a27aa70c56ef
diff --git a/lib/Site.php b/lib/Site.php index <HASH>..<HASH> 100644 --- a/lib/Site.php +++ b/lib/Site.php @@ -207,11 +207,11 @@ class Site extends \TimberSite // Index the viewClass by its file name, so we can render it // when WordPress tries to include that file - $viewPath = \get_stylesheet_directory().'/app/Views'.$viewClass::getFileName().'.php'; + $viewPath = \get_stylesheet_directory().'/app/Views'.$viewClass::getFileName(false).'.php'; if (!file_exists($viewPath)) { $viewPath = str_replace('app/Views', 'app/views', $viewPath); if (!file_exists($viewPath)) { - $viewPath = \get_stylesheet_directory().'/app/Views'.$viewClass::getFileName(false).'.php'; + $viewPath = \get_stylesheet_directory().'/app/Views'.$viewClass::getFileName().'.php'; if (!file_exists($viewPath)) { $viewPath = str_replace('app/Views', 'app/views', $viewPath); }
Reverse order in which View file names are loaded. Try the dashed version of the View name first, so that templates that are 1 word long like home.php will attempt to load the lower case version instead of the uppercase Home.php (This is an issue on OS X)
StoutLogic_understory
train
f0d82add27783a3fe230841f40c281188adae495
diff --git a/lib/librato.js b/lib/librato.js index <HASH>..<HASH> 100644 --- a/lib/librato.js +++ b/lib/librato.js @@ -24,7 +24,7 @@ url_parse = require('url').parse, var tunnelAgent = null; var debug, logAll; -var api, email, token, period, sourceName, sourceRegex, includeMetrics, excludeMetrics; +var api, email, token, period, hostName, sourceRegex, includeMetrics, excludeMetrics; // How long to wait before retrying a failed post, in seconds var retryDelaySecs = 5; @@ -295,10 +295,13 @@ var flush_stats = function librato_flush(ts, metrics) measureName = parse_and_set_tags(measureName, measure); // Use first capturing group as source name - if (!writeToLegacy && sourceRegex && (match = measureName.match(sourceRegex)) && match[1]) { + if (sourceRegex && (match = measureName.match(sourceRegex)) && match[1]) { measure.source = sanitize_name(match[1]); // Remove entire matching string from the measure name & add global prefix. measure.name = sanitize_name(measureName.slice(0, match.index) + measureName.slice(match.index + match[0].length)); + + // Create a measurement-level tag named source + measure.tags.source = measure.source; } else { measure.name = sanitize_name(measureName); } @@ -537,7 +540,7 @@ exports.init = function librato_init(startup_time, config, events, logger) api = config.librato.api; email = config.librato.email; token = config.librato.token; - sourceName = config.librato.source; + hostName = config.librato.source; sourceRegex = config.librato.sourceRegex; snapTime = config.librato.snapTime; includeMetrics = config.librato.includeMetrics; @@ -576,10 +579,10 @@ exports.init = function librato_init(startup_time, config, events, logger) skipInternalMetrics = config.librato.skipInternalMetrics; } - if (sourceName == null) { + if (hostName == null) { var os = require('os'); - sourceName = os.hostname(); + hostName = os.hostname(); } if (config.librato.proxy && config.librato.proxy.uri) { @@ -627,7 +630,7 @@ exports.init = function librato_init(startup_time, config, events, logger) } // Set host as a global tag - tags['host'] = sourceName; + tags['host'] = hostName; } if (!email || !token) {
Create a host tag from the hostname or source. Create a measurement-level source tag if we are doing regex
librato_statsd-librato-backend
train
21fb69d9550aacad59f615b9ad72aaed31b82ec9
diff --git a/src/Mutex.php b/src/Mutex.php index <HASH>..<HASH> 100644 --- a/src/Mutex.php +++ b/src/Mutex.php @@ -5,8 +5,10 @@ namespace Illuminated\Console; use Illuminate\Console\Command; use NinjaMutex\Lock\FlockLock; use NinjaMutex\Lock\MySqlLock; +use NinjaMutex\Lock\PredisRedisLock; use NinjaMutex\Mutex as Ninja; use NinjaMutex\MutexException; +use Redis; class Mutex { @@ -32,7 +34,7 @@ class Mutex return new MySqlLock(env('DB_USERNAME'), env('DB_PASSWORD'), env('DB_HOST')); case 'redis': - throw new MutexException('Strategy `redis` is not implemented yet.'); + return new PredisRedisLock(Redis::connection()); case 'memcache': throw new MutexException('Strategy `memcache` is not implemented yet.');
ICM: `redis` strategy implemented.
dmitry-ivanov_laravel-console-mutex
train
563b397391ef46ad7ddbe1a254bdbc3813b52f46
diff --git a/src/crypto/public_key/elliptic/curves.js b/src/crypto/public_key/elliptic/curves.js index <HASH>..<HASH> 100644 --- a/src/crypto/public_key/elliptic/curves.js +++ b/src/crypto/public_key/elliptic/curves.js @@ -93,41 +93,47 @@ const curves = { keyType: enums.publicKey.ecdsa, hash: enums.hash.sha256, cipher: enums.symmetric.aes128, - node: nodeCurves.secp256k1 + node: nodeCurves.secp256k1, + payloadSize: 32 }, ed25519: { oid: [0x06, 0x09, 0x2B, 0x06, 0x01, 0x04, 0x01, 0xDA, 0x47, 0x0F, 0x01], keyType: enums.publicKey.eddsa, hash: enums.hash.sha512, - node: false // nodeCurves.ed25519 TODO + node: false, // nodeCurves.ed25519 TODO + payloadSize: 32 }, curve25519: { oid: [0x06, 0x0A, 0x2B, 0x06, 0x01, 0x04, 0x01, 0x97, 0x55, 0x01, 0x05, 0x01], keyType: enums.publicKey.ecdsa, hash: enums.hash.sha256, cipher: enums.symmetric.aes128, - node: false // nodeCurves.curve25519 TODO + node: false, // nodeCurves.curve25519 TODO + payloadSize: 32 }, brainpoolP256r1: { oid: [0x06, 0x09, 0x2B, 0x24, 0x03, 0x03, 0x02, 0x08, 0x01, 0x01, 0x07], keyType: enums.publicKey.ecdsa, hash: enums.hash.sha256, cipher: enums.symmetric.aes128, - node: nodeCurves.brainpoolP256r1 + node: nodeCurves.brainpoolP256r1, + payloadSize: 32 }, brainpoolP384r1: { oid: [0x06, 0x09, 0x2B, 0x24, 0x03, 0x03, 0x02, 0x08, 0x01, 0x01, 0x0B], keyType: enums.publicKey.ecdsa, hash: enums.hash.sha384, cipher: enums.symmetric.aes192, - node: nodeCurves.brainpoolP384r1 + node: nodeCurves.brainpoolP384r1, + payloadSize: 48 }, brainpoolP512r1: { oid: [0x06, 0x09, 0x2B, 0x24, 0x03, 0x03, 0x02, 0x08, 0x01, 0x01, 0x0D], keyType: enums.publicKey.ecdsa, hash: enums.hash.sha512, cipher: enums.symmetric.aes256, - node: nodeCurves.brainpoolP512r1 + node: nodeCurves.brainpoolP512r1, + payloadSize: 64 } }; @@ -185,12 +191,7 @@ Curve.prototype.genKeyPair = async function () { return nodeGenKeyPair(this.name); case 'curve25519': { const privateKey = await random.getRandomBytes(32); - const one = new BN(1); - const mask = one.ushln(255 - 3).sub(one).ushln(3); - let secretKey = new BN(privateKey); - secretKey = secretKey.or(one.ushln(255 - 1)); - secretKey = secretKey.and(mask); - secretKey = secretKey.toArrayLike(Uint8Array, 'le', 32); + const secretKey = privateKey.slice().reverse(); keyPair = nacl.box.keyPair.fromSecretKey(secretKey); const publicKey = util.concatUint8Array([new Uint8Array([0x40]), keyPair.publicKey]); return { publicKey, privateKey }; @@ -314,10 +315,6 @@ function rawPublicToJwk(payloadSize, name, publicKey) { */ function privateToJwk(payloadSize, name, publicKey, privateKey) { const jwk = rawPublicToJwk(payloadSize, name, publicKey); - if (privateKey.length !== payloadSize) { - const start = payloadSize - privateKey.length; - privateKey = (new Uint8Array(payloadSize)).set(privateKey, start); - } jwk.d = util.Uint8Array_to_b64(privateKey, true); return jwk; } diff --git a/src/crypto/public_key/elliptic/ecdh.js b/src/crypto/public_key/elliptic/ecdh.js index <HASH>..<HASH> 100644 --- a/src/crypto/public_key/elliptic/ecdh.js +++ b/src/crypto/public_key/elliptic/ecdh.js @@ -146,14 +146,14 @@ async function encrypt(oid, cipher_algo, hash_algo, m, Q, fingerprint) { * @async */ async function genPrivateEphemeralKey(curve, V, Q, d) { + if (d.length !== curve.payloadSize) { + const privateKey = new Uint8Array(curve.payloadSize); + privateKey.set(d, curve.payloadSize - d.length); + d = privateKey; + } switch (curve.type) { case 'curve25519': { - const one = new BN(1); - const mask = one.ushln(255 - 3).sub(one).ushln(3); - let secretKey = new BN(d); - secretKey = secretKey.or(one.ushln(255 - 1)); - secretKey = secretKey.and(mask); - secretKey = secretKey.toArrayLike(Uint8Array, 'le', 32); + const secretKey = d.slice().reverse(); const sharedKey = nacl.scalarMult(secretKey, V.subarray(1)); return { secretKey, sharedKey }; // Note: sharedKey is little-endian here, unlike below }
Don't mask curve<I> private key twice Also, fix handling of private keys with leading zeros for certain curves.
openpgpjs_openpgpjs
train
c9e0343b985306314ef6a6a914fbd5562500439a
diff --git a/Database.php b/Database.php index <HASH>..<HASH> 100644 --- a/Database.php +++ b/Database.php @@ -234,7 +234,7 @@ abstract class Nada_Database **/ public function beginCapture() { - if ($this->_capturedCommands !== null) { + if ($this->isCapturing()) { throw new RuntimeException('Capture already started.'); } $this->_capturedCommands = array(); @@ -250,7 +250,7 @@ abstract class Nada_Database **/ public function endCapture() { - if ($this->_capturedCommands === null) { + if (!$this->isCapturing()) { throw new RuntimeException('Capture not started yet.'); } $commands = $this->_capturedCommands; @@ -259,6 +259,14 @@ abstract class Nada_Database } /** + * Get capturing status + * @return bool TRUE if capturing has been started via beginCapture() + **/ + public function isCapturing() + { + return $this->_capturedCommands !== null; + } + /** * Return a case insensitive LIKE operator if available * * The behavior of the LIKE operator varies across DBMS. Sometimes it is
Added isCapturing() method.
hschletz_NADA
train
586d6d251ba36263615c81ce8f292d7951007ae4
diff --git a/nipap-cli/nipap_cli/command.py b/nipap-cli/nipap_cli/command.py index <HASH>..<HASH> 100755 --- a/nipap-cli/nipap_cli/command.py +++ b/nipap-cli/nipap_cli/command.py @@ -209,8 +209,11 @@ class Command: # if we are in scoop-rest-mode, place elements not matching # anything in argument-array - if not match and self._scoop_rest_arguments: - self.arg.append(p) + if not match: + if self._scoop_rest_arguments: + self.arg.append(p) + else: + raise InvalidCommand("Invalid argument: " + p) else: raise InvalidCommand('ran out of parameters; command too long')
Add CLI input validation for extraneous arguments If extraneous arguments are sent to the command parser an exception is now raised. I hope this doesn't break anything else. The unittest is so far from complete when it comes to command parsing that it won't help. I've done some manual testing which didn't show anything else being broken. Fixes #<I>.
SpriteLink_NIPAP
train
ed57bb202e5562e24914b6fb54085298839b529b
diff --git a/src/sap.ui.integration/test/sap/ui/integration/demokit/cardExplorer/webapp/cachingServiceWorker.js b/src/sap.ui.integration/test/sap/ui/integration/demokit/cardExplorer/webapp/cachingServiceWorker.js index <HASH>..<HASH> 100644 --- a/src/sap.ui.integration/test/sap/ui/integration/demokit/cardExplorer/webapp/cachingServiceWorker.js +++ b/src/sap.ui.integration/test/sap/ui/integration/demokit/cardExplorer/webapp/cachingServiceWorker.js @@ -190,6 +190,10 @@ self.addEventListener('fetch', function (event) { } }); +self.addEventListener('install', function () { + self.skipWaiting(); +}); + self.addEventListener("activate", function (event) { event.waitUntil(clients.claim()); -}); \ No newline at end of file +});
[INTERNAL] Card Explorer: Fix service worker refreshing When multiple tabs with Card Explorer are open, the service worker was not refreshing. Now this is fixed. Change-Id: Ide<I>da<I>d<I>e9cfe<I>efdc<I>e1b<I> JIRA: BGSOFUIRODOPI-<I>
SAP_openui5
train
a6a8986dbcfe65a94b2112985d95480fdb2a82dc
diff --git a/lib/implementation.js b/lib/implementation.js index <HASH>..<HASH> 100644 --- a/lib/implementation.js +++ b/lib/implementation.js @@ -1,5 +1,6 @@ var _ = require('lodash'); var async = require('async'); +var Promise = require('bluebird'); module.exports = function(self, options) { @@ -304,7 +305,119 @@ module.exports = function(self, options) { }; self.ensureIndexes = function(callback) { - return self.apos.docs.db.ensureIndex({ workflowGuid: 1 }, {}, callback); + + return Promise.try(function() { + return self.apos.docs.db.ensureIndex({ workflowGuid: 1 }, {}); + }) + .then(workflowGuidWorkflowLocale) + // depromisify + .then(function() { + return callback(null); + }) + .catch(function(err) { + return callback(err); + }); + + // Early versions did not have this index and thus could + // violate the uniqueness of the guid.locale pair under + // rare race conditions. If the index fails, resolve + // the duplicates and try again + + function workflowGuidWorkflowLocale() { + return self.apos.docs.db.ensureIndex({ workflowGuid: 1, workflowLocale: 1 }, { sparse: 1, unique: 1 }) + .catch(function(err) { + return resolveDuplicateDocs() + .then(function() { + // now we can try the index again, recursively + return workflowGuidWorkflowLocale(); + }); + }); + } + + function resolveDuplicateDocs() { + var locked = false; + // Lock in case somebody else is trying to fix this too + return Promise.try(function() { + return self.apos.locks.lock('apostrophe-workflow:resolveDuplicateDocs'); + }) + .then(function() { + locked = true; + return self.apos.docs.db.aggregate([ + { + $match: { + workflowGuid: { $exists: 1 } + }, + }, + { + $group: { + _id: { + workflowGuid: "$workflowGuid", + workflowLocale: "$workflowLocale" + }, + slugs: { + $addToSet: "$slug" + }, + ids: { + $addToSet: "$_id" + }, + count: { + $sum: 1 + } + } + }, + { + $match: { + count: { + $gt: 1 + } + } + } + ]).toArray(); + }) + .then(function(groups) { + return Promise.mapSeries(groups, function(group) { + // Shortest slug is the keeper (the one with + // a digit added is the one created later) + var slugs = group.slugs.slice(0); + slugs.sort(); + var index = group.slugs.indexOf(slugs[0]); + var id = group.ids[index]; + return Promise.mapSeries(slugs.slice(1), function(slug) { + return Promise.try(function() { + return self.apos.docs.db.findOne({ + workflowGuid: group._id.workflowGuid, + slug: slug + }); + }) + .then(function(orphan) { + if (!orphan) { + // Gone already somehow; not our problem + return; + } + console.error(orphan._id + ' duplicates the workflowGuid and workflowLocale of\n' + id + ' and has been removed and appended to the\nworkflowGuidAndLocaleDuplicates property of the latter to resolve this race\ncondition.\n\nThis is no longer possible for new inserts thanks to a unique sparse index.\n'); + return self.apos.docs.db.update({ + _id: id + }, { + $push: { + workflowGuidAndLocaleDuplicates: orphan + } + }) + .then(function() { + return self.apos.docs.db.remove({ + _id: orphan._id + }); + }); + }); + }); + }); + }) + .finally(function() { + if (!locked) { + return; + } + return self.apos.locks.unlock('apostrophe-workflow:resolveDuplicateDocs'); + }); + } }; // Create mongodb collection in which to permanently record each commit.
add workflowGuid+workflowLocale sparse unique index, with an inline migration to clean up the mess if this constraint has been violated
apostrophecms_apostrophe-workflow
train
13ebabb222194cb506594c14e4861f2b7d142815
diff --git a/lib/rulix.rb b/lib/rulix.rb index <HASH>..<HASH> 100644 --- a/lib/rulix.rb +++ b/lib/rulix.rb @@ -1,3 +1,5 @@ +require 'delegate' + require_relative './rulix/version' require_relative './rulix/errors' require_relative './rulix/validation' diff --git a/lib/rulix/version.rb b/lib/rulix/version.rb index <HASH>..<HASH> 100644 --- a/lib/rulix/version.rb +++ b/lib/rulix/version.rb @@ -1,3 +1,3 @@ module Rulix - VERSION = "0.8.0" + VERSION = "0.8.1" end
Tiny bugfix so this version works
blarshk_rulix
train
6986248371f16425caff229d89608dcc11719b5f
diff --git a/accumulo/src/main/java/org/vertexium/accumulo/AccumuloGraph.java b/accumulo/src/main/java/org/vertexium/accumulo/AccumuloGraph.java index <HASH>..<HASH> 100644 --- a/accumulo/src/main/java/org/vertexium/accumulo/AccumuloGraph.java +++ b/accumulo/src/main/java/org/vertexium/accumulo/AccumuloGraph.java @@ -2607,7 +2607,9 @@ public class AccumuloGraph extends GraphBaseWithSearchIndex implements Traceable @Override public void close() { super.close(); - scanner.close(); + if (scanner != null) { + scanner.close(); + } if (trace != null) { trace.stop(); } diff --git a/test/src/main/java/org/vertexium/test/GraphTestBase.java b/test/src/main/java/org/vertexium/test/GraphTestBase.java index <HASH>..<HASH> 100644 --- a/test/src/main/java/org/vertexium/test/GraphTestBase.java +++ b/test/src/main/java/org/vertexium/test/GraphTestBase.java @@ -28,6 +28,7 @@ import org.vertexium.type.*; import org.vertexium.util.*; import java.io.ByteArrayInputStream; +import java.io.Closeable; import java.io.IOException; import java.io.InputStream; import java.math.BigDecimal; @@ -2476,6 +2477,41 @@ public abstract class GraphTestBase { } @Test + public void testClosingIterables() throws IOException { + graph.prepareVertex("v1", VISIBILITY_A) + .addPropertyValue("k1", "name", "joe", VISIBILITY_A) + .save(AUTHORIZATIONS_A); + + graph.prepareVertex("v2", VISIBILITY_A) + .addPropertyValue("k1", "name", "matt", VISIBILITY_A) + .save(AUTHORIZATIONS_A); + + graph.flush(); + + // Ensure that closing doesn't cause an error if we haven't iterated yet + Iterable<Vertex> vertices1 = graph.getVertices(AUTHORIZATIONS_A); + if (vertices1 instanceof Closeable) { + ((Closeable) vertices1).close(); + } + + // Ensure that closing doesn't cause an error if the iterable was fully traversed + vertices1 = graph.getVertices(AUTHORIZATIONS_A); + toList(vertices1); + if (vertices1 instanceof Closeable) { + ((Closeable) vertices1).close(); + } + + // Ensure that closing query results doesn't cause an error if we haven't iterated yet + QueryResultsIterable<Vertex> queryResults = graph.query(AUTHORIZATIONS_A).hasId("v1").vertices(); + queryResults.close(); + + // Ensure that closing query results doesn't cause an error if the iterable was fully traversed + queryResults = graph.query(AUTHORIZATIONS_A).hasId("v1").vertices(); + toList(queryResults); + queryResults.close(); + } + + @Test public void testGraphQueryWithFetchHints() { graph.prepareVertex("v1", VISIBILITY_A) .addPropertyValue("k1", "name", "joe", VISIBILITY_A)
Fix a NullPointerException if closing an iterable that was never used.
visallo_vertexium
train