hash
stringlengths 40
40
| diff
stringlengths 131
114k
| message
stringlengths 7
980
| project
stringlengths 5
67
| split
stringclasses 1
value |
|---|---|---|---|---|
33042cf104f05a5f4205f15930b308070604952c
|
diff --git a/test/testSerialRequestResponseD0-20.js b/test/testSerialRequestResponseD0-20.js
index <HASH>..<HASH> 100644
--- a/test/testSerialRequestResponseD0-20.js
+++ b/test/testSerialRequestResponseD0-20.js
@@ -57,10 +57,6 @@ describe('test SerialRequestResponseTransport with D0Protocol x20', function() {
else {
expect(counter).to.be.within(1, 19);
expect(JSON.stringify(lastObisResult)).to.be.equal(JSON.stringify(obisResult));
- if (counter === 19) {
- var realDuration = Date.now() - startTime;
- console.log('Real Duration 20: ' + realDuration + ' vs. ' + duration);
- }
}
console.log('Received data ' + counter + ': ' + Object.keys(obisResult));
@@ -89,7 +85,7 @@ describe('test SerialRequestResponseTransport with D0Protocol x20', function() {
var testData = Buffer.from('\u00026.8(0029.055*MWh)6.26(01589.28*m3)9.21(00010213)6.26*01(01563.92*m3)6.8*01(0028.086*MWh)F(0)9.20(64030874)6.35(60*m)6.6(0017.2*kW)6.6*01(0017.2*kW)6.33(001.476*m3ph)9.4(088*C&082*C)6.31(0030710*h)6.32(0000194*h)9.22(R)9.6(000&00010213&0)9.7(20000)6.32*01(0000194*h)6.36(01-01)6.33*01(001.476*m3ph)6.8.1()6.8.2()6.8.3()6.8.4()6.8.5()6.8.1*01()6.8.2*01()6.8.3*01()\r\n6.8.4*01()6.8.5*01()9.4*01(088*C&082*C)6.36.1(2013-11-28)6.36.1*01(2013-11-28)6.36.2(2016-09-24)6.36.2*01(2016-09-24)6.36.3(2015-03-26)6.36.3*01(2015-03-26)6.36.4(2013-09-27)6.36.4*01(2013-09-27)6.36.5(2000-00-00)6.36*02(01)9.36(2017-01-18&01:36:47)9.24(0.6*m3ph)9.17(0)9.18()9.19()9.25()9.1(0&1&0&-&CV&3&2.14)9.2(&&)0.0(00010213)!\r\n\u0003X');
smTransport.serialComm.writeToComputer(testData);
- if (counter === 19) {
+ if (counter === 20) {
endTimer = setTimeout(function() {
expect(smTransport.stopRequests).to.be.false;
smTransport.stop(function() {
|
try fix tests (running "too fast" on GitHub Actions)
|
Apollon77_smartmeter-obis
|
train
|
c98c3e2e7145bf633465f1c7fcd8417f069062e7
|
diff --git a/certificate.js b/certificate.js
index <HASH>..<HASH> 100644
--- a/certificate.js
+++ b/certificate.js
@@ -22,7 +22,8 @@ var AttributeTypeValue = asn.define('AttributeTypeValue', function () {
var AlgorithmIdentifier = asn.define('AlgorithmIdentifier', function () {
this.seq().obj(
this.key('algorithm').objid(),
- this.key('parameters').optional()
+ this.key('parameters').optional(),
+ this.key('curve').objid().optional()
)
})
|
Add curve as parameter to certificate algorithm (#<I>)
This fixes crypto-browserify/browserify-sign#<I>
|
crypto-browserify_parse-asn1
|
train
|
a1dd8ef26c6e05343b88c316071daaee6a2ff7d4
|
diff --git a/ghost/admin/views/editor.js b/ghost/admin/views/editor.js
index <HASH>..<HASH> 100644
--- a/ghost/admin/views/editor.js
+++ b/ghost/admin/views/editor.js
@@ -87,9 +87,11 @@
},
toggleStatus: function () {
- var keys = Object.keys(this.statusMap),
+ var view = this,
+ keys = Object.keys(this.statusMap),
model = this.model,
- currentIndex = keys.indexOf(model.get('status')),
+ prevStatus = this.model.get('status'),
+ currentIndex = keys.indexOf(prevStatus),
newIndex;
@@ -107,18 +109,20 @@
message: 'Your post: ' + model.get('title') + ' has been ' + keys[newIndex],
status: 'passive'
});
- }, function () {
- Ghost.notifications.addItem({
- type: 'error',
- message: 'Your post: ' + model.get('title') + ' has not been ' + keys[newIndex],
- status: 'passive'
- });
+ }, function (response) {
+ var status = keys[newIndex];
+ // Show a notification about the error
+ view.reportSaveError(response, model, status);
+ // Set the button text back to previous
+ model.set({ status: prevStatus });
});
},
handleStatus: function (e) {
e.preventDefault();
- var status = $(e.currentTarget).attr('data-set-status'),
+ var view = this,
+ status = $(e.currentTarget).attr('data-set-status'),
+ prevStatus = this.model.get('status'),
model = this.model;
if (status === 'publish-on') {
@@ -144,12 +148,11 @@
message: 'Your post: ' + model.get('title') + ' has been ' + status,
status: 'passive'
});
- }, function () {
- Ghost.notifications.addItem({
- type: 'error',
- message: 'Your post: ' + model.get('title') + ' has not been ' + status,
- status: 'passive'
- });
+ }, function (response) {
+ // Show a notification about the error
+ view.reportSaveError(response, model, status);
+ // Set the button text back to previous
+ model.set({ status: prevStatus });
});
},
@@ -195,6 +198,25 @@
return $.Deferred().reject();
},
+ reportSaveError: function (response, model, status) {
+ var title = model.get('title') || '[Untitled]',
+ message = 'Your post: ' + title + ' has not been ' + status;
+
+ if (response) {
+ // Get message from response
+ message = this.getErrorMessageFromResponse(response);
+ } else if (model.validationError) {
+ // Grab a validation error
+ message += "; " + model.validationError;
+ }
+
+ Ghost.notifications.addItem({
+ type: 'error',
+ message: message,
+ status: 'passive'
+ });
+ },
+
render: function () {
this.$('.js-post-button').text(this.statusMap[this.model.get('status')]);
}
|
Show validation error when saving post
Show the model.validationError if one is present and also coalesce the
empty title for a more meaningful message. Also, reset the button text
after failure.
|
TryGhost_Ghost
|
train
|
239be41b2c5e8a310ba9f36162c4571ba810b649
|
diff --git a/mqlight/src/main/java/com/ibm/mqlight/api/impl/timer/TimerPromiseImpl.java b/mqlight/src/main/java/com/ibm/mqlight/api/impl/timer/TimerPromiseImpl.java
index <HASH>..<HASH> 100644
--- a/mqlight/src/main/java/com/ibm/mqlight/api/impl/timer/TimerPromiseImpl.java
+++ b/mqlight/src/main/java/com/ibm/mqlight/api/impl/timer/TimerPromiseImpl.java
@@ -28,18 +28,18 @@ import com.ibm.mqlight.api.logging.LoggerFactory;
public class TimerPromiseImpl implements Promise<Void> {
private static final Logger logger = LoggerFactory.getLogger(TimerPromiseImpl.class);
-
+
private final Component component;
private final Object context;
- private AtomicBoolean complete = new AtomicBoolean(false);
-
+ private final AtomicBoolean complete = new AtomicBoolean(false);
+
public TimerPromiseImpl(Component component, Object context) {
final String methodName = "<init>";
logger.entry(this, methodName, component, context);
-
+
this.component = component;
this.context = context;
-
+
logger.exit(this, methodName);
}
@@ -47,7 +47,7 @@ public class TimerPromiseImpl implements Promise<Void> {
public void setFailure(Exception exception) throws IllegalStateException {
final String methodName = "setFailure";
logger.entry(this, methodName, exception);
-
+
if (complete.getAndSet(true)) {
final IllegalStateException ex = new IllegalStateException("Promise already completed");
logger.throwing(this, methodName, ex);
@@ -55,7 +55,7 @@ public class TimerPromiseImpl implements Promise<Void> {
} else {
component.tell(new CancelResponse(this), component);
}
-
+
logger.exit(this, methodName);
}
@@ -63,7 +63,7 @@ public class TimerPromiseImpl implements Promise<Void> {
public void setSuccess(Void result) throws IllegalStateException {
final String methodName = "setSuccess";
logger.entry(this, methodName, result);
-
+
if (complete.getAndSet(true)) {
final IllegalStateException exception = new IllegalStateException("Promise already completed");
logger.throwing(this, methodName, exception);
@@ -71,7 +71,7 @@ public class TimerPromiseImpl implements Promise<Void> {
} else {
component.tell(new PopResponse(this), component);
}
-
+
logger.exit(this, methodName);
}
diff --git a/mqlight/src/main/java/com/ibm/mqlight/api/impl/timer/TimerServiceImpl.java b/mqlight/src/main/java/com/ibm/mqlight/api/impl/timer/TimerServiceImpl.java
index <HASH>..<HASH> 100644
--- a/mqlight/src/main/java/com/ibm/mqlight/api/impl/timer/TimerServiceImpl.java
+++ b/mqlight/src/main/java/com/ibm/mqlight/api/impl/timer/TimerServiceImpl.java
@@ -23,7 +23,6 @@ import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
-import com.ibm.mqlight.api.ClientException;
import com.ibm.mqlight.api.Promise;
import com.ibm.mqlight.api.logging.Logger;
import com.ibm.mqlight.api.logging.LoggerFactory;
@@ -32,9 +31,8 @@ import com.ibm.mqlight.api.timer.TimerService;
public class TimerServiceImpl implements TimerService {
private static final Logger logger = LoggerFactory.getLogger(TimerServiceImpl.class);
-
+
private static final ScheduledThreadPoolExecutor executor;
- private static final ClientException failureException = new ClientException("Timer cancelled");
static {
executor = new ScheduledThreadPoolExecutor(1);
@@ -42,47 +40,48 @@ public class TimerServiceImpl implements TimerService {
executor.allowCoreThreadTimeOut(true);
executor.setRemoveOnCancelPolicy(true);
}
-
+
// Using a default ConcurrentHashMap, with concurrency level 16, which should be sufficient for most applications
private static final ConcurrentHashMap<Promise<Void>, Timer> promiseToTimer = new ConcurrentHashMap<>();
-
+
private static class Timer implements Runnable {
-
+
private static final Logger logger = LoggerFactory.getLogger(Timer.class);
-
+
private final Promise<Void> promise;
private final ConcurrentHashMap<Promise<Void>, Timer> promiseToTimer;
private ScheduledFuture<?> future;
private Timer(Promise<Void> promise, ConcurrentHashMap<Promise<Void>, Timer> promiseToTimer) {
final String methodName = "<init>";
logger.entry(this, methodName, promise, promiseToTimer);
-
+
this.promise = promise;
this.promiseToTimer = promiseToTimer;
-
+
logger.exit(this, methodName);
}
+ @Override
public void run() {
final String methodName = "run";
logger.entry(this, methodName);
-
+
promiseToTimer.remove(promise);
promise.setSuccess(null);
-
+
logger.exit(this, methodName);
}
}
-
+
@Override
public void schedule(long delay, Promise<Void> promise) {
final String methodName = "schedule";
logger.entry(this, methodName, delay, promise);
-
+
final Timer timer = new Timer(promise, promiseToTimer);
final ScheduledFuture<?> sf = executor.schedule(timer, delay, TimeUnit.MILLISECONDS);
timer.future = sf;
promiseToTimer.put(promise, timer);
-
+
logger.exit(this, methodName);
}
@@ -95,10 +94,10 @@ public class TimerServiceImpl implements TimerService {
if (timer != null) {
if (timer.future.cancel(false)) {
promiseToTimer.remove(promise);
- promise.setFailure(failureException);
+ promise.setFailure(null);
}
}
-
+
logger.exit(this, methodName);
}
|
Remove the ClientException when timer is cancelled
|
mqlight_java-mqlight
|
train
|
03a8b4cc50f02d588e55b2d69e362512170076ac
|
diff --git a/lib/chef/provider/remote_file/fetcher.rb b/lib/chef/provider/remote_file/fetcher.rb
index <HASH>..<HASH> 100644
--- a/lib/chef/provider/remote_file/fetcher.rb
+++ b/lib/chef/provider/remote_file/fetcher.rb
@@ -43,7 +43,7 @@ class Chef
def self.network_share?(source)
case source
when String
- !!(%r{\A\\\\[A-Za-z][A-Za-z0-9+\-\.]*} =~ source)
+ !!(%r{\A\\\\[A-Za-z0-9+\-\.]+} =~ source)
else
false
end
diff --git a/spec/unit/provider/remote_file/fetcher_spec.rb b/spec/unit/provider/remote_file/fetcher_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/unit/provider/remote_file/fetcher_spec.rb
+++ b/spec/unit/provider/remote_file/fetcher_spec.rb
@@ -25,13 +25,22 @@ describe Chef::Provider::RemoteFile::Fetcher do
let(:fetcher_instance) { double("fetcher") }
describe "when passed a network share" do
- let(:source) { "\\\\foohost\\fooshare\\Foo.tar.gz" }
-
before do
expect(Chef::Provider::RemoteFile::NetworkFile).to receive(:new).and_return(fetcher_instance)
end
- it "returns a network file fetcher" do
- expect(described_class.for_resource(source, new_resource, current_resource)).to eq(fetcher_instance)
+
+ context "when host is a name" do
+ let(:source) { "\\\\foohost\\fooshare\\Foo.tar.gz" }
+ it "returns a network file fetcher" do
+ expect(described_class.for_resource(source, new_resource, current_resource)).to eq(fetcher_instance)
+ end
+ end
+
+ context "when host is an ip" do
+ let(:source) { "\\\\127.0.0.1\\fooshare\\Foo.tar.gz" }
+ it "returns a network file fetcher" do
+ expect(described_class.for_resource(source, new_resource, current_resource)).to eq(fetcher_instance)
+ end
end
end
|
Allow unc to have ip address
|
chef_chef
|
train
|
ac9bf4117b95094c72fb86e19f91bfa7302d73fe
|
diff --git a/bundles/org.eclipse.orion.client.git/web/orion/git/gitCommands.js b/bundles/org.eclipse.orion.client.git/web/orion/git/gitCommands.js
index <HASH>..<HASH> 100644
--- a/bundles/org.eclipse.orion.client.git/web/orion/git/gitCommands.js
+++ b/bundles/org.eclipse.orion.client.git/web/orion/git/gitCommands.js
@@ -1155,8 +1155,6 @@ var exports = {};
var resetIndexCommand = new mCommands.Command({
name : "Reset",
tooltip: "Reset your active branch to the state of the selected branch. Discard all staged and unstaged changes.",
- imageClass: "git-sprite-refresh",
- spriteClass: "gitCommandSprite",
id : "eclipse.orion.git.resetIndex",
callback: function(data) {
var item = data.items;
|
Bug <I> - new icons for <I>. Remove refresh/reload icon from git reset. Shouldn't use such an innocuous icon for such a dangerous command.
|
eclipse_orion.client
|
train
|
a9641eb301664c4cbff9feb4777dee3f957d589c
|
diff --git a/fedmsg/text/__init__.py b/fedmsg/text/__init__.py
index <HASH>..<HASH> 100644
--- a/fedmsg/text/__init__.py
+++ b/fedmsg/text/__init__.py
@@ -65,6 +65,7 @@ from fedmsg.text.default import DefaultProcessor
class ProcessorsNotInitialized(Exception):
def __iter__(self):
raise self
+ __len__ = __iter__
processors = ProcessorsNotInitialized("You must first call "
"fedmsg.text.make_processors(**config)")
|
Add __len__ to the ProcessorsNotInitialized exception
|
fedora-infra_fedmsg
|
train
|
4cd03403e0e9d1c8b955b9d9881e77e77a481eb4
|
diff --git a/src/Zofe/Rapyd/DataFilter/DataFilter.php b/src/Zofe/Rapyd/DataFilter/DataFilter.php
index <HASH>..<HASH> 100644
--- a/src/Zofe/Rapyd/DataFilter/DataFilter.php
+++ b/src/Zofe/Rapyd/DataFilter/DataFilter.php
@@ -96,8 +96,9 @@ class DataFilter extends DataForm
{
$this->query = $query_scope($this->query, $field->value);
- } elseif (isset($this->model) && method_exists($this->model, $query_scope))
+ } elseif (isset($this->model) && method_exists($this->model, "scope".$query_scope))
{
+ $query_scope = "scope".$query_scope;
$this->query = $this->model->$query_scope($this->query, $field->value);
}
|
demo cleanup customfilter, queryscope moved to model
|
zofe_rapyd-laravel
|
train
|
de56d5d83fe6a9bc50a72368a287bd44fa31a640
|
diff --git a/test/StoragelessSessionTest/Session/DataTest.php b/test/StoragelessSessionTest/Session/DataTest.php
index <HASH>..<HASH> 100644
--- a/test/StoragelessSessionTest/Session/DataTest.php
+++ b/test/StoragelessSessionTest/Session/DataTest.php
@@ -37,4 +37,9 @@ final class DataTest extends PHPUnit_Framework_TestCase
{
self::assertTrue(Data::fromTokenData([])->isEmpty());
}
+
+ public function testContainerIsNotEmptyWhenDataIsProvided()
+ {
+ self::assertFalse(Data::fromTokenData(['foo' => 'bar'])->isEmpty());
+ }
}
|
Container is not supposed to be empty when data is given to it
|
psr7-sessions_storageless
|
train
|
f236126a49f6ec8c52a3c6b91ec8873a45a1b047
|
diff --git a/src/Rah/Sitemap.php b/src/Rah/Sitemap.php
index <HASH>..<HASH> 100644
--- a/src/Rah/Sitemap.php
+++ b/src/Rah/Sitemap.php
@@ -287,14 +287,14 @@ class Rah_Sitemap
}
$rs = safe_rows_start(
- '*, unix_timestamp(Posted) as uPosted, unix_timestamp(LastMod) as uLastMod',
+ '*, unix_timestamp(Posted) as posted, unix_timestamp(LastMod) as uLastMod',
'textpattern',
implode(' and ', $sql) . ' order by Posted desc'
);
if ($rs) {
while ($a = nextRow($rs)) {
- $this->addUrl(permlinkurl($a), (int) max($a['uLastMod'], $a['uPosted']));
+ $this->addUrl(permlinkurl($a), (int) max($a['uLastMod'], $a['posted']));
}
}
|
Fix /year/month/day/title permlinks.
permlinkurl() expects a UNIX timestamp.
Fixes #2
|
gocom_rah_sitemap
|
train
|
47c331e0fb93d3859b7870cf7e80a3c69785f837
|
diff --git a/lib/ancestry/has_ancestry.rb b/lib/ancestry/has_ancestry.rb
index <HASH>..<HASH> 100644
--- a/lib/ancestry/has_ancestry.rb
+++ b/lib/ancestry/has_ancestry.rb
@@ -68,6 +68,7 @@ class << ActiveRecord::Base
# Cache depth in depth cache column before save
before_validation :cache_depth
+ before_save :cache_depth
# Validate depth column
validates_numericality_of depth_cache_column, :greater_than_or_equal_to => 0, :only_integer => true, :allow_nil => false
diff --git a/test/has_ancestry_test.rb b/test/has_ancestry_test.rb
index <HASH>..<HASH> 100644
--- a/test/has_ancestry_test.rb
+++ b/test/has_ancestry_test.rb
@@ -472,6 +472,17 @@ class HasAncestryTreeTest < ActiveSupport::TestCase
end
end
+ def test_depth_caching_after_subtree_movement
+ AncestryTestDatabase.with_model :depth => 6, :width => 1, :cache_depth => true, :depth_cache_column => :depth_cache do |model, roots|
+ node = model.at_depth(3).first
+ node.update_attributes(:parent => model.roots.first)
+ assert_equal(1, node.depth_cache)
+ node.descendants.each do |descendant|
+ assert_equal(descendant.depth, descendant.depth_cache)
+ end
+ end
+ end
+
def test_depth_scopes
AncestryTestDatabase.with_model :depth => 4, :width => 2, :cache_depth => true do |model, roots|
model.before_depth(2).all? { |node| assert node.depth < 2 }
|
Added a before_save callback for cache_depth as well as the existing before_validation callback. This ensures that all descendants in a subtree have their depth cache updated when the subtree is moved.
|
stefankroes_ancestry
|
train
|
fd53bf00c1eb6cd2f4a11edce2c8d30284f460c2
|
diff --git a/dallinger/deployment.py b/dallinger/deployment.py
index <HASH>..<HASH> 100644
--- a/dallinger/deployment.py
+++ b/dallinger/deployment.py
@@ -308,8 +308,8 @@ def _handle_launch_data(url, error, delay=INITIAL_DELAY, attempts=MAX_ATTEMPTS):
launch_data = launch_request.json()
except ValueError:
error(
- "Error parsing response from /launch, "
- "check web dyno logs for details: " + launch_request.text
+ "Error parsing response from {}, "
+ "check web dyno logs for details: {}".format(url, launch_request.text)
)
raise
@@ -318,8 +318,8 @@ def _handle_launch_data(url, error, delay=INITIAL_DELAY, attempts=MAX_ATTEMPTS):
return launch_data
error(
- "Error accessing /launch ({}):\n{}".format(
- launch_request.status_code, launch_request.text
+ "Error accessing {} ({}):\n{}".format(
+ url, launch_request.status_code, launch_request.text
)
)
@@ -443,7 +443,9 @@ def deploy_sandbox_shared_setup(log, verbose=True, app=None, exp_config=None):
# Launch the experiment.
log("Launching the experiment on the remote server and starting recruitment...")
- launch_data = _handle_launch_data("{}/launch".format(heroku_app.url), error=log)
+ launch_url = "{}/launch".format(heroku_app.url)
+ log("Calling {}".format(launch_url), chevrons=False)
+ launch_data = _handle_launch_data(launch_url, error=log)
result = {
"app_name": heroku_app.name,
"app_home": heroku_app.url,
|
When there are launch errors, show the URL
|
Dallinger_Dallinger
|
train
|
7885c32ef8d46b4e1c0f4f8574f2fd1311555971
|
diff --git a/src/Model/Environment.php b/src/Model/Environment.php
index <HASH>..<HASH> 100644
--- a/src/Model/Environment.php
+++ b/src/Model/Environment.php
@@ -310,4 +310,27 @@ class Environment extends Resource
{
return Route::getCollection($this->getLink('#manage-routes'), 0, [], $this->client);
}
+
+ /**
+ * Initialize the environment from an external repository.
+ *
+ * This can only work when the repository is empty.
+ *
+ * @param string $profile
+ * The name of the profile. This is shown in the resulting activity log.
+ * @param string $repository
+ * A repository URL, optionally followed by an '@' sign and a branch name,
+ * e.g. 'git://github.com/platformsh/platformsh-examples.git@drupal/7.x'.
+ * The default branch is 'master'.
+ *
+ * @return Activity
+ */
+ public function initialize($profile, $repository) {
+ $values = [
+ 'profile' => $profile,
+ 'repository' => $repository,
+ ];
+
+ return $this->runLongOperation('initialize', 'post', $values);
+ }
}
diff --git a/src/Model/Project.php b/src/Model/Project.php
index <HASH>..<HASH> 100644
--- a/src/Model/Project.php
+++ b/src/Model/Project.php
@@ -178,27 +178,4 @@ class Project extends Resource
return Integration::create($body, $this->getLink('integrations'), $this->client);
}
-
- /**
- * Initialize the project from an external repository.
- *
- * This can only work when the project's repository is empty.
- *
- * @param string $profile
- * The name of the profile. This is shown in the resulting activity log.
- * @param string $repository
- * A repository URL, optionally followed by an '@' sign and a branch name,
- * e.g. 'git://github.com/platformsh/platformsh-examples.git@drupal/7.x'.
- * The default branch is 'master'.
- *
- * @return Activity
- */
- public function initialize($profile, $repository) {
- $values = [
- 'profile' => $profile,
- 'repository' => $repository,
- ];
-
- return $this->runLongOperation('initialize', 'post', $values);
- }
}
|
Initialize is an environment operation, not project
|
platformsh_platformsh-client-php
|
train
|
2a35ad428b4b34f96d6d36e6d1b390505a9af1e2
|
diff --git a/IPython/html/widgets/widget.py b/IPython/html/widgets/widget.py
index <HASH>..<HASH> 100644
--- a/IPython/html/widgets/widget.py
+++ b/IPython/html/widgets/widget.py
@@ -197,7 +197,7 @@ class Widget(LoggingConfigurable):
keys = self.keys if key is None else [key]
state = {}
for k in keys:
- f = self.trait_metadata(k, 'to_json')
+ f = self.trait_metadata(k, 'serialize')
value = getattr(self, k)
if f is not None:
state[k] = f(value)
@@ -288,11 +288,11 @@ class Widget(LoggingConfigurable):
"""Called when a state is received from the front-end."""
for name in self.keys:
if name in sync_data:
- f = self.trait_metadata(name, 'from_json')
+ f = self.trait_metadata(name, 'deserialize')
if f is not None:
value = f(sync_data[name])
else:
- value = self._unserialize_trait(sync_data[name])
+ value = self._deserialize_trait(sync_data[name])
with self._lock_property(name, value):
setattr(self, name, value)
@@ -326,15 +326,15 @@ class Widget(LoggingConfigurable):
else:
return x # Value must be JSON-able
- def _unserialize_trait(self, x):
+ def _deserialize_trait(self, x):
"""Convert json values to objects
We explicitly support converting valid string widget UUIDs to Widget references.
"""
if isinstance(x, dict):
- return {k: self._unserialize_trait(v) for k, v in x.items()}
+ return {k: self._deserialize_trait(v) for k, v in x.items()}
elif isinstance(x, (list, tuple)):
- return [self._unserialize_trait(v) for v in x]
+ return [self._deserialize_trait(v) for v in x]
elif isinstance(x, string_types) and x.startswith('IPY_MODEL_') and x[10:] in Widget.widgets:
# we want to support having child widgets at any level in a hierarchy
# trusting that a widget UUID will not appear out in the wild
|
Change serialization terminology to serialize/deserialize
|
jupyter-widgets_ipywidgets
|
train
|
ba7b653854cbabacc35cee466976634bc1b3f442
|
diff --git a/src/index.js b/src/index.js
index <HASH>..<HASH> 100644
--- a/src/index.js
+++ b/src/index.js
@@ -6,7 +6,7 @@ import truncate from 'semver-truncate'
import numberRange from 'range-function'
import last from 'array-last'
-export default function majors (range) {
+export default function majors (range, maximum) {
const semvers = new Range(range).set
.reduce((comparators, set) => {
comparators.push.apply(comparators, set)
@@ -23,10 +23,14 @@ export default function majors (range) {
})
if (last(semvers).operator.charAt(0) === '>') {
- throw new Error(`Cannot determine major versions: "${range}" is unbounded`)
+ if (maximum == null) {
+ throw new Error(`Cannot determine major versions: "${range}" is unbounded and no maximum was provided`)
+ }
+ semvers.push({
+ version: parseInt(maximum) + 1,
+ operator: '<'
+ })
}
-
const [lower, upper] = semvers.map(semver => semver.version)
-
return numberRange(lower, upper).map(n => n.toString())
}
diff --git a/test/index.js b/test/index.js
index <HASH>..<HASH> 100644
--- a/test/index.js
+++ b/test/index.js
@@ -7,8 +7,11 @@ test((t) => {
t.deepEqual(majors('> 2 < 5'), ['3', '4'])
t.deepEqual(majors('< 5 > 2'), ['3', '4'])
t.deepEqual(majors('>= 2.3.0 < 5'), ['2', '3', '4'])
+
t.throws(majors.bind(null, '> 2 > 10'), /unbounded/)
t.throws(majors.bind(null, '> 2'), /unbounded/)
+ t.deepEqual(majors('>= 2', '4.3.2'), ['2', '3', '4'], 'unbounded with maximum');
+
t.end()
})
|
Allow an unbound range to be constrained by a maximum verion number
|
bendrucker_major-versions
|
train
|
cadcfb6830228113ef541d2ead43f50c8e11679f
|
diff --git a/src/routesManager.js b/src/routesManager.js
index <HASH>..<HASH> 100644
--- a/src/routesManager.js
+++ b/src/routesManager.js
@@ -79,7 +79,7 @@ RoutesManager.prototype.addRoute = function(route){
};
route.when = route.when || "GET";//set default
context.route.maxLength = context.route.maxLength || context.app.maxLength || 1e6 ;
-
+
const handlerRunners = this.extractHandlersFromRoute(route);
//read request body when there is at least one handler to handle it
@@ -89,7 +89,6 @@ RoutesManager.prototype.addRoute = function(route){
const bigBodyAlert = this.handlers.get("__exceedContentLength").handle || this.handlers.get("__exceedContentLength");
const errorHandler = this.handlers.get("__error").handle || this.handlers.get("__error");
-
this.router.on(route.when,route.uri, async (nativeRequest,nativeResponse,params) => {
const ans = new HttpAnswer(nativeResponse);
const asked = new HttpAsked(nativeRequest,params,context);
@@ -152,13 +151,12 @@ RoutesManager.prototype.extractHandlersFromRoute = function(route){
const handler = this.handlers.get(route.after[i]);
if(!handler) throw new ApplicationSetupError("Unregistered handler " + route.after[i]);
- handlerRunners.push(new Runner(route.after[i],handler,this.beforeEachPreHandler,this.afterEachPreHandler));
+ handlerRunners.push(new Runner(route.after[i],handler.handle || handler,this.beforeEachPreHandler,this.afterEachPreHandler));
}
}
-
if(route.to){
const handler = this.handlers.get(route.to);
- handlerRunners.push(new Runner(route.to,handler,this.beforeMainHandler,this.afterMainHandler));
+ handlerRunners.push(new Runner(route.to,handler.handle || handler,this.beforeMainHandler,this.afterMainHandler));
}
//Prepare the list of handler need to be called after
@@ -170,7 +168,7 @@ RoutesManager.prototype.extractHandlersFromRoute = function(route){
const handler = this.handlers.get(route.then[i]);
if(!handler) throw new ApplicationSetupError("Unregistered handler " + route.then[i]);
- handlerRunners.push(new Runner(route.then[i],handler,this.beforeEachPostHandler,this.afterEachPostHandler));
+ handlerRunners.push(new Runner(route.then[i],handler.handle || handler ,this.beforeEachPostHandler,this.afterEachPostHandler));
}
}
|
fix routes manager when handler can be a method or an object
|
node-muneem_muneem
|
train
|
09f9f99d0ddec158baa649b5aedc5125b76ff8c7
|
diff --git a/howdoi/howdoi.py b/howdoi/howdoi.py
index <HASH>..<HASH> 100755
--- a/howdoi/howdoi.py
+++ b/howdoi/howdoi.py
@@ -649,11 +649,14 @@ def _sanity_check(engine, test_query=None):
if not test_query:
test_query = 'format date bash'
- args = vars(parser.parse_args(('-j ' + test_query).split()))
+ args = vars(parser.parse_args(test_query.split()))
args['search_engine'] = engine
try:
- assert isinstance(howdoi(args).encode('utf-8', 'ignore'), list)
+ result = howdoi(args)
+ # Perhaps better to use `-j` and then check for an error message
+ # rather than trying to enumerate all the error strings
+ assert "Sorry" not in result and "Unable to" not in result
except AssertionError as exc:
if engine == 'google':
raise GoogleValidationError from exc
|
An option for fixing the sanity check issue
|
gleitz_howdoi
|
train
|
29bc9e44c4ad40a4f2739646a4a44bf2747d1637
|
diff --git a/tasks/build.js b/tasks/build.js
index <HASH>..<HASH> 100644
--- a/tasks/build.js
+++ b/tasks/build.js
@@ -8,6 +8,7 @@ var gulp = require('gulp'),
path = require('path');
var argv = global.argv;
+var appiumRoot = global.appiumRoot;
gulp.task('download-build', ['prepare-dirs'], function () {
var m = argv.downloadBuild.match(/(.*)\/(.*)/);
@@ -32,6 +33,31 @@ gulp.task('download-build', ['prepare-dirs'], function () {
});
});
+gulp.task('download-scp-build', ['prepare-dirs'], function () {
+ var m = argv.downloadBuild.match(/(.*)\/(.*)/);
+ var jobName = m[1];
+ var buildNumber = m[2];
+ var uploadServer = process.env.BUILD_UPLOAD_SERVER;
+ var src = path.resolve('builds', jobName, buildNumber, 'appium-build.bz2');
+ var target = path.resolve(global.inputDir, 'appium-build.bz2');
+ console.log('downloading via scp:', src);
+ return utils.smartSpawn(
+ 'scp',
+ [
+ '-o',
+ "UserKnownHostsFile=/dev/null",
+ '-o',
+ 'StrictHostKeyChecking=no',
+ 'appium@' + uploadServer + ':' + src,
+ target
+ ],
+ {
+ print: 'Uploding build to: ' + uploadServer,
+ cwd: appiumRoot
+ }
+ ).promise;
+});
+
gulp.task('expand-build' , function function_name() {
return utils.smartSpawn('tar', [
'xfjp',
diff --git a/tasks/ios-build.js b/tasks/ios-build.js
index <HASH>..<HASH> 100644
--- a/tasks/ios-build.js
+++ b/tasks/ios-build.js
@@ -7,6 +7,7 @@ var gulp = require('gulp'),
// _ = require('underscore');
var appiumRoot = global.appiumRoot;
+var uploadServer = process.env.BUILD_UPLOAD_SERVER;
gulp.task('run-ios-build',
['prepare-dirs'],function () {
@@ -43,7 +44,22 @@ gulp.task('run-ios-build',
}
).promise;
}).then(function() {
- var uploadServer = process.env.BUILD_UPLOAD_SERVER;
+ return utils.smartSpawn(
+ 'ssh',
+ [
+ '-o',
+ "UserKnownHostsFile=/dev/null",
+ '-o',
+ 'StrictHostKeyChecking=no',
+ 'appium@' + uploadServer,
+ 'mkdir -p ' + path.resolve('builds', process.env.JOB_NAME, process.env.BUILD_NUMBER)
+ ],
+ {
+ print: 'Uploding build to: ' + uploadServer,
+ cwd: appiumRoot,
+ }
+ ).promise;
+ }).then(function() {
return utils.smartSpawn(
'scp',
[
@@ -52,12 +68,12 @@ gulp.task('run-ios-build',
'-o',
'StrictHostKeyChecking=no',
path.resolve(global.artifactsDir, 'appium-build.bz2'),
- 'appium@' + uploadServer + ':builds/' + process.env.BUILD_ID + '_appium-build.bz2'
+ 'appium@' + uploadServer + ':' + path.resolve('builds', process.env.JOB_NAME, process.env.BUILD_NUMBER, 'appium-build.bz2')
],
{
print: 'Uploding build to: ' + uploadServer,
cwd: appiumRoot,
}
).promise;
- });
+ });
});
|
adds ios build upload/download logic
|
appium_appium-ci
|
train
|
af65ee08202dcb4372b24d79b20813791b72c05f
|
diff --git a/setup.py b/setup.py
index <HASH>..<HASH> 100755
--- a/setup.py
+++ b/setup.py
@@ -31,6 +31,7 @@ setup(
],
install_requires=[
'requests>=2.3.0',
+ 'six>=1.7.3'
],
tests_require=[
'mock>=1.0.1',
diff --git a/tbk/webpay/payment.py b/tbk/webpay/payment.py
index <HASH>..<HASH> 100644
--- a/tbk/webpay/payment.py
+++ b/tbk/webpay/payment.py
@@ -1,9 +1,10 @@
import sys
import re
import random
-import urlparse
import hashlib
+import six.moves.urllib.parse as urlparse
+
import requests
from .commerce import Commerce
@@ -124,7 +125,7 @@ class Payment(object):
h.update(str(self.commerce.id))
h.update("webpay")
mac = str(h.hexdigest())
-
+
params += ["TBK_MAC=%s" % mac]
params += ["TBK_MONTO=%d" % int(self.amount * 100)]
|
added six for python3 support
|
pedroburon_tbk
|
train
|
0f0e676b38439850297c878e631f5bcaa8e3813e
|
diff --git a/supervisord/tests/common.py b/supervisord/tests/common.py
index <HASH>..<HASH> 100644
--- a/supervisord/tests/common.py
+++ b/supervisord/tests/common.py
@@ -21,7 +21,7 @@ URL = "http://{}:{}".format(HOST, PORT)
PROCESSES_BY_STATE_BY_ITERATION = [dict(up=PROCESSES[x:], down=PROCESSES[:x], unknown=[]) for x in range(4)]
# Configs for Integration Tests
-SUPERVISORD_CONFIG = {'name': "travis", 'host': "localhost", 'port': '19001'}
+SUPERVISORD_CONFIG = {'name': "travis", 'host': HOST, 'port': '19001'}
BAD_SUPERVISORD_CONFIG = {'name': "travis", 'socket': "unix:///wrong/path/supervisor.sock", 'host': "http://127.0.0.1"}
# Configs for Unit/Mocked tests
diff --git a/supervisord/tests/conftest.py b/supervisord/tests/conftest.py
index <HASH>..<HASH> 100644
--- a/supervisord/tests/conftest.py
+++ b/supervisord/tests/conftest.py
@@ -32,6 +32,6 @@ def bad_instance():
@pytest.fixture(scope='session')
def dd_environment():
with docker_run(compose_file=os.path.join(HERE, 'compose', 'supervisord.yaml'), endpoints=URL):
- server = xmlrpclib.Server('http://localhost:19001/RPC2')
+ server = xmlrpclib.Server('{}/RPC2'.format(URL))
server.supervisor.startAllProcesses()
yield SUPERVISORD_CONFIG
diff --git a/supervisord/tox.ini b/supervisord/tox.ini
index <HASH>..<HASH> 100644
--- a/supervisord/tox.ini
+++ b/supervisord/tox.ini
@@ -5,8 +5,12 @@ envlist =
py{27,37}-{3.3.3,unit}
[testenv]
+usedevelop = true
dd_check_style = true
platform = linux|darwin|win32
+passenv =
+ DOCKER*
+ COMPOSE*
setenv = SUPERVISOR_IMAGE=datadog/docker-library:supervisord_3_3_3
deps =
-e../datadog_checks_base[deps]
|
Make e2e work on non-localhost setup (#<I>)
|
DataDog_integrations-core
|
train
|
aeec154a3dccddf7abb14ae5dc1236918618f9ef
|
diff --git a/livesync/indico_livesync/models/queue.py b/livesync/indico_livesync/models/queue.py
index <HASH>..<HASH> 100644
--- a/livesync/indico_livesync/models/queue.py
+++ b/livesync/indico_livesync/models/queue.py
@@ -16,12 +16,15 @@
from __future__ import unicode_literals
+from werkzeug.datastructures import ImmutableDict
+
from indico.core.db.sqlalchemy import db, UTCDateTime
from indico.util.date_time import now_utc
from indico.util.string import return_ascii
from indico.util.struct.enum import IndicoEnum
from indico_livesync.models.agents import LiveSyncAgent
+from indico_livesync.util import obj_deref
class ChangeType(int, IndicoEnum):
@@ -101,6 +104,17 @@ class LiveSyncQueueEntry(db.Model):
backref=db.backref('queue', cascade='all, delete-orphan', lazy='dynamic')
)
+ @property
+ def object(self):
+ """Returns the changed object"""
+ return obj_deref(self.object_ref)
+
+ @property
+ def object_ref(self):
+ """Returns the reference of the changed object"""
+ return ImmutableDict(type=self.type, category_id=self.category_id, event_id=self.event_id,
+ contrib_id=self.contrib_id, subcontrib_id=self.subcontrib_id)
+
@return_ascii
def __repr__(self):
return '<LiveSyncQueueEntry({}, {}, {}, {})>'.format(self.agent, self.id, ChangeType(self.change).name,
|
Add object and object_ref properties
|
indico_indico-plugins
|
train
|
5256f2f40d31888b6afe82dcc261b22b30760e56
|
diff --git a/steamfiles/acf.py b/steamfiles/acf.py
index <HASH>..<HASH> 100644
--- a/steamfiles/acf.py
+++ b/steamfiles/acf.py
@@ -1,21 +1,20 @@
-from collections import OrderedDict
-
__all__ = ('load', 'loads', 'dump', 'dumps')
SECTION_START = '{'
SECTION_END = '}'
-def loads(data):
+def loads(data, wrapper=dict):
"""
Loads ACF content into a Python object.
:param data: An UTF-8 encoded content of an ACF file.
+ :param wrapper: A wrapping object for key-value pairs.
:return: An Ordered Dictionary with ACF data.
"""
if not isinstance(data, str):
raise TypeError('can only load a str as an ACF')
- parsed = OrderedDict()
+ parsed = wrapper()
current_section = parsed
sections = []
@@ -29,7 +28,7 @@ def loads(data):
except ValueError:
if line == SECTION_START:
# Initialize the last added section.
- current_section = _prepare_subsection(parsed, sections)
+ current_section = _prepare_subsection(parsed, sections, wrapper)
elif line == SECTION_END:
# Remove the last section from the queue.
sections.pop()
@@ -43,13 +42,14 @@ def loads(data):
return parsed
-def load(fp):
+def load(fp, wrapper=dict):
"""
Loads the contents of an ACF file into a Python object.
:param fp: A file object.
+ :param wrapper: A wrapping object for key-value pairs.
:return: An Ordered Dictionary with ACF data.
"""
- return loads(fp.read())
+ return loads(fp.read(), wrapper=wrapper)
def dumps(obj):
@@ -100,16 +100,17 @@ def _dumps(obj, level):
return lines
-def _prepare_subsection(data, sections):
+def _prepare_subsection(data, sections, wrapper):
"""
Creates a subsection ready to be filled.
:param data: Semi-parsed dictionary.
:param sections: A list of sections.
+ :param wrapper: A wrapping object for key-value pairs.
:return: A newly created subsection.
"""
current = data
for i in sections[:-1]:
current = current[i]
- current[sections[-1]] = OrderedDict()
+ current[sections[-1]] = wrapper()
return current[sections[-1]]
diff --git a/tests/test_acf.py b/tests/test_acf.py
index <HASH>..<HASH> 100644
--- a/tests/test_acf.py
+++ b/tests/test_acf.py
@@ -1,6 +1,7 @@
import io
import os
import pytest
+from collections import OrderedDict
from steamfiles import acf
test_file_name = os.path.join(os.path.dirname(__file__), 'test_data/appmanifest_202970.acf')
@@ -18,12 +19,20 @@ def test_acf_keys_exist(acf_data):
assert 'BytesDownloaded' in data['AppState']['DlcDownloads']['202988']
assert 'BytesToDownload' in data['AppState']['DlcDownloads']['202988']
+
@pytest.mark.usefixtures('acf_data')
def test_loads_dumps(acf_data):
assert acf.dumps(acf.loads(acf_data)) == acf_data
@pytest.mark.usefixtures('acf_data')
+def test_loads_dumps_with_wrapper(acf_data):
+ loaded = acf.loads(acf_data, wrapper=OrderedDict)
+ assert isinstance(loaded, OrderedDict)
+ assert acf.dumps(loaded) == acf_data
+
+
+@pytest.mark.usefixtures('acf_data')
def test_load_dump(acf_data):
with open(test_file_name, 'rt') as in_file:
out_file = io.StringIO()
@@ -35,6 +44,20 @@ def test_load_dump(acf_data):
assert out_file.read() == acf_data
+@pytest.mark.usefixtures('acf_data')
+def test_load_dump_with_wrapper(acf_data):
+ with open(test_file_name, 'rt') as in_file:
+ out_file = io.StringIO()
+ loaded = acf.load(in_file, wrapper=OrderedDict)
+ acf.dump(loaded, out_file)
+
+ # Rewind to the beginning
+ out_file.seek(0)
+
+ assert isinstance(loaded, OrderedDict)
+ assert out_file.read() == acf_data
+
+
def test_loads_wrong_type():
with pytest.raises(TypeError):
acf.loads(b'\x00\x01\x02')
|
Implement custom containers for ACF.
load() & loads() now parse data into a `dict` instead of `OrderedDict`.
Additionally, they now take an optional argument `wrapper`.
Parsed key-value pairs are processed with `wrapper`, so you can
choose any container for the data, provided it's somewhat compatible
with `dict`. `dict` is also the default container when you don't specify
another one.
|
leovp_steamfiles
|
train
|
65184e98492433213ccf8c7a370dcb5c35187f52
|
diff --git a/java/client/test/org/openqa/selenium/FormHandlingTest.java b/java/client/test/org/openqa/selenium/FormHandlingTest.java
index <HASH>..<HASH> 100644
--- a/java/client/test/org/openqa/selenium/FormHandlingTest.java
+++ b/java/client/test/org/openqa/selenium/FormHandlingTest.java
@@ -27,7 +27,6 @@ import static org.junit.Assert.assertTrue;
import static org.junit.Assume.assumeTrue;
import static org.junit.Assert.fail;
import static org.openqa.selenium.testing.Ignore.Driver.ANDROID;
-import static org.openqa.selenium.testing.Ignore.Driver.CHROME;
import static org.openqa.selenium.testing.Ignore.Driver.IPHONE;
import static org.openqa.selenium.testing.Ignore.Driver.OPERA;
import static org.openqa.selenium.testing.Ignore.Driver.SELENESE;
@@ -166,7 +165,7 @@ public class FormHandlingTest extends JUnit4TestBase {
assertThat(newFormValue, equalTo("some text"));
}
- @Ignore(value = {CHROME, SELENESE, IPHONE, ANDROID, OPERA},
+ @Ignore(value = {SELENESE, IPHONE, ANDROID, OPERA},
reason = "Does not yet support file uploads")
@Test
public void testShouldBeAbleToAlterTheContentsOfAFileUploadInputElement() throws IOException {
@@ -183,7 +182,7 @@ public class FormHandlingTest extends JUnit4TestBase {
assertTrue(uploadPath.endsWith(file.getName()));
}
- @Ignore(value = {ANDROID, CHROME, IPHONE, OPERA, SELENESE},
+ @Ignore(value = {ANDROID, IPHONE, OPERA, SELENESE},
reason = "Does not yet support file uploads")
@Test
public void testShouldBeAbleToSendKeysToAFileUploadInputElementInAnXhtmlDocument() throws IOException {
@@ -204,7 +203,7 @@ public class FormHandlingTest extends JUnit4TestBase {
assertTrue(uploadPath.endsWith(file.getName()));
}
- @Ignore(value = {CHROME, SELENESE, IPHONE, ANDROID, OPERA},
+ @Ignore(value = {SELENESE, IPHONE, ANDROID, OPERA},
reason = "Does not yet support file uploads")
@Test
public void testShouldBeAbleToUploadTheSameFileTwice() throws IOException {
|
AlexeiBarantsev: Unignoring more file uploading tests for Chrome.
r<I>
|
SeleniumHQ_selenium
|
train
|
56c32c0a30efd3d7c4e7c6600a0ca39e51eecc97
|
diff --git a/src/main/java/com/tomgibara/bits/BitVector.java b/src/main/java/com/tomgibara/bits/BitVector.java
index <HASH>..<HASH> 100644
--- a/src/main/java/com/tomgibara/bits/BitVector.java
+++ b/src/main/java/com/tomgibara/bits/BitVector.java
@@ -2913,12 +2913,13 @@ public final class BitVector implements BitStore, Alignable<BitVector>, Cloneabl
@Override
public int size() {
- return countOnesAdj(start, finish);
+ int count = countOnesAdj(start, finish);
+ return bit ? count : finish - start - count;
}
@Override
public boolean isEmpty() {
- return isAllZerosAdj(start, finish);
+ return bit ? isAllZerosAdj(start, finish) : isAllOnesAdj(start, finish);
}
@Override
@@ -2938,7 +2939,7 @@ public final class BitVector implements BitStore, Alignable<BitVector>, Cloneabl
if (!(o instanceof Integer)) return false;
int i = offset + (Integer) o;
if (i < start || i >= finish) return false;
- return getThenSetBit(i, bit) == bit;
+ return getThenSetBit(i, !bit) == bit;
}
@Override
diff --git a/src/main/java/com/tomgibara/bits/IntSetBitStore.java b/src/main/java/com/tomgibara/bits/IntSetBitStore.java
index <HASH>..<HASH> 100644
--- a/src/main/java/com/tomgibara/bits/IntSetBitStore.java
+++ b/src/main/java/com/tomgibara/bits/IntSetBitStore.java
@@ -554,7 +554,7 @@ final class IntSetBitStore extends AbstractBitStore {
@Override
public void remove() {
if (prev == -1) throw new IllegalStateException();
- set.remove(prev);
+ set.add(prev);
prev = -1;
}
diff --git a/src/test/java/com/tomgibara/bits/BitStoreTest.java b/src/test/java/com/tomgibara/bits/BitStoreTest.java
index <HASH>..<HASH> 100644
--- a/src/test/java/com/tomgibara/bits/BitStoreTest.java
+++ b/src/test/java/com/tomgibara/bits/BitStoreTest.java
@@ -21,6 +21,7 @@ import java.util.Arrays;
import java.util.BitSet;
import java.util.Collections;
import java.util.HashSet;
+import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import java.util.Random;
@@ -737,6 +738,25 @@ public abstract class BitStoreTest extends TestCase {
}
assertEquals(v.size(), count + set.size());
+
+ v.fill();
+ assertTrue(zet.isEmpty());
+ assertEquals(0, zet.size());
+
+ v.clear();
+ for (Iterator<?> i = zet.iterator(); i.hasNext(); ) {
+ i.next();
+ i.remove();
+ }
+ assertTrue(v.ones().isAll());
+ assertTrue(zet.isEmpty());
+
+ v.clear();
+ for (int i = 0; i < 30; i++) {
+ zet.remove(i);
+ }
+ assertTrue(v.ones().isAll());
+ assertTrue(zet.isEmpty());
}
public void testCompareTo() {
|
Fixes removal and sizing on zero bit integer set implementations.
|
tomgibara_bits
|
train
|
2740792df3144e205dc84f71dd0db1b04479ead3
|
diff --git a/src/viewer.js b/src/viewer.js
index <HASH>..<HASH> 100644
--- a/src/viewer.js
+++ b/src/viewer.js
@@ -2546,11 +2546,16 @@ function onCanvasDragEnd( event ) {
if ( !event.preventDefaultAction && this.viewport ) {
gestureSettings = this.gestureSettingsByDeviceType( event.pointerType );
- if ( gestureSettings.flickEnabled && event.speed >= gestureSettings.flickMinSpeed ) {
- var amplitudeX = gestureSettings.flickMomentum * ( event.speed * Math.cos( event.direction - (Math.PI / 180 * this.viewport.degrees) ) ),
- amplitudeY = gestureSettings.flickMomentum * ( event.speed * Math.sin( event.direction - (Math.PI / 180 * this.viewport.degrees) ) ),
- center = this.viewport.pixelFromPoint( this.viewport.getCenter( true ) ),
- target = this.viewport.pointFromPixel( new $.Point( center.x - amplitudeX, center.y - amplitudeY ) );
+ if (gestureSettings.flickEnabled &&
+ event.speed >= gestureSettings.flickMinSpeed) {
+ var amplitudeX = gestureSettings.flickMomentum * event.speed *
+ Math.cos(event.direction);
+ var amplitudeY = gestureSettings.flickMomentum * event.speed *
+ Math.sin(event.direction);
+ var center = this.viewport.pixelFromPoint(
+ this.viewport.getCenter(true));
+ var target = this.viewport.pointFromPixel(
+ new $.Point(center.x - amplitudeX, center.y - amplitudeY));
if( !this.panHorizontal ) {
target.x = center.x;
}
|
Fix flick gesture with rotation. Fix #<I>
|
openseadragon_openseadragon
|
train
|
b26d3c758d465bf65a9f016facfe51526b6d303d
|
diff --git a/test/smoketest.py b/test/smoketest.py
index <HASH>..<HASH> 100644
--- a/test/smoketest.py
+++ b/test/smoketest.py
@@ -39,7 +39,9 @@ class RunTC(TestCase):
try:
Run(args, reporter=reporter)
except SystemExit, ex:
- self.assertEqual(ex.code, code)
+ msg = 'expected output status %s, got %s. Below pylint output: \n%s' % (
+ code, ex.code, out.getvalue())
+ self.assertEqual(ex.code, code, msg)
else:
self.fail('expected system exit')
finally:
|
[test] display output when some test fail to ease debugging on CI platform
|
PyCQA_pylint
|
train
|
47e9a2c332d32d734f2b5073b935362df6193866
|
diff --git a/test/testsuite/generator/behavior/versionable/VersionableBehaviorObjectBuilderModifierTest.php b/test/testsuite/generator/behavior/versionable/VersionableBehaviorObjectBuilderModifierTest.php
index <HASH>..<HASH> 100644
--- a/test/testsuite/generator/behavior/versionable/VersionableBehaviorObjectBuilderModifierTest.php
+++ b/test/testsuite/generator/behavior/versionable/VersionableBehaviorObjectBuilderModifierTest.php
@@ -456,6 +456,30 @@ EOF;
$o->save();
$this->assertFalse($o->isVersioningNecessary());
VersionableBehaviorTest1Peer::enableVersioning();
+
+ $b1 = new VersionableBehaviorTest5();
+ $b1->setFoo('Hello');
+ $b2 = new VersionableBehaviorTest5();
+ $b2->setFoo('World');
+ $a = new VersionableBehaviorTest4();
+ $a->setBar(123); // a1
+ $this->assertTrue($a->isVersioningNecessary());
+ $a->save();
+ $this->assertFalse($a->isVersioningNecessary());
+ $a->addVersionableBehaviorTest5($b1);
+ $this->assertTrue($a->isVersioningNecessary());
+ $a->save();
+ $this->assertFalse($a->isVersioningNecessary());
+ $a->addVersionableBehaviorTest5($b2);
+ $this->assertTrue($a->isVersioningNecessary());
+ $a->save();
+ $this->assertFalse($a->isVersioningNecessary());
+ $b2->setFoo('World !');
+ $this->assertTrue($b2->isVersioningNecessary());
+ $this->assertTrue($a->isVersioningNecessary());
+ $a->save();
+ $this->assertFalse($b2->isVersioningNecessary());
+ $this->assertFalse($a->isVersioningNecessary());
}
public function testAddVersionNewObject()
|
add tests to versionnable behavior whit foreign key
|
propelorm_Propel
|
train
|
064bfa1f12710dc4448a2b224b1527ed67df267f
|
diff --git a/anytemplate/utils.py b/anytemplate/utils.py
index <HASH>..<HASH> 100644
--- a/anytemplate/utils.py
+++ b/anytemplate/utils.py
@@ -1,6 +1,6 @@
# -*- coding: utf-8 -*-
"""
-:copyright: (c) 2012 - 2015 by Satoru SATOH <ssato@redhat.com>
+:copyright: (c) 2012 - 2018 by Satoru SATOH <ssato@redhat.com>
:license: MIT
"""
# unicode_literals ?
@@ -16,9 +16,11 @@ import sys
import anytemplate.compat
try:
- from anyconfig.api import load, merge
+ from anyconfig.api import loads, load, merge
except ImportError:
- from anytemplate.compat import json_load as load, merge
+ from anytemplate.compat import (
+ json_loads as loads, json_load as load, merge
+ )
LOGGER = logging.getLogger(__name__)
@@ -154,6 +156,19 @@ def parse_filespec(fspec, sep=':', gpat='*'):
if gpat in fspec else [flip(tpl)]
+def load_context(ctx_path, ctx_type, scm=None):
+ """
+ :param ctx_path: context file path or '-' (read from stdin)
+ :param ctx_type: context file type
+ :param scm: JSON schema file in any formats anyconfig supports, to
+ validate given context files
+ """
+ if ctx_path == '-':
+ return loads(sys.stdin.read(), ac_parser=ctx_type, ac_schema=scm)
+
+ return load(ctx_path, ac_parser=ctx_type, ac_schema=scm)
+
+
def parse_and_load_contexts(contexts, schema=None, werr=False):
"""
:param contexts: list of context file specs
@@ -166,9 +181,9 @@ def parse_and_load_contexts(contexts, schema=None, werr=False):
diff = None
if contexts:
- for fpath, ftype in concat(parse_filespec(f) for f in contexts):
+ for ctx_path, ctx_type in concat(parse_filespec(c) for c in contexts):
try:
- diff = load(fpath, ac_parser=ftype, ac_schema=schema)
+ diff = load_context(ctx_path, ctx_type, scm=schema)
if diff is not None:
merge(ctx, diff)
except (IOError, OSError, AttributeError):
|
enhancement: support to load context from stdin '-'
|
ssato_python-anytemplate
|
train
|
4ede24a23d6f2ee26f527f9dbb509752ca160802
|
diff --git a/lib/sass/util/multibyte_string_scanner.rb b/lib/sass/util/multibyte_string_scanner.rb
index <HASH>..<HASH> 100644
--- a/lib/sass/util/multibyte_string_scanner.rb
+++ b/lib/sass/util/multibyte_string_scanner.rb
@@ -8,6 +8,11 @@ else
# characters, for methods like [#pos] and [#matched_size]. This class deals
# only in characters, instead.
class Sass::Util::MultibyteStringScanner < StringScanner
+ def self.new(str)
+ return StringScanner.new(str) if str.ascii_only?
+ super
+ end
+
def initialize(str)
super
@mb_pos = 0
|
Avoid the extra cost of MultibyteStringScanner when not dealing with multibyte strings.
|
sass_ruby-sass
|
train
|
93fa2c8f872ec44afe2dad42c556a8b0f751977f
|
diff --git a/client/isolate/isolate_test.go b/client/isolate/isolate_test.go
index <HASH>..<HASH> 100644
--- a/client/isolate/isolate_test.go
+++ b/client/isolate/isolate_test.go
@@ -11,6 +11,7 @@ import (
"net/http/httptest"
"os"
"path/filepath"
+ "strings"
"testing"
"github.com/luci/luci-go/client/archiver"
@@ -189,9 +190,9 @@ func TestArchiveFileNotFoundReturnsError(t *testing.T) {
}
future := Archive(a, "/base-dir", opts)
future.WaitForHashed()
- expectedErr := "open /this-file-does-not-exist: no such file or directory"
- ut.AssertEqual(t, expectedErr, future.Error().Error())
+ err := future.Error()
+ ut.AssertEqual(t, true, strings.HasPrefix(err.Error(), "open /this-file-does-not-exist: "))
closeErr := a.Close()
ut.AssertEqual(t, true, closeErr != nil)
- ut.AssertEqual(t, expectedErr, closeErr.Error())
+ ut.AssertEqual(t, true, strings.HasPrefix(closeErr.Error(), "open /this-file-does-not-exist: "))
}
|
Fix test on Windows.
The error message is slightly different.
R=<EMAIL>
BUG=
Review URL: <URL>
|
luci_luci-go
|
train
|
57725da8527275b916ffe5aa81c1dd92cba7f291
|
diff --git a/command/validate/commang.go b/command/validate/commang.go
index <HASH>..<HASH> 100644
--- a/command/validate/commang.go
+++ b/command/validate/commang.go
@@ -64,7 +64,7 @@ func (c Command) Run(env packer.Environment, args []string) int {
// Otherwise, get all the builds
buildNames := tpl.BuildNames()
builds := make([]packer.Build, 0, len(buildNames))
- for i, buildName := range buildNames {
+ for _, buildName := range buildNames {
build, err := tpl.Build(buildName, components)
if err != nil {
errs = append(errs, fmt.Errorf("Build '%s': %s", buildName, err))
@@ -74,11 +74,24 @@ func (c Command) Run(env packer.Environment, args []string) int {
builds = append(builds, build)
}
- // TODO(mitchellh): validate configuration
+ // Check the configuration of all builds
+ for _, b := range builds {
+ err := b.Prepare()
+ if err != nil {
+ errs = append(errs, fmt.Errorf("Errors validating build '%s'. %s", b.Name(), err))
+ }
+ }
if len(errs) > 0 {
- err = &packer.MultiError{errs}
- env.Ui().Error(fmt.Sprintf("Template validation failed. %s", err))
+ env.Ui().Error("Template validation failed. Errors are shown below.\n")
+ for i, err := range errs {
+ env.Ui().Error(err.Error())
+
+ if (i+1) < len(errs) {
+ env.Ui().Error("")
+ }
+ }
+
return 1
}
|
command/validate: Validate configuration
|
hashicorp_packer
|
train
|
f17b1ee837a2d9e4b8beea5d6957ae7baa42870a
|
diff --git a/nupic/research/connections.py b/nupic/research/connections.py
index <HASH>..<HASH> 100644
--- a/nupic/research/connections.py
+++ b/nupic/research/connections.py
@@ -316,6 +316,17 @@ class Connections(object):
return True
+ def __ne__(self, other):
+ """
+ Non-equality operator for Connections instances.
+ Checks if two instances are not functionally identical
+ (might have different internal state).
+
+ @param other (Connections) Connections instance to compare to
+ """
+ return not self.__eq__(other)
+
+
def _synapseSetForSynapses(self, synapses):
"""
Returns a set containing synapse data for synapses.
diff --git a/nupic/research/temporal_memory.py b/nupic/research/temporal_memory.py
index <HASH>..<HASH> 100644
--- a/nupic/research/temporal_memory.py
+++ b/nupic/research/temporal_memory.py
@@ -673,6 +673,50 @@ class TemporalMemory(object):
return tm
+ def __eq__(self, other):
+ """
+ Equality operator for TemporalMemory instances.
+ Checks if two instances are functionally identical
+ (might have different internal state).
+
+ @param other (TemporalMemory) TemporalMemory instance to compare to
+ """
+ epsilon = 0.0000001
+
+ if self.columnDimensions != other.columnDimensions: return False
+ if self.cellsPerColumn != other.cellsPerColumn: return False
+ if self.activationThreshold != other.activationThreshold: return False
+ if abs(self.initialPermanence - other.initialPermanence) > epsilon:
+ return False
+ if abs(self.connectedPermanence - other.connectedPermanence) > epsilon:
+ return False
+ if self.minThreshold != other.minThreshold: return False
+ if self.maxNewSynapseCount != other.maxNewSynapseCount: return False
+ if abs(self.permanenceIncrement - other.permanenceIncrement) > epsilon:
+ return False
+ if abs(self.permanenceDecrement - other.permanenceDecrement) > epsilon:
+ return False
+
+ if self.connections != other.connections: return False
+
+ if self.activeCells != other.activeCells: return False
+ if self.predictiveCells != other.predictiveCells: return False
+ if self.winnerCells != other.winnerCells: return False
+
+ return True
+
+
+ def __ne__(self, other):
+ """
+ Non-equality operator for TemporalMemory instances.
+ Checks if two instances are not functionally identical
+ (might have different internal state).
+
+ @param other (TemporalMemory) TemporalMemory instance to compare to
+ """
+ return not self.__eq__(other)
+
+
def _validateColumn(self, column):
"""
Raises an error if column index is invalid.
diff --git a/tests/unit/nupic/research/temporal_memory_test.py b/tests/unit/nupic/research/temporal_memory_test.py
index <HASH>..<HASH> 100755
--- a/tests/unit/nupic/research/temporal_memory_test.py
+++ b/tests/unit/nupic/research/temporal_memory_test.py
@@ -620,21 +620,7 @@ class TemporalMemoryTest(unittest.TestCase):
tm2 = TemporalMemory.read(proto2)
# Check that the two temporal memory objects have the same attributes
- self.assertEqual(tm1.columnDimensions, tm2.columnDimensions)
- self.assertEqual(tm1.cellsPerColumn, tm2.cellsPerColumn)
- self.assertEqual(tm1.activationThreshold, tm2.activationThreshold)
- self.assertAlmostEqual(tm1.initialPermanence, tm2.initialPermanence)
- self.assertAlmostEqual(tm1.connectedPermanence, tm2.connectedPermanence)
- self.assertEqual(tm1.minThreshold, tm2.minThreshold)
- self.assertEqual(tm1.maxNewSynapseCount, tm2.maxNewSynapseCount)
- self.assertAlmostEqual(tm1.permanenceIncrement, tm2.permanenceIncrement)
- self.assertAlmostEqual(tm1.permanenceDecrement, tm2.permanenceDecrement)
-
- self.assertEqual(tm1.connections, tm2.connections)
-
- self.assertEqual(tm1.activeCells, tm2.activeCells)
- self.assertEqual(tm1.predictiveCells, tm2.predictiveCells)
- self.assertEqual(tm1.winnerCells, tm2.winnerCells)
+ self.assertEqual(tm1, tm2)
# Run a couple records through after deserializing and check results match
tm1.compute(self.patternMachine.get(0))
|
Refactor TemporalMemory equality checking into __eq__ function
|
numenta_nupic
|
train
|
ed89f8ef405249ac52340f60d1a823b1cc7f457a
|
diff --git a/flickr/flickr.go b/flickr/flickr.go
index <HASH>..<HASH> 100644
--- a/flickr/flickr.go
+++ b/flickr/flickr.go
@@ -1,7 +1,9 @@
package flickr
import (
+ "bytes"
"crypto/hmac"
+ "crypto/md5"
"crypto/sha1"
"encoding/base64"
"encoding/xml"
@@ -11,6 +13,7 @@ import (
"math/rand"
"net/http"
"net/url"
+ "sort"
"strconv"
"strings"
"time"
@@ -74,6 +77,13 @@ func (c *FlickrClient) Sign(tokenSecret string) {
c.Args.Set("oauth_signature", c.getSignature(tokenSecret))
}
+// Specific signing process for API calls, it's not the same as OAuth sign
+func (c *FlickrClient) ApiSign(tokenSecret string) {
+ // the "api_sig" param must not be included in the signing process
+ c.Args.Del("api_sig")
+ c.Args.Set("api_sig", c.getApiSignature(tokenSecret))
+}
+
// Evaluate the complete URL to make requests (base url + params)
func (c *FlickrClient) GetUrl() string {
return fmt.Sprintf("%s?%s", c.EndpointUrl, c.Args.Encode())
@@ -114,6 +124,29 @@ func (c *FlickrClient) getSignature(token_secret string) string {
return ret
}
+func (c *FlickrClient) getApiSignature(token_secret string) string {
+ var buf bytes.Buffer
+ buf.WriteString(token_secret)
+
+ keys := make([]string, 0, len(c.Args))
+ for k := range c.Args {
+ keys = append(keys, k)
+ }
+ // args needs to be in alphabetical order
+ sort.Strings(keys)
+
+ for _, k := range keys {
+ arg := c.Args[k][0]
+ buf.WriteString(k)
+ buf.WriteString(arg)
+ }
+
+ base := buf.String()
+
+ data := []byte(base)
+ return fmt.Sprintf("%x", md5.Sum(data))
+}
+
// Base type representing responses from Flickr API
type FlickrResponse struct {
XMLName xml.Name `xml:"rsp"`
diff --git a/flickr/flickr_test.go b/flickr/flickr_test.go
index <HASH>..<HASH> 100644
--- a/flickr/flickr_test.go
+++ b/flickr/flickr_test.go
@@ -221,3 +221,14 @@ func TestFlickrResponse(t *testing.T) {
Expect(t, resp.ErrorCode(), 0)
Expect(t, resp.ErrorMsg(), "")
}
+
+func TestApiSign(t *testing.T) {
+ client := NewFlickrClient("1234567890", "SECRET")
+ client.Args.Set("foo", "1")
+ client.Args.Set("bar", "2")
+ client.Args.Set("baz", "3")
+
+ client.ApiSign(client.ApiSecret)
+
+ Expect(t, client.Args.Get("api_sig"), "a626bf097044e8b6f7b9214f049f3cc7")
+}
|
added method implementing api signature process
|
masci_flickr
|
train
|
5304503a12cba051df03e2c34ce18e7b5da43471
|
diff --git a/packages/strickland/src/length.js b/packages/strickland/src/length.js
index <HASH>..<HASH> 100644
--- a/packages/strickland/src/length.js
+++ b/packages/strickland/src/length.js
@@ -21,7 +21,7 @@ export default function length(minLengthParam, maxLengthParam, validatorContext)
}
return every([
- minLength(validatorContext),
- maxLength(validatorContext)
- ]);
+ minLength(),
+ maxLength()
+ ], validatorContext);
}
diff --git a/packages/strickland/src/max.js b/packages/strickland/src/max.js
index <HASH>..<HASH> 100644
--- a/packages/strickland/src/max.js
+++ b/packages/strickland/src/max.js
@@ -42,6 +42,7 @@ export default function max(maxParam, validatorContext) {
return {
...validationContext,
+ value,
max: maxValue,
isValid
};
diff --git a/packages/strickland/src/maxLength.js b/packages/strickland/src/maxLength.js
index <HASH>..<HASH> 100644
--- a/packages/strickland/src/maxLength.js
+++ b/packages/strickland/src/maxLength.js
@@ -40,6 +40,8 @@ export default function maxLength(maxLengthParam, validatorContext) {
return {
...validationContext,
+ value,
+ length,
maxLength: maxLengthValue,
isValid
};
diff --git a/packages/strickland/src/min.js b/packages/strickland/src/min.js
index <HASH>..<HASH> 100644
--- a/packages/strickland/src/min.js
+++ b/packages/strickland/src/min.js
@@ -42,8 +42,8 @@ export default function min(minParam, validatorContext) {
return {
...validationContext,
- min: minValue,
value,
+ min: minValue,
isValid
};
}
diff --git a/packages/strickland/src/minLength.js b/packages/strickland/src/minLength.js
index <HASH>..<HASH> 100644
--- a/packages/strickland/src/minLength.js
+++ b/packages/strickland/src/minLength.js
@@ -40,6 +40,8 @@ export default function minLength(minLengthParam, validatorContext) {
return {
...validationContext,
+ value,
+ length,
minLength: minLengthValue,
isValid
};
diff --git a/packages/strickland/src/range.js b/packages/strickland/src/range.js
index <HASH>..<HASH> 100644
--- a/packages/strickland/src/range.js
+++ b/packages/strickland/src/range.js
@@ -2,26 +2,26 @@ import every from './every';
import min from './min';
import max from './max';
-export default function range(minParam, maxParam, validatorProps) {
+export default function range(minParam, maxParam, validatorContext) {
if (typeof minParam === 'object') {
- validatorProps = minParam;
+ validatorContext = minParam;
} else if (typeof maxParam === 'object') {
- validatorProps = {
+ validatorContext = {
min: minParam,
...maxParam
};
} else {
- validatorProps = {
+ validatorContext = {
min: minParam,
max: maxParam,
- ...validatorProps
+ ...validatorContext
};
}
return every([
- min(validatorProps),
- max(validatorProps)
- ]);
+ min(),
+ max()
+ ], validatorContext);
}
|
refactor: clean up validator context handling code
|
jeffhandley_strickland
|
train
|
7a52bba65409584a59aa3f3ac7368b8482c3fd45
|
diff --git a/jupytext/cell_reader.py b/jupytext/cell_reader.py
index <HASH>..<HASH> 100644
--- a/jupytext/cell_reader.py
+++ b/jupytext/cell_reader.py
@@ -58,6 +58,15 @@ def count_lines_to_next_cell(cell_end_marker, next_cell_start,
return 1
+def last_two_lines_blank(source):
+ """Are the two last lines blank, and not the third last one?"""
+ if len(source) < 3:
+ return False
+ return (not _BLANK_LINE.match(source[-3]) and
+ _BLANK_LINE.match(source[-2]) and
+ _BLANK_LINE.match(source[-1]))
+
+
class CellReader():
"""A class that can read notebook cells from their text representation"""
@@ -199,18 +208,11 @@ class CellReader():
end of cell marker, and position of next cell start"""
self.cell_type = 'code'
parser = StringParser('python' if self.ext in ['.py', '.jl'] else 'R')
- empty = True
for i, line in enumerate(lines):
# skip cell header
if self.metadata is not None and i == 0:
continue
- # Read something!
- if not _BLANK_LINE.match(line):
- empty = False
- elif empty:
- continue
-
if parser.is_quoted():
parser.read_line(line)
continue
@@ -228,7 +230,10 @@ class CellReader():
return i, i + 1, True
elif _BLANK_LINE.match(line):
if not next_code_is_indented(lines[i:]):
- return i, i + 1, False
+ if i > 0:
+ return i, i + 1, False
+ if len(lines) == 1 or _BLANK_LINE.match(lines[1]):
+ return 1, 2, False
return len(lines), len(lines), False
@@ -273,10 +278,8 @@ class CellReader():
self.content = source
# Exactly two empty lines at the end?
- if (self.ext == '.py' and explicit_eoc and len(source) > 2 and
- not _BLANK_LINE.match(source[-3]) and
- _BLANK_LINE.match(source[-2]) and
- _BLANK_LINE.match(source[-1])):
+ if (self.ext == '.py' and explicit_eoc and
+ last_two_lines_blank(source)):
self.content = source[:-2]
self.metadata['lines_to_end_of_cell_marker'] = 2
@@ -288,16 +291,16 @@ class CellReader():
del self.metadata['active']
self.cell_type = 'raw'
- # Does the next cell start one/two lines later?
- if (next_cell_start + 2 < len(lines) and
+ # Explicit end of cell marker?
+ if (next_cell_start + 1 < len(lines) and
_BLANK_LINE.match(lines[next_cell_start]) and
- _BLANK_LINE.match(lines[next_cell_start + 1]) and
- not _BLANK_LINE.match(lines[next_cell_start + 2])):
- next_cell_start += 2
- elif (next_cell_start + 1 < len(lines) and
- _BLANK_LINE.match(lines[next_cell_start]) and
- not _BLANK_LINE.match(lines[next_cell_start + 1])):
+ not _BLANK_LINE.match(lines[next_cell_start + 1])):
next_cell_start += 1
+ elif (explicit_eoc and next_cell_start + 2 < len(lines) and
+ _BLANK_LINE.match(lines[next_cell_start]) and
+ _BLANK_LINE.match(lines[next_cell_start + 1]) and
+ not _BLANK_LINE.match(lines[next_cell_start + 2])):
+ next_cell_start += 2
self.lines_to_next_cell = count_lines_to_next_cell(
cell_end_marker,
diff --git a/jupytext/cell_to_text.py b/jupytext/cell_to_text.py
index <HASH>..<HASH> 100644
--- a/jupytext/cell_to_text.py
+++ b/jupytext/cell_to_text.py
@@ -163,7 +163,7 @@ class CellExporter():
return True
if all([line.startswith('#') for line in self.source]):
return True
- if CellReader(self.ext).read(source)[1] != len(source):
+ if CellReader(self.ext).read(source)[1] < len(source):
return True
return False
diff --git a/tests/test_preserve_empty_cells.py b/tests/test_preserve_empty_cells.py
index <HASH>..<HASH> 100644
--- a/tests/test_preserve_empty_cells.py
+++ b/tests/test_preserve_empty_cells.py
@@ -17,7 +17,6 @@ def test_file_with_blank_lines(blank_lines):
compare(py_script, py_script2)
-@pytest.mark.skip(reason='#53')
@pytest.mark.parametrize('blank_cells', range(1, 3))
def test_notebook_with_empty_cells(blank_cells):
notebook = new_notebook(cells=[new_markdown_cell('markdown cell one')] +
diff --git a/tests/test_read_simple_python.py b/tests/test_read_simple_python.py
index <HASH>..<HASH> 100644
--- a/tests/test_read_simple_python.py
+++ b/tests/test_read_simple_python.py
@@ -1,6 +1,5 @@
# -*- coding: utf-8 -*-
-import pytest
import jupytext
from testfixtures import compare
from .python_notebook_sample import f, g
@@ -495,10 +494,9 @@ d = 6
assert len(notebook.cells) >= 6
for cell in notebook.cells:
lines = cell.source.splitlines()
- if len(lines) == 1:
- continue
- assert lines[0]
- assert lines[-1]
+ if len(lines) != 1:
+ assert lines[0]
+ assert lines[-1]
script2 = jupytext.writes(notebook, ext='.py')
|
Empty code cells are preserved #<I>
|
mwouts_jupytext
|
train
|
372e52b8cf89ede9f8774210aac793a13ae2d352
|
diff --git a/code/libraries/koowa/components/com_koowa/template/helper/behavior.php b/code/libraries/koowa/components/com_koowa/template/helper/behavior.php
index <HASH>..<HASH> 100644
--- a/code/libraries/koowa/components/com_koowa/template/helper/behavior.php
+++ b/code/libraries/koowa/components/com_koowa/template/helper/behavior.php
@@ -549,7 +549,8 @@ class ComKoowaTemplateHelperBehavior extends KTemplateHelperAbstract
'debug' => JFactory::getApplication()->getCfg('debug'),
'element' => '.select2-listbox',
'options' => array(
- 'width' => 'resolve'
+ 'width' => 'resolve',
+ 'dropdownCssClass' => 'koowa'
)
));
@@ -600,6 +601,7 @@ class ComKoowaTemplateHelperBehavior extends KTemplateHelperAbstract
$config->append(array(
'element' => null,
'options' => array(
+ 'dropdownCssClass' => 'koowa',
'validate' => false, //Toggle if the forms validation helper is loaded
'queryVarName' => 'search',
'width' => 'resolve',
|
Put back the koowa class to the select2 dropdown
|
timble_kodekit
|
train
|
9384abafcc18ea7fbfe9a838aebc1dbc1933211f
|
diff --git a/lib/index.js b/lib/index.js
index <HASH>..<HASH> 100644
--- a/lib/index.js
+++ b/lib/index.js
@@ -245,8 +245,8 @@ module.exports = function(Sequelize) {
} else {
// make through table
var fields = {};
- fields[foreignKey1] = {type: definitions[modelName1].fields[key1].type, allowNull: false, _autoGenerated: true};
- fields[foreignKey2] = {type: definitions[modelName2].fields[key2].type, allowNull: false, _autoGenerated: true};
+ fields[foreignKey1] = {type: definitions[modelName1].fields[key1].type, allowNull: false, reference: null, _autoGenerated: true};
+ fields[foreignKey2] = {type: definitions[modelName2].fields[key2].type, allowNull: false, reference: null, _autoGenerated: true};
if (options.labels) {
fields[foreignKey1].label = modelName1;
|
Do not auto-reference through table keys
|
overlookmotel_sequelize-definer
|
train
|
f5dd6c888a5e5011d2dac074373984604506ab12
|
diff --git a/lib/puppet/util/rdoc/generators/puppet_generator.rb b/lib/puppet/util/rdoc/generators/puppet_generator.rb
index <HASH>..<HASH> 100644
--- a/lib/puppet/util/rdoc/generators/puppet_generator.rb
+++ b/lib/puppet/util/rdoc/generators/puppet_generator.rb
@@ -1,5 +1,7 @@
require 'rdoc/generators/html_generator'
require 'puppet/util/rdoc/code_objects'
+require 'digest/md5'
+
module Generators
# This module holds all the classes needed to generate the HTML documentation
@@ -335,7 +337,7 @@ module Generators
resources.each do |r|
res << {
"name" => CGI.escapeHTML(r.name),
- "aref" => "#{path_prefix}\##{r.aref}"
+ "aref" => CGI.escape(path_prefix)+"\#"+CGI.escape(r.aref)
}
end
res
@@ -414,7 +416,7 @@ module Generators
if path['<<']
path.gsub!(/<<\s*(\w*)/) { "from-#$1" }
end
- File.join(prefix, path.split("::")) + ".html"
+ File.join(prefix, path.split("::").collect { |p| Digest::MD5.hexdigest(p) }) + ".html"
end
def parent_name
@@ -508,7 +510,7 @@ module Generators
h_name = CGI.escapeHTML(name)
@values["classmod"] = "Node"
- @values["title"] = "#{@values['classmod']}: #{h_name}"
+ @values["title"] = CGI.escapeHTML("#{@values['classmod']}: #{h_name}")
c = @context
c = c.parent while c and !c.diagram
|
Fix #<I> - puppetdoc doesn't cope with regex node
The problem is that regex node contains '/' which is a directory
separator on unix.
Since puppetdoc writes a file for each node this was creating empty
directories and documentation for such node couldn't be stored.
This patch removes the slashes in the node names.
|
puppetlabs_puppet
|
train
|
a94b5785ebe1e82040611a2d7f608ff2f17be29f
|
diff --git a/src/Codeception/Module/REST.php b/src/Codeception/Module/REST.php
index <HASH>..<HASH> 100644
--- a/src/Codeception/Module/REST.php
+++ b/src/Codeception/Module/REST.php
@@ -17,6 +17,7 @@ use Codeception\Exception\ModuleConfig as ModuleConfigException;
* ## Configuration
*
* * url *optional* - the url of api
+ * * timeout *optional* - the maximum number of seconds to allow cURL functions to execute
*
* ## Public Properties
*
@@ -29,8 +30,9 @@ use Codeception\Exception\ModuleConfig as ModuleConfigException;
class REST extends \Codeception\Module
{
protected $config = array(
- 'url' => '',
- 'xdebug_remote' => false,
+ 'url' => '',
+ 'timeout' => 30,
+ 'xdebug_remote' => false,
'xdebug_codecoverage' => false,
);
@@ -73,6 +75,8 @@ class REST extends \Codeception\Module
$this->client->setServerParameters(array());
+ $timeout = $this->config['timeout'];
+
if ($this->config['xdebug_remote']
&& function_exists('xdebug_is_enabled')
&& xdebug_is_enabled()
@@ -81,12 +85,15 @@ class REST extends \Codeception\Module
$cookie = new Cookie('XDEBUG_SESSION', $this->config['xdebug_remote'], null, '/');
$this->client->getCookieJar()->set($cookie);
- $clientConfig = $this->client->getClient()->getConfig();
- $curlOptions = $clientConfig->get('curl.options');
- $curlOptions[CURLOPT_TIMEOUT] = 0;
- $clientConfig->set('curl.options', $curlOptions);
+ // timeout is disabled, so we can debug gently :)
+ $timeout = 0;
}
+ $clientConfig = $this->client->getClient()->getConfig();
+ $curlOptions = $clientConfig->get('curl.options');
+ $curlOptions[CURLOPT_TIMEOUT] = $timeout;
+ $clientConfig->set('curl.options', $curlOptions);
+
if ($this->config['xdebug_codecoverage']) {
$this->headers['X-Codeception-CodeCoverage'] = $test->toString();
}
|
ability to set timeout for the cURL
|
Codeception_Codeception
|
train
|
bc2294d7f18977028b349058a9ac6d88313e5e2e
|
diff --git a/spacy/cli/train.py b/spacy/cli/train.py
index <HASH>..<HASH> 100644
--- a/spacy/cli/train.py
+++ b/spacy/cli/train.py
@@ -7,6 +7,7 @@ import cytoolz
from pathlib import Path
import dill
import tqdm
+from thinc.neural.optimizers import linear_decay
from ..tokens.doc import Doc
from ..scorer import Scorer
@@ -40,24 +41,35 @@ def train(lang_id, output_dir, train_data, dev_data, n_iter, n_sents,
corpus = GoldCorpus(train_path, dev_path)
dropout = util.env_opt('dropout', 0.0)
+ dropout_decay = util.env_opt('dropout_decay', 0.0)
optimizer = nlp.begin_training(lambda: corpus.train_tuples, use_gpu=use_gpu)
n_train_docs = corpus.count_train()
+ batch_size = float(util.env_opt('min_batch_size', 4))
+ max_batch_size = util.env_opt('max_batch_size', 64)
+ batch_accel = util.env_opt('batch_accel', 1.001)
print("Itn.\tDep. Loss\tUAS\tNER F.\tTag %\tToken %")
for i in range(n_iter):
with tqdm.tqdm(total=n_train_docs) as pbar:
train_docs = corpus.train_docs(nlp, shuffle=i, projectivize=True)
- for batch in cytoolz.partition_all(20, train_docs):
+ idx = 0
+ while idx < n_train_docs:
+ batch = list(cytoolz.take(int(batch_size), train_docs))
+ if not batch:
+ break
docs, golds = zip(*batch)
- docs = list(docs)
- golds = list(golds)
nlp.update(docs, golds, drop=dropout, sgd=optimizer)
pbar.update(len(docs))
+ idx += len(docs)
+ batch_size *= batch_accel
+ batch_size = min(int(batch_size), max_batch_size)
+ dropout = linear_decay(dropout, dropout_decay, i*n_train_docs+idx)
with nlp.use_params(optimizer.averages):
scorer = nlp.evaluate(corpus.dev_docs(nlp))
print_progress(i, {}, scorer.scores)
with (output_path / 'model.bin').open('wb') as file_:
- dill.dump(nlp, file_, -1)
+ with nlp.use_params(optimizer.averages):
+ dill.dump(nlp, file_, -1)
def _render_parses(i, to_render):
|
Add support for fiddly hyper-parameters to train func
|
explosion_spaCy
|
train
|
1d43a29904162d89b85ae0bc4b7f663cf2cd0456
|
diff --git a/lib/roo/excelx/shared_strings.rb b/lib/roo/excelx/shared_strings.rb
index <HASH>..<HASH> 100755
--- a/lib/roo/excelx/shared_strings.rb
+++ b/lib/roo/excelx/shared_strings.rb
@@ -109,17 +109,23 @@ module Roo
elem.children.each do |rPr_elem|
case rPr_elem.name
when 'b'
+ # set formatting for Bold to true
xml_elems[:b] = true
when 'i'
+ # set formatting for Italics to true
xml_elems[:i] = true
when 'u'
+ # set formatting for Underline to true
xml_elems[:u] = true
when 'vertAlign'
+ # See if the Vertical Alignment is subscript or superscript
case rPr_elem.xpath('@val').first.value
when 'subscript'
+ # set formatting for Subscript to true and Superscript to false ... Can't have both
xml_elems[:sub] = true
xml_elems[:sup] = false
when 'superscript'
+ # set formatting for Superscript to true and Subscript to false ... Can't have both
xml_elems[:sup] = true
xml_elems[:sub] = false
end
|
Added initial support to support HTML formatting.
|
roo-rb_roo
|
train
|
d13b57ca44694919b2526df0a2f26ffb81c50fdd
|
diff --git a/packages/bonde-admin-canary/public/index.html b/packages/bonde-admin-canary/public/index.html
index <HASH>..<HASH> 100644
--- a/packages/bonde-admin-canary/public/index.html
+++ b/packages/bonde-admin-canary/public/index.html
@@ -21,7 +21,7 @@
-->
<title>BONDE</title>
</head>
- <body>
+ <body style='background:#eeeeee;'>
<noscript>
You need to enable JavaScript to run this app.
</noscript>
diff --git a/packages/bonde-admin-canary/src/components/PageLogged/Page.js b/packages/bonde-admin-canary/src/components/PageLogged/Page.js
index <HASH>..<HASH> 100644
--- a/packages/bonde-admin-canary/src/components/PageLogged/Page.js
+++ b/packages/bonde-admin-canary/src/components/PageLogged/Page.js
@@ -9,6 +9,7 @@ const Page = ({
renderActionButtons,
renderTabs,
wrapperHeaderComponent: WrapperHeader,
+ bgColor,
...pageProps
}) => {
const headerNode = (
diff --git a/packages/bonde-styleguide/src/layout/Footer/Footer.js b/packages/bonde-styleguide/src/layout/Footer/Footer.js
index <HASH>..<HASH> 100644
--- a/packages/bonde-styleguide/src/layout/Footer/Footer.js
+++ b/packages/bonde-styleguide/src/layout/Footer/Footer.js
@@ -30,8 +30,7 @@ const Footer = styled(({ children, className, btnHelpLabel, btnHelpClick }) => (
</FooterContent>
</div>
))`{
- position: relative;
- margin-top: 30px;
+ position: absolute;
display: flex;
align-items: center;
height: 94px;
diff --git a/packages/bonde-styleguide/src/layout/Page/Page.js b/packages/bonde-styleguide/src/layout/Page/Page.js
index <HASH>..<HASH> 100644
--- a/packages/bonde-styleguide/src/layout/Page/Page.js
+++ b/packages/bonde-styleguide/src/layout/Page/Page.js
@@ -3,41 +3,18 @@ import PropTypes from 'prop-types'
import styled from 'styled-components'
const PageContainer = styled.div`{
- width: 100%;
- position: relative;
padding-top: ${props => props.top ? `calc(${props.top}px + 32px)` : '32px'};
- padding-left: 155px;
- padding-right: 155px;
- background-color: ${props => props.bgColor || '#EEEEEE'};
-
- margin: -100px 0 -75px;
- min-height: 100%;
- height: auto !important;
- height: 100%;
-
- &:before {
- content: "";
- display: block;
- height: 100px;
- width: 100%;
- }
-
- &:after {
- content: "";
- display: block;
- height: 75px;
- width: 100%;
- }
-}`
+ padding-bottom: 32px;
+ width: 80%;
+ margin: 0 auto;
+`
const PageContent = styled.div`{
- width: 100%;
- position: relative;
display: flex;
}`
-const Page = ({ children, menuComponent: MenuComponent, bgColor, top }) => (
- <PageContainer bgColor={bgColor} top={top}>
+const Page = ({ children, menuComponent: MenuComponent, top }) => (
+ <PageContainer top={top}>
{MenuComponent && <MenuComponent />}
<PageContent>
{children}
@@ -51,9 +28,7 @@ Page.propTypes = {
/** The content of the page. */
children: oneOfType([node, func]),
/** The menu component. */
- menuComponent: oneOfType([node, func]),
- /** The background color of the page. */
- bgColor: string
+ menuComponent: oneOfType([node, func])
}
Page.displayName = 'Page'
|
chore(admin-canary): change page layout and add background with fixed color
|
nossas_bonde-client
|
train
|
e76fffa5387eefdb60f3eec6d3b241bc74c2ac1e
|
diff --git a/src/lib/KevinGH/Box/Console/Command/Info.php b/src/lib/KevinGH/Box/Console/Command/Info.php
index <HASH>..<HASH> 100644
--- a/src/lib/KevinGH/Box/Console/Command/Info.php
+++ b/src/lib/KevinGH/Box/Console/Command/Info.php
@@ -65,7 +65,7 @@
catch (UnexpectedValueException $exception)
{
- $output->writeln("<error>$phar: is corrupt</error>\n");
+ $output->writeln(" - <error>Is corrupt.</error>\n");
continue;
}
diff --git a/src/tests/KevinGH/Box/Console/Command/InfoTest.php b/src/tests/KevinGH/Box/Console/Command/InfoTest.php
index <HASH>..<HASH> 100644
--- a/src/tests/KevinGH/Box/Console/Command/InfoTest.php
+++ b/src/tests/KevinGH/Box/Console/Command/InfoTest.php
@@ -61,4 +61,19 @@
$this->assertEquals($expected, $this->tester->getDisplay());
}
+
+ public function testExecuteWithCorruptPhars()
+ {
+ $temp = $this->file($this->resource('test.phar'));
+
+ $this->tester->execute(array(
+ 'command' => self::COMMAND,
+ 'phar' => array($temp)
+ ));
+
+ $this->assertEquals(
+ "$temp:\n - Is corrupt.\n\n",
+ $this->tester->getDisplay()
+ );
+ }
}
\ No newline at end of file
|
Slightly better Info command testing.
|
box-project_box2
|
train
|
48554b8da0580bb6766803081b33ac2e88973711
|
diff --git a/integrationtest/src/test/java/org/chorusbdd/chorus/selftest/jmxexecutionlistener/TestJmxExecutionListener.java b/integrationtest/src/test/java/org/chorusbdd/chorus/selftest/jmxexecutionlistener/TestJmxExecutionListener.java
index <HASH>..<HASH> 100644
--- a/integrationtest/src/test/java/org/chorusbdd/chorus/selftest/jmxexecutionlistener/TestJmxExecutionListener.java
+++ b/integrationtest/src/test/java/org/chorusbdd/chorus/selftest/jmxexecutionlistener/TestJmxExecutionListener.java
@@ -85,17 +85,18 @@ public class TestJmxExecutionListener extends AbstractInterpreterTest {
String expectedOut = readToString(new FileInputStream(expectedOutFile));
String actualOut = readToString(new FileInputStream(actualOutFile));
- Thread.sleep(500);
+ if ( actualOut.contains(expectedOut))
+
//help with debugging failure in Travis
- if ( ! expectedOut.equals(actualOut)) {
+ if ( ! actualOut.endsWith(expectedOut)) {
System.out.println("Expected -->>>>");
System.out.println(expectedOut);
System.out.println("Actual -->>>>");
System.out.println(actualOut);
}
-
- assertEquals("The remote JMX listener produced the expected output", expectedOut, actualOut);
+ //On Travis runs / Open JDK we are getting an extra 'Picked up _JAVA_OPTIONS:' at the start of actual
+ assertTrue("The remote JMX listener produced the expected output", actualOut.endsWith(expectedOut));
}
private void startJmxExecutionListenerProcess(ForkedRunner f, PrintStream outStream) throws Exception {
@@ -106,7 +107,7 @@ public class TestJmxExecutionListener extends AbstractInterpreterTest {
sysPropsForTest.put("com.sun.management.jmxremote.ssl", "false");
f.runForked(sysPropsForTest, "org.chorusbdd.chorus.selftest.jmxexecutionlistener.ExecutionListenerMain", outStream, 0);
- Thread.sleep(3500); //let the forked listener start up and create its MBeans, no easy way to poll for this
+ Thread.sleep(3000); //let the forked listener start up and create its MBeans, no easy way to poll for this
}
protected void doUpdateTestProperties(DefaultTestProperties sysProps) {
|
Fix TestJmxExecutionListener for Travis builds
|
Chorus-bdd_Chorus
|
train
|
76529875a2b519a2c22d8276689faef3db17e9a9
|
diff --git a/lib/pem/manager.rb b/lib/pem/manager.rb
index <HASH>..<HASH> 100644
--- a/lib/pem/manager.rb
+++ b/lib/pem/manager.rb
@@ -6,6 +6,7 @@ module PEM
class Manager
class << self
def start
+ FastlaneCore::PrintTable.print_values(config: PEM.config, hide_keys: [], title: "Summary")
login
existing_certificate = certificate.all.detect do |c|
|
Added table summary when running PEM
|
fastlane_fastlane
|
train
|
75d3279d559af764a10628686aabfc840d8eb38d
|
diff --git a/pyqode/core/api/code_edit.py b/pyqode/core/api/code_edit.py
index <HASH>..<HASH> 100644
--- a/pyqode/core/api/code_edit.py
+++ b/pyqode/core/api/code_edit.py
@@ -687,10 +687,9 @@ class CodeEdit(QtWidgets.QPlainTextEdit):
implement onStyleChanged and trigger an update.
"""
self.zoom_level -= increment
+ # make sure font size remains > 0
if self.font_size + self.zoom_level <= 0:
self.zoom_level = -self._font_size + 1
- # if abs(self.zoom_level) >= self._font_size:
- # self.zoom_level = -self._font_size + 1
TextHelper(self).mark_whole_doc_dirty()
self._reset_stylesheet()
|
pyQode/pyQode#9 cleanup + comment
|
pyQode_pyqode.core
|
train
|
275c5b4ebfc429b6925ad163fb75f9402fb6a964
|
diff --git a/src/Controllers/Backend.php b/src/Controllers/Backend.php
index <HASH>..<HASH> 100644
--- a/src/Controllers/Backend.php
+++ b/src/Controllers/Backend.php
@@ -1318,16 +1318,16 @@ class Backend implements ControllerProviderInterface
$app['session']->getFlashBag()->set('error', Trans::__('page.edit-users.message.saving-user', array('%user%' => $user['displayname'])));
}
- // If the current user changed their own login name, the session is effectively
- // invalidated. If so, we must redirect to the login page with a flash message.
$currentuser = $app['users']->getCurrentUser();
- if (($user['id'] == $currentuser['id']) && ($user['username'] != $currentuser['username'])) {
- $app['session']->getFlashBag()->set('error', Trans::__('page.edit-users.message.change-self'));
- return Lib::redirect('login');
- } else if ($firstuser) {
+ if ($firstuser) {
// To the dashboard, where 'login' will be triggered..
return Lib::redirect('dashboard');
+ } else if (($user['id'] == $currentuser['id']) && ($user['username'] != $currentuser['username'])) {
+ // If the current user changed their own login name, the session is effectively
+ // invalidated. If so, we must redirect to the login page with a flash message.
+ $app['session']->getFlashBag()->set('error', Trans::__('page.edit-users.message.change-self'));
+ return Lib::redirect('login');
} else {
// Return to the 'Edit users' screen.
return Lib::redirect('users');
|
Fix for #<I>. Remove changed self message when creating first user.
|
bolt_bolt
|
train
|
c7319f5fa0de8e51a2dac0963292370f7adbfdab
|
diff --git a/activesupport/lib/active_support/multibyte/chars.rb b/activesupport/lib/active_support/multibyte/chars.rb
index <HASH>..<HASH> 100644
--- a/activesupport/lib/active_support/multibyte/chars.rb
+++ b/activesupport/lib/active_support/multibyte/chars.rb
@@ -385,7 +385,7 @@ module ActiveSupport #:nodoc:
# Convert characters in the string to uppercase.
#
# Example:
- # 'Laurent, òu sont les tests?'.mb_chars.upcase.to_s #=> "LAURENT, ÒU SONT LES TESTS?"
+ # 'Laurent, où sont les tests ?'.mb_chars.upcase.to_s #=> "LAURENT, OÙ SONT LES TESTS ?"
def upcase
apply_mapping :uppercase_mapping
end
|
Fixed french sentence so it actually makes sense.
|
rails_rails
|
train
|
1def65b1f129457e2be1a0db2fb33fd75a5f570b
|
diff --git a/cmd/argo/commands/cron/get_test.go b/cmd/argo/commands/cron/get_test.go
index <HASH>..<HASH> 100644
--- a/cmd/argo/commands/cron/get_test.go
+++ b/cmd/argo/commands/cron/get_test.go
@@ -70,7 +70,7 @@ func TestNextRuntime(t *testing.T) {
if assert.NoError(t, err) {
next, err := cronWf.GetNextRuntime()
if assert.NoError(t, err) {
- assert.Less(t, next.Unix(), time.Now().Add(1*time.Minute).Unix())
+ assert.LessOrEqual(t, next.Unix(), time.Now().Add(1*time.Minute).Unix())
assert.Greater(t, next.Unix(), time.Now().Unix())
}
}
diff --git a/workflow/controller/operator.go b/workflow/controller/operator.go
index <HASH>..<HASH> 100644
--- a/workflow/controller/operator.go
+++ b/workflow/controller/operator.go
@@ -195,6 +195,8 @@ func (woc *wfOperationCtx) operate() {
woc.preExecutionNodePhases[node.ID] = node.Phase
}
+ woc.setGlobalParameters(execArgs)
+
// Perform one-time workflow validation
if woc.wf.Status.Phase == "" {
woc.markWorkflowRunning()
@@ -269,8 +271,6 @@ func (woc *wfOperationCtx) operate() {
return
}
- woc.setGlobalParameters(execArgs)
-
if woc.execWf.Spec.ArtifactRepositoryRef != nil {
repo, err := woc.getArtifactRepositoryByRef(woc.execWf.Spec.ArtifactRepositoryRef)
if err == nil {
diff --git a/workflow/controller/operator_metrics_test.go b/workflow/controller/operator_metrics_test.go
index <HASH>..<HASH> 100644
--- a/workflow/controller/operator_metrics_test.go
+++ b/workflow/controller/operator_metrics_test.go
@@ -429,3 +429,56 @@ func TestDAGTmplMetrics(t *testing.T) {
assert.NoError(t, err)
assert.Contains(t, metricCounterString, `counter:<value:1 > `)
}
+
+var testRealtimeWorkflowMetricWithGlobalParameters = `
+apiVersion: argoproj.io/v1alpha1
+kind: Workflow
+metadata:
+ name: test-foobar
+ labels:
+ testLabel: foobar
+spec:
+ arguments:
+ parameters:
+ - name: testParam
+ value: foo
+ entrypoint: whalesay
+ metrics:
+ prometheus:
+ - name: intuit_data_persistplat_dppselfservice_workflow_test_duration
+ help: Duration of workflow
+ labels:
+ - key: workflowName
+ value: "{{workflow.name}}"
+ - key: label
+ value: "{{workflow.labels.testLabel}}"
+ gauge:
+ realtime: true
+ value: "{{workflow.duration}}"
+ templates:
+ - name: whalesay
+ resubmitPendingPods: true
+ container:
+ image: docker/whalesay
+ command: [ cowsay ]
+ args: [ "hello world" ]
+`
+
+func TestRealtimeWorkflowMetricWithGlobalParameters(t *testing.T) {
+ cancel, controller := newController()
+ defer cancel()
+ wfcset := controller.wfclientset.ArgoprojV1alpha1().Workflows("")
+ wf := unmarshalWF(testRealtimeWorkflowMetricWithGlobalParameters)
+ _, err := wfcset.Create(wf)
+ assert.NoError(t, err)
+ woc := newWorkflowOperationCtx(wf, controller)
+
+ woc.operate()
+
+ metricErrorDesc := wf.Spec.Metrics.Prometheus[0].GetDesc()
+ assert.NotNil(t, controller.metrics.GetCustomMetric(metricErrorDesc))
+ metricErrorCounter := controller.metrics.GetCustomMetric(metricErrorDesc)
+ metricErrorCounterString, err := getMetricStringValue(metricErrorCounter)
+ assert.NoError(t, err)
+ assert.Contains(t, metricErrorCounterString, `label:<name:"workflowName" value:"test-foobar" > gauge:<value:`)
+}
diff --git a/workflow/controller/operator_test.go b/workflow/controller/operator_test.go
index <HASH>..<HASH> 100644
--- a/workflow/controller/operator_test.go
+++ b/workflow/controller/operator_test.go
@@ -129,12 +129,15 @@ func TestGlobalParams(t *testing.T) {
assert.NotContains(t, woc.globalParams["workflow.creationTimestamp"], "UTC")
}
assert.Contains(t, woc.globalParams, "workflow.duration")
- assert.Contains(t, woc.globalParams, "workflow.labels.workflows.argoproj.io/phase")
assert.Contains(t, woc.globalParams, "workflow.name")
assert.Contains(t, woc.globalParams, "workflow.namespace")
assert.Contains(t, woc.globalParams, "workflow.parameters")
assert.Contains(t, woc.globalParams, "workflow.serviceAccountName")
assert.Contains(t, woc.globalParams, "workflow.uid")
+
+ // Ensure that the phase label is included after the first operation
+ woc.operate()
+ assert.Contains(t, woc.globalParams, "workflow.labels.workflows.argoproj.io/phase")
}
// TestSidecarWithVolume verifies ia sidecar can have a volumeMount reference to both existing or volumeClaimTemplate volumes
|
fix: Create global scope before workflow-level realtime metrics (#<I>)
|
argoproj_argo
|
train
|
05b1ffd57227985e5043ee37b59443fd214d6dbd
|
diff --git a/src/elements/Segment/Segment.js b/src/elements/Segment/Segment.js
index <HASH>..<HASH> 100644
--- a/src/elements/Segment/Segment.js
+++ b/src/elements/Segment/Segment.js
@@ -87,7 +87,7 @@ Segment.propTypes = {
/** Attach segment to other content, like a header. */
attached: PropTypes.oneOfType([
PropTypes.bool,
- PropTypes.oneOf('top', 'bottom'),
+ PropTypes.oneOf(['top', 'bottom']),
]),
/** A basic segment has no special formatting. */
diff --git a/src/modules/Modal/Modal.js b/src/modules/Modal/Modal.js
index <HASH>..<HASH> 100644
--- a/src/modules/Modal/Modal.js
+++ b/src/modules/Modal/Modal.js
@@ -236,7 +236,7 @@ class Modal extends Component {
className,
)
const unhandled = getUnhandledProps(Modal, this.props)
- const portalPropNames = _.keys(Portal.propTypes)
+ const portalPropNames = Portal.handledProps
const rest = _.omit(unhandled, portalPropNames)
const portalProps = _.pick(unhandled, portalPropNames)
diff --git a/src/modules/Popup/Popup.js b/src/modules/Popup/Popup.js
index <HASH>..<HASH> 100644
--- a/src/modules/Popup/Popup.js
+++ b/src/modules/Popup/Popup.js
@@ -340,7 +340,7 @@ export default class Popup extends Component {
if (closed) return trigger
const unhandled = getUnhandledProps(Popup, this.props)
- const portalPropNames = _.keys(Portal.propTypes)
+ const portalPropNames = Portal.handledProps
const rest = _.omit(unhandled, portalPropNames)
const portalProps = _.pick(unhandled, portalPropNames)
|
fix(Modal|Popup): fix propTypes usage (#<I>)
|
Semantic-Org_Semantic-UI-React
|
train
|
dfb7633453104cf376378528c31e4769fcec66d5
|
diff --git a/core/src/main/java/hudson/util/ArgumentListBuilder.java b/core/src/main/java/hudson/util/ArgumentListBuilder.java
index <HASH>..<HASH> 100644
--- a/core/src/main/java/hudson/util/ArgumentListBuilder.java
+++ b/core/src/main/java/hudson/util/ArgumentListBuilder.java
@@ -205,7 +205,7 @@ public class ArgumentListBuilder implements Serializable {
* is needed since the command is now passed as a string to the CMD.EXE shell.
* This is done as follows:
* Wrap arguments in double quotes if they contain any of:
- * space *?;^&<>|" or % followed by a letter.
+ * space *?,;^&<>|" or % followed by a letter.
* <br/> These characters are also prepended with a ^ character: ^&<>|
* <br/> A " is prepended with another " character. Note: Windows has issues
* escaping some combinations of quotes and spaces. Quotes should be avoided.
@@ -223,7 +223,7 @@ public class ArgumentListBuilder implements Serializable {
quoted = percent = false;
for (int i = 0; i < arg.length(); i++) {
char c = arg.charAt(i);
- if (!quoted && (c == ' ' || c == '*' || c == '?' || c == ';')) {
+ if (!quoted && (c == ' ' || c == '*' || c == '?' || c == ',' || c == ';')) {
quoted = startQuoting(quotedArgs, arg, i);
}
else if (c == '^' || c == '&' || c == '<' || c == '>' || c == '|') {
diff --git a/core/src/test/java/hudson/util/ArgumentListBuilderTest.java b/core/src/test/java/hudson/util/ArgumentListBuilderTest.java
index <HASH>..<HASH> 100644
--- a/core/src/test/java/hudson/util/ArgumentListBuilderTest.java
+++ b/core/src/test/java/hudson/util/ArgumentListBuilderTest.java
@@ -110,13 +110,14 @@ public class ArgumentListBuilderTest extends Assert {
ArgumentListBuilder builder = new ArgumentListBuilder(
"ant.bat", "-Dfoo1=abc", // nothing special, no quotes
"-Dfoo2=foo bar", "-Dfoo3=/u*r", "-Dfoo4=/us?", // add quotes, no other escaping
+ "-Dfoo10=bar,baz",
"-Dfoo5=foo;bar^baz", "-Dfoo6=<xml>&here;</xml>", // add quotes and ^ escaping
"-Dfoo7=foo|bar\"baz", // add quotes, ^| for | and "" for "
"-Dfoo8=% %QED% %comspec% %-%(%.%", // add quotes, and extra quotes for %Q and %c
"-Dfoo9=%'''%%@%"); // no quotes as none of the % are followed by a letter
assertArrayEquals(new String[] { "cmd.exe", "/C",
"\"ant.bat -Dfoo1=abc \"-Dfoo2=foo bar\""
- + " \"-Dfoo3=/u*r\" \"-Dfoo4=/us?\" \"-Dfoo5=foo;bar^^baz\""
+ + " \"-Dfoo3=/u*r\" \"-Dfoo4=/us?\" \"-Dfoo10=bar,baz\" \"-Dfoo5=foo;bar^^baz\""
+ " \"-Dfoo6=^<xml^>^&here;^</xml^>\" \"-Dfoo7=foo^|bar\"\"baz\""
+ " \"-Dfoo8=% %\"Q\"ED% %\"c\"omspec% %-%(%.%\""
+ " -Dfoo9=%'''%%@% && exit %%ERRORLEVEL%%\"" },
|
[FIXED HUDSON-<I>] add comma to list of characters that need escaping on windows
git-svn-id: <URL>
|
jenkinsci_jenkins
|
train
|
d97fbea2ad4c3535efc5d1743b52393818f04a39
|
diff --git a/dashbuilder-client/dashbuilder-displayer-editor/src/main/java/org/dashbuilder/client/editor/DisplayerPerspectiveEditorComponent.java b/dashbuilder-client/dashbuilder-displayer-editor/src/main/java/org/dashbuilder/client/editor/DisplayerPerspectiveEditorComponent.java
index <HASH>..<HASH> 100644
--- a/dashbuilder-client/dashbuilder-displayer-editor/src/main/java/org/dashbuilder/client/editor/DisplayerPerspectiveEditorComponent.java
+++ b/dashbuilder-client/dashbuilder-displayer-editor/src/main/java/org/dashbuilder/client/editor/DisplayerPerspectiveEditorComponent.java
@@ -20,10 +20,12 @@ import java.util.Map;
import javax.annotation.PostConstruct;
import javax.enterprise.context.Dependent;
+import com.github.gwtbootstrap.client.ui.Modal;
import com.google.gwt.user.client.ui.IsWidget;
import org.dashbuilder.displayer.DisplayerSettings;
import org.dashbuilder.displayer.client.json.DisplayerSettingsJSONMarshaller;
import org.dashbuilder.displayer.client.widgets.DisplayerEditor;
+import org.dashbuilder.displayer.client.widgets.DisplayerView;
import org.kie.uberfire.perspective.editor.client.api.ExternalPerspectiveEditorComponent;
@Dependent
@@ -51,7 +53,7 @@ public class DisplayerPerspectiveEditorComponent implements ExternalPerspectiveE
@Override
public Map<String,String> getParametersMap() {
- Map<String,String> params = new HashMap<String, String>();
+ Map<String,String> params = new HashMap<String,String>();
params.put("json", jsonMarshaller.toJsonString(editor.getDisplayerSettings()));
return params;
}
@@ -62,7 +64,15 @@ public class DisplayerPerspectiveEditorComponent implements ExternalPerspectiveE
}
@Override
- public IsWidget getPreview( Map<String, String> parameters ) {
- return null;
+ public IsWidget getPreview(Map<String,String> parameters) {
+ String json = parameters.get("json");
+ DisplayerSettings settings = jsonMarshaller.fromJsonString(json);
+ return new DisplayerView(settings).draw();
+ }
+
+ @Override
+ public void modalSettings(Modal popup) {
+ popup.setWidth(900);
+ popup.setMaxHeigth("600px");
}
}
|
Perspective Editor: displayer component preferred size
|
dashbuilder_dashbuilder
|
train
|
8f35e9e0f9bcd10723ee272f348cf2a8db4ef3fa
|
diff --git a/pathio.go b/pathio.go
index <HASH>..<HASH> 100644
--- a/pathio.go
+++ b/pathio.go
@@ -22,8 +22,10 @@ import (
"github.com/aws/aws-sdk-go/service/s3"
)
-const defaultLocation = "us-east-1"
-const aesAlgo = "AES256"
+const (
+ defaultLocation = "us-east-1"
+ aesAlgo = "AES256"
+)
// generate a mock for Pathio
//go:generate $GOPATH/bin/mockgen -source=$GOFILE -destination=gen_mock_s3handler.go -package=pathio
@@ -40,19 +42,29 @@ type Pathio interface {
// Client is the pathio client used to access the local file system and S3.
// To configure options on the client, create a new Client and call its methods
// directly.
-// `&Client{
-// disableS3Encryption: true, // disables encryption
-// Region: "us-east-1", // hardcodes the s3 region, instead of looking it up
-// }.Write(...)`
+// &Client{
+// disableS3Encryption: true, // disables encryption
+// Region: "us-east-1", // hardcodes the s3 region, instead of looking it up
+// }.Write(...)
type Client struct {
disableS3Encryption bool
Region string
+ providedConfig *aws.Config
}
// DefaultClient is the default pathio client called by the Reader, Writer, and
// WriteReader methods. It has S3 encryption enabled.
var DefaultClient Pathio = &Client{}
+// NewClient creates a new client that utilizes the provided AWS config. This can
+// be leveraged to enforce more limited permissions.
+func NewClient(cfg *aws.Config) *Client {
+ return &Client{
+ providedConfig: cfg,
+ Region: "us-west-1",
+ }
+}
+
// Reader calls DefaultClient's Reader method.
func Reader(path string) (rc io.ReadCloser, err error) {
return DefaultClient.Reader(path)
@@ -92,7 +104,7 @@ type s3Connection struct {
// or an S3 path. It is the caller's responsibility to close rc.
func (c *Client) Reader(path string) (rc io.ReadCloser, err error) {
if strings.HasPrefix(path, "s3://") {
- s3Conn, err := s3ConnectionInformation(path, c.Region)
+ s3Conn, err := c.s3ConnectionInformation(path, c.Region)
if err != nil {
return nil, err
}
@@ -117,7 +129,7 @@ func (c *Client) WriteReader(path string, input io.ReadSeeker) error {
}
if strings.HasPrefix(path, "s3://") {
- s3Conn, err := s3ConnectionInformation(path, c.Region)
+ s3Conn, err := c.s3ConnectionInformation(path, c.Region)
if err != nil {
return err
}
@@ -129,7 +141,7 @@ func (c *Client) WriteReader(path string, input io.ReadSeeker) error {
// ListFiles lists all the files/directories in the directory. It does not recurse
func (c *Client) ListFiles(path string) ([]string, error) {
if strings.HasPrefix(path, "s3://") {
- s3Conn, err := s3ConnectionInformation(path, c.Region)
+ s3Conn, err := c.s3ConnectionInformation(path, c.Region)
if err != nil {
return nil, err
}
@@ -142,7 +154,7 @@ func (c *Client) ListFiles(path string) ([]string, error) {
// NOTE: S3 is eventually consistent so keep in mind that there is a delay.
func (c *Client) Exists(path string) (bool, error) {
if strings.HasPrefix(path, "s3://") {
- s3Conn, err := s3ConnectionInformation(path, c.Region)
+ s3Conn, err := c.s3ConnectionInformation(path, c.Region)
if err != nil {
return false, err
}
@@ -288,7 +300,7 @@ func parseS3Path(path string) (string, string, error) {
// s3ConnectionInformation parses the s3 path and returns the s3 connection from the
// correct region, as well as the bucket, and key
-func s3ConnectionInformation(path, region string) (s3Connection, error) {
+func (c *Client) s3ConnectionInformation(path, region string) (s3Connection, error) {
bucket, key, err := parseS3Path(path)
if err != nil {
return s3Connection{}, err
@@ -296,13 +308,13 @@ func s3ConnectionInformation(path, region string) (s3Connection, error) {
// If no region passed in, look up region in S3
if region == "" {
- region, err = getRegionForBucket(newS3Handler(defaultLocation), bucket)
+ region, err = getRegionForBucket(c.newS3Handler(defaultLocation), bucket)
if err != nil {
return s3Connection{}, err
}
}
- return s3Connection{newS3Handler(region), bucket, key}, nil
+ return s3Connection{c.newS3Handler(region), bucket, key}, nil
}
// getRegionForBucket looks up the region name for the given bucket
@@ -348,7 +360,13 @@ func (m *liveS3Handler) HeadObject(input *s3.HeadObjectInput) (*s3.HeadObjectOut
return m.liveS3.HeadObject(input)
}
-func newS3Handler(region string) *liveS3Handler {
+func (c *Client) newS3Handler(region string) *liveS3Handler {
+ if c.providedConfig != nil {
+ return &liveS3Handler{
+ liveS3: s3.New(session.New(), c.providedConfig.WithRegion(region).WithS3ForcePathStyle(true)),
+ }
+ }
+
config := aws.NewConfig().WithRegion(region).WithS3ForcePathStyle(true)
session := session.New()
return &liveS3Handler{s3.New(session, config)}
|
allow creating client with pre-created aws config
|
Clever_pathio
|
train
|
e025a3b52f64f1910fb8132cd6447a47c4cfe849
|
diff --git a/pipenv/patched/pipfile/api.py b/pipenv/patched/pipfile/api.py
index <HASH>..<HASH> 100644
--- a/pipenv/patched/pipfile/api.py
+++ b/pipenv/patched/pipfile/api.py
@@ -147,11 +147,11 @@ class Pipfile(object):
raise RuntimeError('No Pipfile found!')
@classmethod
- def load(klass, filename):
+ def load(klass, filename, inject_env=True):
"""Load a Pipfile from a given filename."""
p = PipfileParser(filename=filename)
pipfile = klass(filename=filename)
- pipfile.data = p.parse()
+ pipfile.data = p.parse(inject_env=inject_env)
return pipfile
@property
@@ -212,7 +212,7 @@ class Pipfile(object):
raise AssertionError('Specifier {!r} does not match {!r}.'.format(marker, specifier))
-def load(pipfile_path=None):
+def load(pipfile_path=None, inject_env=True):
"""Loads a pipfile from a given path.
If none is provided, one will try to be found.
"""
@@ -220,4 +220,4 @@ def load(pipfile_path=None):
if pipfile_path is None:
pipfile_path = Pipfile.find()
- return Pipfile.load(filename=pipfile_path)
+ return Pipfile.load(filename=pipfile_path, inject_env=inject_env)
diff --git a/pipenv/project.py b/pipenv/project.py
index <HASH>..<HASH> 100644
--- a/pipenv/project.py
+++ b/pipenv/project.py
@@ -391,7 +391,7 @@ class Project(object):
@property
def _lockfile(self):
"""Pipfile.lock divided by PyPI and external dependencies."""
- pfile = pipfile.load(self.pipfile_location)
+ pfile = pipfile.load(self.pipfile_location, inject_env=False)
lockfile = json.loads(pfile.lock())
for section in ('default', 'develop'):
lock_section = lockfile.get(section, {})
|
don't propogate env vars to pipfile.lock
|
pypa_pipenv
|
train
|
034564f03a45ce5defc8473d973ed9441a1dc472
|
diff --git a/sqlauth/__init__.py b/sqlauth/__init__.py
index <HASH>..<HASH> 100644
--- a/sqlauth/__init__.py
+++ b/sqlauth/__init__.py
@@ -16,4 +16,4 @@
##
###############################################################################
-__version__ = "0.1.202"
+__version__ = "0.1.203"
diff --git a/sqlauth/scripts/basicrouter.py b/sqlauth/scripts/basicrouter.py
index <HASH>..<HASH> 100755
--- a/sqlauth/scripts/basicrouter.py
+++ b/sqlauth/scripts/basicrouter.py
@@ -220,6 +220,10 @@ class MyRouterSession(RouterSession):
def onJoin(self, details):
log.msg("MyRouterSession.onJoin: {}".format(details))
self.factory.sessiondb.add(details.authid, details.session, self)
+ rv = yield self.call('sys.session.add',
+ action_args={ 'login_id':details.authid, 'session_id':details.session },
+ options = CallOptions(timeout=2000,discloseMe = True))
+ log.msg("MyRouterSession.onJoin: rv:{})".format(rv))
self.factory.sessiondb.activity(details.session, details.session, 'start', True)
return
diff --git a/sqlauth/twisted/sessiondb.py b/sqlauth/twisted/sessiondb.py
index <HASH>..<HASH> 100644
--- a/sqlauth/twisted/sessiondb.py
+++ b/sqlauth/twisted/sessiondb.py
@@ -80,17 +80,14 @@ class SessionDb(object):
log.msg("SessionDb.add({},body:{})".format(authid,session_body))
# first, we remember the session internally in our object store
self._sessiondb[sessionid] = session_body
- rv = yield self.call('sys.session.add',
- action_args={ 'login_id':authid, 'session_id':sessionid },
- options = CallOptions(timeout=2000,discloseMe = True))
# then record the session in the database
- yield self.app_session.call(self.operation,
- """insert into session
- (login_id,ab_session_id,tzname)
- values
- (%(login_id)s,%(session_id)s,(select tzname from login where id = %(login_id)s))""",
- { 'login_id': authid, 'session_id': sessionid },
- options=types.CallOptions(timeout=2000,discloseMe=True))
+ #yield self.app_session.call(self.operation,
+ # """insert into session
+ # (login_id,ab_session_id,tzname)
+ # values
+ # (%(login_id)s,%(session_id)s,(select tzname from login where id = %(login_id)s))""",
+ # { 'login_id': authid, 'session_id': sessionid },
+ # options=types.CallOptions(timeout=2000,discloseMe=True))
return
|
sync with pypi version: <I>
|
lgfausak_sqlauth
|
train
|
afeb4c7a6e34016cf8962fa43d7dbbd398e61aed
|
diff --git a/libnetwork/drivers/macvlan/macvlan_joinleave.go b/libnetwork/drivers/macvlan/macvlan_joinleave.go
index <HASH>..<HASH> 100644
--- a/libnetwork/drivers/macvlan/macvlan_joinleave.go
+++ b/libnetwork/drivers/macvlan/macvlan_joinleave.go
@@ -94,6 +94,7 @@ func (d *driver) Join(nid, eid string, sboxKey string, jinfo driverapi.JoinInfo,
if err := d.storeUpdate(ep); err != nil {
return fmt.Errorf("failed to save macvlan endpoint %.7s to store: %v", ep.id, err)
}
+
return nil
}
@@ -115,30 +116,18 @@ func (d *driver) Leave(nid, eid string) error {
return nil
}
-// getSubnetforIP returns the ipv4 subnet to which the given IP belongs
-func (n *network) getSubnetforIPv4(ip *net.IPNet) *ipv4Subnet {
- for _, s := range n.config.Ipv4Subnets {
- _, snet, err := net.ParseCIDR(s.SubnetIP)
- if err != nil {
- return nil
- }
- // first check if the mask lengths are the same
- i, _ := snet.Mask.Size()
- j, _ := ip.Mask.Size()
- if i != j {
- continue
- }
- if snet.Contains(ip.IP) {
- return s
- }
- }
-
- return nil
+// getSubnetforIPv4 returns the ipv4 subnet to which the given IP belongs
+func (n *network) getSubnetforIPv4(ip *net.IPNet) *ipSubnet {
+ return getSubnetForIP(ip, n.config.Ipv4Subnets)
}
// getSubnetforIPv6 returns the ipv6 subnet to which the given IP belongs
-func (n *network) getSubnetforIPv6(ip *net.IPNet) *ipv6Subnet {
- for _, s := range n.config.Ipv6Subnets {
+func (n *network) getSubnetforIPv6(ip *net.IPNet) *ipSubnet {
+ return getSubnetForIP(ip, n.config.Ipv6Subnets)
+}
+
+func getSubnetForIP(ip *net.IPNet, subnets []*ipSubnet) *ipSubnet {
+ for _, s := range subnets {
_, snet, err := net.ParseCIDR(s.SubnetIP)
if err != nil {
return nil
diff --git a/libnetwork/drivers/macvlan/macvlan_network.go b/libnetwork/drivers/macvlan/macvlan_network.go
index <HASH>..<HASH> 100644
--- a/libnetwork/drivers/macvlan/macvlan_network.go
+++ b/libnetwork/drivers/macvlan/macvlan_network.go
@@ -241,7 +241,7 @@ func (config *configuration) fromOptions(labels map[string]string) error {
func (config *configuration) processIPAM(id string, ipamV4Data, ipamV6Data []driverapi.IPAMData) error {
if len(ipamV4Data) > 0 {
for _, ipd := range ipamV4Data {
- s := &ipv4Subnet{
+ s := &ipSubnet{
SubnetIP: ipd.Pool.String(),
GwIP: ipd.Gateway.String(),
}
@@ -250,7 +250,7 @@ func (config *configuration) processIPAM(id string, ipamV4Data, ipamV6Data []dri
}
if len(ipamV6Data) > 0 {
for _, ipd := range ipamV6Data {
- s := &ipv6Subnet{
+ s := &ipSubnet{
SubnetIP: ipd.Pool.String(),
GwIP: ipd.Gateway.String(),
}
diff --git a/libnetwork/drivers/macvlan/macvlan_store.go b/libnetwork/drivers/macvlan/macvlan_store.go
index <HASH>..<HASH> 100644
--- a/libnetwork/drivers/macvlan/macvlan_store.go
+++ b/libnetwork/drivers/macvlan/macvlan_store.go
@@ -31,16 +31,11 @@ type configuration struct {
Parent string
MacvlanMode string
CreatedSlaveLink bool
- Ipv4Subnets []*ipv4Subnet
- Ipv6Subnets []*ipv6Subnet
+ Ipv4Subnets []*ipSubnet
+ Ipv6Subnets []*ipSubnet
}
-type ipv4Subnet struct {
- SubnetIP string
- GwIP string
-}
-
-type ipv6Subnet struct {
+type ipSubnet struct {
SubnetIP string
GwIP string
}
|
libnetwork: macvlan: use single ipSubnet type
|
moby_moby
|
train
|
6c968dbf544c4ce62cb265ac7562f230bcaac9f9
|
diff --git a/run_fluxanalysis.py b/run_fluxanalysis.py
index <HASH>..<HASH> 100755
--- a/run_fluxanalysis.py
+++ b/run_fluxanalysis.py
@@ -3,4 +3,4 @@
from metnet import command
if __name__ == '__main__':
- command.main(command.FluxAnalysisCommand())
+ command.main(command.FluxBalanceCommand())
|
run_fluxanalysis: Fix invocation of command
|
zhanglab_psamm
|
train
|
a5fb00564119c6c3c34cf94468902c2e91968811
|
diff --git a/xchange-bitmex/src/main/java/org/knowm/xchange/bitmex/Bitmex.java b/xchange-bitmex/src/main/java/org/knowm/xchange/bitmex/Bitmex.java
index <HASH>..<HASH> 100755
--- a/xchange-bitmex/src/main/java/org/knowm/xchange/bitmex/Bitmex.java
+++ b/xchange-bitmex/src/main/java/org/knowm/xchange/bitmex/Bitmex.java
@@ -7,7 +7,6 @@ import javax.annotation.Nullable;
import javax.ws.rs.GET;
import javax.ws.rs.HeaderParam;
import javax.ws.rs.Path;
-import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
@@ -38,7 +37,7 @@ public interface Bitmex {
BitmexWallet getWallet(@HeaderParam("API-KEY") String apiKey,
@HeaderParam("API-NONCE") SynchronizedValueFactory<Long> nonce,
@HeaderParam("API-SIGNATURE") ParamsDigest paramsDigest,
- @Nullable @PathParam("currency") String currency) throws IOException;
+ @Nullable @QueryParam("currency") String currency) throws IOException;
//Get a history of all of your wallet transactions (deposits, withdrawals, PNL)
@GET
@@ -46,7 +45,7 @@ public interface Bitmex {
List<BitmexWalletTransaction> getWalletHistory(@HeaderParam("API-KEY") String apiKey,
@HeaderParam("API-NONCE") SynchronizedValueFactory<Long> nonce,
@HeaderParam("API-SIGNATURE") ParamsDigest paramsDigest,
- @Nullable @PathParam("currency") String currency) throws IOException;
+ @Nullable @QueryParam("currency") String currency) throws IOException;
//Get a summary of all of your wallet transactions (deposits, withdrawals, PNL)
@GET
@@ -54,14 +53,14 @@ public interface Bitmex {
List<BitmexWalletTransaction> getWalletSummary(@HeaderParam("API-KEY") String apiKey,
@HeaderParam("API-NONCE") SynchronizedValueFactory<Long> nonce,
@HeaderParam("API-SIGNATURE") ParamsDigest paramsDigest,
- @Nullable @PathParam("currency") String currency) throws IOException;
+ @Nullable @QueryParam("currency") String currency) throws IOException;
@GET
@Path("user/margin")
BitmexMarginAccount getMarginAccountStatus(@HeaderParam("API-KEY") String apiKey,
@HeaderParam("API-NONCE") SynchronizedValueFactory<Long> nonce,
@HeaderParam("API-SIGNATURE") ParamsDigest paramsDigest,
- @Nullable @PathParam("currency") String currency) throws IOException;
+ @Nullable @QueryParam("currency") String currency) throws IOException;
@GET
@Path("user/margin?currency=all")
@@ -80,7 +79,7 @@ public interface Bitmex {
List<BitmexTrade> getTrades(@HeaderParam("API-KEY") String apiKey,
@HeaderParam("API-NONCE") SynchronizedValueFactory<Long> nonce,
@HeaderParam("API-SIGNATURE") ParamsDigest paramsDigest,
- @PathParam("symbol") String symbol) throws IOException;
+ @QueryParam("symbol") String symbol) throws IOException;
@GET
@Path("position")
@@ -102,7 +101,7 @@ public interface Bitmex {
@GET
@Path("instrument")
- List<BitmexTicker> getTicker(@PathParam("symbol") String symbol) throws IOException, BitmexException;
+ List<BitmexTicker> getTicker(@QueryParam("symbol") String symbol) throws IOException, BitmexException;
@GET
@Path("instrument/active")
diff --git a/xchange-examples/src/main/java/org/knowm/xchange/examples/bitmex/dto/account/BitmexAccountDemo.java b/xchange-examples/src/main/java/org/knowm/xchange/examples/bitmex/dto/account/BitmexAccountDemo.java
index <HASH>..<HASH> 100755
--- a/xchange-examples/src/main/java/org/knowm/xchange/examples/bitmex/dto/account/BitmexAccountDemo.java
+++ b/xchange-examples/src/main/java/org/knowm/xchange/examples/bitmex/dto/account/BitmexAccountDemo.java
@@ -31,6 +31,8 @@ public class BitmexAccountDemo {
System.out.println("Margin infos response: " + bitmexAccountInfo.toString());
BitmexMarginAccount xBt = accountServiceRaw.getBitmexMarginAccountStatus(new Currency("XBt"));
System.out.println(xBt);
+ BitmexMarginAccount usd = accountServiceRaw.getBitmexMarginAccountStatus(new Currency("USD"));
+ System.out.println(usd);
List<BitmexMarginAccount> bitmexMarginAccountsStatus = accountServiceRaw.getBitmexMarginAccountsStatus();
System.out.println(bitmexMarginAccountsStatus);
}
|
[BitMex] Fix for QueryParams
|
knowm_XChange
|
train
|
76c795b3f2419e2a5fa8b2d1e2bc6effe3aa9752
|
diff --git a/goatools/go_enrichment.py b/goatools/go_enrichment.py
index <HASH>..<HASH> 100755
--- a/goatools/go_enrichment.py
+++ b/goatools/go_enrichment.py
@@ -253,8 +253,8 @@ class GOEnrichmentStudy(object):
objprtres = GoeaPrintFunctions()
def __init__(self, pop, assoc, obo_dag, propagate_counts=True, alpha=.05, methods=None, **kws):
- self.name = kws.get('name', 'GOEA')
- print('\nLoad {OBJNAME} Gene Ontology Analysis ...'.format(OBJNAME=self.name))
+ self.name = kws.get('name', '')
+ print('\nLoad {NAME} Ontology Enrichment Analysis ...'.format(NAME=self.name))
self.log = kws['log'] if 'log' in kws else sys.stdout
self._run_multitest = {
'local':self._run_multitest_local,
@@ -295,7 +295,7 @@ class GOEnrichmentStudy(object):
study_name = kws.get('name', 'current')
log = self._get_log_or_prt(kws)
if log:
- log.write('\nRun {OBJNAME} Gene Ontology Analysis: {STU} study set of {N} IDs ...'.format(
+ log.write('\nRuning {OBJNAME} Ontology Analysis: {STU} study set of {N} IDs.\n'.format(
OBJNAME=self.name, N=len(study), STU=study_name))
if len(study) == 0:
return []
@@ -346,7 +346,7 @@ class GOEnrichmentStudy(object):
# To convert msg list to string: "\n".join(msg)
msg = []
if results:
- fmt = "{M:6,} GO terms are associated with {N:6,} of {NT:6,}"
+ fmt = "{M:6,} terms are associated with {N:6,} of {NT:6,}"
stu_items, num_gos_stu = self.get_item_cnt(results, "study_items")
pop_items, num_gos_pop = self.get_item_cnt(results, "pop_items")
stu_txt = fmt.format(N=len(stu_items), M=num_gos_stu, NT=len(set(study)))
@@ -364,16 +364,9 @@ class GOEnrichmentStudy(object):
pop_n, study_n = self.pop_n, len(study_in_pop)
allterms = set(go2studyitems).union(set(self.go2popitems))
if log is not None:
- # Some study genes may not have been found in the population. Report from orig
- study_n_orig = len(study)
- perc = 100.0*study_n/study_n_orig if study_n_orig != 0 else 0.0
- log.write("{R:3.0f}% {N:>6,} of {M:>6,} study items found in population({P})\n".format(
- N=study_n, M=study_n_orig, P=pop_n, R=perc))
- if study_n:
- log.write("Calculating {N:,} uncorrected p-values using {PFNC}\n".format(
- N=len(allterms), PFNC=self.pval_obj.name))
+ self._prt_log_items_found(log, study, study_in_pop, allterms)
# If no study genes were found in the population, return empty GOEA results
- if not study_n:
+ if not study_in_pop:
return []
calc_pvalue = self.pval_obj.calc_pvalue
@@ -395,6 +388,18 @@ class GOEnrichmentStudy(object):
return results
+ def _prt_log_items_found(self, log, study, study_in_pop, allterms):
+ """2 GO terms found significant (< 0.05=alpha) ( 2 enriched + 0 purified): local bonferroni"""
+ # Some study genes may not have been found in the population. Report from orig
+ study_n_orig = len(study)
+ pop_n, study_n = self.pop_n, len(study_in_pop)
+ perc = 100.0*study_n/study_n_orig if study_n_orig != 0 else 0.0
+ log.write("{R:3.0f}% {N:>6,} of {M:>6,} study items found in population({P})\n".format(
+ N=study_n, M=study_n_orig, P=pop_n, R=perc))
+ if study_n:
+ log.write("Calculating {N:,} uncorrected p-values using {PFNC}\n".format(
+ N=len(allterms), PFNC=self.pval_obj.name))
+
def _run_multitest_corr(self, results, usrmethod_flds, alpha, study, log):
"""Do multiple-test corrections on uncorrected pvalues."""
assert 0 < alpha < 1, "Test-wise alpha must fall between (0, 1)"
|
Made info messages more generic to support Human Phenotype Ontology. Moved logging into its own fnc
|
tanghaibao_goatools
|
train
|
7c842a2b4b1b9d94140c269e82392b6422f54ae4
|
diff --git a/py/testdir_hosts/test_rf_311M_rows_fvec.py b/py/testdir_hosts/test_rf_311M_rows_fvec.py
index <HASH>..<HASH> 100644
--- a/py/testdir_hosts/test_rf_311M_rows_fvec.py
+++ b/py/testdir_hosts/test_rf_311M_rows_fvec.py
@@ -26,14 +26,14 @@ class Basic(unittest.TestCase):
for trials in range(2):
parseResult = h2i.import_parse(bucket='home-0xdiag-datasets', path=csvPathname, schema='local',
- timeoutSecs=500)
+ timeoutSecs=700, retryDelaySecs=5)
print "Parse result['destination_key']:", parseResult['destination_key']
inspect = h2o_cmd.runInspect(None,parseResult['destination_key'])
print "\n" + csvFilename
start = time.time()
RFview = h2o_cmd.runRF(parseResult=parseResult, ntrees=2, max_depth=5,
- timeoutSecs=800, retryDelaySecs=10.0)
+ timeoutSecs=800, retryDelaySecs=20)
print "RF end on ", csvFilename, 'took', time.time() - start, 'seconds'
if __name__ == '__main__':
|
Increased polling interval, increased timeouts, but this test is really long running > <I>minutes.
|
h2oai_h2o-2
|
train
|
dfb5c0d64157ff502854abe40a4e191d01306673
|
diff --git a/pyt/__main__.py b/pyt/__main__.py
index <HASH>..<HASH> 100644
--- a/pyt/__main__.py
+++ b/pyt/__main__.py
@@ -48,7 +48,7 @@ def discover_files(targets, excluded_files, recursive=False):
return included_files
-def main(command_line_args=sys.argv[1:]):
+def main(command_line_args=sys.argv[1:]): # noqa: C901
args = parse_args(command_line_args)
ui_mode = UImode.NORMAL
|
Add noqa: C<I> back to def main
|
python-security_pyt
|
train
|
254564bba025b0918bf57c7c9d54e6a5a025d72b
|
diff --git a/src/Migrations/2018_11_16_000000_add_meta_fields.php b/src/Migrations/2018_11_16_000000_add_meta_fields.php
index <HASH>..<HASH> 100644
--- a/src/Migrations/2018_11_16_000000_add_meta_fields.php
+++ b/src/Migrations/2018_11_16_000000_add_meta_fields.php
@@ -38,19 +38,19 @@ class AddMetaFields extends Migration
public function down()
{
Schema::table('wink_tags', function (Blueprint $table) {
- $table->dropColumn('meta')->nullable();
+ $table->dropColumn('meta');
});
Schema::table('wink_pages', function (Blueprint $table) {
- $table->dropColumn('meta')->nullable();
+ $table->dropColumn('meta');
});
Schema::table('wink_authors', function (Blueprint $table) {
- $table->dropColumn('meta')->nullable();
+ $table->dropColumn('meta');
});
Schema::table('wink_posts', function (Blueprint $table) {
- $table->dropColumn('meta')->nullable();
+ $table->dropColumn('meta');
});
}
}
|
Removed unused ->nullable() in dropColumn
|
writingink_wink
|
train
|
70a41e9695f8b9d10bb6f121c987cf9641eda830
|
diff --git a/js/jquery.fileupload.js b/js/jquery.fileupload.js
index <HASH>..<HASH> 100644
--- a/js/jquery.fileupload.js
+++ b/js/jquery.fileupload.js
@@ -520,6 +520,30 @@
return this._enhancePromise(promise);
},
+ // Adds convenience methods to the callback arguments:
+ _addConvenienceMethods: function (e, data) {
+ var that = this;
+ data.submit = function () {
+ if (this.state() !== 'pending') {
+ data.jqXHR = this.jqXHR =
+ (that._trigger('submit', e, this) !== false) &&
+ that._onSend(e, this);
+ }
+ return this.jqXHR || that._getXHRPromise();
+ };
+ data.abort = function () {
+ if (this.jqXHR) {
+ return this.jqXHR.abort();
+ }
+ return this._getXHRPromise();
+ };
+ data.state = function () {
+ if (this.jqXHR) {
+ return that._getDeferredState(this.jqXHR);
+ }
+ };
+ },
+
// Parses the Range header from the server response
// and returns the uploaded bytes:
_getUploadedBytes: function (jqXHR) {
@@ -802,25 +826,7 @@
var newData = $.extend({}, data);
newData.files = fileSet ? element : [element];
newData.paramName = paramNameSet[index];
- newData.submit = function () {
- if (this.state() === 'pending') {
- return this.jqXHR;
- }
- newData.jqXHR = this.jqXHR =
- (that._trigger('submit', e, this) !== false) &&
- that._onSend(e, this);
- return this.jqXHR;
- };
- newData.abort = function () {
- if (this.jqXHR) {
- return this.jqXHR.abort();
- }
- };
- newData.state = function () {
- if (this.jqXHR) {
- return that._getDeferredState(this.jqXHR);
- }
- };
+ that._addConvenienceMethods(e, newData);
result = that._trigger('add', e, newData);
return result;
});
|
Make sure the submit and abort convenience methods always return a jqXHR object.
|
blueimp_jQuery-File-Upload
|
train
|
720e349d6f5cefcfbb4f90f64c15dc168e01816e
|
diff --git a/timed.py b/timed.py
index <HASH>..<HASH> 100644
--- a/timed.py
+++ b/timed.py
@@ -3,7 +3,11 @@ import os.path
import time
import datetime
+DATA_FILE = os.path.expanduser('~/.timed')
+
def main():
+ if not os.path.exists(DATA_FILE):
+ open(DATA_FILE, 'w').close()
if len(sys.argv) == 1:
Controller().default()
elif len(sys.argv) == 2:
@@ -15,7 +19,6 @@ def main():
Controller().summary()
else:
Controller().start(sys.argv[1])
-
class Controller(object):
@@ -66,7 +69,7 @@ def get_elapsed_time(start, end=None):
class Log(object):
- source = os.path.expanduser('~/.timed')
+ source = DATA_FILE
def __init__(self, **fields):
self.id = fields.get('id')
@@ -77,7 +80,10 @@ class Log(object):
def find(self, category=None):
results = []
- lines = open(self.source).readlines()
+ f = open(self.source)
+ lines = f.readlines()
+ f.close()
+
for id, line in enumerate(lines):
fields = line.split()
@@ -100,7 +106,9 @@ class Log(object):
return self.update()
if all((self.category, self.start)):
- self.id = len(open(self.source).readlines())
+ f = open(self.source)
+ self.id = len(f.readlines())
+ f.close()
if self.end:
end = self.end
@@ -108,13 +116,17 @@ class Log(object):
end = '-'
line = '%s %s %s\n' % (self.category, self.start, end)
- open(self.source, 'a').write(line)
+ f = open(self.source, 'a')
+ f.write(line)
+ f.close()
return self.id
def update(self):
if self.id is not None:
- lines = open(self.source).readlines()
+ f = open(self.source)
+ lines = f.readlines()
+ f.close()
line = lines[self.id].split()
if self.end:
@@ -123,7 +135,9 @@ class Log(object):
end = '-'
lines[self.id] = '%s %s %s\n' % (self.category, self.start, end)
- open(self.source, 'w').write(''.join(lines))
+ f = open(self.source, 'w')
+ f.write(''.join(lines))
+ f.close()
def __repr__(self):
return str({'id': self.id, 'category': self.category, 'start': self.start,
|
create .timed file if it doesn't exist + close file handlers
|
adeel_timed
|
train
|
f9eb494858b3a4d87386e3cbe93a071b964f1921
|
diff --git a/jlib-container/src/main/java/org/jlib/container/binaryrelation/Pair.java b/jlib-container/src/main/java/org/jlib/container/binaryrelation/Pair.java
index <HASH>..<HASH> 100644
--- a/jlib-container/src/main/java/org/jlib/container/binaryrelation/Pair.java
+++ b/jlib-container/src/main/java/org/jlib/container/binaryrelation/Pair.java
@@ -21,7 +21,7 @@
package org.jlib.container.binaryrelation;
-import org.jlib.core.language.AbstractObject;
+import org.jlib.core.language.AbstractCloneable;
/**
* Binary association.
@@ -35,7 +35,7 @@ import org.jlib.core.language.AbstractObject;
* @author Igor Akkerman
*/
public class Pair<LeftValue, RightValue>
-extends AbstractObject {
+extends AbstractCloneable {
/** LeftValue of this Pair */
private final LeftValue leftValue;
|
Pair extends AbstractCloneable but not AutoCloneable
|
jlib-framework_jlib-operator
|
train
|
e390427dc8416e5d8fbbeccfb0bcfe5a4d85e2a6
|
diff --git a/AntiSpoof_i18n.php b/AntiSpoof_i18n.php
index <HASH>..<HASH> 100644
--- a/AntiSpoof_i18n.php
+++ b/AntiSpoof_i18n.php
@@ -66,6 +66,9 @@ $wgAntiSpoofMessages['ca'] = array(
'antispoof-mixedscripts' => 'Conté una mescla incompatible d\'escriptures',
'antispoof-tooshort' => 'Nom canònic massa curt',
);
+$wgAntiSpoofMessages['cdo'] = array(
+ 'antispoof-name-conflict' => '"$1" gì miàng ké̤ṳk ī-gĭng cé̤ṳ-cháh gì dióng-hô̤ "$2" kák chiông lāu. Chiāng uâng 1 ciáh miàng.',
+);
$wgAntiSpoofMessages['cs'] = array(
'antispoof-name-conflict' => 'Uživatelské jméno "$1" je příliš podobné existujícímu účtu "$2". Prosím, vyberte si jiné jméno.',
'antispoof-name-illegal' => 'Uživatelské jméno "$1" není povoleno vytvořit, aby se nepletlo nebo nesloužilo k napodobování uživatelského jména: $2. Prosím, vyberte si jiné jméno.',
@@ -566,9 +569,3 @@ $wgAntiSpoofMessages['zh-hk'] = $wgAntiSpoofMessages['zh-hant'];
$wgAntiSpoofMessages['zh-sg'] = $wgAntiSpoofMessages['zh-hans'];
$wgAntiSpoofMessages['zh-tw'] = $wgAntiSpoofMessages['zh-hant'];
$wgAntiSpoofMessages['zh-yue'] = $wgAntiSpoofMessages['yue'];
-
-
-
-
-
-
|
* (Bug <I>) Add Min Dong localisation and its extension messages
|
wikimedia_mediawiki-extensions-AntiSpoof
|
train
|
749c721d70ad392b52746edaf99a2bb6c67ce903
|
diff --git a/contribs/gmf/src/print/component.js b/contribs/gmf/src/print/component.js
index <HASH>..<HASH> 100644
--- a/contribs/gmf/src/print/component.js
+++ b/contribs/gmf/src/print/component.js
@@ -487,6 +487,13 @@ exports.Controller_ = class {
this.setRotation(/** @type {number} */ (rotation));
}
});
+ // Workaround for IE11
+ this.rotationInput_.on('change', (event) => {
+ const rotation = $(event.target).val();
+ if (rotation !== '') {
+ this.setRotation(/** @type {number} */ (rotation));
+ }
+ });
/**
* @type {function(ol.render.Event)}
|
Workaround for IE<I> in print rotation slider
|
camptocamp_ngeo
|
train
|
b2c7172516adf31abfbe61ffb5f4b871b3238b88
|
diff --git a/index.js b/index.js
index <HASH>..<HASH> 100644
--- a/index.js
+++ b/index.js
@@ -43,7 +43,7 @@ Guard.prototype = {
}))
}
- var user = req[options.requestProperty]
+ var user = get(req, options.requestProperty, undefined)
if (!user) {
return next(new UnauthorizedError('user_object_not_found', {
message: util.format('user object "%s" was not found. Check your configuration.', options.requestProperty)
diff --git a/test/test.js b/test/test.js
index <HASH>..<HASH> 100644
--- a/test/test.js
+++ b/test/test.js
@@ -87,6 +87,26 @@ test('valid permissions with custom options', function (t) {
guard.check('ping')(req, res, t.error)
})
+test('valid requestProperty of level 1', function (t) {
+ t.plan(1)
+ var guard = require('../index')({
+ requestProperty: 'identity',
+ permissionsProperty: 'scopes'
+ })
+ var req = { identity: { scopes: ['ping'] } }
+ guard.check('ping')(req, res, t.error)
+})
+
+test('valid requestProperty of level n', function (t) {
+ t.plan(1)
+ var guard = require('../index')({
+ requestProperty: 'token.identity',
+ permissionsProperty: 'scopes'
+ })
+ var req = { token: { identity: { scopes: ['ping'] } } }
+ guard.check('ping')(req, res, t.error)
+})
+
test('invalid permissions [Array] notation', function (t) {
var req = { user: { permissions: ['ping'] } }
guard.check('foo')(req, res, function (err) {
|
FIX set requestProperty (#<I>)
* Extended requestProperty (deep properties)
|
MichielDeMey_express-jwt-permissions
|
train
|
e0557c2e62e63f8103496b82e62b3d9186e477de
|
diff --git a/js/examples/main.js b/js/examples/main.js
index <HASH>..<HASH> 100644
--- a/js/examples/main.js
+++ b/js/examples/main.js
@@ -14,6 +14,7 @@ const htmlContent = `<button onClick="app.connect()">Connect</button>
<button onClick="app.sendBinary()">Send Binary</button>
<button onClick="app.toggleStream()">Sub/Unsub</button>
<button onClick="app.sendMistake()">Mistake</button>
+<button onClick="app.postBinary()">send a float as binary</button>
<br/>
<textarea class="output" rows="12" cols="50"></textarea>
<br/>
@@ -70,6 +71,13 @@ export function sendBinary() {
.then(handleMessage, (err) => logerr(err));
}
+export function postBinary() {
+ if (!session) return;
+ session.call('myprotocol.postbinary', [
+ session.addAttachment(new Float32Array([5678]).buffer),
+ ]).then((r) => log('result ' + r), (err) => logerr(err));
+}
+
export function sendMistake() {
if (!session) return;
session.call('myprotocol.mistake.TYPO', ['ignored'])
diff --git a/js/src/WebsocketConnection/session.js b/js/src/WebsocketConnection/session.js
index <HASH>..<HASH> 100644
--- a/js/src/WebsocketConnection/session.js
+++ b/js/src/WebsocketConnection/session.js
@@ -6,6 +6,8 @@ function Session(publicAPI, model) {
let msgCount = 0;
const inFlightRpc = {};
const attachments = [];
+ const attachmentsToSend = {};
+ let attachmentId = 1;
const regexAttach = /^wslink_bin[\d]+$/;
// matches 'rpc:client3:21'
// client may be dot-separated and include '_'
@@ -47,6 +49,38 @@ function Session(publicAPI, model) {
if (model.ws && clientID && model.ws.readyState === 1) {
const id = `rpc:${clientID}:${msgCount++}`
inFlightRpc[id] = deferred;
+
+ const msg = JSON.stringify({ wslink: '1.0', id, method, args, kwargs });
+
+ if (Object.keys(attachmentsToSend).length) {
+ const sendBinary = (key) => {
+ if (key in attachmentsToSend) {
+ // binary header
+ model.ws.send(JSON.stringify({
+ wslink: '1.0',
+ method: 'wslink.binary.attachment',
+ args: [key],
+ }));
+
+ // send binary
+ model.ws.send(attachmentsToSend[key], { binary: true });
+ delete attachmentsToSend[key];
+ }
+ };
+
+ args.filter((k) => regexAttach.test(k)).forEach(sendBinary);
+ const objFilter = (o) => {
+ Object.keys(o).forEach((k) => {
+ if (regexAttach.test(o[k])) {
+ sendBinary(o[k]);
+ } else {
+ objSearch(o[k]);
+ }
+ });
+ };
+ objFilter(kwargs);
+ }
+
model.ws.send(JSON.stringify({ wslink: '1.0', id, method, args, kwargs }));
} else {
deferred.reject({ code: CLIENT_ERROR, message: `RPC call ${method} unsuccessful: connection not open` });
@@ -203,6 +237,13 @@ function Session(publicAPI, model) {
}
}
};
+
+ publicAPI.addAttachment = (payload) => {
+ const binaryId = `wslink_bin${attachmentId}`;
+ attachmentsToSend[binaryId] = payload;
+ attachmentId++;
+ return binaryId;
+ };
}
|
fix(WebsocketConnection): Support sending binary attachments
|
Kitware_wslink
|
train
|
b01eaf7e86358f02c8340a420af97ce5024f6841
|
diff --git a/commands/command_smudge.go b/commands/command_smudge.go
index <HASH>..<HASH> 100644
--- a/commands/command_smudge.go
+++ b/commands/command_smudge.go
@@ -74,7 +74,7 @@ func smudgeCommand(cmd *cobra.Command, args []string) {
ptr.Encode(os.Stdout)
// Download declined error is ok to skip if we weren't requesting download
if !(lfs.IsDownloadDeclinedError(err) && !download) {
- LoggedError(err, "Error accessing media: %s (%s)", filename, ptr.Oid)
+ LoggedError(err, "Error downloading object: %s (%s)", filename, ptr.Oid)
os.Exit(2)
}
}
|
"media" word is left over from "git media" days
|
git-lfs_git-lfs
|
train
|
f72af2c8b2fbef98144325505a9afe3186d0e205
|
diff --git a/ontobio/io/differ.py b/ontobio/io/differ.py
index <HASH>..<HASH> 100644
--- a/ontobio/io/differ.py
+++ b/ontobio/io/differ.py
@@ -1,4 +1,4 @@
-from ontobio.io import assocparser, gafparser, gpadparser, entityparser
+from ontobio.io import assocparser, gpadparser
from ontobio import ecomap
import click
import pandas as pd
@@ -6,7 +6,9 @@ import datetime
from ontobio.io import qc
from ontobio.io.assocparser import Report
from ontobio.model import collections
-
+import warnings
+from pandas.core.common import SettingWithCopyWarning
+warnings.simplefilter(action="ignore", category=SettingWithCopyWarning)
@click.command()
@click.option("--file1",
@@ -32,7 +34,12 @@ from ontobio.model import collections
help='Options to group by include: subject, object, and/or evidence_code.'
'If more than one of these parameters is listed (ie: -gb = evidence_code, -gb entity_identifier, '
'the grouping report will group by evidence_code and entity_identifier)')
-def compare_files(file1, file2, output, group_by_column):
+@click.option("--restrict_to_decreases",
+ "-rtd",
+ type=click.BOOL,
+ required=False,
+ help='Only report group by results when the second file shows a decrease in number by grouping column')
+def compare_files(file1, file2, output, group_by_column, restrict_to_decreases):
# decide which parser to instantiate, GAF or GPAD
pd.set_option('display.max_rows', 35000)
df_file1, df_file2, assocs1, assocs2 = get_parser(file1, file2)
@@ -44,7 +51,7 @@ def compare_files(file1, file2, output, group_by_column):
compare_associations(assocs1, assocs2, output, file1, file2)
# group_by is a list of strings exactly matching column names.
- generate_group_report(df_file1, df_file2, group_by_column, file1, file2, output)
+ generate_group_report(df_file1, df_file2, group_by_column, file1, file2, restrict_to_decreases, output)
def generate_count_report(df_file1, df_file2, file1, file2, output):
@@ -62,7 +69,7 @@ def generate_count_report(df_file1, df_file2, file1, file2, output):
print(merged_frame)
-def generate_group_report(df_file1, df_file2, group_by_column, file1, file2, output):
+def generate_group_report(df_file1, df_file2, group_by_column, file1, file2, restrict_to_decreases, output):
if len(group_by_column) > 0:
s = "\n\n## GROUP BY SUMMARY \n\n"
@@ -81,13 +88,23 @@ def generate_group_report(df_file1, df_file2, group_by_column, file1, file2, out
column2 = fix_int_df.columns[1]+"2"
fix_int_df.columns.values[1] = column2
df = fix_int_df.query("{0}".format(column1) + " != " + "{0}".format(column2))
- df.rename(columns={list(df)[0]: file1}, inplace=True)
- df.rename(columns={list(df)[1]: file2}, inplace=True)
- s += " * Number of " + group + "s that show differences: " + str(len(df.index)) + "\n"
- s += " * See output file " + output + "_" + group + "_counts_per_column_report" + "\n"
- df.to_csv(output + "_" + group + "_counts_per_column_report", sep='\t')
- print(s)
- print("\n\n")
+ if restrict_to_decreases:
+ print("restricted!")
+ df_restricted = df.query("{0}".format(column1) + " > " + "{0}".format(column2))
+ df_restricted.rename(columns={list(df)[0]: file1}, inplace=True)
+ df_restricted.rename(columns={list(df)[1]: file2}, inplace=True)
+ df_restricted.to_csv(output + "_" + group + "_counts_per_column_report", sep='\t')
+ s += " * Number of unqiue " + group + "s that show less in file2 compared to file1: " + str(len(df.index)) + "\n"
+ s += " * See output file " + output + "_" + group + "_counts_per_column_report" + "\n"
+ print(s)
+ else:
+ s += " * Number of unqiue " + group + "s that show differences: " + str(len(df.index)) + "\n"
+ s += " * See output file " + output + "_" + group + "_counts_per_column_report" + "\n"
+ df.rename(columns={list(df)[0]: file1}, inplace=True)
+ df.rename(columns={list(df)[1]: file2}, inplace=True)
+ df.to_csv(output + "_" + group + "_counts_per_column_report", sep='\t')
+ print(s)
+ print("\n\n")
def compare_associations(assocs1, assocs2, output, file1, file2):
|
add restrict_to_decreases
|
biolink_ontobio
|
train
|
98ba2e69daa3ebf460516f5b57f5340ae71fe830
|
diff --git a/i3pystatus/battery.py b/i3pystatus/battery.py
index <HASH>..<HASH> 100644
--- a/i3pystatus/battery.py
+++ b/i3pystatus/battery.py
@@ -145,12 +145,12 @@ class BatteryChecker(IntervalModule):
}
status = battery.status()
- if status in ["Discharging", "Charging"]:
+ if status in ["Charging", "Discharging"]:
remaining = battery.remaining()
fdict["remaining"] = TimeWrapper(remaining * 60, "%E%h:%M")
if status == "Discharging":
fdict["status"] = "DIS"
- if remaining < 15:
+ if battery.percentage() <= self.alert_percentage:
urgent = True
color = "#ff0000"
else:
|
battery: Use alert_percentage for coloring the entry red
|
enkore_i3pystatus
|
train
|
83dce0105e1ae2443f630ddd01c0e94a848eb2d5
|
diff --git a/src/metapensiero/signal/user.py b/src/metapensiero/signal/user.py
index <HASH>..<HASH> 100644
--- a/src/metapensiero/signal/user.py
+++ b/src/metapensiero/signal/user.py
@@ -169,7 +169,10 @@ class SignalAndHandlerInitMeta(InheritanceToolsMeta):
aname = avalue.name
else:
avalue.name = aname
- assert aname not in signals
+ assert ((aname not in signals) or
+ (aname in signals and avalue is not signals[aname])), \
+ ("The same signal {name!r} was found "
+ "two times".format(name=aname))
if signaller:
avalue.external_signaller = signaller
signals[aname] = avalue
|
Allow a signal with the same name but distinct to be on subclasses bodies
|
metapensiero_metapensiero.signal
|
train
|
6150fa37a2441ca754eae92bb7e5a7338fe75a5c
|
diff --git a/topologies/server.js b/topologies/server.js
index <HASH>..<HASH> 100644
--- a/topologies/server.js
+++ b/topologies/server.js
@@ -902,10 +902,7 @@ var Server = function(options) {
// , showDiskLoc: <boolean>
// , comment: <string>
// , maxTimeMS: <n>
- // }
- // // Options
- // {
- // raw: <boolean>
+ // , raw: <boolean>
// , readPreference: <ReadPreference>
// , tailable: <boolean>
// , oplogReply: <boolean>
@@ -922,11 +919,6 @@ var Server = function(options) {
* @param {{object}|{Long}} cmd Can be either a command returning a cursor or a cursorId
* @param {object} [options.batchSize=0] Batchsize for the operation
* @param {array} [options.documents=[]] Initial documents list for cursor
- * @param {boolean} [options.tailable=false] Tailable flag set
- * @param {boolean} [options.oplogReply=false] oplogReply flag set
- * @param {boolean} [options.awaitdata=false] awaitdata flag set
- * @param {boolean} [options.exhaust=false] exhaust flag set
- * @param {boolean} [options.partial=false] partial flag set
* @param {opResultCallback} callback A callback function
*/
this.cursor = function(ns, cmd, cursorOptions) {
diff --git a/wireprotocol/2_4_support.js b/wireprotocol/2_4_support.js
index <HASH>..<HASH> 100644
--- a/wireprotocol/2_4_support.js
+++ b/wireprotocol/2_4_support.js
@@ -450,12 +450,12 @@ var setupClassicFind = function(bson, ns, cmd, cursorState, topology, options) {
query.slaveOk = readPreference.slaveOk();
// Set up the option bits for wire protocol
- if(options.tailable) { query.tailable = options.tailable; }
- if(options.oplogReply)query.oplogReply = options.oplogReply;
- if(options.noCursorTimeout) query.noCursorTimeout = options.noCursorTimeout;
- if(options.awaitData) query.awaitData = options.awaitData;
- if(options.exhaust) query.exhaust = options.exhaust;
- if(options.partial) query.partial = options.partial;
+ if(typeof cmd.tailable == 'boolean') query.tailable = options.tailable;
+ if(typeof cmd.oplogReply == 'boolean') query.oplogReply = options.oplogReply;
+ if(typeof cmd.noCursorTimeout == 'boolean') query.noCursorTimeout = options.noCursorTimeout;
+ if(typeof cmd.awaitData == 'boolean') query.awaitData = options.awaitData;
+ if(typeof cmd.exhaust == 'boolean') query.exhaust = options.exhaust;
+ if(typeof cmd.partial == 'boolean') query.partial = options.partial;
// Return the query
return query;
}
diff --git a/wireprotocol/2_6_support.js b/wireprotocol/2_6_support.js
index <HASH>..<HASH> 100644
--- a/wireprotocol/2_6_support.js
+++ b/wireprotocol/2_6_support.js
@@ -236,12 +236,12 @@ var setupCommand = function(bson, ns, cmd, cursorState, topology, options) {
query.slaveOk = readPreference.slaveOk();
// Options
- if(options.tailable) query.tailable = options.tailable;
- if(options.oplogReply)query.oplogReply = options.oplogReply;
- if(options.noCursorTimeout) query.noCursorTimeout = options.noCursorTimeout;
- if(options.awaitdata) query.awaitdata = options.awaitdata;
- if(options.exhaust) query.exhaust = options.exhaust;
- if(options.partial) query.partial = options.partial;
+ if(typeof options.tailable == 'boolean') query.tailable = options.tailable;
+ if(typeof options.oplogReply == 'boolean') query.oplogReply = options.oplogReply;
+ if(typeof options.noCursorTimeout == 'boolean') query.noCursorTimeout = options.noCursorTimeout;
+ if(typeof options.awaitdata == 'boolean') query.awaitdata = options.awaitdata;
+ if(typeof options.exhaust == 'boolean') query.exhaust = options.exhaust;
+ if(typeof options.partial == 'boolean') query.partial = options.partial;
// Return the query
return query;
}
|
Changed virtual find command to be more like server spec
|
mongodb_node-mongodb-native
|
train
|
3d98d623e73891533e56ddd84d8894424e6f41bd
|
diff --git a/Twig/CmsExtension.php b/Twig/CmsExtension.php
index <HASH>..<HASH> 100644
--- a/Twig/CmsExtension.php
+++ b/Twig/CmsExtension.php
@@ -177,7 +177,11 @@ class CmsExtension extends \Twig_Extension
}
}
}
-
+
+ if (null === $content) {
+ throw new \RuntimeException('Undefined content.');
+ }
+
if (! $this->template->hasBlock('cms_block_content')) {
throw new \RuntimeException('Unable to find "cms_block_content" twig block.');
}
|
Undefined content in twig extension
|
ekyna_CmsBundle
|
train
|
eb6e17e45d68f538555e4c403883afc91fb97250
|
diff --git a/master/buildbot/data/connector.py b/master/buildbot/data/connector.py
index <HASH>..<HASH> 100644
--- a/master/buildbot/data/connector.py
+++ b/master/buildbot/data/connector.py
@@ -104,7 +104,7 @@ class DataConnector(service.AsyncService):
try:
return self.matcher[path]
except KeyError:
- raise exceptions.InvalidPathError
+ raise exceptions.InvalidPathError("Invalid path: " + "/".join([str(p) for p in path]))
def getResourceType(self, name):
return getattr(self.rtypes, name)
diff --git a/master/buildbot/test/unit/test_www_rest.py b/master/buildbot/test/unit/test_www_rest.py
index <HASH>..<HASH> 100644
--- a/master/buildbot/test/unit/test_www_rest.py
+++ b/master/buildbot/test/unit/test_www_rest.py
@@ -258,7 +258,7 @@ class V2RootResource_REST(www.WwwTestMixin, unittest.TestCase):
def test_not_found(self):
yield self.render_resource(self.rsrc, '/not/found')
self.assertRequest(
- contentJson=dict(error='invalid path'),
+ contentJson=dict(error='Invalid path: not/found'),
contentType='text/plain; charset=utf-8',
responseCode=404)
@@ -526,7 +526,7 @@ class V2RootResource_JSONRPC2(www.WwwTestMixin, unittest.TestCase):
def test_invalid_path(self):
yield self.render_control_resource(self.rsrc, '/not/found')
self.assertJsonRpcError(
- message='invalid path',
+ message='Invalid path: not/found',
jsonrpccode=JSONRPC_CODES['invalid_request'],
responseCode=404)
|
better debug for <I>
|
buildbot_buildbot
|
train
|
030093d79daebac71c3922bb8fb692597766775e
|
diff --git a/lib/elasticsearch/client/abstract_client.rb b/lib/elasticsearch/client/abstract_client.rb
index <HASH>..<HASH> 100644
--- a/lib/elasticsearch/client/abstract_client.rb
+++ b/lib/elasticsearch/client/abstract_client.rb
@@ -7,17 +7,17 @@ module ElasticSearch
:transport => ElasticSearch::Transport::HTTP
}.freeze
- attr_accessor :current_server, :connection
+ attr_accessor :servers, :current_server, :connection
def initialize(servers_or_url, options={}, &block)
@options = DEFAULTS.merge(options)
- @server_list, @default_index, @default_type = extract_server_list_and_defaults(servers_or_url)
- @current_server = @server_list.first
+ @servers, @default_index, @default_type = extract_servers_and_defaults(servers_or_url)
+ @current_server = @servers.first
end
- def extract_server_list_and_defaults(servers_or_url)
+ def extract_servers_and_defaults(servers_or_url)
default_index = default_type = nil
- servers = Array(servers_or_url).collect do |server|
+ given_servers = Array(servers_or_url).collect do |server|
begin
uri = URI.parse(server)
_, default_index, default_type = uri.path.split("/")
@@ -27,11 +27,7 @@ module ElasticSearch
server
end
end
- [servers, default_index, default_type]
- end
-
- def servers
- @server_list
+ [given_servers, default_index, default_type]
end
def inspect
diff --git a/lib/elasticsearch/client/auto_discovering_client.rb b/lib/elasticsearch/client/auto_discovering_client.rb
index <HASH>..<HASH> 100644
--- a/lib/elasticsearch/client/auto_discovering_client.rb
+++ b/lib/elasticsearch/client/auto_discovering_client.rb
@@ -5,7 +5,7 @@ module ElasticSearch
:auto_discovery => true
}.freeze
- def initialize(servers, options={})
+ def initialize(servers_or_url, options={})
super
@options = AUTO_DISCOVERING_DEFAULTS.merge(@options)
if @options[:auto_discovery]
@@ -15,7 +15,7 @@ module ElasticSearch
#TODO how to autodiscover on reconnect? don't want to overwrite methods of RetryingClient
def auto_discover_nodes!
- @server_list = execute(:all_nodes)
+ @servers = execute(:all_nodes)
end
end
end
diff --git a/lib/elasticsearch/client/retrying_client.rb b/lib/elasticsearch/client/retrying_client.rb
index <HASH>..<HASH> 100644
--- a/lib/elasticsearch/client/retrying_client.rb
+++ b/lib/elasticsearch/client/retrying_client.rb
@@ -14,10 +14,10 @@ module ElasticSearch
}.freeze
# use cluster status to get server list
- def initialize(servers, options={})
+ def initialize(servers_or_url, options={})
super
@options = RETRYING_DEFAULTS.merge(@options)
- @retries = options[:retries] || @server_list.size
+ @retries = options[:retries] || @servers.size
@request_count = 0
@max_requests = @options[:server_max_requests]
@retry_period = @options[:server_retry_period]
@@ -46,7 +46,7 @@ module ElasticSearch
def next_server
if @retry_period
rebuild_live_server_list! if Time.now > @last_rebuild + @retry_period
- raise NoServersAvailable, "No live servers in #{@server_list.inspect} since #{@last_rebuild.inspect}." if @live_server_list.empty?
+ raise NoServersAvailable, "No live servers in #{@servers.inspect} since #{@last_rebuild.inspect}." if @live_server_list.empty?
elsif @live_server_list.empty?
rebuild_live_server_list!
end
@@ -56,9 +56,9 @@ module ElasticSearch
def rebuild_live_server_list!
@last_rebuild = Time.now
if @options[:randomize_server_list]
- @live_server_list = @server_list.sort_by { rand }
+ @live_server_list = @servers.sort_by { rand }
else
- @live_server_list = @server_list.dup
+ @live_server_list = @servers.dup
end
end
|
rename @server_list to @servers
|
grantr_rubberband
|
train
|
6174bcb388799c2035752f92ee9684281ea0fd89
|
diff --git a/README.md b/README.md
index <HASH>..<HASH> 100644
--- a/README.md
+++ b/README.md
@@ -39,6 +39,7 @@ c = get_config()
c.NotebookApp.contents_manager_class = S3ContentsManager
c.S3ContentsManager.access_key_id = <AWS Access Key ID / IAM Access Key ID>
c.S3ContentsManager.secret_access_key = <AWS Secret Access Key / IAM Secret Access Key>
+c.S3ContentsManager.session_token = <AWS Session Token / IAM Session Token>
c.S3ContentsManager.bucket = "<bucket-name>>"
```
diff --git a/s3contents/s3_fs.py b/s3contents/s3_fs.py
index <HASH>..<HASH> 100644
--- a/s3contents/s3_fs.py
+++ b/s3contents/s3_fs.py
@@ -38,6 +38,12 @@ class S3FS(GenericFS):
dir_keep_file = Unicode(
".s3keep", help="Empty file to create when creating directories").tag(config=True)
+ session_token = Unicode(
+ help="S3/AWS session token",
+ allow_none=True,
+ default_value=None
+ ).tag(config=True, env="JPYNB_S3_SESSION_TOKEN")
+
def __init__(self, log, **kwargs):
super(S3FS, self).__init__(**kwargs)
self.log = log
@@ -55,6 +61,7 @@ class S3FS(GenericFS):
self.fs = s3fs.S3FileSystem(key=self.access_key_id,
secret=self.secret_access_key,
+ token=self.session_token,
client_kwargs=client_kwargs,
config_kwargs=config_kwargs,
s3_additional_kwargs=s3_additional_kwargs)
diff --git a/s3contents/s3manager.py b/s3contents/s3manager.py
index <HASH>..<HASH> 100644
--- a/s3contents/s3manager.py
+++ b/s3contents/s3manager.py
@@ -29,6 +29,12 @@ class S3ContentsManager(GenericContentsManager):
delimiter = Unicode("/", help="Path delimiter").tag(config=True)
sse = Unicode(help="Type of server-side encryption to use").tag(config=True)
+ session_token = Unicode(
+ help="S3/AWS session token",
+ allow_none=True,
+ default_value=None
+ ).tag(config=True, env="JPYNB_S3_SESSION_TOKEN")
+
def __init__(self, *args, **kwargs):
super(S3ContentsManager, self).__init__(*args, **kwargs)
@@ -40,6 +46,7 @@ class S3ContentsManager(GenericContentsManager):
region_name=self.region_name,
bucket=self.bucket,
prefix=self.prefix,
+ session_token=self.session_token,
signature_version=self.signature_version,
delimiter=self.delimiter,
sse=self.sse)
|
Added session token (#<I>)
|
danielfrg_s3contents
|
train
|
c31ae13a69100d095332cac8c07b0293445ff45d
|
diff --git a/app/chat.js b/app/chat.js
index <HASH>..<HASH> 100644
--- a/app/chat.js
+++ b/app/chat.js
@@ -14,7 +14,7 @@ var models = require('./models/models.js');
var ChatServer = function (app, sessionStore) {
var self = this;
-
+
// Set moment date formatting
moment.calendar.sameDay = 'LT';
@@ -36,7 +36,7 @@ var ChatServer = function (app, sessionStore) {
};
this.listen = function () {
-
+
//
// Setup
//
@@ -68,7 +68,13 @@ var ChatServer = function (app, sessionStore) {
var hs = client.handshake;
var userData = hs.session.user;
-
+
+ var sessionTouchInterval = setInterval(function () {
+ hs.session.reload( function () {
+ hs.session.touch().save();
+ });
+ }, 60 * 1000);
+
//
// Assign Client Profile
//
@@ -83,7 +89,7 @@ var ChatServer = function (app, sessionStore) {
avatar: hash.md5(userData.email)
});
-
+
//
// Message History
//
@@ -119,7 +125,7 @@ var ChatServer = function (app, sessionStore) {
client.emit('room:messages:new', messages);
});
});
-
+
//
// New Message
//
@@ -186,7 +192,7 @@ var ChatServer = function (app, sessionStore) {
});
});
});
-
+
//
// Get Room Users
//
@@ -206,7 +212,7 @@ var ChatServer = function (app, sessionStore) {
});
});
});
-
+
});
//
@@ -231,7 +237,7 @@ var ChatServer = function (app, sessionStore) {
});
});
});
-
+
//
// Roomlist request
//
@@ -262,11 +268,11 @@ var ChatServer = function (app, sessionStore) {
safeName: profile.displayName.replace(/\W/g, '')
});
});
- });
+ });
});
});
});
-
+
//
// Leave Room
//
@@ -314,6 +320,7 @@ var ChatServer = function (app, sessionStore) {
self.io.sockets.in(room).emit('room:users:leave', user);
self.io.sockets.emit('rooms:users:leave', user)
});
+ clearInterval(sessionTouchInterval)
});
});
|
Fix Sessions timing out
Now we refresh Sessions so long as websocket is open
|
sdelements_lets-chat
|
train
|
ff97cdd6d589ef67bcd4fc7a6741274314a46737
|
diff --git a/library/src/main/java/com/pengrad/telegrambot/model/Message.java b/library/src/main/java/com/pengrad/telegrambot/model/Message.java
index <HASH>..<HASH> 100644
--- a/library/src/main/java/com/pengrad/telegrambot/model/Message.java
+++ b/library/src/main/java/com/pengrad/telegrambot/model/Message.java
@@ -16,6 +16,7 @@ public class Message implements Serializable {
private Integer message_id;
private User from;
+ private Chat sender_chat;
private Integer date;
private Chat chat;
private User forward_from;
@@ -73,6 +74,10 @@ public class Message implements Serializable {
return from;
}
+ public Chat senderChat() {
+ return sender_chat;
+ }
+
public Integer date() {
return date;
}
@@ -272,6 +277,7 @@ public class Message implements Serializable {
Message message = (Message) o;
return Objects.equals(message_id, message.message_id) &&
Objects.equals(from, message.from) &&
+ Objects.equals(sender_chat, message.sender_chat) &&
Objects.equals(date, message.date) &&
Objects.equals(chat, message.chat) &&
Objects.equals(forward_from, message.forward_from) &&
@@ -332,6 +338,7 @@ public class Message implements Serializable {
return "Message{" +
"message_id=" + message_id +
", from=" + from +
+ ", sender_chat=" + sender_chat +
", date=" + date +
", chat=" + chat +
", forward_from=" + forward_from +
diff --git a/library/src/test/java/com/pengrad/telegrambot/TelegramBotTest.java b/library/src/test/java/com/pengrad/telegrambot/TelegramBotTest.java
index <HASH>..<HASH> 100644
--- a/library/src/test/java/com/pengrad/telegrambot/TelegramBotTest.java
+++ b/library/src/test/java/com/pengrad/telegrambot/TelegramBotTest.java
@@ -638,6 +638,7 @@ public class TelegramBotTest {
Message message = sendResponse.message();
MessageTest.checkTextMessage(message);
assertEquals(url, message.entities()[0].url());
+ assertEquals(channelId, message.senderChat().id());
}
@Test
|
Added the field sender_chat to the class Message.
|
pengrad_java-telegram-bot-api
|
train
|
e7425338e7f2d6085f84f757f051846c6ea41279
|
diff --git a/src/sap.m/src/sap/m/ProgressIndicator.js b/src/sap.m/src/sap/m/ProgressIndicator.js
index <HASH>..<HASH> 100644
--- a/src/sap.m/src/sap/m/ProgressIndicator.js
+++ b/src/sap.m/src/sap/m/ProgressIndicator.js
@@ -117,6 +117,10 @@ sap.ui.define(['jquery.sap.global', './library', 'sap/ui/core/Control', 'sap/ui/
fAnimationDuration = bUseAnimations ? Math.abs(fPercentDiff) * 20 : 0;
$progressBar = this.$("bar");
+ // Stop currently running animation and start new one.
+ // In case of multiple setPercentValue calls all animations will run and it will take some time until the last value is animated,
+ // which is the one, actually valuable.
+ $progressBar.stop();
$progressBar.animate({
"flex-basis" : fPercentValue + "%"
}, fAnimationDuration, "linear", function() {
|
[INTERNAL][FIX] sap.m.ProgressIndicator: stacked progress animations corrected
Issue
In case of multiple setPercentValue calls all animations will run
and it will take some time until the last value is animated
Solution
Stop currently running animation and start new one.
BCP: <I>
Change-Id: Ic<I>b4d<I>b0a<I>d9ab8e<I>d0fb<I>c9
|
SAP_openui5
|
train
|
c1662356e968453f037300fee698e2d1f1dbe8e2
|
diff --git a/cli/cmd/service.go b/cli/cmd/service.go
index <HASH>..<HASH> 100644
--- a/cli/cmd/service.go
+++ b/cli/cmd/service.go
@@ -1976,7 +1976,7 @@ func (c *ServicedCli) cmdServiceClearEmergency(ctx *cli.Context) {
// serviced service tune SERVICEID
func (c *ServicedCli) cmdServiceTune(ctx *cli.Context) {
args := ctx.Args()
- if len(args) < 2 {
+ if len(args) < 1 {
fmt.Printf("Incorrect Usage.\n\n")
cli.ShowCommandHelp(ctx, "tune")
return
@@ -1995,6 +1995,12 @@ func (c *ServicedCli) cmdServiceTune(ctx *cli.Context) {
}
// Check the arguments
+ if !ctx.IsSet("instances") && !ctx.IsSet("ramThreshold") && !ctx.IsSet("ramThreshold") {
+ fmt.Printf("Incorrect Usage.\n\n")
+ cli.ShowCommandHelp(ctx, "tune")
+ return
+ }
+
modified := false
if ctx.IsSet("instances") {
oldInstanceCount := service.Instances
diff --git a/cli/cmd/service_test.go b/cli/cmd/service_test.go
index <HASH>..<HASH> 100644
--- a/cli/cmd/service_test.go
+++ b/cli/cmd/service_test.go
@@ -1498,7 +1498,7 @@ func ExampleServicedCLI_CmdServiceClearEmergency_usage() {
func ExampleServiceCLI_CmdServiceTune_usage() {
pipeStderr(func() { InitServiceAPITest("serviced", "service", "tune") })
// Output:
- //Incorrect Usage.
+ // Incorrect Usage.
//
// NAME:
// tune - Adjust instance count, RAM commitment, or RAM threshold for a service.
@@ -1524,7 +1524,7 @@ func ExampleServiceCLI_CmdServiceTune_noservice() {
func ExampleServiceCLI_CmdServiceTune_nokwargs() {
pipeStderr(func() { InitServiceAPITest("serviced", "service", "tune", "test-service-1") })
// Output:
- // Incorrect Usage
+ // Incorrect Usage.
//
// NAME:
// tune - Adjust instance count, RAM commitment, or RAM threshold for a service.
|
ZING-<I>: Unit test adjustments
|
control-center_serviced
|
train
|
4c4aed49b3575589c21dbe7e0887bc24e29ebf48
|
diff --git a/bounces.go b/bounces.go
index <HASH>..<HASH> 100644
--- a/bounces.go
+++ b/bounces.go
@@ -12,31 +12,31 @@ import (
"time"
)
-type BounceItem struct {
+type Bounce struct {
CreatedAt string `json:"created_at"`
Code string `json:"code"`
Address string `json:"address"`
Error string `json:"error"`
}
-type Bounces struct {
- TotalCount int `json:"total_count"`
- Items []BounceItem `json:"items"`
+type BounceEnvelope struct {
+ TotalCount int `json:"total_count"`
+ Items []Bounce `json:"items"`
}
type singleBounce struct {
- Bounce BounceItem `json:"bounce"`
+ Bounce Bounce `json:"bounce"`
}
-func (i BounceItem) GetCreatedAt() (t time.Time, err error) {
+func (i Bounce) GetCreatedAt() (t time.Time, err error) {
t, err = time.Parse("Mon, 2 Jan 2006 15:04:05 MST", i.CreatedAt)
return
}
-func (m *mailgunImpl) GetBounces(limit, skip int) (Bounces, error) {
+func (m *mailgunImpl) GetBounces(limit, skip int) (int, []Bounce, error) {
u, err := url.Parse(generateApiUrl(m, bouncesEndpoint))
if err != nil {
- return Bounces{}, err
+ return -1, nil, err
}
q := u.Query()
@@ -50,65 +50,65 @@ func (m *mailgunImpl) GetBounces(limit, skip int) (Bounces, error) {
req, err := http.NewRequest("GET", u.String(), nil)
if err != nil {
- return Bounces{}, err
+ return -1, nil, err
}
req.SetBasicAuth(basicAuthUser, m.ApiKey())
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
- return Bounces{}, err
+ return -1, nil, err
}
if resp.StatusCode != http.StatusOK {
- return Bounces{}, errors.New(fmt.Sprintf("Status is not 200. It was %d", resp.StatusCode))
+ return -1, nil, errors.New(fmt.Sprintf("Status is not 200. It was %d", resp.StatusCode))
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
- return Bounces{}, err
+ return -1, nil, err
}
- var response Bounces
+ var response BounceEnvelope
err2 := json.Unmarshal(body, &response)
if err2 != nil {
- return Bounces{}, err2
+ return -1, nil, err2
}
- return response, nil
+ return response.TotalCount, response.Items, nil
}
-func (m *mailgunImpl) GetSingleBounce(address string) (BounceItem, error) {
+func (m *mailgunImpl) GetSingleBounce(address string) (Bounce, error) {
u, err := url.Parse(generateApiUrl(m, bouncesEndpoint) + "/" + address)
if err != nil {
- return BounceItem{}, err
+ return Bounce{}, err
}
req, err := http.NewRequest("GET", u.String(), nil)
if err != nil {
- return BounceItem{}, err
+ return Bounce{}, err
}
req.SetBasicAuth(basicAuthUser, m.ApiKey())
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
- return BounceItem{}, err
+ return Bounce{}, err
}
if resp.StatusCode != http.StatusOK {
- return BounceItem{}, errors.New(fmt.Sprintf("Status is not 200. It was %d", resp.StatusCode))
+ return Bounce{}, errors.New(fmt.Sprintf("Status is not 200. It was %d", resp.StatusCode))
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
- return BounceItem{}, err
+ return Bounce{}, err
}
var response singleBounce
err2 := json.Unmarshal(body, &response)
if err2 != nil {
- return BounceItem{}, err2
+ return Bounce{}, err2
}
return response.Bounce, nil
diff --git a/mailgun.go b/mailgun.go
index <HASH>..<HASH> 100644
--- a/mailgun.go
+++ b/mailgun.go
@@ -26,8 +26,8 @@ type Mailgun interface {
SendMessage(m *MailgunMessage) (SendMessageResponse, error)
ValidateEmail(email string) (EmailVerification, error)
ParseAddresses(addresses ...string) ([]string, []string, error)
- GetBounces(limit, skip int) (Bounces, error)
- GetSingleBounce(address string) (BounceItem, error)
+ GetBounces(limit, skip int) (int, []Bounce, error)
+ GetSingleBounce(address string) (Bounce, error)
AddBounce(address, code, error string) error
DeleteBounce(address string) error
}
|
Changed some struct to be more Go-like.
|
mailgun_mailgun-go
|
train
|
44c7aa5ab99bba77e4f2af9b5aa974563e08345f
|
diff --git a/lib/index.js b/lib/index.js
index <HASH>..<HASH> 100644
--- a/lib/index.js
+++ b/lib/index.js
@@ -3,7 +3,6 @@
*/
var utf8 = require('utf8');
-var hasBinary = require('has-binary');
var after = require('after');
var keys = require('./keys');
@@ -227,7 +226,7 @@ exports.encodePayload = function (packets, supportsBinary, callback) {
supportsBinary = null;
}
- if (supportsBinary && hasBinary(packets)) {
+ if (supportsBinary) {
return exports.encodePayloadAsBinary(packets, callback);
}
diff --git a/test/browser/index.js b/test/browser/index.js
index <HASH>..<HASH> 100644
--- a/test/browser/index.js
+++ b/test/browser/index.js
@@ -9,3 +9,21 @@ if (Blob) {
}
require('./base64_object.js');
+
+// General browser only tests
+var parser = require('../../');
+var encode = parser.encodePacket;
+var decode = parser.decodePacket;
+var encPayload = parser.encodePayload;
+var decPayload = parser.decodePayload;
+
+describe('basic functionality', function () {
+ it('should encode string payloads as strings even if binary supported', function (done) {
+ encPayload([{ type: 'ping' }, { type: 'post' }], true, function(data) {
+ expect(data).to.be.a('string');
+ done();
+ });
+ });
+});
+
+
diff --git a/test/parser.js b/test/parser.js
index <HASH>..<HASH> 100644
--- a/test/parser.js
+++ b/test/parser.js
@@ -153,15 +153,6 @@ module.exports = function(parser) {
});
});
- describe('basic functionality', function () {
- it('should encode string payloads as strings even if binary supported', function (done) {
- encPayload([{ type: 'ping' }, { type: 'post' }], true, function(data) {
- expect(data).to.be.a('string');
- done();
- });
- });
- });
-
describe('encoding and decoding', function () {
var seen = 0;
it('should encode/decode packets', function (done) {
|
Fix parse error
We always need to send binary when encoding payloads when sending from
server to client, because the polling transport has to know the response
type ahead of time.
|
socketio_engine.io-parser
|
train
|
b2c6eb0f484b076f9d6977eb9d78d4362cacd960
|
diff --git a/jsx-translator.js b/jsx-translator.js
index <HASH>..<HASH> 100644
--- a/jsx-translator.js
+++ b/jsx-translator.js
@@ -137,6 +137,7 @@ assertion:
list (with rep) of capitalized component names must be the same in original and translated
TODO:
+- Bail out if the translation has non-safe attributes; refactor attribute functions.
- spread attribute
- namespace names and member names
- If an expression is just an identifier, then the identifier can be the name by default.
|
Added to todo list.
|
drd_jsxlate
|
train
|
feb1cf91ea2b2ec1c3b4667d8e94cdb4f8ee117f
|
diff --git a/pygsp/graphs/graph.py b/pygsp/graphs/graph.py
index <HASH>..<HASH> 100644
--- a/pygsp/graphs/graph.py
+++ b/pygsp/graphs/graph.py
@@ -130,7 +130,7 @@ class Graph(fourier.GraphFourier, difference.GraphDifference):
def to_networkx(self):
r"""Export the graph to an `Networkx <https://networkx.github.io>`_ object
- The weight are stored as an edge attribute under named `weight`
+ The weights are stored as an edge attribute under the name `weight`.
The signals are stored as node attributes under the name given when
adding them with :meth:`set_signal`.
|
Update pygsp/graphs/graph.py
accept change
|
epfl-lts2_pygsp
|
train
|
51f91f89f6f80e6f4b737605871eb6faef7f25f8
|
diff --git a/docs/plugins.md b/docs/plugins.md
index <HASH>..<HASH> 100644
--- a/docs/plugins.md
+++ b/docs/plugins.md
@@ -125,10 +125,6 @@ end
This will return a class and cache the client object accordingly if caching is enabled. You can call this from a inspec resource by calling `inspec.backend.aws_client(AWS::TEST::CLASS)`.
-#### local?
-
-This flag helps Train decide what detection to use for OS based platforms. This should be set to `true` if your transport target resides in the same instance you are running train from. This setting is not needed for API transports or transports that do not use platform detection.
-
#### platform
`platform` is called when InSpec is trying to detect the platform (OS family, etc). We recommend that you implement platform in a separate Module, and include it.
diff --git a/examples/plugins/train-local-rot13/lib/train-local-rot13/connection.rb b/examples/plugins/train-local-rot13/lib/train-local-rot13/connection.rb
index <HASH>..<HASH> 100644
--- a/examples/plugins/train-local-rot13/lib/train-local-rot13/connection.rb
+++ b/examples/plugins/train-local-rot13/lib/train-local-rot13/connection.rb
@@ -49,11 +49,6 @@ module TrainPlugins
# credentials, now is a good time.
end
- # If you are writing a local-style connection, implement this to return true.
- def local?
- true
- end
-
# Filesystem access.
# If your plugin is for an API, don't implement this.
# If your plugin supports reading files, you'll need to implement this.
diff --git a/examples/plugins/train-local-rot13/test/unit/connection_test.rb b/examples/plugins/train-local-rot13/test/unit/connection_test.rb
index <HASH>..<HASH> 100644
--- a/examples/plugins/train-local-rot13/test/unit/connection_test.rb
+++ b/examples/plugins/train-local-rot13/test/unit/connection_test.rb
@@ -30,16 +30,10 @@ describe TrainPlugins::LocalRot13::Connection do
[
:file_via_connection,
:run_command_via_connection,
- :local?,
].each do |method_name|
it "should provide a #{method_name}() method" do
# false passed to instance_methods says 'don't use inheritance'
connection_class.instance_methods(false).must_include(method_name)
end
end
-
- # Ensure Train knows this is local.
- it "should declare itself as a local transport" do
- connection_class.new(Hash.new).local?.must_equal(true)
- end
end
diff --git a/lib/train/platforms/detect/specifications/os.rb b/lib/train/platforms/detect/specifications/os.rb
index <HASH>..<HASH> 100644
--- a/lib/train/platforms/detect/specifications/os.rb
+++ b/lib/train/platforms/detect/specifications/os.rb
@@ -17,9 +17,15 @@ module Train::Platforms::Detect::Specifications
plat.family('windows').in_family('os')
.detect {
- if winrm? || (@backend.local? && ruby_host_os(/mswin|mingw32|windows/))
- true
+ # Can't return from a `proc` thus the `is_windows` shenanigans
+ is_windows = false
+ is_windows = true if winrm?
+
+ if @backend.class.to_s == 'Train::Transports::Local::Connection'
+ is_windows = true if ruby_host_os(/mswin|mingw32|windows/)
end
+
+ is_windows
}
# windows platform
plat.name('windows').in_family('windows')
diff --git a/lib/train/plugins/base_connection.rb b/lib/train/plugins/base_connection.rb
index <HASH>..<HASH> 100644
--- a/lib/train/plugins/base_connection.rb
+++ b/lib/train/plugins/base_connection.rb
@@ -91,11 +91,6 @@ class Train::Plugins::Transport
end
end
- # Is this a local transport?
- def local?
- false
- end
-
def force_platform!(name, platform_details = nil)
plat = Train::Platforms.name(name)
plat.backend = self
diff --git a/lib/train/transports/local.rb b/lib/train/transports/local.rb
index <HASH>..<HASH> 100644
--- a/lib/train/transports/local.rb
+++ b/lib/train/transports/local.rb
@@ -28,10 +28,6 @@ module Train::Transports
end
end
- def local?
- true
- end
-
def login_command
nil # none, open your shell
end
diff --git a/lib/train/transports/vmware.rb b/lib/train/transports/vmware.rb
index <HASH>..<HASH> 100644
--- a/lib/train/transports/vmware.rb
+++ b/lib/train/transports/vmware.rb
@@ -69,10 +69,6 @@ module Train::Transports
end
end
- def local?
- true
- end
-
def platform
force_platform!('vmware', @platform_details)
end
diff --git a/test/fixtures/plugins/train-test-fixture/lib/train-test-fixture/connection.rb b/test/fixtures/plugins/train-test-fixture/lib/train-test-fixture/connection.rb
index <HASH>..<HASH> 100644
--- a/test/fixtures/plugins/train-test-fixture/lib/train-test-fixture/connection.rb
+++ b/test/fixtures/plugins/train-test-fixture/lib/train-test-fixture/connection.rb
@@ -10,10 +10,6 @@ module TrainPlugins
super(options)
end
- def local?
- true
- end
-
private
def run_command_via_connection(cmd)
diff --git a/test/unit/transports/vmware_test.rb b/test/unit/transports/vmware_test.rb
index <HASH>..<HASH> 100644
--- a/test/unit/transports/vmware_test.rb
+++ b/test/unit/transports/vmware_test.rb
@@ -127,12 +127,6 @@ describe 'Train::Transports::VMware::Connection' do
end
end
- describe '#local' do
- it 'returns true' do
- create_transport.connection.local?.must_equal true
- end
- end
-
describe '#platform' do
it 'returns correct platform details' do
platform = create_transport.connection.platform
|
Remove `#local?` (#<I>)
* Remove `#local?`
It was used only once and provides more confusion than benefit.
* Respond to feedback
|
inspec_train
|
train
|
19afbefde4fa8ab2e55822c3e8ea3f3252b642b0
|
diff --git a/spline/tools/adapter.py b/spline/tools/adapter.py
index <HASH>..<HASH> 100644
--- a/spline/tools/adapter.py
+++ b/spline/tools/adapter.py
@@ -42,7 +42,7 @@ class Adapter(object):
else:
try:
value = getattr(self.data, key)
- except AttributeError as _:
+ except AttributeError:
value = None
return value
diff --git a/tests/tools/test_adapter.py b/tests/tools/test_adapter.py
index <HASH>..<HASH> 100644
--- a/tests/tools/test_adapter.py
+++ b/tests/tools/test_adapter.py
@@ -1,7 +1,7 @@
"""Testing of module adapter."""
# pylint: disable=no-self-use, invalid-name
import unittest
-from hamcrest import assert_that, equal_to, calling, raises
+from hamcrest import assert_that, equal_to
from spline.tools.adapter import Adapter
|
#<I>: missing 'variables' for templating in 'docker(image)' task (fixed other style issues)
|
Nachtfeuer_pipeline
|
train
|
4cd445253e42eb21bfce401f05b2201ecf87e7dc
|
diff --git a/src/basis/ui/paginator.js b/src/basis/ui/paginator.js
index <HASH>..<HASH> 100644
--- a/src/basis/ui/paginator.js
+++ b/src/basis/ui/paginator.js
@@ -257,7 +257,7 @@
/**
* @param {number} pageCount
*/
- setPageCount: function(pageCount){
+ setPageCount: function(pageCount, spotlight){
pageCount = resolveValue(this, this.setPageCount, pageCount, 'pageCountRA_');
var newPageCount = Number(pageCount) || 0;
@@ -267,20 +267,22 @@
{
// set new value
this.pageCount = newPageCount;
+ this.emit_pageCountChanged(oldPageCount);
// sync
this.syncPages();
- this.updateSelection();
- // emit event
- this.emit_pageCountChanged(oldPageCount);
- }
+ if (spotlight || !this.getActivePageChild())
+ this.spotlightPage(this.activePage);
+
+ this.updateSelection();
+ }
},
/**
* @param {number} pageSpan
*/
- setPageSpan: function(pageSpan){
+ setPageSpan: function(pageSpan, spotlight){
pageSpan = resolveValue(this, this.setPageSpan, pageSpan, 'pageSpanRA_');
var newPageSpan = Math.max(1, pageSpan);
@@ -290,13 +292,15 @@
{
// set new value
this.pageSpan = newPageSpan;
+ this.emit_pageSpanChanged(oldPageSpan);
// sync
this.syncPages();
- this.updateSelection();
- // emit event
- this.emit_pageSpanChanged(oldPageSpan);
+ if (spotlight || !this.getActivePageChild())
+ this.spotlightPage(this.activePage);
+
+ this.updateSelection();
}
},
@@ -353,11 +357,11 @@
if (newSpanStartPage != oldSpanStartPage)
{
this.spanStartPage = newSpanStartPage;
+ this.emit_spanStartPageChanged(oldSpanStartPage);
for (var i = 0, child; child = this.childNodes[i]; i++)
child.setPageNumber(this.pageOffset + this.spanStartPage + i);
-
this.updateSelection();
}
},
|
basis.ui.paginator: fixes
- auto-spotlight on page count or span changes
- add missed spanStartPageChanged event emit
- make consistent event emit place
|
basisjs_basisjs
|
train
|
83bcc1da60847e6ab443287c1fd4e783de2c47c2
|
diff --git a/src/store.js b/src/store.js
index <HASH>..<HASH> 100644
--- a/src/store.js
+++ b/src/store.js
@@ -448,7 +448,7 @@ function setupModel(Model, nested) {
if (key === "id") {
if (Model[key] !== true) {
throw TypeError(
- "The 'id' property in model definition must be set to 'true' or not be defined",
+ "The 'id' property in the model definition must be set to 'true' or not defined",
);
}
return (model, data, lastModel) => {
@@ -874,7 +874,7 @@ function get(Model, id) {
if (config.enumerable) {
stringId = stringifyId(id);
- if (!config.list && !stringId) {
+ if (!stringId && !config.list && !draftMap.get(config)) {
throw TypeError(
stringifyModel(
Model,
@@ -1439,15 +1439,15 @@ function store(Model, options = {}) {
return {
get(host, value) {
const valueConfig = definitions.get(value);
- let id = valueConfig !== undefined ? value.id : value;
+ const id = valueConfig !== undefined ? value.id : value;
- if (!id && options.draft) {
- const draftModel = options.draft.create({});
- syncCache(options.draft, draftModel.id, draftModel, false);
- id = draftModel.id;
+ if (options.draft && (value === undefined || value === null)) {
+ const draftModel = options.draft.create({}, { id: undefined });
+ syncCache(options.draft, undefined, draftModel, false);
+ return get(Model, undefined);
}
- return id ? get(Model, id) : undefined;
+ return value ? get(Model, id) : undefined;
},
set: (_, v) => v,
};
@@ -1455,14 +1455,16 @@ function store(Model, options = {}) {
return {
get: (host, value) => {
- let id = (options.id && options.id(host)) || (value && value.id);
+ const id = (options.id && options.id(host)) || (value && value.id);
- if (!id && !value && options.draft) {
+ if (options.draft && !id && (value === undefined || value === null)) {
const draftModel = options.draft.create({});
- syncCache(options.draft, draftModel.id, draftModel, false);
- id = draftModel.id;
+ syncCache(options.draft, undefined, draftModel, false);
+ return get(Model, undefined);
}
+ if (config.enumerable && id === undefined) return undefined;
+
const nextValue = get(Model, id);
if (nextValue !== value && ready(value) && !ready(nextValue)) {
diff --git a/test/spec/store.js b/test/spec/store.js
index <HASH>..<HASH> 100644
--- a/test/spec/store.js
+++ b/test/spec/store.js
@@ -1196,6 +1196,7 @@ describe("store:", () => {
define({
tag: "test-store-factory-enumerable",
modelId: "1",
+ byundefined: store(Model, { id: () => undefined }),
byprop: store(Model, { id: "modelId" }),
byfn: store(Model, { id: ({ modelId }) => modelId }),
withoutid: store(Model),
@@ -1216,6 +1217,10 @@ describe("store:", () => {
}).toThrow();
});
+ it("returns undefined when id resolves to undefined", () => {
+ expect(el.byundefined).toBe(undefined);
+ });
+
it("gets and updates store model instance", () => {
let pendingModel = el.byprop;
expect(store.pending(pendingModel)).toBeTruthy();
|
fix(store): factory with id resolving to undefined, draft models without id
|
hybridsjs_hybrids
|
train
|
1c8a2f232bbe66cce3d0915b7f91d5b1ad16b100
|
diff --git a/cake/libs/model/model.php b/cake/libs/model/model.php
index <HASH>..<HASH> 100644
--- a/cake/libs/model/model.php
+++ b/cake/libs/model/model.php
@@ -1948,7 +1948,6 @@ class Model extends Overloadable {
list($type, $query) = array($conditions, $fields);
}
- $db =& ConnectionManager::getDataSource($this->useDbConfig);
$this->findQueryType = $type;
$this->id = $this->getID();
@@ -1995,6 +1994,9 @@ class Model extends Overloadable {
}
}
+ if (!$db =& ConnectionManager::getDataSource($this->useDbConfig)) {
+ return false;
+ }
$results = $db->read($this, $query);
$this->resetAssociations();
$this->findQueryType = null;
diff --git a/cake/tests/cases/libs/model/model_read.test.php b/cake/tests/cases/libs/model/model_read.test.php
index <HASH>..<HASH> 100644
--- a/cake/tests/cases/libs/model/model_read.test.php
+++ b/cake/tests/cases/libs/model/model_read.test.php
@@ -4899,6 +4899,23 @@ class ModelReadTest extends BaseModelTest {
$expected = array('mariano', 'nate', 'larry', 'garrett');
$this->assertEqual($result, $expected);
}
+
+ /**
+ * Tests that the database configuration assigned to the model can be changed using
+ * (before|after)Find callbacks
+ *
+ * @return void
+ */
+ function testCallbackSourceChange() {
+ $this->loadFixtures('Post');
+ $TestModel = new Post();
+ $this->assertEqual(3, count($TestModel->find('all')));
+
+ $this->expectError(new PatternExpectation('/Non-existent data source foo/i'));
+ $this->expectError(new PatternExpectation('/Only variable references/i'));
+ $this->assertFalse($TestModel->find('all', array('connection' => 'foo')));
+ }
+
/**
* testMultipleBelongsToWithSameClass method
*
diff --git a/cake/tests/cases/libs/model/models.php b/cake/tests/cases/libs/model/models.php
index <HASH>..<HASH> 100644
--- a/cake/tests/cases/libs/model/models.php
+++ b/cake/tests/cases/libs/model/models.php
@@ -763,6 +763,18 @@ class Post extends CakeTestModel {
* @access public
*/
var $belongsTo = array('Author');
+
+ function beforeFind($queryData) {
+ if (isset($queryData['connection'])) {
+ $this->useDbConfig = $queryData['connection'];
+ }
+ return true;
+ }
+
+ function afterFind($results) {
+ $this->useDbConfig = 'test_suite';
+ return $results;
+ }
}
/**
* Author class
|
Changes Model::find() to allow modification of DataSource connection during callbacks.
|
cakephp_cakephp
|
train
|
8a109e061b4815b778129ab2e4b877e9e02a9228
|
diff --git a/promql/engine.go b/promql/engine.go
index <HASH>..<HASH> 100644
--- a/promql/engine.go
+++ b/promql/engine.go
@@ -595,6 +595,9 @@ func (ev *evaluator) eval(expr Expr) Value {
if e.Op == itemLAND {
return ev.vectorAnd(lhs.(Vector), rhs.(Vector), e.VectorMatching)
}
+ if e.Op == itemLOR {
+ return ev.vectorOr(lhs.(Vector), rhs.(Vector), e.VectorMatching)
+ }
return ev.vectorBinop(e.Op, lhs.(Vector), rhs.(Vector), e.VectorMatching)
case lt == ExprVector && rt == ExprScalar:
@@ -733,6 +736,37 @@ func (ev *evaluator) vectorAnd(lhs, rhs Vector, matching *VectorMatching) Vector
return result
}
+func (ev *evaluator) vectorOr(lhs, rhs Vector, matching *VectorMatching) Vector {
+ if matching.Card != CardManyToMany {
+ panic("logical operations must always be many-to-many matching")
+ }
+ // If no matching labels are specified, match by all labels.
+ signature := func(m clientmodel.COWMetric) uint64 {
+ return clientmodel.SignatureForLabels(m.Metric, matching.On)
+ }
+ if len(matching.On) == 0 {
+ signature = func(m clientmodel.COWMetric) uint64 {
+ m.Delete(clientmodel.MetricNameLabel)
+ return uint64(m.Metric.Fingerprint())
+ }
+ }
+
+ var result Vector
+ leftSigs := map[uint64]struct{}{}
+ // Add everything from the left-hand-side vector.
+ for _, ls := range lhs {
+ leftSigs[signature(ls.Metric)] = struct{}{}
+ result = append(result, ls)
+ }
+ // Add all right-hand side elements which have not been added from the left-hand side.
+ for _, rs := range rhs {
+ if _, ok := leftSigs[signature(rs.Metric)]; !ok {
+ result = append(result, rs)
+ }
+ }
+ return result
+}
+
// vectorBinop evaluates a binary operation between two vector values.
func (ev *evaluator) vectorBinop(op itemType, lhs, rhs Vector, matching *VectorMatching) Vector {
result := make(Vector, 0, len(rhs))
@@ -755,7 +789,7 @@ func (ev *evaluator) vectorBinop(op itemType, lhs, rhs Vector, matching *VectorM
// The rhs is guaranteed to be the 'one' side. Having multiple samples
// with the same hash means that the matching is many-to-many,
// which is not supported.
- if _, found := rm[hash]; matching.Card != CardManyToMany && found {
+ if _, found := rm[hash]; found {
// Many-to-many matching not allowed.
ev.errorf("many-to-many matching not allowed")
}
@@ -768,13 +802,6 @@ func (ev *evaluator) vectorBinop(op itemType, lhs, rhs Vector, matching *VectorM
// the binary operation.
for _, ls := range lhs {
hash := hashForMetric(ls.Metric.Metric, matching.On)
- // Any lhs sample we encounter in an OR operation belongs to the result.
- if op == itemLOR {
- ls.Metric = resultMetric(op, ls, nil, matching)
- result = append(result, ls)
- added[hash] = nil // Ensure matching rhs sample is not added later.
- continue
- }
rs, found := rm[hash] // Look for a match in the rhs vector.
if !found {
@@ -820,16 +847,6 @@ func (ev *evaluator) vectorBinop(op itemType, lhs, rhs Vector, matching *VectorM
}
}
- // Add all remaining samples in the rhs in an OR operation if they
- // have not been matched up with a lhs sample.
- if op == itemLOR {
- for hash, rs := range rm {
- if _, exists := added[hash]; !exists {
- rs.Metric = resultMetric(op, rs, nil, matching)
- result = append(result, rs)
- }
- }
- }
return result
}
|
Extract OR operation into own eval method.
|
prometheus_prometheus
|
train
|
3443b63bd41a75839ebc1cded472acf91fe87c11
|
diff --git a/rejected/__init__.py b/rejected/__init__.py
index <HASH>..<HASH> 100644
--- a/rejected/__init__.py
+++ b/rejected/__init__.py
@@ -4,7 +4,7 @@ Rejected is a Python RabbitMQ Consumer Framework and Controller Daemon
"""
__author__ = 'Gavin M. Roy <gavinmroy@gmail.com>'
__since__ = '2009-09-10'
-__version__ = '3.16.4'
+__version__ = '3.16.5'
import logging
from logging import NullHandler
diff --git a/rejected/consumer.py b/rejected/consumer.py
index <HASH>..<HASH> 100644
--- a/rejected/consumer.py
+++ b/rejected/consumer.py
@@ -679,31 +679,31 @@ class Consumer(object):
except exceptions.ChannelClosed as error:
self.logger.critical('Channel closed while processing %s: %s',
message_in.delivery_tag, error)
- self._measurement.set_tag('error', str(error))
+ self._measurement.set_tag('exception', error.__class__.__name__)
raise gen.Return(None)
except exceptions.ConnectionClosed as error:
self.logger.critical('Connection closed while processing %s: %s',
message_in.delivery_tag, error)
- self._measurement.set_tag('error', str(error))
+ self._measurement.set_tag('exception', error.__class__.__name__)
raise gen.Return(None)
except ConsumerException as error:
self.logger.error('ConsumerException processing delivery %s: %s',
message_in.delivery_tag, error)
- self._measurement.set_tag('error', str(error))
+ self._measurement.set_tag('exception', error.__class__.__name__)
raise gen.Return(data.CONSUMER_EXCEPTION)
except MessageException as error:
self.logger.debug('MessageException processing delivery %s: %s',
message_in.delivery_tag, error)
- self._measurement.set_tag('error', str(error))
+ self._measurement.set_tag('exception', error.__class__.__name__)
raise gen.Return(data.MESSAGE_EXCEPTION)
except ProcessingException as error:
self.logger.debug('ProcessingException processing delivery %s: %s',
message_in.delivery_tag, error)
- self._measurement.set_tag('error', str(error))
+ self._measurement.set_tag('exception', error.__class__.__name__)
self._republish_processing_error()
raise gen.Return(data.PROCESSING_EXCEPTION)
@@ -715,7 +715,7 @@ class Consumer(object):
self.log_exception('Exception processing delivery %s: %s',
message_in.delivery_tag, error,
exc_info=exc_info)
- self._measurement.set_tag('error', str(error))
+ self._measurement.set_tag('exception', error.__class__.__name__)
raise gen.Return(data.UNHANDLED_EXCEPTION)
if not self._finished:
diff --git a/setup.py b/setup.py
index <HASH>..<HASH> 100644
--- a/setup.py
+++ b/setup.py
@@ -1,7 +1,7 @@
from setuptools import setup
setup(name='rejected',
- version='3.16.4',
+ version='3.16.5',
description='Rejected is a Python RabbitMQ Consumer Framework and '
'Controller Daemon',
long_description=open('README.rst').read(),
|
The str(error) causes issues with Influx
|
gmr_rejected
|
train
|
d4490b3e14cef78ad63559df3d8bf316723e25ee
|
diff --git a/lib/reporters/tap.js b/lib/reporters/tap.js
index <HASH>..<HASH> 100644
--- a/lib/reporters/tap.js
+++ b/lib/reporters/tap.js
@@ -25,10 +25,10 @@ function TAP(runner) {
var self = this
, stats = this.stats
- , total = runner.total
, n = 1;
runner.on('start', function(){
+ var total = runner.grepTotal(runner.suite);
console.log('%d..%d', 1, total);
});
|
Fix to TAP output when grep is used to filter out tests: these tests should not contribute to the overall total in the TAP plan.
|
mochajs_mocha
|
train
|
9ab3d5e6461862d76ca5e53f179eeda2152bcf54
|
diff --git a/core/model/DataObject.php b/core/model/DataObject.php
index <HASH>..<HASH> 100644
--- a/core/model/DataObject.php
+++ b/core/model/DataObject.php
@@ -734,14 +734,13 @@ class DataObject extends Controller implements DataObjectInterface {
* @param string $sort A sort expression to be inserted into the ORDER BY clause. If omitted, the static field $default_sort on the component class will be used.
* @param string $join A single join clause. This can be used for filtering, only 1 instance of each DataObject will be returned.
* @param string $limit A limit expression to be inserted into the LIMIT clause
- * @param string $having A filter to be inserted into the HAVING clause
*
* @return ComponentSet The components of the one-to-many relationship.
*/
- public function getComponents($componentName, $filter = "", $sort = "", $join = "", $limit = "", $having = "") {
+ public function getComponents($componentName, $filter = "", $sort = "", $join = "", $limit = "") {
$result = null;
- $sum = md5("{$filter}_{$sort}_{$join}_{$limit}_{$having}");
+ $sum = md5("{$filter}_{$sort}_{$join}_{$limit}");
if(isset($this->componentCache[$componentName . '_' . $sum]) && false != $this->componentCache[$componentName . '_' . $sum]) {
return $this->componentCache[$componentName . '_' . $sum];
}
@@ -760,7 +759,7 @@ class DataObject extends Controller implements DataObjectInterface {
$combinedFilter = "$joinField = '$id'";
if($filter) $combinedFilter .= " AND {$filter}";
- $result = $componentObj->instance_get($combinedFilter, $sort, $join, $limit, "ComponentSet", $having);
+ $result = $componentObj->instance_get($combinedFilter, $sort, $join, $limit, "ComponentSet");
}
if(!$result) {
@@ -1432,12 +1431,11 @@ class DataObject extends Controller implements DataObjectInterface {
* @param string $join A single join clause. This can be used for filtering, only 1 instance of each DataObject will be returned.
* @param string $limit A limit expression to be inserted into the LIMIT clause.
* @param string $containerClass The container class to return the results in.
- * @param string $having A filter to be inserted into the HAVING clause.
*
* @return mixed The objects matching the filter, in the class specified by $containerClass
*/
- public static function get($callerClass, $filter = "", $sort = "", $join = "", $limit = "", $containerClass = "DataObjectSet", $having = "") {
- return singleton($callerClass)->instance_get($filter, $sort, $join, $limit, $containerClass, $having);
+ public static function get($callerClass, $filter = "", $sort = "", $join = "", $limit = "", $containerClass = "DataObjectSet") {
+ return singleton($callerClass)->instance_get($filter, $sort, $join, $limit, $containerClass);
}
/**
@@ -1449,12 +1447,11 @@ class DataObject extends Controller implements DataObjectInterface {
* @param string $join A single join clause. This can be used for filtering, only 1 instance of each DataObject will be returned.
* @param string $limit A limit expression to be inserted into the LIMIT clause.
* @param string $containerClass The container class to return the results in.
- * @param string $having A filter to be inserted into the HAVING clause.
*
* @return mixed The objects matching the filter, in the class specified by $containerClass
*/
- public function instance_get($filter = "", $sort = "", $join = "", $limit="", $containerClass = "DataObjectSet", $having = "") {
- $query = $this->extendedSQL($filter, $sort, $limit, $join, $having);
+ public function instance_get($filter = "", $sort = "", $join = "", $limit="", $containerClass = "DataObjectSet") {
+ $query = $this->extendedSQL($filter, $sort, $limit, $join);
$records = $query->execute();
$ret = $this->buildDataObjectSet($records, $containerClass, $query, $this->class);
|
Remove HAVING clause from methods where it doesn't make sense to have them
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
|
16d09d32a68a4124497964923f4febcc13bfd698
|
diff --git a/estnltk/layer_operations/splitting.py b/estnltk/layer_operations/splitting.py
index <HASH>..<HASH> 100644
--- a/estnltk/layer_operations/splitting.py
+++ b/estnltk/layer_operations/splitting.py
@@ -85,6 +85,17 @@ def extract_sections(text: Text,
elif span_start < start or end < span_end:
continue
spans = []
+ # If the section is in a gap between two discontinuous
+ # spans, then it should be skipped ...
+ section_inside_gap = False
+ for sid, s in enumerate( span ):
+ if sid+1 < len( span ):
+ next_s = span[sid+1]
+ if s.end <= start and end <= next_s.start:
+ section_inside_gap = True
+ break
+ if section_inside_gap:
+ continue
for s in span:
parent = map_spans.get((s.base_span, s.layer.name))
if parent:
diff --git a/estnltk/tests/test_layer_operations/test_splitting.py b/estnltk/tests/test_layer_operations/test_splitting.py
index <HASH>..<HASH> 100644
--- a/estnltk/tests/test_layer_operations/test_splitting.py
+++ b/estnltk/tests/test_layer_operations/test_splitting.py
@@ -1,5 +1,10 @@
from estnltk import Text, Layer
+
+from estnltk.converters import layer_to_dict
+from estnltk.converters import dict_to_layer
+
from estnltk.layer_operations import split_by_sentences, extract_sections
+from estnltk.layer_operations import split_by
def test_extract_sections():
@@ -49,3 +54,34 @@ def test_split_by_sentences():
assert ['Teine', 'lõik', '.'] == text_1.paragraphs.text
assert ['Teine', 'lõik', '.'] == text_1.morph_analysis.text
assert ['Teine', 'lõik', '.'] == text_1.morph_extended.text
+
+
+def test_split_by_clauses__fix_empty_spans_error():
+ # Tests that split_by_clauses trim_overlapping=True
+ # does not rise "ValueError: spans is empty"
+ text = Text('Mees, keda kohtasime, oli tuttav.')
+ text.tag_layer(['words', 'sentences', 'morph_analysis'])
+ #from pprint import pprint
+ #pprint(layer_to_dict(text['clauses']))
+ clauses_layer_dict = \
+ {'ambiguous': False,
+ 'attributes': ('clause_type',),
+ 'enveloping': 'words',
+ 'meta': {},
+ 'name': 'clauses',
+ 'parent': None,
+ 'serialisation_module': None,
+ 'spans': [{'annotations': [{'clause_type': 'regular'}],
+ 'base_span': ((0, 4), (22, 25), (26, 32), (32, 33))},
+ {'annotations': [{'clause_type': 'embedded'}],
+ 'base_span': ((4, 5), (6, 10), (11, 20), (20, 21))}]}
+ text.add_layer( dict_to_layer(clauses_layer_dict) )
+ clause_texts = split_by(text, 'clauses',
+ layers_to_keep=list(text.layers),
+ trim_overlapping=True)
+ assert len(clause_texts) == len(text['clauses'])
+ assert clause_texts[0].words.text == ['Mees', ',', 'keda', 'kohtasime', ',', 'oli', 'tuttav', '.'] # <-- Note: this is wrong, needs fixing in future ...
+ assert clause_texts[1].words.text == [',', 'keda', 'kohtasime', ',']
+
+
+
|
Fixed extract_sections: now it should work with discontinouos spans & trim_overlapping=True
|
estnltk_estnltk
|
train
|
fd5b955466d2ef558c5fa83c7bc5f2ecc48f7e44
|
diff --git a/app/controllers/rails_db/tables_controller.rb b/app/controllers/rails_db/tables_controller.rb
index <HASH>..<HASH> 100755
--- a/app/controllers/rails_db/tables_controller.rb
+++ b/app/controllers/rails_db/tables_controller.rb
@@ -41,5 +41,10 @@ module RailsDb
end
end
+ def xlsx
+ @table = RailsDb::Table.new(params[:table_id])
+ render xlsx: "table", filename: "#{@table.name}.xlsx"
+ end
+
end
end
\ No newline at end of file
|
TablesController renders Excel file
|
igorkasyanchuk_rails_db
|
train
|
43455cc4098cdedc6699237d594723ae28718766
|
diff --git a/lib/plugin/components/services/users/index.js b/lib/plugin/components/services/users/index.js
index <HASH>..<HASH> 100644
--- a/lib/plugin/components/services/users/index.js
+++ b/lib/plugin/components/services/users/index.js
@@ -28,45 +28,35 @@ class UsersService {
* }
* )
*/
- getUserRoles (userId) {
- return new Promise((resolve, reject) => this._getUserRoles(userId, (err, roles) => {
- if (err) reject(err)
- else resolve(roles)
- }))
- }
+ async getUserRoles (userId) {
+ const cachedRoles = this.userMembershipsCache.get(userId)
+ if (Array.isArray(cachedRoles)) return cachedRoles
+
+ return this.findAndCacheRoles(userId)
+ } // getUserRoles
- _getUserRoles (userId, callback) {
- let cachedRoles = this.userMembershipsCache.get(userId)
+ async findAndCacheRoles (userId) {
+ let roles = await this.roleMembershipModel.find({
+ where: {
+ memberType: {equals: 'user'},
+ memberId: {equals: userId}
+ }
+ })
- if (Array.isArray(cachedRoles)) {
- callback(null, cachedRoles)
- } else {
- this.roleMembershipModel.find(
- {
- where: {
- memberType: {equals: 'user'},
- memberId: {equals: userId}
- }
- },
- (err, roles) => {
- if (err) return callback(err)
- cachedRoles = _.uniq(_.map(roles, 'roleId'))
+ roles = _.uniq(_.map(roles, 'roleId'))
+ const inhertiedRoles = ['$everyone']
- const inhertiedRoles = ['$everyone']
- cachedRoles.map(roleId => {
- Object.keys(this.rbac.rbac.inherits).map(inheritedBy => {
- if (this.rbac.rbac.inherits[inheritedBy].includes(roleId)) {
- inhertiedRoles.push(inheritedBy)
- }
- })
- })
- cachedRoles = _.uniq(cachedRoles.concat(inhertiedRoles))
- this.userMembershipsCache.set(userId, cachedRoles)
- callback(null, cachedRoles)
+ roles.map(roleId => {
+ Object.keys(this.rbac.rbac.inherits).map(inheritedBy => {
+ if (this.rbac.rbac.inherits[inheritedBy].includes(roleId)) {
+ inhertiedRoles.push(inheritedBy)
}
- )
- }
- }
+ })
+ })
+ roles = _.uniq(roles.concat(inhertiedRoles))
+ this.userMembershipsCache.set(userId, roles)
+ return roles
+ } // getUserRoles
/**
* Resets the internal cache of users and their roles. Needs calling if things change in the tymly_roleMembership_1_0 model and similar.
|
refactor: user service getUserRoles is now async, rather than simply wrapped in a promise
affects: tymly
|
wmfs_tymly-core
|
train
|
fe51d92748453212298fb0de5a01e8f29d06bde4
|
diff --git a/setup.py b/setup.py
index <HASH>..<HASH> 100755
--- a/setup.py
+++ b/setup.py
@@ -52,7 +52,7 @@ setup(
author = 'Brian May',
author_email = 'brian@vpac.org',
description = 'Collection of Django apps to manage a clusters',
- licence = "GPL3+",
+ license = "GPL3+",
packages = packages,
package_data = {
'': [ '*.css', '*.html', '*.js', '*.png', '*.gif', '*.map', '*.txt' ],
|
Rename licence to license.
Change-Id: Icbb<I>aececa<I>f<I>b7a0bd<I>c6be<I>ff
|
Karaage-Cluster_karaage
|
train
|
e6747a78eb1d2b12a5d3f53b3519ab68b05c8fba
|
diff --git a/DependencyInjection/Configuration.php b/DependencyInjection/Configuration.php
index <HASH>..<HASH> 100644
--- a/DependencyInjection/Configuration.php
+++ b/DependencyInjection/Configuration.php
@@ -89,7 +89,16 @@ class Configuration implements ConfigurationInterface
{
$node = new ArrayNodeDefinition('allow_headers');
- $node->prototype('scalar')->end();
+ $node
+ ->beforeNormalization()
+ ->always(function($v) {
+ if ($v === '*') {
+ return array('*');
+ }
+ return $v;
+ })
+ ->end()
+ ->prototype('scalar')->end();
return $node;
}
diff --git a/DependencyInjection/NelmioCorsExtension.php b/DependencyInjection/NelmioCorsExtension.php
index <HASH>..<HASH> 100644
--- a/DependencyInjection/NelmioCorsExtension.php
+++ b/DependencyInjection/NelmioCorsExtension.php
@@ -49,11 +49,21 @@ class NelmioCorsExtension extends Extension
if (in_array('*', $defaults['allow_origin'])) {
$defaults['allow_origin'] = true;
}
+ if (in_array('*', $defaults['allow_headers'])) {
+ $defaults['allow_headers'] = true;
+ } else {
+ $defaults['allow_headers'] = array_map('strtolower', $defaults['allow_headers']);
+ }
foreach ($config['paths'] as $path => $opts) {
$opts = array_filter($opts);
if (isset($opts['allow_origin']) && in_array('*', $opts['allow_origin'])) {
$opts['allow_origin'] = true;
}
+ if (isset($opts['allow_headers']) && in_array('*', $opts['allow_headers'])) {
+ $opts['allow_headers'] = true;
+ } elseif (isset($opts['allow_headers'])) {
+ $opts['allow_headers'] = array_map('strtolower', $opts['allow_headers']);
+ }
$config['paths'][$path] = $opts;
}
diff --git a/EventListener/CorsListener.php b/EventListener/CorsListener.php
index <HASH>..<HASH> 100644
--- a/EventListener/CorsListener.php
+++ b/EventListener/CorsListener.php
@@ -64,7 +64,6 @@ class CorsListener
foreach ($this->paths as $path => $options) {
if (preg_match('{'.$path.'}i', $currentPath)) {
$options = array_merge($this->defaults, $options);
- $options['allow_headers'] = array_map('strtolower', $options['allow_headers']);
// perform preflight checks
if ('OPTIONS' === $request->getMethod()) {
@@ -114,7 +113,7 @@ class CorsListener
$response->headers->set('Access-Control-Allow-Methods', strtoupper(implode(', ', $options['allow_methods'])));
}
if ($options['allow_headers']) {
- $response->headers->set('Access-Control-Allow-Headers', implode(', ', $options['allow_headers']));
+ $response->headers->set('Access-Control-Allow-Headers', $options['allow_headers'] === true ? $request->headers->get('Access-Control-Request-Headers') : implode(', ', $options['allow_headers']));
}
if ($options['max_age']) {
$response->headers->set('Access-Control-Max-Age', $options['max_age']);
@@ -134,8 +133,9 @@ class CorsListener
}
// check request headers
- $headers = trim(strtolower($request->headers->get('Access-Control-Request-Headers')));
- if ($headers) {
+ $headers = $request->headers->get('Access-Control-Request-Headers');
+ if ($options['allow_headers'] !== true && $headers) {
+ $headers = trim(strtolower($headers));
foreach (preg_split('{, *}', $headers) as $header) {
if (in_array($header, self::$simpleHeaders, true)) {
continue;
diff --git a/README.md b/README.md
index <HASH>..<HASH> 100644
--- a/README.md
+++ b/README.md
@@ -40,6 +40,9 @@ seconds.
allow_methods: ['POST', 'PUT', 'GET', 'DELETE']
max_age: 3600
+`allow_origin` and `allow_headers` can be set to `*` to accept any value, the
+allowed methods however have to be explicitly listed.
+
## Installation (Symfony 2.1+)
Require the `nelmio/cors-bundle` package in your composer.json and update your dependencies.
|
Allow wildcard headers by feeding back the requested headers to the response, fixes #7
|
nelmio_NelmioCorsBundle
|
train
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.