hash
stringlengths 40
40
| diff
stringlengths 131
114k
| message
stringlengths 7
980
| project
stringlengths 5
67
| split
stringclasses 1
value |
|---|---|---|---|---|
bcb2be9b782ef802c583e21d4a4f307e1470a21c
|
diff --git a/js/coinbasepro.js b/js/coinbasepro.js
index <HASH>..<HASH> 100644
--- a/js/coinbasepro.js
+++ b/js/coinbasepro.js
@@ -46,7 +46,7 @@ module.exports = class coinbasepro extends Exchange {
'logo': 'https://user-images.githubusercontent.com/1294454/41764625-63b7ffde-760a-11e8-996d-a6328fa9347a.jpg',
'api': 'https://api.pro.coinbase.com',
'www': 'https://pro.coinbase.com/',
- 'doc': 'https://docs.pro.coinbase.com/',
+ 'doc': 'https://docs.pro.coinbase.com',
'fees': [
'https://docs.pro.coinbase.com/#fees',
'https://support.pro.coinbase.com/customer/en/portal/articles/2945310-fees',
|
coinbasepro minor edit in doc url
|
ccxt_ccxt
|
train
|
4011563e5764990db8bc6dec8020b1f148cfe99d
|
diff --git a/Form/Type/CropImageAjaxType.php b/Form/Type/CropImageAjaxType.php
index <HASH>..<HASH> 100644
--- a/Form/Type/CropImageAjaxType.php
+++ b/Form/Type/CropImageAjaxType.php
@@ -38,6 +38,7 @@ class CropImageAjaxType extends AbstractType
$resolver->setDefaults(
array(
+ 'resolver_key' => 'croped_resolver',
'max_width' => 350,
'max_height' => 350,
'reset_button' => true,
diff --git a/Form/Type/FileAjaxType.php b/Form/Type/FileAjaxType.php
index <HASH>..<HASH> 100644
--- a/Form/Type/FileAjaxType.php
+++ b/Form/Type/FileAjaxType.php
@@ -44,9 +44,14 @@ class FileAjaxType extends AbstractType
// Endpoint mandatory for fileupload bundle
$resolver->setRequired(array('endpoint'));
- $resolver->setOptional(array('display_link'));
+ $resolver->setOptional(array(
+ 'display_link',
+ 'resolver_key'
+ ));
+
$resolver->setDefaults(array(
- 'display_link' => true
+ 'display_link' => true,
+ 'resolver_key' => 'upload_resolver'
));
}
@@ -59,7 +64,7 @@ class FileAjaxType extends AbstractType
$fileHistoryUrl = null;
if ($form->getData() !== null) {
$fileHistory = $this->fileHistoryManager->findOneByFileName($form->getData());
- $fileHistoryUrl = $this->fileHistoryManager->getUrl($fileHistory);
+ $fileHistoryUrl = $this->fileHistoryManager->getUrl($fileHistory, $options['resolver_key']);
}
$className = 'jb_result_filename';
diff --git a/Service/FileHistoryManager.php b/Service/FileHistoryManager.php
index <HASH>..<HASH> 100644
--- a/Service/FileHistoryManager.php
+++ b/Service/FileHistoryManager.php
@@ -105,11 +105,11 @@ class FileHistoryManager implements FileHistoryManagerInterface
/**
* {@inheritDoc}
*/
- public function getUrl(FileHistory $fileHistory)
+ public function getUrl(FileHistory $fileHistory, $resolverType = 'upload_resolver')
{
// Add file path to response
$resolver = $this->resolvers->getResolver(
- $this->configuration->getValue($fileHistory->getType(), 'upload_resolver')
+ $this->configuration->getValue($fileHistory->getType(), $resolverType)
);
return $resolver->getUrl($fileHistory->getFilename(), $fileHistory->getType());
}
|
display croped image when submitting in crop field type
|
jbouzekri_FileUploaderBundle
|
train
|
ab1898a944a56dfc94e7198216f0d455e8d5fd18
|
diff --git a/ActiveQuery.php b/ActiveQuery.php
index <HASH>..<HASH> 100644
--- a/ActiveQuery.php
+++ b/ActiveQuery.php
@@ -195,6 +195,7 @@ class ActiveQuery extends Query implements ActiveQueryInterface
/* @var $class ActiveRecord */
$class = $this->modelClass;
$model = $class::instantiate($row);
+ $class = get_class($model);
$class::populateRecord($model, $row);
}
if (!empty($this->with)) {
|
Fixed bug #<I>. Classes that call '*::populateRecord()' after retrieving data from ddbb call now the method on the class of the model returned by '*::instantiate()'. Tests for mysql, elasticsearch and mongodb attached.
|
yiisoft_yii2-sphinx
|
train
|
07918071a3c8c8d7e842b9bfd3be71f37db57001
|
diff --git a/driver/src/test/functional/org/mongodb/MongoFindTest.java b/driver/src/test/functional/org/mongodb/MongoFindTest.java
index <HASH>..<HASH> 100644
--- a/driver/src/test/functional/org/mongodb/MongoFindTest.java
+++ b/driver/src/test/functional/org/mongodb/MongoFindTest.java
@@ -18,18 +18,10 @@ package org.mongodb;
import org.junit.Test;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.fail;
-
public class MongoFindTest extends DatabaseTestCase {
- @Test
+ @Test(expected = MongoQueryFailureException.class)
public void shouldThrowQueryFailureException() {
collection.insert(new Document("loc", new double[]{0, 0}));
- try {
- collection.find(new Document("loc", new Document("$near", new double[]{0, 0}))).getOne();
- fail("Should be a query failure since there is no 2d index");
- } catch (MongoQueryFailureException e) {
- assertEquals(13038, e.getErrorCode());
- }
+ collection.find(new Document("loc", new Document("$near", new double[]{0, 0}))).getOne();
}
}
|
Removed check for specific server error code, as the error code has changed in <I>.
|
mongodb_mongo-java-driver
|
train
|
45f9b6e546139744544d04b4a1545cb62b17e1b4
|
diff --git a/test/selector.js b/test/selector.js
index <HASH>..<HASH> 100644
--- a/test/selector.js
+++ b/test/selector.js
@@ -64,26 +64,6 @@ exports.selector = {
elm.removeClass("test-class")
test.equal(elm.className.indexOf("test-class"), -1)
- test.equal(typeof elm.hasClass, "function")
-
- test.done();
- },
-
- "$.hasClass works as expected": function (test) {
-
- var zeroClipboard = require("../ZeroClipboard")
- var elm = zeroClipboard.$("#d_clip_button")
-
- // element isn't null
- test.ok(elm)
-
- test.equal(typeof elm.hasClass, "function")
-
- elm.addClass("test-class")
- test.notEqual(elm.className.indexOf("test-class"), -1)
- test.ok(elm.hasClass("test-class"))
-
test.done();
}
-
};
\ No newline at end of file
|
We deleted hasClass so test isn't needed
|
zeroclipboard_zeroclipboard
|
train
|
272a6e8739874bd9545df4b174e4ac4f6a78f160
|
diff --git a/clients/java/client/src/main/java/org/camunda/bpm/client/interceptor/ClientRequestInterceptor.java b/clients/java/client/src/main/java/org/camunda/bpm/client/interceptor/ClientRequestInterceptor.java
index <HASH>..<HASH> 100644
--- a/clients/java/client/src/main/java/org/camunda/bpm/client/interceptor/ClientRequestInterceptor.java
+++ b/clients/java/client/src/main/java/org/camunda/bpm/client/interceptor/ClientRequestInterceptor.java
@@ -25,7 +25,7 @@ package org.camunda.bpm.client.interceptor;
public interface ClientRequestInterceptor {
/**
- * Has been invoked before a request is sent to the http server
+ * Gets invoked before a request is sent to the http server
*
* @param requestContext provides the data of the request and offers methods to change it
*/
|
chore(engine): Improve wording in a javadoc comment
|
camunda_camunda-bpm-platform
|
train
|
55555f1bfdf232d82ee9773d3a602824fcea54c3
|
diff --git a/jre_emul/Classes/com/google/j2objc/util/NativeTimeZone.java b/jre_emul/Classes/com/google/j2objc/util/NativeTimeZone.java
index <HASH>..<HASH> 100644
--- a/jre_emul/Classes/com/google/j2objc/util/NativeTimeZone.java
+++ b/jre_emul/Classes/com/google/j2objc/util/NativeTimeZone.java
@@ -116,10 +116,12 @@ public final class NativeTimeZone extends TimeZone {
]-*/;
private static native void setUpTimeZoneDidChangeNotificationHandler() /*-[
- [[NSNotificationCenter defaultCenter] addObserver:[ComGoogleJ2objcUtilNativeTimeZone class]
- selector:@selector(handleTimeZoneChangeWithId:)
- name:NSSystemTimeZoneDidChangeNotification
- object:nil];
+ [[NSNotificationCenter defaultCenter] addObserverForName: NSSystemTimeZoneDidChangeNotification
+ object:nil
+ queue:nil
+ usingBlock:^(NSNotification *note) {
+ ComGoogleJ2objcUtilNativeTimeZone_handleTimeZoneChangeWithId_(note);
+ }];
]-*/;
private static void handleTimeZoneChange(Object notification) {
|
Change NativeTimeZone to support reflection pruning.
|
google_j2objc
|
train
|
1351e14ef0b9c25193a6ba4104e6b212be49340c
|
diff --git a/ros_buildfarm/release_job.py b/ros_buildfarm/release_job.py
index <HASH>..<HASH> 100644
--- a/ros_buildfarm/release_job.py
+++ b/ros_buildfarm/release_job.py
@@ -320,8 +320,8 @@ def get_sourcedeb_job_name(rosdistro_name, release_build_name,
def _get_target_arches(build_file, os_name, os_code_name, print_skipped=True):
arches = []
for arch in build_file.targets[os_name][os_code_name]:
- # TODO support for non amd64 arch missing
- if arch not in ['amd64']:
+ # TODO support for i386 missing
+ if arch in ['i386']:
if print_skipped:
print('Skipping arch:', arch, file=sys.stderr)
continue
diff --git a/ros_buildfarm/trigger_job.py b/ros_buildfarm/trigger_job.py
index <HASH>..<HASH> 100644
--- a/ros_buildfarm/trigger_job.py
+++ b/ros_buildfarm/trigger_job.py
@@ -36,8 +36,8 @@ def trigger_release_jobs(
continue
for arch in sorted(
build_file.targets[os_name][os_code_name].keys()):
- # TODO support for non amd64 arch missing
- if arch not in ['amd64']:
+ # TODO support for i386 missing
+ if arch in ['i386']:
print('Skipping arch:', arch)
continue
targets.append(Target('ubuntu', os_code_name, arch))
|
invert logic for skipping i<I>
|
ros-infrastructure_ros_buildfarm
|
train
|
7a9e73fe20a1925ea7b0061252ac508a71898f20
|
diff --git a/lib/eachSeries.js b/lib/eachSeries.js
index <HASH>..<HASH> 100644
--- a/lib/eachSeries.js
+++ b/lib/eachSeries.js
@@ -17,8 +17,14 @@ class EachSeires extends AigleProxy {
this._iterator = iterator;
this._promise = new Aigle(INTERNAL);
this._index = 0;
+ this._coll = undefined;
+ this._rest = undefined;
+ this._size = undefined;
+ this._keys = undefined;
this._result = undefined;
+ this._iterate = undefined;
if (collection === PENDING) {
+ this._set = set;
this._iterate = this._callResolve;
this._callResolve = execute;
} else {
diff --git a/test/lib/test.each.js b/test/lib/test.each.js
index <HASH>..<HASH> 100644
--- a/test/lib/test.each.js
+++ b/test/lib/test.each.js
@@ -255,6 +255,23 @@ parallel('#each', () => {
assert.ok(error instanceof TypeError);
});
});
+
+ it('should catch an error with a reject promise', done => {
+
+ process.on('unhandledRejection', done);
+ const error = new Error('error');
+ const promise = Aigle.reject(error);
+ promise.catch(error => assert(error));
+ const collection = [1, 4, 2];
+ const iterator = () => promise;
+ return Aigle.delay(DELAY, collection)
+ .each(iterator)
+ .then(() => assert(false))
+ .catch(err => {
+ assert.strictEqual(err, error);
+ done();
+ });
+ });
});
parallel('#forEach', () => {
@@ -280,21 +297,4 @@ parallel('#forEach', () => {
]);
});
});
-
- it('should catch an error with a reject promise', done => {
-
- process.on('unhandledRejection', done);
- const error = new Error('error');
- const promise = Aigle.reject(error);
- promise.catch(error => assert(error));
- const collection = [1, 4, 2];
- const iterator = () => promise;
- return Aigle.delay(DELAY, collection)
- .each(iterator)
- .then(() => assert(false))
- .catch(err => {
- assert.strictEqual(err, error);
- done();
- });
- });
});
diff --git a/test/lib/test.eachSeries.js b/test/lib/test.eachSeries.js
index <HASH>..<HASH> 100644
--- a/test/lib/test.eachSeries.js
+++ b/test/lib/test.eachSeries.js
@@ -205,6 +205,23 @@ parallel('#eachSeries', () => {
]);
});
});
+
+ it('should catch an error with a reject promise', done => {
+
+ process.on('unhandledRejection', done);
+ const error = new Error('error');
+ const promise = Aigle.reject(error);
+ promise.catch(error => assert(error));
+ const collection = [1, 4, 2];
+ const iterator = () => promise;
+ return Aigle.delay(DELAY, collection)
+ .eachSeries(iterator)
+ .then(() => assert(false))
+ .catch(err => {
+ assert.strictEqual(err, error);
+ done();
+ });
+ });
});
parallel('#forEachSeries', () => {
|
perf(eachSeries): improve performance
|
suguru03_aigle
|
train
|
1017a1daa1c48e136f8c8ce6577424f165440cc9
|
diff --git a/lib/mr_darcy/promise/state/base.rb b/lib/mr_darcy/promise/state/base.rb
index <HASH>..<HASH> 100644
--- a/lib/mr_darcy/promise/state/base.rb
+++ b/lib/mr_darcy/promise/state/base.rb
@@ -21,11 +21,11 @@ module MrDarcy
end
def resolve
- raise "Can't resolve from #{get_state} state"
+ raise RuntimeError, "Can't resolve from #{get_state} state"
end
def reject
- raise "Cant reject from #{get_state} state"
+ raise RuntimeError, "Cant reject from #{get_state} state"
end
private
diff --git a/spec/acceptance/dci_bank_transfer_spec.rb b/spec/acceptance/dci_bank_transfer_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/acceptance/dci_bank_transfer_spec.rb
+++ b/spec/acceptance/dci_bank_transfer_spec.rb
@@ -22,7 +22,7 @@ class BankTransfer < MrDarcy::Context
money_source.subtract_funds amount
money_destination.receive_funds amount
else
- raise "insufficient funds"
+ raise RuntimeError, "insufficient funds"
end
amount
end
diff --git a/spec/lib/mr_darcy/promise/base_spec.rb b/spec/lib/mr_darcy/promise/base_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/lib/mr_darcy/promise/base_spec.rb
+++ b/spec/lib/mr_darcy/promise/base_spec.rb
@@ -73,7 +73,7 @@ describe MrDarcy::Promise::Base do
before { mock_promise.reject :bad }
When 'the fail block re-fails' do
- let(:fail_block) { proc { raise :bad } }
+ let(:fail_block) { proc { raise RuntimeError, :bad } }
it_behaves_like 'a rejected promise'
end
|
Always raise with an exception class, since Rubinius throws a tantrum otherwise.
|
jamesotron_MrDarcy
|
train
|
cdbe0eafae34caa6042ca1cec6641725b4eccd94
|
diff --git a/tcconfig/traffic_control.py b/tcconfig/traffic_control.py
index <HASH>..<HASH> 100644
--- a/tcconfig/traffic_control.py
+++ b/tcconfig/traffic_control.py
@@ -40,6 +40,8 @@ def _validate_within_min_max(param_name, value, min_value, max_value):
class TrafficControl(object):
+ __NETEM_QDISC_MAJOR_ID_OFFSET = 10
+
__OUT_DEVICE_QDISC_MINOR_ID = 1
__IN_DEVICE_QDISC_MINOR_ID = 3
@@ -280,14 +282,15 @@ class TrafficControl(object):
return int(device_hash_prefix + base_device_hash, 16)
def __get_netem_qdisc_major_id(self, base_qdisc_major_id):
- base_offset = 10
-
if self.direction == TrafficDirection.OUTGOING:
direction_offset = 0
elif self.direction == TrafficDirection.INCOMING:
direction_offset = 1
- return base_qdisc_major_id + base_offset + direction_offset
+ return (
+ base_qdisc_major_id +
+ self.__NETEM_QDISC_MAJOR_ID_OFFSET +
+ direction_offset)
def __get_qdisc_minor_id(self):
if self.direction == TrafficDirection.OUTGOING:
|
Define netem qdisc major id offset as a private class variable
|
thombashi_tcconfig
|
train
|
4fc59953a044927ad8261b76004826df1564b5d4
|
diff --git a/spec/models/starburst/announcement_spec.rb b/spec/models/starburst/announcement_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/models/starburst/announcement_spec.rb
+++ b/spec/models/starburst/announcement_spec.rb
@@ -39,6 +39,18 @@ RSpec.describe Starburst::Announcement do
end
end
+ describe '.ready_for_delivery' do
+ subject { described_class.ready_for_delivery }
+
+ let!(:due_announcement) { create(:announcement, start_delivering_at: 1.minute.ago) }
+ let!(:not_due_announcement) { create(:announcement, start_delivering_at: 1.minute.from_now) }
+ let!(:expired_announcement) { create(:announcement, stop_delivering_at: 1.minute.ago) }
+ let!(:not_expired_announcement) { create(:announcement, stop_delivering_at: 1.minute.from_now) }
+ let!(:unscheduled_announcement) { create(:announcement, start_delivering_at: nil, stop_delivering_at: nil) }
+
+ it { is_expected.to contain_exactly(due_announcement, not_expired_announcement, unscheduled_announcement) }
+ end
+
describe '.unread_by' do
subject { described_class.unread_by(current_user) }
|
Adds missing specs for Starburst::Announcement.ready_for_delivery
|
csm123_starburst
|
train
|
16b3b872a34040a029bfd2adc170f657e15cc852
|
diff --git a/readme.md b/readme.md
index <HASH>..<HASH> 100644
--- a/readme.md
+++ b/readme.md
@@ -67,3 +67,6 @@ Also, all relations are Eloquent|Eloquent[] by default, you can change them to t
After copying the phpdocs to your model, you can clear the file, so your IDE only uses the real source.
+### License
+
+The Laravel IDE Helper Generator is open-sourced software licensed under the [MIT license](http://opensource.org/licenses/MIT)
\ No newline at end of file
diff --git a/src/Barryvdh/LaravelIdeHelper/GeneratorCommand.php b/src/Barryvdh/LaravelIdeHelper/GeneratorCommand.php
index <HASH>..<HASH> 100755
--- a/src/Barryvdh/LaravelIdeHelper/GeneratorCommand.php
+++ b/src/Barryvdh/LaravelIdeHelper/GeneratorCommand.php
@@ -1,4 +1,14 @@
-<?php namespace Barryvdh\LaravelIdeHelper;
+<?php
+/**
+ * Laravel IDE Helper Generator
+ *
+ * @author Barry vd. Heuvel <barryvdh@gmail.com>
+ * @copyright 2013 Barry vd. Heuvel / Fruitcake Studio (http://www.fruitcakestudio.nl)
+ * @license http://www.opensource.org/licenses/mit-license.php MIT
+ * @link https://github.com/barryvdh/laravel-ide-helper
+ */
+
+namespace Barryvdh\LaravelIdeHelper;
use Illuminate\Console\Command;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Input\InputArgument;
diff --git a/src/Barryvdh/LaravelIdeHelper/IdeHelperServiceProvider.php b/src/Barryvdh/LaravelIdeHelper/IdeHelperServiceProvider.php
index <HASH>..<HASH> 100644
--- a/src/Barryvdh/LaravelIdeHelper/IdeHelperServiceProvider.php
+++ b/src/Barryvdh/LaravelIdeHelper/IdeHelperServiceProvider.php
@@ -1,4 +1,14 @@
-<?php namespace Barryvdh\LaravelIdeHelper;
+<?php
+/**
+ * Laravel IDE Helper Generator
+ *
+ * @author Barry vd. Heuvel <barryvdh@gmail.com>
+ * @copyright 2013 Barry vd. Heuvel / Fruitcake Studio (http://www.fruitcakestudio.nl)
+ * @license http://www.opensource.org/licenses/mit-license.php MIT
+ * @link https://github.com/barryvdh/laravel-ide-helper
+ */
+
+namespace Barryvdh\LaravelIdeHelper;
use Illuminate\Support\ServiceProvider;
diff --git a/src/Barryvdh/LaravelIdeHelper/ModelsCommand.php b/src/Barryvdh/LaravelIdeHelper/ModelsCommand.php
index <HASH>..<HASH> 100644
--- a/src/Barryvdh/LaravelIdeHelper/ModelsCommand.php
+++ b/src/Barryvdh/LaravelIdeHelper/ModelsCommand.php
@@ -1,4 +1,14 @@
-<?php namespace Barryvdh\LaravelIdeHelper;
+<?php
+/**
+ * Laravel IDE Helper Generator
+ *
+ * @author Barry vd. Heuvel <barryvdh@gmail.com>
+ * @copyright 2013 Barry vd. Heuvel / Fruitcake Studio (http://www.fruitcakestudio.nl)
+ * @license http://www.opensource.org/licenses/mit-license.php MIT
+ * @link https://github.com/barryvdh/laravel-ide-helper
+ */
+
+namespace Barryvdh\LaravelIdeHelper;
use Illuminate\Console\Command;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Input\InputArgument;
|
Update license (MIT)
To source/readme
|
barryvdh_laravel-ide-helper
|
train
|
1d0ffba99c660507f3f024f4f3c4d12f88643bc3
|
diff --git a/spyder/plugins/variableexplorer/widgets/tests/test_collectioneditor.py b/spyder/plugins/variableexplorer/widgets/tests/test_collectioneditor.py
index <HASH>..<HASH> 100644
--- a/spyder/plugins/variableexplorer/widgets/tests/test_collectioneditor.py
+++ b/spyder/plugins/variableexplorer/widgets/tests/test_collectioneditor.py
@@ -100,9 +100,9 @@ def test_collectionsmodel_with_two_ints():
assert cm.rowCount() == 2
assert cm.columnCount() == 5
# dict is unordered, so first row might be x or y
- assert data(cm, 0, 0) in {'<p style="color:white">x</p>',
- '<p style="color:white">y</p>'}
- if data(cm, 0, 0) == '<p style="color:white">x</p>':
+ assert data(cm, 0, 0) in {'x',
+ 'y'}
+ if data(cm, 0, 0) == 'x':
row_with_x = 0
row_with_y = 1
else:
@@ -111,7 +111,7 @@ def test_collectionsmodel_with_two_ints():
assert data(cm, row_with_x, 1) == 'int'
assert data(cm, row_with_x, 2) == '1'
assert data(cm, row_with_x, 3) == '1'
- assert data(cm, row_with_y, 0) == '<p style="color:white">y</p>'
+ assert data(cm, row_with_y, 0) == 'y'
assert data(cm, row_with_y, 1) == 'int'
assert data(cm, row_with_y, 2) == '1'
assert data(cm, row_with_y, 3) == '2'
@@ -121,7 +121,7 @@ def test_collectionsmodel_with_index():
for rng_name, rng in generate_pandas_indexes().items():
coll = {'rng': rng}
cm = CollectionsModel(None, coll)
- assert data(cm, 0, 0) == '<p style="color:white">rng</p>'
+ assert data(cm, 0, 0) == 'rng'
assert data(cm, 0, 1) == rng_name
assert data(cm, 0, 2) == '(20,)' or data(cm, 0, 2) == '(20L,)'
try:
@@ -149,16 +149,12 @@ def test_sort_collectionsmodel():
assert cm.rowCount() == 3
assert cm.columnCount() == 5
cm.sort(0) # sort by index
- assert data_table(cm, 3, 4) == [['<p style="color:white">0</p>',
- '<p style="color:white">1</p>',
- '<p style="color:white">2</p>'],
+ assert data_table(cm, 3, 4) == [['0', '1', '2'],
['int', 'int', 'int'],
['1', '1', '1'],
['1', '3', '2']]
cm.sort(3) # sort by value
- assert data_table(cm, 3, 4) == [['<p style="color:white">0</p>',
- '<p style="color:white">2</p>',
- '<p style="color:white">1</p>'],
+ assert data_table(cm, 3, 4) == [['0', '2', '1'],
['int', 'int', 'int'],
['1', '1', '1'],
['1', '2', '3']]
@@ -167,14 +163,12 @@ def test_sort_collectionsmodel():
assert cm.rowCount() == 2
assert cm.columnCount() == 5
cm.sort(1) # sort by type
- assert data_table(cm, 2, 4) == [['<p style="color:white">1</p>',
- '<p style="color:white">0</p>'],
+ assert data_table(cm, 2, 4) == [['1', '0'],
['int', 'list'],
['1', '2'],
['3', '[1, 2]']]
cm.sort(2) # sort by size
- assert data_table(cm, 2, 4) == [['<p style="color:white">1</p>',
- '<p style="color:white">0</p>'],
+ assert data_table(cm, 2, 4) == [['1', '0'],
['int', 'list'],
['1', '2'],
['3', '[1, 2]']]
|
Variable Explorer: Revert changes to collectionseditor's tests
|
spyder-ide_spyder
|
train
|
d788e83d73536a58ff36f5237eba54e5954815e1
|
diff --git a/Manager/EventManager.php b/Manager/EventManager.php
index <HASH>..<HASH> 100644
--- a/Manager/EventManager.php
+++ b/Manager/EventManager.php
@@ -217,15 +217,16 @@ class EventManager
$keyTrans = $this->translator->trans($sortedKey, array(), 'resource');
foreach ($genericResourceEvents as $genericKey => $genericEvent) {
+ $logTrans = $this->translator->trans(
+ $genericEvent === 'all' ? $genericEvent : 'log_' . $genericEvent . '_filter',
+ array(),
+ 'log'
+ );
+
if ($sortedKey !== 'all') {
- $logTrans = $this->translator->trans(
- $genericEvent === 'all' ? $genericEvent : 'log_' . $genericEvent . '_filter',
- array(),
- 'log'
- );
$sortedEvents[$resourceTrans][$keyTrans]['[[' . $sortedKey . ']]' . $genericEvent] = $logTrans;
} else {
- $sortedEvents[$resourceTrans][$allTranslatedText][$genericEvent] = $allTranslatedText;
+ $sortedEvents[$resourceTrans][$allTranslatedText][$genericEvent] = $logTrans;
}
}
|
Adding action for all resource generic log
|
claroline_CoreBundle
|
train
|
140120ec23e70358cb6dfeadf92b9aada4af835b
|
diff --git a/tests/test_build_ext.py b/tests/test_build_ext.py
index <HASH>..<HASH> 100644
--- a/tests/test_build_ext.py
+++ b/tests/test_build_ext.py
@@ -11,7 +11,8 @@ from distutils.tests.support import TempdirManager
from distutils.tests.support import LoggingSilencer
from distutils.extension import Extension
from distutils.errors import (
- CompileError, DistutilsSetupError, UnknownFileError)
+ CompileError, DistutilsPlatformError, DistutilsSetupError,
+ UnknownFileError)
import unittest
from test import support
@@ -431,18 +432,43 @@ class BuildExtTestCase(TempdirManager,
@unittest.skipUnless(sys.platform == 'darwin', 'test only relevant for MacOSX')
- def test_deployment_target(self):
- self._try_compile_deployment_target()
+ def test_deployment_target_default(self):
+ # Issue 9516: Test that, in the absence of the environment variable,
+ # an extension module is compiled with the same deployment target as
+ # the interpreter.
+ self._try_compile_deployment_target('==', None)
+ @unittest.skipUnless(sys.platform == 'darwin', 'test only relevant for MacOSX')
+ def test_deployment_target_too_low(self):
+ # Issue 9516: Test that an extension module is not allowed to be
+ # compiled with a deployment target less than that of the interpreter.
+ self.assertRaises(DistutilsPlatformError,
+ self._try_compile_deployment_target, '>', '10.1')
+
+ @unittest.skipUnless(sys.platform == 'darwin', 'test only relevant for MacOSX')
+ def test_deployment_target_higher_ok(self):
+ # Issue 9516: Test that an extension module can be compiled with a
+ # deployment target higher than that of the interpreter: the ext
+ # module may depend on some newer OS feature.
+ deptarget = sysconfig.get_config_var('MACOSX_DEPLOYMENT_TARGET')
+ if deptarget:
+ # increment the minor version number (i.e. 10.6 -> 10.7)
+ deptarget = [int(x) for x in deptarget.split('.')]
+ deptarget[-1] += 1
+ deptarget = '.'.join(str(i) for i in deptarget)
+ self._try_compile_deployment_target('<', deptarget)
+
+ def _try_compile_deployment_target(self, operator, target):
orig_environ = os.environ
os.environ = orig_environ.copy()
self.addCleanup(setattr, os, 'environ', orig_environ)
- os.environ['MACOSX_DEPLOYMENT_TARGET']='10.1'
- self._try_compile_deployment_target()
-
+ if target is None:
+ if os.environ.get('MACOSX_DEPLOYMENT_TARGET'):
+ del os.environ['MACOSX_DEPLOYMENT_TARGET']
+ else:
+ os.environ['MACOSX_DEPLOYMENT_TARGET'] = target
- def _try_compile_deployment_target(self):
deptarget_c = os.path.join(self.tmp_dir, 'deptargetmodule.c')
with open(deptarget_c, 'w') as fp:
@@ -451,16 +477,17 @@ class BuildExtTestCase(TempdirManager,
int dummy;
- #if TARGET != MAC_OS_X_VERSION_MIN_REQUIRED
+ #if TARGET %s MAC_OS_X_VERSION_MIN_REQUIRED
+ #else
#error "Unexpected target"
#endif
- '''))
+ ''' % operator))
+ # get the deployment target that the interpreter was built with
target = sysconfig.get_config_var('MACOSX_DEPLOYMENT_TARGET')
target = tuple(map(int, target.split('.')))
target = '%02d%01d0' % target
-
deptarget_ext = Extension(
'deptarget',
[deptarget_c],
|
Issue #<I>: Correct and expand OS X deployment target tests in distutils
test_build_ext.
|
pypa_setuptools
|
train
|
d1b1be4c0073acf11d4e8b0de12c459140603730
|
diff --git a/lib/temple/filters/multi_flattener.rb b/lib/temple/filters/multi_flattener.rb
index <HASH>..<HASH> 100644
--- a/lib/temple/filters/multi_flattener.rb
+++ b/lib/temple/filters/multi_flattener.rb
@@ -4,19 +4,22 @@ module Temple
def initialize(options = {})
@options = {}
end
-
+
def compile(exp)
- return exp unless exp.first == :multi
+ exp.first == :multi ? on_multi(*exp[1..-1]) : exp
+ end
+
+ def on_multi(*exps)
# If the multi contains a single element, just return the element
- return compile(exp[1]) if exp.length == 2
+ return compile(exps.first) if exps.length == 1
result = [:multi]
- exp[1..-1].each do |e|
- e = compile(e)
- if e.first == :multi
- result.concat(e[1..-1])
+ exps.each do |exp|
+ exp = compile(exp)
+ if exp.first == :multi
+ result.concat(exp[1..-1])
else
- result << e
+ result << exp
end
end
@@ -24,4 +27,4 @@ module Temple
end
end
end
-end
\ No newline at end of file
+end
|
Make MultiFlattener consistent with the other filters
|
judofyr_temple
|
train
|
74e8d7b769c9c18c12b87c55fa05fde588c169ef
|
diff --git a/javascript/libjoynr-js/src/main/js/joynr/messaging/routing/MessageRouter.js b/javascript/libjoynr-js/src/main/js/joynr/messaging/routing/MessageRouter.js
index <HASH>..<HASH> 100644
--- a/javascript/libjoynr-js/src/main/js/joynr/messaging/routing/MessageRouter.js
+++ b/javascript/libjoynr-js/src/main/js/joynr/messaging/routing/MessageRouter.js
@@ -165,43 +165,48 @@ var JSONSerializer = require('../../util/JSONSerializer');
* @param {String} participantId
* @param {boolean} isGloballyVisible
*
- * @returns result
+ * @returns {Promise} promise
*/
this.addNextHopToParentRoutingTable =
function addNextHopToParentRoutingTable(participantId, isGloballyVisible) {
- var result;
+ if (Typing.getObjectType(incomingAddress) === "WebSocketClientAddress") {
+ return routingProxy.addNextHop({
+ participantId : participantId,
+ webSocketClientAddress: incomingAddress,
+ isGloballyVisible : isGloballyVisible
+ });
+ }
if (Typing.getObjectType(incomingAddress) === "BrowserAddress") {
- result = routingProxy.addNextHop({
+ return routingProxy.addNextHop({
participantId : participantId,
browserAddress : incomingAddress,
isGloballyVisible: isGloballyVisible
});
- } else if (Typing.getObjectType(incomingAddress) === "ChannelAddress") {
- result = routingProxy.addNextHop({
+ }
+ if (Typing.getObjectType(incomingAddress) === "WebSocketAddress") {
+ return routingProxy.addNextHop({
participantId : participantId,
- channelAddress : incomingAddress,
+ webSocketAddress : incomingAddress,
isGloballyVisible: isGloballyVisible
});
- } else if (Typing.getObjectType(incomingAddress) === "WebSocketAddress") {
- result = routingProxy.addNextHop({
+ }
+ if (Typing.getObjectType(incomingAddress) === "ChannelAddress") {
+ return routingProxy.addNextHop({
participantId : participantId,
- webSocketAddress : incomingAddress,
+ channelAddress : incomingAddress,
isGloballyVisible: isGloballyVisible
});
- } else if (Typing.getObjectType(incomingAddress) === "WebSocketClientAddress") {
- result = routingProxy.addNextHop({
- participantId : participantId,
- webSocketClientAddress: incomingAddress,
- isGloballyVisible : isGloballyVisible
- });
- } else if (Typing.getObjectType(incomingAddress) === "CommonApiDbusAddress") {
- result = routingProxy.addNextHop({
+ }
+ if (Typing.getObjectType(incomingAddress) === "CommonApiDbusAddress") {
+ return routingProxy.addNextHop({
participantId : participantId,
commonApiDbusAddress: incomingAddress,
isGloballyVisible : isGloballyVisible
});
}
- return result;
+ var errorMsg = "Invalid address type of incomingAddress: " + Typing.getObjectType(incomingAddress);
+ log.fatal(errorMsg);
+ return Promise.reject(new JoynrRuntimeException({ detailMessage: errorMsg }));
};
/**
|
[JS] refactor MessageRouter.addNextHopToParentRoutingTable
* fix JsDoc comment
* reorder check for address type:
check for WebSocketClientAddress first, because the incoming
address is usually of that type
* log and return error if type of incoming address is unknown
Change-Id: I4b<I>a6d<I>cb6b<I>c<I>a<I>dba<I>a<I>fc7a
|
bmwcarit_joynr
|
train
|
10900a91cf91b10859f6060a1897a697104e6877
|
diff --git a/tests/conftest.py b/tests/conftest.py
index <HASH>..<HASH> 100644
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@ -1,3 +1,4 @@
+import logging
import os
import threading
@@ -13,6 +14,16 @@ from .util import _support
# 'nicer'.
+# Perform logging by default; pytest will capture and thus hide it normally,
+# presenting it on error/failure.
+# Also make sure to set up timestamping for more sanity when debugging.
+logging.basicConfig(
+ level=logging.DEBUG,
+ format="[%(relativeCreated)s]\t%(levelname)s:%(name)s:%(message)s",
+ datefmt="%H:%M:%S",
+)
+
+
def make_sftp_folder(client):
"""
Create some non-existing, new folder on the given SFTP connection.
|
Tweak test-level logging format to include timestamps
|
paramiko_paramiko
|
train
|
0e09100e63dcb8ea9780d82ef37a58ba2815fbdb
|
diff --git a/lib/best_companies/cli.rb b/lib/best_companies/cli.rb
index <HASH>..<HASH> 100644
--- a/lib/best_companies/cli.rb
+++ b/lib/best_companies/cli.rb
@@ -1,6 +1,13 @@
class BestCompanies::CLI
- BASE_PATH = "https://www.greatplacetowork.com/best-workplaces/100-best/2017"
+ BASE_PATH = "https://www.greatplacetowork.com/best-workplaces/100-best/2017"
- def start
- end
+ def self.start
+ create_list
+
+ end
+
+ def self.create_list
+ company_hash = BestCompanies::Scraper.new.scrape_companies(BASE_PATH)
+ BestCompanies::Company.create_from_list(company_hash)
+ end
end
\ No newline at end of file
|
added two class methods to start the program and to create a list of companies
|
yosayon_Best_Companies
|
train
|
d3383f74e645253e2423e5336b87f585de6b2485
|
diff --git a/test/integration/generated_gimarshallingtests_test.rb b/test/integration/generated_gimarshallingtests_test.rb
index <HASH>..<HASH> 100644
--- a/test/integration/generated_gimarshallingtests_test.rb
+++ b/test/integration/generated_gimarshallingtests_test.rb
@@ -588,7 +588,23 @@ describe GIMarshallingTests do
end
it "has a working method #vfunc_with_callback" do
- skip "Needs vfunc setup"
+ skip unless get_method_introspection_data("GIMarshallingTests", "Object",
+ "vfunc_with_callback")
+
+ result = 1
+
+ derived_instance = make_derived_instance do |info|
+ info.install_vfunc_implementation :vfunc_with_callback, proc { |obj, callback, callback_data|
+ callback.call(42, callback_data)
+ }
+ end
+
+ derived_instance.vfunc_with_callback proc { |val, user_data| result = val + user_data }, 23
+
+ # The current implementation of the vfunc_with_callback method currently
+ # doesn't actually call the virtual function vfunc_with_callback.
+ result.must_equal 1
+ result.wont_equal 42 + 23
end
describe "its 'int' property" do
|
Add odd but passing test for #vfunc_with_callback
|
mvz_gir_ffi
|
train
|
46136004df484a95a6fbf3c8f306684a5304e1eb
|
diff --git a/system/modules/DocumentManagementSystem/classes/DmsConfig.php b/system/modules/DocumentManagementSystem/classes/DmsConfig.php
index <HASH>..<HASH> 100644
--- a/system/modules/DocumentManagementSystem/classes/DmsConfig.php
+++ b/system/modules/DocumentManagementSystem/classes/DmsConfig.php
@@ -86,7 +86,8 @@ class DmsConfig
*/
public static function getTempDirectory($blnAppendTrailingSlash)
{
- $path = self::getBaseDirectory(true) . self::DIRECTORY_NAME_TEMP;
+ //$path = self::getBaseDirectory(true) . self::DIRECTORY_NAME_TEMP;
+ $path = "system/tmp";
if ($blnAppendTrailingSlash)
{
|
Upload to `system/tmp` (see #<I> )
|
ContaoDMS_dms
|
train
|
1a119742919425fa1f1134ca13b78985acd96547
|
diff --git a/src/com/aoindustries/taglib/ApplicationResources.java b/src/com/aoindustries/taglib/ApplicationResources.java
index <HASH>..<HASH> 100644
--- a/src/com/aoindustries/taglib/ApplicationResources.java
+++ b/src/com/aoindustries/taglib/ApplicationResources.java
@@ -1,6 +1,6 @@
/*
* aocode-public-taglib - Reusable Java taglib of general tools with minimal external dependencies.
- * Copyright (C) 2009, 2010, 2011, 2013 AO Industries, Inc.
+ * Copyright (C) 2009, 2010, 2011, 2013, 2015 AO Industries, Inc.
* support@aoindustries.com
* 7262 Bull Pen Cir
* Mobile, AL 36695
@@ -55,5 +55,5 @@ public final class ApplicationResources extends EditableResourceBundle {
);
}
- static final ApplicationResourcesAccessor accessor = ApplicationResourcesAccessor.getInstance(bundleSet.getBaseName());
+ public static final ApplicationResourcesAccessor accessor = ApplicationResourcesAccessor.getInstance(bundleSet.getBaseName());
}
|
Reusing some parts of aocode-public-taglib in docs-taglib implementation.
|
aoindustries_ao-taglib
|
train
|
fe2ae61596b74ee94d692350ee026a9b952499e0
|
diff --git a/run.go b/run.go
index <HASH>..<HASH> 100644
--- a/run.go
+++ b/run.go
@@ -12,3 +12,11 @@ func Run(executable string, args ...string) *cmdtest.Session {
return sess
}
+
+func Curl(uri string) *cmdtest.Session {
+ return Run("curl", "-s", uri)
+}
+
+func Cf(args ...string) *cmdtest.Session {
+ return Run("go-cf", args...)
+}
|
poll app endpoint instead of immediately expecting
Also stop asserting on exit codes; not really user-visible and just adds
noise. Added Cf and Curl and Curling helpers to make the tests prettier.
|
cloudfoundry-incubator_cf-test-helpers
|
train
|
59dff18cfd8b5b3923b1fb346ef699d8bad3b302
|
diff --git a/src/js/Inks/InkContainer.js b/src/js/Inks/InkContainer.js
index <HASH>..<HASH> 100644
--- a/src/js/Inks/InkContainer.js
+++ b/src/js/Inks/InkContainer.js
@@ -3,6 +3,7 @@ import { findDOMNode } from 'react-dom';
import TransitionGroup from 'react-addons-transition-group';
import cn from 'classnames';
+import { ENTER, SPACE } from '../constants/keyCodes';
import isValidClick from '../utils/EventUtils/isValidClick';
import captureNextEvent from '../utils/EventUtils/captureNextEvent';
import calcPageOffset from '../utils/calcPageOffset';
@@ -57,6 +58,7 @@ export default class InkContainer extends PureComponent {
this._handleTouchEnd = this._handleTouchEnd.bind(this);
this._handleRemove = this._handleRemove.bind(this);
this._handleSubmit = this._handleSubmit.bind(this);
+ this._handleKeyDown = this._handleKeyDown.bind(this);
this._getKeyboardContainer = this._getKeyboardContainer.bind(this);
this._stopPropagationToFocus = this._stopPropagationToFocus.bind(this);
this._initOrRemoveEvents = this._initOrRemoveEvents.bind(this);
@@ -168,6 +170,10 @@ export default class InkContainer extends PureComponent {
this.setState({ inks });
}
+ /**
+ * Gets the container for any keyboard events. This will almost always be the main element,
+ * but text fields will need to be the input itself.
+ */
_getKeyboardContainer() {
if (this._container.classList.contains('md-text-field-container')) {
return this._container.querySelector('.md-text-field');
@@ -176,6 +182,12 @@ export default class InkContainer extends PureComponent {
return this._container;
}
+ /**
+ * Sets the ink container and the main container from the ref callback. When the component
+ * is mounting, the keyboard, mouse, and keyboard events will be initialized.
+ *
+ * @param {Object} inkContainer - The ink container.
+ */
_setContainers(inkContainer) {
if (inkContainer !== null) {
this._inkContainer = findDOMNode(inkContainer);
@@ -187,6 +199,18 @@ export default class InkContainer extends PureComponent {
}
}
+ /**
+ * This function will either add or remove the event listeners for creating inks.
+ *
+ * @param {Object} props - The current props to use for figuring out if the events should
+ * be added or removed.
+ * @param {bool=} keyboardDiff - Boolean if there was a difference between the current props and either
+ * the previous or next props for the keyboard interactions being disabled.
+ * @param {bool=} mouseDiff - Boolean if there was a difference between the current props and either
+ * the previous or next props for the mouse interactions being disabled.
+ * @param {bool=} touchDiff - Boolean if there was a difference between the current props and either
+ * the previous or next props for the touch interactions being disabled.
+ */
_initOrRemoveEvents(props, keyboardDiff = true, mouseDiff = true, touchDiff = true) {
const mouseDisabled = this._isListenerDisabled('mouse', props.disabledInteractions);
const touchDisabled = this._isListenerDisabled('touch', props.disabledInteractions);
@@ -195,6 +219,7 @@ export default class InkContainer extends PureComponent {
if (keyboardDiff) {
const fn = `${keyboardDisabled ? 'remove' : 'add'}EventListener`;
this._getKeyboardContainer()[fn]('focus', this._handleFocus);
+ this._getKeyboardContainer()[fn]('keydown', this._handleKeyDown);
if (this._container.getAttribute('type') === 'submit') {
window[fn]('submit', this._handleSubmit);
@@ -254,6 +279,15 @@ export default class InkContainer extends PureComponent {
this._clicked = false;
}
+ _handleKeyDown(e) {
+ const key = e.which || e.keyCode;
+ if (key === ENTER || key === SPACE) {
+ this._clicked = true;
+ this.createInk();
+ this._maybeDelayClick();
+ }
+ }
+
_handleFocus() {
if (this._clicked) {
return;
@@ -275,7 +309,6 @@ export default class InkContainer extends PureComponent {
return;
}
- e.stopPropagation();
this._mouseLeave = false;
this._container.addEventListener('mouseleave', this._handleMouseLeave);
this._createInk(e.pageX, e.pageY);
|
Fixed the Ink Injector for Keyboard _Clicks_
The ink inject now creates an ink correctly when a keyboard only user
_clicks_ an ink with the space or enter key.
The inject ink will also now correctly delay the click event with
keyboard interactions as well if the waitForInkTransition prop is
enabled.
|
mlaursen_react-md
|
train
|
65dfa20031695da56ae2bb2a739d84c8d47d3d38
|
diff --git a/code/SiteTreeSubsites.php b/code/SiteTreeSubsites.php
index <HASH>..<HASH> 100644
--- a/code/SiteTreeSubsites.php
+++ b/code/SiteTreeSubsites.php
@@ -40,6 +40,15 @@ class SiteTreeSubsites extends DataObjectDecorator {
}
/**
+ * Check if we're currently looking at the main site.
+ * @return boolean TRUE main site | FALSE sub-site
+ */
+ function isMainSite() {
+ if($this->owner->SubsiteID == 0) return true;
+ return false;
+ }
+
+ /**
* Update any requests to limit the results to the current site
*/
function augmentSQL(SQLQuery &$query) {
@@ -212,6 +221,7 @@ class SiteTreeSubsites extends DataObjectDecorator {
$url = Director::absoluteURL($this->owner->Link());
return preg_replace('/\/\/[^\/]+\//', '//' . $this->owner->Subsite()->domain() . '/', $url);
}
+
}
?>
|
ENHANCEMENT Added isMainSite() to SiteTree decorator for subsites so it can be checked if we're currently viewing the main site or a sub-site
|
silverstripe_silverstripe-subsites
|
train
|
a6982b850afcc8b1309576ffd293bf59ebf0ca39
|
diff --git a/src/ses.php b/src/ses.php
index <HASH>..<HASH> 100644
--- a/src/ses.php
+++ b/src/ses.php
@@ -44,18 +44,22 @@ class SimpleEmailService {
}
// List all identities your AWS account.
- public function list_identities($identity_type = 'EmailAddress') {
+ public function list_identities($identity_type = '') {
$this -> action = 'ListIdentities';
$this -> method = 'GET';
- if (!preg_match('/EmailAddress|Domain/', $identity_type)) {
- error_log('IdentityType must be EmailAddress or Domain');
+ if (!preg_match('/^(EmailAddress|Domain|)$/', $identity_type)) {
+ throw new Exception('IdentityType must be EmailAddress or Domain');
return;
}
- $parameters = array(
- 'IdentityType' => $identity_type
- );
+ if ($identity_type) {
+ $parameters = array(
+ 'IdentityType' => $identity_type
+ );
+ } else {
+ $parameters = array();
+ }
$this -> generate_signature($parameters);
$context = $this -> create_stream_context();
|
IdentityType is option on list_identities
|
okamos_php-ses
|
train
|
1d94b669cecdf36c57039ec5f5f1a902deb61b63
|
diff --git a/critical-css.js b/critical-css.js
index <HASH>..<HASH> 100644
--- a/critical-css.js
+++ b/critical-css.js
@@ -61,7 +61,7 @@
// Call PhantomJS with our runner script.
execFile(binPath, childArgs, phantomOptions, function(err, stdout, stderr) {
if (err) {
- console.log('Something is awry wrong with phantomjs...');
+ console.log('Something is awry with phantomjs...');
if (stderr) {
err.message = stderr;
}
diff --git a/lib/runner.js b/lib/runner.js
index <HASH>..<HASH> 100644
--- a/lib/runner.js
+++ b/lib/runner.js
@@ -117,7 +117,7 @@
}, function() {
// Run the parser.
- page.evaluate(function() {
+ page.evaluate(function(options) {
var parser = new CSSCriticalPath(window, document);
var CSSList = parser.generateCSS();
@@ -128,7 +128,7 @@
catch (err) {
throw new Error(err);
}
- });
+ }, parserOptions);
});
});
|
Pass on relevant config params to parser
|
attila_critical-css
|
train
|
ddb0ca844e77e6aa7fffdd96e98ff3f9d2781575
|
diff --git a/prov-rdf/src/main/java/org/openprovenance/prov/rdf/RdfCollector.java b/prov-rdf/src/main/java/org/openprovenance/prov/rdf/RdfCollector.java
index <HASH>..<HASH> 100644
--- a/prov-rdf/src/main/java/org/openprovenance/prov/rdf/RdfCollector.java
+++ b/prov-rdf/src/main/java/org/openprovenance/prov/rdf/RdfCollector.java
@@ -761,7 +761,7 @@ public class RdfCollector extends RDFHandlerBase {
} else
{
// Ugly!
- String prefix = uri.getNamespace().hashCode() + "";
+ String prefix = "ns" + uri.getNamespace().hashCode() + "";//
handleNamespace(prefix, uri.getNamespace());
qname = new QName(uri.getNamespace(), uri.getLocalName(), prefix);
}
|
added ns to prefix to ensure its valid xml prefix
|
lucmoreau_ProvToolbox
|
train
|
e830ce81ca3e599c6be9cb970c161c00ed267210
|
diff --git a/spec/lib/darrrr/recovery_token_spec.rb b/spec/lib/darrrr/recovery_token_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/lib/darrrr/recovery_token_spec.rb
+++ b/spec/lib/darrrr/recovery_token_spec.rb
@@ -43,8 +43,7 @@ module Darrrr
begin
Encoding.default_internal = Encoding::UTF_8
- obj = token.to_binary_s
- obj.to_binary_s.encoding.must_equal Encoding::ASCII_8BIT
+ AccountProvider.this.generate_recovery_token(data: "hai", audience: recovery_provider).first
ensure
Encoding.default_internal = before_enc
$_w = w
|
call into higher API to show the library is broken
|
github_darrrr
|
train
|
406dce877c7d8cf2862d4886c53e3191b4d47b19
|
diff --git a/tests/col.test.js b/tests/col.test.js
index <HASH>..<HASH> 100644
--- a/tests/col.test.js
+++ b/tests/col.test.js
@@ -1,7 +1,7 @@
import React from 'react';
import renderer from 'react-test-renderer';
import { shallow } from 'enzyme';
-import { css } from 'aphrodite';
+import { css, StyleSheet } from 'aphrodite';
import { Col, style } from '../src/components';
@@ -26,6 +26,17 @@ describe('Col', () => {
expect(className).toContain(css(style['col-md-12']));
});
+ it('Should properly merge styles', () => {
+ const styleSheet = StyleSheet.create({
+ foo: {},
+ });
+
+ const wrapper = shallow(<Col styles={styleSheet.foo} md={12} />);
+ const { className } = wrapper.props();
+ expect(className).toContain(css(styleSheet.foo));
+ expect(className).toContain(css(style['col-md-12']));
+ });
+
it('Should support auto-width', () => {
const wrapper = shallow(<Col xs sm md lg />);
const classes = ['col-xs', 'col-sm', 'col-md', 'col-md'];
diff --git a/tests/grid.test.js b/tests/grid.test.js
index <HASH>..<HASH> 100644
--- a/tests/grid.test.js
+++ b/tests/grid.test.js
@@ -1,7 +1,7 @@
import React from 'react';
import renderer from 'react-test-renderer';
import { shallow } from 'enzyme';
-import { css } from 'aphrodite';
+import { css, StyleSheet } from 'aphrodite';
import { Grid, style } from '../src/components';
@@ -23,6 +23,17 @@ describe('Grid', () => {
expect(className).toContain(css(style.container));
});
+ it('Should properly merge styles', () => {
+ const styleSheet = StyleSheet.create({
+ foo: {},
+ });
+
+ const wrapper = shallow(<Grid styles={styleSheet.foo} />);
+ const { className } = wrapper.props();
+ expect(className).toContain(css(styleSheet.foo));
+ expect(className).toContain(css(style.container));
+ });
+
it('Should have children', () => {
const wrapper = shallow(
<Grid className="foo">
diff --git a/tests/row.test.js b/tests/row.test.js
index <HASH>..<HASH> 100644
--- a/tests/row.test.js
+++ b/tests/row.test.js
@@ -1,7 +1,7 @@
import React from 'react';
import renderer from 'react-test-renderer';
import { shallow } from 'enzyme';
-import { css } from 'aphrodite';
+import { css, StyleSheet } from 'aphrodite';
import { Row, style } from '../src/components';
@@ -23,6 +23,17 @@ describe('Row', () => {
expect(className).toContain(css(style.row));
});
+ it('Should properly merge styles', () => {
+ const styleSheet = StyleSheet.create({
+ foo: {},
+ });
+
+ const wrapper = shallow(<Row styles={styleSheet.foo} />);
+ const { className } = wrapper.props();
+ expect(className).toContain(css(styleSheet.foo));
+ expect(className).toContain(css(style.row));
+ });
+
it('Should add modificators', () => {
const tree = renderer.create(
<Row
|
Test style merging. Preserve old behavior
|
patrickml_react-flexbox-grid-aphrodite
|
train
|
0251fad68b13f8bbfd8f94d6eccb6f6c7dc46aef
|
diff --git a/lib/manager/docker/extract.js b/lib/manager/docker/extract.js
index <HASH>..<HASH> 100644
--- a/lib/manager/docker/extract.js
+++ b/lib/manager/docker/extract.js
@@ -9,7 +9,7 @@ function extractDependencies(content) {
return [];
}
const [, , fromLine] = fromMatch;
- const [fromPrefix, currentFrom, ...fromRest] = fromLine.split(' ');
+ const [fromPrefix, currentFrom, ...fromRest] = fromLine.match(/\S+/g);
const fromSuffix = fromRest.join(' ');
let dockerRegistry;
const split = currentFrom.split('/');
diff --git a/lib/manager/docker/update.js b/lib/manager/docker/update.js
index <HASH>..<HASH> 100644
--- a/lib/manager/docker/update.js
+++ b/lib/manager/docker/update.js
@@ -6,13 +6,13 @@ function setNewValue(currentFileContent, upgrade) {
try {
logger.debug(`setNewValue: ${upgrade.newFrom}`);
const oldLine = new RegExp(
- `(^|\n)${upgrade.fromPrefix} ${upgrade.depName}.*? ?${
+ `(^|\n)${upgrade.fromPrefix}(\\s+)${upgrade.depName}.*?(\\s?)${
upgrade.fromSuffix
}\n`
);
- let newLine = `$1${upgrade.fromPrefix} ${upgrade.newFrom}`;
+ let newLine = `$1${upgrade.fromPrefix}$2${upgrade.newFrom}$3`;
if (upgrade.fromSuffix.length) {
- newLine += ` ${upgrade.fromSuffix}`;
+ newLine += `${upgrade.fromSuffix}`;
}
newLine += '\n';
const newFileContent = currentFileContent.replace(oldLine, newLine);
diff --git a/test/manager/docker/__snapshots__/extract.spec.js.snap b/test/manager/docker/__snapshots__/extract.spec.js.snap
index <HASH>..<HASH> 100644
--- a/test/manager/docker/__snapshots__/extract.spec.js.snap
+++ b/test/manager/docker/__snapshots__/extract.spec.js.snap
@@ -1,5 +1,23 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP
+exports[`lib/manager/docker/extract extractDependencies() handles abnoral spacing 1`] = `
+Array [
+ Object {
+ "currentDepTag": "node:8.7.0",
+ "currentDepTagDigest": "node:8.7.0",
+ "currentDigest": undefined,
+ "currentFrom": "registry.allmine.info:5005/node:8.7.0",
+ "currentTag": "8.7.0",
+ "depName": "node",
+ "depType": "Dockerfile",
+ "dockerRegistry": "registry.allmine.info:5005",
+ "fromLine": "FROM registry.allmine.info:5005/node:8.7.0",
+ "fromPrefix": "FROM",
+ "fromSuffix": "",
+ },
+]
+`;
+
exports[`lib/manager/docker/extract extractDependencies() handles comments 1`] = `
Array [
Object {
diff --git a/test/manager/docker/__snapshots__/update.spec.js.snap b/test/manager/docker/__snapshots__/update.spec.js.snap
index <HASH>..<HASH> 100644
--- a/test/manager/docker/__snapshots__/update.spec.js.snap
+++ b/test/manager/docker/__snapshots__/update.spec.js.snap
@@ -1,5 +1,12 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP
+exports[`workers/branch/dockerfile setNewValue handles strange whitespace 1`] = `
+"# comment FROM node:8
+FROM node:8@sha256:abcdefghijklmnop as base
+RUN something
+"
+`;
+
exports[`workers/branch/dockerfile setNewValue replaces existing value 1`] = `
"# comment FROM node:8
FROM node:8@sha256:abcdefghijklmnop
diff --git a/test/manager/docker/extract.spec.js b/test/manager/docker/extract.spec.js
index <HASH>..<HASH> 100644
--- a/test/manager/docker/extract.spec.js
+++ b/test/manager/docker/extract.spec.js
@@ -73,5 +73,11 @@ describe('lib/manager/docker/extract', () => {
expect(res[0].dockerRegistry).toEqual('registry2.something.info');
expect(res[0].depName).toEqual('someaccount/node');
});
+ it('handles abnoral spacing', () => {
+ const res = extractDependencies(
+ 'FROM registry.allmine.info:5005/node:8.7.0\n\n'
+ );
+ expect(res).toMatchSnapshot();
+ });
});
});
diff --git a/test/manager/docker/update.spec.js b/test/manager/docker/update.spec.js
index <HASH>..<HASH> 100644
--- a/test/manager/docker/update.spec.js
+++ b/test/manager/docker/update.spec.js
@@ -28,6 +28,19 @@ describe('workers/branch/dockerfile', () => {
const res = dockerfile.setNewValue(currentFileContent, upgrade);
expect(res).toMatchSnapshot();
});
+ it('handles strange whitespace', () => {
+ const currentFileContent =
+ '# comment FROM node:8\nFROM node:8 as base\nRUN something\n';
+ const upgrade = {
+ depName: 'node',
+ currentVersion: 'node:8',
+ fromPrefix: 'FROM',
+ fromSuffix: 'as base',
+ newFrom: 'node:8@sha256:abcdefghijklmnop',
+ };
+ const res = dockerfile.setNewValue(currentFileContent, upgrade);
+ expect(res).toMatchSnapshot();
+ });
it('returns null on error', () => {
const currentFileContent = null;
const upgrade = {
|
fix: allow multiple whitespace in dockerfile from line (#<I>)
|
renovatebot_renovate
|
train
|
cc25111c6837449386f527448e750bde16243cbd
|
diff --git a/jdbc4/src/main/java/org/javasimon/jdbc4/SqlNormalizer.java b/jdbc4/src/main/java/org/javasimon/jdbc4/SqlNormalizer.java
index <HASH>..<HASH> 100644
--- a/jdbc4/src/main/java/org/javasimon/jdbc4/SqlNormalizer.java
+++ b/jdbc4/src/main/java/org/javasimon/jdbc4/SqlNormalizer.java
@@ -23,7 +23,7 @@ public final class SqlNormalizer {
private static final Replacer[] FIRST_REPLACERS;
private static final Replacer[] SECOND_REPLACERS;
- private static final Replacer FUNCTION_REPLACER = new Replacer("([-(=<>!+*/,]+\\s?)\\w+\\([^()]*\\)", "$1?", true);
+ private static final Replacer FUNCTION_REPLACER = new Replacer("([-(=<>!+*/,]+\\s?)\\w+\\([^()]*\\)", "$1?", Replacer.Modificator.REPEAT_UNTIL_UNCHANGED);
private static final Replacer TYPE_SELECTOR = new Replacer("^\\W*(\\w+)\\W.*", "$1");
|
Fixed compilation issue. Virgo: check this commit
|
virgo47_javasimon
|
train
|
349053c19c5af7c9311f123ac076eb2954d7c344
|
diff --git a/lib/rules/no-unsafe-innerhtml.js b/lib/rules/no-unsafe-innerhtml.js
index <HASH>..<HASH> 100644
--- a/lib/rules/no-unsafe-innerhtml.js
+++ b/lib/rules/no-unsafe-innerhtml.js
@@ -20,6 +20,9 @@ module.exports = function (context) {
var VALID_UNWRAPPERS = ["Sanitizer.unwrapSafeHTML", "unwrapSafeHTML"];
function allowedExpression(expression, parent) {
+ if (typeof parent === "undefined") {
+ throw new Error("allowedExpressions() expects two parameters. Only one given.");
+ }
/*
expression = { right-hand side of innerHTML or 2nd param to insertAdjacentHTML
parent is the parent node of the call or assignment. used to look into comments.
@@ -39,12 +42,15 @@ module.exports = function (context) {
// we just assign a literal (e.g. a string, a number, a bool)
allowed = true;
} else if (expression.type === "TemplateLiteral") {
+ allowed = true;
// check for ${..} expressions
- if (expression.expressions.length === 0) {
- allowed = true;
- } else {
- allowed = false;
- } // else: contains expressions, but no tagged function? not cool.
+ for (var e = 0; e < expression.expressions.length; e++) {
+ var templateExpression = expression.expressions[e];
+ if (!allowedExpression(templateExpression, expression)) {
+ allowed = false;
+ break;
+ }
+ }
} else if (expression.type === "TaggedTemplateExpression") {
// context.getSource(expression.tag) is the function name
if (VALID_ESCAPERS.indexOf(context.getSource(expression.tag)) !== -1) {
diff --git a/tests/rules/no-unsafe-innerhtml.js b/tests/rules/no-unsafe-innerhtml.js
index <HASH>..<HASH> 100644
--- a/tests/rules/no-unsafe-innerhtml.js
+++ b/tests/rules/no-unsafe-innerhtml.js
@@ -120,8 +120,20 @@ eslintTester.run("no-unsafe-innerhtml", rule, {
{
code: "document.writeln(Sanitizer.escapeHTML`<em>${evil}</em>`);",
ecmaFeatures: features
- }
-
+ },
+ // template string expression tests
+ {
+ code: "u.innerHTML = `<span>${'lulz'}</span>`;",
+ ecmaFeatures: features
+ },
+ {
+ code: "v.innerHTML = `<span>${'lulz'}</span>${55}`;",
+ ecmaFeatures: features
+ },
+ {
+ code: "w.innerHTML = `<span>${'lulz'+'meh'}</span>`;",
+ ecmaFeatures: features
+ },
],
// Examples of code that should trigger the rule
@@ -159,13 +171,33 @@ eslintTester.run("no-unsafe-innerhtml", rule, {
]
},
{
- code: "m.outerHTML = htmlString;",
- errors: [
+ code: "m.outerHTML = htmlString;",
+ errors: [
{
message: "Unsafe assignment to outerHTML",
type: "AssignmentExpression"
}
- ]
+ ]
+ },
+ {
+ code: "t.innerHTML = `<span>${name}</span>`;",
+ errors: [
+ {
+ message: "Unsafe assignment to innerHTML",
+ type: "AssignmentExpression"
+ }
+ ],
+ ecmaFeatures: features
+ },
+ {
+ code: "t.innerHTML = `<span>${'foobar'}</span>${evil}`;",
+ errors: [
+ {
+ message: "Unsafe assignment to innerHTML",
+ type: "AssignmentExpression"
+ }
+ ],
+ ecmaFeatures: features
},
// insertAdjacentHTML examples
{
|
Allow expressions within template strings, as long as they are allowed on their own (literals, etc.). Adding bailout in allowedExpression when used improperly. This has bitten mee way too often
|
mozilla_eslint-plugin-no-unsanitized
|
train
|
9b54ed62e8416313e2cc0e1094edf8b5dcdffe64
|
diff --git a/src/neevo/Neevo.php b/src/neevo/Neevo.php
index <HASH>..<HASH> 100644
--- a/src/neevo/Neevo.php
+++ b/src/neevo/Neevo.php
@@ -33,8 +33,9 @@ class Neevo implements INeevoObservable, INeevoObserver {
private $connection;
- // Neevo revision
- const REVISION = 461;
+ // Neevo version
+ const VERSION = '1.0-dev',
+ REVISION = '@VCREV@ released on @VCDATE@';
// Data types
const BOOL = 'b',
diff --git a/src/neevo/NeevoLoader.php b/src/neevo/NeevoLoader.php
index <HASH>..<HASH> 100644
--- a/src/neevo/NeevoLoader.php
+++ b/src/neevo/NeevoLoader.php
@@ -71,6 +71,15 @@ class NeevoLoader {
/**
+ * Unregister the autoloader.
+ * @return void
+ */
+ public function unregister(){
+ spl_autoload_unregister(array($this, 'tryLoad'));
+ }
+
+
+ /**
* Try load Neevo class/interface.
* @param string $type
* @return bool
|
Release version <I>-dev
|
smasty_Neevo
|
train
|
50e8066d54bd3d81d44921af668b45b59b2b0b48
|
diff --git a/src/parse/converters/element.js b/src/parse/converters/element.js
index <HASH>..<HASH> 100644
--- a/src/parse/converters/element.js
+++ b/src/parse/converters/element.js
@@ -24,6 +24,7 @@ define([
validTagNameFollower = /^[\s\n\/>]/,
onPattern = /^on/,
proxyEventPattern = /^on-([a-zA-Z$_][a-zA-Z$_0-9\-]+)/,
+ reservedEventNames = /(?:change|reset|teardown|update)/,
directives = { 'intro-outro': 't0', intro: 't1', outro: 't2', decorator: 'o' },
exclude = { exclude: true },
converters;
@@ -93,6 +94,13 @@ define([
}
addProxyEvent = function ( name ) {
+ var directiveName = directive.n || directive;
+
+ if ( reservedEventNames.test( directiveName ) ) {
+ parser.pos -= directiveName.length;
+ parser.error( 'Cannot use reserved event names (change, reset, teardown, update)' );
+ }
+
element.v[ name ] = directive;
};
diff --git a/test/samples/parse.js b/test/samples/parse.js
index <HASH>..<HASH> 100644
--- a/test/samples/parse.js
+++ b/test/samples/parse.js
@@ -733,6 +733,12 @@ var parseTests = [
[ { t: 2,
p: [ 1, 20 ],
r: 'mustache' } ] } ] } ]
+ },
+ {
+ name: 'Reserved event names cannot be used for proxy events',
+ template: '<div on-foo="change"></div>',
+ error: 'Cannot use reserved event names (change, reset, teardown, update) at line 1 character 15:\n' +
+ '<div on-foo=\"change\"></div>\n ^----'
}
];
|
closes #<I> - reserved event names cannot be used in templates
|
ractivejs_ractive
|
train
|
c558ce6c2d1f8cb102511cac4d0ed8f01e01d345
|
diff --git a/lib/cocoaseeds/core.rb b/lib/cocoaseeds/core.rb
index <HASH>..<HASH> 100644
--- a/lib/cocoaseeds/core.rb
+++ b/lib/cocoaseeds/core.rb
@@ -541,7 +541,7 @@ module Seeds
if seed.source_dir
full_source_path = File.expand_path(seed.source_dir)
- command = "cp -R #{full_source_path}/ #{self.root_path}/Seeds/#{seed.name}"
+ command = "cp -R #{full_source_path}/* #{self.root_path}/Seeds/#{seed.name}"
output = `#{command}`
else
raise Seeds::Exception.new\
|
Copy all contents of directory instead of directory itself
|
devxoul_CocoaSeeds
|
train
|
db688de477f0b6baaf65b08b55ef8c9c98079723
|
diff --git a/lib/mws/apis/orders.rb b/lib/mws/apis/orders.rb
index <HASH>..<HASH> 100644
--- a/lib/mws/apis/orders.rb
+++ b/lib/mws/apis/orders.rb
@@ -7,8 +7,10 @@ class Mws::Apis::Orders
def list(options={})
options[:version] ||= '2011-01-01'
options[:action] = 'ListOrders'
- response = @connection.get(:orders, options)
- response['Orders'] || []
+ doc = @connection.get(:orders, options)
+ doc.find('mws:Orders/mws:Order').map do | node |
+ 'Someday this will be an Order'
+ end
end
end
diff --git a/lib/mws/connection.rb b/lib/mws/connection.rb
index <HASH>..<HASH> 100644
--- a/lib/mws/connection.rb
+++ b/lib/mws/connection.rb
@@ -1,5 +1,6 @@
-require 'faraday'
-require 'faraday_middleware'
+require 'uri'
+require 'net/http'
+require 'xml'
class Mws::Connection
@@ -11,14 +12,6 @@ class Mws::Connection
@merchant = options[:merchant]
@access = options[:access]
@secret = options[:secret]
- @conn = Faraday.new(url: "#{@scheme}://#{@host}") do | faraday |
- faraday.adapter Faraday.default_adapter
- faraday.headers = {
- 'User-Agent' => 'MWS Client/0.0.1 (Language=Ruby)',
- 'Accept-Encoding' => 'text/xml'
- }
- faraday.response :xml, content_type: /\bxml$/
- end
@orders = Mws::Apis::Orders.new self
@feeds = Mws::Apis::Feeds.new self
end
@@ -39,16 +32,26 @@ class Mws::Connection
options[:access] ||= @access
query = Mws::Query.new options, derive_list_ext
signer = Mws::Signer.new method: method, host: @host, path: path, secret: @secret
- response = @conn.send(method, "#{path}?#{signer.sign query}") do | request |
- unless body.nil?
- request.headers['Content-Type'] = 'text/xml'
- req.body = body
- end
+ uri = URI("#{@scheme}://#{@host}#{path}?#{signer.sign query}")
+ req = Net::HTTP.const_get(method.to_s.capitalize).new (uri.request_uri)
+ req['User-Agent'] = 'MWS Client/0.0.1 (Language=Ruby)'
+ req['Accept-Encoding'] = 'text/xml'
+ if req.request_body_permitted? and body
+ req.content_type = 'text/xml'
+ req.body = body
+ end
+ res = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') do | http |
+ http.request req
+ end
+ raise "Code: #{res.code}, Message :#{res.msg}" if res.body.nil?
+ doc = XML::Parser.string(res.body).parse
+ doc.root.namespaces.default_prefix = 'mws'
+ doc.find('/mws:ErrorResponse/mws:Error').each do | error |
+ message = []
+ error.each_element { |node| message << "#{node.name}: #{node.child}" }
+ raise message.join ", "
end
- raise "#{response.code}:#{response.message}" if response.body.nil?
- error = response.body['ErrorResponse']
- raise "Type: #{error['Error']['Type']}, Message: #{error['Error']['Message']}" unless error.nil?
- response.body["#{options[:action]}Response"]["#{options[:action]}Result"]
+ doc.find_first "mws:#{options[:action]}Result"
end
end
diff --git a/mws.gemspec b/mws.gemspec
index <HASH>..<HASH> 100644
--- a/mws.gemspec
+++ b/mws.gemspec
@@ -17,6 +17,5 @@ Gem::Specification.new do |gem|
gem.test_files = gem.files.grep(%r{^(test|spec|features)/})
gem.require_paths = ['lib']
gem.add_development_dependency 'rspec'
- gem.add_dependency 'faraday'
- gem.add_dependency 'faraday_middleware'
+ gem.add_dependency 'libxml-ruby'
end
|
converted to libxml-ruby and Net::HTTP
|
bitbutcher_mws
|
train
|
7783bde437b6cf19cf0f9db4b11ec51efc759f40
|
diff --git a/pyrtl/__init__.py b/pyrtl/__init__.py
index <HASH>..<HASH> 100644
--- a/pyrtl/__init__.py
+++ b/pyrtl/__init__.py
@@ -1,7 +1,6 @@
# core rtl constructs
from core import Block
-from core import BlockIterator
from core import PyrtlError
from core import PyrtlInternalError
from core import working_block
|
Removing the block iterator from the __init__ file
|
UCSBarchlab_PyRTL
|
train
|
25e28eedbb31e1661aeca294ce6bb51edbd18fee
|
diff --git a/solvebio/resource/apiresource.py b/solvebio/resource/apiresource.py
index <HASH>..<HASH> 100644
--- a/solvebio/resource/apiresource.py
+++ b/solvebio/resource/apiresource.py
@@ -224,47 +224,3 @@ class UpdateableAPIResource(APIResource):
continue
params[k] = getattr(obj, k) or ""
return params
-
-
-class UploadableAPIResource(APIResource):
- """Defines *create()*, *create_from_file()* and
- *create_from_url()* methods which allow one to upload a (VCF) file
- to be stored on the system.
- """
-
- @classmethod
- def create(cls, genome_build, **params):
- if 'vcf_url' in params:
- if 'vcf_file' in params:
- raise TypeError('Specified both vcf_url and vcf_file; ' +
- 'use only one')
- return cls.create_from_url(genome_build, params['vcf_url'])
- elif 'vcf_file' in params:
- return cls.create_from_file(genome_build, params['vcf_file'])
- else:
- raise TypeError('Must specify exactly one of vcf_url or ' +
- 'vcf_file parameter')
-
- @classmethod
- def create_from_file(cls, genome_build, vcf_file):
- """Creates from the specified file. The data of
- the should be in VCF format."""
-
- files = {'vcf_file': open(vcf_file, 'rb')}
- params = {'genome_build': genome_build}
- response = client.request('post', cls.class_url(), params=params,
- files=files)
- return convert_to_solve_object(response)
-
- @classmethod
- def create_from_url(cls, genome_build, vcf_url):
- """Creates from the specified URL. The data of
- the should be in VCF format."""
-
- params = {'genome_build': genome_build,
- 'vcf_url': vcf_url}
- try:
- response = client.request('post', cls.class_url(), params=params)
- except SolveError as response:
- pass
- return convert_to_solve_object(response)
diff --git a/solvebio/resource/sample.py b/solvebio/resource/sample.py
index <HASH>..<HASH> 100644
--- a/solvebio/resource/sample.py
+++ b/solvebio/resource/sample.py
@@ -1,13 +1,58 @@
"""Solvebio API Resource for Samples"""
from .apiresource import DeletableAPIResource, DownloadableAPIResource, \
- ListableAPIResource, UploadableAPIResource
+ ListableAPIResource
+from ..client import client
+from ..errors import SolveError
+from .solveobject import convert_to_solve_object
class Sample(DeletableAPIResource, DownloadableAPIResource,
- ListableAPIResource, UploadableAPIResource):
+ ListableAPIResource):
"""
Samples are VCF files uploaded to the SolveBio API. We currently
support uncompressed, extension `.vcf`, and gzip-compressed, extension
`.vcf.gz`, VCF files. Any other extension will be rejected.
"""
+
+ """Defines *create()*, *create_from_file()* and
+ *create_from_url()* methods which allow one to upload a (VCF) file
+ to be stored on the system.
+ """
+
+ @classmethod
+ def create(cls, genome_build, **params):
+ if 'vcf_url' in params:
+ if 'vcf_file' in params:
+ raise TypeError('Specified both vcf_url and vcf_file; ' +
+ 'use only one')
+ return cls.create_from_url(genome_build, params['vcf_url'])
+ elif 'vcf_file' in params:
+ return cls.create_from_file(genome_build, params['vcf_file'])
+ else:
+ raise TypeError('Must specify exactly one of vcf_url or ' +
+ 'vcf_file parameter')
+
+ @classmethod
+ def create_from_file(cls, genome_build, vcf_file):
+ """Creates from the specified file. The data of
+ the should be in VCF format."""
+
+ files = {'vcf_file': open(vcf_file, 'rb')}
+ params = {'genome_build': genome_build}
+ response = client.request('post', cls.class_url(), params=params,
+ files=files)
+ return convert_to_solve_object(response)
+
+ @classmethod
+ def create_from_url(cls, genome_build, vcf_url):
+ """Creates from the specified URL. The data of
+ the should be in VCF format."""
+
+ params = {'genome_build': genome_build,
+ 'vcf_url': vcf_url}
+ try:
+ response = client.request('post', cls.class_url(), params=params)
+ except SolveError as response:
+ pass
+ return convert_to_solve_object(response)
|
Remove UploadableAPIResource and add code to Sample where it is the only place it is used.
|
solvebio_solvebio-python
|
train
|
ba953c38782a4cc36005434a09c2b7c4faf3cad4
|
diff --git a/app/assets/javascripts/jquery/active_scaffold.js b/app/assets/javascripts/jquery/active_scaffold.js
index <HASH>..<HASH> 100644
--- a/app/assets/javascripts/jquery/active_scaffold.js
+++ b/app/assets/javascripts/jquery/active_scaffold.js
@@ -441,7 +441,7 @@ var ActiveScaffold = {
replace: function(element, html) {
if (typeof(element) == 'string') element = '#' + element;
element = jQuery(element);
- var new_element = typeof(html) == 'string' ? jQuery.parseHTML(html.trim()) : html;
+ var new_element = typeof(html) == 'string' ? jQuery.parseHTML(html.trim(), true) : html;
new_element = jQuery(new_element);
element.replaceWith(new_element);
new_element.trigger('as:element_updated');
|
keep scripts on parsing html
|
activescaffold_active_scaffold
|
train
|
2570c62624253050b7a7878014a8fcf33c300989
|
diff --git a/lib/bitcoin_payments/client.rb b/lib/bitcoin_payments/client.rb
index <HASH>..<HASH> 100644
--- a/lib/bitcoin_payments/client.rb
+++ b/lib/bitcoin_payments/client.rb
@@ -78,12 +78,15 @@ module BitcoinPayments
received_payment = ReceivedPayment.create!(
payment: Payment.new(
+ # payment from this address
btc_address: BtcAddress.find_or_initialize_by(
public_key: get_sender_address(transaction['txid'])
),
amount: transaction['amount'],
txid: transaction['txid'],
),
+ # paid to this address
+ btc_address: btc_address,
)
LoggerHelper.ts_puts("received_payment created: #{received_payment.inspect}")
diff --git a/lib/bitcoin_payments/models/btc_address.rb b/lib/bitcoin_payments/models/btc_address.rb
index <HASH>..<HASH> 100644
--- a/lib/bitcoin_payments/models/btc_address.rb
+++ b/lib/bitcoin_payments/models/btc_address.rb
@@ -3,6 +3,7 @@ module BitcoinPayments::Models::BtcAddress
included do
has_many(:payments, inverse_of: :btc_address)
+ has_many(:received_payments, inverse_of: :btc_address)
validates(:public_key, presence: true, uniqueness: { case_sensitive: true })
diff --git a/lib/bitcoin_payments/models/payment.rb b/lib/bitcoin_payments/models/payment.rb
index <HASH>..<HASH> 100644
--- a/lib/bitcoin_payments/models/payment.rb
+++ b/lib/bitcoin_payments/models/payment.rb
@@ -2,6 +2,8 @@ module BitcoinPayments::Models::Payment
extend ActiveSupport::Concern
included do
+ # sender's address for received payments
+ # payee address for sent payments
belongs_to(:btc_address, inverse_of: :payments, dependent: :destroy)
has_one(:received_payment, inverse_of: :payment)
diff --git a/lib/bitcoin_payments/models/received_payment.rb b/lib/bitcoin_payments/models/received_payment.rb
index <HASH>..<HASH> 100644
--- a/lib/bitcoin_payments/models/received_payment.rb
+++ b/lib/bitcoin_payments/models/received_payment.rb
@@ -3,7 +3,7 @@ module BitcoinPayments::Models::ReceivedPayment
included do
belongs_to(:payment, inverse_of: :received_payment, dependent: :destroy)
- belongs_to(:btc_address, inverse_of: :received_payments)
+ belongs_to(:btc_address, inverse_of: :received_payments) # payment to this address
validates(:payment, presence: true)
validates(:payment_id, uniqueness: true)
|
received payment has sender and receiver addresses
|
lihanli_bitcoin_active_record
|
train
|
90b758869e21155f57dd59c9969e770b717f5e02
|
diff --git a/bundles/BlockManagerBundle/Templating/Twig/Extension/RenderingExtension.php b/bundles/BlockManagerBundle/Templating/Twig/Extension/RenderingExtension.php
index <HASH>..<HASH> 100644
--- a/bundles/BlockManagerBundle/Templating/Twig/Extension/RenderingExtension.php
+++ b/bundles/BlockManagerBundle/Templating/Twig/Extension/RenderingExtension.php
@@ -289,7 +289,6 @@ class RenderingExtension extends Twig_Extension implements Twig_Extension_Global
$blockDefinition = $block->getBlockDefinition();
if ($blockDefinition instanceof TwigBlockDefinitionInterface) {
$blockParams['twig_block_content'] = $this->renderTwigBlock(
- $block,
$blockDefinition->getTwigBlockName($block),
$twigTemplate,
$twigContext,
@@ -336,15 +335,16 @@ class RenderingExtension extends Twig_Extension implements Twig_Extension_Global
/**
* Renders the provided Twig block.
*
- * @param \Netgen\BlockManager\API\Values\Page\Block $block
* @param string $twigBlockName
* @param \Twig_Template $twigTemplate
* @param array $twigContext
* @param array $twigBlocks
*
+ * @throws \Exception If rendering failed
+ *
* @return string
*/
- protected function renderTwigBlock(Block $block, $twigBlockName, Twig_Template $twigTemplate, array $twigContext = array(), array $twigBlocks = array())
+ protected function renderTwigBlock($twigBlockName, Twig_Template $twigTemplate, array $twigContext = array(), array $twigBlocks = array())
{
$level = ob_get_level();
ob_start();
|
Remove unused param in rendering extension
|
netgen-layouts_layouts-core
|
train
|
14fbb21bd2a827fda5a82ff9e1358f6c9d95ffd8
|
diff --git a/resources/lang/vi-VN/cachet.php b/resources/lang/vi-VN/cachet.php
index <HASH>..<HASH> 100644
--- a/resources/lang/vi-VN/cachet.php
+++ b/resources/lang/vi-VN/cachet.php
@@ -14,7 +14,7 @@ return [
'components' => [
'last_updated' => 'Lần cập nhật cuối :timestamp',
'status' => [
- 0 => 'Unknown',
+ 0 => 'Không biết',
1 => 'Hoạt động',
2 => 'Vấn đề hiệu suất',
3 => 'Ngưng hoạt động một phần',
@@ -28,11 +28,12 @@ return [
// Incidents
'incidents' => [
'none' => 'Không có báo cáo về sự số nào',
- 'past' => 'Sự số trong quá khứ',
- 'stickied' => 'Stickied Incidents',
+ 'past' => 'Các sự số trong quá khứ',
+ 'stickied' => 'Sự cố Stickied',
'scheduled' => 'Bảo trì định kỳ',
'scheduled_at' => ', định kỳ :timestamp',
- 'posted' => 'Posted :timestamp',
+ 'posted' => 'Đã đăng :timestamp',
+ 'posted_at' => 'Posted at :timestamp',
'status' => [
1 => 'Đang điều tra',
2 => 'Xác định',
@@ -44,9 +45,9 @@ return [
// Schedule
'schedules' => [
'status' => [
- 0 => 'Upcoming',
- 1 => 'In Progress',
- 2 => 'Complete',
+ 0 => 'Sắp tới',
+ 1 => 'Đang xử lý',
+ 2 => 'Hoàn thành',
],
],
@@ -65,8 +66,8 @@ return [
// Metrics
'metrics' => [
'filter' => [
- 'last_hour' => 'Last Hour',
- 'hourly' => 'Last 12 Hours',
+ 'last_hour' => 'Giờ trước',
+ 'hourly' => '12 giờ trước',
'weekly' => 'Tuần',
'monthly' => 'Tháng',
],
@@ -74,22 +75,22 @@ return [
// Subscriber
'subscriber' => [
- 'subscribe' => 'Subscribe to get the updates',
+ 'subscribe' => 'Đăng ký để nhận các thông báo cập nhật',
'unsubscribe' => 'Unsubscribe at :link',
'button' => 'Đăng ký',
'manage' => [
- 'no_subscriptions' => 'You\'re currently subscribed to all updates.',
- 'my_subscriptions' => 'You\'re currently subscribed to the following updates.',
+ 'no_subscriptions' => 'Bạn hiện đã đăng ký nhận tất cả các thông báo cập nhật.',
+ 'my_subscriptions' => 'Bạn hiện đã đăng ký nhận các thông báo cập nhật sau.',
],
'email' => [
- 'subscribe' => 'Subscribe to email updates.',
- 'subscribed' => 'You\'ve been subscribed to email notifications, please check your email to confirm your subscription.',
- 'verified' => 'Your email subscription has been confirmed. Thank you!',
- 'manage' => 'Manage your subscription',
- 'unsubscribe' => 'Unsubscribe from email updates.',
- 'unsubscribed' => 'Your email subscription has been cancelled.',
- 'failure' => 'Something went wrong with the subscription.',
- 'already-subscribed' => 'Cannot subscribe :email because they\'re already subscribed.',
+ 'subscribe' => 'Đăng ký nhận thông báo cập nhật qua email.',
+ 'subscribed' => 'Bạn đã đăng ký nhận email thông báo cập nhật, xin vui lòng kiểm tra email của bạn để xác nhận.',
+ 'verified' => 'Đăng ký email của bạn đã được xác nhận. Cảm ơn bạn!',
+ 'manage' => 'Quản lý đăng ký',
+ 'unsubscribe' => 'Hủy đăng ký thông báo cập nhật qua email.',
+ 'unsubscribed' => 'Đăng ký email của bạn đã bị hủy bỏ.',
+ 'failure' => 'Có lỗi xảy ra khi đăng ký nhận thông báo cập nhật.',
+ 'already-subscribed' => 'Không thể đăng ký :email bởi vì họ đã đăng ký.',
],
],
|
New translations cachet.php (Vietnamese)
|
CachetHQ_Cachet
|
train
|
2f2019a42d8bf3c9101999f204079fdaf7411b0d
|
diff --git a/code/DMSSiteTreeExtension.php b/code/DMSSiteTreeExtension.php
index <HASH>..<HASH> 100644
--- a/code/DMSSiteTreeExtension.php
+++ b/code/DMSSiteTreeExtension.php
@@ -42,7 +42,7 @@ class DMSSiteTreeExtension extends DataExtension {
sprintf(
'<a class="ss-ui-button ss-ui-action-constructive cms-panel-link" data-pjax-target="Content" data-icon="add" href="%s">%s</a>',
Controller::join_links(singleton('DMSDocumentAddController')->Link(), '?ID=' . $this->owner->ID),
- "Add Document"
+ "Add Documents"
)
);
|
MINOR: changing button label to indicate that multiple documents can be added at once
|
silverstripe_silverstripe-dms
|
train
|
48cbc21e22bf621986990da77fb8ec6e5c4514e8
|
diff --git a/tasks/shared-config.js b/tasks/shared-config.js
index <HASH>..<HASH> 100644
--- a/tasks/shared-config.js
+++ b/tasks/shared-config.js
@@ -156,7 +156,8 @@ module.exports = function( grunt ) {
function getSassSafeValue( value ) {
if ( mout.lang.isArray( value ) ) {
- return '(' + normalizeArrayValue( value, getSassSafeValue, ", " ) + ')';
+ var arrayString = normalizeArrayValue( value, getSassSafeValue, ', ' );
+ return '(' + arrayString + ')';
}
return getStyleSafeValue( value );
}
@@ -193,6 +194,11 @@ module.exports = function( grunt ) {
css: [ "scss", "sass", "less", "styl" ]
};
+ // variable converters
+ var styleConverter = {
+ scss: getSassSafeValue,
+ sass: getSassSafeValue
+ };
// variable patterns
var outputPattern = {
@@ -206,16 +212,6 @@ module.exports = function( grunt ) {
js: "var {{name}} = {{vars}};\n"
};
- var valueConverter = {
- scss: getSassSafeValue,
- sass: getSassSafeValue,
- css: getStyleSafeValue,
- sassmaps: getSassSafeValue,
- styl: getStyleSafeValue,
- less: getStyleSafeValue
- };
-
-
// Normalize user input
options.dest = normalizeOutArray( options.dest );
options.jsFormat = normalizeFormat( options.jsFormat );
@@ -242,8 +238,8 @@ module.exports = function( grunt ) {
resolveNested( data[ key ], name );
} else {
-
- var value = valueConverter[ type ]( data[ key ] );
+ var converter = styleConverter[ type ] || getStyleSafeValue;
+ var value = converter( data[ key ] );
content += pattern.replace( "{{key}}", options.namespace + name ).replace( "{{value}}", value );
}
@@ -266,6 +262,13 @@ module.exports = function( grunt ) {
return options.singlequote ? output.replace( /"/g, "'" ) : output;
}
+ function generateJSON( data ) {
+ var preparedData = prepareValues( data );
+
+ var content = JSON.stringify( preparedData, null, options.indention );
+ return options.singlequote ? content.replace( /"/g, "'" ) : content;
+ }
+
function generateAMD( data ) {
var preparedData = prepareValues( data );
var content = JSON.stringify( preparedData, null, options.indention );
@@ -301,14 +304,9 @@ module.exports = function( grunt ) {
var sassMapStr = "";
var currentValue;
- for ( key in data ) {
- if ( data.hasOwnProperty( key ) ) {
- if ( mout.lang.isObject( data[ key ] ) ) {
- currentValue = generateSassMapsRecursive( data[ key ] );
- } else {
- currentValue = valueConverter.sassmaps( data[ key ] );
- }
-
+ if ( mout.lang.isObject( data ) ) {
+ for ( key in data ) {
+ currentValue = generateSassMapsRecursive( data[ key ] );
currentItem = pattern.replace( "{{key}}", key ).replace( "{{value}}", currentValue );
if ( first ) {
@@ -320,6 +318,11 @@ module.exports = function( grunt ) {
sassMapStr = sassMapStr.replace( ",\n" + options.indention + ")", "\n" + options.indention + ")" );
}
+ } else if ( mout.lang.isArray( data ) ) {
+ var arrayString = normalizeArrayValue( data, generateSassMapsRecursive, ', ' );
+ return '(' + arrayString + ')';
+ } else {
+ return getStyleSafeValue( data );
}
// the slice removes the last comma
@@ -506,6 +509,10 @@ module.exports = function( grunt ) {
generator = generateSassMaps;
+ } else if ( fileType === "json" ) {
+
+ generator = generateJSON;
+
} else if ( mout.array.contains( fileExtensions.css, fileType ) ) {
generator = generateStyle;
@@ -540,4 +547,4 @@ module.exports = function( grunt ) {
} );
-};
+};
\ No newline at end of file
|
Adapted generateSassMapsRecursive to support nested lists.
|
MathiasPaumgarten_grunt-shared-config
|
train
|
3cec781067a6fab74c2b20d24d343f27906c0df1
|
diff --git a/Neos.Cache/Tests/Unit/Frontend/StringFrontendTest.php b/Neos.Cache/Tests/Unit/Frontend/StringFrontendTest.php
index <HASH>..<HASH> 100644
--- a/Neos.Cache/Tests/Unit/Frontend/StringFrontendTest.php
+++ b/Neos.Cache/Tests/Unit/Frontend/StringFrontendTest.php
@@ -13,9 +13,11 @@ include_once(__DIR__ . '/../../BaseTestCase.php');
* source code.
*/
use Neos\Cache\Backend\AbstractBackend;
-use Neos\Cache\Tests\BaseTestCase;
+use Neos\Cache\Backend\NullBackend;
use Neos\Cache\Backend\TaggableBackendInterface;
+use Neos\Cache\Exception\NotSupportedByBackendException;
use Neos\Cache\Frontend\StringFrontend;
+use Neos\Cache\Tests\BaseTestCase;
/**
* Testcase for the string cache frontend
@@ -131,13 +133,24 @@ class StringFrontendTest extends BaseTestCase
/**
* @test
+ * @expectedException \Neos\Cache\Exception\NotSupportedByBackendException
+ */
+ public function getByTagThrowAnExceptionWithoutTaggableBackend()
+ {
+ $backend = $this->prepareDefaultBackend();
+ $cache = new StringFrontend('VariableFrontend', $backend);
+ $cache->getByTag('foo');
+ }
+
+ /**
+ * @test
*/
public function getByTagCallsBackendAndReturnsIdentifiersAndValuesOfEntries()
{
$tag = 'sometag';
$identifiers = ['one', 'two'];
$entries = ['one' => 'one value', 'two' => 'two value'];
- $backend = $this->prepareDefaultBackend();
+ $backend = $this->prepareTaggableBackend();
$backend->expects($this->once())->method('findIdentifiersByTag')->with($this->equalTo($tag))->will($this->returnValue($identifiers));
$backend->expects($this->exactly(2))->method('get')->will($this->onConsecutiveCalls('one value', 'two value'));
@@ -157,4 +170,16 @@ class StringFrontendTest extends BaseTestCase
->disableOriginalConstructor()
->getMock();
}
+
+ /**
+ * @param array $methods
+ * @return AbstractBackend|\PHPUnit_Framework_MockObject_MockObject
+ */
+ protected function prepareTaggableBackend(array $methods = ['get', 'set', 'has', 'remove', 'findIdentifiersByTag', 'flush', 'flushByTag', 'collectGarbage'])
+ {
+ return $this->getMockBuilder(NullBackend::class)
+ ->setMethods($methods)
+ ->disableOriginalConstructor()
+ ->getMock();
+ }
}
diff --git a/Neos.Cache/Tests/Unit/Frontend/VariableFrontendTest.php b/Neos.Cache/Tests/Unit/Frontend/VariableFrontendTest.php
index <HASH>..<HASH> 100644
--- a/Neos.Cache/Tests/Unit/Frontend/VariableFrontendTest.php
+++ b/Neos.Cache/Tests/Unit/Frontend/VariableFrontendTest.php
@@ -13,6 +13,8 @@ include_once(__DIR__ . '/../../BaseTestCase.php');
* source code.
*/
use Neos\Cache\Backend\AbstractBackend;
+use Neos\Cache\Backend\NullBackend;
+use Neos\Cache\Exception\NotSupportedByBackendException;
use Neos\Cache\Tests\BaseTestCase;
use Neos\Cache\Backend\TaggableBackendInterface;
use Neos\Cache\Frontend\StringFrontend;
@@ -187,13 +189,24 @@ class VariableFrontendTest extends BaseTestCase
/**
* @test
+ * @expectedException \Neos\Cache\Exception\NotSupportedByBackendException
+ */
+ public function getByTagThrowAnExceptionWithoutTaggableBackend()
+ {
+ $backend = $this->prepareDefaultBackend();
+ $cache = new VariableFrontend('VariableFrontend', $backend);
+ $cache->getByTag('foo');
+ }
+
+ /**
+ * @test
*/
public function getByTagCallsBackendAndReturnsIdentifiersAndValuesOfEntries()
{
$tag = 'sometag';
$identifiers = ['one', 'two'];
$entries = ['one' => 'one value', 'two' => 'two value'];
- $backend = $this->prepareDefaultBackend();
+ $backend = $this->prepareTaggableBackend();
$backend->expects($this->once())->method('findIdentifiersByTag')->with($this->equalTo($tag))->will($this->returnValue($identifiers));
$backend->expects($this->exactly(2))->method('get')->will($this->onConsecutiveCalls(serialize('one value'), serialize('two value')));
@@ -232,4 +245,16 @@ class VariableFrontendTest extends BaseTestCase
->disableOriginalConstructor()
->getMock();
}
+
+ /**
+ * @param array $methods
+ * @return AbstractBackend|\PHPUnit_Framework_MockObject_MockObject
+ */
+ protected function prepareTaggableBackend(array $methods = ['get', 'set', 'has', 'remove', 'findIdentifiersByTag', 'flush', 'flushByTag', 'collectGarbage'])
+ {
+ return $this->getMockBuilder(NullBackend::class)
+ ->setMethods($methods)
+ ->disableOriginalConstructor()
+ ->getMock();
+ }
}
|
TASK: Adapt test to check cache backend tangible behaviour
|
neos_flow-development-collection
|
train
|
3cd1ebce8728e0f4f1c5b7c3c1c3f74348cc1301
|
diff --git a/src/Bellhop.spec.js b/src/Bellhop.spec.js
index <HASH>..<HASH> 100644
--- a/src/Bellhop.spec.js
+++ b/src/Bellhop.spec.js
@@ -33,10 +33,16 @@ describe('Bellhop Client', () => {
});
it('Trigger should call event', done => {
- bellhop.on('highscore', () => {
- done();
+ bellhop.on('highscore', $event => {
+ expect($event.data).to.be.a('object');
});
bellhop.trigger('highscore');
+
+ bellhop.on('data', $event => {
+ expect($event.data.foo).to.equal('bar');
+ done();
+ });
+ bellhop.trigger('data', { foo: 'bar' });
});
it('Should be able to remove events', () => {
diff --git a/src/BellhopEventDispatcher.js b/src/BellhopEventDispatcher.js
index <HASH>..<HASH> 100644
--- a/src/BellhopEventDispatcher.js
+++ b/src/BellhopEventDispatcher.js
@@ -80,11 +80,13 @@ export class BellhopEventDispatcher {
* Trigger any event handlers for an event type
* @method trigger
* @param {Object | String} event The event to send
+ * @param {*} [data = undefined] optional data to send to other locations in the app that are listening for this event
*/
- trigger(event) {
+ trigger(event, data = {}) {
if (typeof event == 'string') {
event = {
- type: event
+ type: event,
+ data: 'object' === typeof data && null !== data ? data : {}
};
}
|
Added the option to pass data to other parts of the app through trigger
|
SpringRoll_Bellhop
|
train
|
033aed68a4fb0b413fe40e600fdf4464bba19feb
|
diff --git a/spec/stack_master/role_assumer_spec.rb b/spec/stack_master/role_assumer_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/stack_master/role_assumer_spec.rb
+++ b/spec/stack_master/role_assumer_spec.rb
@@ -3,6 +3,7 @@ RSpec.describe StackMaster::RoleAssumer do
let(:account) { '1234567890' }
let(:role) { 'my-role' }
+ let(:role_arn) { "arn:aws:iam::#{account}:role/#{role}" }
describe '#assume_role' do
let(:assume_role) { role_assumer.assume_role(account, role, &my_block) }
@@ -15,7 +16,7 @@ RSpec.describe StackMaster::RoleAssumer do
it 'calls the assume role API once' do
expect(Aws::AssumeRoleCredentials).to receive(:new).with(
- role_arn: "arn:aws:iam::#{account}:role/#{role}",
+ role_arn: role_arn,
role_session_name: instance_of(String)
).once
@@ -32,7 +33,7 @@ RSpec.describe StackMaster::RoleAssumer do
it 'assumes the role before calling block' do
expect(Aws::AssumeRoleCredentials).to receive(:new).with(
- role_arn: "arn:aws:iam::#{account}:role/#{role}",
+ role_arn: role_arn,
role_session_name: instance_of(String)
).ordered
expect(my_block).to receive(:call).ordered
@@ -116,7 +117,7 @@ RSpec.describe StackMaster::RoleAssumer do
context 'with the same account and role' do
it 'assumes the role once' do
expect(Aws::AssumeRoleCredentials).to receive(:new).with(
- role_arn: "arn:aws:iam::#{account}:role/#{role}",
+ role_arn: role_arn,
role_session_name: instance_of(String)
).once
@@ -128,7 +129,7 @@ RSpec.describe StackMaster::RoleAssumer do
context 'with a different account' do
it 'assumes each role once' do
expect(Aws::AssumeRoleCredentials).to receive(:new).with(
- role_arn: "arn:aws:iam::#{account}:role/#{role}",
+ role_arn: role_arn,
role_session_name: instance_of(String)
).once
expect(Aws::AssumeRoleCredentials).to receive(:new).with(
@@ -144,7 +145,7 @@ RSpec.describe StackMaster::RoleAssumer do
context 'with a different role' do
it 'assumes each role once' do
expect(Aws::AssumeRoleCredentials).to receive(:new).with(
- role_arn: "arn:aws:iam::#{account}:role/#{role}",
+ role_arn: role_arn,
role_session_name: instance_of(String)
).once
expect(Aws::AssumeRoleCredentials).to receive(:new).with(
|
DRY up the role arn use in role assumer spec
|
envato_stack_master
|
train
|
60a4ad0c528a06915728daa8eb019a461416c83e
|
diff --git a/frame.go b/frame.go
index <HASH>..<HASH> 100644
--- a/frame.go
+++ b/frame.go
@@ -515,31 +515,14 @@ func (f *Frame) newView(path, name string) *View {
return view
}
-// DeleteView removes the standard and inverse view from the frame.
+// DeleteView removes the view from the frame.
func (f *Frame) DeleteView(name string) error {
- // Delete the standard view.
- if err := f.deleteView(ViewStandard + "_" + name); err != nil {
- return err
- }
-
- // Delete the inverse view.
- if f.InverseEnabled() {
- if err := f.deleteView(ViewInverse + "_" + name); err != nil {
- return err
- }
- }
-
- return nil
-}
-
-// deleteView removes view from the frame.
-func (f *Frame) deleteView(name string) error {
view := f.views[name]
if view == nil {
return ErrInvalidView
}
- // Close data files before deletion
+ // Close data files before deletion.
if err := view.Close(); err != nil {
return err
}
diff --git a/frame_test.go b/frame_test.go
index <HASH>..<HASH> 100644
--- a/frame_test.go
+++ b/frame_test.go
@@ -323,7 +323,7 @@ func TestFrame_DeleteView(t *testing.T) {
t.Fatal("expected view")
}
- err = f.DeleteView("v")
+ err = f.DeleteView(viewName)
if err != nil {
t.Fatal(err)
}
@@ -332,7 +332,7 @@ func TestFrame_DeleteView(t *testing.T) {
t.Fatal("view still exists in frame")
}
- // // Retrieve existing view.
+ // Recreate view with same name, verify that the old view was not reused.
view2, err := f.CreateViewIfNotExists(viewName)
if err != nil {
t.Fatal(err)
diff --git a/handler.go b/handler.go
index <HASH>..<HASH> 100644
--- a/handler.go
+++ b/handler.go
@@ -805,12 +805,6 @@ func (h *Handler) handleDeleteView(w http.ResponseWriter, r *http.Request) {
return
}
- // Check the frame for time quantum.
- if f.TimeQuantum() == "" {
- http.Error(w, "frame does not contain a Time Quantum", http.StatusBadRequest)
- return
- }
-
// Delete the view.
if err := f.DeleteView(viewName); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
diff --git a/handler_test.go b/handler_test.go
index <HASH>..<HASH> 100644
--- a/handler_test.go
+++ b/handler_test.go
@@ -1516,19 +1516,20 @@ func TestHandler_GetTimeStamp(t *testing.T) {
func TestHandler_DeleteView(t *testing.T) {
hldr := test.MustOpenHolder()
defer hldr.Close()
- hldr.MustCreateFragmentIfNotExists("i0", "f0", pilosa.ViewStandard+"_2017", 1).MustSetBits(30, (1*SliceWidth)+1)
+ viewName := pilosa.ViewStandard + "_2017"
+ hldr.MustCreateFragmentIfNotExists("i0", "f0", viewName, 1).MustSetBits(30, (1*SliceWidth)+1)
hldr.Index("i0").Frame("f0").SetTimeQuantum("YMD")
h := test.NewHandler()
h.Holder = hldr.Holder
h.Cluster = test.NewCluster(1)
w := httptest.NewRecorder()
- h.ServeHTTP(w, test.MustNewHTTPRequest("DELETE", "/index/i0/frame/f0/view/2017", strings.NewReader("")))
+ h.ServeHTTP(w, test.MustNewHTTPRequest("DELETE", "/index/i0/frame/f0/view/standard_2017", strings.NewReader("")))
if w.Code != http.StatusOK {
t.Fatalf("unexpected status code: %d", w.Code)
} else if body := w.Body.String(); body != `{}`+"\n" {
t.Fatalf("unexpected body: %s", body)
- } else if f := hldr.Index("i0").Frame("f0").View(pilosa.ViewStandard + "_2017"); f != nil {
+ } else if f := hldr.Index("i0").Frame("f0").View(viewName); f != nil {
t.Fatal("expected nil view")
}
}
|
Use the full view name in the Delete API. Will need to append the prefix: `standard_`, `inverse_`, or `field_`
|
pilosa_pilosa
|
train
|
ae9f5a04b1fe978017c1018f0cb0debd3cd6345c
|
diff --git a/lib/questionlib.php b/lib/questionlib.php
index <HASH>..<HASH> 100644
--- a/lib/questionlib.php
+++ b/lib/questionlib.php
@@ -464,13 +464,16 @@ function question_delete_course_category($category, $newcategory, $feedback=true
if (!$newcontext = context_coursecat::instance($newcategory->id)) {
return false;
}
- $topcategory = question_get_top_category($context->id, true);
- $newtopcategory = question_get_top_category($newcontext->id, true);
- question_move_category_to_context($topcategory->id, $context->id, $newcontext->id);
- $DB->set_field('question_categories', 'parent', $newtopcategory->id, array('parent' => $topcategory->id));
- // Now delete the top category.
- $DB->delete_records('question_categories', array('id' => $topcategory->id));
+ // Only move question categories if there is any question category at all!
+ if ($topcategory = question_get_top_category($context->id)) {
+ $newtopcategory = question_get_top_category($newcontext->id, true);
+
+ question_move_category_to_context($topcategory->id, $context->id, $newcontext->id);
+ $DB->set_field('question_categories', 'parent', $newtopcategory->id, array('parent' => $topcategory->id));
+ // Now delete the top category.
+ $DB->delete_records('question_categories', array('id' => $topcategory->id));
+ }
if ($feedback) {
$a = new stdClass();
|
MDL-<I> Questions: Only move question categories if there is any
|
moodle_moodle
|
train
|
7a59261354eca7c6a102e4f2a1d7b13aa2744649
|
diff --git a/lib/chef/provider/service/openbsd.rb b/lib/chef/provider/service/openbsd.rb
index <HASH>..<HASH> 100644
--- a/lib/chef/provider/service/openbsd.rb
+++ b/lib/chef/provider/service/openbsd.rb
@@ -205,16 +205,17 @@ class Chef
# The variable name used in /etc/rc.conf.local for enabling this service
def builtin_service_enable_variable_name
@bsevn ||= begin
+ result = nil
if rcd_script_found
::File.open(init_command) do |rcscript|
if m = rcscript.read.match(/^# \$OpenBSD: (\w+)[(.rc),]?/)
- return m[1] + "_flags"
+ result = m[1] + "_flags"
end
end
end
# Fallback allows us to keep running in whyrun mode when
# the script does not exist.
- @new_resource.service_name
+ result || @new_resource.service_name
end
end
|
fix caching of builtin_service_enable_variable_name
|
chef_chef
|
train
|
e92ab9550f7ecbd2fcb6666d812cdecac0beb53f
|
diff --git a/src/rsa/rsa.js b/src/rsa/rsa.js
index <HASH>..<HASH> 100644
--- a/src/rsa/rsa.js
+++ b/src/rsa/rsa.js
@@ -99,6 +99,7 @@ function RSA_decrypt ( data ) {
if ( this.key[0].compare(msg) <= 0 )
throw new RangeError("data too large");
+ var result;
if ( this.key.length > 3 ) {
var m = this.key[0],
d = this.key[2],
@@ -116,15 +117,24 @@ function RSA_decrypt ( data ) {
var h = p.reduce( u.multiply(t) );
- this.result = h.multiply(q).add(y).clamp(m.bitLength).toBytes();
+ result = h.multiply(q).add(y).clamp(m.bitLength).toBytes();
}
else {
var m = this.key[0],
d = this.key[2];
- this.result = m.power( msg, d ).toBytes();
+ result = m.power( msg, d ).toBytes();
}
+ var bytelen = m.bitLength + 7 >> 3;
+ if ( result.length < bytelen ) {
+ var r = new Uint8Array(bytelen);
+ r.set( result, bytelen - result.length );
+ result = r;
+ }
+
+ this.result = result;
+
return this;
}
|
Fix RSA.decrypt: pad with zeros up to key length
|
asmcrypto_asmcrypto.js
|
train
|
261e5d7ff4f34785c28b2cacb55fcbe9455dc3c5
|
diff --git a/src/interval_sequence_methods.py b/src/interval_sequence_methods.py
index <HASH>..<HASH> 100755
--- a/src/interval_sequence_methods.py
+++ b/src/interval_sequence_methods.py
@@ -99,7 +99,8 @@ class SequenceMethods(object):
# fails for at least one gene (CCDC18), which begins with a N, and
# throws the coordinates off
if cds_seq != self.cds_sequence:
- raise ValueError("haven't obtained the right CDS for {0}\n{1}\n\nshould be\n{2}\n".format(self.get_name(), cds_seq, self.cds_sequence))
+ raise ValueError("haven't obtained the right CDS for {0}\n{1}" + \
+ "\n\nshould be\n{2}\n".format(self.get_name(), cds_seq, self.cds_sequence))
def reverse_complement(self, seq):
""" reverse complement a DNA or RNA sequence
diff --git a/src/site_specific_rates.py b/src/site_specific_rates.py
index <HASH>..<HASH> 100755
--- a/src/site_specific_rates.py
+++ b/src/site_specific_rates.py
@@ -169,7 +169,12 @@ class SiteRates(object):
if self.masked is not None and self.masked.in_coding_region(bp):
continue
- # get the distances to the closest exon boundaries
+ # ignore sites outside the CDS region
+ if bp < min(self.gene.get_cds_start(), self.gene.get_cds_end()) or \
+ bp > max(self.gene.get_cds_start(), self.gene.get_cds_end()):
+ continue
+
+ # get the distances to the closest CDS exon boundaries
exon_start, exon_end = self.gene.find_closest_exon(bp)
self.boundary_dist = min(abs(exon_start - bp), abs(exon_end - bp))
diff --git a/unit_test/test_sequence_methods.py b/unit_test/test_sequence_methods.py
index <HASH>..<HASH> 100755
--- a/unit_test/test_sequence_methods.py
+++ b/unit_test/test_sequence_methods.py
@@ -88,6 +88,10 @@ class TestSequenceMethodsPy(unittest.TestCase):
self.gene.cds_min = 2
self.gene.cds_max = 8
+ # check that we get an error if we haven't got any reference CDS to check
+ with self.assertRaises(AttributeError):
+ self.gene.add_genomic_sequence("AAA")
+
gdna = "AAAGGCCTTT"
self.gene.cds_sequence = "AGGCTT"
@@ -104,8 +108,26 @@ class TestSequenceMethodsPy(unittest.TestCase):
with self.assertRaises(ValueError):
self.gene.add_genomic_sequence(gdna)
- def test_get_trinucleotide_around_cds_position(self):
- """ test that get_trinucleotide_around_cds_position() works correctly
+ def test_add_genomic_sequence_expanded(self):
+ """ test that add_genomic_sequence() works correctly with extra sequence
+ """
+
+ # now check when the 5' and 3' sequence is extended beyond the gene
+ self.gene.start = 1
+ self.gene.end = 9
+ self.gene.exons = [(1, 4), (6, 9)]
+ self.gene.cds = [(2, 4), (6, 8)]
+ self.gene.cds_min = 2
+ self.gene.cds_max = 8
+
+ gdna = "AAAGGCCTTT"
+ self.gene.cds_sequence = "AGGCTT"
+
+ self.gene.add_genomic_sequence(gdna, offset=1)
+ self.assertEqual(self.gene.cds_sequence, "AGGCTT")
+
+ def test_get_trinucleotide(self):
+ """ test that get_trinucleotide() works correctly
"""
self.gene.start = 0
@@ -114,6 +136,7 @@ class TestSequenceMethodsPy(unittest.TestCase):
self.gene.cds = [(2, 4), (6, 8)]
self.gene.cds_min = 2
self.gene.cds_max = 8
+ self.gene.gdna_offset = 0
self.gene.genomic_sequence = "AAAGGCCTTT"
# test CDS positions: start, end, and spanning the exon boundaries
@@ -130,6 +153,15 @@ class TestSequenceMethodsPy(unittest.TestCase):
with self.assertRaises(AssertionError):
self.gene.get_trinucleotide(10)
+
+ # test when we define the sequence by the add_genomic_sequence method
+ self.gene.start = 1
+ self.gene.end = 9
+ self.gene.exons = [(1, 4), (6, 9)]
+ self.gene.cds = [(2, 4), (6, 8)]
+ self.gene.cds_sequence = "AGGCTT"
+ self.gene.add_genomic_sequence("AAAGGCCTTT", offset=1)
+ self.assertEqual(self.gene.get_trinucleotide(2), "AAG")
def test_get_codon_sequence(self):
""" test that get_codon_sequence() works correctly
|
exclude sites up or downstream of the CDS, improved unit tests
|
jeremymcrae_denovonear
|
train
|
073c78a46ba0a74d09df6375771d82aa4ca6530a
|
diff --git a/scriptworker/artifacts.py b/scriptworker/artifacts.py
index <HASH>..<HASH> 100644
--- a/scriptworker/artifacts.py
+++ b/scriptworker/artifacts.py
@@ -225,14 +225,20 @@ def get_artifact_url(context, task_id, path):
Raises:
TaskClusterFailure: on failure.
"""
- url = urljoin(
- context.queue.options['baseUrl'],
- 'v1/' +
- unquote(context.queue.makeRoute('getLatestArtifact', replDict={
- 'taskId': task_id,
- 'name': path
- }))
- )
+ try:
+ url = unquote(context.queue.buildUrl('getLatestArtifact', task_id, path))
+ except AttributeError:
+ # taskcluster client 0.3.x
+ # XXX remove when we no longer want to support taskcluster<1.0.0
+ url = urljoin(
+ context.queue.options['baseUrl'],
+ 'v1/' +
+ unquote(context.queue.makeRoute('getLatestArtifact', replDict={
+ 'taskId': task_id,
+ 'name': path
+ }))
+ )
+
return url
diff --git a/scriptworker/test/test_artifacts.py b/scriptworker/test/test_artifacts.py
index <HASH>..<HASH> 100644
--- a/scriptworker/test/test_artifacts.py
+++ b/scriptworker/test/test_artifacts.py
@@ -17,7 +17,6 @@ from scriptworker.exceptions import ScriptWorkerRetryException
from . import touch, rw_context, event_loop, fake_session, fake_session_500, successful_queue
-# TODO avoid copying this fixture
@pytest.yield_fixture(scope='function')
def context(rw_context):
rw_context.config['artifact_expiration_hours'] = 1
@@ -162,7 +161,14 @@ def test_craft_artifact_put_headers():
# get_artifact_url {{{1
-def test_get_artifact_url():
+@pytest.mark.parametrize("tc03x", (True, False))
+def test_get_artifact_url(tc03x):
+
+ def buildUrl(*args, **kwargs):
+ if tc03x:
+ raise AttributeError("foo")
+ else:
+ return "https://netloc/v1/rel/path"
def makeRoute(*args, **kwargs):
return "rel/path"
@@ -171,6 +177,7 @@ def test_get_artifact_url():
context.queue = mock.MagicMock()
context.queue.options = {'baseUrl': 'https://netloc/'}
context.queue.makeRoute = makeRoute
+ context.queue.buildUrl = buildUrl
assert get_artifact_url(context, "x", "y") == "https://netloc/v1/rel/path"
|
fix get_artifact_url for taskcluster <I>.x, but keep <I>.x compatibility
|
mozilla-releng_scriptworker
|
train
|
1e329f4d5b987d21281f890b9987845894190229
|
diff --git a/src/mask.js b/src/mask.js
index <HASH>..<HASH> 100644
--- a/src/mask.js
+++ b/src/mask.js
@@ -320,10 +320,15 @@ angular.module('ui.mask', [])
return s !== '';
});
+ // need a string search offset in cases where the mask contains multiple identical components
+ // I.E. a mask of 99.99.99-999.99
+ var offset = 0;
return components.map(function(c) {
+ var componentPosition = maskPlaceholderCopy.indexOf(c, offset);
+ offset = componentPosition + 1;
return {
value: c,
- position: maskPlaceholderCopy.indexOf(c)
+ position: componentPosition
};
});
}
diff --git a/test/maskSpec.js b/test/maskSpec.js
index <HASH>..<HASH> 100644
--- a/test/maskSpec.js
+++ b/test/maskSpec.js
@@ -270,6 +270,13 @@ describe("uiMask", function () {
input.val("1231456").triggerHandler("change");
expect(scope.x).toBe("123456");
});
+
+ it("should mask the input properly with multiple identical mask components", function() {
+ var input = compileElement(inputHtml);
+ scope.$apply("mask = '99.99.99-999.99'");
+ input.val("811").triggerHandler("input");
+ expect(input.val()).toBe("81.1_.__-___.__");
+ });
});
describe("verify change is called", function () {
|
Fix bug caused by multiple identical mask components
Added a search offset in the getMaskComponents function so that if the
mask contains multiple identical mask components it will get the proper
string position of each component in the mask
|
angular-ui_ui-mask
|
train
|
403101d1ac374acbea13c6da802ecdc8b4abcfeb
|
diff --git a/gnsq/reader.py b/gnsq/reader.py
index <HASH>..<HASH> 100644
--- a/gnsq/reader.py
+++ b/gnsq/reader.py
@@ -211,7 +211,7 @@ class Reader(object):
self.logger.info('backoff complete, resuming normal operation')
count = self.connection_max_in_flight
- for conn in self.conns.values():
+ for conn in self.conns:
self.send_ready(conn, count)
def _poll_lookupd(self):
|
Iterate directly over conns.
|
wtolson_gnsq
|
train
|
e5641423783eb91e43df0b7ccffe14cd4c4c4373
|
diff --git a/tensorflow_probability/python/experimental/lazybones/deferred.py b/tensorflow_probability/python/experimental/lazybones/deferred.py
index <HASH>..<HASH> 100644
--- a/tensorflow_probability/python/experimental/lazybones/deferred.py
+++ b/tensorflow_probability/python/experimental/lazybones/deferred.py
@@ -65,20 +65,29 @@ class DeferredBase(special_methods.SpecialMethods):
@property
def value(self):
- return deferred_scope.DeferredScope.current_scope[self]
+ return deferred_scope.DeferredScope.current_scope[self][0]
+
+ @property
+ def frozen(self):
+ return deferred_scope.DeferredScope.current_scope[self][1]
@value.setter
- def value(self, value):
- deferred_scope.DeferredScope.current_scope[self] = value
+ def value(self, new_value):
+ old_value, old_freeze = deferred_scope.DeferredScope.current_scope[self]
+ new_freeze = new_value is not UNKNOWN
+ if new_freeze == old_freeze and new_value is old_value:
+ return
+ deferred_scope.DeferredScope.current_scope[self] = (new_value, new_freeze)
for c in self.children:
- c.value = UNKNOWN
+ if not c.frozen:
+ c.value = UNKNOWN
- def set_value_down_to(self, value, leaves):
- """Set self value and resets all children up to but not including leaves."""
- deferred_scope.DeferredScope.current_scope[self] = value
- for c in self.children:
- if not any(c is l for l in leaves):
- c.set_value_down_to(UNKNOWN, leaves)
+ @frozen.setter
+ def frozen(self, freeze):
+ old_value, old_freeze = deferred_scope.DeferredScope.current_scope[self]
+ if old_value is UNKNOWN or freeze == old_freeze:
+ return
+ deferred_scope.DeferredScope.current_scope[self] = (old_value, freeze)
@property
def parents(self):
@@ -96,10 +105,19 @@ class DeferredBase(special_methods.SpecialMethods):
# that to be a subsequent "scope hit". I.e., we need the value to be
# explicitly `UNKNOWN` to "block" cache hitting on "higher up" scope
# contexts.
- self.value = UNKNOWN
+ deferred_scope.DeferredScope.current_scope[self] = (UNKNOWN, False)
+ for c in self.children:
+ c.reset()
def eval(self):
- raise AttributeError('Must be defined.')
+ if self.value is not UNKNOWN:
+ return self.value
+ v = self._eval()
+ deferred_scope.DeferredScope.current_scope[self] = (v, False)
+ for c in self.children:
+ if not c.frozen:
+ c.value = UNKNOWN
+ return v
def __action__(self, fn, *args, **kwargs):
return Deferred(fn, self, *args, **kwargs)
@@ -239,20 +257,11 @@ class Deferred(DeferredBase):
def kwargs(self):
return self._kwargs
- def eval(self):
- if self.value is not UNKNOWN:
- return self.value
+ def _eval(self):
fn, args, kwargs = tf.nest.map_structure(
lambda x: x.eval() if isinstance(x, DeferredBase) else x,
[self.fn, self.args, self.kwargs])
- # It'd be a subtle bug to do this:
- # self.value = fn(*args, **kwargs)
- # because then children would be reset on automatic evaluation of the graph.
- # This means that user specified values might be ignored, depending on the
- # order of the eval.
- v = fn(*args, **kwargs)
- deferred_scope.DeferredScope.current_scope[self] = v
- return v
+ return fn(*args, **kwargs)
class DeferredInput(DeferredBase):
diff --git a/tensorflow_probability/python/experimental/lazybones/deferred_scope.py b/tensorflow_probability/python/experimental/lazybones/deferred_scope.py
index <HASH>..<HASH> 100644
--- a/tensorflow_probability/python/experimental/lazybones/deferred_scope.py
+++ b/tensorflow_probability/python/experimental/lazybones/deferred_scope.py
@@ -92,7 +92,7 @@ class DeferredScope(object):
if v is not _NOT_FOUND:
return v
if self._parent is None:
- return UNKNOWN
+ return UNKNOWN, False
return self._parent[k]
def __setitem__(self, k, v):
diff --git a/tensorflow_probability/python/experimental/lazybones/utils/probability.py b/tensorflow_probability/python/experimental/lazybones/utils/probability.py
index <HASH>..<HASH> 100644
--- a/tensorflow_probability/python/experimental/lazybones/utils/probability.py
+++ b/tensorflow_probability/python/experimental/lazybones/utils/probability.py
@@ -59,7 +59,7 @@ def distribution_measure(vertexes, values, attr, combine):
if v is not None:
# TODO(jvdillon): If eval recursively eval'ed we could assign this as a
# deferred try-cast.
- x.set_value_down_to(v, vertexes)
+ x.value = v
d = x.parents[0].parents[0]
distributions.append(d)
r = combine(getattr(d, attr)(x) for d, x in zip(distributions, vertexes))
|
tfp.experimental.lazybones: Annotate manually set vertices as "frozen" for
easier counterfactual graph evaluation.
PiperOrigin-RevId: <I>
|
tensorflow_probability
|
train
|
43f69381cf0544af1c74a188c176a0b450bae6f9
|
diff --git a/lib/Limitation/Mapper/SubtreeLimitationMapper.php b/lib/Limitation/Mapper/SubtreeLimitationMapper.php
index <HASH>..<HASH> 100755
--- a/lib/Limitation/Mapper/SubtreeLimitationMapper.php
+++ b/lib/Limitation/Mapper/SubtreeLimitationMapper.php
@@ -8,8 +8,6 @@
*/
namespace EzSystems\RepositoryForms\Limitation\Mapper;
-use eZ\Publish\API\Repository\LocationService;
-use eZ\Publish\API\Repository\SearchService;
use eZ\Publish\API\Repository\Values\Content\LocationQuery;
use eZ\Publish\API\Repository\Values\Content\Query\Criterion\Ancestor;
use eZ\Publish\API\Repository\Values\User\Limitation;
|
[CS] Fixed SubtreeLimitationMapper according to rule no_unused_imports
|
ezsystems_repository-forms
|
train
|
c44d2535c60946d5a6980b0f3a268767e27f9862
|
diff --git a/drwmutex.go b/drwmutex.go
index <HASH>..<HASH> 100644
--- a/drwmutex.go
+++ b/drwmutex.go
@@ -154,7 +154,7 @@ func (dm *DRWMutex) lockBlocking(isReadLock bool) {
//
func lock(clnts []RPC, locks *[]string, lockName string, isReadLock bool) bool {
- // Create buffered channel of quorum size
+ // Create buffered channel of size equal to total number of nodes.
ch := make(chan Granted, dnodeCount)
for index, c := range clnts {
@@ -216,6 +216,8 @@ func lock(clnts []RPC, locks *[]string, lockName string, isReadLock bool) bool {
// We know that we are not going to get the lock anymore, so exit out
// and release any locks that did get acquired
done = true
+ // Increment the number of grants received from the buffered channel.
+ i++
releaseAll(clnts, locks, lockName, isReadLock)
}
}
@@ -230,7 +232,6 @@ func lock(clnts []RPC, locks *[]string, lockName string, isReadLock bool) bool {
}
if done {
- i++
break
}
}
|
Update 'i' only if lock grant from buffered channel (#<I>)
|
minio_dsync
|
train
|
c3d06de1eab193e4f575219594eb60706f994db7
|
diff --git a/lavalink/models.py b/lavalink/models.py
index <HASH>..<HASH> 100644
--- a/lavalink/models.py
+++ b/lavalink/models.py
@@ -422,6 +422,15 @@ class BasePlayer(ABC):
await self.node._send(op='voiceUpdate', guildId=self._internal_id, **self._voice_state)
@abstractmethod
+ async def node_unavailable(self):
+ """|coro|
+
+ Called when a player's node becomes unavailable.
+ Useful for changing player state before it's moved to another node.
+ """
+ raise NotImplementedError
+
+ @abstractmethod
async def change_node(self, node):
"""|coro|
@@ -498,13 +507,13 @@ class DefaultPlayer(BasePlayer):
self._user_data = {}
self.paused: bool = False
+ self._internal_pause: bool = False # Toggled when player's node becomes unavailable, primarily used for track position tracking.
self._last_update = 0
self._last_position = 0
self.position_timestamp: int = 0
self.volume: int = 100
self.shuffle: bool = False
self.loop: int = 0 # 0 = off, 1 = single track, 2 = queue
- # self.equalizer = [0.0 for x in range(15)] # 0-14, -0.25 - 1.0
self.filters: Dict[str, Filter] = {}
self.queue: List[AudioTrack] = []
@@ -542,7 +551,7 @@ class DefaultPlayer(BasePlayer):
if not self.is_playing:
return 0
- if self.paused:
+ if self.paused or self._internal_pause:
return min(self._last_position, self.current.duration)
difference = time() * 1000 - self._last_update
@@ -1056,6 +1065,15 @@ class DefaultPlayer(BasePlayer):
self._last_position = state.get('position', 0)
self.position_timestamp = state.get('time', 0)
+ @abstractmethod
+ async def node_unavailable(self):
+ """|coro|
+
+ Called when a player's node becomes unavailable.
+ Useful for changing player state before it's moved to another node.
+ """
+ self._internal_pause = True
+
async def change_node(self, node):
"""|coro|
@@ -1087,6 +1105,8 @@ class DefaultPlayer(BasePlayer):
if self.paused:
await self.node._send(op='pause', guildId=self._internal_id, pause=self.paused)
+ self._internal_pause = False
+
if self.volume != 100:
await self.node._send(op='volume', guildId=self._internal_id, volume=self.volume)
diff --git a/lavalink/nodemanager.py b/lavalink/nodemanager.py
index <HASH>..<HASH> 100644
--- a/lavalink/nodemanager.py
+++ b/lavalink/nodemanager.py
@@ -213,6 +213,12 @@ class NodeManager:
reason: :class:`str`
The reason why the node was disconnected.
"""
+ for player in node.players:
+ try:
+ await player.node_unavailable()
+ except: # noqa: E722 pylint: disable=bare-except
+ _log.exception('An error occurred whilst calling player.node_unavailable()')
+
await self._lavalink._dispatch_event(NodeDisconnectedEvent(node, code, reason))
best_node = self.find_ideal_node(node.region)
|
Add node_unavailable() to BasePlayer, pause position clock during node unavailability
|
Devoxin_Lavalink.py
|
train
|
46f0ce82963f76a1d751c5ba12d9c9e51a9d4c08
|
diff --git a/tests/functional/simple_test.py b/tests/functional/simple_test.py
index <HASH>..<HASH> 100644
--- a/tests/functional/simple_test.py
+++ b/tests/functional/simple_test.py
@@ -344,10 +344,10 @@ pure_python_package
out = uncolor(out)
assert ' '.join((
'\n> virtualenv_run/bin/python -m pip.__main__ install',
- '--find-links=file://%s/.pip/wheelhouse' % tmpdir,
+ '--find-links=file://%s/home/.pip/wheelhouse' % tmpdir,
'-r requirements.d/venv-update.txt\n',
)) in out
- assert '\nSuccessfully installed pip-faster pure-python-package wheel virtualenv\n' in out
+ assert '\nSuccessfully installed pip-faster pure-python-package ' in out
assert '\n Successfully uninstalled pure-python-package\n' in out
expected = '\n'.join((
|
fun: the "successfully installed" message is not well-ordered for inferred requirements
|
Yelp_venv-update
|
train
|
4d5d063ee2bb294c92ff370530487e4556d94172
|
diff --git a/lib/index.js b/lib/index.js
index <HASH>..<HASH> 100755
--- a/lib/index.js
+++ b/lib/index.js
@@ -27,6 +27,7 @@ if (require.main === module) {
}
/**
+ * Return init method for external use
* @param {String|Array} [files]
* @param {Object} [userConfig]
*/
|
Use read stream to ensure file is greater than 0 bytes
|
BrowserSync_browser-sync
|
train
|
f80de1bd236547559a6c0e70d78bb75f062e049c
|
diff --git a/meshio/msh_io.py b/meshio/msh_io.py
index <HASH>..<HASH> 100644
--- a/meshio/msh_io.py
+++ b/meshio/msh_io.py
@@ -215,7 +215,7 @@ def write(
# 'physical' and 'geometrical' go first; this is what the gmsh
# file format prescribes
- keywords = cell_data[cell_type].keys()
+ keywords = list(cell_data[cell_type].keys())
keywords.remove('physical')
keywords.remove('geometrical')
sorted_keywords = ['physical', 'geometrical'] + keywords
@@ -225,7 +225,7 @@ def write(
num_nodes_per_cell = node_idcs.shape[1]
form = '%d ' + '%d' % meshio_to_gmsh_type[cell_type] \
- + ' %d' % len(cell_data) + ' %d' * len(cell_data) \
+ + ' %d' % fcd.shape[1] + ' %d' * fcd.shape[1] \
+ ' ' + ' '.join(num_nodes_per_cell * ['%d']) \
+ '\n'
for k, c in enumerate(node_idcs):
|
some msh fixes for python3
|
nschloe_meshio
|
train
|
872eeb57ca951935ba83a44ac3a3f0a9d9c40303
|
diff --git a/src/geo/ui/widgets/histogram/content-view.js b/src/geo/ui/widgets/histogram/content-view.js
index <HASH>..<HASH> 100644
--- a/src/geo/ui/widgets/histogram/content-view.js
+++ b/src/geo/ui/widgets/histogram/content-view.js
@@ -60,9 +60,10 @@ module.exports = WidgetContent.extend({
_storeBounds: function() {
var data = this.model.getData();
if (data && data.length > 0) {
- var start = data[0].start;
- var end = data[data.length - 1].end;
- this.model.set({ start: start, end: end, bins: data.length });
+ this.start = data[0].start;
+ this.end = data[data.length - 1].end;
+ this.binsCount = data.length;
+ this.model.set({ start: this.start, end: this.end, bins: this.binsCount });
}
},
@@ -397,7 +398,7 @@ module.exports = WidgetContent.extend({
this.lockZoomedData = false;
this.unsettingRange = true;
- this.model.set({ own_filter: null });
+ this.model.set({ start: this.start, end: this.end, bins_count: this.binsCount, own_filter: null });
this.viewModel.set({ zoom_enabled: false, filter_enabled: false, lo_index: null, hi_index: null });
this.filter.unsetRange();
|
After zoom out sends original bucket count, start and end again
|
CartoDB_carto.js
|
train
|
78001de3dad4bc3dd9a74b576680ee30a7b63d7d
|
diff --git a/src/Transport/Curl.php b/src/Transport/Curl.php
index <HASH>..<HASH> 100644
--- a/src/Transport/Curl.php
+++ b/src/Transport/Curl.php
@@ -12,7 +12,7 @@ use Joomla\Http\Exception\InvalidResponseCodeException;
use Joomla\Http\TransportInterface;
use Joomla\Http\Response;
use Joomla\Uri\UriInterface;
-use Zend\Diactoros\Stream;
+use Zend\Diactoros\Stream as StreamResponse;
/**
* HTTP transport class for using cURL.
@@ -250,7 +250,7 @@ class Curl implements TransportInterface
$verifiedHeaders[trim(substr($header, 0, $pos))] = trim(substr($header, ($pos + 1)));
}
- $streamInterface = new Stream('php://memory');
+ $streamInterface = new StreamResponse('php://memory', 'rw');
$streamInterface->write($body);
return new Response($streamInterface, $statusCode, $verifiedHeaders);
diff --git a/src/Transport/Socket.php b/src/Transport/Socket.php
index <HASH>..<HASH> 100644
--- a/src/Transport/Socket.php
+++ b/src/Transport/Socket.php
@@ -13,7 +13,7 @@ use Joomla\Http\TransportInterface;
use Joomla\Http\Response;
use Joomla\Uri\UriInterface;
use Joomla\Uri\Uri;
-use Zend\Diactoros\Stream;
+use Zend\Diactoros\Stream as StreamResponse;
/**
* HTTP transport class for using sockets directly.
@@ -234,7 +234,7 @@ class Socket implements TransportInterface
$verifiedHeaders[trim(substr($header, 0, $pos))] = trim(substr($header, ($pos + 1)));
}
- $streamInterface = new Stream('php://memory');
+ $streamInterface = new StreamResponse('php://memory', 'rw');
$streamInterface->write($body);
return new Response($streamInterface, $statusCode, $verifiedHeaders);
diff --git a/src/Transport/Stream.php b/src/Transport/Stream.php
index <HASH>..<HASH> 100644
--- a/src/Transport/Stream.php
+++ b/src/Transport/Stream.php
@@ -235,7 +235,7 @@ class Stream implements TransportInterface
$verifiedHeaders[trim(substr($header, 0, $pos))] = trim(substr($header, ($pos + 1)));
}
- $streamInterface = new StreamResponse('php://memory');
+ $streamInterface = new StreamResponse('php://memory', 'rw');
$streamInterface->write($body);
return new Response($streamInterface, $statusCode, $verifiedHeaders);
|
Create the Stream in a writable mode, alias the class
|
joomla-framework_http
|
train
|
3fa767d9ffa9cc9bcdfecbe97c046fa1077d7a60
|
diff --git a/bucket.go b/bucket.go
index <HASH>..<HASH> 100755
--- a/bucket.go
+++ b/bucket.go
@@ -45,3 +45,9 @@ func (b *Bucket) getAndDelete(key string) *Item{
delete(b.lookup, key)
return item
}
+
+func (b *Bucket) clear() {
+ b.Lock()
+ defer b.Unlock()
+ b.lookup = make(map[string]*Item)
+}
diff --git a/cache.go b/cache.go
index <HASH>..<HASH> 100755
--- a/cache.go
+++ b/cache.go
@@ -18,7 +18,7 @@ type Cache struct {
func New(config *Configuration) *Cache {
c := &Cache{
- list: new(list.List),
+ list: list.New(),
Configuration: config,
bucketCount: uint32(config.buckets),
buckets: make([]*Bucket, config.buckets),
@@ -51,12 +51,14 @@ func (c *Cache) Set(key string, value interface{}, duration time.Duration) {
c.promote(item)
}
-func (c *Cache) Fetch(key string, duration time.Duration, fetch func() interface{}) interface{} {
+func (c *Cache) Fetch(key string, duration time.Duration, fetch func() (interface{}, error)) (interface{}, error) {
item := c.Get(key)
- if item != nil { return item }
- value := fetch()
- c.Set(key, value, duration)
- return value
+ if item != nil { return item, nil }
+ value, err := fetch()
+ if err == nil {
+ c.Set(key, value, duration)
+ }
+ return value, err
}
func (c *Cache) Delete(key string) {
@@ -66,6 +68,14 @@ func (c *Cache) Delete(key string) {
}
}
+//this isn't thread safe. It's meant to be called from non-concurrent tests
+func (c *Cache) Clear() {
+ for _, bucket := range c.buckets {
+ bucket.clear()
+ }
+ c.list = list.New()
+}
+
func (c *Cache) deleteItem(bucket *Bucket, item *Item) {
bucket.delete(item.key) //stop othe GETs from getting it
c.deletables <- item
|
added non-threadsafe Clear (for tests), fixed Fetch
|
karlseguin_ccache
|
train
|
84b8aaf24f9aa6ff6aa3d8a0a59418460762dea7
|
diff --git a/context.go b/context.go
index <HASH>..<HASH> 100644
--- a/context.go
+++ b/context.go
@@ -360,8 +360,11 @@ func (c *context) FormParams() (url.Values, error) {
func (c *context) FormFile(name string) (*multipart.FileHeader, error) {
f, fh, err := c.request.FormFile(name)
+ if err != nil {
+ return nil, err
+ }
defer f.Close()
- return fh, err
+ return fh, nil
}
func (c *context) MultipartForm() (*multipart.Form, error) {
|
Fix panic in FormFile if file not found (#<I>)
|
labstack_echo
|
train
|
a7b93ce6f50ffa6bd1e40230f0f32a5a4bdcfac6
|
diff --git a/pyt/cfg.py b/pyt/cfg.py
index <HASH>..<HASH> 100644
--- a/pyt/cfg.py
+++ b/pyt/cfg.py
@@ -189,12 +189,12 @@ class CFG(ast.NodeVisitor):
if not module_statements:
raise Exception('Empty module. It seems that your file is empty, there is nothing to analyse.')
- first_node = module_statements[0]
+ first_node = module_statements.first_statement
entry_node.connect(first_node)
exit_node = self.append_node(Node('Exit node', EXIT))
- last_nodes = module_statements[1]
+ last_nodes = module_statements.last_statements
exit_node.connect_predecessors(last_nodes)
def flatten_cfg_statements(self, cfg_statements):
|
utilize the namedtuple accessors in create method
|
python-security_pyt
|
train
|
bf4514f86ca2ebadf9b44d7662926830ffc4431c
|
diff --git a/dipper/sources/FlyBase.py b/dipper/sources/FlyBase.py
index <HASH>..<HASH> 100644
--- a/dipper/sources/FlyBase.py
+++ b/dipper/sources/FlyBase.py
@@ -85,7 +85,7 @@ class FlyBase(PostgreSQLSource):
}
def __init__(self):
- super().__init__(self, 'flybase')
+ super().__init__('flybase')
logger.setLevel(logging.INFO)
self.version_num = None # to be used to store the version number to be acquired later
|
flybase fix constructor call to superclass
|
monarch-initiative_dipper
|
train
|
0c942ab95c6b409102c1ba4d09f5c89b13483179
|
diff --git a/lib/workspace.js b/lib/workspace.js
index <HASH>..<HASH> 100644
--- a/lib/workspace.js
+++ b/lib/workspace.js
@@ -123,8 +123,9 @@ module.exports = class Workspace {
var location = command_dir;
do {
- var dappfile_path = path.join(location, constants.DAPPFILE_FILENAME);
- if (fs.existsSync(dappfile_path)) {
+ var Dappfile_path = path.join(location, 'Dappfile');
+ var dappfile_path = path.join(location, 'dappfile');
+ if (fs.existsSync(dappfile_path) || fs.existsSync(Dappfile_path)) {
return location;
}
location = path.join(location, '..');
|
try to fix Dappfile/dappfile error
|
dapphub_dapple
|
train
|
005b1214e2bd90a56b47c3d25bb316d882cfea05
|
diff --git a/CGRtools/algorithms/smiles.py b/CGRtools/algorithms/smiles.py
index <HASH>..<HASH> 100644
--- a/CGRtools/algorithms/smiles.py
+++ b/CGRtools/algorithms/smiles.py
@@ -70,6 +70,8 @@ class Smiles:
kwargs['hybridization'] = False
if '!n' in format_spec:
kwargs['neighbors'] = False
+ if '!r' in format_spec:
+ kwargs['aromatic'] = False
return ''.join(self._smiles(self.atoms_order.get, **kwargs))
return str(self)
@@ -218,46 +220,39 @@ class MoleculeSmiles(Smiles):
atom = self._atoms[n]
charge = self._charges[n]
ih = self._hydrogens[n]
- if atom.isotope:
- smi = [str(atom.isotope), atom.atomic_symbol]
- else:
- smi = [atom.atomic_symbol]
- if kwargs.get('stereo', True) and n in self._atoms_stereo: # carbon only
- smi.append('@' if self._translate_tetrahedron_stereo(n, adjacency[n]) else '@@')
- if ih:
- smi.append('H')
- smi.insert(0, '[')
- smi.append(']')
+ smi = ['', # [
+ str(atom.isotope) if atom.isotope else '', # isotope
+ None,
+ '', # stereo
+ '', # hydrogen
+ '', # charge
+ ''] # ]
+
+ if kwargs.get('stereo', True) and n in self._atoms_stereo: # neutral carbon only
+ smi[3] = '@' if self._translate_tetrahedron_stereo(n, adjacency[n]) else '@@'
elif charge:
+ smi[5] = charge_str[charge]
+
+ if any(smi) or atom.atomic_symbol not in organic_set or self._radicals[n]:
+ smi[0] = '['
+ smi[-1] = ']'
if ih == 1:
- smi.append('H')
- elif ih:
- smi.append(f'H{ih}')
- smi.append(charge_str[charge])
- smi.insert(0, '[')
- smi.append(']')
- elif self._radicals[n]:
- if ih == 1:
- smi.append('H')
- elif ih:
- smi.append(f'H{ih}')
- smi.insert(0, '[')
- smi.append(']')
- elif atom.atomic_symbol not in organic_set:
- if ih == 1:
- smi.append('H')
+ smi[4] = 'H'
elif ih:
- smi.append(f'H{ih}')
- smi.insert(0, '[')
- smi.append(']')
- elif len(smi) != 1:
- smi.insert(0, '[')
- smi.append(']')
+ smi[4] = f'H{ih}'
+
+ if kwargs.get('aromatic', True) and self._hybridizations[n] == 4:
+ smi[2] = atom.atomic_symbol.lower()
+ else:
+ smi[2] = atom.atomic_symbol
return ''.join(smi)
def _format_bond(self, n, m, **kwargs):
- return order_str[self._bonds[n][m].order]
+ order = self._bonds[n][m].order
+ if kwargs.get('aromatic', True) and order == 4:
+ return ''
+ return order_str[order]
class CGRSmiles(Smiles):
@@ -270,9 +265,13 @@ class CGRSmiles(Smiles):
p_charge = self._p_charges[n]
p_is_radical = self._p_radicals[n]
if atom.isotope:
- smi = [str(atom.isotope), atom.atomic_symbol]
+ smi = [str(atom.isotope)]
+ else:
+ smi = []
+ if kwargs.get('aromatic', True) and (self._hybridizations[n] == 4 or self._p_hybridizations[n] == 4):
+ smi.append(atom.atomic_symbol.lower())
else:
- smi = [atom.atomic_symbol]
+ smi.append(atom.atomic_symbol)
if charge or p_charge:
smi.append(dyn_charge_str[(charge, p_charge)])
@@ -286,7 +285,10 @@ class CGRSmiles(Smiles):
def _format_bond(self, n, m, **kwargs):
bond = self._bonds[n][m]
- return dyn_order_str[(bond.order, bond.p_order)]
+ order, p_order = bond.order, bond.p_order
+ if kwargs.get('aromatic', True) and order == p_order == 4:
+ return ''
+ return dyn_order_str[(order, p_order)]
class QuerySmiles(Smiles):
|
smiles generation update.
now support convenient aromatic rings.
|
cimm-kzn_CGRtools
|
train
|
01ce638046165560b0d2ae3441bc812d16953422
|
diff --git a/src/Contracts/GravatarInterface.php b/src/Contracts/GravatarInterface.php
index <HASH>..<HASH> 100644
--- a/src/Contracts/GravatarInterface.php
+++ b/src/Contracts/GravatarInterface.php
@@ -12,5 +12,133 @@ interface GravatarInterface
| Getters & Setters
| ------------------------------------------------------------------------------------------------
*/
+ /**
+ * Get the current default image setting.
+ *
+ * @return string|false
+ */
+ public function getDefaultImage();
+
+ /**
+ * Set the default image to use for avatars.
+ *
+ * @param string|false $image
+ *
+ * @return self
+ *
+ * @throws \Arcanedev\Gravatar\Exceptions\InvalidImageUrlException
+ */
+ public function setDefaultImage($image);
+
+ /**
+ * Get the currently set avatar size.
+ *
+ * @return int
+ */
+ public function getSize();
+
+ /**
+ * Set the avatar size to use.
+ *
+ * @param integer $size - The avatar size to use, must be less than 512 and greater than 0.
+ *
+ * @return self
+ *
+ * @throws \Arcanedev\Gravatar\Exceptions\InvalidImageSizeException
+ */
+ public function setSize($size);
+ /**
+ * Get the current maximum allowed rating for avatars.
+ *
+ * @return string
+ */
+ public function getRating();
+
+ /**
+ * Set the maximum allowed rating for avatars.
+ *
+ * @param string $rating
+ *
+ * @return self
+ *
+ * @throws \Arcanedev\Gravatar\Exceptions\InvalidImageRatingException
+ */
+ public function setRating($rating);
+
+ /**
+ * Check if we are using the secure protocol for the image URLs.
+ *
+ * @return bool
+ */
+ public function isSecured();
+
+ /* ------------------------------------------------------------------------------------------------
+ | Main Functions
+ | ------------------------------------------------------------------------------------------------
+ */
+ /**
+ * Get Gravatar image source.
+ *
+ * @param string $email
+ * @param int|null $size
+ * @param string|null $rating
+ *
+ * @return string
+ */
+ public function src($email, $size = null, $rating = null);
+
+ /**
+ * Get the avatar URL based on the provided email address.
+ *
+ * @param string $email
+ * @param bool $hash
+ *
+ * @return string
+ */
+ public function get($email, $hash = true);
+
+ /**
+ * Get Gravatar image tag.
+ *
+ * @param string $email
+ * @param string|null $alt
+ * @param array $attributes
+ * @param string|null $rating
+ *
+ * @return string
+ */
+ public function image($email, $alt = null, $attributes = [], $rating = null);
+
+ /**
+ * Enable the use of the secure protocol for image URLs.
+ *
+ * @return self
+ */
+ public function enableSecure();
+
+ /**
+ * Disable the use of the secure protocol for image URLs.
+ *
+ * @return self
+ */
+ public function disableSecure();
+
+ /**
+ * Check if email has a gravatar.
+ *
+ * @param string $email
+ *
+ * @return bool
+ */
+ public function exists($email);
+
+ /**
+ * Get a hashed email.
+ *
+ * @param string $email
+ *
+ * @return string
+ */
+ public function hashEmail($email);
}
|
Updating the Gravatar Interface
|
ARCANEDEV_Gravatar
|
train
|
6cee051000456871b1fe04b7d8c939a28869d0bc
|
diff --git a/werkzeug/contrib/iterio.py b/werkzeug/contrib/iterio.py
index <HASH>..<HASH> 100644
--- a/werkzeug/contrib/iterio.py
+++ b/werkzeug/contrib/iterio.py
@@ -83,7 +83,7 @@ class IterIO(object):
Note for Python 3: due to the incompatible interface of bytes and
streams you should set the sentinel value explicitly to an empty
bytestring (``b''``) if you are expecting to deal with bytes as
- otherwise the end of the stream is marked with the strong sentinel
+ otherwise the end of the stream is marked with the wrong sentinel
value.
.. versionadded:: 0.9
|
strong sentinel value -> wrong sentinel value
|
pallets_werkzeug
|
train
|
885e00ba54ac5b9ca4e8eeded7393419e69df730
|
diff --git a/salt/grains/core.py b/salt/grains/core.py
index <HASH>..<HASH> 100644
--- a/salt/grains/core.py
+++ b/salt/grains/core.py
@@ -879,7 +879,7 @@ def id_():
'''
return {'id': __opts__.get('id', '')}
-_REPLACE_LINUX_RE = re.compile(r'linux', re.IGNORECASE)
+_REPLACE_LINUX_RE = re.compile(r'\Wlinux', re.IGNORECASE)
# This maps (at most) the first ten characters (no spaces, lowercased) of
# 'osfullname' to the 'os' grain that Salt traditionally uses.
|
Only remove the word linux from distroname when its not part of the name
This will now still replace "CentOS Linux" with "CentOS" while leaving "CloudLinux" unmodified.
Fixes #<I>
|
saltstack_salt
|
train
|
2df428405ea4df0f7ff2252761ca599e29e8bed9
|
diff --git a/src/com/mebigfatguy/fbcontrib/detect/HangingExecutors.java b/src/com/mebigfatguy/fbcontrib/detect/HangingExecutors.java
index <HASH>..<HASH> 100644
--- a/src/com/mebigfatguy/fbcontrib/detect/HangingExecutors.java
+++ b/src/com/mebigfatguy/fbcontrib/detect/HangingExecutors.java
@@ -83,7 +83,7 @@ public class HangingExecutors extends BytecodeScanningDetector {
* finds ExecutorService objects that don't get a call to the terminating
* methods, and thus, never appear to be shutdown properly (the threads
* exist until shutdown is called)
- *
+ *
* @param classContext
* the class context object of the currently parsed java class
*/
@@ -133,7 +133,7 @@ public class HangingExecutors extends BytecodeScanningDetector {
/**
* implements the visitor to reset the opcode stack
- *
+ *
* @param obj
* the context object of the currently parsed code block
*/
@@ -149,7 +149,7 @@ public class HangingExecutors extends BytecodeScanningDetector {
/**
* implements the visitor to collect the method name
- *
+ *
* @param obj
* the context object of the currently parsed method
*/
@@ -161,7 +161,7 @@ public class HangingExecutors extends BytecodeScanningDetector {
/**
* Browses for calls to shutdown() and shutdownNow(), and if they happen,
* remove the hanging candidate, as there is a chance it will be called.
- *
+ *
* @param seen
* the opcode of the currently parsed instruction
*/
@@ -310,6 +310,7 @@ class LocalHangingExecutor extends LocalTypeDetector {
private static final Map<String, Set<String>> watchedClassMethods;
private static final Map<String, Integer> syncCtors;
+ private static final Integer JAVA_5 = Integer.valueOf(Constants.MAJOR_1_5);
static {
Set<String> forExecutors = new HashSet<String>();
@@ -323,8 +324,8 @@ class LocalHangingExecutor extends LocalTypeDetector {
watchedClassMethods = Collections.unmodifiableMap(wcm);
Map<String, Integer> sc = new HashMap<String, Integer>();
- sc.put("java/util/concurrent/ThreadPoolExecutor", Integer.valueOf(Constants.MAJOR_1_5));
- sc.put("java/util/concurrent/ScheduledThreadPoolExecutor", Integer.valueOf(Constants.MAJOR_1_5));
+ sc.put("java/util/concurrent/ThreadPoolExecutor", JAVA_5);
+ sc.put("java/util/concurrent/ScheduledThreadPoolExecutor", JAVA_5);
syncCtors = Collections.unmodifiableMap(sc);
}
diff --git a/src/com/mebigfatguy/fbcontrib/detect/LocalSynchronizedCollection.java b/src/com/mebigfatguy/fbcontrib/detect/LocalSynchronizedCollection.java
index <HASH>..<HASH> 100755
--- a/src/com/mebigfatguy/fbcontrib/detect/LocalSynchronizedCollection.java
+++ b/src/com/mebigfatguy/fbcontrib/detect/LocalSynchronizedCollection.java
@@ -1,17 +1,17 @@
/*
* fb-contrib - Auxiliary detectors for Java programs
* Copyright (C) 2005-2016 Dave Brosius
- *
+ *
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
- *
+ *
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
- *
+ *
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
@@ -41,11 +41,13 @@ import edu.umd.cs.findbugs.OpcodeStack.CustomUserValue;
@CustomUserValue
public class LocalSynchronizedCollection extends LocalTypeDetector {
private static final Map<String, Integer> syncCtors = new HashMap<String, Integer>();
+ private static final Integer JAVA_1_1 = Integer.valueOf(Constants.MAJOR_1_1);
+ private static final Integer JAVA_5 = Integer.valueOf(Constants.MAJOR_1_5);
static {
- syncCtors.put("java/util/Vector", Integer.valueOf(Constants.MAJOR_1_1));
- syncCtors.put("java/util/Hashtable", Integer.valueOf(Constants.MAJOR_1_1));
- syncCtors.put("java/lang/StringBuffer", Integer.valueOf(Constants.MAJOR_1_5));
+ syncCtors.put("java/util/Vector", JAVA_1_1);
+ syncCtors.put("java/util/Hashtable", JAVA_1_1);
+ syncCtors.put("java/lang/StringBuffer", JAVA_5);
}
private static final Map<String, Set<String>> synchClassMethods = new HashMap<String, Set<String>>();
@@ -68,7 +70,7 @@ public class LocalSynchronizedCollection extends LocalTypeDetector {
/**
* constructs a LSYC detector given the reporter to report bugs on
- *
+ *
* @param bugReporter
* the sync of bug reports
*/
|
extract Java versions to constant Integers instead of repeatedly converting shorts, Github #<I>
|
mebigfatguy_fb-contrib
|
train
|
6f9edf732e75f58a6503dd5810f539f9dc0aa6cf
|
diff --git a/core/server/src/main/java/alluxio/master/file/FileSystemMaster.java b/core/server/src/main/java/alluxio/master/file/FileSystemMaster.java
index <HASH>..<HASH> 100644
--- a/core/server/src/main/java/alluxio/master/file/FileSystemMaster.java
+++ b/core/server/src/main/java/alluxio/master/file/FileSystemMaster.java
@@ -3101,7 +3101,7 @@ public final class FileSystemMaster extends AbstractMaster {
LOG.debug("File {} is expired. Performing action {}", inode.getName(), ttlAction);
switch (ttlAction) {
case FREE:
- free(path, FreeOptions.defaults().setForced(true));
+ free(path, FreeOptions.defaults().setForced(true).setRecursive(true));
// Reset state
inode.setTtl(Constants.NO_TTL);
inode.setTtlAction(TtlAction.DELETE);
|
[SMALLFIX] Fix recursive flag for TTL Free
|
Alluxio_alluxio
|
train
|
f75259b246eac5134578720112695033d0f51b35
|
diff --git a/src/higher-order.js b/src/higher-order.js
index <HASH>..<HASH> 100644
--- a/src/higher-order.js
+++ b/src/higher-order.js
@@ -110,6 +110,7 @@ function branch(cursors, Component) {
this.setState(this.watcher.get());
};
+ handler();
this.watcher.on('update', handler);
}
|
Updating BranchedComponent state on componentDidMount.
|
Yomguithereal_baobab-react
|
train
|
8be015d1b18261cedb169e76f98f7f7395bbb20d
|
diff --git a/archunit/src/main/java/com/tngtech/archunit/core/AnnotationProxy.java b/archunit/src/main/java/com/tngtech/archunit/core/AnnotationProxy.java
index <HASH>..<HASH> 100644
--- a/archunit/src/main/java/com/tngtech/archunit/core/AnnotationProxy.java
+++ b/archunit/src/main/java/com/tngtech/archunit/core/AnnotationProxy.java
@@ -260,7 +260,7 @@ class AnnotationProxy {
for (Map.Entry<String, Object> entry : toProxy.getProperties().entrySet()) {
Class<?> returnType = getDeclaredMethod(entry.getKey()).getReturnType();
String value = format(conversions.convertIfNecessary(entry.getValue(), returnType));
- properties.add(String.format("%s=%s", entry.getKey(), value));
+ properties.add(entry.getKey() + "=" + value);
}
return Joiner.on(", ").join(properties);
}
diff --git a/archunit/src/main/java/com/tngtech/archunit/core/Formatters.java b/archunit/src/main/java/com/tngtech/archunit/core/Formatters.java
index <HASH>..<HASH> 100644
--- a/archunit/src/main/java/com/tngtech/archunit/core/Formatters.java
+++ b/archunit/src/main/java/com/tngtech/archunit/core/Formatters.java
@@ -7,17 +7,19 @@ import com.google.common.base.Joiner;
import com.google.common.primitives.Ints;
public class Formatters {
- private static final String FULL_METHOD_NAME_TEMPLATE = "%s.%s(%s)";
-
private Formatters() {
}
public static String formatMethod(String ownerName, String methodName, JavaClassList parameters) {
- return String.format(FULL_METHOD_NAME_TEMPLATE, ownerName, methodName, formatMethodParameters(parameters));
+ return format(ownerName, methodName, formatMethodParameters(parameters));
+ }
+
+ private static String format(String ownerName, String methodName, String parameters) {
+ return ownerName + "." + methodName + "(" + parameters + ")";
}
public static String formatMethod(String ownerName, String methodName, List<String> parameters) {
- return String.format(FULL_METHOD_NAME_TEMPLATE, ownerName, methodName, formatMethodParameterTypeNames(parameters));
+ return format(ownerName, methodName, formatMethodParameterTypeNames(parameters));
}
private static String formatMethodParameters(List<? extends HasName> parameters) {
@@ -31,7 +33,7 @@ public class Formatters {
public static String formatMethodParameterTypeNames(List<String> typeNames) {
List<String> formatted = new ArrayList<>();
for (String name : typeNames) {
- formatted.add(String.format("%s.class", ensureSimpleName(name)));
+ formatted.add(ensureSimpleName(name) + ".class");
}
return Joiner.on(", ").join(formatted);
}
diff --git a/archunit/src/main/java/com/tngtech/archunit/core/JavaStaticInitializer.java b/archunit/src/main/java/com/tngtech/archunit/core/JavaStaticInitializer.java
index <HASH>..<HASH> 100644
--- a/archunit/src/main/java/com/tngtech/archunit/core/JavaStaticInitializer.java
+++ b/archunit/src/main/java/com/tngtech/archunit/core/JavaStaticInitializer.java
@@ -21,11 +21,6 @@ public class JavaStaticInitializer extends JavaCodeUnit {
}
@Override
- public String toString() {
- return String.format("%s{owner=%s, name=%s}", getClass().getSimpleName(), getOwner(), getName());
- }
-
- @Override
public Member reflect() {
throw new UnsupportedOperationException("Can't reflect on a static initializer");
}
|
It's sad, but String.format(..) is noticeably slow
|
TNG_ArchUnit
|
train
|
7a195d7905e128f3175d59a2a38b66e61c380219
|
diff --git a/aiohttp_admin/backends/sa.py b/aiohttp_admin/backends/sa.py
index <HASH>..<HASH> 100644
--- a/aiohttp_admin/backends/sa.py
+++ b/aiohttp_admin/backends/sa.py
@@ -36,7 +36,7 @@ class PGResource(AbstractResource):
async def list(self, request):
await require(request, Permissions.view)
columns_names = list(self._table.c.keys())
- q = validate_query(request.GET, columns_names)
+ q = validate_query(request.query, columns_names)
paging = calc_pagination(q, self._primary_key)
filters = q.get('_filters')
|
request.GET to request.query
|
aio-libs_aiohttp_admin
|
train
|
1ce371755c9860d17184f13f57a9c0103084f628
|
diff --git a/plenum/server/monitor.py b/plenum/server/monitor.py
index <HASH>..<HASH> 100644
--- a/plenum/server/monitor.py
+++ b/plenum/server/monitor.py
@@ -108,10 +108,6 @@ class Monitor(HasActionQueue, PluginLoaderHelper):
self.latenciesByBackupsInLast = {}
# Monitoring suspicious spikes in cluster throughput
- self.clusterThroughputSpikeCoefficient = \
- self.notifierEventTriggeringConfig['clusterThroughputSpike']['coefficient']
- self.clusterThroughputSpikeMinCnt = \
- self.notifierEventTriggeringConfig['clusterThroughputSpike']['minCnt']
self.clusterThroughputSpikeMonitorData = {
'value': 0,
'cnt': 0
@@ -416,7 +412,7 @@ class Monitor(HasActionQueue, PluginLoaderHelper):
notifierPluginTriggerEvents['clusterThroughputSpike'],
self.clusterThroughputSpikeMonitorData,
throughput,
- self.clusterThroughputSpikeMinCnt
+ self.notifierEventTriggeringConfig['clusterThroughputSpike']
)
@property
diff --git a/plenum/server/node.py b/plenum/server/node.py
index <HASH>..<HASH> 100644
--- a/plenum/server/node.py
+++ b/plenum/server/node.py
@@ -1416,7 +1416,7 @@ class Node(HasActionQueue, Motor, Propagator, MessageProcessor, HasFileStorage,
notifierPluginTriggerEvents['nodeRequestSpike'],
self.nodeRequestSpikeMonitorData,
requests,
- self.config.notifierEventTriggeringConfig['nodeRequestSpike']['minCnt']
+ self.config.notifierEventTriggeringConfig['nodeRequestSpike']
)
def sendInstanceChange(self, viewNo: int):
diff --git a/plenum/server/notifier_plugin_manager.py b/plenum/server/notifier_plugin_manager.py
index <HASH>..<HASH> 100644
--- a/plenum/server/notifier_plugin_manager.py
+++ b/plenum/server/notifier_plugin_manager.py
@@ -30,23 +30,32 @@ class PluginManager:
self.importPlugins()
def sendMessageUponSuspiciousSpike(self, event: str, historicalData: Dict,
- newVal: float, minCnt: int):
+ newVal: float, config: Dict):
+ assert 'value' in historicalData
+ assert 'cnt' in historicalData
+ assert 'minCnt' in config
+ assert 'coefficient' in config
+
+ coefficient = config['coefficient']
+ minCnt = config['minCnt']
val = historicalData['value']
cnt = historicalData['cnt']
historicalData['value'] = \
val * (cnt / (cnt + 1)) + newVal / (cnt + 1)
historicalData['cnt'] += 1
- if historicalData[
- 'cnt'] < minCnt:
+ if historicalData['cnt'] < minCnt:
logger.debug('Not enough data to detect a {} spike'.format(event))
- return
+ return None
+
+ if (val / coefficient) < newVal < (val * coefficient):
+ logger.debug('New value is within bounds')
+ return None
- return self._sendMessage(
- event,
- '{} suspicious spike has been noticed at {}. Usual thoughput: {}. New throughput: {}.'
- .format(event, time.time(), val, newVal)
- )
+ message = '{} suspicious spike has been noticed at {}. Usual thoughput: {}. New throughput: {}.'\
+ .format(event, time.time(), val, newVal)
+ logger.warning(message)
+ return self._sendMessage(event, message)
def importPlugins(self):
plugins = self._findPlugins()
diff --git a/plenum/test/plugin/test_notifier_plugin_manager.py b/plenum/test/plugin/test_notifier_plugin_manager.py
index <HASH>..<HASH> 100644
--- a/plenum/test/plugin/test_notifier_plugin_manager.py
+++ b/plenum/test/plugin/test_notifier_plugin_manager.py
@@ -38,3 +38,51 @@ def testPluginManagerSendsMessage(pluginManagerWithImportedModules):
._sendMessage(topic, message)
assert sent == 3
+
+def testPluginManagerSendMessageUponSuspiciousSpikeFailsOnMinCnt(pluginManagerWithImportedModules):
+ topic = randomText(10)
+ historicalData = {
+ 'value': 0,
+ 'cnt': 0
+ }
+ newVal = 10
+ config = {
+ 'coefficient': 2,
+ 'minCnt': 10
+ }
+ assert pluginManagerWithImportedModules\
+ .sendMessageUponSuspiciousSpike(topic, historicalData, newVal, config)\
+ is None
+
+
+def testPluginManagerSendMessageUponSuspiciousSpikeFailsOnCoefficient(pluginManagerWithImportedModules):
+ topic = randomText(10)
+ historicalData = {
+ 'value': 10,
+ 'cnt': 10
+ }
+ newVal = 15
+ config = {
+ 'coefficient': 2,
+ 'minCnt': 10
+ }
+ assert pluginManagerWithImportedModules\
+ .sendMessageUponSuspiciousSpike(topic, historicalData, newVal, config)\
+ is None
+
+
+def testPluginManagerSendMessageUponSuspiciousSpike(pluginManagerWithImportedModules):
+ topic = randomText(10)
+ historicalData = {
+ 'value': 10,
+ 'cnt': 10
+ }
+ newVal = 20
+ config = {
+ 'coefficient': 2,
+ 'minCnt': 10
+ }
+ sent, found = pluginManagerWithImportedModules\
+ .sendMessageUponSuspiciousSpike(topic, historicalData, newVal, config)
+ assert sent == 3
+
|
Feature: Notifier Plugin Manager
Changes: Added tests for sendMessageUponSuspiciousSpike
|
hyperledger_indy-plenum
|
train
|
bca0fdf13a39c5090097434f3e7644f572deb9bd
|
diff --git a/requestium/requestium.py b/requestium/requestium.py
index <HASH>..<HASH> 100644
--- a/requestium/requestium.py
+++ b/requestium/requestium.py
@@ -24,7 +24,7 @@ class Session(requests.Session):
Some usefull helper methods and object wrappings have been added.
"""
- def __init__(self, webdriver_path='./phantomjs', default_timeout=5, browser='phantomjs'):
+ def __init__(self, webdriver_path, browser, default_timeout=5):
super(Session, self).__init__()
self.webdriver_path = webdriver_path
self.default_timeout = default_timeout
|
Remove defaults from webdriver initialization
Specifically made as a move away from phantomjs which used to be the
default, as the owner of that project has abandoned it.
|
tryolabs_requestium
|
train
|
d2354679e43d722f6c7a4e791e2326d0b6bb997a
|
diff --git a/README.md b/README.md
index <HASH>..<HASH> 100644
--- a/README.md
+++ b/README.md
@@ -82,3 +82,17 @@ Dumper::Agent.start(app_key: 'YOUR_APP_KEY', debug: true)
```
It gives verbose logging that helps us to understand the problem.
+
+## Custom Options
+
+You can also pass custom dump options, with `custom_options` and `format` for the database type.
+
+```ruby
+Dumper::Agent.start(
+ app_key: 'YOUR_APP_KEY',
+ postgresql: {
+ format: 'dump',
+ custom_options: '-Fc --no-acl --no-owner'
+ }
+)
+```
diff --git a/lib/dumper/database/base.rb b/lib/dumper/database/base.rb
index <HASH>..<HASH> 100644
--- a/lib/dumper/database/base.rb
+++ b/lib/dumper/database/base.rb
@@ -3,10 +3,10 @@ module Dumper
class Base
include Dumper::Utility::ObjectFinder
- attr_accessor :tmpdir, :filename, :config
+ attr_accessor :tmpdir, :filename, :config, :custom_options, :format
def file_ext
- self.class::FILE_EXT
+ (format || self.class::FORMAT) + '.gz'
end
def dump_path
diff --git a/lib/dumper/database/mongodb.rb b/lib/dumper/database/mongodb.rb
index <HASH>..<HASH> 100644
--- a/lib/dumper/database/mongodb.rb
+++ b/lib/dumper/database/mongodb.rb
@@ -2,10 +2,10 @@ module Dumper
module Database
class MongoDB < Base
DUMP_TOOL = 'mongodump'
- FILE_EXT = 'tar.gz'
+ FORMAT = 'tar'
def command
- "cd #{tmpdir} && #{dump_tool_path} #{connection_options} #{additional_options} && tar -czf #{filename} --exclude='#{filename}' ."
+ "cd #{tmpdir} && #{dump_tool_path} #{connection_options} #{additional_options} #{custom_options} && tar -czf #{filename} --exclude='#{filename}' ."
end
def connection_options
diff --git a/lib/dumper/database/mysql.rb b/lib/dumper/database/mysql.rb
index <HASH>..<HASH> 100644
--- a/lib/dumper/database/mysql.rb
+++ b/lib/dumper/database/mysql.rb
@@ -2,10 +2,10 @@ module Dumper
module Database
class MySQL < Base
DUMP_TOOL = 'mysqldump'
- FILE_EXT = 'sql.gz'
+ FORMAT = 'sql'
def command
- "cd #{tmpdir} && #{dump_tool_path} #{connection_options} #{additional_options} #{@config[:database]} | gzip > #{filename}"
+ "cd #{tmpdir} && #{dump_tool_path} #{connection_options} #{additional_options} #{custom_options} #{@config[:database]} | gzip > #{filename}"
end
def connection_options
diff --git a/lib/dumper/database/postgresql.rb b/lib/dumper/database/postgresql.rb
index <HASH>..<HASH> 100644
--- a/lib/dumper/database/postgresql.rb
+++ b/lib/dumper/database/postgresql.rb
@@ -2,10 +2,10 @@ module Dumper
module Database
class PostgreSQL < Base
DUMP_TOOL = 'pg_dump'
- FILE_EXT = 'sql.gz'
+ FORMAT = 'sql'
def command
- "cd #{tmpdir} && #{password_variable} #{dump_tool_path} #{connection_options} #{@config[:database]} | gzip > #{filename}"
+ "cd #{tmpdir} && #{password_variable} #{dump_tool_path} #{connection_options} #{custom_options} #{@config[:database]} | gzip > #{filename}"
end
def connection_options
diff --git a/lib/dumper/database/redis.rb b/lib/dumper/database/redis.rb
index <HASH>..<HASH> 100644
--- a/lib/dumper/database/redis.rb
+++ b/lib/dumper/database/redis.rb
@@ -2,7 +2,7 @@ module Dumper
module Database
class Redis < Base
DUMP_TOOL = 'redis-cli'
- FILE_EXT = 'rdb.gz'
+ FORMAT = 'rdb'
def command
uncompressed = filename.sub('.gz','')
diff --git a/lib/dumper/stack.rb b/lib/dumper/stack.rb
index <HASH>..<HASH> 100644
--- a/lib/dumper/stack.rb
+++ b/lib/dumper/stack.rb
@@ -34,6 +34,10 @@ module Dumper
DATABASES.each do |key, klass|
database = klass.new
next unless database.set_config_for(@rails_env) || database.set_config_for(options[:additional_env])
+ if options[key].is_a?(Hash)
+ database.custom_options = options[key][:custom_options]
+ database.format = options[key][:format]
+ end
@databases[key] = database
end
diff --git a/lib/dumper/version.rb b/lib/dumper/version.rb
index <HASH>..<HASH> 100644
--- a/lib/dumper/version.rb
+++ b/lib/dumper/version.rb
@@ -1,3 +1,3 @@
module Dumper
- VERSION = '1.5.0'
+ VERSION = '1.6.0'
end
|
Support custom dump options. Refs #5 <I>
|
dumperhq_dumper
|
train
|
1e158236c7d369cca5a072a170b18f8c85e4e274
|
diff --git a/lib/deep_pluck/model.rb b/lib/deep_pluck/model.rb
index <HASH>..<HASH> 100644
--- a/lib/deep_pluck/model.rb
+++ b/lib/deep_pluck/model.rb
@@ -51,12 +51,21 @@ module DeepPluck
#---------------------------------------
private
def do_query(parent, reflect, relation)
- if reflect.belongs_to?
- return relation.where(:id => parent.map{|s| s[reflect.foreign_key]}.uniq.compact)
+ if reflect.belongs_to? #A belongs_to association cannot have a :through option
+ parent_key = reflect.foreign_key
+ relation_key = 'id'
else
- return relation.where(reflect.foreign_key => parent.map{|s| s["id"]}.uniq.compact)
+ parent_key = 'id'
+ if reflect.options[:through]
+ relation = relation.joins(reflect.options[:through])
+ relation_key = "#{reflect.options[:through]}.id"
+ else
+ relation_key = reflect.foreign_key
+ end
end
+ return relation.where(relation_key => parent.map{|s| s[parent_key]}.uniq.compact)
end
+ private
def set_includes_data(parent, children_store_name, model)
reflect = reflect_on_association(children_store_name)
if reflect.belongs_to? #Child.where(:id => parent.pluck(:child_id))
|
should join the option[:through] table
|
khiav223577_deep_pluck
|
train
|
dd861aa51d6b9de3f91ed0fa9d63cad456c523f0
|
diff --git a/yagmail/yagmail.py b/yagmail/yagmail.py
index <HASH>..<HASH> 100644
--- a/yagmail/yagmail.py
+++ b/yagmail/yagmail.py
@@ -282,7 +282,7 @@ class SMTP():
def _add_recipients_headers(self, msg, addresses):
# Quoting the useralias so it should match display-name from https://tools.ietf.org/html/rfc5322 ,
# even if it's an email address.
- msg['From'] = '"{}" <{}>'.format(self.useralias.replace('"', '\\"'), self.user)
+ msg['From'] = '"{}" <{}>'.format(self.useralias.replace('\\', '\\\\').replace('"', '\\"'), self.user)
if 'To' in addresses:
msg['To'] = addresses['To']
else:
|
Escape backslashes before escaping quotation marks
|
kootenpv_yagmail
|
train
|
0766bfa385c97c81e2a7f7ea9b1a9e7ca6f12854
|
diff --git a/test/jquery.ajax-retry_test.js b/test/jquery.ajax-retry_test.js
index <HASH>..<HASH> 100644
--- a/test/jquery.ajax-retry_test.js
+++ b/test/jquery.ajax-retry_test.js
@@ -92,6 +92,22 @@
'{ "id": 12, "comment": "error!" }');
});
+ test('data is taken from successful response ', 1, function() {
+ var def = $.post("/test",{});
+
+ def.retry(2).done(function(data) {
+ ok(data.id === 12);
+ });
+
+ this.requests[0].respond(400, { "Content-Type": "application/json" },
+ '{ "id": 11, "comment": "error!" }');
+
+
+ this.requests[1].respond(200, { "Content-Type": "application/json" },
+ '{ "id": 12, "comment": "Hey there" }');
+ });
+
+
module('jQuery retry uses timeout value', {
setup: function() {
this.xhr = sinon.useFakeXMLHttpRequest();
@@ -107,18 +123,18 @@
}
});
- test('timeout is waited before next retry', 4, function() {
+ test('timeout is waited before next retry', 3, function() {
var def = $.post("/test",{});
- def.withTimeout(2000).retry(2).done(function(data) {
- ok(data.id === 12);
- });
+ def.withTimeout(2000).retry(2);
ok(this.requests.length === 1);
this.requests[0].respond(400, { "Content-Type": "application/json" },
'{ "id": 11, "comment": "error!" }');
ok(this.requests.length === 1);
+
this.clock.tick(2000);
+
ok(this.requests.length === 2);
this.requests[1].respond(200, { "Content-Type": "application/json" },
'{ "id": 12, "comment": "Hey there" }');
@@ -134,5 +150,5 @@
this.clock.tick(1999);
ok(this.requests.length === 1);
});
-
+
}(jQuery));
|
separate test for specifiying which response fulfilled data is taken from
|
johnkpaul_jquery-ajax-retry
|
train
|
c7bf474a5c7862d6136ce5c22260b0f371d01619
|
diff --git a/src/main/java/org/la4j/matrix/sparse/CCSMatrix.java b/src/main/java/org/la4j/matrix/sparse/CCSMatrix.java
index <HASH>..<HASH> 100644
--- a/src/main/java/org/la4j/matrix/sparse/CCSMatrix.java
+++ b/src/main/java/org/la4j/matrix/sparse/CCSMatrix.java
@@ -498,5 +498,27 @@ public class CCSMatrix extends AbstractCompressedMatrix implements SparseMatrix
return (min < 0) ? min : 0;
}
+ @Override
+ public double maxInColumn(int j) {
+ double max = Double.NEGATIVE_INFINITY;
+ for (int k = columnPointers[j]; k < columnPointers[j + 1]; k++) {
+ if (values[k] > max) {
+ max = values[k];
+ }
+ }
+ return (max > 0) ? max : 0;
+ }
+
+ @Override
+ public double minInColumn(int j) {
+ double min = Double.POSITIVE_INFINITY;
+ for (int k = columnPointers[j]; k < columnPointers[j + 1]; k++) {
+ if (values[k] < min) {
+ min = values[k];
+ }
+ }
+ return (min < 0) ? min : 0;
+ }
+
}
diff --git a/src/main/java/org/la4j/matrix/sparse/CRSMatrix.java b/src/main/java/org/la4j/matrix/sparse/CRSMatrix.java
index <HASH>..<HASH> 100644
--- a/src/main/java/org/la4j/matrix/sparse/CRSMatrix.java
+++ b/src/main/java/org/la4j/matrix/sparse/CRSMatrix.java
@@ -573,4 +573,28 @@ public class CRSMatrix extends AbstractCompressedMatrix implements SparseMatrix
return (min < 0) ? min : 0;
}
+ @Override
+ public double maxInRow(int i) {
+ double max = Double.NEGATIVE_INFINITY;
+ for (int k = rowPointers[i]; k < rowPointers[i + 1]; k++) {
+ if (values[k] > max) {
+ max = values[k];
+ }
+ }
+ return (max > 0) ? max : 0;
+ }
+
+ @Override
+ public double minInRow(int i) {
+ double min = Double.POSITIVE_INFINITY;
+ for (int k = rowPointers[i]; k < rowPointers[i + 1]; k++) {
+ if (values[k] < min) {
+ min = values[k];
+ }
+ }
+ return (min < 0) ? min : 0;
+ }
+
+
+
}
|
Added min/max in rows and columns methods for SparseMatrix (issue #<I>)
|
vkostyukov_la4j
|
train
|
d6b301b18ed868ddf51713ad1770a080265ad63e
|
diff --git a/CHANGELOG.md b/CHANGELOG.md
index <HASH>..<HASH> 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -7,6 +7,7 @@ adheres to [Semantic Versioning](http://semver.org/).
- Added 'ActionDispatch::Http::MimeNegotiation::InvalidType' (Rails 6.1) to
default ignore list. (#402, @jrochkind)
- Replaced fixed number for retries in Sidekiq Plugin with Sidekiq::JobRetry constant
+- Properly set environment in deployment tracking (#404, @stmllr)
## [4.8.0] - 2021-03-16
### Fixed
diff --git a/lib/honeybadger/agent.rb b/lib/honeybadger/agent.rb
index <HASH>..<HASH> 100644
--- a/lib/honeybadger/agent.rb
+++ b/lib/honeybadger/agent.rb
@@ -195,16 +195,16 @@ module Honeybadger
# @example
# Honeybadger.track_deployment(revision: 'be2ceb6')
#
- # @param [String] :env The environment name. Defaults to the current configured environment.
+ # @param [String] :environment The environment name. Defaults to the current configured environment.
# @param [String] :revision The VCS revision being deployed. Defaults to the currently configured revision.
# @param [String] :local_username The name of the user who performed the deploy.
# @param [String] :repository The base URL of the VCS repository. It should be HTTPS-style.
#
# @return [Boolean] true if the deployment was successfully tracked and false
# otherwise.
- def track_deployment(env: nil, revision: nil, local_username: nil, repository: nil)
+ def track_deployment(environment: nil, revision: nil, local_username: nil, repository: nil)
opts = {
- env: env || config[:env],
+ environment: environment || config[:env],
revision: revision || config[:revision],
local_username: local_username,
repository: repository
diff --git a/spec/unit/honeybadger/agent_spec.rb b/spec/unit/honeybadger/agent_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/unit/honeybadger/agent_spec.rb
+++ b/spec/unit/honeybadger/agent_spec.rb
@@ -65,7 +65,7 @@ describe Honeybadger::Agent do
it 'passes the revision to the servce' do
allow_any_instance_of(Honeybadger::Util::HTTP).to receive(:compress) { |_, body| body }
stub_request(:post, "https://api.honeybadger.io/v1/deploys").
- with(body: { env: nil, revision: '1234', local_username: nil, repository: nil }).
+ with(body: { environment: nil, revision: '1234', local_username: nil, repository: nil }).
to_return(status: 200)
expect(instance.track_deployment(revision: '1234')).to eq(true)
|
Properly set environment in deployment tracking (#<I>)
* Properly set environment in deployment tracking
Follow-up to #<I>
* Add proper PR reference to Changelog
* env => environment
|
honeybadger-io_honeybadger-ruby
|
train
|
57c82a582cc3ad624e875099b1bc0381847b67e0
|
diff --git a/salt/states/pkg.py b/salt/states/pkg.py
index <HASH>..<HASH> 100644
--- a/salt/states/pkg.py
+++ b/salt/states/pkg.py
@@ -328,7 +328,7 @@ def installed(
version
Install a specific version of a package. This option is ignored if
either "pkgs" or "sources" is used. Currently, this option is supported
- for the following pkg providers: :mod:`apt <salt.modules.apt_pkg>`,
+ for the following pkg providers: :mod:`apt <salt.modules.aptpkg>`,
:mod:`ebuild <salt.modules.ebuild>`,
:mod:`pacman <salt.modules.pacman>`,
:mod:`yumpkg <salt.modules.yumpkg>`, and
@@ -361,7 +361,7 @@ def installed(
- bar
- baz
- ``NOTE:`` For :mod:`apt <salt.modules.apt_pkg>`,
+ ``NOTE:`` For :mod:`apt <salt.modules.aptpkg>`,
:mod:`ebuild <salt.modules.ebuild>`,
:mod:`pacman <salt.modules.pacman>`, :mod:`yumpkg <salt.modules.yumpkg>`,
and :mod:`zypper <salt.modules.zypper>`, version numbers can be specified
|
Fix `aptpkg` referencess.
|
saltstack_salt
|
train
|
64180742398b866c9887906cb597aa3954d1f217
|
diff --git a/abaaso.js b/abaaso.js
index <HASH>..<HASH> 100644
--- a/abaaso.js
+++ b/abaaso.js
@@ -1423,6 +1423,7 @@ var abaaso = function(){
try {
var exception = false,
invalid = [],
+ pattern = validate.pattern,
value = null;
for (var i in args) {
@@ -1436,7 +1437,7 @@ var abaaso = function(){
break;
case "date":
value = new String(value);
- if ((!validate.pattern.notEmpty.test(value))
+ if ((!pattern.notEmpty.test(value))
|| (!new Date(value))) {
invalid.push(i);
exception = true;
@@ -1444,15 +1445,15 @@ var abaaso = function(){
break;
case "domainip":
value = new String(value);
- if ((!validate.pattern.domain.test(value))
- || (!validate.pattern.ip.test(value))) {
+ if ((!pattern.domain.test(value))
+ || (!pattern.ip.test(value))) {
invalid.push(i);
exception = true;
}
break;
default:
value = new String(value);
- var pattern = (validate.pattern[args[i]]) ? validate.pattern[args[i]] : args[i];
+ pattern = (pattern[args[i]]) ? pattern[args[i]] : args[i];
if (!pattern.test(value)) {
invalid.push(i);
exception = true;
|
Revised validate.test() to be a little cleaner
|
avoidwork_abaaso
|
train
|
ebc5167f454c2b6fb724f3396945a2814fc25615
|
diff --git a/src/Symfony/Component/Translation/Dumper/MoFileDumper.php b/src/Symfony/Component/Translation/Dumper/MoFileDumper.php
index <HASH>..<HASH> 100644
--- a/src/Symfony/Component/Translation/Dumper/MoFileDumper.php
+++ b/src/Symfony/Component/Translation/Dumper/MoFileDumper.php
@@ -75,7 +75,7 @@ class MoFileDumper extends FileDumper
return 'mo';
}
- private function writeLong(string $str): string
+ private function writeLong(mixed $str): string
{
return pack('V*', $str);
}
|
[Translation] fix <I>b support
|
symfony_symfony
|
train
|
9d052ede3a01901d1fa6ae7da16414b4f3ffbd13
|
diff --git a/nsqd/diskqueue.go b/nsqd/diskqueue.go
index <HASH>..<HASH> 100644
--- a/nsqd/diskqueue.go
+++ b/nsqd/diskqueue.go
@@ -404,7 +404,7 @@ func (d *DiskQueue) fileName(fileNum int64) string {
//
// conveniently this also means that we're asynchronously reading from the filesystem
func (d *DiskQueue) ioLoop() {
- var data []byte
+ var dataRead []byte
var err error
var count int64
var r chan []byte
@@ -422,7 +422,7 @@ func (d *DiskQueue) ioLoop() {
if (d.readFileNum < d.writeFileNum) || (d.readPos < d.writePos) {
if d.nextReadPos == d.readPos {
- data, err = d.readOne()
+ dataRead, err = d.readOne()
if err != nil {
log.Printf("ERROR: reading from diskqueue(%s) at %d of %s - %s",
d.name, d.readPos, d.fileName(d.readFileNum), err.Error())
@@ -434,14 +434,15 @@ func (d *DiskQueue) ioLoop() {
}
}
r = d.readChan
+ } else {
+ r = nil
}
select {
// the Go channel spec dictates that nil channel operations (read or write)
// in a select are skipped, we set r to d.readChan only when there is data to read
// and reset it to nil after writing to the channel
- case r <- data:
- r = nil
+ case r <- dataRead:
oldReadFileNum := d.readFileNum
d.readFileNum = d.nextReadFileNum
d.readPos = d.nextReadPos
@@ -465,8 +466,8 @@ func (d *DiskQueue) ioLoop() {
}
case <-d.emptyChan:
d.emptyResponseChan <- d.doEmpty()
- case data := <-d.writeChan:
- d.writeResponseChan <- d.writeOne(data)
+ case dataWrite := <-d.writeChan:
+ d.writeResponseChan <- d.writeOne(dataWrite)
case <-d.exitChan:
goto exit
}
|
diskqueue: fix bug where readChan is not reset
|
nsqio_nsq
|
train
|
35ebc43c313e3ef33ef5003bf42821e8e820acbb
|
diff --git a/test/helper.rb b/test/helper.rb
index <HASH>..<HASH> 100644
--- a/test/helper.rb
+++ b/test/helper.rb
@@ -1,5 +1,6 @@
require "test-unit"
require "test/unit/notify"
+require "pp"
require "daimon_markdown"
|
Always require "pp"
This is useful for debug.
|
bm-sms_daimon_markdown
|
train
|
93174bd3b6c02b29a1582ce091eb92f9010b8af6
|
diff --git a/src/streamlink/stream/dash.py b/src/streamlink/stream/dash.py
index <HASH>..<HASH> 100644
--- a/src/streamlink/stream/dash.py
+++ b/src/streamlink/stream/dash.py
@@ -11,6 +11,7 @@ from streamlink.stream.stream import Stream
from streamlink.stream.dash_manifest import MPD, sleeper, sleep_until, utc, freeze_timeline
from streamlink.stream.ffmpegmux import FFMPEGMuxer
from streamlink.stream.segmented import SegmentedStreamReader, SegmentedStreamWorker, SegmentedStreamWriter
+from streamlink.utils import parse_xml
from streamlink.utils.l10n import Language
log = logging.getLogger(__name__)
@@ -162,22 +163,26 @@ class DASHStream(Stream):
return dict(type=type(self).shortname(), url=req.url, headers=headers)
@classmethod
- def parse_manifest(cls, session, url, **args):
+ def parse_manifest(cls, session, url_or_manifest, **args):
"""
Attempt to parse a DASH manifest file and return its streams
:param session: Streamlink session instance
- :param url: URL of the manifest file
+ :param url_or_manifest: URL of the manifest file or an XML manifest string
:return: a dict of name -> DASHStream instances
"""
ret = {}
- res = session.http.get(url, **args)
- url = res.url
- urlp = list(urlparse(url))
- urlp[2], _ = urlp[2].rsplit("/", 1)
+ if url_or_manifest.startswith('<?xml'):
+ mpd = MPD(parse_xml(url_or_manifest, ignore_ns=True))
+ else:
+ res = session.http.get(url_or_manifest, **args)
+ url = res.url
- mpd = MPD(session.http.xml(res, ignore_ns=True), base_url=urlunparse(urlp), url=url)
+ urlp = list(urlparse(url))
+ urlp[2], _ = urlp[2].rsplit("/", 1)
+
+ mpd = MPD(session.http.xml(res, ignore_ns=True), base_url=urlunparse(urlp), url=url)
video, audio = [], []
diff --git a/tests/streams/test_dash.py b/tests/streams/test_dash.py
index <HASH>..<HASH> 100644
--- a/tests/streams/test_dash.py
+++ b/tests/streams/test_dash.py
@@ -5,7 +5,7 @@ from streamlink.stream import *
from streamlink.stream.dash import DASHStreamWorker
from streamlink.stream.dash_manifest import MPD
from tests.mock import MagicMock, patch, ANY, Mock, call
-from tests.resources import xml
+from tests.resources import text, xml
class TestDASHStream(unittest.TestCase):
@@ -208,6 +208,13 @@ class TestDASHStream(unittest.TestCase):
self.session, self.test_url)
mpdClass.assert_called_with(ANY, base_url="http://test.bar", url="http://test.bar/foo.mpd")
+ def test_parse_manifest_string(self):
+ with text("dash/test_9.mpd") as mpd_txt:
+ test_manifest = mpd_txt.read()
+
+ streams = DASHStream.parse_manifest(self.session, test_manifest)
+ self.assertSequenceEqual(list(streams.keys()), ['2500k'])
+
@patch('streamlink.stream.dash.DASHStreamReader')
@patch('streamlink.stream.dash.FFMPEGMuxer')
def test_stream_open_video_only(self, muxer, reader):
|
streams.dash: Support manifest strings in addition to manifest urls (#<I>)
* stream.dash: Support manifest strings in addition to manifest urls
Addresses #<I>. Allows parse_manifest() to accept a string
containing a properly-formatted XML manifest instead of a
manifest url.
* streams.dash: add unit test for manifest string
* streams.dash: fix parse_manifest_string unit test
|
streamlink_streamlink
|
train
|
683c6dfd8f2fd76be914edf26cd303a148777684
|
diff --git a/src/cmd/pachd/main.go b/src/cmd/pachd/main.go
index <HASH>..<HASH> 100644
--- a/src/cmd/pachd/main.go
+++ b/src/cmd/pachd/main.go
@@ -65,7 +65,7 @@ func do(appEnvObj interface{}) error {
appEnv.Namespace,
)
go func() {
- if err := sharder.AssignRoles(nil); err != nil {
+ if err := sharder.AssignRoles(address, nil); err != nil {
protolion.Printf("Error from sharder.AssignRoles: %s", err.Error())
}
}()
@@ -205,7 +205,7 @@ func getKubeClient(env *appEnv) (*kube.Client, error) {
func getRethinkAPIServer(env *appEnv) (persist.APIServer, error) {
if err := persist_server.InitDBs(fmt.Sprintf("%s:28015", env.DatabaseAddress), env.DatabaseName); err != nil {
- return nil, err
+ protolion.Errorf("InitDBs returned error: %s", err.Error())
}
return persist_server.NewRethinkAPIServer(fmt.Sprintf("%s:28015", env.DatabaseAddress), env.DatabaseName)
}
diff --git a/src/pkg/shard/shard.go b/src/pkg/shard/shard.go
index <HASH>..<HASH> 100644
--- a/src/pkg/shard/shard.go
+++ b/src/pkg/shard/shard.go
@@ -13,7 +13,7 @@ type Sharder interface {
Register(cancel chan bool, address string, servers []Server) error
RegisterFrontends(cancel chan bool, address string, frontends []Frontend) error
- AssignRoles(chan bool) error
+ AssignRoles(address string, cancel chan bool) error
}
type TestSharder interface {
diff --git a/src/pkg/shard/sharder.go b/src/pkg/shard/sharder.go
index <HASH>..<HASH> 100644
--- a/src/pkg/shard/sharder.go
+++ b/src/pkg/shard/sharder.go
@@ -156,7 +156,44 @@ func (a *sharder) RegisterFrontends(cancel chan bool, address string, frontends
return
}
-func (a *sharder) AssignRoles(cancel chan bool) (retErr error) {
+func (a *sharder) AssignRoles(address string, cancel chan bool) (retErr error) {
+ var unsafeAssignRolesCancel chan bool
+ errChan := make(chan error)
+ // oldValue is the last value we wrote, if it's not "" it means we have the
+ // lock since we're the ones who set it last
+ oldValue := ""
+ for {
+ if err := a.discoveryClient.CheckAndSet("lock", address, holdTTL, oldValue); err != nil {
+ protolion.Errorf("sharder.AssignRoles failed to acquire lock %+v", err)
+ if oldValue != "" {
+ // lock lost
+ oldValue = ""
+ close(unsafeAssignRolesCancel)
+ protolion.Errorf("sharder.AssignRoles error from unsafeAssignRolesCancel: %+v", <-errChan)
+ }
+ } else {
+ if oldValue == "" {
+ // lock acquired
+ oldValue = address
+ unsafeAssignRolesCancel = make(chan bool)
+ go func() {
+ errChan <- a.unsafeAssignRoles(unsafeAssignRolesCancel)
+ }()
+ }
+ }
+ select {
+ case <-cancel:
+ if oldValue != "" {
+ close(unsafeAssignRolesCancel)
+ return <-errChan
+ }
+ case <-time.After(time.Second * time.Duration(holdTTL/2)):
+ }
+ }
+}
+
+// unsafeAssignRoles should be run
+func (a *sharder) unsafeAssignRoles(cancel chan bool) (retErr error) {
protolion.Info(&StartAssignRoles{})
defer func() {
protolion.Info(&FinishAssignRoles{errorToString(retErr)})
@@ -443,7 +480,7 @@ func (s *localSharder) RegisterFrontends(cancel chan bool, address string, front
return nil
}
-func (s *localSharder) AssignRoles(chan bool) error {
+func (s *localSharder) AssignRoles(string, chan bool) error {
return nil
}
diff --git a/src/pps/persist/server/rethink_api_server.go b/src/pps/persist/server/rethink_api_server.go
index <HASH>..<HASH> 100644
--- a/src/pps/persist/server/rethink_api_server.go
+++ b/src/pps/persist/server/rethink_api_server.go
@@ -60,9 +60,6 @@ func InitDBs(address string, databaseName string) error {
return err
}
if _, err := gorethink.DBCreate(databaseName).RunWrite(session); err != nil {
- if _, ok := err.(gorethink.RQLRuntimeError); ok {
- return nil
- }
return err
}
for _, table := range tables {
|
sharder.AssignRoles now aquires a cluster lock
This lets us blindly fire it up when the cluster boots up.
|
pachyderm_pachyderm
|
train
|
5a5f5787828b25d0eec7153f4b1a6e8f40900065
|
diff --git a/pysswords/python_two.py b/pysswords/python_two.py
index <HASH>..<HASH> 100644
--- a/pysswords/python_two.py
+++ b/pysswords/python_two.py
@@ -2,14 +2,6 @@ from errno import EEXIST
import os
import sys
from functools import partial
-try:
- from unittest.mock import patch, Mock
- from io import StringIO
-except ImportError:
- # backwards compatbility with Python2
- from mock import patch, Mock
- from StringIO import StringIO
-
if sys.version_info < (3,):
def makedirs(name, exist_ok=False):
diff --git a/tests/test.py b/tests/test.py
index <HASH>..<HASH> 100644
--- a/tests/test.py
+++ b/tests/test.py
@@ -10,6 +10,14 @@ from functools import wraps
import gnupg
+try:
+ from unittest.mock import patch, Mock
+ from io import StringIO
+except ImportError:
+ # backwards compatbility with Python2
+ from mock import patch, Mock
+ from StringIO import StringIO
+
__file__ = os.path.relpath(inspect.getsourcefile(lambda _: None))
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.relpath(__file__))))
import pysswords
@@ -18,6 +26,8 @@ from pysswords.db.credential import CredentialNotFoundError
from pysswords.python_two import *
+
+
TEST_DIR = os.path.join(os.path.dirname(os.path.relpath(__file__)))
TEST_DATA_DIR = os.path.join(TEST_DIR, "data")
BENCHMARK = os.environ.get("BENCHMARK")
|
Update mock python2 compatibility for development
|
marcwebbie_passpie
|
train
|
1f912dbf1d7379ee4bd3043f6abce69d52208423
|
diff --git a/tasks/complexity.js b/tasks/complexity.js
index <HASH>..<HASH> 100644
--- a/tasks/complexity.js
+++ b/tasks/complexity.js
@@ -63,7 +63,7 @@ module.exports = function(grunt) {
assignSeverity: function(data, options) {
var levels = [
- 'ignore',
+ 'info',
'warning',
'error'
];
|
error level info instead of ignore for the lowest complexity breach
|
vigetlabs_grunt-complexity
|
train
|
dcb100bfbd67eba24b44445223fcf1055c379723
|
diff --git a/lib/fluent/plugin/in_tail.rb b/lib/fluent/plugin/in_tail.rb
index <HASH>..<HASH> 100644
--- a/lib/fluent/plugin/in_tail.rb
+++ b/lib/fluent/plugin/in_tail.rb
@@ -34,6 +34,16 @@ module Fluent::Plugin
helpers :timer, :event_loop, :parser, :compat_parameters
+ class WatcherSetupError < StandardError
+ def initialize(msg)
+ @message = msg
+ end
+
+ def to_s
+ @message
+ end
+ end
+
FILE_PERMISSION = 0644
def initialize
@@ -250,6 +260,12 @@ module Fluent::Plugin
event_loop_attach(watcher.stat_trigger)
end
tw
+ rescue => e
+ if tw
+ tw.detach
+ tw.close
+ end
+ raise e
end
def start_watchers(paths)
@@ -266,7 +282,13 @@ module Fluent::Plugin
end
end
- @tails[path] = setup_watcher(path, pe)
+ begin
+ tw = setup_watcher(path, pe)
+ rescue WatcherSetupError => e
+ log.warn "Skip #{path} because unexpected setup error happens: #{e}"
+ next
+ end
+ @tails[path] = tw
}
end
@@ -480,8 +502,8 @@ module Fluent::Plugin
end
def detach
- @timer_trigger.detach if @enable_watch_timer && @timer_trigger.attached?
- @stat_trigger.detach if @stat_trigger.attached?
+ @timer_trigger.detach if @enable_watch_timer && @timer_trigger && @timer_trigger.attached?
+ @stat_trigger.detach if @stat_trigger && @stat_trigger.attached?
@io_handler.on_notify if @io_handler
end
@@ -698,6 +720,9 @@ module Fluent::Plugin
io = Fluent::FileWrapper.open(@watcher.path)
io.seek(@watcher.pe.read_pos + @fifo.bytesize)
io
+ rescue RangeError
+ io.close if io
+ raise WatcherSetupError, "seek error with #{@watcher.path}: file position = #{@watcher.pe.read_pos.to_s(16)}, reading bytesize = #{@fifo.bytesize.to_s(16)}"
rescue Errno::ENOENT
nil
end
@@ -715,6 +740,9 @@ module Fluent::Plugin
@io ||= open
yield @io
end
+ rescue WatcherSetupError => e
+ close
+ raise e
rescue
@watcher.log.error $!.to_s
@watcher.log.error_backtrace
|
in_tail: Skip setup failed watcher to avoid resource leak and log bloat. ref #<I>
|
fluent_fluentd
|
train
|
871c0b9f191c5bb5d80eaa565cb2285e1e703315
|
diff --git a/src/Rules/Functions/PrintfParametersRule.php b/src/Rules/Functions/PrintfParametersRule.php
index <HASH>..<HASH> 100644
--- a/src/Rules/Functions/PrintfParametersRule.php
+++ b/src/Rules/Functions/PrintfParametersRule.php
@@ -4,8 +4,8 @@ namespace PHPStan\Rules\Functions;
use PhpParser\Node;
use PhpParser\Node\Expr\FuncCall;
-use PhpParser\Node\Scalar\String_;
use PHPStan\Analyser\Scope;
+use PHPStan\Type\Constant\ConstantStringType;
class PrintfParametersRule implements \PHPStan\Rules\Rule
{
@@ -52,8 +52,8 @@ class PrintfParametersRule implements \PHPStan\Rules\Rule
return []; // caught by CallToFunctionParametersRule
}
- $formatArg = $args[$formatArgumentPosition]->value;
- if (!($formatArg instanceof String_)) {
+ $formatArgType = $scope->getType($args[$formatArgumentPosition]->value);
+ if (!($formatArgType instanceof ConstantStringType)) {
return []; // inspect only literal string format
}
@@ -63,7 +63,7 @@ class PrintfParametersRule implements \PHPStan\Rules\Rule
}
}
- $format = $formatArg->value;
+ $format = $formatArgType->getValue();
$placeHoldersCount = $this->getPlaceholdersCount($name, $format);
$argsCount -= $formatArgumentPosition;
diff --git a/tests/PHPStan/Rules/Functions/PrintfParametersRuleTest.php b/tests/PHPStan/Rules/Functions/PrintfParametersRuleTest.php
index <HASH>..<HASH> 100644
--- a/tests/PHPStan/Rules/Functions/PrintfParametersRuleTest.php
+++ b/tests/PHPStan/Rules/Functions/PrintfParametersRuleTest.php
@@ -73,6 +73,10 @@ class PrintfParametersRuleTest extends \PHPStan\Testing\RuleTestCase
'Call to sprintf contains 2 placeholders, 1 value given.',
29,
],
+ [
+ 'Call to sprintf contains 2 placeholders, 1 value given.',
+ 45,
+ ],
]);
}
diff --git a/tests/PHPStan/Rules/Functions/data/printf.php b/tests/PHPStan/Rules/Functions/data/printf.php
index <HASH>..<HASH> 100644
--- a/tests/PHPStan/Rules/Functions/data/printf.php
+++ b/tests/PHPStan/Rules/Functions/data/printf.php
@@ -40,3 +40,7 @@ fscanf($str, '%.E', $number); // ok
sscanf($str, '%[A-Z]%d', $char, $number); // ok
sprintf('%s %s %s', ...[1]); // do not detect unpacked arguments
sprintf('%s %s %s', ...[1, 2, 3]); // ok
+
+$format = '%s %s';
+sprintf($format, 'foo'); // one parameter missing
+sprintf($format, 'foo', 'bar'); // ok
|
PrintfParametersRule - support constant types
|
phpstan_phpstan
|
train
|
9558287c5b3510a8ce0de1de44686a0dd7125533
|
diff --git a/lib/flipper/railtie.rb b/lib/flipper/railtie.rb
index <HASH>..<HASH> 100644
--- a/lib/flipper/railtie.rb
+++ b/lib/flipper/railtie.rb
@@ -1,6 +1,6 @@
module Flipper
class Railtie < Rails::Railtie
- initializer "flipper.memoizer" do |app|
+ initializer "flipper.memoizer", after: :load_config_initializers do |app|
config = Flipper.configuration
if config.memoize
|
Initialize flipper after config/initializers/*
|
jnunemaker_flipper
|
train
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.