hash
stringlengths
40
40
diff
stringlengths
131
114k
message
stringlengths
7
980
project
stringlengths
5
67
split
stringclasses
1 value
7bc4fb6add4186f93e090c65f155556db2ab46aa
diff --git a/lib/html/pipeline/camo_filter.rb b/lib/html/pipeline/camo_filter.rb index <HASH>..<HASH> 100644 --- a/lib/html/pipeline/camo_filter.rb +++ b/lib/html/pipeline/camo_filter.rb @@ -20,12 +20,10 @@ module HTML # go through the github asset proxy. def call doc.search("img").each do |element| - next if element['src'].nil? - src = element['src'].strip - src = src.sub(%r!^http://github.com!, 'https://github.com') - next if context[:disable_asset_proxy] - element['src'] = asset_proxy_url(src) + if src = element['src'] + element['src'] = asset_proxy_url(src) + end end doc end diff --git a/test/html/pipeline/camo_filter_test.rb b/test/html/pipeline/camo_filter_test.rb index <HASH>..<HASH> 100644 --- a/test/html/pipeline/camo_filter_test.rb +++ b/test/html/pipeline/camo_filter_test.rb @@ -18,12 +18,6 @@ class HTML::Pipeline::CamoFilterTest < Test::Unit::TestCase CamoFilter.call(orig, @options).to_s end - def test_rewrites_dotcom_image_urls - orig = %(<p><img src="http://github.com/img.png"></p>) - assert_equal "<p><img src=\"https://github.com/img.png\"></p>", - CamoFilter.call(orig, @options).to_s - end - def test_camouflaging_https_image_urls orig = %(<p><img src="https://foo.com/img.png"></p>) assert_includes 'img src="' + @asset_proxy_url,
Skip rewriting github.com origin images
jch_html-pipeline
train
2cde19f24c3679e8162e3abbce73818a8b0c02a0
diff --git a/src/Controller/Component/RequestHandlerComponent.php b/src/Controller/Component/RequestHandlerComponent.php index <HASH>..<HASH> 100644 --- a/src/Controller/Component/RequestHandlerComponent.php +++ b/src/Controller/Component/RequestHandlerComponent.php @@ -256,7 +256,7 @@ class RequestHandlerComponent extends Component public function convertXml($xml) { try { - $xml = Xml::build($xml); + $xml = Xml::build($xml, ['readFile' => false]); if (isset($xml->data)) { return Xml::toArray($xml->data); } diff --git a/src/Utility/Xml.php b/src/Utility/Xml.php index <HASH>..<HASH> 100644 --- a/src/Utility/Xml.php +++ b/src/Utility/Xml.php @@ -86,6 +86,9 @@ class Xml * - `return` Can be 'simplexml' to return object of SimpleXMLElement or 'domdocument' to return DOMDocument. * - `loadEntities` Defaults to false. Set to true to enable loading of `<!ENTITY` definitions. This * is disabled by default for security reasons. + * - `readFile` Set to false to disable file reading. This is important to disable when + * putting user data into Xml::build(). If enabled local files will be read if they exist. + * Defaults to true for backwards compatibility reasons. * - If using array as input, you can pass `options` from Xml::fromArray. * * @param string|array $input XML string, a path to a file, a URL or an array @@ -98,6 +101,7 @@ class Xml $defaults = [ 'return' => 'simplexml', 'loadEntities' => false, + 'readFile' => true ]; $options += $defaults; @@ -109,7 +113,7 @@ class Xml return static::_loadXml($input, $options); } - if (file_exists($input)) { + if ($options['readFile'] && file_exists($input)) { return static::_loadXml(file_get_contents($input), $options); } diff --git a/tests/TestCase/Controller/Component/RequestHandlerComponentTest.php b/tests/TestCase/Controller/Component/RequestHandlerComponentTest.php index <HASH>..<HASH> 100644 --- a/tests/TestCase/Controller/Component/RequestHandlerComponentTest.php +++ b/tests/TestCase/Controller/Component/RequestHandlerComponentTest.php @@ -507,6 +507,27 @@ class RequestHandlerComponentTest extends TestCase } /** + * Test that file handles are ignored as XML data. + * + * @return void + * @triggers Controller.startup $this->Controller + */ + public function testStartupIgnoreFileAsXml() + { + $this->Controller->request = $this->getMock('Cake\Network\Request', ['_readInput']); + $this->Controller->request->expects($this->any()) + ->method('_readInput') + ->will($this->returnValue('/dev/random')); + + $this->Controller->request->env('REQUEST_METHOD', 'POST'); + $this->Controller->request->env('CONTENT_TYPE', 'application/xml'); + + $event = new Event('Controller.startup', $this->Controller); + $this->RequestHandler->startup($event); + $this->assertEquals([], $this->Controller->request->data); + } + + /** * Test mapping a new type and having startup process it. * * @return void diff --git a/tests/TestCase/Utility/XmlTest.php b/tests/TestCase/Utility/XmlTest.php index <HASH>..<HASH> 100644 --- a/tests/TestCase/Utility/XmlTest.php +++ b/tests/TestCase/Utility/XmlTest.php @@ -116,6 +116,18 @@ class XmlTest extends TestCase } /** + * Test that the readFile option disables local file parsing. + * + * @expectedException \Cake\Utility\Exception\XmlException + * @return void + */ + public function testBuildFromFileWhenDisabled() + { + $xml = CORE_TESTS . 'Fixture/sample.xml'; + $obj = Xml::build($xml, ['readFile' => false]); + } + + /** * Test build() with a Collection instance. * * @return void
Add option to disable local XML file parsing. Provide an option to disable reading local files. This is very useful when accepting 'XML' data from request data. In this situation we don't want to parse local file as XML.
cakephp_cakephp
train
8da59c05bb55989ef1c87b702e32fe50cd604aac
diff --git a/lib/chore/airbrake.rb b/lib/chore/airbrake.rb index <HASH>..<HASH> 100644 --- a/lib/chore/airbrake.rb +++ b/lib/chore/airbrake.rb @@ -16,10 +16,9 @@ Chore.add_hook(:on_failure) do |msg,error| msg_class = msg['class'] || 'Unknown message class' airbrake_opts = {} - airbrake_opts[:action] = msg_class + airbrake_opts[:action] = msg_class.respond_to?(:underscore) ? msg_class.underscore : msg_class airbrake_opts[:parameters] = {:message => msg} - airbrake_opts[:environment_name] = "Chore" - airbrake_opts[:cgi_data] = ENV + airbrake_opts[:component] = 'chore' airbrake_opts.merge!(Chore::Airbrake.options) if Chore::Airbrake.options Chore.logger.debug {"Sending exception to airbrake. error: #{error}, opts: #{airbrake_opts}"} diff --git a/spec/chore/airbrake_spec.rb b/spec/chore/airbrake_spec.rb index <HASH>..<HASH> 100644 --- a/spec/chore/airbrake_spec.rb +++ b/spec/chore/airbrake_spec.rb @@ -34,14 +34,14 @@ describe Chore do # should be set by the class of the message expected_options[:action] = "TestJob" expected_options[:parameters] = {:message => $test_msg} - expected_options[:environment_name] = "Chore" + expected_options[:component] = "chore" expected_options end it "should send an airbrake exception if chore/airbrake as been required" do expected_options = get_default_airbrake_options - Airbrake.should_receive(:notify).with(kind_of(RuntimeError), hash_including(expected_options)) + Airbrake.should_receive(:notify).with(kind_of(RuntimeError), expected_options) Chore.run_hooks_for(:on_failure, $test_msg, RuntimeError.new("exception")) end @@ -53,7 +53,7 @@ describe Chore do expected_options = get_default_airbrake_options expected_options = expected_options.merge(additional_airbrake_options) - Airbrake.should_receive(:notify).with(kind_of(RuntimeError), hash_including(expected_options)) + Airbrake.should_receive(:notify).with(kind_of(RuntimeError), expected_options) Chore.run_hooks_for(:on_failure, $test_msg, RuntimeError.new("exception")) end
Update Airbrake integration to not include ENV and use more appropriate component / action values to bring it in line with other libraries like resque
Tapjoy_chore
train
14db5e4cac457aa55718bcc208551df82dcc9eb6
diff --git a/lib/search_engine_summarizer.py b/lib/search_engine_summarizer.py index <HASH>..<HASH> 100644 --- a/lib/search_engine_summarizer.py +++ b/lib/search_engine_summarizer.py @@ -90,7 +90,8 @@ def get_authors_tags(config=CITATION_CONFIG): tags_names = [ 'first_author', 'additional_author', - 'alternative_author_name' + 'alternative_author_name', + 'collaboration_name', ] tags = {} @@ -102,8 +103,8 @@ def get_authors_tags(config=CITATION_CONFIG): def get_authors_from_record(recID, tags): - """ - Get all authors for a record + """Get all authors for a record + We need this function because there's 3 different types of authors and to fetch each one of them we need look through MARC tags """ @@ -118,8 +119,17 @@ def get_authors_from_record(recID, tags): return authors -def get_coauthors(author, tags, cache): +def get_collaborations_from_record(recID, tags): + """ Get all collaborations for a record, + + Similar to get_authors_from_record """ + return set(get_fieldvalues(recID, tags['collaboration_name'])) + + +def get_coauthors(author, tags, cache): + """ Get all coauthors for an author + Given author A, returns all the authors having published a record with author A """ @@ -193,7 +203,7 @@ def summarize_records(recids, of, ln, searchpattern="", searchfield="", req=None if compute_self_citations: try: tags = get_authors_tags() - except IndexError, msg: + except (IndexError, ConfigParser.NoOptionError), msg: register_exception(prefix="attribute " + \ str(msg) + " missing in config", alert_admin=True) compute_self_citations = False @@ -211,15 +221,25 @@ def summarize_records(recids, of, ln, searchpattern="", searchfield="", req=None for recid, lciters in d_recid_citers[coll]: if lciters: authors = get_authors_from_record(recid, tags) - for cit in lciters: - cit_authors = get_authors_from_record(cit, tags) - #extend with circle of friends - for author in list(cit_authors)[:20]: - author_friends = get_coauthors(author, tags, authors_cache) - cit_authors.update(author_friends) - - if len(authors.intersection(cit_authors)) == 0: - d_total_cites[coll] += 1 + if len(authors) > 20: + # Use collaboration names + collaborations = get_collaborations_from_record(recid, tags) + for cit in lciters: + cit_collaborations = get_collaborations_from_record(cit, tags) + if len(collaborations.intersection(cit_collaborations)) == 0: + d_total_cites[coll] += 1 + + else: + # Use author names + for cit in lciters: + cit_authors = get_authors_from_record(cit, tags) + #extend with circle of friends + for author in list(cit_authors)[:20]: + author_friends = get_coauthors(author, tags, authors_cache) + cit_authors.update(author_friends) + + if len(authors.intersection(cit_authors)) == 0: + d_total_cites[coll] += 1 if d_total_cites[coll] != 0: d_avg_cites[coll] = d_total_cites[coll] * 1.0 / d_total_recs[coll]
WebSearch: use collaborations in self-cite counts * Use collaboration name for records having more than <I> authors when calculating self-citations.
inveniosoftware_invenio-records
train
0553ce8f300524e690c0589d5257e01d99f53a61
diff --git a/traits/magic/iterator.php b/traits/magic/iterator.php index <HASH>..<HASH> 100644 --- a/traits/magic/iterator.php +++ b/traits/magic/iterator.php @@ -31,63 +31,60 @@ trait Iterator * Current position of the Iterator. Incremented by `next` & reset by `rewind` * @var int */ - protected $iterator_position = 0; + protected $_iterator_position = 0; /** - * Gets the value @ $iterator_position + * Gets the value @ $_iterator_position * * @param void * @return mixed Whatever the current value is */ final public function current() { - return array_values($this->{$this::MAGIC_PROPERTY})[$this->iterator_position]; + return $this->{$this::MAGIC_PROPERTY}[$this->key()]; } /** - * Returns the original key (not $iterator_position) at the current position + * Returns the original key (not $_iterator_position) at the current position * * @param void * @return mixed Probably a string, but could be an integer. */ final public function key() { - return array_keys($this->{$this::MAGIC_PROPERTY})[$this->iterator_position]; + return @array_keys($this->{$this::MAGIC_PROPERTY})[$this->_iterator_position]; } /** - * Increment $iterator_position + * Increment $_iterator_position * * @param void * @return void */ final public function next() { - ++$this->iterator_position; + ++$this->_iterator_position; } /** - * Reset $iterator_position to 0 + * Reset $_iterator_position to 0 * * @param void * @return void */ final public function rewind() { - $this->iterator_position = 0; + $this->_iterator_position = 0; } /** - * Checks if data is set for current $iterator_position + * Checks if data is set for current $_iterator_position * * @param void * @return bool Whether or not there is data set at current position */ final public function valid() { - return array_key_exists( - $this->iterator_position, - array_values($this->{$this::MAGIC_PROPERTY}) - ); + return count($this->{$this::MAGIC_PROPERTY}) > $this->_iterator_position; } }
Updates to Iterator trait * Renamed `$iterator_position` to `$_iterator_position` * `current` now uses `$this->key()` instead of internal code * `valid` now does a length comparison
shgysk8zer0_core_api
train
34a33954d7845311fc99354ef282cbfdacda0245
diff --git a/pylint/__pkginfo__.py b/pylint/__pkginfo__.py index <HASH>..<HASH> 100644 --- a/pylint/__pkginfo__.py +++ b/pylint/__pkginfo__.py @@ -22,7 +22,7 @@ import sys modname = distname = 'pylint' -numversion = (1, 4, 3) +numversion = (1, 5, 0) version = '.'.join([str(num) for num in numversion]) install_requires = [
Update the version to reflect what will be released. Some users are using the repo's version and it's misleading to have the same version for the released code.
PyCQA_pylint
train
4528e7b556b771bab60d740fc35058c14c8b0421
diff --git a/index.js b/index.js index <HASH>..<HASH> 100644 --- a/index.js +++ b/index.js @@ -1,3 +1,28 @@ -module.exports.cli = function() { - console.log("WIP"); -} +var Interface = require('./lib/interface.js'); + +module.exports.start = function(argv, stdin, stdout) { + argv || (argv = process.argv.slice(2)); + + if (argv.length < 1) { + console.error('Usage: node debug script.js'); + process.exit(1); + } + + // Setup input/output streams + stdin = stdin || process.stdin; + stdout = stdout || process.stdout; + + var args = ['--debug-brk'].concat(argv), + interface_ = new Interface(stdin, stdout, args); + + stdin.resume(); + + process.on('uncaughtException', function(e) { + console.error("There was an internal error in Node's debugger. " + + 'Please report this bug.'); + console.error(e.message); + console.error(e.stack); + if (interface_.child) interface_.child.kill(); + process.exit(1); + }); +};
construct interface. Code pasted from src/node.js
sidorares_node-cli-debugger
train
3f0d98e34b326dd7f764abf2b3cca666e4b99907
diff --git a/agent.go b/agent.go index <HASH>..<HASH> 100644 --- a/agent.go +++ b/agent.go @@ -710,11 +710,6 @@ func (s *sandbox) listenToUdevEvents() { continue } - // We only care about add event - if uEv.Action != "add" { - continue - } - span, _ := trace(rootContext, "udev", "udev event") span.setTag("udev-action", uEv.Action) span.setTag("udev-name", uEv.DevName) @@ -730,6 +725,18 @@ func (s *sandbox) listenToUdevEvents() { "uevent-devname": uEv.DevName, }) + if uEv.Action == "remove" { + fieldLogger.Infof("Remove dev from pciDeviceMap") + s.Lock() + delete(s.pciDeviceMap, uEv.DevPath) + s.Unlock() + goto FINISH_SPAN + } + + if uEv.Action != "add" { + goto FINISH_SPAN + } + fieldLogger.Infof("Received add uevent") // Check if device hotplug event results in a device node being created. @@ -782,7 +789,7 @@ func (s *sandbox) listenToUdevEvents() { fieldLogger.WithError(err).Error("failed online device") } } - + FINISH_SPAN: span.finish() } }
agent: Remove dev from pciDeviceMap when device is unplugged Delete `uEv.DevPath` from pciDeviceMap when recieving `remove` uevent. Fixes #<I>
kata-containers_agent
train
0301040e48c4c15565787419ab9cf1f99f7895af
diff --git a/libdokan/mount_test.go b/libdokan/mount_test.go index <HASH>..<HASH> 100644 --- a/libdokan/mount_test.go +++ b/libdokan/mount_test.go @@ -1826,7 +1826,7 @@ func TestInvalidateDataOnWrite(t *testing.T) { defer libkbfs.CleanupCancellationDelayer(ctx) config := libkbfs.MakeTestConfigOrBust(t, "jdoe", "wsmith") defer libkbfs.CheckConfigAndShutdown(ctx, t, config) - mnt1, fs1, cancelFn1 := makeFS(t, ctx, config) + mnt1, _, cancelFn1 := makeFS(t, ctx, config) defer mnt1.Close() defer cancelFn1() mnt2, fs2, cancelFn2 := makeFSE(t, ctx, config, 'U') @@ -2182,7 +2182,7 @@ func TestInvalidateAcrossMounts(t *testing.T) { config1 := libkbfs.MakeTestConfigOrBust(t, "user1", "user2") defer libkbfs.CheckConfigAndShutdown(ctx, t, config1) - mnt1, _, cancelFn1 := makeFS(t, ctx, config1) + mnt1, fs1, cancelFn1 := makeFS(t, ctx, config1) defer mnt1.Close() defer cancelFn1() @@ -2455,7 +2455,7 @@ func TestUnstageFile(t *testing.T) { defer libkbfs.CleanupCancellationDelayer(ctx) config1 := libkbfs.MakeTestConfigOrBust(t, "user1", "user2") defer libkbfs.CheckConfigAndShutdown(ctx, t, config1) - mnt1, _, cancelFn1 := makeFS(t, ctx, config1) + mnt1, fs1, cancelFn1 := makeFS(t, ctx, config1) defer mnt1.Close() defer cancelFn1()
libdokan: fix mount tests by declaring fs1 variable Issue: KBFS-<I>
keybase_client
train
b381e1a97306d3709e2913de327e7870a7896576
diff --git a/concrete/src/Asset/CssAsset.php b/concrete/src/Asset/CssAsset.php index <HASH>..<HASH> 100644 --- a/concrete/src/Asset/CssAsset.php +++ b/concrete/src/Asset/CssAsset.php @@ -17,6 +17,13 @@ class CssAsset extends Asset protected $assetSupportsCombination = true; /** + * The default media of this asset. + * + * @var string + */ + protected $media = 'all'; + + /** * @return string */ public function getAssetDefaultPosition() @@ -33,6 +40,26 @@ class CssAsset extends Asset } /** + * Set the media of this asset. + * + * @param string $media + */ + public function setAssetMedia($media) + { + $this->media = $media; + } + + /** + * Get the media of this asset. + * + * @return string + */ + public function getAssetMedia() + { + return $this->media; + } + + /** * @return string */ protected static function getRelativeOutputDirectory() @@ -176,11 +203,24 @@ class CssAsset extends Asset } /** + * {@inheritdoc} + * + * @see \Concrete\Core\Asset\AssetInterface::register() + */ + public function register($filename, $args, $pkg = false) + { + parent::register($filename, $args, $pkg); + if ($args['media']) { + $this->setAssetMedia($args['media']); + } + } + + /** * @return string */ public function __toString() { - $e = new HeadLink($this->getAssetURL(), 'stylesheet', 'text/css', 'all'); + $e = new HeadLink($this->getAssetURL(), 'stylesheet', 'text/css', $this->getAssetMedia()); if (count($this->combinedAssetSourceFiles)) { $source = ''; foreach ($this->combinedAssetSourceFiles as $file) {
Added support for the "media" attribute for CSS resources
concrete5_concrete5
train
6a7598b00717fc2531ad737abd931d41fe18ac89
diff --git a/suro-client/src/main/java/com/netflix/suro/client/async/AsyncSuroClient.java b/suro-client/src/main/java/com/netflix/suro/client/async/AsyncSuroClient.java index <HASH>..<HASH> 100644 --- a/suro-client/src/main/java/com/netflix/suro/client/async/AsyncSuroClient.java +++ b/suro-client/src/main/java/com/netflix/suro/client/async/AsyncSuroClient.java @@ -16,6 +16,7 @@ package com.netflix.suro.client.async; +import com.google.common.annotations.VisibleForTesting; import com.google.common.util.concurrent.ThreadFactoryBuilder; import com.google.inject.Inject; import com.netflix.config.DynamicIntProperty; @@ -112,7 +113,19 @@ public class AsyncSuroClient implements ISuroClient { poller.execute(createPoller()); - jobQueue = new ArrayBlockingQueue<Runnable>(config.getAsyncJobQueueCapacity()); + jobQueue = new ArrayBlockingQueue<Runnable>(config.getAsyncJobQueueCapacity()) + { + @Override + public boolean offer(Runnable runnable) { + try { + put(runnable); // not to reject the task, slowing down + } catch (InterruptedException e) { + // do nothing + } + return true; + } + } + ; senders = new ThreadPoolExecutor( config.getAsyncSenderThreads(), config.getAsyncSenderThreads(), @@ -154,6 +167,9 @@ public class AsyncSuroClient implements ISuroClient { send(message); } + @VisibleForTesting + protected long queuedMessageSetCount = 0; + private boolean running; private long lastBatch; @@ -181,6 +197,7 @@ public class AsyncSuroClient implements ISuroClient { lastBatch = System.currentTimeMillis(); rateLimiter.pause(builder.size()); senders.execute(new AsyncSuroSender(builder.build(), client, config)); + ++queuedMessageSetCount; } else if (builder.size() == 0) { Thread.sleep(config.getAsyncTimeout()); } @@ -192,6 +209,7 @@ public class AsyncSuroClient implements ISuroClient { builder.drainFrom(messageQueue, (int) messageQueue.size()); if (builder.size() > 0) { senders.execute(new AsyncSuroSender(builder.build(), client, config)); + ++queuedMessageSetCount; } } }; @@ -205,13 +223,11 @@ public class AsyncSuroClient implements ISuroClient { poller.awaitTermination(5000 + config.getAsyncTimeout(), TimeUnit.MILLISECONDS); if (!poller.isTerminated()) { log.error("AsyncSuroClient.poller didn't terminate gracefully within {} seconds", (5 + config.getAsyncTimeout()/1000)); - poller.shutdownNow(); } senders.shutdown(); senders.awaitTermination(5000 + config.getAsyncTimeout(), TimeUnit.MILLISECONDS); if (!senders.isTerminated()) { log.error("AsyncSuroClient.senders didn't terminate gracefully within {} seconds", (5 + config.getAsyncTimeout()/1000)); - senders.shutdownNow(); } } catch (InterruptedException e) { // ignore exceptions while shutting down diff --git a/suro-client/src/test/java/com/netflix/suro/client/async/TestAsyncSuroClient.java b/suro-client/src/test/java/com/netflix/suro/client/async/TestAsyncSuroClient.java index <HASH>..<HASH> 100644 --- a/suro-client/src/test/java/com/netflix/suro/client/async/TestAsyncSuroClient.java +++ b/suro-client/src/test/java/com/netflix/suro/client/async/TestAsyncSuroClient.java @@ -66,8 +66,6 @@ public class TestAsyncSuroClient { } private void setupFile(final Properties props) throws Exception { - servers = TestConnectionPool.startServers(3); - props.put(ClientConfig.LB_SERVER, TestConnectionPool.createConnectionString(servers)); props.put(ClientConfig.ASYNC_FILEQUEUE_PATH, tempDir.newFolder().getAbsolutePath()); props.put(ClientConfig.ASYNC_QUEUE_TYPE, "file"); @@ -187,4 +185,27 @@ public class TestAsyncSuroClient { long duration = System.currentTimeMillis() - start; assertTrue(duration >= 5000); } + + @Test + public void shouldBeBlockedOnJobQueueFull() throws Exception { + for (SuroServer4Test c : servers) { + c.setHoldConnection(); + } + Properties props = new Properties(); + props.setProperty(ClientConfig.ASYNC_JOBQUEUE_CAPACITY, "1"); + props.setProperty(ClientConfig.ASYNC_SENDER_THREADS, "1"); + props.setProperty(ClientConfig.CONNECTION_TIMEOUT, Integer.toString(Integer.MAX_VALUE)); + + setupFile(props); + + AsyncSuroClient client = injector.getInstance(AsyncSuroClient.class); + + for (int i = 0; i < 3000; ++i) { + client.send(new Message("routingKey", "testMessage".getBytes())); + } + client.shutdown(); + + assertEquals(client.queuedMessageSetCount, 2); + + } }
AsyncSuroClient jobQueue is blocked on offer()
Netflix_suro
train
09b4d371d203f7f22dcf1741a3f6c657404fb61e
diff --git a/src/TestFramework/PhpSpec/CommandLine/ArgumentsAndOptionsBuilder.php b/src/TestFramework/PhpSpec/CommandLine/ArgumentsAndOptionsBuilder.php index <HASH>..<HASH> 100644 --- a/src/TestFramework/PhpSpec/CommandLine/ArgumentsAndOptionsBuilder.php +++ b/src/TestFramework/PhpSpec/CommandLine/ArgumentsAndOptionsBuilder.php @@ -44,14 +44,18 @@ final class ArgumentsAndOptionsBuilder implements CommandLineArgumentsAndOptions { public function build(string $configPath, string $extraOptions): array { - return array_filter([ - 'run', - '--config', - $configPath, - '--no-ansi', - '--format=tap', - '--stop-on-failure', - $extraOptions, - ]); + $options = array_merge( + [ + 'run', + '--config', + $configPath, + '--no-ansi', + '--format=tap', + '--stop-on-failure', + ], + explode(' ', $extraOptions) + ); + + return array_filter($options); } } diff --git a/src/TestFramework/PhpUnit/CommandLine/ArgumentsAndOptionsBuilder.php b/src/TestFramework/PhpUnit/CommandLine/ArgumentsAndOptionsBuilder.php index <HASH>..<HASH> 100644 --- a/src/TestFramework/PhpUnit/CommandLine/ArgumentsAndOptionsBuilder.php +++ b/src/TestFramework/PhpUnit/CommandLine/ArgumentsAndOptionsBuilder.php @@ -44,10 +44,14 @@ final class ArgumentsAndOptionsBuilder implements CommandLineArgumentsAndOptions { public function build(string $configPath, string $extraOptions): array { - return array_filter([ - '--configuration', - $configPath, - $extraOptions, - ]); + $options = array_merge( + [ + '--configuration', + $configPath, + ], + explode(' ', $extraOptions) + ); + + return array_filter($options); } } diff --git a/tests/TestFramework/PhpSpec/CommandLine/ArgumentsAndOptionsBuilderTest.php b/tests/TestFramework/PhpSpec/CommandLine/ArgumentsAndOptionsBuilderTest.php index <HASH>..<HASH> 100644 --- a/tests/TestFramework/PhpSpec/CommandLine/ArgumentsAndOptionsBuilderTest.php +++ b/tests/TestFramework/PhpSpec/CommandLine/ArgumentsAndOptionsBuilderTest.php @@ -57,8 +57,9 @@ final class ArgumentsAndOptionsBuilderTest extends TestCase '--format=tap', '--stop-on-failure', '--verbose', + '--debug', ], - $builder->build($configPath, '--verbose') + $builder->build($configPath, '--verbose --debug') ); } diff --git a/tests/TestFramework/PhpUnit/CommandLine/ArgumentsAndOptionsBuilderTest.php b/tests/TestFramework/PhpUnit/CommandLine/ArgumentsAndOptionsBuilderTest.php index <HASH>..<HASH> 100644 --- a/tests/TestFramework/PhpUnit/CommandLine/ArgumentsAndOptionsBuilderTest.php +++ b/tests/TestFramework/PhpUnit/CommandLine/ArgumentsAndOptionsBuilderTest.php @@ -53,8 +53,9 @@ final class ArgumentsAndOptionsBuilderTest extends TestCase '--configuration', $configPath, '--verbose', + '--debug', ], - $builder->build($configPath, '--verbose') + $builder->build($configPath, '--verbose --debug') ); }
Multiple extra test framework options escape in the wrong way (#<I>) * Multiple extra test framework options escape in the wrong way * Ensure multiple test framework options work as expected
infection_infection
train
18ce711cc71da90d7f0d690bc5617d4626d6ce02
diff --git a/packages/ember-metal/lib/mixin.js b/packages/ember-metal/lib/mixin.js index <HASH>..<HASH> 100644 --- a/packages/ember-metal/lib/mixin.js +++ b/packages/ember-metal/lib/mixin.js @@ -76,7 +76,7 @@ function mergeMixins(mixins, m, descs, values, base) { for(idx=0;idx<len;idx++) { mixin = mixins[idx]; - Ember.assert('Null value found in Ember.mixin()', !!mixin); + Ember.assert('Expected hash or Mixin instance, got ' + Object.prototype.toString.call(mixin), typeof mixin === 'object' && mixin !== null && Object.prototype.toString.call(mixin) !== '[object Array]'); if (mixin instanceof Mixin) { guid = Ember.guidFor(mixin); @@ -388,7 +388,8 @@ Mixin.prototype.reopen = function() { for(idx=0;idx<len;idx++) { mixin = arguments[idx]; - Ember.assert("Expected Mixin or hash, got null or undefined.", !!mixin); + Ember.assert('Expected hash or Mixin instance, got ' + Object.prototype.toString.call(mixin), typeof mixin === 'object' && mixin !== null && Object.prototype.toString.call(mixin) !== '[object Array]'); + if (mixin instanceof Mixin) { mixins.push(mixin); } else {
Guard mergeMixins parameters more generally Previously we caught passing null or undefined into Object.create() or .extend(). Now we also catch any other invalid types like strings, numbers, or arrays. We cannot use Ember.typeOf, since runtime depends on metal and we don't want circular dependencies. For the weird array check, see <URL>
emberjs_ember.js
train
b165874d74c3a8a476abbfc1a801df656623c6be
diff --git a/src/Command/ProjectDownloadTrait.php b/src/Command/ProjectDownloadTrait.php index <HASH>..<HASH> 100644 --- a/src/Command/ProjectDownloadTrait.php +++ b/src/Command/ProjectDownloadTrait.php @@ -93,35 +93,31 @@ trait ProjectDownloadTrait $fileSystem->rename($downloadPath, $copyPath); } catch (IOExceptionInterface $e) { $io->commentBlock( - sprintf( - $this->trans('commands.site.new.messages.downloaded'), - $version, - $downloadPath - ) + sprintf( + $this->trans('commands.site.new.messages.downloaded'), + $version, + $downloadPath + ) ); $io->error( - sprintf( - $this->trans('commands.site.new.messages.error-copying'), - $e->getPath() - ) + sprintf( + $this->trans('commands.site.new.messages.error-copying'), + $e->getPath() + ) ); return; } $io->success( - sprintf( - $this->trans('commands.site.new.messages.downloaded'), - $version, - $copyPath - ) + sprintf( + $this->trans('commands.site.new.messages.downloaded'), + $version, + $copyPath + ) ); } - - - - } catch (\Exception $e) { $io->error($e->getMessage());
[console] relocate code to Trait to test TravisCI
hechoendrupal_drupal-console
train
132a1a6c9436090349968f7f28d6c81dd288ff72
diff --git a/lib/bullet/stack_trace_filter.rb b/lib/bullet/stack_trace_filter.rb index <HASH>..<HASH> 100644 --- a/lib/bullet/stack_trace_filter.rb +++ b/lib/bullet/stack_trace_filter.rb @@ -1,6 +1,6 @@ module Bullet module StackTraceFilter - VENDOR_PATH = "/vendor".freeze + VENDOR_PATH = '/vendor'.freeze def caller_in_project app_root = rails? ? Rails.root.to_s : Dir.pwd diff --git a/lib/bullet/version.rb b/lib/bullet/version.rb index <HASH>..<HASH> 100644 --- a/lib/bullet/version.rb +++ b/lib/bullet/version.rb @@ -1,4 +1,4 @@ module Bullet - VERSION = "5.6.0".freeze + VERSION = '5.6.0'.freeze end
Auto corrected by following Style/StringLiterals
flyerhzm_bullet
train
8324c1b9a6dd46a66c4105452b2af93263ee536b
diff --git a/tlsutil/config.go b/tlsutil/config.go index <HASH>..<HASH> 100644 --- a/tlsutil/config.go +++ b/tlsutil/config.go @@ -187,39 +187,6 @@ func (c *Config) OutgoingTLSConfig() (*tls.Config, error) { return tlsConfig, nil } -// Clone returns a copy of c. Only the exported fields are copied. This -// was copied from https://golang.org/src/crypto/tls/common.go since that -// isn't exported and Go 1.7's vet uncovered an unsafe copy of a mutex in -// here. -// -// TODO (slackpad) - This can be removed once we move to Go 1.8, see -// https://github.com/golang/go/commit/d24f446 for details. -func clone(c *tls.Config) *tls.Config { - return &tls.Config{ - Rand: c.Rand, - Time: c.Time, - Certificates: c.Certificates, - NameToCertificate: c.NameToCertificate, - GetCertificate: c.GetCertificate, - RootCAs: c.RootCAs, - NextProtos: c.NextProtos, - ServerName: c.ServerName, - ClientAuth: c.ClientAuth, - ClientCAs: c.ClientCAs, - InsecureSkipVerify: c.InsecureSkipVerify, - CipherSuites: c.CipherSuites, - PreferServerCipherSuites: c.PreferServerCipherSuites, - SessionTicketsDisabled: c.SessionTicketsDisabled, - SessionTicketKey: c.SessionTicketKey, - ClientSessionCache: c.ClientSessionCache, - MinVersion: c.MinVersion, - MaxVersion: c.MaxVersion, - CurvePreferences: c.CurvePreferences, - DynamicRecordSizingDisabled: c.DynamicRecordSizingDisabled, - Renegotiation: c.Renegotiation, - } -} - // OutgoingTLSWrapper returns a a DCWrapper based on the OutgoingTLS // configuration. If hostname verification is on, the wrapper // will properly generate the dynamic server name for verification. @@ -245,7 +212,7 @@ func (c *Config) OutgoingTLSWrapper() (DCWrapper, error) { // Generate the wrapper based on hostname verification if c.VerifyServerHostname { wrapper = func(dc string, conn net.Conn) (net.Conn, error) { - conf := clone(tlsConfig) + conf := tlsConfig.Clone() conf.ServerName = "server." + dc + "." + domain return WrapTLSClient(conn, conf) }
Removes stale TLS config clone() in favor of new supported method.
hashicorp_consul
train
8ba6e2e88628ec5dd95a701ce42ad0fd0f6d8c26
diff --git a/pyclustering/nnet/som.py b/pyclustering/nnet/som.py index <HASH>..<HASH> 100755 --- a/pyclustering/nnet/som.py +++ b/pyclustering/nnet/som.py @@ -610,11 +610,12 @@ class som: """ self._data = data - self._sqrt_distances = self.__initialize_distances(self._size, self._location) if self.__ccore_som_pointer is not None: return wrapper.som_train(self.__ccore_som_pointer, data, epochs, autostop) - + + self._sqrt_distances = self.__initialize_distances(self._size, self._location) + for i in range(self._size): self._award[i] = 0 self._capture_objects[i].clear()
#<I>: Correction for previously introduced problem with CCORE.
annoviko_pyclustering
train
b3a09e601ab89125c5d5e8d5f42a41093bca5419
diff --git a/wro4j-core/src/test/java/ro/isdc/wro/http/handler/TestResourceProxyRequestHandler.java b/wro4j-core/src/test/java/ro/isdc/wro/http/handler/TestResourceProxyRequestHandler.java index <HASH>..<HASH> 100644 --- a/wro4j-core/src/test/java/ro/isdc/wro/http/handler/TestResourceProxyRequestHandler.java +++ b/wro4j-core/src/test/java/ro/isdc/wro/http/handler/TestResourceProxyRequestHandler.java @@ -6,6 +6,10 @@ import org.junit.Test; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import ro.isdc.wro.config.Context; +import ro.isdc.wro.manager.factory.BaseWroManagerFactory; +import ro.isdc.wro.model.group.processor.InjectorBuilder; +import ro.isdc.wro.model.resource.locator.UriLocator; +import ro.isdc.wro.model.resource.locator.factory.UriLocatorFactory; import ro.isdc.wro.util.WroTestUtils; import ro.isdc.wro.util.WroUtil; @@ -18,8 +22,8 @@ import java.io.*; import static org.hamcrest.core.Is.is; import static org.junit.Assert.assertThat; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; +import static org.mockito.Matchers.anyString; +import static org.mockito.Mockito.*; /** * @author Ivar Conradi Østhus @@ -85,13 +89,37 @@ public class TestResourceProxyRequestHandler { victim.handle(request, response); String body = outputStream.toString(); - String expectedBody = loadTestResource("test.css"); + String expectedBody = IOUtils.toString(getInputStream("test.css")); assertThat(body, is(expectedBody)); } - private String loadTestResource(String filename) throws IOException { - InputStream is = this.getClass().getClassLoader().getResourceAsStream(packagePath + "/" + filename); - return IOUtils.toString(is); + @Test + public void shouldReturnRelativeResource() + throws IOException { + String resourceUri = "/" + packagePath + "/" + "test.css"; + + //Set up victim + UriLocatorFactory uriLocatorFactory = mock(UriLocatorFactory.class); + UriLocator uriLocator = mock(UriLocator.class); + final BaseWroManagerFactory factory = new BaseWroManagerFactory(); + factory.setUriLocatorFactory(uriLocatorFactory); + when(uriLocatorFactory.getInstance(anyString())).thenReturn(uriLocator); + when(uriLocator.locate(resourceUri)).thenReturn(getInputStream("test.css")); + when(request.getParameter(ResourceProxyRequestHandler.PARAM_RESOURCE_ID)).thenReturn(resourceUri); + victim = new ResourceProxyRequestHandler(); + InjectorBuilder.create(factory).build().inject(victim); + + //Perform Action + victim.handle(request, response); + String body = outputStream.toString(); + String expectedBody = IOUtils.toString(getInputStream("test.css")); + + verify(uriLocator, times(1)).locate(resourceUri); + assertThat(body, is(expectedBody)); + } + + private InputStream getInputStream(String filename) throws IOException { + return this.getClass().getClassLoader().getResourceAsStream(packagePath + "/" + filename); } }
Issue<I> - Added new test case
wro4j_wro4j
train
9c5303285ad3844569537d16ca548809e9c53aa6
diff --git a/core/model/VirtualPage.php b/core/model/VirtualPage.php index <HASH>..<HASH> 100755 --- a/core/model/VirtualPage.php +++ b/core/model/VirtualPage.php @@ -30,8 +30,9 @@ class VirtualPage extends Page { "Sort", "Status", 'ShowInMenus', - 'ShowInSearch', // 'Locale' + 'ShowInSearch', + 'Version', ); $allFields = $this->db(); diff --git a/tests/model/VirtualPageTest.php b/tests/model/VirtualPageTest.php index <HASH>..<HASH> 100644 --- a/tests/model/VirtualPageTest.php +++ b/tests/model/VirtualPageTest.php @@ -210,6 +210,29 @@ class VirtualPageTest extends SapphireTest { $this->assertFalse($vp->IsModifiedOnStage); } + function testVirtualPagesCreateVersionRecords() { + $source = $this->objFromFixture('Page', 'master'); + $source->Title = "T0"; + $source->write(); + + // Creating a new VP to ensure that Version #s are out of alignment + $vp = new VirtualPage(); + $vp->CopyContentFromID = $source->ID; + $vp->write(); + + $source->Title = "T1"; + $source->write(); + $source->Title = "T2"; + $source->write(); + + $this->assertEquals($vp->ID, DB::query("SELECT \"RecordID\" FROM \"SiteTree_versions\" + WHERE \"RecordID\" = $vp->ID AND \"Title\" = 'T1'")->value()); + $this->assertEquals($vp->ID, DB::query("SELECT \"RecordID\" FROM \"SiteTree_versions\" + WHERE \"RecordID\" = $vp->ID AND \"Title\" = 'T2'")->value()); + $this->assertEquals($vp->ID, DB::query("SELECT \"RecordID\" FROM \"SiteTree_versions\" + WHERE \"RecordID\" = $vp->ID AND \"Version\" = $vp->Version")->value()); + } + function fixVersionNumberCache($page) { $pages = func_get_args(); foreach($pages as $p) {
BUGFIX: Generate SiteTree_version records for VirtualPages more reliably. (from r<I>) (from r<I>) git-svn-id: svn://svn.silverstripe.com/silverstripe/open/modules/sapphire/trunk@<I> <I>b<I>ca-7a2a-<I>-9d3b-<I>d<I>a<I>a9
silverstripe_silverstripe-framework
train
a4e7711756611bcf03d2df6724903110cf219f4d
diff --git a/app/index.js b/app/index.js index <HASH>..<HASH> 100644 --- a/app/index.js +++ b/app/index.js @@ -233,7 +233,7 @@ JhipsterGenerator.prototype.askFor = function askFor() { }, { when: function (response) { - return (!(response.javaVersion == '7')); + return (!(response.javaVersion == '7') && response.databaseType == 'sql'); }, type: 'list', name: 'searchEngine',
Limit ElasticSearch support to SQL databases
jhipster_generator-jhipster
train
5cff9bf1548cc0fe45cb0060f86e99d069721d2b
diff --git a/angr/simos/javavm.py b/angr/simos/javavm.py index <HASH>..<HASH> 100644 --- a/angr/simos/javavm.py +++ b/angr/simos/javavm.py @@ -29,6 +29,9 @@ class SimJavaVM(SimOS): self.native_libs = [obj for obj in self.project.loader.initial_load_objects if not isinstance(obj.arch, ArchSoot)] + if len(self.native_libs) == 0: + raise AngrSimOSError("No native lib was loaded. Is the native_libs_ld_path set correctly?") + # Step 2: determine and set the native SimOS from . import os_mapping # import dynamically, since the JavaVM class is part of the os_mapping dict # for each native library get the Arch
Add more helpful error message, if no native libraries were loaded.
angr_angr
train
7d4f1b1c2af69395ed4ac771241883b56079812b
diff --git a/yarn_api_client/base.py b/yarn_api_client/base.py index <HASH>..<HASH> 100644 --- a/yarn_api_client/base.py +++ b/yarn_api_client/base.py @@ -38,7 +38,8 @@ class BaseYarnAPI(object): if response.status == OK: return self.response_class(response) else: - msg = 'Response finished with status: %s' % response.status + explanation = response.read() + msg = 'Response finished with status: %s. Details: %s' % (response.status, explanation) raise APIError(msg) def construct_parameters(self, arguments):
Read response before raising the exception One MUST read response before launching a new request. Otherwise it is imposible to get a new response object
toidi_hadoop-yarn-api-python-client
train
adb62d8be6b89b0d8beb1e4866ef16e1026f3c10
diff --git a/cmd2/cmd2.py b/cmd2/cmd2.py index <HASH>..<HASH> 100644 --- a/cmd2/cmd2.py +++ b/cmd2/cmd2.py @@ -495,6 +495,9 @@ class Cmd(cmd.Cmd): # will be added if there is an unmatched opening quote self.allow_closing_quote = True + # An optional header that prints above the tab-completion suggestions + self.completion_header = '' + # If the tab-completion suggestions should be displayed in a way that is different than the actual match values, # then place those results in this list. The full matches still must be returned from your completer function. # For an example, look at path_complete() which uses this to show only the basename of paths as the @@ -661,6 +664,7 @@ class Cmd(cmd.Cmd): """ self.allow_appended_space = True self.allow_closing_quote = True + self.completion_header = '' self.display_matches = [] self.matches_delimited = False @@ -1254,6 +1258,10 @@ class Cmd(cmd.Cmd): strings_array[1:-1] = encoded_matches strings_array[-1] = None + # Print the header if one exists + if self.completion_header: + self.stdout.write('\n' + self.completion_header) + # Call readline's display function # rl_display_match_list(strings_array, number of completion matches, longest match length) readline_lib.rl_display_match_list(strings_array, len(encoded_matches), longest_match_length) @@ -1279,6 +1287,10 @@ class Cmd(cmd.Cmd): # Add padding for visual appeal matches_to_display, _ = self._pad_matches_to_display(matches_to_display) + # Print the header if one exists + if self.completion_header: + readline.rl.mode.console.write('\n' + self.completion_header) + # Display matches using actual display function. This also redraws the prompt and line. orig_pyreadline_display(matches_to_display)
Added ability to print a header above tab-completion suggestions
python-cmd2_cmd2
train
40629ca49bef1a864b2d94593335eac7c927b084
diff --git a/framework/yii/helpers/BaseFileHelper.php b/framework/yii/helpers/BaseFileHelper.php index <HASH>..<HASH> 100644 --- a/framework/yii/helpers/BaseFileHelper.php +++ b/framework/yii/helpers/BaseFileHelper.php @@ -155,6 +155,11 @@ class BaseFileHelper * and '.svn/' matches directory paths ending with '.svn'. Note, the '/' characters in a pattern matches * both '/' and '\' in the paths. * - recursive: boolean, whether the files under the subdirectories should also be copied. Defaults to true. + * - beforeCopy: callback, a PHP callback that is called before copying each sub-directory or file. + * This option is used only when publishing a directory. If the callback returns false, the copy + * operation for the sub-directory or file will be cancelled. + * The signature of the callback should be: `function ($from, $to)`, where `$from` is the sub-directory or + * file to be copied from, while `$to` is the copy target. * - afterCopy: callback, a PHP callback that is called after each sub-directory or file is successfully copied. * The signature of the callback should be: `function ($from, $to)`, where `$from` is the sub-directory or * file copied from, while `$to` is the copy target. @@ -173,6 +178,9 @@ class BaseFileHelper $from = $src . DIRECTORY_SEPARATOR . $file; $to = $dst . DIRECTORY_SEPARATOR . $file; if (static::filterPath($from, $options)) { + if (isset($options['beforeCopy'])) { + call_user_func($options['beforeCopy'], $from, $to); + } if (is_file($from)) { copy($from, $to); if (isset($options['fileMode'])) {
Added missing beforeCopy option to FileHelper::copyDirectory It was mentioned in AssetManager::publish phpdoc.
yiisoft_yii2-bootstrap4
train
8e4b12f1c0c0623c5fb335c9a5deac8bfda305dd
diff --git a/kernel/classes/workflowtypes/event/ezmultiplexer/ezmultiplexertype.php b/kernel/classes/workflowtypes/event/ezmultiplexer/ezmultiplexertype.php index <HASH>..<HASH> 100644 --- a/kernel/classes/workflowtypes/event/ezmultiplexer/ezmultiplexertype.php +++ b/kernel/classes/workflowtypes/event/ezmultiplexer/ezmultiplexertype.php @@ -180,42 +180,46 @@ class eZMultiplexerType extends eZWorkflowEventType $processParameters = $process->attribute( 'parameter_list' ); $storeProcessParameters = false; $classID = false; - $objectID = false; + $object = false; $sectionID = false; $languageID = 0; if ( isset( $processParameters['object_id'] ) ) { - $objectID = $processParameters['object_id']; - $object = eZContentObject::fetch( $objectID ); - if ( $object ) + $object = eZContentObject::fetch( $processParameters['object_id'] ); + } + else if ( isset( $processParameters['node_id'] ) ) + { + $object = eZContentObject::fetchByNodeID( $processParameters['node_id'] ); + } + + if ( $object instanceof eZContentObject ) + { + // Examine if the published version contains one of the languages we + // match for. + if ( isset( $processParameters['version'] ) ) { - // Examine if the published version contains one of the languages we - // match for. - if ( isset( $processParameters['version'] ) ) - { - $versionID = $processParameters['version']; - $version = $object->version( $versionID ); + $versionID = $processParameters['version']; + $version = $object->version( $versionID ); - if ( is_object( $version ) ) + if ( is_object( $version ) ) + { + $version_option = $event->attribute( 'version_option' ); + if ( ( $version_option == eZMultiplexerType::VERSION_OPTION_FIRST_ONLY and $processParameters['version'] > 1 ) or + ( $version_option == eZMultiplexerType::VERSION_OPTION_EXCEPT_FIRST and $processParameters['version'] == 1 ) ) { - $version_option = $event->attribute( 'version_option' ); - if ( ( $version_option == eZMultiplexerType::VERSION_OPTION_FIRST_ONLY and $processParameters['version'] > 1 ) or - ( $version_option == eZMultiplexerType::VERSION_OPTION_EXCEPT_FIRST and $processParameters['version'] == 1 ) ) - { - return eZWorkflowType::STATUS_ACCEPTED; - } - - // If the language ID is part of the mask the result is non-zero. - $languageID = (int)$version->attribute( 'initial_language_id' ); + return eZWorkflowType::STATUS_ACCEPTED; } + + // If the language ID is part of the mask the result is non-zero. + $languageID = (int)$version->attribute( 'initial_language_id' ); } - $sectionID = $object->attribute( 'section_id' ); - $class = $object->attribute( 'content_class' ); - if ( $class ) - { - $classID = $class->attribute( 'id' ); - } + } + $sectionID = $object->attribute( 'section_id' ); + $class = $object->attribute( 'content_class' ); + if ( $class ) + { + $classID = $class->attribute( 'id' ); } }
Fixed #<I>: Multiplexer workflow event (and maybe others) doesn't work with the updatesection and read triggers
ezsystems_ezpublish-legacy
train
d8da761ca622ac72ca3d246d8df0f1f4c53010cb
diff --git a/src/fn/fn-ramp.js b/src/fn/fn-ramp.js index <HASH>..<HASH> 100644 --- a/src/fn/fn-ramp.js +++ b/src/fn/fn-ramp.js @@ -71,25 +71,31 @@ module.exports = function (datasource, decl) { function ramp (datasource, column, args) { var method; + var tuple = []; + if (Array.isArray(args[0])) { - var scheme = args[0]; + tuple = args[0]; method = args[1]; - - return colorRamp(datasource, column, scheme, method); - } - - var min = +args[0]; - var max = +args[1]; - - var buckets = 5; - method = args[2]; - - if (Number.isFinite(+args[2])) { - buckets = +args[2]; - method = args[3]; + } else { + var min = +args[0]; + var max = +args[1]; + + var buckets = 5; + method = args[2]; + + if (Number.isFinite(+args[2])) { + buckets = +args[2]; + method = args[3]; + } + + var range = max - min; + var width = range / buckets; + for (var i = 0; i < buckets; i++) { + tuple.push(min + ((i + 1) * width)); + } } - return numericRamp(datasource, column, min, max, buckets, method); + return tupleRamp(datasource, column, tuple, method); } function getRamp (datasource, column, buckets, method) { @@ -103,35 +109,16 @@ function getRamp (datasource, column, buckets, method) { }); } -function colorRamp (datasource, column, scheme, method) { - var buckets = scheme.length; - return getRamp(datasource, column, buckets, method) - .then(function (ramp) { - var i; - var rampResult = []; - - for (i = 0; i < buckets; i++) { - rampResult.push(ramp[i]); - rampResult.push(scheme[i]); - } - - return rampResult; - }); -} - -function numericRamp (datasource, column, min, max, buckets, method) { +function tupleRamp (datasource, column, tuple, method) { + var buckets = tuple.length; return getRamp(datasource, column, buckets, method) .then(function (ramp) { var i; var rampResult = []; - min = +min; - max = +max; - var range = max - min; - var width = range / buckets; for (i = 0; i < buckets; i++) { rampResult.push(ramp[i]); - rampResult.push(min + ((i + 1) * width)); + rampResult.push(tuple[i]); } return rampResult; diff --git a/test/acceptance/ramp.test.js b/test/acceptance/ramp.test.js index <HASH>..<HASH> 100644 --- a/test/acceptance/ramp.test.js +++ b/test/acceptance/ramp.test.js @@ -85,4 +85,34 @@ describe('color-ramp', function () { done(err); }); }); + + it('should work with numeric ramps', function (done) { + var cartocss = [ + '#layer{', + ' marker-width: ramp([population], (4, 8, 12), jenks);', + '}' + ].join('\n'); + + var expectedCartocss = [ + '#layer{', + ' marker-width: 4;', + ' [ population > 0 ]{', + ' marker-width: 8', + ' }', + ' [ population > 1 ]{', + ' marker-width: 12', + ' }', + '}' + ].join('\n'); + + postcss([postcssTurboCarto.getPlugin()]) + .process(cartocss) + .then(function (result) { + assert.equal(result.css, expectedCartocss); + done(); + }) + .catch(function (err) { + done(err); + }); + }); });
Ramp function not coupled with selector types, e.g., polygon-color Closes #<I>
CartoDB_turbo-carto
train
23fbaa1aea78bbda473ff595f7c0f774a7051466
diff --git a/database-provider/src/main/java/org/jboss/pressgang/ccms/wrapper/DBServerEntitiesWrapper.java b/database-provider/src/main/java/org/jboss/pressgang/ccms/wrapper/DBServerEntitiesWrapper.java index <HASH>..<HASH> 100644 --- a/database-provider/src/main/java/org/jboss/pressgang/ccms/wrapper/DBServerEntitiesWrapper.java +++ b/database-provider/src/main/java/org/jboss/pressgang/ccms/wrapper/DBServerEntitiesWrapper.java @@ -46,6 +46,11 @@ public class DBServerEntitiesWrapper extends DBBaseWrapper<ServerEntitiesWrapper } @Override + public Integer getFrozenTagId() { + return getEntity().getFrozenTagId(); + } + + @Override public Integer getInternalOnlyTagId() { return getEntity().getInternalOnlyTagId(); } @@ -56,6 +61,11 @@ public class DBServerEntitiesWrapper extends DBBaseWrapper<ServerEntitiesWrapper } @Override + public Integer getObsoleteTagId() { + return getEntity().getObsoleteTagId(); + } + + @Override public Integer getReviewTagId() { return getEntity().getReviewTagId(); } diff --git a/provider-commons/src/main/java/org/jboss/pressgang/ccms/wrapper/ServerEntitiesWrapper.java b/provider-commons/src/main/java/org/jboss/pressgang/ccms/wrapper/ServerEntitiesWrapper.java index <HASH>..<HASH> 100644 --- a/provider-commons/src/main/java/org/jboss/pressgang/ccms/wrapper/ServerEntitiesWrapper.java +++ b/provider-commons/src/main/java/org/jboss/pressgang/ccms/wrapper/ServerEntitiesWrapper.java @@ -7,8 +7,10 @@ public interface ServerEntitiesWrapper extends BaseWrapper<ServerEntitiesWrapper Integer getAbstractTagId(); Integer getAuthorGroupTagId(); Integer getContentSpecTagId(); + Integer getFrozenTagId(); Integer getInternalOnlyTagId(); Integer getLegalNoticeTagId(); + Integer getObsoleteTagId(); Integer getReviewTagId(); Integer getRevisionHistoryTagId(); Integer getTaskTagId(); diff --git a/rest-provider/src/main/java/org/jboss/pressgang/ccms/wrapper/RESTServerEntitiesV1Wrapper.java b/rest-provider/src/main/java/org/jboss/pressgang/ccms/wrapper/RESTServerEntitiesV1Wrapper.java index <HASH>..<HASH> 100644 --- a/rest-provider/src/main/java/org/jboss/pressgang/ccms/wrapper/RESTServerEntitiesV1Wrapper.java +++ b/rest-provider/src/main/java/org/jboss/pressgang/ccms/wrapper/RESTServerEntitiesV1Wrapper.java @@ -29,6 +29,11 @@ public class RESTServerEntitiesV1Wrapper extends RESTBaseWrapper<ServerEntitiesW } @Override + public Integer getFrozenTagId() { + return getEntity().getFrozenTagId(); + } + + @Override public Integer getInternalOnlyTagId() { return getEntity().getInternalOnlyTagId(); } @@ -39,6 +44,11 @@ public class RESTServerEntitiesV1Wrapper extends RESTBaseWrapper<ServerEntitiesW } @Override + public Integer getObsoleteTagId() { + return getEntity().getObsoleteTagId(); + } + + @Override public Integer getReviewTagId() { return getEntity().getReviewTagId(); }
Added the Frozen and Obselete tag entity constants to the Server Settings model.
pressgang-ccms_PressGangCCMSDatasourceProviders
train
12b333c63063e656af85e4b9fffc8671e7140b13
diff --git a/response.class.php b/response.class.php index <HASH>..<HASH> 100644 --- a/response.class.php +++ b/response.class.php @@ -394,11 +394,13 @@ class CPS_Response foreach ($source as $key => $value) { CPS_Response::simpleXmlToArrayHelper($res, $key, $value, $children); } - foreach ($source->children('www.clusterpoint.com') as $key => $value) { - $newkey = 'cps:' . $key; - CPS_Response::simpleXmlToArrayHelper($res, $newkey, $value, $children); + if ($source) + { + foreach ($source->children('www.clusterpoint.com') as $key => $value) { + $newkey = 'cps:' . $key; + CPS_Response::simpleXmlToArrayHelper($res, $newkey, $value, $children); + } } - if (!$children) return (string)$source; return $res; @@ -466,4 +468,4 @@ class CPS_Response protected $_contentArray; protected $_connection; /**#@-*/ -} \ No newline at end of file +}
Fixed warning "Node no longer exists in response.class.php on line"
clusterpoint_php-client-api
train
83f1df4e0bc2dd06ff0644601837c7aa6fbc1f5c
diff --git a/index.js b/index.js index <HASH>..<HASH> 100644 --- a/index.js +++ b/index.js @@ -11,21 +11,4 @@ var Bot = module.exports.Bot = require('./lib/Bot.js'), InlineQueryResultArticle = module.exports.InlineQueryResultArticle = require('./lib/InlineQueryResultArticle.js'), InlineQueryResultLocation = module.exports.InlineQueryResultLocation = require('./lib/InlineQueryResultLocation.js'), Keyboard = module.exports.Keyboard = require('./lib/Keyboard.js'), - ChatMember = module.exports.ChatMember = require('./lib/ChatMember.js'); - -const bot = new Bot("121919558:AAHT7fH1QlAYGNAtQOwvBlwbOodIajou3Y8"); -bot.init(); - -bot.on('message', (message) => { - var keyboard = new Keyboard(); - keyboard.addButton(0, 0, {text:"sasasasa", callback_data: "uhuhuhuhuhuhu"}); - keyboard.toInline(); - message.reply("ygygygygygygy", {reply_markup: keyboard}) -}); - -bot.on('callback_query', (query) => { - query.message.editText("sassa", false, {}).catch((err) => {console.log(err)}); - query.message.chat.getMembersCount().then((user) => { - query.message.chat.unbanMember(query.from) - }) -}); \ No newline at end of file + ChatMember = module.exports.ChatMember = require('./lib/ChatMember.js'); \ No newline at end of file
Inadvertently pushed some test code
ALCC01_nodeogram
train
247e09f6242fba471844d642e6e63cfec156b4cb
diff --git a/javascript/operations.js b/javascript/operations.js index <HASH>..<HASH> 100644 --- a/javascript/operations.js +++ b/javascript/operations.js @@ -391,6 +391,13 @@ export default { }) }, + consoleTable: (operation, callee) => { + operate(operation, () => { + const { data, columns } = operation + console.table(data, columns || []) + }) + }, + notification: (operation, callee) => { before(document, callee, operation) operate(operation, () => { diff --git a/lib/cable_ready/config.rb b/lib/cable_ready/config.rb index <HASH>..<HASH> 100644 --- a/lib/cable_ready/config.rb +++ b/lib/cable_ready/config.rb @@ -42,6 +42,7 @@ module CableReady append clear_storage console_log + console_table dispatch_event go graft
console_table operation (#<I>)
hopsoft_cable_ready
train
060863ad2b6d026ec8681358f17e4a9fce1751db
diff --git a/gbdxtools/images/meta.py b/gbdxtools/images/meta.py index <HASH>..<HASH> 100644 --- a/gbdxtools/images/meta.py +++ b/gbdxtools/images/meta.py @@ -311,12 +311,19 @@ class GeoImage(Container): x_chunks = int((ur[0] - ll[0]) / x_size) + 1 y_chunks = int((ll[1] - ur[1]) / y_size) + 1 + num_bands = self.shape[0] + + try: + dtype = img_md["dataType"] + except: + dtype = 'UNSIGNED_INTEGER' + daskmeta = { "dask": {}, - "chunks": (img_md["numBands"], y_size, x_size), - "dtype": IPE_TO_DTYPE[img_md["dataType"]], - "name": "warp-{}".format(self.ipe_id), - "shape": (img_md["numBands"], y_chunks * y_size, x_chunks * x_size) + "chunks": (num_bands, y_size, x_size), + "dtype": IPE_TO_DTYPE[dtype], + "name": "warp-{}".format(self.name), + "shape": (num_bands, y_chunks * y_size, x_chunks * x_size) } def px_to_geom(xmin, ymin): diff --git a/gbdxtools/ipe/util.py b/gbdxtools/ipe/util.py index <HASH>..<HASH> 100644 --- a/gbdxtools/ipe/util.py +++ b/gbdxtools/ipe/util.py @@ -33,7 +33,7 @@ IPE_TO_DTYPE = { "SHORT": "short", "UNSIGNED_SHORT": "ushort", "INTEGER": "int32", - "UNSIGNED_INTEGER": "uint32", + "UNSIGNED_INTEGER": "uint8", "LONG": "int64", "UNSIGNED_LONG": "uint64", "FLOAT": "float32", diff --git a/tests/unit/test_catalog_image.py b/tests/unit/test_catalog_image.py index <HASH>..<HASH> 100644 --- a/tests/unit/test_catalog_image.py +++ b/tests/unit/test_catalog_image.py @@ -65,10 +65,10 @@ class CatalogImageTest(unittest.TestCase): except: pass - @my_vcr.use_cassette('tests/unit/cassettes/test_cat_image_unsupported_type.yaml', filter_headers=['authorization']) - def test_catalog_image_unsupported_type(self): - try: - img = CatalogImage('S2A_OPER_MSI_L1C_DS_MPS__20160904T224944_S20160904T180250_N02.04') - except UnsupportedImageType: - pass + #@my_vcr.use_cassette('tests/unit/cassettes/test_cat_image_unsupported_type.yaml', filter_headers=['authorization']) + #def test_catalog_image_unsupported_type(self): + # try: + # img = CatalogImage('S2A_OPER_MSI_L1C_DS_MPS__20160904T224944_S20160904T180250_N02.04') + # except UnsupportedImageType: + # pass
removing unsupported image test as we have no unsupported images types i think
DigitalGlobe_gbdxtools
train
f6ce11ae8e302b34fc5e6ac579968641ed9f73d9
diff --git a/gandi/cli/commands/paas.py b/gandi/cli/commands/paas.py index <HASH>..<HASH> 100644 --- a/gandi/cli/commands/paas.py +++ b/gandi/cli/commands/paas.py @@ -9,10 +9,11 @@ from gandi.cli.core.params import pass_gandi, DATACENTER, PAAS_TYPE, option @click.option('--state', default=None, help='filter results by state') @click.option('--id', help='display ids', is_flag=True) @click.option('--vhosts', help='display vhosts', default=True, is_flag=True) +@click.option('--type', help='display types', is_flag=True) @click.option('--limit', help='limit number of results', default=100, show_default=True) @pass_gandi -def list(gandi, state, id, vhosts, limit): +def list(gandi, state, id, vhosts, type, limit): """List PaaS instances.""" options = { @@ -26,6 +27,8 @@ def list(gandi, state, id, vhosts, limit): output_keys.append('id') if vhosts: output_keys.append('vhost') + if type: + output_keys.append('type') paas_hosts = {} result = gandi.paas.list(options)
Add the possibility to show type in paas list.
Gandi_gandi.cli
train
4668232eb504cd8bb4398746fc780c056b42a368
diff --git a/cluster/src/main/java/io/atomix/cluster/impl/DefaultNode.java b/cluster/src/main/java/io/atomix/cluster/impl/DefaultNode.java index <HASH>..<HASH> 100644 --- a/cluster/src/main/java/io/atomix/cluster/impl/DefaultNode.java +++ b/cluster/src/main/java/io/atomix/cluster/impl/DefaultNode.java @@ -64,7 +64,7 @@ public class DefaultNode extends Node { * Default cluster node builder. */ public static class Builder extends Node.Builder { - protected static final int DEFAULT_PORT = 5678; + protected static final int DEFAULT_PORT = 5679; @Override public Node build() { diff --git a/messaging/netty/src/main/java/io/atomix/messaging/netty/NettyMessagingService.java b/messaging/netty/src/main/java/io/atomix/messaging/netty/NettyMessagingService.java index <HASH>..<HASH> 100644 --- a/messaging/netty/src/main/java/io/atomix/messaging/netty/NettyMessagingService.java +++ b/messaging/netty/src/main/java/io/atomix/messaging/netty/NettyMessagingService.java @@ -94,6 +94,8 @@ import static io.atomix.utils.concurrent.Threads.namedThreads; * Netty based MessagingService. */ public class NettyMessagingService implements ManagedMessagingService { + private static final String DEFAULT_NAME = "atomix"; + public static final int DEFAULT_PORT = 5679; /** * Returns a new Netty messaging service builder. @@ -108,9 +110,6 @@ public class NettyMessagingService implements ManagedMessagingService { * Netty messaging service builder. */ public static class Builder extends MessagingService.Builder { - private static final String DEFAULT_NAME = "atomix"; - private static final int DEFAULT_PORT = 5678; - private String name = DEFAULT_NAME; private Endpoint endpoint; diff --git a/server/src/main/java/io/atomix/server/AtomixServer.java b/server/src/main/java/io/atomix/server/AtomixServer.java index <HASH>..<HASH> 100644 --- a/server/src/main/java/io/atomix/server/AtomixServer.java +++ b/server/src/main/java/io/atomix/server/AtomixServer.java @@ -15,11 +15,11 @@ */ package io.atomix.server; -import com.google.common.base.Joiner; import io.atomix.Atomix; import io.atomix.cluster.Node; import io.atomix.cluster.NodeId; import io.atomix.messaging.Endpoint; +import io.atomix.messaging.netty.NettyMessagingService; import net.sourceforge.argparse4j.ArgumentParsers; import net.sourceforge.argparse4j.inf.Argument; import net.sourceforge.argparse4j.inf.ArgumentParser; @@ -61,7 +61,7 @@ public class AtomixServer { parser.addArgument("address") .required(true) .type(nodeType) - .metavar("NAME:HOST:TCP_PORT") + .metavar("NAME:HOST:PORT") .help("The server address"); parser.addArgument("--bootstrap", "-b") .nargs("*") @@ -72,7 +72,7 @@ public class AtomixServer { .metavar("PORT") .required(false) .type(Integer.class) - .setDefault(0) + .setDefault(5678) .help("An optional HTTP server port"); parser.addArgument("--data-dir", "-d") .required(false) @@ -111,7 +111,7 @@ public class AtomixServer { private static String[] parseAddress(String address) { String[] parsed = address.split(":"); - if (parsed.length > 3 || parsed.length < 2) { + if (parsed.length > 3) { throw new IllegalArgumentException("Malformed address " + address); } return parsed; @@ -120,26 +120,39 @@ public class AtomixServer { private static NodeId parseNodeId(String[] address) { if (address.length == 3) { return NodeId.from(address[0]); + } else if (address.length == 2) { + return NodeId.from(parseEndpoint(address).toString()); } else { - return NodeId.from(Joiner.on(":").join(address)); + try { + InetAddress.getByName(address[0]); + return NodeId.from(parseEndpoint(address).toString()); + } catch (UnknownHostException e) { + return NodeId.from(address[0]); + } } } private static Endpoint parseEndpoint(String[] address) { String host; - String port; + int port; if (address.length == 3) { host = address[1]; - port = address[2]; + port = Integer.parseInt(address[2]); + } else if (address.length == 2) { + try { + host = address[0]; + port = Integer.parseInt(address[1]); + } catch (NumberFormatException e) { + host = address[1]; + port = NettyMessagingService.DEFAULT_PORT; + } } else { host = address[0]; - port = address[1]; + port = NettyMessagingService.DEFAULT_PORT; } try { - return new Endpoint(InetAddress.getByName(host), Integer.parseInt(port)); - } catch (NumberFormatException e) { - throw new IllegalArgumentException("Malformed TCP port " + port); + return new Endpoint(InetAddress.getByName(host), port); } catch (UnknownHostException e) { throw new IllegalArgumentException("Failed to resolve host", e); }
Allow default names/ports to be provided in Atomix server configuration.
atomix_atomix
train
f16629c3a1d12938b97dae97079612325c7114f3
diff --git a/guja-core/src/main/java/com/wadpam/guja/oauth2/api/UserResource.java b/guja-core/src/main/java/com/wadpam/guja/oauth2/api/UserResource.java index <HASH>..<HASH> 100644 --- a/guja-core/src/main/java/com/wadpam/guja/oauth2/api/UserResource.java +++ b/guja-core/src/main/java/com/wadpam/guja/oauth2/api/UserResource.java @@ -90,9 +90,7 @@ public class UserResource { throw new BadRequestRestException("Missing mandatory parameters"); } - checkUsernameFormat(user.getUsername()); - checkPasswordFormat(user.getPassword()); - checkEmailFormat(user.getEmail()); + validateUser(user); user = userService.signup(user); @@ -106,6 +104,12 @@ public class UserResource { } + private void validateUser(DUser user) { + checkUsernameFormat(user.getUsername()); + checkPasswordFormat(user.getPassword()); + checkEmailFormat(user.getEmail()); + } + private static void checkUsernameFormat(String username) { if (!USERNAME_PATTERN.matcher(username).matches()) { LOGGER.info("Invalid username format {}", username); @@ -237,6 +241,7 @@ public class UserResource { @Context SecurityContext securityContext, DUser user) { checkNotNull(id); + validateUser(user); user = userService.update(id, user, securityContext.isUserInRole(OAuth2UserResource.ROLE_ADMIN));
Added user validation to user updates.
Wadpam_guja
train
ffea4eb478ba3d0c04603537b9af1516ef03f039
diff --git a/scripts/generate/logs/index.js b/scripts/generate/logs/index.js index <HASH>..<HASH> 100644 --- a/scripts/generate/logs/index.js +++ b/scripts/generate/logs/index.js @@ -54,6 +54,12 @@ var eventElementsPerBulk = eventsPerBulk * 2; // events are stored next to their function createIndex(indexName, done) { console.log('made index', indexName); var indexBody = { + settings: { + index: { + number_of_shards: 1, + number_of_replicas: 0 + } + }, mappings: { _default_: { properties: { diff --git a/test/unit/specs/client.js b/test/unit/specs/client.js index <HASH>..<HASH> 100644 --- a/test/unit/specs/client.js +++ b/test/unit/specs/client.js @@ -21,18 +21,18 @@ describe('Client instances creation', function () { }).to.throwError(/previous "elasticsearch" module/); }); - it('inherits the 0.90 API by default', function () { - expect(client.bulk).to.eql(apis['0.90'].bulk); - expect(client.cluster.nodeStats).to.eql(apis['0.90'].cluster.prototype.nodeStats); + it('inherits the 1.0 API by default', function () { + expect(client.bulk).to.eql(apis['1.0'].bulk); + expect(client.nodes.stats).to.eql(apis['1.0'].nodes.prototype.stats); }); - it('inherits the 1.0 API when specified', function () { + it('inherits the 0.90 API when specified', function () { client.close(); client = es.Client({ - apiVersion: '1.0' + apiVersion: '0.90' }); - expect(client.bulk).to.eql(apis['1.0'].bulk); - expect(client.nodes.stats).to.eql(apis['1.0'].nodes.prototype.stats); + expect(client.bulk).to.eql(apis['0.90'].bulk); + expect(client.cluster.nodeStats).to.eql(apis['0.90'].cluster.prototype.nodeStats); }); it('closing the client causes it\'s transport to be closed', function () { diff --git a/test/unit/specs/http_connector.js b/test/unit/specs/http_connector.js index <HASH>..<HASH> 100644 --- a/test/unit/specs/http_connector.js +++ b/test/unit/specs/http_connector.js @@ -371,7 +371,7 @@ describe('Http Connector', function () { describe('Connection cleanup', function () { it('destroys any connections created', function (done) { - this.timeout(4000); + this.timeout(10000); var cp = require('child_process'); var path = require('path'); var es = require('event-stream');
tests now look for the <I> API by default
elastic_elasticsearch-js
train
f588776ed74cecc2ce84a32d9e8a9235b65cedff
diff --git a/src/osrm.js b/src/osrm.js index <HASH>..<HASH> 100644 --- a/src/osrm.js +++ b/src/osrm.js @@ -102,6 +102,11 @@ OSRM.prototype = { }); response.on('end', function() { clearTimeout(timeout); + if (response.headers['content-type'] === undefined) + { + return callback(new Error("Response does not have a content-type set.")); + } + var format = response.headers['content-type'].split(";")[0]; if (format === 'application/json') { diff --git a/test/test.js b/test/test.js index <HASH>..<HASH> 100644 --- a/test/test.js +++ b/test/test.js @@ -20,6 +20,7 @@ test('request', function(t) { var osrm = new OSRM(); osrm.request('/route/v1/driving/13.438640,52.519930;13.415852,52.513191', function(error, response) { t.notOk(error); + t.ok(response); t.ok(response.waypoints); t.ok(response.routes); t.ok(response.routes[0].geometry);
Throw meaningful error for missing content-type
Project-OSRM_osrm.js
train
5b476c2873da339a61c3e80ecfd02f015f3eb163
diff --git a/Gruntfile.js b/Gruntfile.js index <HASH>..<HASH> 100644 --- a/Gruntfile.js +++ b/Gruntfile.js @@ -372,7 +372,7 @@ module.exports = function(grunt) { ); }); - config.clean.cdnjs = 'dist/cdnjs'; + //config.clean.cdnjs = 'dist/cdnjs';
remove cdnjs for normal build process
fullcalendar_fullcalendar
train
6de484b4b5f66cbfd9e952718812df8607581cb7
diff --git a/api/python/quilt3/main.py b/api/python/quilt3/main.py index <HASH>..<HASH> 100644 --- a/api/python/quilt3/main.py +++ b/api/python/quilt3/main.py @@ -13,7 +13,9 @@ import requests from . import api, session from . import __version__ as quilt3_version from .session import open_url -from .util import get_from_config, catalog_s3_url, catalog_package_url, QuiltException +from .util import get_from_config, catalog_s3_url, catalog_package_url, QuiltException, PhysicalKey, \ + fix_url, get_package_registry +from .registry import app def cmd_config(catalog_url): """ @@ -165,6 +167,10 @@ def cmd_disable_telemetry(): api._disable_telemetry() print("Successfully disabled telemetry.") +def cmd_list_packages(registry): + registry_parsed = PhysicalKey.from_url(get_package_registry(fix_url(registry))) + for package_name in api._list_packages(registry=registry_parsed): + print(package_name) def cmd_verify(name, registry, top_hash, dir, extra_files_ok): pkg = api.Package._browse(name, registry, top_hash) @@ -266,6 +272,16 @@ def create_parser(): ) install_p.set_defaults(func=api.Package.install) + # list-packages + shorthelp = "List all packages in a registry" + list_packages_p = subparsers.add_parser("list-packages", description=shorthelp, help=shorthelp, allow_abbrev=False) + list_packages_p.add_argument( + "registry", + help="Registry for packages, e.g. s3://quilt-example", + type=str, + ) + list_packages_p.set_defaults(func=cmd_list_packages) + # verify shorthelp = "Verify that package contents matches a given directory" verify_p = subparsers.add_parser("verify", description=shorthelp, help=shorthelp, allow_abbrev=False)
Added CLI command `quilt3 list-packages $REGISTRY` (#<I>)
quiltdata_quilt
train
2a00a6513e77297a25131b3b380908eea7559959
diff --git a/src/main/java/com/nulabinc/backlog4j/Notification.java b/src/main/java/com/nulabinc/backlog4j/Notification.java index <HASH>..<HASH> 100644 --- a/src/main/java/com/nulabinc/backlog4j/Notification.java +++ b/src/main/java/com/nulabinc/backlog4j/Notification.java @@ -8,11 +8,37 @@ import java.util.Date; * @author nulab-inc */ public interface Notification { + + enum Reason { + Assigned(1), Commented(2), IssueCreated(3), IssueUpdated(4), + FileAttached(5), ProjectUserAdded(6), Other(9); + + Reason(int intValue) { + this.intValue = intValue; + } + + public int getIntValue() { + return intValue; + } + + public static Reason valueOf(final int anIntValue) { + for (Reason d : values()) { + if (d.getIntValue() == anIntValue) { + return d; + } + } + return null; + } + + private int intValue; + } + + long getId(); boolean isAlreadyRead(); - int getReason(); + Reason getReason(); boolean isResourceAlreadyRead(); diff --git a/src/main/java/com/nulabinc/backlog4j/internal/json/NotificationJSONImpl.java b/src/main/java/com/nulabinc/backlog4j/internal/json/NotificationJSONImpl.java index <HASH>..<HASH> 100644 --- a/src/main/java/com/nulabinc/backlog4j/internal/json/NotificationJSONImpl.java +++ b/src/main/java/com/nulabinc/backlog4j/internal/json/NotificationJSONImpl.java @@ -43,8 +43,8 @@ public class NotificationJSONImpl implements Notification { } @Override - public int getReason() { - return reason; + public Reason getReason() { + return Notification.Reason.valueOf(this.reason); } @Override diff --git a/src/test/java/com/nulabinc/backlog4j/internal/json/NotificationJSONImplTest.java b/src/test/java/com/nulabinc/backlog4j/internal/json/NotificationJSONImplTest.java index <HASH>..<HASH> 100644 --- a/src/test/java/com/nulabinc/backlog4j/internal/json/NotificationJSONImplTest.java +++ b/src/test/java/com/nulabinc/backlog4j/internal/json/NotificationJSONImplTest.java @@ -24,7 +24,7 @@ public class NotificationJSONImplTest extends AbstractJSONImplTest{ Notification notification = notifications.get(0); assertEquals(808, notification.getId()); assertEquals(false, notification.isAlreadyRead()); - assertEquals(3, notification.getReason()); + assertEquals(Notification.Reason.IssueCreated, notification.getReason()); assertEquals(true, notification.isResourceAlreadyRead()); Project project = notification.getProject();
Change notification reason int to enum .
nulab_backlog4j
train
0a35149b52e1d689a00655da943e147a68d34122
diff --git a/Query/Builder.php b/Query/Builder.php index <HASH>..<HASH> 100644 --- a/Query/Builder.php +++ b/Query/Builder.php @@ -643,7 +643,9 @@ class Builder { */ public function having($column, $operator = null, $value = null) { - $this->havings[] = compact('column', 'operator', 'value'); + $type = 'Basic'; + + $this->havings[] = compact('type', 'column', 'operator', 'value'); $this->bindings[] = $value; @@ -651,6 +653,37 @@ class Builder { } /** + * Add a raw where clause to the query. + * + * @param string $sql + * @param array $bindings + * @param string $boolean + * @return Illuminate\Database\Query\Builder + */ + public function havingRaw($sql, array $bindings = array(), $boolean = 'and') + { + $type = 'raw'; + + $this->havings[] = compact('type', 'sql', 'boolean'); + + $this->bindings = array_merge($this->bindings, $bindings); + + return $this; + } + + /** + * Add a raw or having clause to the query. + * + * @param string $sql + * @param array $bindings + * @return Illuminate\Database\Query\Builder + */ + public function orHavingRaw($sql, array $bindings = array()) + { + return $this->havingRaw($sql, $bindings, 'or'); + } + + /** * Add an "order by" clause to the query. * * @param string $column diff --git a/Query/Grammars/Grammar.php b/Query/Grammars/Grammar.php index <HASH>..<HASH> 100644 --- a/Query/Grammars/Grammar.php +++ b/Query/Grammars/Grammar.php @@ -408,6 +408,10 @@ class Grammar extends BaseGrammar { { extract($having); + if ($type === 'raw') { + return $boolean.' '.$sql; + } + return 'and '.$me->wrap($column).' '.$operator.' '.$me->parameter($value); }, $havings));
Added havingRaw() and orHavingRaw() I'm not sure if this is the perfect implementation, but it does what I need at the tests are green.
illuminate_database
train
0bf6f1ecffc6b2fb5d102d2f0f5c95fd575d48c4
diff --git a/class.js b/class.js index <HASH>..<HASH> 100644 --- a/class.js +++ b/class.js @@ -99,9 +99,7 @@ proto.isMetaClass = function isMetaClass () { proto.getSuperclass = function getSuperclass () { var superclassPointer = this._getSuperclassPointer() if (superclassPointer.isNull()) return null; - var name = core.class_getName(superclassPointer) - , superclass = exports.getClass(name) - return superclass; + return exports.wrap(superclassPointer); } proto.getInstanceMethod = function getInstanceMethod (sel) {
Don't lookup the superclass by name, just wrap the pointer straight up.
TooTallNate_NodObjC
train
b89d1e76f221d389d207c31a00c2737236ec9371
diff --git a/modules/admin/src/resources/js/controllers.js b/modules/admin/src/resources/js/controllers.js index <HASH>..<HASH> 100644 --- a/modules/admin/src/resources/js/controllers.js +++ b/modules/admin/src/resources/js/controllers.js @@ -61,12 +61,13 @@ $scope.currentFilter = "0"; // ng-change event triggers this method - $scope.reloadFilter = function() { + // this method is also used withing after save/update events in order to retrieve current selecter filter data. + $scope.realoadCrudList = function() { LuyaLoading.start(); if ($scope.currentFilter == 0) { $scope.loadList(); } else { - $http.get($scope.config.apiEndpoint + '/filter?filterName=' + $scope.currentFilter).success(function(data) { + $http.get($scope.config.apiEndpoint + '/filter?filterName=' + $scope.currentFilter + '&' + $scope.config.apiListQueryString).success(function(data) { LuyaLoading.stop(); $scope.data.list = data; }); @@ -238,7 +239,7 @@ $scope.updateErrors = []; $http.put($scope.config.apiEndpoint + '/' + $scope.data.updateId, angular.toJson($scope.data.update, true)).success(function(data) { - $scope.loadList(); + $scope.realoadCrudList(); AdminToastService.success(i18n['js_ngrest_rm_update'], 2000); $scope.switchTo(0); $scope.highlightId = $scope.data.updateId; @@ -256,7 +257,7 @@ $scope.createErrors = []; $http.post($scope.config.apiEndpoint, angular.toJson($scope.data.create, true)).success(function(data) { - $scope.loadList(); + $scope.realoadCrudList(); $scope.data.create = {}; AdminToastService.success(i18n['js_ngrest_rm_success'], 2000); $scope.switchTo(0); diff --git a/modules/admin/src/views/ngrest/render/crud.php b/modules/admin/src/views/ngrest/render/crud.php index <HASH>..<HASH> 100644 --- a/modules/admin/src/views/ngrest/render/crud.php +++ b/modules/admin/src/views/ngrest/render/crud.php @@ -79,7 +79,7 @@ <?php if (!empty($config->filters)): ?> <div class="input input--select input--vertical"> <label class="input__label">Apply Filters</label> - <select class="input__field" ng-change="reloadFilter()" ng-model="currentFilter"> + <select class="input__field" ng-change="realoadCrudList()" ng-model="currentFilter"> <option value="0">Reset to default</option> <? foreach (array_keys($config->filters) as $name): ?> <option value="<?= $name; ?>"><?= $name; ?></option>
keep filter after save/update event, observe call type and fields #<I>
luyadev_luya
train
622de043e45fb05990cd9429fcfb9313db5467db
diff --git a/CHANGELOG.rst b/CHANGELOG.rst index <HASH>..<HASH> 100644 --- a/CHANGELOG.rst +++ b/CHANGELOG.rst @@ -14,6 +14,11 @@ Change Log Unreleased -------------------- +[3.3.23] 2020-07-13 +------------------- + +* Remove unneceesary data migration + [3.3.22] 2020-07-13 ------------------- diff --git a/enterprise/__init__.py b/enterprise/__init__.py index <HASH>..<HASH> 100644 --- a/enterprise/__init__.py +++ b/enterprise/__init__.py @@ -2,6 +2,6 @@ Your project description goes here. """ -__version__ = "3.3.22" +__version__ = "3.3.23" default_app_config = "enterprise.apps.EnterpriseConfig" # pylint: disable=invalid-name diff --git a/enterprise/migrations/0101_move_data_to_saved_for_later.py b/enterprise/migrations/0101_move_data_to_saved_for_later.py index <HASH>..<HASH> 100644 --- a/enterprise/migrations/0101_move_data_to_saved_for_later.py +++ b/enterprise/migrations/0101_move_data_to_saved_for_later.py @@ -3,21 +3,13 @@ from django.db import migrations -# saved_for_later will replace the marked_done field +# this field is new, there is no data in prod that we have to update def move_data_from_marked_done_to_saved_for_later(apps, schema_editor): - EnterpriseCourseEnrollment = apps.get_model('enterprise', 'EnterpriseCourseEnrollment') - course_enrollments = EnterpriseCourseEnrollment.objects.all() - for course_enrollment in course_enrollments: - course_enrollment.saved_for_later = course_enrollment.marked_done - EnterpriseCourseEnrollment.objects.bulk_update(course_enrollments, ['saved_for_later']) + pass def move_data_from_saved_for_later_to_marked_done(apps, schema_editor): - EnterpriseCourseEnrollment = apps.get_model('enterprise', 'EnterpriseCourseEnrollment') - course_enrollments = EnterpriseCourseEnrollment.objects.all() - for course_enrollment in course_enrollments: - course_enrollment.marked_done = course_enrollment.saved_for_later - EnterpriseCourseEnrollment.objects.bulk_update(course_enrollments, ['marked_done']) + pass class Migration(migrations.Migration):
Remove data migration Because we don't have user data in prod yet, and the migration was failing, we are choosing to not migrate the data
edx_edx-enterprise
train
1558f3f49dc39df062d04fc753617ae3c43e8e17
diff --git a/README.md b/README.md index <HASH>..<HASH> 100644 --- a/README.md +++ b/README.md @@ -26,7 +26,7 @@ For the code of the current stable 0.4.x release, checkout the * [ExtLibeventLoop](#extlibeventloop) * [ExtLibevLoop](#extlibevloop) * [LoopInterface](#loopinterface) - * [addtimer()](#addtimer) + * [addTimer()](#addtimer) * [addPeriodicTimer()](#addperiodictimer) * [cancelTimer()](#canceltimer) * [isTimerActive()](#istimeractive) @@ -184,6 +184,15 @@ It is commonly installed as part of many PHP distributions. If this extension is missing (or you're running on Windows), signal handling is not supported and throws a `BadMethodCallException` instead. +This event loop is known to rely on wall-clock time to schedule future +timers, because a monotonic time source is not available in PHP by default. +While this does not affect many common use cases, this is an important +distinction for programs that rely on a high time precision or on systems +that are subject to discontinuous time adjustments (time jumps). +This means that if you schedule a timer to trigger in 30s and then adjust +your system time forward by 20s, the timer may trigger in 10s. +See also [`addTimer()`](#addtimer) for more details. + #### ExtEventLoop An `ext-event` based event loop. @@ -267,6 +276,17 @@ hello('Tester', $loop); The execution order of timers scheduled to execute at the same time is not guaranteed. +This interface suggests that event loop implementations SHOULD use a +monotic time source if available. Given that a monotonic time source is +not available on PHP by default, event loop implementations MAY fall back +to using wall-clock time. +While this does not affect many common use cases, this is an important +distinction for programs that rely on a high time precision or on systems +that are subject to discontinuous time adjustments (time jumps). +This means that if you schedule a timer to trigger in 30s and then adjust +your system time forward by 20s, the timer SHOULD still trigger in 30s. +See also [event loop implementations](#loop-implementations) for more details. + #### addPeriodicTimer() The `addPeriodicTimer(float $interval, callable $callback): TimerInterface` method can be used to diff --git a/src/LoopInterface.php b/src/LoopInterface.php index <HASH>..<HASH> 100644 --- a/src/LoopInterface.php +++ b/src/LoopInterface.php @@ -224,6 +224,17 @@ interface LoopInterface * The execution order of timers scheduled to execute at the same time is * not guaranteed. * + * This interface suggests that event loop implementations SHOULD use a + * monotic time source if available. Given that a monotonic time source is + * not available on PHP by default, event loop implementations MAY fall back + * to using wall-clock time. + * While this does not affect many common use cases, this is an important + * distinction for programs that rely on a high time precision or on systems + * that are subject to discontinuous time adjustments (time jumps). + * This means that if you schedule a timer to trigger in 30s and then adjust + * your system time forward by 20s, the timer SHOULD still trigger in 30s. + * See also [event loop implementations](#loop-implementations) for more details. + * * @param int|float $interval The number of seconds to wait before execution. * @param callable $callback The callback to invoke. * diff --git a/src/StreamSelectLoop.php b/src/StreamSelectLoop.php index <HASH>..<HASH> 100644 --- a/src/StreamSelectLoop.php +++ b/src/StreamSelectLoop.php @@ -39,6 +39,15 @@ use React\EventLoop\Timer\Timers; * If this extension is missing (or you're running on Windows), signal handling is * not supported and throws a `BadMethodCallException` instead. * + * This event loop is known to rely on wall-clock time to schedule future + * timers, because a monotonic time source is not available in PHP by default. + * While this does not affect many common use cases, this is an important + * distinction for programs that rely on a high time precision or on systems + * that are subject to discontinuous time adjustments (time jumps). + * This means that if you schedule a timer to trigger in 30s and then adjust + * your system time forward by 20s, the timer may trigger in 10s. + * See also [`addTimer()`](#addtimer) for more details. + * * @link http://php.net/manual/en/function.stream-select.php */ class StreamSelectLoop implements LoopInterface
Documentation for monotonic time source vs wall-clock time
reactphp_event-loop
train
a049fd39a658b66c0eb8a37e807d849611781da3
diff --git a/lucene-directory/src/main/java/org/infinispan/lucene/ExternalizerIds.java b/lucene-directory/src/main/java/org/infinispan/lucene/ExternalizerIds.java index <HASH>..<HASH> 100644 --- a/lucene-directory/src/main/java/org/infinispan/lucene/ExternalizerIds.java +++ b/lucene-directory/src/main/java/org/infinispan/lucene/ExternalizerIds.java @@ -31,31 +31,32 @@ package org.infinispan.lucene; * @author Sanne Grinovero * @since 5.0 */ +@SuppressWarnings("boxing") public interface ExternalizerIds { /** * @see org.infinispan.lucene.FileListCacheKey.Externalizer */ - static final int FILE_LIST_CACHE_KEY = 1300; + static final Integer FILE_LIST_CACHE_KEY = 1300; /** * @see org.infinispan.lucene.FileMetadata.Externalizer */ - static final int FILE_METADATA = 1301; + static final Integer FILE_METADATA = 1301; /** * @see org.infinispan.lucene.FileCacheKey.Externalizer */ - static final int FILE_CACHE_KEY = 1302; + static final Integer FILE_CACHE_KEY = 1302; /** * @see org.infinispan.lucene.ChunkCacheKey.Externalizer */ - static final int CHUNK_CACHE_KEY = 1303; + static final Integer CHUNK_CACHE_KEY = 1303; /** * @see org.infinispan.lucene.FileReadLockKey.Externalizer */ - static final int FILE_READLOCK_KEY = 1304; + static final Integer FILE_READLOCK_KEY = 1304; } diff --git a/lucene-directory/src/test/java/org/infinispan/lucene/DatabaseStoredIndexTest.java b/lucene-directory/src/test/java/org/infinispan/lucene/DatabaseStoredIndexTest.java index <HASH>..<HASH> 100644 --- a/lucene-directory/src/test/java/org/infinispan/lucene/DatabaseStoredIndexTest.java +++ b/lucene-directory/src/test/java/org/infinispan/lucene/DatabaseStoredIndexTest.java @@ -78,7 +78,7 @@ public class DatabaseStoredIndexTest extends SingleCacheManagerTest { JdbcStringBasedCacheStoreConfig jdbcStoreConfiguration = new JdbcStringBasedCacheStoreConfig(connectionFactoryConfig, tm); jdbcStoreConfiguration.setKey2StringMapperClass(LuceneKey2StringMapper.class.getName()); CacheLoaderManagerConfig loaderManagerConfig = configuration.getCacheLoaderManagerConfig(); - loaderManagerConfig.setPreload(false); + loaderManagerConfig.setPreload(Boolean.FALSE); loaderManagerConfig.addCacheLoaderConfig(jdbcStoreConfiguration); } diff --git a/lucene-directory/src/test/java/org/infinispan/lucene/DirectoryIntegrityCheck.java b/lucene-directory/src/test/java/org/infinispan/lucene/DirectoryIntegrityCheck.java index <HASH>..<HASH> 100644 --- a/lucene-directory/src/test/java/org/infinispan/lucene/DirectoryIntegrityCheck.java +++ b/lucene-directory/src/test/java/org/infinispan/lucene/DirectoryIntegrityCheck.java @@ -118,7 +118,7 @@ public class DirectoryIntegrityCheck { Object readLockValue = cache.get(readLockKey); Assert.assertNotNull(readLockValue); Assert.assertTrue(readLockValue instanceof Integer); - int v = (Integer) readLockValue; + int v = ((Integer) readLockValue).intValue(); Assert.assertTrue(v > 1, "readlock exists for unregistered file of unexpected value: " + v + " for file: " + filename); } diff --git a/lucene-directory/src/test/java/org/infinispan/lucene/profiling/CacheStoreStressTest.java b/lucene-directory/src/test/java/org/infinispan/lucene/profiling/CacheStoreStressTest.java index <HASH>..<HASH> 100644 --- a/lucene-directory/src/test/java/org/infinispan/lucene/profiling/CacheStoreStressTest.java +++ b/lucene-directory/src/test/java/org/infinispan/lucene/profiling/CacheStoreStressTest.java @@ -65,7 +65,7 @@ public class CacheStoreStressTest extends SingleCacheManagerTest { JdbcStringBasedCacheStoreConfig jdbcStoreConfiguration = new JdbcStringBasedCacheStoreConfig(connectionFactoryConfig, tm); jdbcStoreConfiguration.setKey2StringMapperClass(LuceneKey2StringMapper.class.getName()); CacheLoaderManagerConfig loaderManagerConfig = configuration.getCacheLoaderManagerConfig(); - loaderManagerConfig.setPreload(true); + loaderManagerConfig.setPreload(Boolean.TRUE); loaderManagerConfig.addCacheLoaderConfig(jdbcStoreConfiguration); }
ISPN-<I> Reduce autoboxing operations
infinispan_infinispan
train
2eb43c6baf2f3efc08fd2ff145838e325b3f615c
diff --git a/core/src/main/java/io/micronaut/core/convert/ArgumentConversionContext.java b/core/src/main/java/io/micronaut/core/convert/ArgumentConversionContext.java index <HASH>..<HASH> 100644 --- a/core/src/main/java/io/micronaut/core/convert/ArgumentConversionContext.java +++ b/core/src/main/java/io/micronaut/core/convert/ArgumentConversionContext.java @@ -19,6 +19,8 @@ import io.micronaut.core.annotation.AnnotationMetadata; import io.micronaut.core.annotation.AnnotationMetadataProvider; import io.micronaut.core.type.Argument; +import java.util.Map; + /** * Extended version of the {@link ConversionContext} specifically for conversion {@link Argument} instances. * @@ -34,6 +36,16 @@ public interface ArgumentConversionContext<T> extends ConversionContext, Annotat Argument<T> getArgument(); @Override + default Argument[] getTypeParameters() { + return getArgument().getTypeParameters(); + } + + @Override + default Map<String, Argument<?>> getTypeVariables() { + return getArgument().getTypeVariables(); + } + + @Override default AnnotationMetadata getAnnotationMetadata() { return getArgument().getAnnotationMetadata(); } diff --git a/core/src/main/java/io/micronaut/core/convert/DefaultArgumentConversionContext.java b/core/src/main/java/io/micronaut/core/convert/DefaultArgumentConversionContext.java index <HASH>..<HASH> 100644 --- a/core/src/main/java/io/micronaut/core/convert/DefaultArgumentConversionContext.java +++ b/core/src/main/java/io/micronaut/core/convert/DefaultArgumentConversionContext.java @@ -48,16 +48,6 @@ class DefaultArgumentConversionContext<T> implements ArgumentConversionContext<T } @Override - public Argument[] getTypeParameters() { - return argument.getTypeParameters(); - } - - @Override - public Map<String, Argument<?>> getTypeVariables() { - return argument.getTypeVariables(); - } - - @Override public Locale getLocale() { return finalLocale; } diff --git a/core/src/main/java/io/micronaut/core/convert/ImmutableArgumentConversionContext.java b/core/src/main/java/io/micronaut/core/convert/ImmutableArgumentConversionContext.java index <HASH>..<HASH> 100644 --- a/core/src/main/java/io/micronaut/core/convert/ImmutableArgumentConversionContext.java +++ b/core/src/main/java/io/micronaut/core/convert/ImmutableArgumentConversionContext.java @@ -18,6 +18,8 @@ package io.micronaut.core.convert; import io.micronaut.core.type.Argument; import io.micronaut.core.util.ArgumentUtils; +import java.util.Map; + /** * Immutable variant of {@link io.micronaut.core.convert.ArgumentConversionContext} that can be used as a constant * in cases where conversion error handling and rejection is not required. @@ -27,6 +29,7 @@ import io.micronaut.core.util.ArgumentUtils; * @author graemerocher */ public interface ImmutableArgumentConversionContext<T> extends ArgumentConversionContext<T> { + /** * Create a new simple {@link ConversionContext} for the given generic type variables. *
Fix getting type arguments from the immutable conversion context
micronaut-projects_micronaut-core
train
627dade0c796e720205e26fc875d33db3e548122
diff --git a/marshaler.go b/marshaler.go index <HASH>..<HASH> 100644 --- a/marshaler.go +++ b/marshaler.go @@ -128,7 +128,8 @@ func (enc *Encoder) SetIndentTables(indent bool) *Encoder { // // In addition to the "toml" tag struct tag, a "comment" tag can be used to emit // a TOML comment before the value being annotated. Comments are ignored inside -// inline tables. +// inline tables. For array tables, the comment is only present before the first +// element of the array. func (enc *Encoder) Encode(v interface{}) error { var ( b []byte @@ -890,6 +891,8 @@ func (enc *Encoder) encodeSliceAsArrayTable(b []byte, ctx encoderCtx, v reflect. scratch = append(scratch, "]]\n"...) ctx.skipTableHeader = true + b = enc.encodeComment(ctx.indent, ctx.options.comment, b) + for i := 0; i < v.Len(); i++ { b = append(b, scratch...) diff --git a/unmarshaler_test.go b/unmarshaler_test.go index <HASH>..<HASH> 100644 --- a/unmarshaler_test.go +++ b/unmarshaler_test.go @@ -2399,6 +2399,30 @@ func TestIssue772(t *testing.T) { require.Equal(t, "reach-masterdev-", config.FileHandling.FilePattern) } +func TestIssue774(t *testing.T) { + type ScpData struct { + Host string `json:"host"` + } + + type GenConfig struct { + SCP []ScpData `toml:"scp" comment:"Array of Secure Copy Configurations"` + } + + c := &GenConfig{} + c.SCP = []ScpData{{Host: "main.domain.com"}} + + b, err := toml.Marshal(c) + require.NoError(t, err) + + expected := `# Array of Secure Copy Configurations +[[scp]] +Host = 'main.domain.com' + +` + + require.Equal(t, expected, string(b)) +} + func TestUnmarshalDecodeErrors(t *testing.T) { examples := []struct { desc string
Encode: support comment on array tables (#<I>) Fixes #<I>
pelletier_go-toml
train
6263687b77f9dc0c31d1b2e71d933438c4c5e261
diff --git a/setup.py b/setup.py index <HASH>..<HASH> 100644 --- a/setup.py +++ b/setup.py @@ -4,7 +4,7 @@ from setuptools import setup, find_packages setup( name='synapse', - version='0.1.0-alpha', + version='0.1.0a1', description='Synapse Distributed Key-Value Hypergraph Analysis Framework', author='Invisigoth Kenshoto', author_email='invisigoth.kenshoto@gmail.com',
PEP<I> compliant version string.
vertexproject_synapse
train
db777714ae8dbaed89a9e44ca3cd67a7968e55fe
diff --git a/keyvalue/client-internal/src/main/java/alluxio/client/keyvalue/hadoop/KeyValueRecordWriter.java b/keyvalue/client-internal/src/main/java/alluxio/client/keyvalue/hadoop/KeyValueRecordWriter.java index <HASH>..<HASH> 100644 --- a/keyvalue/client-internal/src/main/java/alluxio/client/keyvalue/hadoop/KeyValueRecordWriter.java +++ b/keyvalue/client-internal/src/main/java/alluxio/client/keyvalue/hadoop/KeyValueRecordWriter.java @@ -21,8 +21,9 @@ import alluxio.client.keyvalue.KeyValueSystem; import alluxio.exception.AlluxioException; import org.apache.hadoop.io.BytesWritable; -import org.apache.hadoop.mapred.RecordWriter; +import org.apache.hadoop.mapreduce.RecordWriter; import org.apache.hadoop.mapred.Reporter; +import org.apache.hadoop.mapreduce.TaskAttemptContext; import org.apache.hadoop.util.Progressable; import org.apache.http.annotation.ThreadSafe; @@ -33,7 +34,7 @@ import java.util.Arrays; * A {@link RecordWriter} to write key-value pairs into a temporary key-value store. */ @ThreadSafe -class KeyValueRecordWriter implements RecordWriter<BytesWritable, BytesWritable> { +class KeyValueRecordWriter extends RecordWriter<BytesWritable, BytesWritable> { private final KeyValueStoreWriter mWriter; private final Progressable mProgress; @@ -68,7 +69,7 @@ class KeyValueRecordWriter implements RecordWriter<BytesWritable, BytesWritable> } @Override - public synchronized void close(Reporter reporter) throws IOException { + public synchronized void close(TaskAttemptContext context) throws IOException { // Completes the new store. mWriter.close(); }
Update KeyValueRecordWriter to use the new API
Alluxio_alluxio
train
0fdafa6f9286ff4a3a1b1c36f24bcf23c824bb14
diff --git a/phoebe/frontend/bundle.py b/phoebe/frontend/bundle.py index <HASH>..<HASH> 100644 --- a/phoebe/frontend/bundle.py +++ b/phoebe/frontend/bundle.py @@ -2020,6 +2020,10 @@ class Bundle(ParameterSet): (except twig or context) """ + + if not _devel_enabled: + raise NotImplementedError("'flip_constraint' not officially supported for this release. Enable developer mode to test.") + self._kwargs_checks(kwargs) kwargs['twig'] = twig
flip_constraint is now a developer_mode feature
phoebe-project_phoebe2
train
394877688f150e3ce0612671953fe8c8aab5602c
diff --git a/demo/components/victory-bar-demo.js b/demo/components/victory-bar-demo.js index <HASH>..<HASH> 100644 --- a/demo/components/victory-bar-demo.js +++ b/demo/components/victory-bar-demo.js @@ -192,8 +192,9 @@ export default class App extends React.Component { })} </VictoryStack> + <VictoryChart> <VictoryGroup - offset={15} + offset={10} style={{parent: parentStyle}} animate={{duration: 1000}} colorScale={"qualitative"} @@ -202,6 +203,7 @@ export default class App extends React.Component { return <Wrapper key={index}><VictoryBar key={index} data={data}/></Wrapper>; })} </VictoryGroup> + </VictoryChart> <VictoryGroup style={{parent: parentStyle}} offset={18} diff --git a/src/components/victory-group/victory-group.js b/src/components/victory-group/victory-group.js index <HASH>..<HASH> 100644 --- a/src/components/victory-group/victory-group.js +++ b/src/components/victory-group/victory-group.js @@ -398,9 +398,9 @@ export default class VictoryGroup extends React.Component { const { datasets } = calculatedProps; const childProps = this.getChildProps(props, calculatedProps); const getAnimationProps = Wrapper.getAnimationProps.bind(this); - const noOfChildren = childComponents.length; return childComponents.map((child, index) => { const xOffset = this.getXO(props, calculatedProps, datasets, index); + console.log(props.offset); const data = datasets[index].map((datum) => Object.assign({}, datum, {xOffset})); const style = Wrapper.getChildStyle(child, index, calculatedProps); const labels = props.labels ? this.getLabels(props, datasets, index) : child.props.labels; @@ -411,7 +411,7 @@ export default class VictoryGroup extends React.Component { theme: child.props.theme || props.theme, labelComponent: props.labelComponent || child.props.labelComponent, style, - domainPadding: {x: (props.width / noOfChildren) / 2}, + domainPadding: {x: (props.offset * childComponents.length) / 2}, data, xOffset: child.type.role === "stack-wrapper" ? xOffset : undefined, colorScale: this.getColorScale(props, child) diff --git a/src/components/victory-stack/victory-stack.js b/src/components/victory-stack/victory-stack.js index <HASH>..<HASH> 100644 --- a/src/components/victory-stack/victory-stack.js +++ b/src/components/victory-stack/victory-stack.js @@ -95,10 +95,16 @@ export default class VictoryStack extends React.Component { */ domainPadding: PropTypes.oneOfType([ PropTypes.shape({ - x: CustomPropTypes.nonNegative, - y: CustomPropTypes.nonNegative + x: PropTypes.oneOfType([ + PropTypes.number, + CustomPropTypes.domain + ]), + y: PropTypes.oneOfType([ + PropTypes.number, + CustomPropTypes.domain + ]) }), - CustomPropTypes.nonNegative + PropTypes.number ]), /** * The event prop take an array of event objects. Event objects are composed of
change how domainpadding is calculated
FormidableLabs_victory
train
2deb810fd60c845f6304c514e1ff3f1fc4066e12
diff --git a/doc/src/main/java/fr/putnami/pwt/doc/client/DocumentationApp.java b/doc/src/main/java/fr/putnami/pwt/doc/client/DocumentationApp.java index <HASH>..<HASH> 100644 --- a/doc/src/main/java/fr/putnami/pwt/doc/client/DocumentationApp.java +++ b/doc/src/main/java/fr/putnami/pwt/doc/client/DocumentationApp.java @@ -72,7 +72,7 @@ public class DocumentationApp implements EntryPoint { DocumentationDisplay display = new DocumentationDisplay(); RootPanel.get().add(display); - GoogleAnalytics.get(ApplicationConfig.ANALYTICS_TRACKER_ID).forceSSL(true); + GoogleAnalytics.init(ApplicationConfig.ANALYTICS_TRACKER_ID, ApplicationConfig.DOMAIN).forceSSL(true); SimpleErrorDisplayer errorDisplayer = new SimpleErrorDisplayer(); errorDisplayer.setConstants((ConstantsWithLookup) GWT.create(ErrorConstants.class)); diff --git a/doc/src/main/java/fr/putnami/pwt/doc/client/application/ApplicationConfig.java b/doc/src/main/java/fr/putnami/pwt/doc/client/application/ApplicationConfig.java index <HASH>..<HASH> 100644 --- a/doc/src/main/java/fr/putnami/pwt/doc/client/application/ApplicationConfig.java +++ b/doc/src/main/java/fr/putnami/pwt/doc/client/application/ApplicationConfig.java @@ -20,6 +20,8 @@ public final class ApplicationConfig { public static final String ANALYTICS_TRACKER_ID = "UA-51591008-1"; + public static final String DOMAIN = "putnami.org"; + private ApplicationConfig() { // Nothing to do } diff --git a/doc/src/main/java/fr/putnami/pwt/doc/client/guide/ReferenceGuide.java b/doc/src/main/java/fr/putnami/pwt/doc/client/guide/ReferenceGuide.java index <HASH>..<HASH> 100644 --- a/doc/src/main/java/fr/putnami/pwt/doc/client/guide/ReferenceGuide.java +++ b/doc/src/main/java/fr/putnami/pwt/doc/client/guide/ReferenceGuide.java @@ -154,7 +154,7 @@ public class ReferenceGuide extends Composite implements EntryPoint { ErrorManager.get().setErrorDisplayer(errorDisplayer); ErrorManager.get().registerErrorHandler(new UmbrellaExceptionHandler()); - GoogleAnalytics.get(ApplicationConfig.ANALYTICS_TRACKER_ID).trackPage(); + GoogleAnalytics.init(ApplicationConfig.ANALYTICS_TRACKER_ID, ApplicationConfig.DOMAIN).trackPage(); addHeading("Putnami Web Toolkit", 1); addContent(new WelcomeView(), 0); diff --git a/plugins/google-analytics/src/main/java/fr/putnami/pwt/plugin/ga/client/GoogleAnalytics.java b/plugins/google-analytics/src/main/java/fr/putnami/pwt/plugin/ga/client/GoogleAnalytics.java index <HASH>..<HASH> 100644 --- a/plugins/google-analytics/src/main/java/fr/putnami/pwt/plugin/ga/client/GoogleAnalytics.java +++ b/plugins/google-analytics/src/main/java/fr/putnami/pwt/plugin/ga/client/GoogleAnalytics.java @@ -34,8 +34,19 @@ public abstract class GoogleAnalytics { return ga; } + public static GoogleAnalytics init(String account, String domain) { + GoogleAnalytics ga = cache.get(account); + if (ga == null) { + ga = GWT.create(GoogleAnalytics.class); + ga.initialize(account, domain); + } + return ga; + } + protected abstract void initialize(String account); + protected abstract void initialize(String account, String domain); + public abstract void forceSSL(boolean force); public abstract void trackPage(); diff --git a/plugins/google-analytics/src/main/java/fr/putnami/pwt/plugin/ga/client/GoogleAnalyticsImpl.java b/plugins/google-analytics/src/main/java/fr/putnami/pwt/plugin/ga/client/GoogleAnalyticsImpl.java index <HASH>..<HASH> 100644 --- a/plugins/google-analytics/src/main/java/fr/putnami/pwt/plugin/ga/client/GoogleAnalyticsImpl.java +++ b/plugins/google-analytics/src/main/java/fr/putnami/pwt/plugin/ga/client/GoogleAnalyticsImpl.java @@ -50,9 +50,14 @@ public class GoogleAnalyticsImpl extends GoogleAnalytics implements StartActivit @Override protected void initialize(String account) { + initialize(account, "auto"); + } + + @Override + protected void initialize(String account, String domain) { initScript(); MvpController.get().addStartActivityHandler(this); - createTracker(account); + createTracker(account, domain); } @Override @@ -74,16 +79,9 @@ public class GoogleAnalyticsImpl extends GoogleAnalytics implements StartActivit $wnd.ga.l = 1 * new Date(); }-*/; - private native void createTracker(String account) - /*-{ - $wnd.ga('create', account, 'auto'); - }-*/; - - private native void createLocalhostTracker(String account) + private native void createTracker(String account, String domain) /*-{ - $wnd.ga('create', account, { - 'cookieDomain': 'none' - }); + $wnd.ga('create', account, domain); }-*/; @Override
[google-analytics][feature] init the tracker with the domain name
Putnami_putnami-web-toolkit
train
2a3e4b18e4ee9fe0b25d15cb7cfc3eebbd788c80
diff --git a/phantom/server_test.go b/phantom/server_test.go index <HASH>..<HASH> 100644 --- a/phantom/server_test.go +++ b/phantom/server_test.go @@ -93,7 +93,7 @@ var _ = Describe("Phantom server", func() { It("returns the request error", func() { server.Port = 0 _, err := server.CreateSession() - Expect(err).To(MatchError("Post http://127.0.0.1:0/session: dial tcp 127.0.0.1:0: can't assign requested address")) + Expect(err.Error()).To(ContainSubstring("can't assign requested address")) }) })
Attempt to fix flakey spec on travis
sclevine_agouti
train
fd988896a124a7292167c8fd92ace313c38482a4
diff --git a/lib/mongo/error/operation_failure.rb b/lib/mongo/error/operation_failure.rb index <HASH>..<HASH> 100644 --- a/lib/mongo/error/operation_failure.rb +++ b/lib/mongo/error/operation_failure.rb @@ -35,7 +35,8 @@ module Mongo 'connect failed', 'error querying', 'could not get last error', - 'connection attempt failed' + 'connection attempt failed', + 'interrupted at shutdown' ].freeze # Can the operation that caused the error be retried?
Add 'interrupted at shutdown' to the list of retryable messages, as it can happen when taking a mongoD out of rotation for compaction.
mongodb_mongo-ruby-driver
train
b9c2a5a912b6353105056084b649ccd57c99885d
diff --git a/test/PactVerifierConfigTest.php b/test/PactVerifierConfigTest.php index <HASH>..<HASH> 100644 --- a/test/PactVerifierConfigTest.php +++ b/test/PactVerifierConfigTest.php @@ -52,5 +52,7 @@ class PactVerifierConfigTest extends TestCase $this->assertEquals('http://127.0.10.13:333', $actual, 'The protocol embedded in the URL trumps what is passed in'); $this->assertEquals("127.0.10.13", $config->getBaseUrn(), "Ensure URN is properly set"); $this->assertEquals("333", $config->getPort(), "Ensure port is properly set"); + + $this->assertTrue(false, "Force a failure to see if appveyor fails"); } }
Force a unit test failure for appveyor
pact-foundation_pact-php
train
444d18504bbee9c0cc6086b90a009c60fad4af0e
diff --git a/docs/src/color-variables.js b/docs/src/color-variables.js index <HASH>..<HASH> 100644 --- a/docs/src/color-variables.js +++ b/docs/src/color-variables.js @@ -53,7 +53,7 @@ export {colors, gradientHues, palettes, getPaletteByName, variables} export const allColors = palettes.reduce((all, {values}) => all.concat(values), []) export const borders = Object.keys(variables) - .filter(key => key.startsWith('border-') && !variables[key].includes('$')) + .filter(key => key.startsWith('border-') && !variables[key].includes('$') && key !== 'border-gray-darker') .sort() .map(key => ({ variable: key,
Remove border-gray-darker from list
primer_css
train
4d93868f96def7c230b3aaa608876db05db0f1b9
diff --git a/lib/qx/tool/cli/commands/add/Class.js b/lib/qx/tool/cli/commands/add/Class.js index <HASH>..<HASH> 100644 --- a/lib/qx/tool/cli/commands/add/Class.js +++ b/lib/qx/tool/cli/commands/add/Class.js @@ -109,8 +109,9 @@ qx.Class.define("qx.tool.cli.commands.add.Class", { // check top-level namespace let class_namespaces = argv.classname.split(/\./); - if (class_namespaces[0] !== values.namespace) { - throw new qx.tool.cli.Utils.UserError(`Invalid top namespace '${class_namespaces[0]}'. Must be '${values.namespace}'.`); + let manifest_namepaces = values.namespace.split(/\./); + if (class_namespaces[0] !== manifest_namepaces[0]) { + throw new qx.tool.cli.Utils.UserError(`Invalid top namespace '${class_namespaces[0]}'. Must be '${manifest_namepaces[0]}'.`); } // get path to the template file
Fixes a bug where the top namespace was wrongly compared with the given full namespace
qooxdoo_qooxdoo-compiler
train
f4d0a7528dd1402297393cf4cfa476e74309d33a
diff --git a/lib/clickhouse/cli/console.rb b/lib/clickhouse/cli/console.rb index <HASH>..<HASH> 100644 --- a/lib/clickhouse/cli/console.rb +++ b/lib/clickhouse/cli/console.rb @@ -153,23 +153,25 @@ module Clickhouse def self.print_result(result) if result.is_a?(Clickhouse::Connection::Query::ResultSet) - array = [result.names].concat(result.to_a) - lengths = array.inject([]) do |lengths, row| - row.each_with_index do |value, index| - length = value.to_s.strip.length - lengths[index] = [lengths[index].to_i, length].max + if result.size > 0 + array = [result.names].concat(result.to_a) + lengths = array.inject([]) do |lengths, row| + row.each_with_index do |value, index| + length = value.to_s.strip.length + lengths[index] = [lengths[index].to_i, length].max + end + lengths end - lengths - end - puts - array.each_with_index do |row, i| - values = [nil] - lengths.each_with_index do |length, index| - values << row[index].to_s.ljust(length, " ") + puts + array.each_with_index do |row, i| + values = [nil] + lengths.each_with_index do |length, index| + values << row[index].to_s.ljust(length, " ") + end + values << nil + separator = (i == 0) ? "+" : "|" + puts values.join(" #{separator} ") end - values << nil - separator = (i == 0) ? "+" : "|" - puts values.join(" #{separator} ") end else puts result == true ? "Ok." : result
Not printing headers if result set is empty
archan937_clickhouse
train
3f007d9f7d25d93d276931a952b149dd27d0707c
diff --git a/packages/components/bolt-tabs/__tests__/tabs.e2e.js b/packages/components/bolt-tabs/__tests__/tabs.e2e.js index <HASH>..<HASH> 100644 --- a/packages/components/bolt-tabs/__tests__/tabs.e2e.js +++ b/packages/components/bolt-tabs/__tests__/tabs.e2e.js @@ -63,8 +63,8 @@ module.exports = { console.log(`global browser url: ${testingUrl}`); currentBrowser = '--' + browser.currentEnv || 'chrome'; let testName = 'tabs-adaptive-menu'; - const video = 'bolt-video'; - const videoPlayer = 'bolt-video video-js'; // click on video element not button itself + const video = 'video-js'; + const videoPlayer = 'video-js'; // click on video element not button itself browser .url( @@ -97,13 +97,13 @@ module.exports = { .assert.cssClassPresent(videoPlayer, ['vjs-paused']) .execute( function(data) { - return document.querySelector('bolt-video').player.currentTime(); + return document.querySelector('video-js').player.currentTime(); }, [], function(result) { browser.assert.ok( result.value > 1, - `<bolt-video> starts playing when <bolt-button> is clicked -- verified since the current video's play time is ${result.value} seconds`, + `<video-js> starts playing when <bolt-button> is clicked -- verified since the current video's play time is ${result.value} seconds`, ); }, )
WWW-<I>: updated the tabs test that tests for a tabbed video
bolt-design-system_bolt
train
db9ba81f322ddbd17648ac4ca833efdbaec66128
diff --git a/cellbase-server/src/main/java/org/opencb/cellbase/server/ws/genomic/VariantWSServer.java b/cellbase-server/src/main/java/org/opencb/cellbase/server/ws/genomic/VariantWSServer.java index <HASH>..<HASH> 100755 --- a/cellbase-server/src/main/java/org/opencb/cellbase/server/ws/genomic/VariantWSServer.java +++ b/cellbase-server/src/main/java/org/opencb/cellbase/server/ws/genomic/VariantWSServer.java @@ -270,14 +270,15 @@ public class VariantWSServer extends GenericRestWSServer { id = variationQueryResultList.get(i).getResult().toString(); } + // TODO: start & end are both being set to variantList.get(i).getPosition(), modify this for indels variantAnnotation = new VariantAnnotation(variantList.get(i).getChromosome(), variantList.get(i).getPosition(),variantList.get(i).getPosition(),variantList.get(i).getReference(),variantList.get(i).getAlternative()); variantAnnotation.setId(id); variantAnnotation.setClinicalData(phenotype); variantAnnotation.setConsequenceTypes(consequenceTypeList); - clinicalQueryResult.setResult(Arrays.asList(variantAnnotation)); - + clinicalQueryResult.setResult(Collections.singletonList(variantAnnotation)); + i++; } return createOkResponse(clinicalQueryResultList);
feature/consequence-type: small bug fixed at VariantWSServer
opencb_cellbase
train
27efab4c8d7f450daee5bfb9d2fca6e9617c1e0b
diff --git a/src/views/user/profile.blade.php b/src/views/user/profile.blade.php index <HASH>..<HASH> 100755 --- a/src/views/user/profile.blade.php +++ b/src/views/user/profile.blade.php @@ -68,9 +68,9 @@ Admin area: modifica profilo utente <span class="text-danger">{{$errors->first('billing_city')}}</span> {{FormField::billing_address_zip(["label" => "CAP fatturazione", "autocomplete" => "off"])}} <span class="text-danger">{{$errors->first('billing_address_zip')}}</span> - {{FormField::billing_state(["label" => "Provincia fatturazione", "autocomplete" => "off"])}} + {{FormField::billing_country(["label" => "Provincia fatturazione", "autocomplete" => "off"])}} <span class="text-danger">{{$errors->first('billing_country')}}</span> - {{FormField::billing_country(["label" => "Nazione fatturazione", "autocomplete" => "off"])}} + {{FormField::billing_state(["label" => "Nazione fatturazione", "autocomplete" => "off"])}} <span class="text-danger">{{$errors->first('billing_state')}}</span> </div> @@ -82,9 +82,9 @@ Admin area: modifica profilo utente <span class="text-danger">{{$errors->first('shipping_city')}}</span> {{FormField::shipping_address_zip(["label" => "CAP spedizione", "autocomplete" => "off"])}} <span class="text-danger">{{$errors->first('shipping_address_zip')}}</span> - {{FormField::shipping_state(["label" => "Provincia spedizione", "autocomplete" => "off"])}} + {{FormField::shipping_country(["label" => "Provincia spedizione", "autocomplete" => "off"])}} <span class="text-danger">{{$errors->first('shipping_country')}}</span> - {{FormField::shipping_country(["label" => "Nazione spedizione", "autocomplete" => "off"])}} + {{FormField::shipping_state(["label" => "Nazione spedizione", "autocomplete" => "off"])}} <span class="text-danger">{{$errors->first('shipping_state')}}</span>
fix state e country in profile invertiti
Palmabit-IT_authenticator
train
a256da301c044023edada60c4dde2aac79c988cd
diff --git a/src/feat/agencies/bootstrap.py b/src/feat/agencies/bootstrap.py index <HASH>..<HASH> 100755 --- a/src/feat/agencies/bootstrap.py +++ b/src/feat/agencies/bootstrap.py @@ -6,7 +6,8 @@ from feat import everything from feat.agents.base import descriptor from feat.agents.common import host from feat.common import log, run, defer -from feat.interface.agent import Access, Address, Storage +from feat.interface.agent import (Access, Address, Storage, + AgencyAgentState, ) def add_options(parser): @@ -127,6 +128,7 @@ def bootstrap(parser=None, args=None, descriptors=None): d.addCallback(defer.drop_result, conn.save_document, host_desc) d.addCallbacks(agency.start_agent, agency._error_handler, callbackKeywords=host_kwargs) + d.addCallbacks(lambda medium: medium.wait_for_state(AgencyAgentState.ready)) # Starting the other agents diff --git a/src/feat/agencies/common.py b/src/feat/agencies/common.py index <HASH>..<HASH> 100644 --- a/src/feat/agencies/common.py +++ b/src/feat/agencies/common.py @@ -34,9 +34,11 @@ class StateMachineMixin(object): def wait_for_state(self, *states): if self.state in states: return defer.succeed(self) - return defer.DeferredList( + d = defer.DeferredList( map(lambda state: self._notifier.wait(state), states), fireOnOneCallback=True) + d.addCallback(lambda _: self) + return d def _set_state(self, state): if not self.state or not (state == self.state):
Wait for host to be ready before starting anything else
f3at_feat
train
842c66ae389f81e0bc271e3aceada7e6debde6e8
diff --git a/examples/helloRPC/jsclient.js b/examples/helloRPC/jsclient.js index <HASH>..<HASH> 100644 --- a/examples/helloRPC/jsclient.js +++ b/examples/helloRPC/jsclient.js @@ -3,7 +3,7 @@ "use strict"; -var hello = require("hello"); +var hello = require("hello").hello; var client = new hello.HelloClient("http://127.0.0.1:8910/hello"); var request = new hello.Request(); diff --git a/examples/helloRPC/jsserver.js b/examples/helloRPC/jsserver.js index <HASH>..<HASH> 100644 --- a/examples/helloRPC/jsserver.js +++ b/examples/helloRPC/jsserver.js @@ -3,7 +3,7 @@ "use strict"; -var hello = require("hello"); +var hello = require("hello").hello; function HelloImpl() { this.hello = function(request) {
Fix hello example, broken by accident during merge
datawire_quark
train
5f94811f24d28ba06f634bd245cb4d9d6ef8e50e
diff --git a/lib/jsi/pathed_node.rb b/lib/jsi/pathed_node.rb index <HASH>..<HASH> 100644 --- a/lib/jsi/pathed_node.rb +++ b/lib/jsi/pathed_node.rb @@ -37,7 +37,7 @@ module JSI # @yield [Object, Object] each key and value of this hash node # @return [self, Enumerator] def each(&block) - return to_enum(__method__) { node_content_hash_pubsend(:size) } unless block_given? + return to_enum(__method__) { node_content_hash_pubsend(:size) } unless block if block.arity > 1 node_content_hash_pubsend(:each_key) { |k| yield k, self[k] } else @@ -82,8 +82,8 @@ module JSI # # @yield [Object] each element of this array node # @return [self, Enumerator] - def each - return to_enum(__method__) { node_content_ary_pubsend(:size) } unless block_given? + def each(&block) + return to_enum(__method__) { node_content_ary_pubsend(:size) } unless block node_content_ary_pubsend(:each_index) { |i| yield(self[i]) } self end diff --git a/lib/jsi/typelike_modules.rb b/lib/jsi/typelike_modules.rb index <HASH>..<HASH> 100644 --- a/lib/jsi/typelike_modules.rb +++ b/lib/jsi/typelike_modules.rb @@ -115,7 +115,7 @@ module JSI end self_respondingto_key = self.respond_to?(:key?) ? self : to_hash other.to_hash.each_pair do |key, value| - if block_given? && self_respondingto_key.key?(key) + if block && self_respondingto_key.key?(key) value = yield(key, self[key], value) end self[key] = value
m use local `block` variable, don't need to call block_given?
notEthan_jsi
train
b6f8a67fdb7207a0d090ad212bdab6ad42410f25
diff --git a/app/controllers/integral/posts_controller.rb b/app/controllers/integral/posts_controller.rb index <HASH>..<HASH> 100644 --- a/app/controllers/integral/posts_controller.rb +++ b/app/controllers/integral/posts_controller.rb @@ -3,6 +3,7 @@ module Integral class PostsController < BlogController before_action :find_post, only: [:show] before_action :find_related_posts, only: [:show] + before_action :validate_page_has_results, only: [:index] after_action :increment_post_count, only: [:show] # GET / @@ -83,5 +84,11 @@ module Integral # a 301 redirect that uses the current friendly id. redirect_to post_url(@post.slug), status: :moved_permanently if request.path != post_path(@post.slug) end + + def validate_page_has_results + if !params[:page].nil? && Integral::Post.published.where(locale: I18n.locale).paginate(page: params[:page]).empty? + raise ActionController::RoutingError, 'Invalid Page Number' + end + end end end diff --git a/app/controllers/integral/tags_controller.rb b/app/controllers/integral/tags_controller.rb index <HASH>..<HASH> 100644 --- a/app/controllers/integral/tags_controller.rb +++ b/app/controllers/integral/tags_controller.rb @@ -2,6 +2,7 @@ module Integral # Front end tags controller class TagsController < BlogController before_action :find_tag, only: [:show] + before_action :validate_page_has_results, only: [:show] # GET / # List blog tags @@ -37,5 +38,11 @@ module Integral super add_breadcrumb t('integral.breadcrumbs.blog'), :posts_url end + + def validate_page_has_results + if !params[:page].nil? && Integral::Post.tagged_with(@tag.name).published.paginate(page: params[:page]).empty? + raise ActionController::RoutingError, 'Invalid Page Number' + end + end end end
Blog - Throw <I> when visitors try to access pages which do not (or no longer) exist
yamasolutions_integral
train
d4b7ba6670e405332e180cba9e173c6fd16b34ba
diff --git a/shared/validate/validate.go b/shared/validate/validate.go index <HASH>..<HASH> 100644 --- a/shared/validate/validate.go +++ b/shared/validate/validate.go @@ -262,10 +262,6 @@ func IsNetworkAddressV6(value string) error { // IsNetworkAddressCIDRV6 validates an IPv6 addresss string in CIDR format. If string is empty, returns valid. func IsNetworkAddressCIDRV6(value string) error { - if value == "" { - return nil - } - ip, subnet, err := net.ParseCIDR(value) if err != nil { return err
shared/validate: Makes IsNetworkAddressCIDRV6 non-optional
lxc_lxd
train
f7ee1796bc57241ff9a954c1696a2d7314454c95
diff --git a/pylsdj/bread_spec.py b/pylsdj/bread_spec.py index <HASH>..<HASH> 100644 --- a/pylsdj/bread_spec.py +++ b/pylsdj/bread_spec.py @@ -324,27 +324,31 @@ softsynth = [ b.padding(8 * 3) ] +FX_COMMANDS = { + 0: '-', + 1: 'A', + 2: 'C', + 3: 'D', + 4: 'E', + 5: 'F', + 6: 'G', + 7: 'H', + 8: 'K', + 9: 'L', + 10: 'M', + 11: 'O', + 12: 'P', + 13: 'R', + 14: 'S', + 15: 'T', + 16: 'V', + 17: 'W', + 18: 'Z' +} + table_command = [ - ("fx", b.array(NUM_TABLES, b.array(STEPS_PER_TABLE, b.enum(8, { - 0: '-', - 1: 'A', - 2: 'C', - 4: 'E', - 5: 'F', - 6: 'G', - 7: 'H', - 8: 'K', - 9: 'L', - 10: 'M', - 11: 'O', - 12: 'P', - 13: 'R', - 14: 'S', - 15: 'T', - 16: 'V', - 17: 'W', - 18: 'Z' - })))), + ("fx", b.array(NUM_TABLES, + b.array(STEPS_PER_TABLE, b.enum(8, FX_COMMANDS)))), ("val", b.array(NUM_TABLES, b.array(STEPS_PER_TABLE, b.byte))) ] @@ -497,7 +501,8 @@ song = [ ("wave_synth_overwrite_lock", b.array(2, b.byte)), b.padding(8 * 58), # Beginning of bank 2 - ("phrase_fx", b.array(NUM_PHRASES, b.array(STEPS_PER_PHRASE, b.byte))), + ("phrase_fx", b.array(NUM_PHRASES, b.array( + STEPS_PER_PHRASE, b.enum(8, FX_COMMANDS)))), ("phrase_fx_val", b.array(NUM_PHRASES, b.array(STEPS_PER_PHRASE, b.byte))), b.padding(32 * 8), # Beginning of bank 3
Re-use the fx commands enum in phrases.
alexras_pylsdj
train
7996250b80c992f88b8487e36ee2dd6e05645ccd
diff --git a/activejdbc/src/main/java/org/javalite/activejdbc/cache/CacheEvent.java b/activejdbc/src/main/java/org/javalite/activejdbc/cache/CacheEvent.java index <HASH>..<HASH> 100644 --- a/activejdbc/src/main/java/org/javalite/activejdbc/cache/CacheEvent.java +++ b/activejdbc/src/main/java/org/javalite/activejdbc/cache/CacheEvent.java @@ -53,7 +53,7 @@ public class CacheEvent { */ public CacheEvent( String group, String source){ if(group == null) - throw new IllegalArgumentException("group canot be null"); + throw new IllegalArgumentException("group cannot be null"); this.type = CacheEventType.GROUP; this.source = source; diff --git a/activejdbc/src/main/java/org/javalite/activejdbc/cache/CacheManager.java b/activejdbc/src/main/java/org/javalite/activejdbc/cache/CacheManager.java index <HASH>..<HASH> 100644 --- a/activejdbc/src/main/java/org/javalite/activejdbc/cache/CacheManager.java +++ b/activejdbc/src/main/java/org/javalite/activejdbc/cache/CacheManager.java @@ -56,12 +56,25 @@ public abstract class CacheManager { /** - * Flash cache. + * Flashes cache. * + * @param propagate true to propagate event to listeners, false to not propagate * @param event type of caches to flush. */ - public final void flush(CacheEvent event){ + public final void flush(CacheEvent event, boolean propagate){ doFlush(event); + if(propagate){ + propagate(event); + } + + if (logger.isInfoEnabled()) { + String message = "Cache purged: " + (event.getType() == CacheEvent.CacheEventType.ALL + ? "all caches" : "table: " + event.getGroup()); + LogFilter.log(logger, message); + } + } + + private void propagate(CacheEvent event){ for(CacheEventListener listener: listeners){ try{ listener.onFlush(event); @@ -69,11 +82,16 @@ public abstract class CacheManager { logger.warn("failed to propagate cache event: {} to listener: {}", event, listener, e); } } - if (logger.isInfoEnabled()) { - String message = "Cache purged: " + (event.getType() == CacheEvent.CacheEventType.ALL - ? "all caches" : "table: " + event.getGroup()); - LogFilter.log(logger, message); - } + } + + + /** + * Flashes cache. + * + * @param event type of caches to flush. + */ + public final void flush(CacheEvent event){ + flush(event, true); } public final void addCacheEventListener(CacheEventListener listener){ diff --git a/activejdbc/src/test/java/org/javalite/activejdbc/CacheTest.java b/activejdbc/src/test/java/org/javalite/activejdbc/CacheTest.java index <HASH>..<HASH> 100644 --- a/activejdbc/src/test/java/org/javalite/activejdbc/CacheTest.java +++ b/activejdbc/src/test/java/org/javalite/activejdbc/CacheTest.java @@ -28,6 +28,8 @@ import org.junit.Test; import java.util.List; +import static org.javalite.test.jspec.JSpec.$; + /** * @author Igor Polevoy @@ -156,22 +158,33 @@ public class CacheTest extends ActiveJDBCTest { int count = 0; @Test public void shouldNotPropagateCacheEventForNonCachedModels(){ - CacheEventListener cl = new CacheEventListener() { public void onFlush(CacheEvent event) { count++; } }; - - QueryCache.instance().getCacheManager().addCacheEventListener(cl); + Registry.cacheManager().addCacheEventListener(cl); Person.deleteAll(); a(count).shouldBeEqual(1); + Account.deleteAll(); + a(count).shouldBeEqual(1); + } + + int count1 = 0; + @Test + public void shouldNotPropagateCacheEventOnFlush(){ + CacheEventListener cl = new CacheEventListener() { + public void onFlush(CacheEvent event) { + count1++; + } + }; + Registry.cacheManager().addCacheEventListener(cl); + Registry.cacheManager().flush(new CacheEvent("people", "blah"), false); - Account.deleteAll(); + $(count1).shouldBeEqual(0); - a(count).shouldBeEqual(1); - } + } }
#<I> Implement possibility to stop cache event propagation
javalite_activejdbc
train
2873c61c9b12942ad17b878595ab9cbf3b54c158
diff --git a/app/models/bento_search/result_item.rb b/app/models/bento_search/result_item.rb index <HASH>..<HASH> 100644 --- a/app/models/bento_search/result_item.rb +++ b/app/models/bento_search/result_item.rb @@ -138,10 +138,10 @@ module BentoSearch # Manually set language_str will over-ride display string calculated from # language_code. # - # Consumers can look at language_code or language_str regardless (although - # either or both may be nil). You can get a language_list gem obj from - # language_obj, and use to normalize to a - # 2- or 3-letter from language_code that could be either. + # Consumers that want a language code can use #language_iso_639_1 or + # #language_iso_639_2 (either may be null), or #language_str for uncontrolled + # string. If engine just sets one of these, internals take care of filling + # out the others. r attr_accessor :language_code attr_writer :language_str def language_str @@ -159,6 +159,16 @@ module BentoSearch @language_obj ||= LanguageList::LanguageInfo.find( self.language_code ) end + # Two letter ISO language code, or nil + def language_iso_639_1 + language_obj.try { |l| l.iso_639_1 } + end + + # Three letter ISO language code, or nil + def language_iso_639_3 + language_obj.try {|l| l.iso_639_3 } + end + # year published. a ruby int # PART of:. # * schema.org CreativeWork "datePublished", year portion
ResultItem: convenience methods for ISO <I>-1 and -3
jrochkind_bento_search
train
2444556cebc10bd0a1bde6c004cd1c2e9538a72b
diff --git a/aeron-archiver/src/main/java/io/aeron/archiver/ArchiveStreamFragmentReader.java b/aeron-archiver/src/main/java/io/aeron/archiver/ArchiveStreamFragmentReader.java index <HASH>..<HASH> 100644 --- a/aeron-archiver/src/main/java/io/aeron/archiver/ArchiveStreamFragmentReader.java +++ b/aeron-archiver/src/main/java/io/aeron/archiver/ArchiveStreamFragmentReader.java @@ -58,6 +58,7 @@ class ArchiveStreamFragmentReader implements AutoCloseable this.streamInstanceId = streamInstanceId; this.archiveFolder = archiveFolder; final String archiveMetaFileName = ArchiveFileUtil.archiveMetaFileName(streamInstanceId); + // TODO: Should this just be read rather than mapped given the one of read? final File archiveMetaFile = new File(archiveFolder, archiveMetaFileName); final ArchiveDescriptorDecoder metaDecoder = ArchiveFileUtil.archiveMetaFileFormatDecoder(archiveMetaFile); termBufferLength = metaDecoder.termBufferLength();
[Java] Add TODO to query if mapping is a good idea when only a small number of bytes are read once?
real-logic_aeron
train
bf451407454853873305e25f7026e97a4119694d
diff --git a/lib/appium_lib/ios/helper.rb b/lib/appium_lib/ios/helper.rb index <HASH>..<HASH> 100644 --- a/lib/appium_lib/ios/helper.rb +++ b/lib/appium_lib/ios/helper.rb @@ -151,8 +151,8 @@ module Appium::Ios # Prints a string of interesting elements to the console. # @return [void] - def page - get_page + def page window_number = 0 + get_page source_window window_number || 0 nil end
page on iOS now takes window number The number can be any int >= 0. Examples: page 0 # regular app page page 1 # wifi page 2 # alerts Fix #<I>
appium_ruby_lib
train
19852f8426302d787b7776b6a5a8d39849ef0182
diff --git a/Dropbox/OAuth/Consumer/ConsumerAbstract.php b/Dropbox/OAuth/Consumer/ConsumerAbstract.php index <HASH>..<HASH> 100644 --- a/Dropbox/OAuth/Consumer/ConsumerAbstract.php +++ b/Dropbox/OAuth/Consumer/ConsumerAbstract.php @@ -46,11 +46,11 @@ abstract class ConsumerAbstract protected function authenticate() { if ((!$this->storage->get('access_token'))) { - if (!$this->storage->get('request_token')) { + try { + $this->getAccessToken(); + } catch(\Dropbox\Exception $e) { $this->getRequestToken(); $this->authorise(); - } else { - $this->getAccessToken(); } } }
Added try/catch to prevent Exception when invalid/expired request token is supplied
BenExile_Dropbox
train
5c6ce768da49d489c151c57553a33cc779af305d
diff --git a/squad/api/rest.py b/squad/api/rest.py index <HASH>..<HASH> 100644 --- a/squad/api/rest.py +++ b/squad/api/rest.py @@ -29,6 +29,7 @@ from squad.core.models import ( Status, Callback, ) +from squad.core.failures import failures_with_confidence from squad.core.tasks import prepare_report, update_delayed_report from squad.core.comparison import TestComparison, MetricComparison from squad.core.queries import test_confidence @@ -878,6 +879,10 @@ class BuildViewSet(NestedViewSetMixin, ModelViewSet): Returns list of Test objects belonging to this build. List is paginated + * `api/builds/<id>/failures_with_confidence` GET + + List of failing tests with confidence scores. List is paginated + * `api/builds/<id>/metrics` GET Returns list of Metric objects belonging to this build. List is paginated @@ -971,6 +976,26 @@ class BuildViewSet(NestedViewSetMixin, ModelViewSet): except ProjectStatus.DoesNotExist: raise NotFound() + @action(detail=True, methods=['get'], suffix='failures_with_confidence') + def failures_with_confidence(self, request, pk=None): + build = self.get_object() + failures = build.tests.filter( + result=False, + ).exclude( + has_known_issues=True, + ).only( + 'suite__slug', 'metadata__name', 'metadata__id', + ).order_by( + 'suite__slug', 'metadata__name', + ).values_list( + 'suite__slug', 'metadata__name', 'metadata__id', named=True, + ) + + page = self.paginate_queryset(failures) + fwc = failures_with_confidence(build.project, build, page) + serializer = FailuresWithConfidenceSerializer(fwc, many=True, context={'request': request}) + return self.get_paginated_response(serializer.data) + @action(detail=True, methods=['get'], suffix='test runs') def testruns(self, request, pk=None): testruns = self.get_object().test_runs.prefetch_related( @@ -1273,6 +1298,19 @@ class TestSerializer(DynamicFieldsModelSerializer, serializers.HyperlinkedModelS exclude = ['metadata'] +class ConfidenceSerializer(serializers.BaseSerializer): + def to_representation(self, confidence): + return { + "count" : confidence.count, + "passes" : confidence.passes, + "score": confidence.score, + } + + +class FailuresWithConfidenceSerializer(TestSerializer): + confidence = ConfidenceSerializer() + + class TestViewSet(NestedViewSetMixin, ModelViewSet): queryset = Test.objects.prefetch_related('metadata').all() diff --git a/test/api/test_rest.py b/test/api/test_rest.py index <HASH>..<HASH> 100644 --- a/test/api/test_rest.py +++ b/test/api/test_rest.py @@ -721,6 +721,49 @@ class RestApiTest(APITestCase): data = self.hit('/api/builds/%d/tests/?environment__slug=myenv&suite__slug=foooooooosuitedoestexist' % self.build.id) self.assertEqual(0, len(data['results'])) + def test_build_failures_with_confidence(self): + data = self.hit('/api/builds/%d/failures_with_confidence/' % self.build3.id) + + self.assertEqual(data['count'], 18) + self.assertIsNone(data['next']) + self.assertIsNone(data['previous']) + self.assertEqual(len(data['results']), 18) + + failure = data['results'].pop(0) + self.assertEqual(failure['name'], 'bar/test2') + self.assertEqual(failure['result'], False) + self.assertEqual(failure['status'], 'fail') + self.assertEqual(failure['confidence'], {'count': 2, 'passes': 0, 'score': 0.0}) + + def test_build_failures_with_confidence_with_first_build(self): + """ + The first build will not have any history, so the confidence scores for those failures should all be zero + """ + data = self.hit('/api/builds/%d/failures_with_confidence/' % self.build.id) + + for f in data['results']: + self.assertEqual(f['confidence'], {'count': 0, 'passes': 0, 'score': 0}) + + def test_build_failures_with_confidence_with_pagination(self): + data = self.hit('/api/builds/%d/failures_with_confidence/?limit=2' % self.build3.id) + + self.assertEqual(data['count'], 18) + self.assertIsNotNone(data['next']) + self.assertIsNone(data['previous']) + self.assertEqual(len(data['results']), 2) + + failure = data['results'][0] + self.assertEqual(failure['name'], 'bar/test2') + self.assertEqual(failure['result'], False) + self.assertEqual(failure['status'], 'fail') + self.assertEqual(failure['confidence'], {'count': 2, 'passes': 0, 'score': 0.0}) + + failure = data['results'][1] + self.assertEqual(failure['name'], 'bar/test2') + self.assertEqual(failure['result'], False) + self.assertEqual(failure['status'], 'fail') + self.assertEqual(failure['confidence'], {'count': 2, 'passes': 0, 'score': 0.0}) + def test_build_metrics(self): data = self.hit('/api/builds/%d/metrics/' % self.build.id) self.assertEqual(1, len(data['results']))
squad: api: rest: add failures_with_confidence endpoint Add an endpoint that returns a build's failures with confidence data set
Linaro_squad
train
5c3f06074fde515b7f2904758747a741f956009a
diff --git a/intake/catalog/base.py b/intake/catalog/base.py index <HASH>..<HASH> 100644 --- a/intake/catalog/base.py +++ b/intake/catalog/base.py @@ -10,7 +10,7 @@ from requests.compat import urljoin, urlparse from ..auth.base import BaseClientAuth from .entry import CatalogEntry from .remote import RemoteCatalogEntry -from .utils import flatten, reload_on_change +from .utils import flatten, reload_on_change, RemoteCatalogError from ..source.base import DataSource logger = logging.getLogger('intake') @@ -247,9 +247,13 @@ class RemoteCatalog(Catalog): 'page[size]': self._page_size} response = requests.get(self.info_url, params=params, **self._get_http_args()) - if response.status_code != 200: - raise Exception('%s: status code %d' % (response.url, - response.status_code)) + # Produce a chained exception with both the underlying HTTPError + # and our own more direct context. + try: + response.raise_for_status() + except HTTPError: + raise RemoteCatalogError( + "Failed to fetch page of entries.") info = msgpack.unpackb(response.content, encoding='utf-8') page = {source['name']: RemoteCatalogEntry( url=self.source_url, @@ -267,9 +271,11 @@ class RemoteCatalog(Catalog): **self._get_http_args()) if response.status_code == 404: raise KeyError(name) - if response.status_code != 200: - raise Exception('%s: status code %d' % (response.url, - response.status_code)) + try: + response.raise_for_status() + except HTTPError: + raise RemoteCatalogError( + "Failed to fetch entry {!r}.".format(name)) info = msgpack.unpackb(response.content, encoding='utf-8') return RemoteCatalogEntry( url=self.source_url, @@ -401,9 +407,11 @@ class RemoteCatalog(Catalog): params = {'page[number]': 1, 'page[size]': 0} response = requests.get(self.info_url, params=params, **self._get_http_args()) - if response.status_code != 200: - raise Exception('%s: status code %d' % (response.url, - response.status_code)) + try: + response.raise_for_status() + except HTTPError: + raise RemoteCatalogError( + "Failed to fetch metadata {!r}.".format(name)) info = msgpack.unpackb(response.content, encoding='utf-8') self.metadata = info['metadata'] self._entries.reset() diff --git a/intake/catalog/utils.py b/intake/catalog/utils.py index <HASH>..<HASH> 100644 --- a/intake/catalog/utils.py +++ b/intake/catalog/utils.py @@ -155,3 +155,7 @@ def coerce(dtype, value): return value op = COERCION_RULES[dtype] return op() if value is None else op(value) + + +class RemoteCatalogError(Exception): + pass
Produce better exceptions for HTTP errors.
intake_intake
train
0bca12977558bb79ccdd931cdaa9ffcda56193cb
diff --git a/mod/choice/lib.php b/mod/choice/lib.php index <HASH>..<HASH> 100644 --- a/mod/choice/lib.php +++ b/mod/choice/lib.php @@ -269,6 +269,12 @@ function choice_user_submit_response($formanswer, $choice, $userid, $course, $cm $formanswers = array($formanswer); } + $options = $DB->get_records('choice_options', array('choiceid' => $choice->id), '', 'id'); + foreach ($formanswers as $key => $val) { + if (!isset($options[$val])) { + print_error('cannotsubmit', 'choice', $continueurl); + } + } // Start lock to prevent synchronous access to the same data // before it's updated, if using limits. if ($choice->limitanswers) { diff --git a/mod/choice/tests/lib_test.php b/mod/choice/tests/lib_test.php index <HASH>..<HASH> 100644 --- a/mod/choice/tests/lib_test.php +++ b/mod/choice/tests/lib_test.php @@ -131,6 +131,28 @@ class mod_choice_lib_testcase extends externallib_advanced_testcase { } + public function test_choice_user_submit_response_validation() { + global $USER; + + $this->resetAfterTest(); + + $this->setAdminUser(); + // Setup test data. + $course = $this->getDataGenerator()->create_course(); + $choice1 = $this->getDataGenerator()->create_module('choice', array('course' => $course->id)); + $choice2 = $this->getDataGenerator()->create_module('choice', array('course' => $course->id)); + $cm = get_coursemodule_from_instance('choice', $choice1->id); + + $choicewithoptions1 = choice_get_choice($choice1->id); + $choicewithoptions2 = choice_get_choice($choice2->id); + $optionids1 = array_keys($choicewithoptions1->option); + $optionids2 = array_keys($choicewithoptions2->option); + + // Make sure we cannot submit options from a different choice instance. + $this->setExpectedException('moodle_exception'); + choice_user_submit_response($optionids2[0], $choice1, $USER->id, $course, $cm); + } + /** * Test choice_get_my_response * @return void
MDL-<I> mod_choice: Validate the submitted optionid Make sure any submitted choice options actually belong to the current choice module.
moodle_moodle
train
f23721c6cffb62cddf652742beaec2c4f3c70a3d
diff --git a/src/main/java/com/hubspot/jinjava/el/JinjavaInterpreterResolver.java b/src/main/java/com/hubspot/jinjava/el/JinjavaInterpreterResolver.java index <HASH>..<HASH> 100644 --- a/src/main/java/com/hubspot/jinjava/el/JinjavaInterpreterResolver.java +++ b/src/main/java/com/hubspot/jinjava/el/JinjavaInterpreterResolver.java @@ -175,7 +175,11 @@ public class JinjavaInterpreterResolver extends SimpleResolver { // super class getValue returns null for them. To make negative // indices work as they do in python, detect them here and convert // to the equivalent positive index. - if (base.getClass().isArray() && (property instanceof Number)) { + // + // Check for Integer or Long instead of Number so the behavior for a + // floating-point index doesn't change (e.g. -1.5 stays -1.5, it + // doesn't become -1). + if (base.getClass().isArray() && ((property instanceof Integer) || (property instanceof Long))) { int propertyNum = ((Number)property).intValue(); if (propertyNum < 0) { propertyNum += ((Object[])base).length; diff --git a/src/test/java/com/hubspot/jinjava/el/ExtendedSyntaxBuilderTest.java b/src/test/java/com/hubspot/jinjava/el/ExtendedSyntaxBuilderTest.java index <HASH>..<HASH> 100644 --- a/src/test/java/com/hubspot/jinjava/el/ExtendedSyntaxBuilderTest.java +++ b/src/test/java/com/hubspot/jinjava/el/ExtendedSyntaxBuilderTest.java @@ -274,6 +274,8 @@ public class ExtendedSyntaxBuilderTest { assertThat(val("stringToSplit.split('-')")).isEqualTo(new String[]{ "one", "two", "three", "four", "five" }); assertThat(val("stringToSplit.split('-')[-1]")).isEqualTo("five"); + assertThat(val("stringToSplit.split('-')[1.5]")).isEqualTo(""); + assertThat(val("stringToSplit.split('-')[-1.5]")).isEqualTo(""); // out of range returns null, as -6 + the length of the array is still // negative, and java doesn't support negative array indices.
don't change the behavior of negative float indices
HubSpot_jinjava
train
afdabc8cf6eaefe192a073d4fdf3864f89248620
diff --git a/src/Data/Entity/Base.php b/src/Data/Entity/Base.php index <HASH>..<HASH> 100644 --- a/src/Data/Entity/Base.php +++ b/src/Data/Entity/Base.php @@ -11,7 +11,9 @@ abstract class Base extends \Flancer32\Lib\DataObject implements \Praxigento\Core\Data\IEntity { - /** @inheritdoc */ + /** + * @return string + */ public function getEntityName() { return static::ENTITY_NAME; // "static::" will use child attribute value diff --git a/src/Data/IEntity.php b/src/Data/IEntity.php index <HASH>..<HASH> 100644 --- a/src/Data/IEntity.php +++ b/src/Data/IEntity.php @@ -20,7 +20,7 @@ interface IEntity /** * Get array with names of the primary key attributes. * - * @return array + * @return string[] */ public function getPrimaryKeyAttrs(); } \ No newline at end of file
MOBI-<I> - REST API operation to get PV data for the order
praxigento_mobi_mod_core
train
fbed30d478a41e1599eb740d6d17ce09924bef1e
diff --git a/ModulesServiceProvider.php b/ModulesServiceProvider.php index <HASH>..<HASH> 100644 --- a/ModulesServiceProvider.php +++ b/ModulesServiceProvider.php @@ -90,7 +90,7 @@ class ModulesServiceProvider extends ServiceProvider */ protected function registerServices() { - $this->app->bindShared('modules', function ($app) { + $this->app->singleton('modules', function ($app) { $path = $app['config']->get('modules.paths.modules'); return new Repository($app, $path);
Fixing deprecated method bindShared Switched to singleton
pingpong-labs_modules
train
2ee2e29262dfbaf34f77d116c1404806133d884c
diff --git a/integration/consul_catalog_test.go b/integration/consul_catalog_test.go index <HASH>..<HASH> 100644 --- a/integration/consul_catalog_test.go +++ b/integration/consul_catalog_test.go @@ -175,6 +175,37 @@ func (s *ConsulCatalogSuite) TestSimpleConfiguration(c *check.C) { c.Assert(err, checker.IsNil) } +func (s *ConsulCatalogSuite) TestRegisterServiceWithoutIP(c *check.C) { + tempObjects := struct { + ConsulAddress string + DefaultRule string + }{ + ConsulAddress: s.consulAddress, + DefaultRule: "Host(`{{ normalize .Name }}.consul.localhost`)", + } + + file := s.adaptFile(c, "fixtures/consul_catalog/simple.toml", tempObjects) + defer os.Remove(file) + + err := s.registerService("whoami1", "whoami", "", "80", []string{"traefik.enable=true"}) + c.Assert(err, checker.IsNil) + + cmd, display := s.traefikCmd(withConfigFile(file)) + defer display(c) + err = cmd.Start() + c.Assert(err, checker.IsNil) + defer cmd.Process.Kill() + + req, err := http.NewRequest(http.MethodGet, "http://127.0.0.1:8080/api/http/services", nil) + c.Assert(err, checker.IsNil) + + err = try.Request(req, 2*time.Second, try.StatusCodeIs(200), try.BodyContainsOr("whoami@consulcatalog", "\"http://127.0.0.1:80\": \"UP\"")) + c.Assert(err, checker.IsNil) + + err = s.deregisterService("whoami1") + c.Assert(err, checker.IsNil) +} + func (s *ConsulCatalogSuite) TestDefaultConsulService(c *check.C) { tempObjects := struct { ConsulAddress string diff --git a/pkg/provider/consulcatalog/config.go b/pkg/provider/consulcatalog/config.go index <HASH>..<HASH> 100644 --- a/pkg/provider/consulcatalog/config.go +++ b/pkg/provider/consulcatalog/config.go @@ -163,6 +163,10 @@ func (p *Provider) addServerTCP(ctx context.Context, item itemData, loadBalancer return errors.New("port is missing") } + if item.Address == "" { + return errors.New("address is missing") + } + loadBalancer.Servers[0].Address = net.JoinHostPort(item.Address, port) return nil } @@ -193,6 +197,10 @@ func (p *Provider) addServer(ctx context.Context, item itemData, loadBalancer *d return errors.New("port is missing") } + if item.Address == "" { + return errors.New("address is missing") + } + loadBalancer.Servers[0].URL = fmt.Sprintf("%s://%s", loadBalancer.Servers[0].Scheme, net.JoinHostPort(item.Address, port)) loadBalancer.Servers[0].Scheme = "" diff --git a/pkg/provider/consulcatalog/consul_catalog.go b/pkg/provider/consulcatalog/consul_catalog.go index <HASH>..<HASH> 100644 --- a/pkg/provider/consulcatalog/consul_catalog.go +++ b/pkg/provider/consulcatalog/consul_catalog.go @@ -157,10 +157,15 @@ func (p *Provider) getConsulServicesData(ctx context.Context) ([]itemData, error for _, consulService := range consulServices { labels := tagsToNeutralLabels(consulService.ServiceTags, p.Prefix) + address := consulService.ServiceAddress + if address == "" { + address = consulService.Address + } + item := itemData{ ID: consulService.ServiceID, Name: consulService.ServiceName, - Address: consulService.ServiceAddress, + Address: address, Port: strconv.Itoa(consulService.ServicePort), Labels: labels, Status: consulService.Checks.AggregatedStatus(),
Fix empty address for registering service without IP
containous_traefik
train
62182313e7faf178f43030872b52e49250b46e75
diff --git a/liquibase-core/src/main/java/liquibase/change/core/AddColumnChange.java b/liquibase-core/src/main/java/liquibase/change/core/AddColumnChange.java index <HASH>..<HASH> 100644 --- a/liquibase-core/src/main/java/liquibase/change/core/AddColumnChange.java +++ b/liquibase-core/src/main/java/liquibase/change/core/AddColumnChange.java @@ -87,6 +87,7 @@ public class AddColumnChange extends AbstractChange implements ChangeWithColumns List<SqlStatement> sql = new ArrayList<SqlStatement>(); List<AddColumnStatement> addColumnStatements = new ArrayList<AddColumnStatement>(); + List<UpdateStatement> addColumnUpdateStatements = new ArrayList<UpdateStatement>(); if (getColumns().size() == 0) { return new SqlStatement[] { @@ -141,15 +142,21 @@ public class AddColumnChange extends AbstractChange implements ChangeWithColumns if (column.getValueObject() != null) { UpdateStatement updateStatement = new UpdateStatement(getCatalogName(), getSchemaName(), getTableName()); updateStatement.addNewColumnValue(column.getName(), column.getValueObject()); - sql.add(updateStatement); + if(database instanceof DB2Database) { + // Cannot update until table is reorganized in DB2 + addColumnUpdateStatements.add(updateStatement); + } else { + sql.add(updateStatement); + } } } if (database instanceof DB2Database) { sql.add(new ReorganizeTableStatement(getCatalogName(), getSchemaName(), getTableName())); + // Add all the update statements after the reorg table in DB2 + sql.addAll(addColumnUpdateStatements); } - if (addColumnStatements.size() == 1) { sql.add(0, addColumnStatements.get(0)); } else {
CORE-<I> Multiple Add Columns should not result in multiple table reorgs in DB2
liquibase_liquibase
train
2f5425303f56991db633d878355ecbfa1589f467
diff --git a/packages/plugins-indentable-list/src/onKeyDown/index.js b/packages/plugins-indentable-list/src/onKeyDown/index.js index <HASH>..<HASH> 100644 --- a/packages/plugins-indentable-list/src/onKeyDown/index.js +++ b/packages/plugins-indentable-list/src/onKeyDown/index.js @@ -60,14 +60,20 @@ export default function createOnKeyDown( }); return true; } else if (startBlock === endBlock) { - change - .setNodeByKey(key, { + change.setNodeByKey(key, { + data: data.delete(startAtField).delete(checkField) + }); + if (startOffset === 0) { + change.splitBlock(1); + } else { + change.insertBlock({ + type: startBlock.type, data: data.delete(startAtField).delete(checkField) - }) - .splitBlock(1) - .setNodeByKey(key, { - data }); + } + change.setNodeByKey(key, { + data + }); return true; } return undefined;
another attempt to fix data on list split
Vericus_slate-kit
train
fb32d3bb8c9a2cc1baf5bf25aa5c94726b89c2ac
diff --git a/src/Application.php b/src/Application.php index <HASH>..<HASH> 100644 --- a/src/Application.php +++ b/src/Application.php @@ -2,6 +2,10 @@ namespace TylerSommer\Nice; +use Symfony\Component\DependencyInjection\ContainerBuilder; +use Symfony\Component\DependencyInjection\ContainerInterface; +use Symfony\Component\DependencyInjection\Reference; +use Symfony\Component\EventDispatcher\ContainerAwareEventDispatcher; use Symfony\Component\EventDispatcher\EventDispatcher; use Symfony\Component\EventDispatcher\EventDispatcherInterface; use Symfony\Component\HttpFoundation\Request; @@ -14,33 +18,59 @@ use TylerSommer\Nice\Router\RouterSubscriber; class Application extends HttpKernel { /** + * @var ContainerInterface + */ + protected $container; + + /** * Constructor - * - * @param callable $routeFactory + * + * @param ContainerInterface $container * @param EventDispatcherInterface $dispatcher * @param ControllerResolverInterface $resolver * @param RequestStack $requestStack + * + * @internal param callable $routeFactory */ public function __construct( - callable $routeFactory, + ContainerInterface $container = null, EventDispatcherInterface $dispatcher = null, ControllerResolverInterface $resolver = null, RequestStack $requestStack = null ) { - $dispatcher = $dispatcher ?: new EventDispatcher(); + $this->container = $container = $container ?: new ContainerBuilder(); + + $dispatcher = $dispatcher ?: new ContainerAwareEventDispatcher($container); $resolver = $resolver ?: new ControllerResolver(); parent::__construct($dispatcher, $resolver, $requestStack); - $routeDispatcher = \FastRoute\simpleDispatcher($routeFactory); - $subscriber = new RouterSubscriber($routeDispatcher); + $container->register('router.parser', 'FastRoute\RouteParser\Std'); + $container->register('router.data_generator', 'FastRoute\DataGenerator\GroupCountBased'); + $container->register('router.collector', 'FastRoute\RouteCollector') + ->addArgument(new Reference('router.parser')) + ->addArgument(new Reference('router.data_generator')); + + $container->register('routes', 'Closure') + ->setSynthetic(true); + + $container->register('router.dispatcher_factory', 'TylerSommer\Nice\Router\DispatcherFactory\GroupCountBasedFactory') + ->addArgument(new Reference('router.collector')) + ->addArgument(new Reference('routes')); + + $container->register('router.dispatcher', 'FastRoute\Dispatcher') + ->setFactoryService('router.dispatcher_factory') + ->setFactoryMethod('create'); - $dispatcher->addSubscriber($subscriber); + $container->register('router.dispatcher_subscriber', 'TylerSommer\Nice\Router\RouterSubscriber') + ->addArgument(new Reference('router.dispatcher')); + + $dispatcher->addSubscriberService('router.dispatcher_subscriber', 'TylerSommer\Nice\Router\RouterSubscriber'); } /** * Helper method to get things going. - * + * * Inspired by Silex */ public function run() @@ -50,4 +80,12 @@ class Application extends HttpKernel $response->send(); $this->terminate($request, $response); } + + /** + * @return ContainerInterface + */ + public function getContainer() + { + return $this->container; + } }
Initial integration with symfony dic
nice-php_framework
train
4e176774ae5e2906c6d432e7aa1451175d9f5c18
diff --git a/mordred/task_enrich.py b/mordred/task_enrich.py index <HASH>..<HASH> 100644 --- a/mordred/task_enrich.py +++ b/mordred/task_enrich.py @@ -27,8 +27,10 @@ import time from datetime import datetime -from grimoire_elk.feeder import (do_studies, enrich_backend, refresh_projects, - refresh_identities) +from grimoire_elk.elk import (do_studies, + enrich_backend, + refresh_projects, + refresh_identities) from grimoire_elk.elastic_items import ElasticItems from grimoire_elk.elastic import ElasticSearch
[task_enrich] Update import section This code updates the import section to reflect the changes made on GElk.
chaoss_grimoirelab-sirmordred
train
e067806017d4fdea4cd05c4f83230b756a0e91a2
diff --git a/satpy/readers/fci_l1c_fdhsi.py b/satpy/readers/fci_l1c_fdhsi.py index <HASH>..<HASH> 100644 --- a/satpy/readers/fci_l1c_fdhsi.py +++ b/satpy/readers/fci_l1c_fdhsi.py @@ -34,6 +34,9 @@ in 2021 by the earliest. For more information about FCI, see `EUMETSAT`_. .. _EUMETSAT: https://www.eumetsat.int/website/home/Satellites/FutureSatellites/MeteosatThirdGeneration/MTGDesign/index.html#fci # noqa: E501 """ +from __future__ import (division, absolute_import, print_function, + unicode_literals) + import logging import numpy as np import dask.array as da @@ -119,10 +122,9 @@ class FCIFDHSIFileHandler(NetCDF4FileHandler): attrs.pop("units") self.nlines, self.ncols = res.shape - res.attrs.update({ - **key.to_dict(), - **info, - **attrs}) + res.attrs.update(key.to_dict()) + res.attrs.update(info) + res.attrs.update(attrs) return res def get_channel_dataset(self, channel): diff --git a/satpy/tests/reader_tests/test_fci_l1c_fdhsi.py b/satpy/tests/reader_tests/test_fci_l1c_fdhsi.py index <HASH>..<HASH> 100644 --- a/satpy/tests/reader_tests/test_fci_l1c_fdhsi.py +++ b/satpy/tests/reader_tests/test_fci_l1c_fdhsi.py @@ -19,6 +19,10 @@ """Tests for the 'fci_l1c_fdhsi' reader.""" +from __future__ import (division, absolute_import, print_function, + unicode_literals) + +import sys import os import numpy as np @@ -126,11 +130,10 @@ class FakeNetCDF4FileHandler2(FakeNetCDF4FileHandler): # # ... but only what satpy is using ... - return { - **self._get_test_content_all_channels(), - **self._get_test_content_areadef(), - } - + D = {} + D.update(self._get_test_content_all_channels()) + D.update(self._get_test_content_areadef()) + return D class FakeNetCDF4FileHandler3(FakeNetCDF4FileHandler2): """Mock bad data @@ -338,6 +341,10 @@ class TestFCIL1CFDHSIReaderGoodData(TestFCIL1CFDHSIReader): class TestFCIL1CFDHSIReaderBadData(TestFCIL1CFDHSIReader): _alt_handler = FakeNetCDF4FileHandler3 + @unittest.skipIf( + sys.version < (3, 4), + "skipping log message testing on old Python version " + "that doesn't have TestCase.assertLogs") def test_handling_bad_data_ir(self): """Test handling of bad data """
Make MTG FCI tests run on Python 2 Downgrade syntax and skip one test to make FCI reader tests succeed on Python 2
pytroll_satpy
train
d9c597cf9f6c7eb1ab85f309dbdd26d449ee2023
diff --git a/stacker_blueprints/empire/daemon.py b/stacker_blueprints/empire/daemon.py index <HASH>..<HASH> 100644 --- a/stacker_blueprints/empire/daemon.py +++ b/stacker_blueprints/empire/daemon.py @@ -69,6 +69,10 @@ class EmpireDaemon(Blueprint): " either acm or iam." ), "default": ""}, + "DesiredCount": { + "type": "Number", + "description": "The number of controller tasks to run.", + "default": "2"}, "InstanceSecurityGroup": { "type": "String", "description": "Security group of the controller instances."}, @@ -457,7 +461,7 @@ class EmpireDaemon(Blueprint): ecs.Service( "Service", Cluster=Ref("ControllerCluster"), - DesiredCount=2, + DesiredCount=Ref("DesiredCount"), LoadBalancers=[ ecs.LoadBalancer( ContainerName="empire",
Make the desired number of tasks configurable
remind101_stacker_blueprints
train
aa9c733b13a3639486dcd0dc5a5d3fd2e6e27a32
diff --git a/lib/pair_see/too_much_stuff.rb b/lib/pair_see/too_much_stuff.rb index <HASH>..<HASH> 100644 --- a/lib/pair_see/too_much_stuff.rb +++ b/lib/pair_see/too_much_stuff.rb @@ -1,3 +1,4 @@ +require 'pry' module PairSee class TooMuchStuff require 'yamler' @@ -65,31 +66,43 @@ module PairSee end def all_commits + pairs_result = Hash[@dev_pairs.map {|k, v| [names_key(k, v), 0]}] + solos_result = Hash[@devs.map {|k| [k.display_name, 0]}] + result = pairs_result.merge solos_result - @dev_pairs.map {|person1, person2| - foo = @log_lines.map {|log_line| - aa = log_line.authored_by?(person1, person2) - bb = log_line.authored_by?(person1) && (@devs - [person1]).none? { |single_person| log_line.authored_by?(single_person) } - (aa ? ["pair", log_line, [person1, person2]] : nil) || - (bb ? ["solo", log_line, [person1]]) - } - .compact - .map {|type, log_line, devs| - PairCommitCount.new() - } - .sort_by {|type, log_line, devs| pcc.count}.map {|type, pcc| pcc.to_s} + @log_lines.each {|ll| + result = method_name(ll, result) } - - a = @dev_pairs.map do |person1, person2| - PairCommitCount.new(@log_lines.commits_for_pair(person1, person2).count, person1, person2) - end - - b = @devs.map {|person| - PairCommitCount.new(@log_lines.solo_commits(@devs, person).count, person) + result + .sort_by {|_, count| count} + .reject {|_, count| count == 0} + .map {|names, count| "#{names}: #{count}"} + + end + + def method_name(ll, result) + @dev_pairs.each {|d1, d2| + if ll.authored_by?(d1, d2) then + result[names_key(d1, d2)] += 1 + return result + elsif is_solo_by?(@devs, d1, ll) + result[d1.display_name] += 1 + return result + elsif is_solo_by?(@devs, d2, ll) + result[d2.display_name] += 1 + return result + end } + return result + end - (a + b).sort_by(&:count).reject(&:empty?).map(&:to_s) + def is_solo_by?(devs, person, log_line) + no_other_devs_in_commit = (devs - [person]).none? {|dx| log_line.authored_by?(dx)} + log_line.authored_by?(person) && no_other_devs_in_commit + end + def names_key(k, v) + [k, v].sort_by {|a| a.display_name}.map(&:to_s).join(", ") end def b(log_line, person1)
possibly making things worse by refactoring
compwron_pairSee
train
81107a8a4eb126c05baf3219d9120d76b23fc174
diff --git a/src/com/opera/core/systems/UmsEventHandler.java b/src/com/opera/core/systems/UmsEventHandler.java index <HASH>..<HASH> 100644 --- a/src/com/opera/core/systems/UmsEventHandler.java +++ b/src/com/opera/core/systems/UmsEventHandler.java @@ -19,18 +19,20 @@ public class UmsEventHandler extends EventHandler { @Override public void onRuntimeStarted(RuntimeInfo info) { + /* if(info.getHtmlFramePath().equals("_top") && info.getWindowID() == services.getWindowManager().getActiveWindowId()) { //check if we already have such a runtime and clean them up if needed services.getDebugger().cleanUpRuntimes(); services.getDebugger().setRuntime(info); } + */ services.getDebugger().addRuntime(info); } @Override public void onUpdatedWindow(WindowInfo info) { //logger.log(Level.INFO, window.toString()); - if(info.getOpenerID() == 0) + //if(info.getOpenerID() == 0) services.getWindowManager().addWindow(info); }
Disable tracking of active window, require explicit switch
operasoftware_operaprestodriver
train
5df23f34f01f6195bc16b6ea7e67622317507659
diff --git a/core.go b/core.go index <HASH>..<HASH> 100644 --- a/core.go +++ b/core.go @@ -328,8 +328,6 @@ func (sock *socket) SendAnyPipe(msg *Message) (PipeKey, error) { default: } } - // we should never get here - panic("fell off end of loop") } // SendToPipe implements the ProtocolHandle SendToPipe method.
So, it turns out that git vet complains about unreachable code. We don't need anything here anyway, because the compiler will complain about a missing return statement.
nanomsg_mangos-v1
train
adffbe1de8ff7ca8ee2b4ed6623192969765f686
diff --git a/raven/transport/udp.py b/raven/transport/udp.py index <HASH>..<HASH> 100644 --- a/raven/transport/udp.py +++ b/raven/transport/udp.py @@ -31,9 +31,9 @@ class BaseUDPTransport(Transport): a v6 address if it's the only option. """ addresses = getaddrinfo(host, port) + v4_addresses = [info for info in addresses if info[0] == AF_INET] if has_ipv6: v6_addresses = [info for info in addresses if info[0] == AF_INET6] - v4_addresses = [info for info in addresses if info[0] == AF_INET] if v6_addresses and not v4_addresses: # The only time we return a v6 address is if it's the only option return v6_addresses[0]
init v4_address earlier
getsentry_raven-python
train
c7ef75b8fb275d325e5f19e040e31f34c344ff06
diff --git a/closure/goog/net/xhrio.js b/closure/goog/net/xhrio.js index <HASH>..<HASH> 100644 --- a/closure/goog/net/xhrio.js +++ b/closure/goog/net/xhrio.js @@ -300,6 +300,7 @@ goog.net.XhrIo.sendInstances_ = []; * incomplete request will be aborted; 0 means no timeout is set. * @param {boolean=} opt_withCredentials Whether to send credentials with the * request. Default to false. See {@link goog.net.XhrIo#setWithCredentials}. + * @return {!goog.net.XhrIo} The sent XhrIo. */ goog.net.XhrIo.send = function(url, opt_callback, opt_method, opt_content, opt_headers, opt_timeoutInterval, @@ -317,6 +318,7 @@ goog.net.XhrIo.send = function(url, opt_callback, opt_method, opt_content, x.setWithCredentials(opt_withCredentials); } x.send(url, opt_method, opt_content, opt_headers); + return x; };
Add a return to static send method to get the sent XhrIo instance. ------------- Created by MOE: <URL>
google_closure-library
train
b969599daf4fd3d14a8382fde79536e213b975ff
diff --git a/pkg/kubelet/dockertools/convert.go b/pkg/kubelet/dockertools/convert.go index <HASH>..<HASH> 100644 --- a/pkg/kubelet/dockertools/convert.go +++ b/pkg/kubelet/dockertools/convert.go @@ -28,14 +28,18 @@ import ( // This file contains helper functions to convert docker API types to runtime // (kubecontainer) types. +const ( + statusRunningPrefix = "Up" + statusExitedPrefix = "Exited" +) func mapState(state string) kubecontainer.ContainerState { // Parse the state string in docker.APIContainers. This could break when // we upgrade docker. switch { - case strings.HasPrefix(state, "Up"): + case strings.HasPrefix(state, statusRunningPrefix): return kubecontainer.ContainerStateRunning - case strings.HasPrefix(state, "Exited"): + case strings.HasPrefix(state, statusExitedPrefix): return kubecontainer.ContainerStateExited default: return kubecontainer.ContainerStateUnknown diff --git a/pkg/kubelet/dockertools/fake_docker_client.go b/pkg/kubelet/dockertools/fake_docker_client.go index <HASH>..<HASH> 100644 --- a/pkg/kubelet/dockertools/fake_docker_client.go +++ b/pkg/kubelet/dockertools/fake_docker_client.go @@ -282,6 +282,7 @@ func (f *FakeDockerClient) StartContainer(id string, hostConfig *docker.HostConf } container.NetworkSettings = &docker.NetworkSettings{IPAddress: "2.3.4.5"} f.ContainerMap[id] = container + f.updateContainerStatus(id, statusRunningPrefix) f.normalSleep(200, 50, 50) return nil } @@ -322,6 +323,7 @@ func (f *FakeDockerClient) StopContainer(id string, timeout uint) error { container.State.Running = false } f.ContainerMap[id] = container + f.updateContainerStatus(id, statusExitedPrefix) f.normalSleep(200, 50, 50) return nil } @@ -412,6 +414,14 @@ func (f *FakeDockerClient) RemoveImage(image string) error { return err } +func (f *FakeDockerClient) updateContainerStatus(id, status string) { + for i := range f.ContainerList { + if f.ContainerList[i].ID == id { + f.ContainerList[i].Status = status + } + } +} + // FakeDockerPuller is a stub implementation of DockerPuller. type FakeDockerPuller struct { sync.Mutex
Fix fake docker client to corretly report status of containers
kubernetes_kubernetes
train
6dc168b1e93d5333731e50a56e20d9937943b36a
diff --git a/spec/tree/values/nodes/StructuredIrrelevantSpec.js b/spec/tree/values/nodes/StructuredIrrelevantSpec.js index <HASH>..<HASH> 100644 --- a/spec/tree/values/nodes/StructuredIrrelevantSpec.js +++ b/spec/tree/values/nodes/StructuredIrrelevantSpec.js @@ -1,7 +1,7 @@ import StructuredIrrelevant from "../../../../src/tree/values/nodes/StructuredIrrelevant"; describe( "StructuredIrrelevant", () => { - it( "can make an StructuredIrrelevant node", () => { + it( "can make a StructuredIrrelevant node", () => { const nodeContents = "<script> console.log('hey!'); </script>"; const structuredIrrelevantNode = new StructuredIrrelevant( nodeContents ); expect( structuredIrrelevantNode.content ).toEqual( nodeContents );
Update StructuredIrrelevantSpec.js
Yoast_YoastSEO.js
train
f285ff965d12e40e9f7fac37cc83938bfcbafeee
diff --git a/lib/serverspec/setup.rb b/lib/serverspec/setup.rb index <HASH>..<HASH> 100644 --- a/lib/serverspec/setup.rb +++ b/lib/serverspec/setup.rb @@ -21,38 +21,22 @@ EOF @vagrant = gets.chomp if @vagrant =~ (/(true|t|yes|y|1)$/i) @vagrant = true - else - @vagrant = false - end - print "Auto-configure Vagrant from Vagrantfile? y/n: " - auto_config = gets.chomp - if auto_config =~ (/(true|t|yes|y|1)$/i) - if File.exists?("Vagrantfile") - vagrant_list = `vagrant status` - if vagrant_list != '' - vagrant_list.each_line do |line| - if match = /([a-z]+[\s]+)(created|not created|poweroff|running)[\s](\(virtualbox\)|\(vmware\))/.match(line) - puts match[1] - end - end - else - $stderr.puts "Vagrant status error - Check your Vagrantfile" - exit 1 - end + print "Auto-configure Vagrant from Vagrantfile? y/n: " + auto_config = gets.chomp + if auto_config =~ (/(true|t|yes|y|1)$/i) + auto_vagrant_configuration else - $stderr.puts "Vagrantfile not found in directory!" - exit 1 + print("Input vagrant instance name: ") + @hostname = gets.chomp end else - print("Input vagrant instance name: ") - @hostname = gets.chomp + @vagrant = false end - print("Input target host name: ") - @hostname = gets.chomp - else - @hostname = 'localhost' - end - + print("Input target host name: ") + @hostname = gets.chomp + else + @hostname = 'localhost' + end [ 'spec', "spec/#{@hostname}" ].each { |dir| safe_mkdir(dir) } safe_create_spec safe_create_spec_helper @@ -213,7 +197,24 @@ EOF end end - + def self.auto_vagrant_configuration + if File.exists?("Vagrantfile") + vagrant_list = `vagrant status` + if vagrant_list != '' + vagrant_list.each_line do |line| + if match = /([a-z]+[\s]+)(created|not created|poweroff|running)[\s](\(virtualbox\)|\(vmware\))/.match(line) + puts match[1] + end + end + else + $stderr.puts "Vagrant status error - Check your Vagrantfile or .vagrant" + exit 1 + end + else + $stderr.puts "Vagrantfile not found in directory!" + exit 1 + end + end end end
Refactored Vagrant configuration… into separate method. Got too confusing with all the if's...
mizzy_serverspec
train
d9a9567e900658e0b52a6e7f6a2afb60fb2eb62f
diff --git a/environs/interface.go b/environs/interface.go index <HASH>..<HASH> 100644 --- a/environs/interface.go +++ b/environs/interface.go @@ -116,7 +116,7 @@ type Environ interface { // Name returns the Environ's name. Name() string - // Bootstrap initializes the state for the ehttp://e.linkedin.com/pub/cc?_ri_=X0Gzc2X%3DWQpglLjHJlYQGnWM9Wmzczb5jcumzdzbUza0krpJ1IHy1zbKM6oudBVXtpKX%3DSACTCD&_ei_=ElhY7pRVQKMkByKfU5j5nyTdqpv_9wz7Jge06DvYsd6c0nIJozNk4cNMOPC1Urjg7VaJ00kOxaaDHWP4Pi6FQTEX7HtnX6dCCY5_xSJOUbu4ajHGueKYqV91dfEPm_weAS30DdZlQpvjwJZconUle6z6-oOidmOLrLjX70.nvironment, possibly + // Bootstrap initializes the state for the environment, possibly // starting one or more instances. If the configuration's // AdminSecret is non-empty, the adminstrator password on the // newly bootstrapped state will be set to a hash of it (see
Removed rogue paste, thanks fwereade...
juju_juju
train
74686dcec6f2d6cf0a270249d186b0c7e1fca175
diff --git a/src/main/java/nl/hsac/fitnesse/fixture/slim/SlimFixture.java b/src/main/java/nl/hsac/fitnesse/fixture/slim/SlimFixture.java index <HASH>..<HASH> 100644 --- a/src/main/java/nl/hsac/fitnesse/fixture/slim/SlimFixture.java +++ b/src/main/java/nl/hsac/fitnesse/fixture/slim/SlimFixture.java @@ -97,22 +97,26 @@ public class SlimFixture implements InteractionAwareFixture { * @return rawValue if it was just text, cleaned version if it was not. */ protected String cleanupValue(String rawValue) { - String result; - Matcher matcher = PATTERN.matcher(rawValue); - if (matcher.matches()) { - result = matcher.group(2) + matcher.group(3); - } else { - result = cleanupPreFormatted(rawValue); + String result = null; + if (rawValue != null) { + Matcher matcher = PATTERN.matcher(rawValue); + if (matcher.matches()) { + result = matcher.group(2) + matcher.group(3); + } else { + result = cleanupPreFormatted(rawValue); + } } return result; } protected String cleanupPreFormatted(String rawValue) { String result = rawValue; - Matcher matcher = PRE_FORMATTED_PATTERN.matcher(rawValue); - if (matcher.matches()) { - String escapedBody = matcher.group(1); - result = StringEscapeUtils.unescapeHtml4(escapedBody); + if (rawValue != null) { + Matcher matcher = PRE_FORMATTED_PATTERN.matcher(rawValue); + if (matcher.matches()) { + String escapedBody = matcher.group(1); + result = StringEscapeUtils.unescapeHtml4(escapedBody); + } } return result; }
Ensure we don't throw exceptions when values are null
fhoeben_hsac-fitnesse-fixtures
train
5137d31aeae26fc577b2d184a7770aba7329d484
diff --git a/lib/itbit/market.rb b/lib/itbit/market.rb index <HASH>..<HASH> 100644 --- a/lib/itbit/market.rb +++ b/lib/itbit/market.rb @@ -7,7 +7,9 @@ module Itbit # The symbol ticker conveniently formatted as a ruby Hash with # symbolized keys. def self.ticker - raw_ticker = JSON.parse(RestClient.get("#{Api.api_url}/markets/#{symbol.upcase}/ticker")) + url = "#{Api.api_url}/markets/#{symbol.upcase}/ticker" + rest_cl = RestClient::Request.execute :method => :get, :url => url, :ssl_version => 'SSLv23' + raw_ticker = JSON.parse(rest_cl) raw_ticker.reduce({}) do |ticker, pair| key = pair.first.underscore.to_sym value = case key @@ -40,10 +42,11 @@ module Itbit end # @visibility private - def self.old_request(path, options = { }) + def self.old_request(path, options = { }) url = "https://www.itbit.com/api/v2#{path}" url << "?#{options.to_query}" if options.any? - JSON.parse(RestClient.get(url)) + rest_cl = RestClient::Request.execute :method => :get, :url => url, :ssl_version => 'SSLv23' + JSON.parse(rest_cl) end end
Updated RestClient Corrects SSLv3 compatibility
bitex-la_itbit
train
292cc006403130b2859b941d98669466e511013e
diff --git a/xclim/testing/tests/test_indices.py b/xclim/testing/tests/test_indices.py index <HASH>..<HASH> 100644 --- a/xclim/testing/tests/test_indices.py +++ b/xclim/testing/tests/test_indices.py @@ -1045,6 +1045,41 @@ class TestTxDays: np.testing.assert_array_equal(out[1:], [0]) +class TestJetStreamIndices: + # data needs to consist of at least 61 days for Lanczos filter (here: 66 days) + time_coords = pd.date_range("2000-01-01", "2000-03-06", freq="D") + # make random ua data array of shape (66 days, 3 plevs, 5 lons, 5 lats) + np.random.seed(42) + da_ua = xr.DataArray( + np.random.rand(66, 3, 5, 5), + coords={ + "time": time_coords, + "plev": [75000, 85000, 100000], + "lon": [-60, -59, -58, -57, -56], + "lat": [15, 16, 17, 18, 19], + }, + dims=["time", "plev", "lon", "lat"], + attrs={ + "standard_name": "eastward_wind", + "units": "m s-1", + }, + ) + da_ua.plev.attrs["units"] = "Pa" + + def test_jetstream_metric_woolings(self): + da_ua = self.da_ua + out = xci.jetstream_metric_woolings(da_ua) + np.testing.assert_equal(len(out), 2) + jetlat, jetstr = out + # should be 6 values that are not NaN because of 61 day moving window and 66 chosen + np.testing.assert_equal(np.sum(~np.isnan(jetlat).data), 6) + np.testing.assert_equal(np.sum(~np.isnan(jetstr).data), 6) + np.testing.assert_equal(jetlat.max().data, 19.0) + np.testing.assert_equal(jetstr.max().data, 0.5620588628647811) + assert jetlat.units == "deg" + assert jetstr.units == "m s-1" + + class TestLiquidPrecipitationRatio: def test_simple(self, pr_series, tas_series): pr = np.zeros(100)
add jetstream indicies test and test for woolings metric
Ouranosinc_xclim
train
168506183f426400c61547f238be8e217b70a8c3
diff --git a/repository/repository.go b/repository/repository.go index <HASH>..<HASH> 100644 --- a/repository/repository.go +++ b/repository/repository.go @@ -32,9 +32,12 @@ type Unit interface { // tsuru server. func clone(u Unit) ([]byte, error) { var buf bytes.Buffer - p, _ := GetPath() + p, err := GetPath() + if err != nil { + return nil, fmt.Errorf("Tsuru is misconfigured: %s", err) + } cmd := fmt.Sprintf("git clone %s %s --depth 1", GetReadOnlyUrl(u.GetName()), p) - err := u.Command(&buf, &buf, cmd) + err = u.Command(&buf, &buf, cmd) b := buf.Bytes() log.Printf(`"git clone" output: %s`, b) return b, err @@ -45,9 +48,12 @@ func clone(u Unit) ([]byte, error) { // It works like Clone, pulling from the app bare repository. func pull(u Unit) ([]byte, error) { var buf bytes.Buffer - p, _ := GetPath() + p, err := GetPath() + if err != nil { + return nil, fmt.Errorf("Tsuru is misconfigured: %s", err) + } cmd := fmt.Sprintf("cd %s && git pull origin master", p) - err := u.Command(&buf, &buf, cmd) + err = u.Command(&buf, &buf, cmd) b := buf.Bytes() log.Printf(`"git pull" output: %s`, b) return b, err diff --git a/repository/repository_test.go b/repository/repository_test.go index <HASH>..<HASH> 100644 --- a/repository/repository_test.go +++ b/repository/repository_test.go @@ -56,6 +56,16 @@ func (s *S) TestCloneRepository(c *gocheck.C) { c.Assert(u.RanCommand(expectedCommand), gocheck.Equals, true) } +func (s *S) TestCloneRepositoryUndefinedPath(c *gocheck.C) { + old, _ := config.Get("git:unit-repo") + config.Unset("git:unit-repo") + defer config.Set("git:unit-repo", old) + u := FakeUnit{name: "my-unit"} + _, err := clone(&u) + c.Assert(err, gocheck.NotNil) + c.Assert(err.Error(), gocheck.Equals, `Tsuru is misconfigured: key "git:unit-repo" not found`) +} + func (s *S) TestPullRepository(c *gocheck.C) { u := FakeUnit{name: "your-unit"} _, err := pull(&u) @@ -64,6 +74,16 @@ func (s *S) TestPullRepository(c *gocheck.C) { c.Assert(u.RanCommand(expectedCommand), gocheck.Equals, true) } +func (s *S) TestPullRepositoryUndefinedPath(c *gocheck.C) { + old, _ := config.Get("git:unit-repo") + config.Unset("git:unit-repo") + defer config.Set("git:unit-repo", old) + u := FakeUnit{name: "my-unit"} + _, err := pull(&u) + c.Assert(err, gocheck.NotNil) + c.Assert(err.Error(), gocheck.Equals, `Tsuru is misconfigured: key "git:unit-repo" not found`) +} + func (s *S) TestCloneOrPullRepositoryRunsClone(c *gocheck.C) { u := FakeUnit{name: "my-unit"} _, err := CloneOrPull(&u)
repository: added tests for missing git:unit-repo setting
tsuru_tsuru
train
5b6efb784f987b87680e665b27f2e11bc735add7
diff --git a/lib/namespace.js b/lib/namespace.js index <HASH>..<HASH> 100644 --- a/lib/namespace.js +++ b/lib/namespace.js @@ -126,20 +126,8 @@ SocketNamespace.prototype.packet = function (packet) { , exceptions = this.flags.exceptions , packet = parser.encodePacket(packet); - store.clients(this.flags.endpoint, function (clients) { - clients.forEach(function (id) { - if (~exceptions.indexOf(id)) { - log.debug('ignoring packet to ', id); - return; - } - - if (volatile) { - store.publish('volatile:' + id, packet); - } else { - store.client(id).publish(packet); - } - }); - }); + this.manager.onDispatch(this.flags.endpoint, packet, volatile, exceptions); + this.store.publish('dispatch', this.flags.endpoint, packet, volatile, exceptions); this.setFlags();
Simplified global message dispatching by leveraging subscriptions.
socketio_socket.io
train
1d997d9da52bdea858cf202cff00c42e1d69c9be
diff --git a/gns3server/web/route.py b/gns3server/web/route.py index <HASH>..<HASH> 100644 --- a/gns3server/web/route.py +++ b/gns3server/web/route.py @@ -40,6 +40,7 @@ def parse_request(request, input_schema): try: request.json = json.loads(body.decode('utf-8')) except ValueError as e: + request.json = {"malformed_json": body.decode('utf-8')} raise aiohttp.web.HTTPBadRequest(text="Invalid JSON {}".format(e)) else: request.json = {} @@ -137,6 +138,10 @@ class Route(object): log.warn("Could not write to the record file {}: {}".format(record_file, e)) response = Response(route=route, output_schema=output_schema) yield from func(request, response) + except aiohttp.web.HTTPBadRequest as e: + response = Response(route=route) + response.set_status(e.status) + response.json({"message": e.text, "status": e.status, "path": route, "request": request.json}) except aiohttp.web.HTTPException as e: response = Response(route=route) response.set_status(e.status)
Return more informations about bad requests for crash reports
GNS3_gns3-server
train