hash
stringlengths 40
40
| diff
stringlengths 131
114k
| message
stringlengths 7
980
| project
stringlengths 5
67
| split
stringclasses 1
value |
|---|---|---|---|---|
5e0138ba4d73c1eb530c623de1eed5ddb58e295a
|
diff --git a/src/dt2js.js b/src/dt2js.js
index <HASH>..<HASH> 100644
--- a/src/dt2js.js
+++ b/src/dt2js.js
@@ -27,6 +27,19 @@ function getRAMLContext (ramlData, rootFileDir) {
}
/**
+ * restore ints and booleans stored as strings
+ *
+ * @param {String} val - the value to be tested and possibly converted
+ * @returns {Mixed} - either a string, int or boolean.
+ */
+function destringify (val) {
+ if (parseInt(val)) return parseInt(val)
+ if (val === 'true') return true
+ if (val === 'false') return false
+ return val
+}
+
+/**
* traverses AST generated by yaml-ast-parser
* and create json object..
*
@@ -74,7 +87,8 @@ function traverse (obj, ast, rootFileDir) {
}
// a leaf node to be added
} else if (currentNode.value && currentNode.value.value) {
- var val = parseInt(currentNode.value.value) || currentNode.value.value
+ // if it looks like an int, it's an int
+ var val = destringify(currentNode.value.value)
deep(obj, keys.join('.'), val)
// a leaf that is an array
} else if (currentNode.value && currentNode.value.items) {
diff --git a/test/test_dt2js.js b/test/test_dt2js.js
index <HASH>..<HASH> 100644
--- a/test/test_dt2js.js
+++ b/test/test_dt2js.js
@@ -64,6 +64,26 @@ describe('dt2js.dt2js()', function () {
})
})
+describe('dt2js.destringify()', function () {
+ var destringify = dt2js.__get__('destringify')
+ it('should change a string to an int where possible', function () {
+ var val = destringify('100')
+ expect(val).to.equal(100)
+ })
+ it('should leave non int/ non boolean as a string', function () {
+ var val = destringify('foo')
+ expect(val).to.equal('foo')
+ })
+ it('should convert the string "true" to boolean true', function () {
+ var val = destringify('true')
+ expect(val).to.equal(true)
+ })
+ it('should convert the string "false" to boolean false', function () {
+ var val = destringify('false')
+ expect(val).to.equal(false)
+ })
+})
+
describe('dt2js.addRootKeywords()', function () {
var addRootKeywords = dt2js.__get__('addRootKeywords')
it('should add missing root keywords', function () {
|
add destringify() catch booleans as well as ints. add tests
|
raml-org_ramldt2jsonschema
|
train
|
6f4ffa68be8a5d6c7e7898b05fc7c14e3fa76615
|
diff --git a/Form/CanonizationExtension.php b/Form/CanonizationExtension.php
index <HASH>..<HASH> 100644
--- a/Form/CanonizationExtension.php
+++ b/Form/CanonizationExtension.php
@@ -48,7 +48,11 @@ class CanonizationExtension extends AbstractTypeExtension implements EventSubscr
$builder->addEventListener(FormEvents::PRE_SUBMIT, [$this, 'onPreSubmit'], 512);
if ($this->currentRequest && $options['canonize']) {
- $builder->setMethod($this->currentRequest->getRealMethod());
+ $method = $this->currentRequest->getRealMethod();
+
+ if (in_array($method, ['GET', 'PUT', 'POST', 'DELETE', 'PATCH'])) {
+ $builder->setMethod($method);
+ }
}
}
|
Applying form canonization extension only for allowed methods
|
vaniocz_vanio-web-bundle
|
train
|
6caf8a1fce985d73e8b066eed1f8e7da103f8af6
|
diff --git a/src/resources/views/dataImport/index.blade.php b/src/resources/views/dataImport/index.blade.php
index <HASH>..<HASH> 100644
--- a/src/resources/views/dataImport/index.blade.php
+++ b/src/resources/views/dataImport/index.blade.php
@@ -105,7 +105,11 @@
v-if="summary" key="report">
<div class="row">
<div class="col-xs-12 col-md-4">
- <box-widget theme="bg-orange"
+ <button v-if="summary.errors === 0"
+ class="btn btn-primary margin-bottom-md"
+ @click="summary=null">{{ __("Back") }}
+ </button>
+ <box-widget theme="bg-orange"
image="/images/excel_logo.svg"
name="{{ __(('Excel Import')) }}"
position="{{ __('Summary') }}"
|
added back button for summary when there are no errors
|
laravel-enso_DataImport
|
train
|
7272b14ebabf284ccebed9a680ac6206a16fb951
|
diff --git a/ChartNew.js b/ChartNew.js
index <HASH>..<HASH> 100644
--- a/ChartNew.js
+++ b/ChartNew.js
@@ -1130,6 +1130,7 @@ window.Chart = function (context) {
animation: true,
animationSteps: 60,
animationEasing: "easeOutQuart",
+ extrapolateMissingData : true,
onAnimationComplete: null,
annotateLabel: "<%=(v1 == '' ? '' : v1) + (v1!='' && v2 !='' ? ' - ' : '')+(v2 == '' ? '' : v2)+(v1!='' || v2 !='' ? ':' : '') + v3%>"
@@ -5491,6 +5492,8 @@ window.Chart = function (context) {
}
}
+ if((typeof(data.datasets[i].data[j+1]) !== 'undefined') || (true == config.extrapolateMissingData))
+ {
if(currentAnimPc.subVal > 0)
{
// next not missing value
@@ -5545,6 +5548,27 @@ window.Chart = function (context) {
}
}
} else {
+ if(false == config.extrapolateMissingData)
+ {
+ ctx.stroke();
+ if (config.datasetFill) {
+ ctx.lineTo(prevXpos, xAxisPosY - zeroY);
+ ctx.lineTo(xPos(i,frstpt,data), xAxisPosY - zeroY);
+ ctx.lineTo(xPos(i,frstpt,data), yPos(i, frstpt));
+ ctx.closePath();
+ if (typeof data.datasets[i].fillColor == "function")ctx.fillStyle = data.datasets[i].fillColor("FILLCOLOR",data,config,i,-1,currentAnimPc.mainVal,-1);
+ else if(typeof data.datasets[i].fillColor=="string")ctx.fillStyle = data.datasets[i].fillColor;
+ else ctx.fillStyle=config.defaultFillColor;
+ ctx.fill();
+ }
+
+ ctx.beginPath();
+ prevpt=-1;
+ frstpt=-1;
+ prevAnimPc=0;
+ prevnotempty=0;
+ }
+ else {
if(currentAnimPc.subVal > 0)
{
@@ -5552,6 +5576,8 @@ window.Chart = function (context) {
for(t=j+1;t<data.datasets[i].data["length"] && nxtnotmiss==-1;t++){
if (!(typeof(data.datasets[i].data[t])=='undefined')) nxtnotmiss=t;
}
+ if((typeof(data.datasets[i].data[j]) !== 'undefined') || (true == config.extrapolateMissingData))
+ {
if(nxtnotmiss!=-1) {
prevXpos=xPos(i,j+currentAnimPc.subVal,data);
if (config.bezierCurve) {
@@ -5561,6 +5587,8 @@ window.Chart = function (context) {
ctx.lineTo(xPos(i,j+currentAnimPc.subVal,data), yPos(i, j+1));
}
}
+ }
+ }
}
}
}
|
Break line in line chart enhancement #<I>
|
FVANCOP_ChartNew.js
|
train
|
5a6b7f4b334df750272b1eefa65740a2bf01e610
|
diff --git a/dev/com.ibm.ws.injection/src/com/ibm/ws/injectionengine/osgi/internal/OSGiInjectionEngineImpl.java b/dev/com.ibm.ws.injection/src/com/ibm/ws/injectionengine/osgi/internal/OSGiInjectionEngineImpl.java
index <HASH>..<HASH> 100644
--- a/dev/com.ibm.ws.injection/src/com/ibm/ws/injectionengine/osgi/internal/OSGiInjectionEngineImpl.java
+++ b/dev/com.ibm.ws.injection/src/com/ibm/ws/injectionengine/osgi/internal/OSGiInjectionEngineImpl.java
@@ -577,7 +577,7 @@ public class OSGiInjectionEngineImpl extends AbstractInjectionEngine implements
@Override
public ResourceFactoryBuilder getResourceFactoryBuilder(String type) throws InjectionException {
Iterator<ResourceFactoryBuilder> builderIter = resourceFactoryBuilders.getServices(type);
- ResourceFactoryBuilder builder = builderIter.hasNext() ? builderIter.next() : null;
+ ResourceFactoryBuilder builder = builderIter != null && builderIter.hasNext() ? builderIter.next() : null;
if (builder == null) {
throw new InjectionException(type + " definitions are not supported in this server configuration");
}
|
Issue #<I>: Improve injection exception
Improve serviceability by avoiding a NullPointerException; throw expected,
meaningful InjectionException
|
OpenLiberty_open-liberty
|
train
|
b6d05cf321fb4676e9542dd5884c5cdacc461862
|
diff --git a/Neos.Utility.ObjectHandling/Classes/TYPO3/Flow/Utility/TypeHandling.php b/Neos.Utility.ObjectHandling/Classes/TYPO3/Flow/Utility/TypeHandling.php
index <HASH>..<HASH> 100644
--- a/Neos.Utility.ObjectHandling/Classes/TYPO3/Flow/Utility/TypeHandling.php
+++ b/Neos.Utility.ObjectHandling/Classes/TYPO3/Flow/Utility/TypeHandling.php
@@ -23,7 +23,7 @@ abstract class TypeHandling
/**
* A property type parse pattern.
*/
- const PARSE_TYPE_PATTERN = '/^\\\\?(?P<type>integer|int|float|double|boolean|bool|string|DateTime|[A-Z][a-zA-Z0-9\\\\]+|object|array|ArrayObject|SplObjectStorage|Doctrine\\\\Common\\\\Collections\\\\Collection|Doctrine\\\\Common\\\\Collections\\\\ArrayCollection)(?:<\\\\?(?P<elementType>[a-zA-Z0-9\\\\]+)>)?/';
+ const PARSE_TYPE_PATTERN = '/^\\\\?(?P<type>integer|int|float|double|boolean|bool|string|DateTime|[A-Z][a-zA-Z0-9\\\\_]+|object|array|ArrayObject|SplObjectStorage|Doctrine\\\\Common\\\\Collections\\\\Collection|Doctrine\\\\Common\\\\Collections\\\\ArrayCollection)(?:<\\\\?(?P<elementType>[a-zA-Z0-9\\\\_]+)>)?/';
/**
* A type pattern to detect literal types.
diff --git a/Neos.Utility.ObjectHandling/Tests/Unit/TypeHandlingTest.php b/Neos.Utility.ObjectHandling/Tests/Unit/TypeHandlingTest.php
index <HASH>..<HASH> 100644
--- a/Neos.Utility.ObjectHandling/Tests/Unit/TypeHandlingTest.php
+++ b/Neos.Utility.ObjectHandling/Tests/Unit/TypeHandlingTest.php
@@ -54,6 +54,10 @@ class TypeHandlingTest extends \PHPUnit_Framework_TestCase
array('SplObjectStorage<\TYPO3\Foo\Bar>', array('type' => 'SplObjectStorage', 'elementType' => 'TYPO3\Foo\Bar')),
array('Doctrine\Common\Collections\Collection<\TYPO3\Foo\Bar>', array('type' => 'Doctrine\Common\Collections\Collection', 'elementType' => 'TYPO3\Foo\Bar')),
array('Doctrine\Common\Collections\ArrayCollection<\TYPO3\Foo\Bar>', array('type' => 'Doctrine\Common\Collections\ArrayCollection', 'elementType' => 'TYPO3\Foo\Bar')),
+
+ // Types might also contain underscores at various points.
+ array('Doctrine\Common\Collections\Special_Class_With_Underscores', array('type' => 'Doctrine\Common\Collections\Special_Class_With_Underscores', 'elementType' => null)),
+ array('Doctrine\Common\Collections\ArrayCollection<\TYPO3\Foo_\Bar>', array('type' => 'Doctrine\Common\Collections\ArrayCollection', 'elementType' => 'TYPO3\Foo_\Bar')),
);
}
@@ -88,6 +92,9 @@ class TypeHandlingTest extends \PHPUnit_Framework_TestCase
array('SplObjectStorage<\object>', 'SplObjectStorage'),
array('Doctrine\Common\Collections\Collection<ElementType>', 'Doctrine\Common\Collections\Collection'),
array('Doctrine\Common\Collections\ArrayCollection<>', 'Doctrine\Common\Collections\ArrayCollection'),
+
+ // Types might also contain underscores at various points.
+ array('Doctrine\Common\Collections\Array_Collection<>', 'Doctrine\Common\Collections\Array_Collection'),
);
}
|
BUGFIX: Type Handling should not break when classnames contain underscores
While underscores in class names are not used in Flow code itself, it might
happen that TypeHandling is used outside Flow - where having underscores
in class names is perfectly valid.
This change ensures that underscores in class names are recognized properly.
|
neos_flow-development-collection
|
train
|
9f5bfe6dc8aa909cc1b157b407328e53ed1e9ab6
|
diff --git a/km3modules/__init__.py b/km3modules/__init__.py
index <HASH>..<HASH> 100644
--- a/km3modules/__init__.py
+++ b/km3modules/__init__.py
@@ -9,6 +9,7 @@ A collection of commonly used modules.
from .common import Dump, Keep, Delete, StatusBar
from .mc import GlobalRandomState
+from . import ahrs
from . import common
from . import communication
from . import fit
|
Import ahrs as submodule in km3module
|
tamasgal_km3pipe
|
train
|
c4c8928ab46b42bbb25b11e87d83d250b3988596
|
diff --git a/install/class/ReadDirectory.php b/install/class/ReadDirectory.php
index <HASH>..<HASH> 100755
--- a/install/class/ReadDirectory.php
+++ b/install/class/ReadDirectory.php
@@ -5,9 +5,15 @@ namespace BFW\Install;
class ReadDirectory
{
/**
- * @var $list : List all path found
+ * @var string $calledClass : Name of the current class.
+ * For recall this correct class when she's extended.
*/
- protected $list = [];
+ protected $calledClass = '';
+
+ /**
+ * @var array $list : List all path found
+ */
+ protected $list;
/**
* @var $ignore : Item to ignored during the reading of directories
@@ -21,7 +27,8 @@ class ReadDirectory
*/
public function __construct(&$listFiles)
{
- $this->list = &$listFiles;
+ $this->calledClass = get_called_class();
+ $this->list = &$listFiles;
}
/**
|
ReadDirectory : Add the calledClass attribute
For have the correct class when she's extends
|
bfw-systems_bfw
|
train
|
577deac1513071eb04b7456c3ababe48d42d97f4
|
diff --git a/lib/waterline/methods/destroy.js b/lib/waterline/methods/destroy.js
index <HASH>..<HASH> 100644
--- a/lib/waterline/methods/destroy.js
+++ b/lib/waterline/methods/destroy.js
@@ -447,8 +447,10 @@ module.exports = function destroy(/* criteria, explicitCbMaybe, metaContainer */
'Warning: Unexpected behavior in database adapter:\n'+
'Since `fetch` is NOT enabled, this adapter (for datastore `'+WLModel.datastore+'`)\n'+
'should NOT have sent back anything as the 2nd argument when triggering the callback\n'+
- 'from its `destroy` method. But it did! And since it\'s an array, displaying this\n'+
- 'warning to help avoid confusion and draw attention to the bug. Specifically, got:\n'+
+ 'from its `destroy` method. But it did!\n'+
+ '\n'+
+ '(Displaying this warning to help avoid confusion and draw attention to the bug.\n'+
+ 'Specifically, got:\n'+
util.inspect(rawAdapterResult, {depth:5})+'\n'+
'(Ignoring it and proceeding anyway...)'+'\n'
);
|
Fixing warning message to be more accurate (we show it whether or not an array came back, so it's weird to call it an array if it isn't. That's like putting a rabbit behind a curtain, telling the audience you're going to make the rabbit disappear, then pulling away the curtain from in front of the rabbit only to reveal that there is an opposum there instead-- but then telling the audience 'Ah, well, something must have gone wrong, since clearly there is still a rabbit here.')
|
balderdashy_waterline
|
train
|
6e3af4cb834a42ace77c02ba953125d714f4873a
|
diff --git a/src/Exceptions/Handler.php b/src/Exceptions/Handler.php
index <HASH>..<HASH> 100644
--- a/src/Exceptions/Handler.php
+++ b/src/Exceptions/Handler.php
@@ -117,9 +117,9 @@ class Handler extends ExceptionHandler
if (view()->exists("cortex/foundation::common.errors.{$status}")) {
return response()->view("cortex/foundation::common.errors.{$status}", ['exception' => $exception], $status, $exception->getHeaders());
- } else {
- return parent::renderHttpException($exception);
}
+
+ return parent::renderHttpException($exception);
}
/**
diff --git a/src/Overrides/Illuminate/Routing/UrlGenerator.php b/src/Overrides/Illuminate/Routing/UrlGenerator.php
index <HASH>..<HASH> 100644
--- a/src/Overrides/Illuminate/Routing/UrlGenerator.php
+++ b/src/Overrides/Illuminate/Routing/UrlGenerator.php
@@ -40,7 +40,7 @@ class UrlGenerator extends BaseUrlGenerator
// for passing the array of parameters to this URL as a list of segments.
$root = $this->formatRoot($this->formatScheme($secure));
- list($path, $query) = $this->extractQueryString($path);
+ [$path, $query] = $this->extractQueryString($path);
return $this->format(
$root, '/'.trim($path.'/'.$tail, '/')
diff --git a/src/Overrides/Mcamara/LaravelLocalization/LaravelLocalization.php b/src/Overrides/Mcamara/LaravelLocalization/LaravelLocalization.php
index <HASH>..<HASH> 100644
--- a/src/Overrides/Mcamara/LaravelLocalization/LaravelLocalization.php
+++ b/src/Overrides/Mcamara/LaravelLocalization/LaravelLocalization.php
@@ -36,9 +36,9 @@ class LaravelLocalization extends BaseLaravelLocalization
$url = '';
$url .= isset($parsed_url['scheme']) ? $parsed_url['scheme'].'://' : '';
- $url .= isset($parsed_url['host']) ? $parsed_url['host'] : '';
+ $url .= $parsed_url['host'] ?? '';
$url .= isset($parsed_url['port']) ? ':'.$parsed_url['port'] : '';
- $user = isset($parsed_url['user']) ? $parsed_url['user'] : '';
+ $user = $parsed_url['user'] ?? '';
$pass = isset($parsed_url['pass']) ? ':'.$parsed_url['pass'] : '';
$url .= $user.(($user || $pass) ? "{$pass}@" : '');
diff --git a/src/Relations/BelongsToMorph.php b/src/Relations/BelongsToMorph.php
index <HASH>..<HASH> 100644
--- a/src/Relations/BelongsToMorph.php
+++ b/src/Relations/BelongsToMorph.php
@@ -114,14 +114,14 @@ class BelongsToMorph extends BelongsTo
// the calling method's name and use that as the relationship name as most
// of the time this will be what we desire to use for the relationships.
if (is_null($relation)) {
- list($current, $caller) = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 2);
+ [$current, $caller] = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 2);
$relation = $caller['function'];
}
$morphName = Arr::get(array_flip(Relation::morphMap()), $related, $related);
- list($type, $id) = self::getMorphs(Str::snake($name), $type, $id);
+ [$type, $id] = self::getMorphs(Str::snake($name), $type, $id);
$instance = new $related();
|
Apply fixes from StyleCI (#<I>)
|
rinvex_cortex-foundation
|
train
|
f94551d04c1b117feff8706a18aa491d68de6c0d
|
diff --git a/lib/sessions.js b/lib/sessions.js
index <HASH>..<HASH> 100644
--- a/lib/sessions.js
+++ b/lib/sessions.js
@@ -224,6 +224,13 @@ function endTransaction(clientSession, commandName, callback) {
if (clientSession.serverSession.stmtId === 0) {
// The server transaction was never started.
+
+ // reset internal transaction state
+ clientSession.transactionOptions = null;
+ if (clientSession.autoStartTransaction) {
+ clientSession.startTransaction();
+ }
+
callback(null, null);
return;
}
@@ -243,7 +250,6 @@ function endTransaction(clientSession, commandName, callback) {
(err, reply) => {
// reset internal transaction state
clientSession.transactionOptions = null;
-
if (clientSession.autoStartTransaction) {
clientSession.startTransaction();
}
|
refactor(txns): reset internal txn state even if never started
|
mongodb-js_mongodb-core
|
train
|
98866f426d03157a30c533a99f3ac2bf8e2dfc2d
|
diff --git a/server/camlistored/ui/detail.js b/server/camlistored/ui/detail.js
index <HASH>..<HASH> 100644
--- a/server/camlistored/ui/detail.js
+++ b/server/camlistored/ui/detail.js
@@ -87,7 +87,7 @@ cam.DetailView = React.createClass({
},
handlePendingNavigation_: function() {
- if (!this.handlePendingNavigation_) {
+ if (!this.pendingNavigation_) {
return;
}
|
Fix bug where you have to press back twice to get out of detail view.
Change-Id: Ib2a<I>b3eb1c<I>e<I>cf<I>e<I>ac6f<I>
|
perkeep_perkeep
|
train
|
8161e1b621bfb384071b14aff020a5e8cf11f3a3
|
diff --git a/android/src/main/java/com/dieam/reactnativepushnotification/modules/RNReceivedMessageHandler.java b/android/src/main/java/com/dieam/reactnativepushnotification/modules/RNReceivedMessageHandler.java
index <HASH>..<HASH> 100644
--- a/android/src/main/java/com/dieam/reactnativepushnotification/modules/RNReceivedMessageHandler.java
+++ b/android/src/main/java/com/dieam/reactnativepushnotification/modules/RNReceivedMessageHandler.java
@@ -9,6 +9,7 @@ import android.app.Application;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
+import android.content.Context;
import android.util.Log;
import android.net.Uri;
import androidx.annotation.NonNull;
@@ -46,10 +47,11 @@ public class RNReceivedMessageHandler {
// ^ It's null when message is from GCM
RNPushNotificationConfig config = new RNPushNotificationConfig(mFirebaseMessagingService.getApplication());
- bundle.putString("title", getLocalizedString(remoteNotification.getTitleLocalizationKey(),
- remoteNotification.getTitleLocalizationArgs(), remoteNotification.getTitle()));
- bundle.putString("message", getLocalizedString(remoteNotification.getBodyLocalizationKey(),
- remoteNotification.getBodyLocalizationArgs(), remoteNotification.getBody()));
+ String title = getLocalizedString(remoteNotification.getTitle(), remoteNotification.getTitleLocalizationKey(), remoteNotification.getTitleLocalizationArgs());
+ String body = getLocalizedString(remoteNotification.getBody(), remoteNotification.getBodyLocalizationKey(), remoteNotification.getBodyLocalizationArgs());
+
+ bundle.putString("title", title);
+ bundle.putString("message", body);
bundle.putString("sound", remoteNotification.getSound());
bundle.putString("color", remoteNotification.getColor());
bundle.putString("tag", remoteNotification.getTag());
@@ -181,19 +183,27 @@ public class RNReceivedMessageHandler {
}
}
- private String getLocalizedString(String locKey, String[] locArgs, String defaultText) {
- String packageName = getPackageName();
- String result = defaultText;
+ private String getLocalizedString(String text, String locKey, String[] locArgs) {
+ if(text != null) {
+ return text;
+ }
+
+ Context context = mFirebaseMessagingService.getApplicationContext();
+ String packageName = context.getPackageName();
+
+ String result = null;
+
if (locKey != null) {
- int id = getResources().getIdentifier(locKey, "string", packageName);
+ int id = context.getResources().getIdentifier(locKey, "string", packageName);
if (id != 0) {
if (locArgs != null) {
- result = res.getString(id, (Object[]) locArgs);
+ result = context.getResources().getString(id, (Object[]) locArgs);
} else {
- result = res.getString(id);
+ result = context.getResources().getString(id);
}
}
}
+
return result;
}
}
|
Update RNReceivedMessageHandler.java
|
zo0r_react-native-push-notification
|
train
|
3e607c726fb6728a71cf086b1bab4152f9b01cf1
|
diff --git a/common-core-jackson-serialization-open/src/test/java/com/bbn/bue/common/serialization/jackson/TestSerialization.java b/common-core-jackson-serialization-open/src/test/java/com/bbn/bue/common/serialization/jackson/TestSerialization.java
index <HASH>..<HASH> 100644
--- a/common-core-jackson-serialization-open/src/test/java/com/bbn/bue/common/serialization/jackson/TestSerialization.java
+++ b/common-core-jackson-serialization-open/src/test/java/com/bbn/bue/common/serialization/jackson/TestSerialization.java
@@ -26,4 +26,12 @@ public class TestSerialization extends TestCase {
assertEquals(foo, JacksonTestUtils.roundTripThroughSerializer(foo, serializer));
}
+ @Test
+ public void testSerializingFromString() throws IOException {
+ final Map<String, FMeasureCounts> foo = ImmutableMap.of("Hello",
+ FMeasureCounts.from(1, 2, 3));
+ final String serialized = serializer.writeValueAsString(foo);
+ assertEquals(foo, serializer.deserializeFromString(serialized, foo.getClass()));
+ }
+
}
|
add method to test serialization to and from strings
|
BBN-E_bue-common-open
|
train
|
29b1b2abe6d55d88331a6e6f2265f1ec436d8188
|
diff --git a/spec/twitter/client_spec.rb b/spec/twitter/client_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/twitter/client_spec.rb
+++ b/spec/twitter/client_spec.rb
@@ -82,7 +82,7 @@ describe Twitter::Client do
it "should recursively merge connection options" do
stub_get("/1/statuses/user_timeline.json").
- with(:query => {:screen_name => "sferik"}, :headers => {"User-Agent" => "Custom User Agent"}).
+ with(:query => {:screen_name => "sferik"}, :headers => {"Accept" => "application/json", "User-Agent" => "Custom User Agent"}).
to_return(:body => fixture("statuses.json"), :headers => {:content_type => "application/json; charset=utf-8"})
client = Twitter::Client.new(:connection_options => {:headers => {:user_agent => 'Custom User Agent'}})
client.user_timeline("sferik")
|
Ensure Accept header is preserved after deep merge
|
sferik_twitter
|
train
|
455e3f3142517f78f2731e9fc2140a87b0d362c8
|
diff --git a/org.jenetics/src/main/java/org/jenetics/util/LCG64ShiftRandom.java b/org.jenetics/src/main/java/org/jenetics/util/LCG64ShiftRandom.java
index <HASH>..<HASH> 100644
--- a/org.jenetics/src/main/java/org/jenetics/util/LCG64ShiftRandom.java
+++ b/org.jenetics/src/main/java/org/jenetics/util/LCG64ShiftRandom.java
@@ -69,7 +69,7 @@ import java.io.Serializable;
*
* @author <a href="mailto:franz.wilhelmstoetter@gmx.at">Franz Wilhelmstötter</a>
* @since 1.1
- * @version 2.0 — <em>$Date: 2013-05-25 $</em>
+ * @version 2.0 — <em>$Date: 2013-05-27 $</em>
*/
public class LCG64ShiftRandom extends Random64 {
@@ -82,7 +82,7 @@ public class LCG64ShiftRandom extends Random64 {
*
* @author <a href="mailto:franz.wilhelmstoetter@gmx.at">Franz Wilhelmstötter</a>
* @since 1.1
- * @version 1.1 — <em>$Date: 2013-05-25 $</em>
+ * @version 2.0 — <em>$Date: 2013-05-27 $</em>
*/
public static final class Param implements Serializable {
@@ -182,7 +182,7 @@ public class LCG64ShiftRandom extends Random64 {
*
* @author <a href="mailto:franz.wilhelmstoetter@gmx.at">Franz Wilhelmstötter</a>
* @since 1.1
- * @version 1.1 — <em>$Date: 2013-05-25 $</em>
+ * @version 2.0 — <em>$Date: 2013-05-27 $</em>
*/
public static class ThreadLocal extends java.lang.ThreadLocal<LCG64ShiftRandom> {
private static final long STEP_BASE = 1L << 56;
@@ -270,7 +270,7 @@ public class LCG64ShiftRandom extends Random64 {
*
* @author <a href="mailto:franz.wilhelmstoetter@gmx.at">Franz Wilhelmstötter</a>
* @since 1.1
- * @version 1.1 — <em>$Date: 2013-05-25 $</em>
+ * @version 2.0 — <em>$Date: 2013-05-27 $</em>
*/
public static class ThreadSafe extends LCG64ShiftRandom {
private static final long serialVersionUID = 1L;
|
Update version string to <I>.
|
jenetics_jenetics
|
train
|
573513f9c871a2ededd25758072f5f8f3356b684
|
diff --git a/lib/pre/context.js b/lib/pre/context.js
index <HASH>..<HASH> 100644
--- a/lib/pre/context.js
+++ b/lib/pre/context.js
@@ -13,8 +13,9 @@ var assert = require('assert-plus');
* @returns {Function}
*/
function ctx() {
- var data = {};
return function context(req, res, next) {
+ var data = {};
+
req.set = function set(key, value) {
assert.string(key, 'key must be string');
diff --git a/test/context.test.js b/test/context.test.js
index <HASH>..<HASH> 100644
--- a/test/context.test.js
+++ b/test/context.test.js
@@ -0,0 +1,100 @@
+'use strict';
+
+// external requires
+var assert = require('chai').assert;
+var restify = require('restify');
+var restifyClients = require('restify-clients');
+
+// local files
+var helper = require('./lib/helper');
+var plugins = require('../lib');
+
+// local globals
+var SERVER;
+var CLIENT;
+var PORT;
+
+describe('accept parser', function () {
+
+ before(function (done) {
+ SERVER = restify.createServer({
+ dtrace: helper.dtrace,
+ log: helper.getLog('server')
+ });
+
+ SERVER.use(plugins.pre.context());
+
+ SERVER.get('/', function respond(req, res, next) {
+ res.send();
+ next();
+ });
+
+ SERVER.listen(0, '127.0.0.1', function () {
+ PORT = SERVER.address().port;
+ CLIENT = restifyClients.createJsonClient({
+ url: 'http://127.0.0.1:' + PORT,
+ dtrace: helper.dtrace,
+ retry: false
+ });
+
+ done();
+ });
+ });
+
+ after(function (done) {
+ CLIENT.close();
+ SERVER.close(done);
+ });
+
+
+ it('should use context', function (done) {
+
+ SERVER.get('/', [
+ function one(req, res, next) {
+ req.set('foo', {
+ a: 1
+ });
+ return next();
+ },
+ function two(req, res, next) {
+ assert.deepEqual(req.get('foo'), {
+ a: 1
+ });
+ req.get('foo').b = 2;
+ req.set('bar', [1]);
+ return next();
+ },
+ function three(req, res, next) {
+ assert.deepEqual(req.get('foo'), {
+ a: 1,
+ b: 2
+ });
+ assert.deepEqual(req.get('bar'), [1]);
+ res.send();
+ return next();
+ }
+ ]);
+
+ CLIENT.get('/', function (err, _, res) {
+ assert.ifError(err);
+ assert.equal(res.statusCode, 200);
+ return done();
+ });
+ });
+
+
+ it('should not share context', function (done) {
+
+ SERVER.get('/', function one(req, res, next) {
+ // ensure we don't get context from previous request
+ assert.equal(req.get('foo', null));
+ return next();
+ });
+
+ CLIENT.get('/', function (err, _, res) {
+ assert.ifError(err);
+ assert.equal(res.statusCode, 200);
+ return done();
+ });
+ });
+});
|
fix req ctx (#<I>)
|
restify_plugins
|
train
|
827025af6f69ff57c80697f5441d9df35f58a038
|
diff --git a/brokit/blat.py b/brokit/blat.py
index <HASH>..<HASH> 100644
--- a/brokit/blat.py
+++ b/brokit/blat.py
@@ -8,6 +8,7 @@ from tempfile import mkstemp
from cogent import DNA
from cogent.core.genetic_code import GeneticCodes
+from cogent.parse.blast import MinimalBlatParser9
from skbio.parse.sequences import parse_fasta
from skbio.app.util import (CommandLineApplication, ResultPath,
|
added an import so we can access it from QIIME
|
biocore_burrito-fillings
|
train
|
1e198be55d4c3b4118ba6fc3f0c0202868158324
|
diff --git a/package.json b/package.json
index <HASH>..<HASH> 100644
--- a/package.json
+++ b/package.json
@@ -30,13 +30,16 @@
"testling": {
"harness": "mocha-bdd",
"files": "test/*.browser.js",
- "browsers": {
- "ie": [ 6, 7, 8 ],
- "ff": [ 19 ],
- "safari": [ 5 ],
- "opera": [ 12 ],
- "chrome": [ 25 ]
- }
+ "browsers": [
+ "ie/6..latest",
+ "chrome/22..latest",
+ "firefox/16..latest",
+ "safari/latest",
+ "opera/11.0..latest",
+ "iphone/6",
+ "ipad/6",
+ "android-browser/latest"
+ ]
},
"devDependencies": {
"browserchannel": "1.0.x",
diff --git a/primus.js b/primus.js
index <HASH>..<HASH> 100644
--- a/primus.js
+++ b/primus.js
@@ -20,7 +20,7 @@ function Primus(url, options) {
if (Stream) Stream.call(this); // Initialize a stream interface.
- this.initialise().connect();
+ this.initialise().open();
}
Primus.OPENING = 0; // We're opening the connection.
@@ -113,7 +113,7 @@ Primus.prototype.initialise = function initalise() {
*
* @api private
*/
-Primus.prototype.connect = function connect() {
+Primus.prototype.open = function open() {
this.emit('outgoing::connect', this.uri('ws'), this.uri('http'));
return this;
@@ -152,6 +152,7 @@ Primus.prototype.write = function write(data) {
* @api public
*/
Primus.prototype.end = function end(data) {
+ if (this.readyState === Primus.CLOSED) return this;
if (data) this.write(data);
this.writable = false;
diff --git a/test/transformer.base.js b/test/transformer.base.js
index <HASH>..<HASH> 100644
--- a/test/transformer.base.js
+++ b/test/transformer.base.js
@@ -47,6 +47,20 @@ module.exports = function base(transformer) {
});
});
+ it('should change readyStates', function (done) {
+ var socket = new Socket('http://localhost:'+ server.portnumber);
+
+ expect(socket.readyState).to.equal(Socket.OPENING);
+
+ socket.on('open', function () {
+ expect(socket.readyState).to.equal(Socket.OPEN);
+ socket.end();
+ }).on('end', function () {
+ expect(socket.readyState).to.equal(Socket.CLOSED);
+ done();
+ });
+ });
+
it('emits an `end` event when its closed', function (done) {
var socket = new Socket('http://localhost:'+ server.portnumber);
@@ -55,6 +69,19 @@ module.exports = function base(transformer) {
}).on('end', done);
});
+ it('only emits `end` once', function (done) {
+ var socket = new Socket('http://localhost:'+ server.portnumber);
+
+ socket.on('open', function () {
+ socket.end();
+ socket.end();
+ socket.end();
+ socket.end();
+ socket.end();
+ socket.end();
+ }).on('end', done);
+ });
+
it('sends & receives messages', function (done) {
var socket = new Socket('http://localhost:'+ server.portnumber);
@@ -69,6 +96,23 @@ module.exports = function base(transformer) {
});
});
+ it('emits an `error` event when it cannot encode the data', function (done) {
+ var socket = new Socket('http://localhost:'+ server.portnumber);
+
+ socket.on('open', function () {
+ var data = { foo: 'bar' };
+ data.recusrive = data;
+
+ socket.write(data);
+ }).on('error', function (err) {
+ expect(err).to.not.be.instanceOf(String);
+ expect(err.message).to.contain('JSON');
+
+ socket.end();
+ done();
+ });
+ });
+
it('buffers messages before it connected', function (done) {
var socket = new Socket('http://localhost:'+ server.portnumber)
, messages = 10
|
[test] Updated testling
[test] More test coverage
|
primus_primus
|
train
|
660cb58fa4be12e2096cbd004423648f29bab9fe
|
diff --git a/satpy/readers/hrit_goes.py b/satpy/readers/hrit_goes.py
index <HASH>..<HASH> 100644
--- a/satpy/readers/hrit_goes.py
+++ b/satpy/readers/hrit_goes.py
@@ -380,12 +380,14 @@ class HRITGOESFileHandler(HRITFileHandler):
logger.debug("Getting raw data")
res = super(HRITGOESFileHandler, self).get_dataset(key, info)
- res.attrs = info.copy()
self.mda['calibration_parameters'] = self._get_calibration_params()
+
res = self.calibrate(res, key.calibration)
+ new_attrs = info.copy()
+ new_attrs.update(res.attrs)
+ res.attrs = new_attrs
res.attrs['platform_name'] = self.platform_name
res.attrs['sensor'] = 'goes_imager'
-
return res
def _get_calibration_params(self):
|
Fix attribute assignment in hrit_goes
|
pytroll_satpy
|
train
|
9ac36f0b492735e39551ae0102c4f2ff9637382d
|
diff --git a/lib/doc/workbook.js b/lib/doc/workbook.js
index <HASH>..<HASH> 100644
--- a/lib/doc/workbook.js
+++ b/lib/doc/workbook.js
@@ -195,7 +195,7 @@ class Workbook {
this._worksheets = [];
value.worksheets.forEach(worksheetModel => {
const {id, name, state} = worksheetModel;
- const orderNo = value.sheets.findIndex(ws => ws.id === id);
+ const orderNo = value.sheets && value.sheets.findIndex(ws => ws.id === id);
const worksheet = this._worksheets[id] = new Worksheet({
id,
name,
diff --git a/lib/xlsx/xform/sheet/cell-xform.js b/lib/xlsx/xform/sheet/cell-xform.js
index <HASH>..<HASH> 100644
--- a/lib/xlsx/xform/sheet/cell-xform.js
+++ b/lib/xlsx/xform/sheet/cell-xform.js
@@ -387,7 +387,7 @@ utils.inherits(CellXform, BaseXform, {
},
reconcile(model, options) {
- const style = model.styleId && options.styles.getStyleModel(model.styleId);
+ const style = model.styleId && options.styles && options.styles.getStyleModel(model.styleId);
if (style) {
model.style = style;
}
@@ -398,7 +398,9 @@ utils.inherits(CellXform, BaseXform, {
switch (model.type) {
case Enums.ValueType.String:
if (typeof model.value === 'number') {
- model.value = options.sharedStrings.getString(model.value);
+ if (options.sharedStrings) {
+ model.value = options.sharedStrings.getString(model.value);
+ }
}
if (model.value.richText) {
model.type = Enums.ValueType.RichText;
diff --git a/spec/integration/workbook-xlsx-reader.spec.js b/spec/integration/workbook-xlsx-reader.spec.js
index <HASH>..<HASH> 100644
--- a/spec/integration/workbook-xlsx-reader.spec.js
+++ b/spec/integration/workbook-xlsx-reader.spec.js
@@ -289,6 +289,14 @@ describe("WorkbookReader", () => {
});
});
+ describe("with a spreadsheet that is missing some files in the zip container", function() {
+ it("should not break", function() {
+ const workbook = new Excel.Workbook();
+ return workbook.xlsx
+ .readFile("./spec/integration/data/missing-bits.xlsx");
+ });
+ });
+
describe("with a spreadsheet that contains images", () => {
before(function() {
const testContext = this;
|
Fix reading of a file with missing entries in the zip container
|
exceljs_exceljs
|
train
|
c85f24fda206898d6603f4f5656d386453796f6f
|
diff --git a/utils.go b/utils.go
index <HASH>..<HASH> 100644
--- a/utils.go
+++ b/utils.go
@@ -281,7 +281,7 @@ func createPidFile(path string, process *libcontainer.Process) error {
tmpDir = filepath.Dir(path)
tmpName = filepath.Join(tmpDir, fmt.Sprintf(".%s", filepath.Base(path)))
)
- f, err := os.OpenFile(tmpName, os.O_RDWR|os.O_CREATE|os.O_EXCL, 0666)
+ f, err := os.OpenFile(tmpName, os.O_RDWR|os.O_CREATE|os.O_EXCL|os.O_SYNC, 0666)
if err != nil {
return err
}
|
Sync on the pid file to ensure the write is persisted
|
opencontainers_runc
|
train
|
6d9d9a1c29d7e0f91a3c772cdc10cdb7380f6c92
|
diff --git a/public_header.go b/public_header.go
index <HASH>..<HASH> 100644
--- a/public_header.go
+++ b/public_header.go
@@ -35,7 +35,7 @@ func (h *PublicHeader) WritePublicHeader(b *bytes.Buffer) error {
b.WriteByte(publicFlagByte)
utils.WriteUint64(b, uint64(h.ConnectionID)) // TODO: Send shorter connection id if possible
- utils.WriteUint32(b, uint32(h.PacketNumber)) // TODO: Send shorter packet number if possible
+ utils.WriteUint48(b, uint64(h.PacketNumber)) // TODO: Send shorter packet number if possible
return nil
}
diff --git a/public_header_test.go b/public_header_test.go
index <HASH>..<HASH> 100644
--- a/public_header_test.go
+++ b/public_header_test.go
@@ -79,7 +79,7 @@ var _ = Describe("Public Header", func() {
PacketNumber: 2,
}
publicHeader.WritePublicHeader(b)
- Expect(b.Bytes()).To(Equal([]byte{0x2c, 0xf6, 0x19, 0x86, 0x66, 0x9b, 0x9f, 0xfa, 0x4c, 2, 0, 0, 0}))
+ Expect(b.Bytes()).To(Equal([]byte{0x2c, 0xf6, 0x19, 0x86, 0x66, 0x9b, 0x9f, 0xfa, 0x4c, 2, 0, 0, 0, 0, 0}))
})
It("sets the Version Flag", func() {
|
send packet numbers with 6byte for simpler session tests
|
lucas-clemente_quic-go
|
train
|
320182f7349d2a6b41f5d3d6869a72ebcb3c5156
|
diff --git a/header.go b/header.go
index <HASH>..<HASH> 100644
--- a/header.go
+++ b/header.go
@@ -1011,6 +1011,9 @@ func (h *ResponseHeader) tryRead(r *bufio.Reader, n int) error {
if n == 1 || err == io.EOF {
return io.EOF
}
+ if err == bufio.ErrBufferFull {
+ err = bufferFullError(r)
+ }
return fmt.Errorf("error when reading response headers: %s", err)
}
isEOF := (err != nil)
@@ -1060,6 +1063,9 @@ func (h *RequestHeader) tryRead(r *bufio.Reader, n int) error {
if n == 1 || err == io.EOF {
return io.EOF
}
+ if err == bufio.ErrBufferFull {
+ err = bufferFullError(r)
+ }
return fmt.Errorf("error when reading request headers: %s", err)
}
isEOF := (err != nil)
@@ -1083,6 +1089,15 @@ func (h *RequestHeader) tryRead(r *bufio.Reader, n int) error {
return nil
}
+func bufferFullError(r *bufio.Reader) error {
+ n := r.Buffered()
+ b, err := r.Peek(n)
+ if err != nil {
+ panic(fmt.Sprintf("BUG: unexpected error returned from bufio.Reader.Peek(Buffered()): %s", err))
+ }
+ return fmt.Errorf("headers exceed %d bytes. Increase ReadBufferSize. buf=%q", n, b)
+}
+
func isOnlyCRLF(b []byte) bool {
for _, ch := range b {
if ch != '\r' && ch != '\n' {
|
Return more clear error message when headers don't fit read buffer size
|
valyala_fasthttp
|
train
|
1dd8f73d4a16be177840b1cc147c1423bec5f79e
|
diff --git a/internal/support/notifications/controller/http/subscription.go b/internal/support/notifications/controller/http/subscription.go
index <HASH>..<HASH> 100644
--- a/internal/support/notifications/controller/http/subscription.go
+++ b/internal/support/notifications/controller/http/subscription.go
@@ -82,7 +82,7 @@ func (sc *SubscriptionController) AllSubscriptions(w http.ResponseWriter, r *htt
config := notificationContainer.ConfigurationFrom(sc.dic.Get)
// parse URL query string for offset and limit
- offset, limit, _, err := utils.ParseGetAllObjectsRequestQueryString(r, 0, math.MaxUint32, -1, config.Service.MaxResultCount)
+ offset, limit, _, err := utils.ParseGetAllObjectsRequestQueryString(r, 0, math.MaxInt32, -1, config.Service.MaxResultCount)
if err != nil {
utils.WriteErrorResponse(w, ctx, lc, err, "")
return
diff --git a/internal/support/notifications/controller/http/transmission.go b/internal/support/notifications/controller/http/transmission.go
index <HASH>..<HASH> 100644
--- a/internal/support/notifications/controller/http/transmission.go
+++ b/internal/support/notifications/controller/http/transmission.go
@@ -85,7 +85,7 @@ func (tc *TransmissionController) AllTransmissions(w http.ResponseWriter, r *htt
config := notificationContainer.ConfigurationFrom(tc.dic.Get)
// parse URL query string for offset and limit
- offset, limit, _, err := utils.ParseGetAllObjectsRequestQueryString(r, 0, math.MaxUint32, -1, config.Service.MaxResultCount)
+ offset, limit, _, err := utils.ParseGetAllObjectsRequestQueryString(r, 0, math.MaxInt32, -1, config.Service.MaxResultCount)
if err != nil {
utils.WriteErrorResponse(w, ctx, lc, err, "")
return
|
fix(notifications): Remove warning from <I>-bit build.
Building the core services on <I>-bit ARM, I got a warning "Constant
<I> is bigger than 'int'", which stopped the build (my environment
may be too pedantic). This resolves it.
|
edgexfoundry_edgex-go
|
train
|
9f6eecb08077392dd0e14105a9aa76c338ea93b8
|
diff --git a/src/components/sidenav/sidenav.js b/src/components/sidenav/sidenav.js
index <HASH>..<HASH> 100644
--- a/src/components/sidenav/sidenav.js
+++ b/src/components/sidenav/sidenav.js
@@ -256,6 +256,7 @@ function SidenavDirective($mdMedia, $mdUtil, $mdConstant, $mdTheming, $animate,
var lastParentOverFlow;
var backdrop;
var triggeringElement = null;
+ var previousContainerStyles;
var promise = $q.when(true);
var isLockedOpenParsed = $parse(attr.mdIsLockedOpen);
var isLocked = function() {
@@ -324,6 +325,8 @@ function SidenavDirective($mdMedia, $mdUtil, $mdConstant, $mdTheming, $animate,
parent[isOpen ? 'on' : 'off']('keydown', onKeyDown);
if (backdrop) backdrop[isOpen ? 'on' : 'off']('click', close);
+ var restorePositioning = updateContainerPositions(parent, isOpen);
+
if ( isOpen ) {
// Capture upon opening..
triggeringElement = $document[0].activeElement;
@@ -332,16 +335,60 @@ function SidenavDirective($mdMedia, $mdUtil, $mdConstant, $mdTheming, $animate,
disableParentScroll(isOpen);
return promise = $q.all([
- isOpen && backdrop ? $animate.enter(backdrop, parent) :
- backdrop ? $animate.leave(backdrop) : $q.when(true),
- $animate[isOpen ? 'removeClass' : 'addClass'](element, '_md-closed')
- ])
- .then(function() {
- // Perform focus when animations are ALL done...
- if (scope.isOpen) {
- focusEl && focusEl.focus();
- }
- });
+ isOpen && backdrop ? $animate.enter(backdrop, parent) : backdrop ?
+ $animate.leave(backdrop) : $q.when(true),
+ $animate[isOpen ? 'removeClass' : 'addClass'](element, '_md-closed')
+ ]).then(function() {
+ // Perform focus when animations are ALL done...
+ if (scope.isOpen) {
+ focusEl && focusEl.focus();
+ }
+
+ // Restores the positioning on the sidenav and backdrop.
+ restorePositioning && restorePositioning();
+ });
+ }
+
+ function updateContainerPositions(parent, willOpen) {
+ var drawerEl = element[0];
+ var scrollTop = parent[0].scrollTop;
+
+ if (willOpen && scrollTop) {
+ previousContainerStyles = {
+ top: drawerEl.style.top,
+ bottom: drawerEl.style.bottom,
+ height: drawerEl.style.height
+ };
+
+ // When the parent is scrolled down, then we want to be able to show the sidenav at the current scroll
+ // position. We're moving the sidenav down to the correct scroll position and apply the height of the
+ // parent, to increase the performance. Using 100% as height, will impact the performance heavily.
+ var positionStyle = {
+ top: scrollTop + 'px',
+ bottom: 'initial',
+ height: parent[0].clientHeight + 'px'
+ };
+
+ // Apply the new position styles to the sidenav and backdrop.
+ element.css(positionStyle);
+ backdrop.css(positionStyle);
+ }
+
+ // When the sidenav is closing and we have previous defined container styles,
+ // then we return a restore function, which resets the sidenav and backdrop.
+ if (!willOpen && previousContainerStyles) {
+ return function() {
+ drawerEl.style.top = previousContainerStyles.top;
+ drawerEl.style.bottom = previousContainerStyles.bottom;
+ drawerEl.style.height = previousContainerStyles.height;
+
+ backdrop[0].style.top = null;
+ backdrop[0].style.bottom = null;
+ backdrop[0].style.height = null;
+
+ previousContainerStyles = null;
+ }
+ }
}
/**
|
fix(sidenav): update position of sidenav and backdrop if scrolled.
Currently the sidenav is not animating when the parent is scrolled, this
was caused by the absolute position.
This commit, updates the position of the sidenav and backdrop when the
parent is scrolled.
It sets the position to the current scroll position and sets the height to
the parents `clientHeight`. Using a `<I>%` height, will impact the
performance heavily.
Fixes #<I>.
Closes #<I>
|
angular_material
|
train
|
fa98e2ec379a98ab51e1480e8c1ced3375547b5b
|
diff --git a/app/controllers/admin/feedback_controller.rb b/app/controllers/admin/feedback_controller.rb
index <HASH>..<HASH> 100644
--- a/app/controllers/admin/feedback_controller.rb
+++ b/app/controllers/admin/feedback_controller.rb
@@ -142,7 +142,7 @@ class Admin::FeedbackController < Admin::BaseController
def delete_all_spam
if request.post?
- Feedback.delete_all('state in ("presumed_spam", "spam")')
+ Feedback.delete_all(['state in (?,?)', "presumed_spam", "spam"])
flash[:notice] = _("All spam have been deleted")
end
end
diff --git a/spec/controllers/admin/feedback_controller_spec.rb b/spec/controllers/admin/feedback_controller_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/controllers/admin/feedback_controller_spec.rb
+++ b/spec/controllers/admin/feedback_controller_spec.rb
@@ -292,6 +292,18 @@ describe Admin::FeedbackController do
end
end
+
+ describe '#bulkops action' do
+
+ before :each do
+ post :bulkops, :bulkop => 'Delete all spam'
+ end
+
+ it 'should redirect to action' do
+ @response.should redirect_to(:action => 'index')
+ end
+ end
+
end
end
|
fix bug #<I> which not delete all spam with postgresql database
|
publify_publify
|
train
|
0a076bdcbcef156fc1265f799419255440a3f3e7
|
diff --git a/howler.js b/howler.js
index <HASH>..<HASH> 100644
--- a/howler.js
+++ b/howler.js
@@ -903,6 +903,10 @@
// find first inactive node to recycle
for (var i=0; i<self._audioNode.length; i++) {
if (self._audioNode[i].paused && self._audioNode[i].readyState === 4) {
+ // before using this node, reset its pos
+ self._audioNode[i]._pos = 0;
+
+ // send the node back for use by the new play instance
callback(self._audioNode[i]);
node = true;
break;
|
Reset inactive node's position before using it for new playback
|
goldfire_howler.js
|
train
|
574cc3fba34f80ab25286220d03319207032813e
|
diff --git a/lib/xcres/builder/resources_builder.rb b/lib/xcres/builder/resources_builder.rb
index <HASH>..<HASH> 100644
--- a/lib/xcres/builder/resources_builder.rb
+++ b/lib/xcres/builder/resources_builder.rb
@@ -188,12 +188,10 @@ EOS
def build_swift_contents swift_file
swift_file.writeln BANNER
- swift_file.writeln
- swift_file.writeln
swift_file.writeln 'public enum %s {' % resources_constant_name
swift_file.section do |struct|
enumerate_sections do |section_key, enumerate_keys|
- struct.writeln 'public enum %s : String {' % section_key
+ struct.writeln 'public enum %s: String {' % section_key
struct.section do |section_struct|
enumerate_keys.call do |key, value, comment|
if documented?
|
Improve formatting of generated Swift file
* Remove two of three empty lines at the top of the document
* Remove space before colon in enum declarations
I personally like this style better. Github seems to agree:
<URL>
|
xcres_xcres
|
train
|
1ff55d16275a9bd6f1efcf224ed853abead89aec
|
diff --git a/asv/environment.py b/asv/environment.py
index <HASH>..<HASH> 100644
--- a/asv/environment.py
+++ b/asv/environment.py
@@ -327,14 +327,11 @@ def get_environments(conf, env_specifiers, verbose=True):
# Ignore requirement matrix
requirements_iter = [dict(python=python) for python in pythons]
- env_matrix_combinations = iter_env_matrix_combinations(conf.env_matrix)
-
- if not env_matrix_combinations:
- env_matrix_combinations = [{}]
-
for requirements in requirements_iter:
python = requirements.pop('python')
+ env_matrix_combinations = iter_env_matrix_combinations(conf.env_matrix)
+
for combination in env_matrix_combinations:
try:
if env_type:
|
Fix initialization of an iterator
|
airspeed-velocity_asv
|
train
|
758b784d1a103b1f2d2e97e4b2431bd61f5dbb3a
|
diff --git a/molgenis-data-migrate/src/test/java/org/molgenis/data/version/MetaDataVersionServiceTest.java b/molgenis-data-migrate/src/test/java/org/molgenis/data/version/MetaDataVersionServiceTest.java
index <HASH>..<HASH> 100644
--- a/molgenis-data-migrate/src/test/java/org/molgenis/data/version/MetaDataVersionServiceTest.java
+++ b/molgenis-data-migrate/src/test/java/org/molgenis/data/version/MetaDataVersionServiceTest.java
@@ -1,39 +1,64 @@
package org.molgenis.data.version;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertNotNull;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
+import java.sql.Connection;
+import java.sql.ResultSet;
+import java.sql.SQLException;
import javax.sql.DataSource;
import org.apache.commons.io.FileUtils;
-import org.mockito.Mockito;
import org.springframework.util.FileCopyUtils;
+import org.testng.Assert;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import com.google.common.io.Files;
+import com.mysql.jdbc.DatabaseMetaData;
public class MetaDataVersionServiceTest
{
private MetaDataVersionService metaDataVersionService;
private File molgenisHomeFolder;
private File propertiesFile;
- private DataSource dataSource;
+ private ResultSet molgenisUserTableResultSet;
@BeforeMethod
- public void beforeMethod() throws IOException
+ public void beforeMethod() throws IOException, SQLException
{
molgenisHomeFolder = Files.createTempDir();
System.setProperty("molgenis.home", molgenisHomeFolder.getAbsolutePath());
propertiesFile = new File(molgenisHomeFolder, "molgenis-server.properties");
propertiesFile.createNewFile();
- dataSource = Mockito.mock(DataSource.class);
- metaDataVersionService = new MetaDataVersionService(dataSource);
+ }
+
+ private void createMetaDataVersion(boolean withMolgenisUserTable)
+ {
+ try
+ {
+ DataSource dataSource = mock(DataSource.class);
+ Connection connection = mock(Connection.class);
+ when(dataSource.getConnection()).thenReturn(connection);
+ DatabaseMetaData dbMeta = mock(DatabaseMetaData.class);
+ when(connection.getMetaData()).thenReturn(dbMeta);
+ molgenisUserTableResultSet = mock(ResultSet.class);
+ when(dbMeta.getTables(null, null, "MolgenisUser", new String[]
+ { "TABLE" })).thenReturn(molgenisUserTableResultSet);
+ when(molgenisUserTableResultSet.first()).thenReturn(withMolgenisUserTable);
+ metaDataVersionService = new MetaDataVersionService(dataSource);
+ }
+ catch (SQLException e)
+ {
+ Assert.fail("Shouldn't happen.", e);
+ }
}
@AfterMethod
@@ -43,21 +68,31 @@ public class MetaDataVersionServiceTest
}
@Test
- public void getDatabaseMetaDataVersion()
+ public void getDatabaseMetaDataVersionNoMolgenisUserTable() throws SQLException
{
+ createMetaDataVersion(false);
assertEquals(metaDataVersionService.getDatabaseMetaDataVersion(),
MetaDataVersionService.CURRENT_META_DATA_VERSION);
}
@Test
+ public void getDatabaseMetaDataVersionMolgenisUserTablePresent() throws SQLException
+ {
+ createMetaDataVersion(true);
+ assertEquals(metaDataVersionService.getDatabaseMetaDataVersion(), 0);
+ }
+
+ @Test
public void getMolgenisServerProperties()
{
+ createMetaDataVersion(false);
assertNotNull(metaDataVersionService.getMolgenisServerProperties());
}
@Test
public void updateToCurrentVersion() throws IOException
{
+ createMetaDataVersion(false);
FileCopyUtils.copy("meta.data.version=0", new FileWriter(propertiesFile));
assertEquals(metaDataVersionService.getDatabaseMetaDataVersion(), 0);
|
Add test to MetaDataVersionService for the install-or-upgrade determination.
|
molgenis_molgenis
|
train
|
24327c11a52a01d3562eb78a0d4d99533decf543
|
diff --git a/server/sonar-server-common/src/main/java/org/sonar/server/es/newindex/FieldAware.java b/server/sonar-server-common/src/main/java/org/sonar/server/es/newindex/FieldAware.java
index <HASH>..<HASH> 100644
--- a/server/sonar-server-common/src/main/java/org/sonar/server/es/newindex/FieldAware.java
+++ b/server/sonar-server-common/src/main/java/org/sonar/server/es/newindex/FieldAware.java
@@ -43,17 +43,17 @@ public abstract class FieldAware<U extends FieldAware<U>> {
@SuppressWarnings("unchecked")
public KeywordFieldBuilder<U> keywordFieldBuilder(String fieldName) {
- return (KeywordFieldBuilder<U>) new KeywordFieldBuilder(this, fieldName);
+ return new KeywordFieldBuilder(this, fieldName);
}
@SuppressWarnings("unchecked")
public TextFieldBuilder<U> textFieldBuilder(String fieldName) {
- return (TextFieldBuilder<U>) new TextFieldBuilder(this, fieldName);
+ return new TextFieldBuilder(this, fieldName);
}
@SuppressWarnings("unchecked")
public NestedFieldBuilder<U> nestedFieldBuilder(String fieldName) {
- return (NestedFieldBuilder<U>) new NestedFieldBuilder(this, fieldName);
+ return new NestedFieldBuilder(this, fieldName);
}
public U createBooleanField(String fieldName) {
diff --git a/sonar-duplications/src/main/java/org/sonar/duplications/block/ByteArray.java b/sonar-duplications/src/main/java/org/sonar/duplications/block/ByteArray.java
index <HASH>..<HASH> 100644
--- a/sonar-duplications/src/main/java/org/sonar/duplications/block/ByteArray.java
+++ b/sonar-duplications/src/main/java/org/sonar/duplications/block/ByteArray.java
@@ -19,7 +19,6 @@
*/
package org.sonar.duplications.block;
-import java.nio.Buffer;
import java.nio.ByteBuffer;
import java.nio.IntBuffer;
import java.util.Arrays;
@@ -97,7 +96,7 @@ public final class ByteArray {
//This is because the generated byte code includes the static return type of the method, which is not found on Java 8 and lower because
//the overloaded methods with covariant return types don't exist.
- ((Buffer) bb).rewind();
+ bb.rewind();
IntBuffer ib = bb.asIntBuffer();
int[] result = new int[size];
ib.get(result);
diff --git a/sonar-plugin-api/src/main/java/org/sonar/api/utils/ZipUtils.java b/sonar-plugin-api/src/main/java/org/sonar/api/utils/ZipUtils.java
index <HASH>..<HASH> 100644
--- a/sonar-plugin-api/src/main/java/org/sonar/api/utils/ZipUtils.java
+++ b/sonar-plugin-api/src/main/java/org/sonar/api/utils/ZipUtils.java
@@ -56,11 +56,11 @@ public final class ZipUtils {
* @return the target directory
*/
public static File unzip(File zip, File toDir) throws IOException {
- return unzip(zip, toDir, (Predicate<ZipEntry>) ze -> true);
+ return unzip(zip, toDir, ze -> true);
}
public static File unzip(InputStream zip, File toDir) throws IOException {
- return unzip(zip, toDir, (Predicate<ZipEntry>) ze -> true);
+ return unzip(zip, toDir, ze -> true);
}
/**
|
Code smell fix: Remove redundant casts
|
SonarSource_sonarqube
|
train
|
34f5d9d5b16554b50a45b266d39780e5ffdb2612
|
diff --git a/client/src/view-helper.js b/client/src/view-helper.js
index <HASH>..<HASH> 100644
--- a/client/src/view-helper.js
+++ b/client/src/view-helper.js
@@ -564,7 +564,7 @@ define('view-helper', ['lib!marked', 'lib!dompurify'], function (marked, DOMPuri
if (result && Object.prototype.toString.call(result) === '[object Promise]') {
result.then(function () {
- resove();
+ resolve();
});
return;
|
fix process setup handlers (#<I>)
|
espocrm_espocrm
|
train
|
030c29ec11828a23a403caae3aad9ea793af6595
|
diff --git a/gradle.properties b/gradle.properties
index <HASH>..<HASH> 100644
--- a/gradle.properties
+++ b/gradle.properties
@@ -17,7 +17,7 @@ checkstyleToolVersion=8.2
bookKeeperVersion=4.7.3
commonsioVersion=2.6
commonsLang3Version=3.7
-dockerClientVersion=8.11.7
+dockerClientVersion=8.15.1
ecsObjectClientVersion=3.1.3
spotbugsVersion=3.1.11
spotbugsAnnotationsVersion=3.1.11
diff --git a/test/system/preTestScript.sh b/test/system/preTestScript.sh
index <HASH>..<HASH> 100755
--- a/test/system/preTestScript.sh
+++ b/test/system/preTestScript.sh
@@ -17,7 +17,7 @@ echo "Master IP of jarvis cluster is $MASTER"
NUM_SLAVES=${3:-null}
DOCKER_VERSION=`docker version --format '{{.Server.APIVersion}}'`
echo "Docker API version is $DOCKER_VERSION"
-DOCKER_API_MIN_VERSION=1.22
+DOCKER_API_MIN_VERSION=1.37
st=`echo "${DOCKER_VERSION} < ${DOCKER_API_MIN_VERSION}" | bc`
if [ 1 -eq $st ];
then
diff --git a/test/system/src/main/java/io/pravega/test/system/framework/services/docker/BookkeeperDockerService.java b/test/system/src/main/java/io/pravega/test/system/framework/services/docker/BookkeeperDockerService.java
index <HASH>..<HASH> 100644
--- a/test/system/src/main/java/io/pravega/test/system/framework/services/docker/BookkeeperDockerService.java
+++ b/test/system/src/main/java/io/pravega/test/system/framework/services/docker/BookkeeperDockerService.java
@@ -30,6 +30,7 @@ import java.util.Map;
import lombok.extern.slf4j.Slf4j;
import static io.pravega.test.system.framework.Utils.DOCKER_NETWORK;
+import static com.spotify.docker.client.messages.swarm.RestartPolicy.RESTART_POLICY_ANY;
@Slf4j
public class BookkeeperDockerService extends DockerBasedService {
@@ -81,7 +82,7 @@ public class BookkeeperDockerService extends DockerBasedService {
stringList.add(env4);
final TaskSpec taskSpec = TaskSpec
- .builder().restartPolicy(RestartPolicy.builder().maxAttempts(0).condition("none").build())
+ .builder().restartPolicy(RestartPolicy.builder().maxAttempts(1).condition(RESTART_POLICY_ANY).build())
.containerSpec(ContainerSpec.builder()
.hostname(serviceName)
.labels(labels)
diff --git a/test/system/src/main/java/io/pravega/test/system/framework/services/docker/DockerBasedService.java b/test/system/src/main/java/io/pravega/test/system/framework/services/docker/DockerBasedService.java
index <HASH>..<HASH> 100644
--- a/test/system/src/main/java/io/pravega/test/system/framework/services/docker/DockerBasedService.java
+++ b/test/system/src/main/java/io/pravega/test/system/framework/services/docker/DockerBasedService.java
@@ -160,7 +160,7 @@ public abstract class DockerBasedService implements io.pravega.test.system.frame
String serviceId = Exceptions.handleInterruptedCall(() -> dockerClient.listServices(criteria).get(0).id());
EndpointSpec endpointSpec = Exceptions.handleInterruptedCall(() -> dockerClient.inspectService(serviceId).spec().endpointSpec());
Service service = Exceptions.handleInterruptedCall(() -> dockerClient.inspectService(serviceId));
- Exceptions.handleInterrupted(() -> dockerClient.updateService(serviceId, service.version().index(), ServiceSpec.builder().endpointSpec(endpointSpec).mode(ServiceMode.withReplicas(instanceCount)).taskTemplate(taskSpec).name(serviceName).build()));
+ Exceptions.handleInterrupted(() -> dockerClient.updateService(serviceId, service.version().index(), ServiceSpec.builder().endpointSpec(endpointSpec).mode(ServiceMode.withReplicas(instanceCount)).taskTemplate(taskSpec).name(serviceName).networks(service.spec().networks()).build()));
return Exceptions.handleInterruptedCall(() -> waitUntilServiceRunning());
} catch (DockerException e) {
@@ -196,7 +196,7 @@ public abstract class DockerBasedService implements io.pravega.test.system.frame
// Default Health Check which uses netstat command to ensure the service is up and running.
List<String> defaultHealthCheck(int port) {
- return customHealthCheck("netstat -plnt | grep " + port + " || exit 1");
+ return customHealthCheck("netstat -ltn 2> /dev/null | grep " + port + " || ss -ltn 2> /dev/null | grep " + port + " || exit 1");
}
//Custom Health check with the command provided by the service.
diff --git a/test/system/src/main/java/io/pravega/test/system/framework/services/docker/PravegaSegmentStoreDockerService.java b/test/system/src/main/java/io/pravega/test/system/framework/services/docker/PravegaSegmentStoreDockerService.java
index <HASH>..<HASH> 100644
--- a/test/system/src/main/java/io/pravega/test/system/framework/services/docker/PravegaSegmentStoreDockerService.java
+++ b/test/system/src/main/java/io/pravega/test/system/framework/services/docker/PravegaSegmentStoreDockerService.java
@@ -91,7 +91,7 @@ public class PravegaSegmentStoreDockerService extends DockerBasedService {
//set env
String env1 = "PRAVEGA_SEGMENTSTORE_OPTS=" + hostSystemProperties;
- String env2 = "JAVA_OPTS=-Xmx900m";
+ String env2 = "JAVA_OPTS=-Xmx2000m";
List<String> envList = new ArrayList<>();
envList.add(env1);
envList.add(env2);
|
Issue <I>: Change bookies health check command (#<I>)
* Changes docker client version to <I>
* Increases segment store memory to <I>m
* Updates service spec in docker client update service() to pass networks.
* Updates DOCKER_API_MIN_VERSION to <I>
* Changes the default health check command of bookie
* Increases the max restart attempts to 1 and changes the restart policy
|
pravega_pravega
|
train
|
2a89f924211092bb69f69798c189c031d56936f1
|
diff --git a/liquibase-core/src/main/java/liquibase/changelog/ChangeSet.java b/liquibase-core/src/main/java/liquibase/changelog/ChangeSet.java
index <HASH>..<HASH> 100644
--- a/liquibase-core/src/main/java/liquibase/changelog/ChangeSet.java
+++ b/liquibase-core/src/main/java/liquibase/changelog/ChangeSet.java
@@ -186,6 +186,8 @@ public class ChangeSet implements Conditional, ChangeLogChild {
*/
private String runOrder;
+ private Map<String, Object> attributes = new HashMap<String, Object>();
+
public boolean shouldAlwaysRun() {
return alwaysRun;
}
@@ -377,7 +379,12 @@ public class ChangeSet implements Conditional, ChangeLogChild {
handleChildNode(changeNode, resourceAccessor);
}
} else {
- addChange(toChange(child, resourceAccessor));
+ Change change = toChange(child, resourceAccessor);
+ if (change == null && child.getValue() instanceof String) {
+ this.setAttribute(child.getName(), child.getValue());
+ } else {
+ addChange(change);
+ }
}
}
@@ -1116,4 +1123,14 @@ public class ChangeSet implements Conditional, ChangeLogChild {
public int hashCode() {
return toString(false).hashCode();
}
+
+ public Object getAttribute(String attribute) {
+ return attributes.get(attribute);
+ }
+
+ public ChangeSet setAttribute(String attribute, Object value) {
+ this.attributes.put(attribute, value);
+
+ return this;
+ }
}
diff --git a/liquibase-core/src/main/java/liquibase/command/core/DiffCommand.java b/liquibase-core/src/main/java/liquibase/command/core/DiffCommand.java
index <HASH>..<HASH> 100644
--- a/liquibase-core/src/main/java/liquibase/command/core/DiffCommand.java
+++ b/liquibase-core/src/main/java/liquibase/command/core/DiffCommand.java
@@ -19,7 +19,7 @@ import liquibase.util.StringUtils;
import java.io.PrintStream;
import java.util.Set;
-public class DiffCommand extends AbstractCommand {
+public class DiffCommand extends AbstractCommand<CommandResult> {
private Database referenceDatabase;
private Database targetDatabase;
diff --git a/liquibase-core/src/main/java/liquibase/command/core/DiffToChangeLogCommand.java b/liquibase-core/src/main/java/liquibase/command/core/DiffToChangeLogCommand.java
index <HASH>..<HASH> 100644
--- a/liquibase-core/src/main/java/liquibase/command/core/DiffToChangeLogCommand.java
+++ b/liquibase-core/src/main/java/liquibase/command/core/DiffToChangeLogCommand.java
@@ -56,10 +56,14 @@ public class DiffToChangeLogCommand extends DiffCommand {
}
if (StringUtils.trimToNull(changeLogFile) == null) {
- new DiffToChangeLog(diffResult, diffOutputControl).print(outputStream);
+ createDiffToChangeLogObject(diffResult).print(outputStream);
} else {
- new DiffToChangeLog(diffResult, diffOutputControl).print(changeLogFile);
+ createDiffToChangeLogObject(diffResult).print(changeLogFile);
}
return new CommandResult("OK");
}
+
+ protected DiffToChangeLog createDiffToChangeLogObject(DiffResult diffResult) {
+ return new DiffToChangeLog(diffResult, diffOutputControl);
+ }
}
|
Improve extensibility of changeSet object
|
liquibase_liquibase
|
train
|
94a8062b93d60f4fb08714403761c4323c85a18a
|
diff --git a/guava-testlib/src/com/google/common/testing/ClassSanityTester.java b/guava-testlib/src/com/google/common/testing/ClassSanityTester.java
index <HASH>..<HASH> 100644
--- a/guava-testlib/src/com/google/common/testing/ClassSanityTester.java
+++ b/guava-testlib/src/com/google/common/testing/ClassSanityTester.java
@@ -124,7 +124,7 @@ public final class ClassSanityTester {
/**
* Sets the default value for {@code type}. The default value isn't used in testing {@link
* Object#equals} because more than one sample instances are needed for testing inequality.
- * To set sample instances for equality testing, use {@link #setSampleInstances} instead.
+ * To set distinct values for equality testing, use {@link #setDistinctValues} instead.
*/
public <T> ClassSanityTester setDefault(Class<T> type, T value) {
nullPointerTester.setDefault(type, value);
@@ -143,11 +143,13 @@ public final class ClassSanityTester {
* non-null sample is sufficient. Setting an empty list will clear sample instances for {@code
* type}.
*
- * @deprecated Use {@link #setDistinctValues} instead. This method will be removed in Guava
- * release 20.0.
+ * @deprecated To supply multiple values, use {@link #setDistinctValues}. It accepts only two
+ * values, which is enough for any {@code equals} testing. To supply a single value, use
+ * {@link #setDefault}. This method will be removed in Guava release 20.0.
*/
@Deprecated
- public <T> ClassSanityTester setSampleInstances(Class<T> type, Iterable<? extends T> instances) {
+ public <T> ClassSanityTester setSampleInstances(
+ Class<T> type, Iterable<? extends T> instances) {
ImmutableList<? extends T> samples = ImmutableList.copyOf(instances);
Set<Object> uniqueValues = new HashSet<Object>();
for (T instance : instances) {
@@ -299,7 +301,7 @@ public final class ClassSanityTester {
throw Throwables.propagate(e);
}
}
-
+
void doTestEquals(Class<?> cls)
throws ParameterNotInstantiableException, ParameterHasNoDistinctValueException,
IllegalAccessException, InvocationTargetException, FactoryMethodReturnsNullException {
@@ -820,4 +822,3 @@ public final class ClassSanityTester {
}
}
}
-
|
Hide setSampleInstances internally.
-------------
Created by MOE: <URL>
|
google_guava
|
train
|
a84edc25dcc0abd06151b40582702693b603a3a6
|
diff --git a/app/models/effective/active_record_datatable_tool.rb b/app/models/effective/active_record_datatable_tool.rb
index <HASH>..<HASH> 100644
--- a/app/models/effective/active_record_datatable_tool.rb
+++ b/app/models/effective/active_record_datatable_tool.rb
@@ -72,19 +72,33 @@ module Effective
collection
end
when :has_many
- inverse_ids = term.split(',').map { |term| (term = term.to_i) == 0 ? nil : term }.compact
- return collection unless inverse_ids.present?
-
reflection = collection.klass.reflect_on_association(table_column[:name].to_sym)
raise "unable to find #{collection.klass.name} :has_many :#{table_column[:name]} association" unless reflection
- obj = reflection.build_association({}) # Clinic
+ obj = reflection.build_association({})
klass = obj.class
inverse = reflection.inverse_of || klass.reflect_on_association(collection.table_name) || obj.class.reflect_on_association(collection.table_name.singularize)
raise "unable to find #{klass.name} has_many :#{collection.table_name} or belongs_to :#{collection.table_name.singularize} associations" unless inverse
- ids = klass.where(id: inverse_ids).joins(inverse.name).pluck(inverse.foreign_key)
+ ids = if [:select, :grouped_select].include?(table_column[:filter][:type])
+ # Treat the search term as one or more IDs
+ inverse_ids = term.split(',').map { |term| (term = term.to_i) == 0 ? nil : term }.compact
+ return collection unless inverse_ids.present?
+
+ klass.where(id: inverse_ids).joins(inverse.name).pluck(inverse.foreign_key)
+ else
+ # Treat the search term as a string.
+ klass_columns = if (table_column[:column] == klass.table_name) # No custom column has been defined
+ klass.columns.map { |col| col.name if col.text? }.compact # Search all database text? columns
+ else
+ [table_column[:column].gsub("#{klass.table_name}.", '')] # table_column :order_items, column: 'order_items.title'
+ end
+
+ conditions = klass_columns.map { |col_name| "#{klass.table_name}.#{col_name} #{ilike} :term" }
+
+ klass.where(conditions.join(' OR '), term: "%#{term}%", num: term.to_i).joins(inverse.name).pluck(inverse.foreign_key)
+ end
collection.public_send(sql_op, id: ids)
when :obfuscated_id
|
automatically filter has_many with string column filters
|
code-and-effect_effective_datatables
|
train
|
216fa306eec8d561993a26a08a669717a7755701
|
diff --git a/br/pkg/utils/backoff.go b/br/pkg/utils/backoff.go
index <HASH>..<HASH> 100644
--- a/br/pkg/utils/backoff.go
+++ b/br/pkg/utils/backoff.go
@@ -3,6 +3,9 @@
package utils
import (
+ "context"
+ "database/sql"
+ "io"
"time"
"github.com/pingcap/errors"
@@ -102,8 +105,27 @@ func NewPDReqBackoffer() Backoffer {
}
func (bo *pdReqBackoffer) NextBackoff(err error) time.Duration {
- bo.delayTime = 2 * bo.delayTime
- bo.attempt--
+ // bo.delayTime = 2 * bo.delayTime
+ // bo.attempt--
+ e := errors.Cause(err)
+ switch e { // nolint:errorlint
+ case nil, context.Canceled, context.DeadlineExceeded, io.EOF, sql.ErrNoRows:
+ // Excepted error, finish the operation
+ bo.delayTime = 0
+ bo.attempt = 0
+ default:
+ switch status.Code(e) {
+ case codes.DeadlineExceeded, codes.NotFound, codes.AlreadyExists, codes.PermissionDenied, codes.ResourceExhausted, codes.Aborted, codes.OutOfRange, codes.Unavailable, codes.DataLoss, codes.Unknown:
+ bo.delayTime = 2 * bo.delayTime
+ bo.attempt--
+ default:
+ // Unexcepted error
+ bo.delayTime = 0
+ bo.attempt = 0
+ log.Warn("unexcepted error, stop to retry", zap.Error(err))
+ }
+ }
+
if bo.delayTime > bo.maxDelayTime {
return bo.maxDelayTime
}
diff --git a/br/pkg/utils/retry.go b/br/pkg/utils/retry.go
index <HASH>..<HASH> 100644
--- a/br/pkg/utils/retry.go
+++ b/br/pkg/utils/retry.go
@@ -58,11 +58,6 @@ func WithRetry(
err := retryableFunc()
if err != nil {
allErrors = multierr.Append(allErrors, err)
- retry := IsRetryableError(err)
- if !retry { // exited retry
- return allErrors
- }
-
select {
case <-ctx.Done():
return allErrors // nolint:wrapcheck
|
br: Retryable refactoring for PD back offer (#<I>)
|
pingcap_tidb
|
train
|
6cb3f3f2a488b5e4ed69811400a60a3da801c28e
|
diff --git a/spec/wirble_compatibility_spec.rb b/spec/wirble_compatibility_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/wirble_compatibility_spec.rb
+++ b/spec/wirble_compatibility_spec.rb
@@ -6,7 +6,7 @@ describe Looksee::WirbleCompatibility do
#
# Run the given ruby string, and return the standard output.
#
- def run_in_irb(code)
+ def init_irb_with(code)
code = <<-EOS.demargin.gsub(/\n/, ';')
|#{code}
|#{stubbing_code}
@@ -45,8 +45,8 @@ describe Looksee::WirbleCompatibility do
EOS
end
- it "should output lookup path info correctly if wirble is not loaded" do
- output = run_in_irb(<<-EOS.demargin)
+ it "should work if wirble is not loaded" do
+ output = init_irb_with(<<-EOS.demargin)
|require 'irb'
|require 'looksee/shortcuts'
|require 'wirble'
@@ -59,8 +59,8 @@ describe Looksee::WirbleCompatibility do
EOS
end
- it "should output lookup path info correctly if wirble is loaded, but not initialized" do
- output = run_in_irb(<<-EOS.demargin)
+ it "should work if wirble is loaded, but not initialized" do
+ output = init_irb_with(<<-EOS.demargin)
|require 'irb'
|require 'wirble'
|require 'looksee/shortcuts'
@@ -73,8 +73,8 @@ describe Looksee::WirbleCompatibility do
EOS
end
- it "should output lookup path info correctly if wirble is loaded and initialized, but colorizing is off" do
- output = run_in_irb(<<-EOS.demargin)
+ it "should work if wirble is loaded and initialized, but colorizing is off" do
+ output = init_irb_with(<<-EOS.demargin)
|require 'irb'
|require 'wirble'
|Wirble.init
@@ -87,8 +87,8 @@ describe Looksee::WirbleCompatibility do
EOS
end
- it "should output lookup path info correctly if wirble is loaded, initialized, and colorizing is on" do
- output = run_in_irb(<<-EOS.demargin)
+ it "should work if wirble is loaded, initialized, and colorizing is on" do
+ output = init_irb_with(<<-EOS.demargin)
|require 'irb'
|require 'wirble'
|Wirble.init
|
Renaming in tests to make intentions clearer.
|
oggy_looksee
|
train
|
720ffbf2c58f7adba48e31f84ecf367d43255cf8
|
diff --git a/tests/integration/modules/test_hosts.py b/tests/integration/modules/test_hosts.py
index <HASH>..<HASH> 100644
--- a/tests/integration/modules/test_hosts.py
+++ b/tests/integration/modules/test_hosts.py
@@ -1,8 +1,6 @@
-# -*- coding: utf-8 -*-
"""
Test the hosts module
"""
-from __future__ import absolute_import, print_function, unicode_literals
import logging
import os
|
Drop Py2 and six on tests/integration/modules/test_hosts.py
|
saltstack_salt
|
train
|
9a9a4c2db1a87178250eef363131f10f48503d44
|
diff --git a/lib/rescodegen.rb b/lib/rescodegen.rb
index <HASH>..<HASH> 100644
--- a/lib/rescodegen.rb
+++ b/lib/rescodegen.rb
@@ -1,6 +1,8 @@
#! /usr/bin/env ruby
require 'optparse'
require './lib/code_generator/swift_strings_generator'
+require './lib/code_generator/objc_header_strings_generator'
+require './lib/code_generator/objc_main_strings_generator'
require './lib/key_generator/strings_key_generator'
options = { output: ".", language: "swift" }
@@ -21,11 +23,21 @@ parser.parse!
abort "Invalid -l argument. Expects swift or objc." if !options[:language].match("swift|objc")
input_file = ARGV.last
abort "Missing input_file.\n\n#{parser.help}" if input_file.nil?
+output_file = options[:output] + "/Strings"
-output_file = options[:output] + "/Strings.swift"
+def generate_swift_file(code_safe_keys, keys, output_file)
+ File.write(output_file + ".swift", SwiftStringsGenerator.new.generate(code_safe_keys, keys))
+end
+
+def generate_objc_files(code_safe_keys, keys, output_file)
+ File.write(output_file + ".h", ObjcHeaderStringsGenerator.new.generate(code_safe_keys, keys))
+ File.write(output_file + ".m", ObjcMainStringsGenerator.new.generate(code_safe_keys, keys))
+end
generator = StringsKeyGenerator.new(File.readlines(input_file))
keys = generator.keys
code_safe_keys = generator.code_safe_keys
-File.write(output_file, SwiftStringsGenerator.new.generate(code_safe_keys, keys))
+generate_swift_file(code_safe_keys, keys, output_file) if options[:language] == "swift"
+generate_objc_files(code_safe_keys, keys, output_file) if options[:language] == "objc"
+
|
rescodegen now supports objc
|
seanhenry_rescodegen
|
train
|
bd954cd18bdd9e822cfb8505bc03601eb4dbba80
|
diff --git a/src/Charcoal/User/AbstractAuthenticator.php b/src/Charcoal/User/AbstractAuthenticator.php
index <HASH>..<HASH> 100644
--- a/src/Charcoal/User/AbstractAuthenticator.php
+++ b/src/Charcoal/User/AbstractAuthenticator.php
@@ -131,6 +131,16 @@ abstract class AbstractAuthenticator implements
}
/**
+ * Create a new user model.
+ *
+ * @return \Charcoal\User\Access\AuthenticatableInterface
+ */
+ public function createUser()
+ {
+ return $this->userFactory()->create($this->userType());
+ }
+
+ /**
* Retrieve the auth-token object type.
*
* @return string
@@ -152,9 +162,19 @@ abstract class AbstractAuthenticator implements
}
/**
+ * Create a new auth-token model.
+ *
+ * @return \Charcoal\User\AuthToken
+ */
+ public function createToken()
+ {
+ return $this->tokenFactory()->create($this->tokenType());
+ }
+
+ /**
* Set the user object type (model).
*
- * @param string $type The user object type.
+ * @param string $type The user object type.
* @throws InvalidArgumentException If the user object type parameter is not a string.
* @return void
*/
@@ -172,7 +192,7 @@ abstract class AbstractAuthenticator implements
/**
* Set a user model factory.
*
- * @param FactoryInterface $factory The factory used to create new user instances.
+ * @param FactoryInterface $factory The factory used to create new user instances.
* @return void
*/
protected function setUserFactory(FactoryInterface $factory)
@@ -183,7 +203,7 @@ abstract class AbstractAuthenticator implements
/**
* Set the authorization token type (model).
*
- * @param string $type The auth-token object type.
+ * @param string $type The auth-token object type.
* @throws InvalidArgumentException If the token object type parameter is not a string.
* @return void
*/
@@ -201,7 +221,7 @@ abstract class AbstractAuthenticator implements
/**
* Set a model factory for token-based authentication.
*
- * @param FactoryInterface $factory The factory used to create new auth-token instances.
+ * @param FactoryInterface $factory The factory used to create new auth-token instances.
* @return void
*/
protected function setTokenFactory(FactoryInterface $factory)
@@ -418,7 +438,7 @@ abstract class AbstractAuthenticator implements
);
}
- $user = $this->userFactory()->create($this->userType());
+ $user = $this->createUser();
if (!$user->source()->tableExists()) {
$user->source()->createTable();
}
@@ -465,7 +485,7 @@ abstract class AbstractAuthenticator implements
*/
protected function authenticateBySession()
{
- $user = $this->userFactory()->create($this->userType());
+ $user = $this->createUser();
$key = $user::sessionKey();
if (!isset($_SESSION[$key])) {
@@ -500,7 +520,7 @@ abstract class AbstractAuthenticator implements
*/
protected function authenticateByToken()
{
- $authToken = $this->tokenFactory()->create($this->tokenType());
+ $authToken = $this->createToken();
if (!$authToken->isEnabled()) {
return null;
@@ -516,7 +536,7 @@ abstract class AbstractAuthenticator implements
return null;
}
- $user = $this->userFactory()->create($this->userType());
+ $user = $this->createUser();
$user->load($userId);
// Allow model to validate user standing
@@ -559,7 +579,7 @@ abstract class AbstractAuthenticator implements
*/
protected function deleteUserTokens(AuthenticatableInterface $user = null)
{
- $authToken = $this->tokenFactory()->create($this->tokenType());
+ $authToken = $this->createToken();
if (!$authToken->isEnabled()) {
return;
}
@@ -637,7 +657,7 @@ abstract class AbstractAuthenticator implements
);
}
- $authToken = $this->tokenFactory()->create($this->tokenType());
+ $authToken = $this->createToken();
if (!$authToken->isEnabled()) {
return;
|
Add creation methods on Authenticator
Added:
- Methods `createUser()` and `createToken()` to quickly make instances outside the Authenticator
|
locomotivemtl_charcoal-user
|
train
|
baf257adcb1fe224e6f04b1de744052ad7bc81fe
|
diff --git a/cmd/bucket-targets.go b/cmd/bucket-targets.go
index <HASH>..<HASH> 100644
--- a/cmd/bucket-targets.go
+++ b/cmd/bucket-targets.go
@@ -24,7 +24,7 @@ import (
jsoniter "github.com/json-iterator/go"
"github.com/minio/madmin-go"
- minio "github.com/minio/minio-go/v7"
+ "github.com/minio/minio-go/v7"
miniogo "github.com/minio/minio-go/v7"
"github.com/minio/minio-go/v7/pkg/credentials"
"github.com/minio/minio/internal/bucket/replication"
@@ -272,17 +272,20 @@ func (sys *BucketTargetSys) UpdateAllTargets(bucket string, tgts *madmin.BucketT
}
sys.Lock()
defer sys.Unlock()
- if tgts == nil || tgts.Empty() {
- // remove target and arn association
- if tgts, ok := sys.targetsMap[bucket]; ok {
- for _, t := range tgts {
- if tgt, ok := sys.arnRemotesMap[t.Arn]; ok && tgt.healthCancelFn != nil {
- tgt.healthCancelFn()
- }
- delete(sys.arnRemotesMap, t.Arn)
+
+ // Remove existingtarget and arn association
+ if tgts, ok := sys.targetsMap[bucket]; ok {
+ for _, t := range tgts {
+ if tgt, ok := sys.arnRemotesMap[t.Arn]; ok && tgt.healthCancelFn != nil {
+ tgt.healthCancelFn()
}
+ delete(sys.arnRemotesMap, t.Arn)
}
delete(sys.targetsMap, bucket)
+ }
+
+ // No need for more if not adding anything
+ if tgts == nil || tgts.Empty() {
sys.updateBandwidthLimit(bucket, 0)
return
}
|
fix: health client leak when calling UpdateAllTargets (#<I>)
When `LoadBucketMetadataHandler` is called and `UpdateAllTargets` gets called.
Since targets are rebuilt we cancel all.
|
minio_minio
|
train
|
a160e411fdc66a2e275eb96816a8a87458a363ca
|
diff --git a/adventure/__main__.py b/adventure/__main__.py
index <HASH>..<HASH> 100644
--- a/adventure/__main__.py
+++ b/adventure/__main__.py
@@ -3,6 +3,7 @@
import argparse
import os
import re
+import readline
from sys import executable, stdout
from time import sleep
from . import load_advent_dat
|
Import readline to support command line editing
|
brandon-rhodes_python-adventure
|
train
|
8456dee98f3917953c17266387208f878ae8e77d
|
diff --git a/salt/cloud/__init__.py b/salt/cloud/__init__.py
index <HASH>..<HASH> 100644
--- a/salt/cloud/__init__.py
+++ b/salt/cloud/__init__.py
@@ -1089,7 +1089,7 @@ class Cloud(object):
output['ret'] = action_out
return output
- def volume_create(self, vm_, local_master=True):
+ def volume_create(self, vm_):
'''
Create a single volume
'''
@@ -1109,15 +1109,12 @@ class Cloud(object):
return
try:
- alias, driver = vm_['provider'].split(':')
- func = '{0}.volume_create'.format(driver)
- log.debug('Function: {0}'.format(func))
+ log.debug('Function: {0}'.format(fun))
log.debug('VM: {0}'.format(pprint.pformat(vm_)))
with context.func_globals_inject(
self.clouds[fun],
- __active_provider_name__=':'.join([alias,
- driver])):
- output = self.clouds[func](vm_)
+ __active_provider_name__=vm_['provider']):
+ output = self.clouds[fun](vm_)
except KeyError as exc:
log.exception(
'Failed to create VM {0}. Configuration value {1} needs '
diff --git a/salt/cloud/clouds/nova.py b/salt/cloud/clouds/nova.py
index <HASH>..<HASH> 100644
--- a/salt/cloud/clouds/nova.py
+++ b/salt/cloud/clouds/nova.py
@@ -787,12 +787,11 @@ def list_nodes_select(call=None):
)
-def volume_create(name, size=100, snapshot=None, voltype=None, provider=None):
+def volume_create(name, size=100, snapshot=None, voltype=None):
'''
Create block storage device
'''
conn = get_conn()
- log.debug(pprint.pformat(conn.volume_conn.volumes.list()))
return conn.volume_create(
name,
size,
|
[salt.cloud] nova cloud driver has the provider injected
|
saltstack_salt
|
train
|
7a2d633aa9cf20e594f2f3a087479018e0c7d419
|
diff --git a/src/Core/Content/ProductStream/DataAbstractionLayer/Indexing/ProductStreamIndexer.php b/src/Core/Content/ProductStream/DataAbstractionLayer/Indexing/ProductStreamIndexer.php
index <HASH>..<HASH> 100644
--- a/src/Core/Content/ProductStream/DataAbstractionLayer/Indexing/ProductStreamIndexer.php
+++ b/src/Core/Content/ProductStream/DataAbstractionLayer/Indexing/ProductStreamIndexer.php
@@ -150,7 +150,7 @@ class ProductStreamIndexer implements IndexerInterface
$bytes = Uuid::fromHexToBytesList($ids);
$filters = $this->connection->fetchAll(
- 'SELECT product_stream_id as array_key, product_stream_filter.* FROM product_stream_filter WHERE product_stream_id IN (:ids) ORDER BY product_stream_id',
+ 'SELECT product_stream_id as array_key, product_stream_filter.* FROM product_stream_filter WHERE product_stream_id IN (:ids) ORDER BY product_stream_id',
['ids' => $bytes],
['ids' => Connection::PARAM_STR_ARRAY]
);
|
NTR - fix double space in query
|
shopware_platform
|
train
|
5662a92c460e0a4be822f6cabb79f1fb62897b1b
|
diff --git a/src/server/pkg/hashtree/hashtree.go b/src/server/pkg/hashtree/hashtree.go
index <HASH>..<HASH> 100644
--- a/src/server/pkg/hashtree/hashtree.go
+++ b/src/server/pkg/hashtree/hashtree.go
@@ -93,7 +93,7 @@ func (h *HashTree) updateHash(path string) error {
func (h *HashTree) init() {
if h.Fs == nil {
- h.Fs = map[string]*Node{}
+ h.Fs = make(map[string]*Node)
}
if h.Version == 0 {
h.Version = 1
diff --git a/src/server/pkg/hashtree/hashtree_bench_test.go b/src/server/pkg/hashtree/hashtree_bench_test.go
index <HASH>..<HASH> 100644
--- a/src/server/pkg/hashtree/hashtree_bench_test.go
+++ b/src/server/pkg/hashtree/hashtree_bench_test.go
@@ -24,16 +24,17 @@ import (
// amount of time it takes to do the rehashing is proportional to the number of
// files already in 'h', this is an O(n^2) operation with respect to 'cnt'.
// Because of this, BenchmarkPutFile can be very slow for large 'cnt', often
-// larger then BenchmarkMerge for the same 'cnt'. Be sure to set -timeout 3h for
-// 'cnt' == 100k
+// much slower than BenchmarkMerge. Be sure to set -timeout 3h for 'cnt' == 100k
+//
+// Benchmarked times at rev. 27311193faf56f8e0e9a4e267ab6ea7abc1fe64e
// cnt | time (s)
// -----+-------------
-// 1k | 0.000 s/op
-// 10k | 39.134 s/op
-// 100k | - (probably >1h)
+// 1k | 0.000 s/op
+// 10k | 145.139 s/op
+// 100k | 5101.328 s/op (1.4h)
func BenchmarkPutFile(b *testing.B) {
// Add 'cnt' files
- cnt := int(1e4)
+ cnt := int(1e5)
r := rand.New(rand.NewSource(0))
h := &HashTree{}
for i := 0; i < cnt; i++ {
@@ -47,7 +48,8 @@ func BenchmarkPutFile(b *testing.B) {
// happens at the completion of a job. Because all re-hashing is saved until the
// end, this is O(n) with respect to 'cnt', making it much faster than calling
// PutFile 'cnt' times.
-// Benchmarked times at rev. 3ecd3d7520b75b0650f69b3cf4d4ea44908255f8
+//
+// Benchmarked times at rev. 27311193faf56f8e0e9a4e267ab6ea7abc1fe64e
// cnt | time (s)
// -----+-------------
// 1k | 0.004 s/op
@@ -78,15 +80,15 @@ func BenchmarkMerge(b *testing.B) {
// subtracted from BenchmarkDelete (since that operation is necessarily part of
// the benchmark)
//
-// Benchmarked times at rev. 3ecd3d7520b75b0650f69b3cf4d4ea44908255f8
+// Benchmarked times at rev. 27311193faf56f8e0e9a4e267ab6ea7abc1fe64e
// cnt | time (s)
// -----+-------------
// 1k | 0.003 s/op
-// 10k | 0.042 s/op
-// 100k | 0.484 s/op
+// 10k | 0.040 s/op
+// 100k | 0.464 s/op
func BenchmarkClone(b *testing.B) {
// Create a tree with 'cnt' files
- cnt := int(1e5)
+ cnt := int(1e4)
r := rand.New(rand.NewSource(0))
srcTs := make([]Interface, cnt)
for i := 0; i < cnt; i++ {
@@ -103,12 +105,17 @@ func BenchmarkClone(b *testing.B) {
}
}
-// Benchmarked times at rev. 3ecd3d7520b75b0650f69b3cf4d4ea44908255f8
+// BenchmarkDelete times how long it takes to delete a directory with 'cnt'
+// children from a HashTree. If implemented poorly, this can be a quadratic
+// operation (have to re-hash /foo after deleting each /foo/shard-xxxxx) and
+// will take >1h to delete /foo containing 100k files
+//
+// Benchmarked times at rev. 27311193faf56f8e0e9a4e267ab6ea7abc1fe64e
// cnt | time (s)
// -----+-------------
// 1k | 0.004 s/op
-// 10k | 0.039 s/op
-// 100k | 0.476 s/op
+// 10k | 0.044 s/op
+// 100k | 0.531 s/op
func BenchmarkDelete(b *testing.B) {
// Create a tree with 'cnt' files
cnt := int(1e5)
|
Add benchmarks (with updated times and comments)
|
pachyderm_pachyderm
|
train
|
d5ed99dc32fbaeb34919fa0033c9f230af2373e8
|
diff --git a/myfitnesspal/entry.py b/myfitnesspal/entry.py
index <HASH>..<HASH> 100644
--- a/myfitnesspal/entry.py
+++ b/myfitnesspal/entry.py
@@ -6,6 +6,12 @@ class Entry(MFPBase):
self._name = name
self._nutrition = nutrition
+ def __getitem__(self, value):
+ return self.totals[value]
+
+ def keys(self):
+ return self.totals.keys()
+
@property
def name(self):
return self._name
diff --git a/myfitnesspal/meal.py b/myfitnesspal/meal.py
index <HASH>..<HASH> 100644
--- a/myfitnesspal/meal.py
+++ b/myfitnesspal/meal.py
@@ -11,6 +11,9 @@ class Meal(MFPBase):
raise ValueError('Index must be an integer')
return self.entries[value]
+ def __len__(self):
+ return len(self.entries)
+
@property
def entries(self):
return self._entries
diff --git a/readme.markdown b/readme.markdown
index <HASH>..<HASH> 100644
--- a/readme.markdown
+++ b/readme.markdown
@@ -39,27 +39,18 @@ day = client.get_date(my_birthday)
print day
# >> <03/02/13 {'sodium': 3326, 'carbohydrates': 369, 'calories': 2001, 'fat': 22, 'sugar': 103, 'protein': 110}>
-# To see all meals either
+# To see all meals you can use the Day object's `meals` property
print day.meals
# >> [<Breakfast {}>,
# <Lunch {'sodium': 712, 'carbohydrates': 106, 'calories': 485, 'fat': 3, 'sugar': 0, 'protein': 17}>,
# <Dinner {'sodium': 2190, 'carbohydrates': 170, 'calories': 945, 'fat': 11, 'sugar': 17, 'protein': 53}>,
# <Snacks {'sodium': 424, 'carbohydrates': 93, 'calories': 571, 'fat': 8, 'sugar': 86, 'protein': 40}>]
-# Or, to just see what meals exist:
-print day.keys()
-# >> ['Breakfast', 'Lunch', 'Dinner', 'Snacks']
-
-# To access dinner, you can either access its index in `day.meals`:
-day.meals[2]
-# >> <Dinner {'sodium': 2190, 'carbohydrates': 170, 'calories': 945, 'fat': 11, 'sugar': 17, 'protein': 53}>
-
-# Or use a day as a dictionary having meal names as keys:
-day['Dinner']
+# To access dinner, you can access it by its index in `day.meals`:
+dnner = day.meals[2]
+dinner
# >> <Dinner {'sodium': 2190, 'carbohydrates': 170, 'calories': 945, 'fat': 11, 'sugar': 17, 'protein': 53}>
-dinner = day['Dinner']
-
# To get a list of things I ate for dinner, I can use the dinner Meal object's `entries` property:
dinner.entries
# >> [<Montebello - Spaghetti noodles, 6 oz. {'sodium': 0, 'carbohydrates': 132, 'calories': 630, 'fat': 3, 'sugar': 3, 'protein': 21}>,
@@ -101,4 +92,25 @@ spaghetti.totals
# 'sodium': 0,
# 'sugar': 3}
+
+## Hints
+
+# Day objects act as dictionaries:
+day.keys()
+# >> ['Breakfast', 'Lunch', 'Dinner', 'Snack']
+lunch = day['Lunch']
+
+# Meal objects act as lists:
+print lunch
+# >> [<Generic - Ethiopian - Miser Wat (Red Lentils), 2 cup {'sodium': 508, 'carbohydrates': 76, 'calories': 346, 'fat': 2, 'sugar': 0, 'protein': 12}>,
+# <Injera - Ethiopian Flatbread, 18 " diameter {'sodium': 204, 'carbohydrates': 30, 'calories': 139, 'fat': 1, 'sugar': 0, 'protein': 5}>]
+len(lunch)
+# >> 2
+miser_wat = lunch[0]
+print miser_wat
+# >> <Generic - Ethiopian - Miser Wat (Red Lentils), 2 cup {'sodium': 508, 'carbohydrates': 76, 'calories': 346, 'fat': 2, 'sugar': 0, 'protein': 12}>
+
+# and Entry objects act as dictionaries:
+print miser_wat['calories']
+# >> 346
```
|
Clarifying documentation; adding dictionary interface for Entry objects.
|
coddingtonbear_python-myfitnesspal
|
train
|
55aa192157858c1f4c85b617a7b7b63866c86a46
|
diff --git a/lib/magic_grid/collection.rb b/lib/magic_grid/collection.rb
index <HASH>..<HASH> 100644
--- a/lib/magic_grid/collection.rb
+++ b/lib/magic_grid/collection.rb
@@ -62,6 +62,14 @@ module MagicGrid
end
end
+ def hash_string
+ if @collection.respond_to? :to_sql
+ @collection.to_sql.hash.abs.to_s(36)
+ else
+ @options.hash.abs.to_s(36)
+ end
+ end
+
def search_using_builtin(collection, q)
collection.__send__(@options[:search_method], q)
end
diff --git a/lib/magic_grid/column.rb b/lib/magic_grid/column.rb
index <HASH>..<HASH> 100644
--- a/lib/magic_grid/column.rb
+++ b/lib/magic_grid/column.rb
@@ -26,6 +26,10 @@ module MagicGrid
end
end
+ def self.hash_string(column_or_columns)
+ Array(column_or_columns).map(&:label).join.hash.abs.to_s(36)
+ end
+
def label
@col[:label]
end
diff --git a/lib/magic_grid/definition.rb b/lib/magic_grid/definition.rb
index <HASH>..<HASH> 100644
--- a/lib/magic_grid/definition.rb
+++ b/lib/magic_grid/definition.rb
@@ -88,19 +88,7 @@ module MagicGrid
end
def magic_id
- @options.fetch(:id, columns_hash + collection_hash)
- end
-
- def columns_hash
- @columns.map(&:label).join.hash.abs.to_s(36)
- end
-
- def collection_hash
- if @collection.respond_to? :to_sql
- @collection.to_sql.hash.abs.to_s(36)
- else
- ""
- end
+ @options[:id] || (Column.hash_string(@columns) + @collection.hash_string)
end
def searchable?
|
Move column and collection hashing into Column and Collection classes
|
rmg_magic_grid
|
train
|
a92e4354b08c9311727e0327a8e060390250b4a4
|
diff --git a/lib/pulsar/rest.js b/lib/pulsar/rest.js
index <HASH>..<HASH> 100644
--- a/lib/pulsar/rest.js
+++ b/lib/pulsar/rest.js
@@ -27,6 +27,7 @@ module.exports = (function() {
certificate: sslOptions ? sslOptions['cert'] : null,
key: sslOptions ? sslOptions['key'] : null,
name: 'pulsar-rest-api',
+ debug: true,
version: '1.0.0'
});
@@ -62,7 +63,7 @@ module.exports = (function() {
var task = self.pulsar.getTask(req.params.id);
var listenerTimeout = setTimeout(function() {
- task.removeListener('taskClose', listener);
+ task.removeListener('close', listener);
res.send({changed: false});
}, 10000);
@@ -76,14 +77,14 @@ module.exports = (function() {
return next();
}
- task.once('taskClose', listener);
+ task.once('close', listener);
});
this.server.get('/task/:id/output', function(req, res, next) {
var task = self.pulsar.getTask(req.params.id);
var listenerTimeout = setTimeout(function() {
- task.removeListener('taskChanged', listener);
+ task.removeListener('change', listener);
res.send({changed: false});
}, 10000);
@@ -97,7 +98,7 @@ module.exports = (function() {
return next();
}
- task.once('taskChanged', listener);
+ task.once('change', listener);
});
this.server.post('/task/:id/kill', function(req, res, next) {
@@ -120,6 +121,20 @@ module.exports = (function() {
return next();
});
+ this.server.get('/tasks/created', function(req, res, next) {
+ var listenerTimeout = setTimeout(function() {
+ self.pulsar.removeListener('create', listener);
+ res.send({changed: false});
+ }, 10000);
+
+ var listener = function(task) {
+ res.send({changed: true, task: task.getData()});
+ clearTimeout(listenerTimeout);
+ };
+
+ self.pulsar.once('create', listener);
+ });
+
this.server.listen(port);
return this.server;
diff --git a/lib/pulsar/task.js b/lib/pulsar/task.js
index <HASH>..<HASH> 100644
--- a/lib/pulsar/task.js
+++ b/lib/pulsar/task.js
@@ -25,12 +25,16 @@ module.exports = (function() {
return this.status.get();
}
+ PulsarTask.prototype.onCreate = function() {
+ this.emit("create", { task: this });
+ }
+
PulsarTask.prototype.onUpdate = function() {
- this.emit("taskChanged", { task: this });
+ this.emit("change", { task: this });
}
PulsarTask.prototype.onClose = function() {
- this.emit("taskClose", { task: this });
+ this.emit("close", { task: this });
}
PulsarTask.prototype.execute = function() {
diff --git a/test/pulsar.js b/test/pulsar.js
index <HASH>..<HASH> 100644
--- a/test/pulsar.js
+++ b/test/pulsar.js
@@ -41,7 +41,7 @@ exports.testTaskEvents = function(test) {
var pulsar = new Pulsar(pulsarDbMock)
var task = createDummyTask(pulsar);
- task.on('taskChanged', function(data) { test.equal(data.task.id, task.id); });
+ task.on('change', function(data) { test.equal(data.task.id, task.id); });
task.onUpdate();
test.expect(1);
test.done();
|
Updated events name; Extended REST with /tasks/created
|
cargomedia_pulsar-rest-api
|
train
|
695f0263dec35d9239ce7773637f5e234433b533
|
diff --git a/src/Navigation.js b/src/Navigation.js
index <HASH>..<HASH> 100644
--- a/src/Navigation.js
+++ b/src/Navigation.js
@@ -24,6 +24,10 @@ function registerComponent(screenID, generator, store = undefined, Provider = un
function _registerComponentNoRedux(screenID, generator) {
const generatorWrapper = function() {
const InternalComponent = generator();
+ if (!InternalComponent) {
+ console.error(`Navigation: ${screenID} registration result is 'undefined'`);
+ }
+
return class extends Screen {
static navigatorStyle = InternalComponent.navigatorStyle || {};
static navigatorButtons = InternalComponent.navigatorButtons || {};
|
Add error when trying to load a component which was badly registered (#<I>)
|
wix_react-native-navigation
|
train
|
9cfe3b9473a1f2f155dc5a4b0b79fe873cc0ac4c
|
diff --git a/ara/api/filters.py b/ara/api/filters.py
index <HASH>..<HASH> 100644
--- a/ara/api/filters.py
+++ b/ara/api/filters.py
@@ -145,6 +145,9 @@ class HostFilter(BaseFilter):
class ResultFilter(DateFilter):
playbook = django_filters.NumberFilter(field_name="playbook__id", lookup_expr="exact")
+ task = django_filters.NumberFilter(field_name="task__id", lookup_expr="exact")
+ play = django_filters.NumberFilter(field_name="play__id", lookup_expr="exact")
+ host = django_filters.NumberFilter(field_name="host__id", lookup_expr="exact")
changed = django_filters.BooleanFilter(field_name="changed", lookup_expr="exact")
status = django_filters.MultipleChoiceFilter(
field_name="status", choices=ara_models.Result.STATUS, lookup_expr="iexact"
diff --git a/ara/api/tests/tests_result.py b/ara/api/tests/tests_result.py
index <HASH>..<HASH> 100644
--- a/ara/api/tests/tests_result.py
+++ b/ara/api/tests/tests_result.py
@@ -128,16 +128,33 @@ class ResultTestCase(APITestCase):
request = self.client.get("/api/v1/results/%s" % result.id)
self.assertEqual(result.status, request.data["status"])
- def test_get_result_by_playbook(self):
- playbook = factories.PlaybookFactory()
- host_one = factories.HostFactory(name="one")
- host_two = factories.HostFactory(name="two")
- result = factories.ResultFactory(playbook=playbook, host=host_one, status="failed")
- factories.ResultFactory(playbook=playbook, host=host_two, status="skipped")
- request = self.client.get("/api/v1/results?playbook=%s" % playbook.id)
+ def test_get_result_by_association(self):
+ # Create two results in necessarily two different playbooks with different children:
+ # playbook -> play -> task -> result <- host
+ first_result = factories.ResultFactory()
+ second_result = factories.ResultFactory()
+
+ # the fields with the association ids
+ associations = ["playbook", "play", "task", "host"]
+
+ # Validate that we somehow didn't wind up with the same association ids
+ for association in associations:
+ first = getattr(first_result, association)
+ second = getattr(second_result, association)
+ self.assertNotEqual(first.id, second.id)
+
+ # In other words, there must be two distinct results
+ request = self.client.get("/api/v1/results")
+ self.assertEqual(2, request.data["count"])
self.assertEqual(2, len(request.data["results"]))
- self.assertEqual(result.status, request.data["results"][1]["status"])
- self.assertEqual("skipped", request.data["results"][0]["status"])
+
+ # Searching for the first_result associations should only yield one result
+ for association in associations:
+ assoc_id = getattr(first_result, association).id
+ results = self.client.get("/api/v1/results?%s=%s" % (association, assoc_id))
+ self.assertEqual(1, results.data["count"])
+ self.assertEqual(1, len(results.data["results"]))
+ self.assertEqual(assoc_id, results.data["results"][0][association])
def test_get_result_by_statuses(self):
failed_result = factories.ResultFactory(status="failed")
|
API: Add search by play, task and host for results
We had search by playbook but somehow the other ones were left out.
Change-Id: Ib<I>ea8e<I>bd8d<I>e2c<I>e2f<I>f<I>fe
|
ansible-community_ara
|
train
|
a9f792d17c6b1dcd64a5b2a7ce9c855d23cbdbe3
|
diff --git a/CHANGELOG.md b/CHANGELOG.md
index <HASH>..<HASH> 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,6 +1,6 @@
# Changelog
-## Version 2.8.7-SNAPSHOT Release Notes (IN PROGRESS)
+## Version 2.9.0-SNAPSHOT Release Notes (IN PROGRESS)
### Enhancements ###
diff --git a/src/main/java/com/lazerycode/jmeter/exceptions/ResultsFileNotFoundException.java b/src/main/java/com/lazerycode/jmeter/exceptions/ResultsFileNotFoundException.java
index <HASH>..<HASH> 100644
--- a/src/main/java/com/lazerycode/jmeter/exceptions/ResultsFileNotFoundException.java
+++ b/src/main/java/com/lazerycode/jmeter/exceptions/ResultsFileNotFoundException.java
@@ -3,7 +3,7 @@ package com.lazerycode.jmeter.exceptions;
import org.apache.maven.plugin.MojoExecutionException;
public class ResultsFileNotFoundException extends MojoExecutionException {
- public ResultsFileNotFoundException(String message, Throwable cause) {
- super(message, cause);
+ public ResultsFileNotFoundException(String message) {
+ super(message);
}
}
diff --git a/src/main/java/com/lazerycode/jmeter/testrunner/ResultScanner.java b/src/main/java/com/lazerycode/jmeter/testrunner/ResultScanner.java
index <HASH>..<HASH> 100644
--- a/src/main/java/com/lazerycode/jmeter/testrunner/ResultScanner.java
+++ b/src/main/java/com/lazerycode/jmeter/testrunner/ResultScanner.java
@@ -4,6 +4,7 @@ import com.fasterxml.jackson.databind.MappingIterator;
import com.fasterxml.jackson.dataformat.csv.CsvMapper;
import com.fasterxml.jackson.dataformat.csv.CsvSchema;
import com.lazerycode.jmeter.exceptions.IOException;
+import com.lazerycode.jmeter.exceptions.ResultsFileNotFoundException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -59,8 +60,12 @@ public class ResultScanner implements IResultScanner {
*
* @param file File to parse
* @throws IOException IOException
+ * @throws ResultsFileNotFoundException File not found
*/
- public void parseResultFile(File file) throws IOException {
+ public void parseResultFile(File file) throws IOException, ResultsFileNotFoundException {
+ if (!file.exists()) {
+ throw new ResultsFileNotFoundException("Unable to find " + file.getAbsolutePath());
+ }
LOGGER.info("Parsing results file '{}' in format '{}'", file, format);
if (countFailures) {
diff --git a/src/test/java/com/lazerycode/jmeter/testrunner/ResultScannerTest.java b/src/test/java/com/lazerycode/jmeter/testrunner/ResultScannerTest.java
index <HASH>..<HASH> 100644
--- a/src/test/java/com/lazerycode/jmeter/testrunner/ResultScannerTest.java
+++ b/src/test/java/com/lazerycode/jmeter/testrunner/ResultScannerTest.java
@@ -1,7 +1,7 @@
package com.lazerycode.jmeter.testrunner;
import com.lazerycode.jmeter.exceptions.IOException;
-import com.lazerycode.jmeter.testrunner.ResultScanner;
+import com.lazerycode.jmeter.exceptions.ResultsFileNotFoundException;
import org.junit.Test;
import java.io.File;
@@ -114,30 +114,37 @@ public class ResultScannerTest {
assertThat(fileScanner.getSuccessCount()).isEqualTo(2);
}
- @Test(expected=IllegalArgumentException.class)
+ @Test(expected = IllegalArgumentException.class)
public void emptyCSVFileThrowsIllegalArgumentException() throws Exception {
File resultsFile = new File(emptyCSVFileURL.toURI());
ResultScanner fileScanner = new ResultScanner(COUNT_SUCCESSES, COUNT_FAILURES, true);
fileScanner.parseResultFile(resultsFile);
}
- @Test(expected=IllegalStateException.class)
+ @Test(expected = IllegalStateException.class)
public void csvFileMissingDelimiterThrowsIllegalStateException() throws Exception {
File resultsFile = new File(csvMissingDelimiterFileURL.toURI());
ResultScanner fileScanner = new ResultScanner(COUNT_SUCCESSES, COUNT_FAILURES, true);
fileScanner.parseResultFile(resultsFile);
}
- @Test(expected= IOException.class)
- public void invalidCSVFileThrowsIOException() throws Exception {
+ @Test(expected = ResultsFileNotFoundException.class)
+ public void fileThatDoesNotExistThrowsResultsFileNotFoundException() throws Exception {
File resultsFile = new File("DoesNotExist.nope");
ResultScanner fileScanner = new ResultScanner(COUNT_SUCCESSES, COUNT_FAILURES, true);
fileScanner.parseResultFile(resultsFile);
}
- @Test(expected= IOException.class)
+ @Test(expected = IOException.class)
+ public void invalidCSVFileThrowsIOException() throws Exception {
+ File resultsFile = new File("/");
+ ResultScanner fileScanner = new ResultScanner(COUNT_SUCCESSES, COUNT_FAILURES, true);
+ fileScanner.parseResultFile(resultsFile);
+ }
+
+ @Test(expected = IOException.class)
public void invalidJTLileThrowsIOException() throws Exception {
- File resultsFile = new File("DoesNotExist.nope");
+ File resultsFile = new File("/");
ResultScanner fileScanner = new ResultScanner(COUNT_SUCCESSES, COUNT_FAILURES, false);
fileScanner.parseResultFile(resultsFile);
}
|
Throw a ResultsFileNotFoundException if results file does not exist
|
jmeter-maven-plugin_jmeter-maven-plugin
|
train
|
860c7a1d3bb565d0d104575d4f35160fcc37e94a
|
diff --git a/ricecooker/classes/nodes.py b/ricecooker/classes/nodes.py
index <HASH>..<HASH> 100644
--- a/ricecooker/classes/nodes.py
+++ b/ricecooker/classes/nodes.py
@@ -1069,7 +1069,9 @@ class CustomNavigationNode(ContentNode):
required_file_format = file_formats.HTML5
def __init__(self, *args, **kwargs):
- kwargs["extra_fields"] = {'modality': "CUSTOM_NAVIGATION"}
+ kwargs["extra_fields"] = kwargs.get("extra_fields", {})
+ kwargs["extra_fields"]["options"] = kwargs["extra_fields"].get("options", {})
+ kwargs["extra_fields"]["options"].update({'modality': "CUSTOM_NAVIGATION"})
super(CustomNavigationNode, self).__init__(*args, **kwargs)
def generate_thumbnail(self):
@@ -1102,7 +1104,9 @@ class CustomNavigationChannelNode(ChannelNode):
required_file_format = file_formats.HTML5
def __init__(self, *args, **kwargs):
- kwargs["extra_fields"] = {'modality': "CUSTOM_NAVIGATION"}
+ kwargs["extra_fields"] = kwargs.get("extra_fields", {})
+ kwargs["extra_fields"]["options"] = kwargs["extra_fields"].get("options", {})
+ kwargs["extra_fields"]["options"].update({'modality': "CUSTOM_NAVIGATION"})
super(CustomNavigationChannelNode, self).__init__(*args, **kwargs)
def validate(self):
|
Ensures that custom navigation is properly set as 'options' on extra_fields.
This ensures it gets set in `options` on the kolibri exported contentnode.
|
learningequality_ricecooker
|
train
|
80e7c27ec27b5adcd99f60f5d6a13a65386ed69b
|
diff --git a/examples/network/network_api_demo.py b/examples/network/network_api_demo.py
index <HASH>..<HASH> 100755
--- a/examples/network/network_api_demo.py
+++ b/examples/network/network_api_demo.py
@@ -27,7 +27,6 @@ import os
from pkg_resources import resource_filename
-from nupic.algorithms.anomaly import computeRawAnomalyScore
from nupic.data.file_record_stream import FileRecordStream
from nupic.engine import Network
from nupic.encoders import MultiEncoder, ScalarEncoder, DateEncoder
|
removes anomaly.py dependency in network_api_demo.py
|
numenta_nupic
|
train
|
58ebc5c9a5cc932678f7b1624171a4704ea133fc
|
diff --git a/builder/vmware/iso/step_create_vmx.go b/builder/vmware/iso/step_create_vmx.go
index <HASH>..<HASH> 100644
--- a/builder/vmware/iso/step_create_vmx.go
+++ b/builder/vmware/iso/step_create_vmx.go
@@ -404,7 +404,9 @@ func (s *stepCreateVMX) Run(_ context.Context, state multistep.StateBag) multist
state.Put("vmnetwork", network)
/// check if serial port has been configured
- if config.Serial != "" {
+ if config.Serial == "" {
+ templateData.Serial_Present = "FALSE"
+ } else {
serial, err := unformat_serial(config.Serial)
if err != nil {
err := fmt.Errorf("Error procesing VMX template: %s", err)
@@ -439,6 +441,7 @@ func (s *stepCreateVMX) Run(_ context.Context, state multistep.StateBag) multist
templateData.Serial_Yield = serial.auto.yield
templateData.Serial_Auto = "TRUE"
case nil:
+ templateData.Serial_Present = "FALSE"
break
default:
@@ -450,7 +453,9 @@ func (s *stepCreateVMX) Run(_ context.Context, state multistep.StateBag) multist
}
/// check if parallel port has been configured
- if config.Parallel != "" {
+ if config.Parallel == "" {
+ templateData.Parallel_Present = "FALSE"
+ } else {
parallel, err := unformat_parallel(config.Parallel)
if err != nil {
err := fmt.Errorf("Error procesing VMX template: %s", err)
@@ -473,6 +478,7 @@ func (s *stepCreateVMX) Run(_ context.Context, state multistep.StateBag) multist
templateData.Parallel_Auto = "TRUE"
templateData.Parallel_Bidirectional = parallel.auto.bidirectional
case nil:
+ templateData.Parallel_Present = "FALSE"
break
default:
|
When specifying NONE for serial or parallel in the VMware builder, disable the serial and parallel port devices entirely.
|
hashicorp_packer
|
train
|
e3e80c357d7101b666b1595d470ec79c5f42a5bc
|
diff --git a/core/src/main/java/com/google/bitcoin/core/BitcoinSerializer.java b/core/src/main/java/com/google/bitcoin/core/BitcoinSerializer.java
index <HASH>..<HASH> 100644
--- a/core/src/main/java/com/google/bitcoin/core/BitcoinSerializer.java
+++ b/core/src/main/java/com/google/bitcoin/core/BitcoinSerializer.java
@@ -96,12 +96,7 @@ public class BitcoinSerializer {
/**
* Writes message to to the output stream.
*/
- public void serialize(Message message, OutputStream out) throws IOException {
- String name = names.get(message.getClass());
- if (name == null) {
- throw new Error("BitcoinSerializer doesn't currently know how to serialize " + message.getClass());
- }
-
+ public void serialize(String name, byte[] message, OutputStream out) throws IOException {
byte[] header = new byte[4 + COMMAND_LEN + 4 + 4 /* checksum */];
uint32ToByteArrayBE(params.getPacketMagic(), header, 0);
@@ -111,38 +106,26 @@ public class BitcoinSerializer {
header[4 + i] = (byte) (name.codePointAt(i) & 0xFF);
}
- byte[] payload = message.bitcoinSerialize();
-
- Utils.uint32ToByteArrayLE(payload.length, header, 4 + COMMAND_LEN);
-
- byte[] checksum = message.getChecksum();
- if (checksum == null) {
- Sha256Hash msgHash = message.getHash();
- if (msgHash != null && message instanceof Transaction) {
- // if the message happens to have a precalculated hash use
- // it.
- // reverse copying 4 bytes is about 1600 times faster than
- // calculating a new hash
- // this is only possible for transactions as block hashes
- // are hashes of the header only
- byte[] hash = msgHash.getBytes();
- int start = 4 + COMMAND_LEN + 4;
- for (int i = start; i < start + 4; i++)
- header[i] = hash[31 - i + start];
-
- } else {
- byte[] hash = doubleDigest(payload);
- System.arraycopy(hash, 0, header, 4 + COMMAND_LEN + 4, 4);
- }
- } else {
- System.arraycopy(checksum, 0, header, 4 + COMMAND_LEN + 4, 4);
- }
+ Utils.uint32ToByteArrayLE(message.length, header, 4 + COMMAND_LEN);
+ byte[] hash = doubleDigest(message);
+ System.arraycopy(hash, 0, header, 4 + COMMAND_LEN + 4, 4);
out.write(header);
- out.write(payload);
+ out.write(message);
if (log.isDebugEnabled())
- log.debug("Sending {} message: {}", name, bytesToHexString(header) + bytesToHexString(payload));
+ log.debug("Sending {} message: {}", name, bytesToHexString(header) + bytesToHexString(message));
+ }
+
+ /**
+ * Writes message to to the output stream.
+ */
+ public void serialize(Message message, OutputStream out) throws IOException {
+ String name = names.get(message.getClass());
+ if (name == null) {
+ throw new Error("BitcoinSerializer doesn't currently know how to serialize " + message.getClass());
+ }
+ serialize(name, message.bitcoinSerialize(), out);
}
/**
|
BitcoinSerializer: Remove some optimisations that date from the time when someone was trying to make bitcoinj into a super scalable multiplexor, and allow writing of arbitrary byte arrays that get checksummed and prefixed.
|
bitcoinj_bitcoinj
|
train
|
673f966f09f9530ebd9d853ef0d62d8b923e76a2
|
diff --git a/source/MySQLiByDanielGPnumbers.php b/source/MySQLiByDanielGPnumbers.php
index <HASH>..<HASH> 100644
--- a/source/MySQLiByDanielGPnumbers.php
+++ b/source/MySQLiByDanielGPnumbers.php
@@ -170,7 +170,7 @@ trait MySQLiByDanielGPnumbers
} elseif (in_array($fieldDetails['DATA_TYPE'], ['decimal', 'numeric'])) {
return ['M' => $fieldDetails['NUMERIC_PRECISION'], 'd' => $fieldDetails['NUMERIC_SCALE']];
} elseif (in_array($fieldDetails['DATA_TYPE'], ['bigint', 'int', 'mediumint', 'smallint', 'tinyint'])) {
- return $this->setFldLmtsExact($fieldDetails['DATA_TYPE']);
+ return $this->setFldLmtsExact($fieldDetails['DATA_TYPE'], $fieldDetails['COLUMN_TYPE']);
}
return $this->setFieldSpecificElse($fieldDetails);
}
@@ -184,7 +184,7 @@ trait MySQLiByDanielGPnumbers
return ['M' => '???'];
}
- private function setFldLmtsExact($cTp)
+ private function setFldLmtsExact($dTp, $cTp)
{
$xct = [
'bigint' => ['l' => -9223372036854775808, 'L' => 9223372036854775807, 's' => 21, 'sUS' => 20],
@@ -194,10 +194,10 @@ trait MySQLiByDanielGPnumbers
'tinyint' => ['l' => -128, 'L' => 127, 's' => 4, 'sUS' => 3],
];
$aReturn = null;
- if (array_key_exists($cTp, $xct)) {
- $aReturn = ['m' => $xct[$cTp]['l'], 'M' => $xct[$cTp]['L'], 'l' => $xct[$cTp]['s']];
+ if (array_key_exists($dTp, $xct)) {
+ $aReturn = ['m' => $xct[$dTp]['l'], 'M' => $xct[$dTp]['L'], 'l' => $xct[$dTp]['s']];
if (strpos($cTp, 'unsigned') !== false) {
- $aReturn = ['m' => 0, 'M' => ($xct[$cTp]['L'] - $xct[$cTp]['l']), 'l' => $xct[$cTp]['sUS']];
+ $aReturn = ['m' => 0, 'M' => ($xct[$dTp]['L'] - $xct[$dTp]['l']), 'l' => $xct[$dTp]['sUS']];
}
}
return $aReturn;
@@ -214,7 +214,7 @@ trait MySQLiByDanielGPnumbers
{
$btn = [];
$btn[] = '<input type="submit" id="submit" style="margin-left:220px;" value="'
- . $this->lclMsgCmn('i18n_Form_ButtonSave') . '" />';
+ . $this->lclMsgCmn('i18n_Form_ButtonSave') . '" />';
if (isset($feat['insertAndUpdate'])) {
$btn[] = '<input type="hidden" id="insertAndUpdate" name="insertAndUpdate" value="insertAndUpdate" />';
}
|
field type having unsigned flag required special attention in determining limits detection
|
danielgp_common-lib
|
train
|
9b18e39ba94f5ccb8a0d9e772b9b56efcd9eeaf9
|
diff --git a/fathom-rest/src/main/java/fathom/rest/Context.java b/fathom-rest/src/main/java/fathom/rest/Context.java
index <HASH>..<HASH> 100644
--- a/fathom-rest/src/main/java/fathom/rest/Context.java
+++ b/fathom-rest/src/main/java/fathom/rest/Context.java
@@ -87,4 +87,10 @@ public class Context extends DefaultRouteContext {
return set;
}
+ public <T> Context putLocal(String name, T t) {
+ setLocal(name, t);
+
+ return this;
+ }
+
}
|
Add putLocal Context method for fluency
|
gitblit_fathom
|
train
|
4928f40d2b473356e8f1cd6c621e84b56c8bdaec
|
diff --git a/contrib/aws/awsexecutor.py b/contrib/aws/awsexecutor.py
index <HASH>..<HASH> 100644
--- a/contrib/aws/awsexecutor.py
+++ b/contrib/aws/awsexecutor.py
@@ -14,7 +14,7 @@ import os
import requests
import shutil
import sys
-import time
+from threading import Event
import zipfile
import benchexec.util
@@ -40,6 +40,7 @@ DEFAULT_CLOUD_CPUCORE_REQUIREMENT = 2 # one core with hyperthreading
DEFAULT_CLOUD_CPUMODEL_REQUIREMENT = "" # empty string matches every model
STOPPED_BY_INTERRUPT = False
+event_handler = Event()
def init(config, benchmark):
@@ -165,17 +166,20 @@ def execute_benchmark(benchmark, output_handler):
)
logging.debug("Sending http-request for progress: \n%s", progress_url)
printMsg = 0
- # Give the ec2-instance some time for instantiation
- while True:
+ # Poll the current status in AWS by periodically sending an http-request
+ # (for example, how much tasks have been verified so far)
+ while not event_handler.is_set():
http_request = requests.get(progress_url)
_exitWhenRequestFailed(http_request)
msg = http_request.json()
+ # poll every 15 sec and print a user message every second time
if msg.get("message") == "Internal server error":
+ # This message appears if the ec2-instances are not instantiated / running yet
printMsg += 1
if printMsg % 2 == 0:
logging.info("Waiting for EC2 to launch the batch processes...")
- time.sleep(15)
+ event_handler.wait(15)
elif not msg["completed"]:
printMsg += 1
if printMsg % 2 == 0:
@@ -185,7 +189,7 @@ def execute_benchmark(benchmark, output_handler):
"Waiting until all tasks have been verified... "
"(Completed: {}/{})".format(jobsCompleted, totalJobs)
)
- time.sleep(15)
+ event_handler.wait(15)
else:
logging.info(
"Execution of %s tasks finished. Collecting the results back from AWS.",
@@ -212,6 +216,13 @@ def execute_benchmark(benchmark, output_handler):
if os.path.exists(tasks_arc_path):
os.remove(tasks_arc_path)
+ # Clean
+ url = REQUEST_URL["clean"].format(aws_endpoint, aws_token)
+ logging.debug(
+ "Sending an http-request for cleaning up the used aws services: \n%s", url
+ )
+ requests.get(url)
+
if STOPPED_BY_INTERRUPT:
output_handler.set_error("interrupted")
@@ -219,13 +230,10 @@ def execute_benchmark(benchmark, output_handler):
handleCloudResults(benchmark, output_handler, start_time, end_time)
- # Clean
- url = REQUEST_URL["clean"].format(aws_endpoint, aws_token)
- logging.debug("Sending http-request for cleaning up the aws services: \n%s", url)
- http_request = requests.get(url)
-
def stop():
+ global event_handler
+ event_handler.set()
global STOPPED_BY_INTERRUPT
STOPPED_BY_INTERRUPT = True
|
AWS executor: add event handler that listens to user-interrupts
|
sosy-lab_benchexec
|
train
|
8bd97828c40e20b117d24f8ba17482445eae701a
|
diff --git a/app/transitions/fade.js b/app/transitions/fade.js
index <HASH>..<HASH> 100644
--- a/app/transitions/fade.js
+++ b/app/transitions/fade.js
@@ -3,14 +3,16 @@ import { isAnimating, finish, timeSpent, animate, stop } from "liquid-fire";
export default function fade(opts={}) {
var firstStep;
var outOpts = opts;
+ var fadingElement = findFadingElement(this);
- if (isAnimating(this.oldElement, 'fade-out')) {
- // if the old view is already fading out, let it finish.
- firstStep = finish(this.oldElement, 'fade-out');
+ if (fadingElement) {
+ // We still have some older version that is in the process of
+ // fading out, so out first step is waiting for it to finish.
+ firstStep = finish(fadingElement, 'fade-out');
} else {
if (isAnimating(this.oldElement, 'fade-in')) {
- // if the old view is partially faded in, scale its fade-out
- // duration appropriately.
+ // if the previous view is partially faded in, scale its
+ // fade-out duration appropriately.
outOpts = { duration: timeSpent(this.oldElement, 'fade-in') };
}
stop(this.oldElement);
@@ -22,3 +24,15 @@ export default function fade(opts={}) {
});
}
// END-SNIPPET
+
+function findFadingElement(context) {
+ for (var i = 0; i < context.older.length; i++) {
+ var entry = context.older[i];
+ if (isAnimating(entry.element, 'fade-out')) {
+ return entry.element;
+ }
+ }
+ if (isAnimating(context.oldElement, 'fade-out')) {
+ return context.oldElement;
+ }
+}
|
robust mult-interruption support for fade transition
|
ember-animation_liquid-fire
|
train
|
13ea159e9c8346a288b62164360c7d3447a4e6c6
|
diff --git a/theme/image.php b/theme/image.php
index <HASH>..<HASH> 100644
--- a/theme/image.php
+++ b/theme/image.php
@@ -121,24 +121,25 @@ if ($rev > -1) {
// parameters to get the best performance.
function send_cached_image($imagepath, $rev) {
- $lifetime = 60*60*24*3; // 3 days
+ $lifetime = 60*60*24*30; // 30 days
$pathinfo = pathinfo($imagepath);
$imagename = $pathinfo['filename'].'.'.$pathinfo['extension'];
switch($pathinfo['extension']) {
- case 'gif' : $mimetype = 'image/gif'; break;
- case 'png' : $mimetype = 'image/png'; break;
- case 'jpg' : $mimetype = 'image/jpeg'; break;
+ case 'gif' : $mimetype = 'image/gif'; break;
+ case 'png' : $mimetype = 'image/png'; break;
+ case 'jpg' : $mimetype = 'image/jpeg'; break;
case 'jpeg' : $mimetype = 'image/jpeg'; break;
- case 'ico' : $mimetype = 'image/vnd.microsoft.icon'; break;
+ case 'ico' : $mimetype = 'image/vnd.microsoft.icon'; break;
default: $mimetype = 'document/unknown';
}
header('Etag: '.md5("$rev/$imagepath"));
header('Content-Disposition: inline; filename="'.$imagename.'"');
- header('Last-Modified: '. gmdate('D, d M Y H:i:s', filemtime($imagepath)) .' GMT');
+ header('Last-Modified: '. gmdate('D, d M Y H:i:s', time()) .' GMT');
header('Expires: '. gmdate('D, d M Y H:i:s', time() + $lifetime) .' GMT');
header('Pragma: ');
+ header('Cache-Control: max-age='.$lifetime);
header('Accept-Ranges: none');
header('Content-Type: '.$mimetype);
header('Content-Length: '.filesize($imagepath));
@@ -153,17 +154,17 @@ function send_uncached_image($imagepath) {
$imagename = $pathinfo['filename'].'.'.$pathinfo['extension'];
switch($pathinfo['extension']) {
- case 'gif' : $mimetype = 'image/gif'; break;
- case 'png' : $mimetype = 'image/png'; break;
- case 'jpg' : $mimetype = 'image/jpeg'; break;
+ case 'gif' : $mimetype = 'image/gif'; break;
+ case 'png' : $mimetype = 'image/png'; break;
+ case 'jpg' : $mimetype = 'image/jpeg'; break;
case 'jpeg' : $mimetype = 'image/jpeg'; break;
- case 'ico' : $mimetype = 'image/vnd.microsoft.icon'; break;
+ case 'ico' : $mimetype = 'image/vnd.microsoft.icon'; break;
default: $mimetype = 'document/unknown';
}
header('Content-Disposition: inline; filename="'.$imagename.'"');
header('Last-Modified: '. gmdate('D, d M Y H:i:s', time()) .' GMT');
- header('Expires: '. gmdate('D, d M Y H:i:s', time() + 2) .' GMT');
+ header('Expires: '. gmdate('D, d M Y H:i:s', time() + 15) .' GMT');
header('Pragma: ');
header('Accept-Ranges: none');
header('Content-Type: '.$mimetype);
|
MDL-<I> longer image caching in theme designer mode (performance)
|
moodle_moodle
|
train
|
9624121fc312c1e7a5897047d5ab6fd8baa87d5c
|
diff --git a/ast_test.go b/ast_test.go
index <HASH>..<HASH> 100644
--- a/ast_test.go
+++ b/ast_test.go
@@ -859,6 +859,37 @@ var astTests = []testCase{
IfStmt{},
},
{
+ []string{"if; then a=; fi", "if; then a=\nfi"},
+ IfStmt{
+ ThenStmts: []Stmt{
+ {Assigns: []Assign{
+ {Name: lit("a")},
+ }},
+ },
+ },
+ },
+ {
+ []string{"if; then >f; fi", "if; then >f\nfi"},
+ IfStmt{
+ ThenStmts: []Stmt{
+ {Redirs: []Redirect{
+ {Op: RDROUT, Word: litWord("f")},
+ }},
+ },
+ },
+ },
+ {
+ []string{"a=b; c=d", "a=b\nc=d"},
+ []Stmt{
+ {Assigns: []Assign{
+ {Name: lit("a"), Value: litWord("b")},
+ }},
+ {Assigns: []Assign{
+ {Name: lit("c"), Value: litWord("d")},
+ }},
+ },
+ },
+ {
[]string{"while; do; done", "while\ndo\ndone"},
WhileStmt{},
},
diff --git a/parse.go b/parse.go
index <HASH>..<HASH> 100644
--- a/parse.go
+++ b/parse.go
@@ -740,6 +740,10 @@ func (p *parser) gotStmt(s *Stmt) bool {
} else {
break
}
+ if p.newLine {
+ p.gotEnd = true
+ return true
+ }
}
p.gotStmtAndOr(s, addRedir)
if !p.peekEnd() {
|
Fix single redirects or assignments with newlines
|
mvdan_sh
|
train
|
7f428a9e515d8a04893ace3584124fb70b42647c
|
diff --git a/src/core.js b/src/core.js
index <HASH>..<HASH> 100755
--- a/src/core.js
+++ b/src/core.js
@@ -107,6 +107,14 @@
* @memberOf me.sys
*/
nativeBase64 : (typeof($.atob) == 'function'),
+
+ /**
+ * Touch capabilities <br>
+ * @type {Boolean}
+ * @memberOf me.sys
+ */
+ touch : false,
+
// Global settings
/**
@@ -753,6 +761,9 @@
me.sys.sound = false;
}
+ // detect touch capabilities
+ me.sys.touch = ('createTouch' in document) || ('ontouchstart' in $);
+
// init the FPS counter if needed
me.timer.init();
|
Added "touch" capability detection (ticket #7)
|
melonjs_melonJS
|
train
|
9c830d6a44d3ffec3c23d4101e29159e929db7a4
|
diff --git a/lib/utils/known-browsers.js b/lib/utils/known-browsers.js
index <HASH>..<HASH> 100644
--- a/lib/utils/known-browsers.js
+++ b/lib/utils/known-browsers.js
@@ -34,6 +34,16 @@ function chromeArgs(browserTmpDir, url) {
];
}
+function headlessChromeArgs(browserTmpDir, url) {
+ return [
+ '--headless',
+ '--disable-gpu',
+ '--disable-software-rasterizer',
+ '--mute-audio',
+ '--remote-debugging-port=0',
+ '--window-size=1440,900'].concat(chromeArgs(browserTmpDir, url));
+}
+
// Return the catalogue of the browsers that Testem supports for the platform. Each 'browser object'
// will contain these fields:
//
@@ -96,6 +106,18 @@ module.exports = function knownBrowsers(platform, config) {
return chromeArgs(this.browserTmpDir(), url);
}
},
+ {
+ name: 'Headless Chrome',
+ possiblePath: chromeWinPaths(userHomeDir, 'Chrome').concat(chromeOSXPaths('Google Chrome')),
+ possibleExe: [
+ 'google-chrome',
+ 'google-chrome-stable',
+ 'chrome'
+ ],
+ args(config, url) {
+ return headlessChromeArgs(this.browserTmpDir(), url);
+ }
+ },
// On Windows, Chrome Stable/Beta/Dev are installed on the same path
{
@@ -109,6 +131,16 @@ module.exports = function knownBrowsers(platform, config) {
}
},
{
+ name: 'Headless Chrome Beta',
+ possiblePath: chromeOSXPaths('Google Chrome Beta'),
+ possibleExe: [
+ 'google-chrome-beta'
+ ],
+ args(config, url) {
+ return headlessChromeArgs(this.browserTmpDir(), url);
+ }
+ },
+ {
name: 'Chrome Dev',
possiblePath: chromeOSXPaths('Google Chrome Dev'),
possibleExe: [
diff --git a/tests/utils/known-browsers_tests.js b/tests/utils/known-browsers_tests.js
index <HASH>..<HASH> 100644
--- a/tests/utils/known-browsers_tests.js
+++ b/tests/utils/known-browsers_tests.js
@@ -189,7 +189,7 @@ describe('knownBrowsers', function() {
}
browsers = knownBrowsers('any', config);
- chrome = findBrowser(browsers, 'Chrome');
+ chrome = findBrowser(browsers, browserName || 'Chrome');
}
beforeEach(function() {
@@ -283,6 +283,36 @@ describe('knownBrowsers', function() {
]);
});
});
+
+ describe('headless browser_args', function() {
+ beforeEach(function() {
+ setup('Headless Chrome');
+ });
+
+ afterEach(function() {
+ setup();
+ });
+
+ it('constructs correct args with browser_args', function() {
+ expect(chrome.args.call(launcher, config, url)).to.deep.eq([
+ '--testem',
+ '--headless',
+ '--disable-gpu',
+ '--disable-software-rasterizer',
+ '--mute-audio',
+ '--remote-debugging-port=0',
+ '--window-size=1440,900',
+ '--user-data-dir=' + browserTmpDir,
+ '--no-default-browser-check',
+ '--no-first-run',
+ '--ignore-certificate-errors',
+ '--test-type',
+ '--disable-renderer-backgrounding',
+ '--disable-background-timer-throttling',
+ url
+ ]);
+ });
+ });
});
describe('Safari', function() {
|
Adding headless chrome to known browser (#<I>)
|
testem_testem
|
train
|
075ab1e93f76ac9d4d0aba3854cbff293ae2c8b3
|
diff --git a/erizo_controller/erizoClient/src/Stream.js b/erizo_controller/erizoClient/src/Stream.js
index <HASH>..<HASH> 100644
--- a/erizo_controller/erizoClient/src/Stream.js
+++ b/erizo_controller/erizoClient/src/Stream.js
@@ -31,7 +31,15 @@ Erizo.Stream = function (spec) {
// Public functions
that.getID = function () {
- return spec.streamID;
+ var id;
+ // Unpublished local streams don't yet have an ID.
+ if (that.local && !spec.streamID) {
+ id = 'local';
+ }
+ else {
+ id = spec.streamID;
+ }
+ return id;
};
// Get attributes of this stream.
|
Provide valid ID for unpublished local stream
Fixes getID() to return a sensible ID for unpublished local streams.
|
lynckia_licode
|
train
|
222f79bb4c6e2aa5426cc5ff25f1b2461e18a300
|
diff --git a/datasette/default_menu_links.py b/datasette/default_menu_links.py
index <HASH>..<HASH> 100644
--- a/datasette/default_menu_links.py
+++ b/datasette/default_menu_links.py
@@ -3,7 +3,10 @@ from datasette import hookimpl
@hookimpl
def menu_links(datasette, actor):
- if actor and actor.get("id") == "root":
+ async def inner():
+ if not await datasette.permission_allowed(actor, "debug-menu"):
+ return []
+
return [
{"href": datasette.urls.path("/-/databases"), "label": "Databases"},
{
@@ -38,3 +41,5 @@ def menu_links(datasette, actor):
{"href": datasette.urls.path("/-/actor"), "label": "Debug actor"},
{"href": datasette.urls.path("/-/patterns"), "label": "Pattern portfolio"},
]
+
+ return inner
diff --git a/datasette/default_permissions.py b/datasette/default_permissions.py
index <HASH>..<HASH> 100644
--- a/datasette/default_permissions.py
+++ b/datasette/default_permissions.py
@@ -5,7 +5,7 @@ from datasette.utils import actor_matches_allow
@hookimpl(tryfirst=True)
def permission_allowed(datasette, actor, action, resource):
async def inner():
- if action == "permissions-debug":
+ if action in ("permissions-debug", "debug-menu"):
if actor and actor.get("id") == "root":
return True
elif action == "view-instance":
diff --git a/datasette/views/special.py b/datasette/views/special.py
index <HASH>..<HASH> 100644
--- a/datasette/views/special.py
+++ b/datasette/views/special.py
@@ -96,7 +96,8 @@ class PermissionsDebugView(BaseView):
return await self.render(
["permissions_debug.html"],
request,
- {"permission_checks": reversed(self.ds._permission_checks)},
+ # list() avoids error if check is performed during template render:
+ {"permission_checks": list(reversed(self.ds._permission_checks))},
)
diff --git a/docs/authentication.rst b/docs/authentication.rst
index <HASH>..<HASH> 100644
--- a/docs/authentication.rst
+++ b/docs/authentication.rst
@@ -522,3 +522,12 @@ permissions-debug
Actor is allowed to view the ``/-/permissions`` debug page.
Default *deny*.
+
+.. _permissions_debug_menu:
+
+debug-menu
+----------
+
+Controls if the various debug pages are displayed in the navigation menu.
+
+Default *deny*.
diff --git a/tests/test_html.py b/tests/test_html.py
index <HASH>..<HASH> 100644
--- a/tests/test_html.py
+++ b/tests/test_html.py
@@ -1507,3 +1507,41 @@ def test_edit_sql_link_not_shown_if_user_lacks_permission(permission_allowed):
assert "Edit SQL" in response.text
else:
assert "Edit SQL" not in response.text
+
+
+@pytest.mark.parametrize(
+ "actor_id,should_have_links,should_not_have_links",
+ [
+ (None, None, None),
+ ("test", None, ["/-/permissions"]),
+ ("root", ["/-/permissions", "/-/allow-debug", "/-/metadata"], None),
+ ],
+)
+def test_navigation_menu_links(
+ app_client, actor_id, should_have_links, should_not_have_links
+):
+ cookies = {}
+ if actor_id:
+ cookies = {"ds_actor": app_client.actor_cookie({"id": actor_id})}
+ html = app_client.get("/", cookies=cookies).text
+ soup = Soup(html, "html.parser")
+ details = soup.find("nav").find("details")
+ if not actor_id:
+ # Should not show a menu
+ assert details is None
+ return
+ # They are logged in: should show a menu
+ assert details is not None
+ # And a rogout form
+ assert details.find("form") is not None
+ if should_have_links:
+ for link in should_have_links:
+ assert (
+ details.find("a", {"href": link}) is not None
+ ), "{} expected but missing from nav menu".format(link)
+
+ if should_not_have_links:
+ for link in should_not_have_links:
+ assert (
+ details.find("a", {"href": link}) is None
+ ), "{} found but should not have been in nav menu".format(link)
diff --git a/tests/test_permissions.py b/tests/test_permissions.py
index <HASH>..<HASH> 100644
--- a/tests/test_permissions.py
+++ b/tests/test_permissions.py
@@ -310,10 +310,11 @@ def test_permissions_checked(app_client, path, permissions):
def test_permissions_debug(app_client):
app_client.ds._permission_checks.clear()
- assert 403 == app_client.get("/-/permissions").status
+ assert app_client.get("/-/permissions").status == 403
# With the cookie it should work
cookie = app_client.actor_cookie({"id": "root"})
response = app_client.get("/-/permissions", cookies={"ds_actor": cookie})
+ assert response.status == 200
# Should show one failure and one success
soup = Soup(response.body, "html.parser")
check_divs = soup.findAll("div", {"class": "check"})
|
debug-menu permission, closes #<I>
Also added tests for navigation menu logic.
|
simonw_datasette
|
train
|
3ab2ccc98cbd64b585d4565f2a915cc7ae877c95
|
diff --git a/mvn-scalaxb/src/main/java/org/scalaxb/maven/ScalaxbMojo.java b/mvn-scalaxb/src/main/java/org/scalaxb/maven/ScalaxbMojo.java
index <HASH>..<HASH> 100644
--- a/mvn-scalaxb/src/main/java/org/scalaxb/maven/ScalaxbMojo.java
+++ b/mvn-scalaxb/src/main/java/org/scalaxb/maven/ScalaxbMojo.java
@@ -196,8 +196,8 @@ public class ScalaxbMojo extends AbstractMojo {
getLog().warn("No XSD or WSDL files found: not running scalaxb");
} else {
List<String> inputFiles = new ArrayList<String>();
- inputFiles.addAll(schemaFiles);
inputFiles.addAll(wsdlFiles);
+ inputFiles.addAll(schemaFiles);
generateBindings(inputFiles);
}
}
|
mvn-scalaxb: Specify WSDL files before XSD files in scalaxb arguments list.
Scalaxb determines the 'module' to use by looking at the type of the first file
in the arguments list. Hence, where a project contains both XSD and WSDL files,
the WSDL files should be specified first. This is consistent with sbt-scalaxb.
|
eed3si9n_scalaxb
|
train
|
734ed92f11dbee3317a48e31d2c47f4bc645645f
|
diff --git a/aiodocker/docker.py b/aiodocker/docker.py
index <HASH>..<HASH> 100644
--- a/aiodocker/docker.py
+++ b/aiodocker/docker.py
@@ -190,8 +190,10 @@ class DockerImages(object):
if isinstance(auth, dict):
auth = json.dumps(auth).encode('utf8')
auth = base64.b64encode(auth)
- if not isinstance(auth, bytes):
- raise TypeError("auth must be base64 encoded bytes or a dictionary")
+ if not isinstance(auth, (bytes, str)):
+ raise TypeError("auth must be base64 encoded string/bytes or a dictionary")
+ if isinstance(auth, bytes):
+ auth = auth.decode('ascii')
headers['X-Registry-Auth'] = auth
if tag:
params['tag'] = tag
|
auth header needs to be a string
|
aio-libs_aiodocker
|
train
|
d53748c54dd18ba5183bff8da3f11cfd107282e6
|
diff --git a/matplotlib_colorbar/tests/test_colorbar.py b/matplotlib_colorbar/tests/test_colorbar.py
index <HASH>..<HASH> 100644
--- a/matplotlib_colorbar/tests/test_colorbar.py
+++ b/matplotlib_colorbar/tests/test_colorbar.py
@@ -2,6 +2,7 @@
""" """
# Standard library modules.
+import sys
# Third party modules.
import matplotlib.pyplot as plt
@@ -389,7 +390,8 @@ def test_colorbar_example1():
colorbar.set_ticks([0.0, 0.5, 1.0])
ax.add_artist(colorbar)
-
+@pytest.mark.skipif(sys.version_info < (3, 5),
+ reason="requires python3.5 or higher")
@image_comparison(baseline_images=['example2'], extensions=['png'], style='mpl20')
def test_colorbar_example2():
with cbook.get_sample_data('grace_hopper.png') as fp:
|
Skip 2nd example on Python <I> and <I>
|
ppinard_matplotlib-colorbar
|
train
|
a54bd88d41a73428fbf79218dd561f4c6f750b92
|
diff --git a/lib/pdk/cli/exec.rb b/lib/pdk/cli/exec.rb
index <HASH>..<HASH> 100644
--- a/lib/pdk/cli/exec.rb
+++ b/lib/pdk/cli/exec.rb
@@ -1,3 +1,5 @@
+require 'pdk'
+
module PDK
module CLI
module Exec
|
(maint) Ensure pdk/cli/exec works standalone
|
puppetlabs_pdk
|
train
|
1280ad6d19fa56e9bf6d6a261c1231326cb3d8c3
|
diff --git a/activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb b/activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb
index <HASH>..<HASH> 100644
--- a/activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb
+++ b/activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb
@@ -281,7 +281,7 @@ module ActiveRecord
end
def discard! # :nodoc:
- @connection.socket_io.reopen(IO::NULL)
+ @connection.socket_io.reopen(IO::NULL) rescue nil
@connection = nil
end
diff --git a/activerecord/test/cases/connection_adapters/connection_handler_test.rb b/activerecord/test/cases/connection_adapters/connection_handler_test.rb
index <HASH>..<HASH> 100644
--- a/activerecord/test/cases/connection_adapters/connection_handler_test.rb
+++ b/activerecord/test/cases/connection_adapters/connection_handler_test.rb
@@ -171,6 +171,46 @@ module ActiveRecord
assert_equal 3, ActiveRecord::Base.connection.select_value("SELECT COUNT(*) FROM people")
end
+ def test_forked_child_recovers_from_disconnected_parent
+ object_id = ActiveRecord::Base.connection.object_id
+ assert ActiveRecord::Base.connection.active?
+
+ rd, wr = IO.pipe
+ rd.binmode
+ wr.binmode
+
+ outer_pid = fork {
+ ActiveRecord::Base.connection.disconnect!
+
+ pid = fork {
+ rd.close
+ if ActiveRecord::Base.connection.active?
+ pair = [ActiveRecord::Base.connection.object_id,
+ ActiveRecord::Base.connection.select_value("SELECT COUNT(*) FROM people")]
+ wr.write Marshal.dump pair
+ end
+ wr.close
+
+ exit # allow finalizers to run
+ }
+
+ Process.waitpid pid
+ }
+
+ wr.close
+
+ Process.waitpid outer_pid
+ child_id, child_count = Marshal.load(rd.read)
+
+ assert_not_equal object_id, child_id
+ rd.close
+
+ assert_equal 3, child_count
+
+ # Outer connection is unaffected
+ assert_equal 6, ActiveRecord::Base.connection.select_value("SELECT 2 * COUNT(*) FROM people")
+ end
+
def test_retrieve_connection_pool_copies_schema_cache_from_ancestor_pool
@pool.schema_cache = @pool.connection.schema_cache
@pool.schema_cache.add("posts")
|
Make discard safe when it follows a manual disconnect
It doesn't have to do anything, but it shouldn't fail.
Fixes #<I>.
|
rails_rails
|
train
|
9c699af1f008406e9cc33bc533e4688c4e7dc21c
|
diff --git a/app/scripts/Mobilization/__tests__/components/MobilizationList.spec.js b/app/scripts/Mobilization/__tests__/components/MobilizationList.spec.js
index <HASH>..<HASH> 100644
--- a/app/scripts/Mobilization/__tests__/components/MobilizationList.spec.js
+++ b/app/scripts/Mobilization/__tests__/components/MobilizationList.spec.js
@@ -1,20 +1,52 @@
import React from 'react'
-
import { expect } from 'chai'
import { shallow } from 'enzyme'
import MobilizationList from '../../components/MobilizationList'
+describe('app/scripts/Mobilization/components/MobilizationList', () => {
+ let wrapper
+ const context = { router: {} }
+ const props = {
+ mobilizations: [{ id: 1 }],
+ redirectToEdit: () => {}
+ }
-describe('<MobilizationList />', () => {
- let context = { router: {} }
- let mobilizationList
-
- beforeEach(() => {
- mobilizationList = shallow(<MobilizationList />, { context })
+ before(() => {
+ wrapper = shallow(<MobilizationList {...props} />, { context })
})
- //
- // TODO: Write MobilizationListItem tests.
- //
+ describe('#render', () => {
+ it('should render one div.mobilization-list', () => {
+ expect(wrapper.find('div.mobilization-list')).to.have.length(1)
+ })
+
+ describe('component MobilizationListItemsHeader', () => {
+ it('should render one MobilizationListItemsHeader component', () => {
+ expect(wrapper.find('MobilizationListItemsHeader')).to.have.length(1)
+ })
+ })
+
+ describe('component MobilizationListItem', () => {
+ let listItem
+ beforeEach(() => {
+ wrapper = shallow(<MobilizationList {...props} />, { context })
+ listItem = wrapper.find('MobilizationListItem')
+ })
+
+ it('should render two MobilizationListItem component', () => {
+ wrapper.setProps({ ...props, mobilizations: [{ id: 1 }, { id: 2 }] })
+ expect(wrapper.find('MobilizationListItem')).to.have.length(2)
+ })
+ it('should render one MobilizationListItem component', () => {
+ expect(listItem).to.have.length(1)
+ })
+ it('should render MobilizationListItem with mobilization prop properly', () => {
+ expect(listItem.props().mobilization).to.be.deep.equal(props.mobilizations[0])
+ })
+ it('should render MobilizationListItem with redirectToEdit prop as a function', () => {
+ expect(listItem.props().redirectToEdit).to.be.a.function
+ })
+ })
+ })
})
|
Update MobilizationList component tests. #<I>
|
nossas_bonde-client
|
train
|
4606fd39624b676e89d8b21e0516f3ad77eabd0e
|
diff --git a/salt/master.py b/salt/master.py
index <HASH>..<HASH> 100644
--- a/salt/master.py
+++ b/salt/master.py
@@ -435,7 +435,7 @@ class AESFuncs(object):
'ret': clear_load['ret'],
}
expr_form = 'glob'
- timeout = 5
+ timeout = 0
if clear_load.has_key('tgt_type'):
load['tgt_type'] = clear_load['tgt_type']
expr_form = load['tgt_type']
@@ -447,11 +447,11 @@ class AESFuncs(object):
context = zmq.Context(1)
pub_sock = context.socket(zmq.PUSH)
pub_sock.connect(
- 'tcp://127.0.0.1:{0}publish_pull_port]'.format(self.opts)
+ 'tcp://127.0.0.1:{0[publish_pull_port]}'.format(self.opts)
)
pub_sock.send(salt.payload.package(payload))
# Run the client get_returns method
- return self.local._get_returns(
+ return self.local.get_returns(
jid,
self.local.check_minions(
clear_load['tgt'],
|
Clean out the last minion_publish bugs
|
saltstack_salt
|
train
|
e122b3ba90d5d195b4bae5328e8e7f5bd24fcf0a
|
diff --git a/lib/gir_ffi/builders/module_builder.rb b/lib/gir_ffi/builders/module_builder.rb
index <HASH>..<HASH> 100644
--- a/lib/gir_ffi/builders/module_builder.rb
+++ b/lib/gir_ffi/builders/module_builder.rb
@@ -48,7 +48,7 @@ module GirFFI
unless defined? @module
build_dependencies
instantiate_module
- setup_lib_for_ffi
+ setup_lib_for_ffi unless lib_already_set_up
setup_module unless already_set_up
end
@module
@@ -78,18 +78,25 @@ module GirFFI
end
def setup_lib_for_ffi
- @lib = get_or_define_module @module, :Lib
-
- unless (class << @lib; self.include? FFI::Library; end)
- @lib.extend FFI::Library
- @lib.ffi_lib_flags :global, :lazy
- libspec = gir.shared_library(@namespace)
- unless libspec.nil?
- @lib.ffi_lib(*libspec.split(/,/))
- end
+ lib.extend FFI::Library
+ lib.ffi_lib_flags :global, :lazy
+ if shared_library_specification
+ lib.ffi_lib(*shared_library_specification.split(/,/))
end
end
+ def shared_library_specification
+ @shared_library_specification ||= gir.shared_library(@namespace)
+ end
+
+ def lib_already_set_up
+ (class << lib; self; end).include? FFI::Library
+ end
+
+ def lib
+ @lib ||= get_or_define_module @module, :Lib
+ end
+
def sub_builder info
if info.info_type == :function
FunctionBuilder.new info
|
Refactor ModuleBuilder#setup_lib_for_ffi
|
mvz_gir_ffi
|
train
|
a049aaa82e67ec41cafb780079b936b3e3fda2d2
|
diff --git a/site/bitimportsfile.js b/site/bitimportsfile.js
index <HASH>..<HASH> 100644
--- a/site/bitimportsfile.js
+++ b/site/bitimportsfile.js
@@ -17,11 +17,11 @@ System = (function () {
})
// Setup js pipeline with babel
.plugin("js", {
- match: { path: /\.(js)$/ }
+ extensions: ["js"]
})
// Setup style pipeline
.plugin("style", {
- match: { path: /\.(css)$/ },
+ extensions: ["css"],
transform: "loadstyle-bits"
});
})();
diff --git a/src/bit-imports.js b/src/bit-imports.js
index <HASH>..<HASH> 100644
--- a/src/bit-imports.js
+++ b/src/bit-imports.js
@@ -158,7 +158,7 @@ Bitimports.prototype.config = function(options) {
* })
* // Setup js pipeline with babel-bits
* .plugin("js", {
- * match: { path: /\.(js)$/ },
+ * extensions: ["js"],
* transform: {
* handler: "babel",
* options: {
|
changed site and docs to show `extensions` config
|
MiguelCastillo_bit-imports
|
train
|
ff5f02be56dd76646ecb276163b7ca5a221e5a0d
|
diff --git a/mollie/api/client.py b/mollie/api/client.py
index <HASH>..<HASH> 100644
--- a/mollie/api/client.py
+++ b/mollie/api/client.py
@@ -230,6 +230,11 @@ class Client(object):
self.client_secret = client_secret
self.oauth = OAuth2Session(
client_id,
+ auto_refresh_kwargs={
+ 'client_id': client_id,
+ 'client_secret': self.client_secret,
+ },
+ auto_refresh_url='https://api.mollie.com/oauth2/tokens',
redirect_uri=redirect_uri,
scope=scope,
token=token,
|
Enable automatic refresh of expired access token
|
mollie_mollie-api-python
|
train
|
13ef56d23bbc3e736118eb59db06dd94ff59e6a2
|
diff --git a/test/tests.js b/test/tests.js
index <HASH>..<HASH> 100644
--- a/test/tests.js
+++ b/test/tests.js
@@ -343,7 +343,7 @@ describe('any type', function() {
});
var o = new SO();
- o.date = '06/21/1988';
+ o.date = 'Tue Jun 21 1988 00:00:00 GMT-0700 (PDT)';
o.date.should.be.a.Number;
o.date.should.equal(582879600000);
});
@@ -1359,7 +1359,7 @@ describe('toObject()', function() {
it('should write getter when getter returns different type', function() {
var o = new SO();
- o.magicDate = 'June 21, 1988';
+ o.magicDate = 'Tue Jun 21 1988 00:00:00 GMT-0700 (PDT)';
var obj = o.toObject();
obj.magicDate.should.be.an.instanceof(Number);
obj.magicDate.should.equal(582879600000);
|
Test now doesn't depend on timezone.
|
scotthovestadt_schema-object
|
train
|
3d5351658b2a482218db33abdf1d498b15a565fe
|
diff --git a/lib/mindbody/service.rb b/lib/mindbody/service.rb
index <HASH>..<HASH> 100644
--- a/lib/mindbody/service.rb
+++ b/lib/mindbody/service.rb
@@ -6,6 +6,7 @@ module Mb
SRC_CREDS = "SourceCredentials"
class << self; attr_accessor :endpoint; end
+ class << self; attr_accessor :doc_path; end
#Sets up the service WSDL endpoint given a Mindbody service name
def self.service(service_name)
|
add doc_path as self attribute accessor in service class
|
trisrael_mindbody
|
train
|
33a692fb075f5009d2eb97150a7fc28638a06f11
|
diff --git a/src/Chord.js b/src/Chord.js
index <HASH>..<HASH> 100644
--- a/src/Chord.js
+++ b/src/Chord.js
@@ -52,6 +52,8 @@ class ConductorChord {
moveKeysInterval: 10000,
+ checkPubKeyInterval: 2500,
+
isServer: false,
allowUpgrade: true,
@@ -131,6 +133,7 @@ class ConductorChord {
setInterval(this.node.stabilize.bind(this.node), this.config.stabilizeInterval);
setInterval(this.node.fixFingers.bind(this.node), this.config.fixFingersInterval);
setInterval(this.fileStore.relocateKeys.bind(this.fileStore), this.config.moveKeysInterval);
+ setInterval(this._checkForID.bind(this), this.config.checkPubKeyInterval);
}
//space to store, well, external nodes - if you're a server, for instance.
@@ -467,6 +470,7 @@ class ConductorChord {
setInterval(this.node.stabilize.bind(this.node), this.config.stabilizeInterval);
setInterval(this.node.fixFingers.bind(this.node), this.config.fixFingersInterval);
setInterval(this.fileStore.relocateKeys.bind(this.fileStore), this.config.moveKeysInterval);
+ setInterval(this._checkForID.bind(this), this.config.checkPubKeyInterval);
}
)
},
@@ -516,6 +520,19 @@ class ConductorChord {
if(m)
this.message(m);
}
+
+ _checkForID () {
+ if (this.chord.state.substr(0,5)!=="full_")
+ return;
+
+ this.lookupItem(this.id.idString)
+ .then(
+ result => {
+ if (result!==this.pubKeyPem)
+ this.addItem(this.id.idString, this.pubKeyPem);
+ }
+ )
+ }
}
module.exports = ConductorChord;
\ No newline at end of file
|
[Chord] Added periodic checking of pubKey entry.
It's incredibly likely that a disconnecting node could take your public
key file offline with it. Although I'm not using a proper key management
system (and won't have time to), this consideration is still particularly
important given that we have no key replication within the system...
|
FelixMcFelix_conductor-chord
|
train
|
db84bb9bd30e7d35890a97cbd380c09a541b5ca2
|
diff --git a/cmd/generic-handlers.go b/cmd/generic-handlers.go
index <HASH>..<HASH> 100644
--- a/cmd/generic-handlers.go
+++ b/cmd/generic-handlers.go
@@ -354,11 +354,11 @@ func setHTTPStatsHandler(h http.Handler) http.Handler {
h.ServeHTTP(meteredResponse, r)
if strings.HasPrefix(r.URL.Path, minioReservedBucketPath) {
- globalConnStats.incInputBytes(meteredRequest.BytesCount())
- globalConnStats.incOutputBytes(meteredResponse.BytesCount())
+ globalConnStats.incInputBytes(meteredRequest.BytesRead())
+ globalConnStats.incOutputBytes(meteredResponse.BytesWritten())
} else {
- globalConnStats.incS3InputBytes(meteredRequest.BytesCount())
- globalConnStats.incS3OutputBytes(meteredResponse.BytesCount())
+ globalConnStats.incS3InputBytes(meteredRequest.BytesRead())
+ globalConnStats.incS3OutputBytes(meteredResponse.BytesWritten())
}
})
}
diff --git a/internal/http/stats/http-traffic-recorder.go b/internal/http/stats/http-traffic-recorder.go
index <HASH>..<HASH> 100644
--- a/internal/http/stats/http-traffic-recorder.go
+++ b/internal/http/stats/http-traffic-recorder.go
@@ -20,7 +20,6 @@ package stats
import (
"io"
"net/http"
- "sync/atomic"
)
// IncomingTrafficMeter counts the incoming bytes from the underlying request.Body.
@@ -32,14 +31,14 @@ type IncomingTrafficMeter struct {
// Read calls the underlying Read and counts the transferred bytes.
func (r *IncomingTrafficMeter) Read(p []byte) (n int, err error) {
n, err = r.ReadCloser.Read(p)
- atomic.AddInt64(&r.countBytes, int64(n))
+ r.countBytes += int64(n)
return n, err
}
-// BytesCount returns the number of transferred bytes
-func (r *IncomingTrafficMeter) BytesCount() int64 {
- return atomic.LoadInt64(&r.countBytes)
+// BytesRead returns the number of transferred bytes
+func (r *IncomingTrafficMeter) BytesRead() int64 {
+ return r.countBytes
}
// OutgoingTrafficMeter counts the outgoing bytes through the responseWriter.
@@ -52,7 +51,7 @@ type OutgoingTrafficMeter struct {
// Write calls the underlying write and counts the output bytes
func (w *OutgoingTrafficMeter) Write(p []byte) (n int, err error) {
n, err = w.ResponseWriter.Write(p)
- atomic.AddInt64(&w.countBytes, int64(n))
+ w.countBytes += int64(n)
return n, err
}
@@ -61,7 +60,7 @@ func (w *OutgoingTrafficMeter) Flush() {
w.ResponseWriter.(http.Flusher).Flush()
}
-// BytesCount returns the number of transferred bytes
-func (w *OutgoingTrafficMeter) BytesCount() int64 {
- return atomic.LoadInt64(&w.countBytes)
+// BytesWritten returns the number of transferred bytes
+func (w *OutgoingTrafficMeter) BytesWritten() int64 {
+ return w.countBytes
}
|
avoid atomics for self contained reader/writers (#<I>)
read/writers are not concurrent in handlers
and self contained - no need to use atomics on
them.
avoids unnecessary contentions where it's not
required.
|
minio_minio
|
train
|
0c6f9651c4a7971c78962bfc96c6d092212651b8
|
diff --git a/pear-manager.php b/pear-manager.php
index <HASH>..<HASH> 100755
--- a/pear-manager.php
+++ b/pear-manager.php
@@ -12,6 +12,12 @@
declare(ticks = 1);
+/**
+ * Uncomment and set to your prefix.
+ */
+//define("NET_GEARMAN_JOB_CLASS_PREFIX", "");
+
+
require dirname(__FILE__)."/GearmanManager.php";
/**
@@ -38,7 +44,6 @@ class GearmanPearManager extends GearmanManager {
define('NET_GEARMAN_JOB_PATH', $this->worker_dir);
require "Net/Gearman/Worker.php";
-
$worker = new Net_Gearman_Worker($this->servers);
foreach($worker_list as $w){
@@ -127,9 +132,11 @@ class GearmanPearManager extends GearmanManager {
}
if(is_array($l)){
+ $log_message = "";
foreach($l as $ln){
- $this->log("($handle) $ln", GearmanManager::LOG_LEVEL_WORKER_INFO);
+ $log_message.= "($handle) $ln\n";
}
+ $this->log($log_message, GearmanManager::LOG_LEVEL_WORKER_INFO);
} else {
$this->log("($handle) $l", GearmanManager::LOG_LEVEL_WORKER_INFO);
}
@@ -147,9 +154,11 @@ class GearmanPearManager extends GearmanManager {
}
if(is_array($result_log)){
+ $log_message = "";
foreach($result_log as $ln){
- $this->log("($handle) $ln", GearmanManager::LOG_LEVEL_DEBUG);
+ $log_message.="($handle) $ln\n";
}
+ $this->log($log_message, GearmanManager::LOG_LEVEL_DEBUG);
} else {
$this->log("($handle) $result_log", GearmanManager::LOG_LEVEL_DEBUG);
}
@@ -164,7 +173,7 @@ class GearmanPearManager extends GearmanManager {
require "Net/Gearman/Job/Common.php";
foreach($worker_files as $file){
- $class = "Net_Gearman_Job_".substr(basename($file), 0, -4);
+ $class = NET_GEARMAN_JOB_CLASS_PREFIX.substr(basename($file), 0, -4);
include $file;
if(!class_exists($class) && !method_exists($class, "run")) {
$this->log("Class $class not found in $file or run method not present");
|
Handle custom job class prefixes. Write multi line logs as one log call so they are all together in the log.
|
brianlmoon_GearmanManager
|
train
|
23d5d9c55adf4a3551ab17326bcdab32aba1c32a
|
diff --git a/bin/pseudohiki2html.rb b/bin/pseudohiki2html.rb
index <HASH>..<HASH> 100755
--- a/bin/pseudohiki2html.rb
+++ b/bin/pseudohiki2html.rb
@@ -270,6 +270,17 @@ USAGE: #{File.basename(__FILE__)} [options]") do |opt|
end
alias set_options_from_command_line parse_command_line_options
+ def check_argv
+ case ARGV.length
+ when 0
+ if OPTIONS.need_output_file and not OPTIONS[:output]
+ raise "You must specify a file name for output"
+ end
+ when 1
+ OPTIONS.read_input_filename(ARGV[0])
+ end
+ end
+
def set_options_from_input_file(input_lines)
input_lines.each do |line|
break if FILE_HEADER_PAT !~ line
@@ -317,18 +328,7 @@ end
input_manager = InputManager.new
-def check_argv
- case ARGV.length
- when 0
- if OPTIONS.need_output_file and not OPTIONS[:output]
- raise "You must specify a file name for output"
- end
- when 1
- OPTIONS.read_input_filename(ARGV[0])
- end
-end
-
-check_argv
+OPTIONS.check_argv
input_lines = ARGF.readlines
|
moved #check_argv() to OPTIONS#check_argv()
|
nico-hn_PseudoHikiParser
|
train
|
af9380ac9e22f6f6d83e315e99784b8079ec0ddd
|
diff --git a/tests/functional/cfngin/test_recreate_failed/test_runner.py b/tests/functional/cfngin/test_recreate_failed/test_runner.py
index <HASH>..<HASH> 100644
--- a/tests/functional/cfngin/test_recreate_failed/test_runner.py
+++ b/tests/functional/cfngin/test_recreate_failed/test_runner.py
@@ -42,21 +42,26 @@ def test_deploy_bad_exit_code(deploy_bad_result: Result) -> None:
@pytest.mark.order(after="test_deploy_bad_exit_code")
def test_deploy_bad_log_messages(deploy_bad_result: Result, namespace: str) -> None:
"""Test deploy bad log messages."""
- expected_lines = [
- "cfngin.yml:deploy (in progress)",
- "recreate-failed:submitted (creating new stack)",
- "recreate-failed:submitted (rolling back new stack)",
- f"{namespace}-recreate-failed:roll back reason: "
+ assert (
+ "[runway] cfngin.yml:deploy (in progress)\n"
+ "[runway] recreate-failed:submitted (creating new stack)\n"
+ ) in deploy_bad_result.stdout, (
+ f"stdout does not match expected\n\nSTDOUT:\n{deploy_bad_result.stdout}"
+ )
+ # output may not have a "rolling back" msg - depends on API throttling
+ assert (
+ f"[runway] {namespace}-recreate-failed:roll back reason: "
"The following resource(s) failed to create: [BrokenWaitCondition]. "
- "Rollback requested by user.",
- "recreate-failed:failed (rolled back new stack)",
- "The following steps failed: recreate-failed",
- ]
- expected = "\n".join(f"[runway] {msg}" for msg in expected_lines)
- assert expected in deploy_bad_result.stdout, (
- "stdout does not match expected\n\nEXPECTED:\n"
- f"{expected}\n\nSTDOUT:\n{deploy_bad_result.stdout}"
+ "Rollback requested by user."
+ ) in deploy_bad_result.stdout, (
+ f"stdout does not match expected\n\nSTDOUT:\n{deploy_bad_result.stdout}"
)
+ # output may or may not have a "rolled back" or "failed (creating new stack)" msg
+ # depends on API throttling
+ assert (
+ "[runway] The following steps failed: recreate-failed"
+ in deploy_bad_result.stdout
+ ), f"stdout does not match expected\n\nSTDOUT:\n{deploy_bad_result.stdout}"
@pytest.mark.order(after="test_deploy_bad_log_messages")
|
improve CFNgin recreate failed functional test consistency (#<I>)
|
onicagroup_runway
|
train
|
bf4033ad650ea41bbbeeb8c077717912fbd4c2c0
|
diff --git a/lib/codesake/dawn/kb/basic_check.rb b/lib/codesake/dawn/kb/basic_check.rb
index <HASH>..<HASH> 100644
--- a/lib/codesake/dawn/kb/basic_check.rb
+++ b/lib/codesake/dawn/kb/basic_check.rb
@@ -123,27 +123,6 @@ module Codesake
"http://www.rubysec.com/advisories/#{@name}/"
end
- # Public: checks if the ruby version used for target application works a pre-requisite to exploit a particular vulnerability.
- #
- # Take the CVE-2013-1655 as example. The Puppet rubygem vulnerability
- # can be exploited only if the ruby version is 1.9.3 or following. For
- # such a reason this method will check for the ruby version used by the
- # target.
- #
- # Returns:
- # true if the running ruby is vulnerable or false otherwise
- def is_ruby_vulnerable_version?
- return false if @ruby_vulnerable_versions.nil?
-
- found = false
-
- @ruby_vulnerable_versions.each do |v|
- found = true if v == @ruby_version
- end
-
- found
- end
-
def cvss_score
return Cvss::Engine.new.score(self.cvss) unless self.cvss.nil?
" "
diff --git a/lib/codesake/dawn/kb/dependency_check.rb b/lib/codesake/dawn/kb/dependency_check.rb
index <HASH>..<HASH> 100644
--- a/lib/codesake/dawn/kb/dependency_check.rb
+++ b/lib/codesake/dawn/kb/dependency_check.rb
@@ -65,10 +65,6 @@ module Codesake
message = "Vulnerable #{dep[:name]} gem version found: #{dep[:version]}"
ret = vuln
end
- if vuln && ! @ruby_vulnerable_versions.empty?
- ret = is_ruby_vulnerable_version?
- message = "Vulnerable #{dep[:name]} gem version found: #{dep[:version]}" if ret
- end
end
end
end
|
Removed old ruby version check. It's outdated and no longer needed
|
thesp0nge_dawnscanner
|
train
|
5e0cb02804e7c0edc7e0cf6d713ba5b8f71b9b0f
|
diff --git a/cloudinary_storage/storage.py b/cloudinary_storage/storage.py
index <HASH>..<HASH> 100644
--- a/cloudinary_storage/storage.py
+++ b/cloudinary_storage/storage.py
@@ -66,3 +66,9 @@ class MediaCloudinaryStorage(Storage):
return False
response.raise_for_status()
return True
+
+ def get_available_name(self, name, max_length=None):
+ if max_length is None:
+ return name
+ else:
+ return name[:max_length]
diff --git a/tests/test_storage.py b/tests/test_storage.py
index <HASH>..<HASH> 100644
--- a/tests/test_storage.py
+++ b/tests/test_storage.py
@@ -78,6 +78,21 @@ class CloudinaryMediaStorageTests(SimpleTestCase):
with self.assertRaises(IOError):
self.storage.open('name')
+ def test_get_available_name(self):
+ name = 'name'
+ available_name = self.storage.get_available_name(name)
+ self.assertEqual(name, available_name)
+
+ def test_get_available_name_with_max_length(self):
+ name = 'name'
+ available_name = self.storage.get_available_name(name, 2)
+ self.assertEqual('na', available_name)
+
+ def test_get_available_name_with_max_length_bigger_than_name_length(self):
+ name = 'name'
+ available_name = self.storage.get_available_name(name, 10)
+ self.assertEqual(name, available_name)
+
@classmethod
def tearDownClass(cls):
cls.storage.delete(cls.file_name)
|
Added get available name method to media storage
|
klis87_django-cloudinary-storage
|
train
|
b5e16c0a947223fdda20363909ad42d89705d9f0
|
diff --git a/lib/kaminari/models/array_extension.rb b/lib/kaminari/models/array_extension.rb
index <HASH>..<HASH> 100644
--- a/lib/kaminari/models/array_extension.rb
+++ b/lib/kaminari/models/array_extension.rb
@@ -11,7 +11,12 @@ module Kaminari
# * <tt>:total_count</tt> - total_count
def initialize(original_array, options = {})
@_original_array, @_limit_value, @_offset_value, @_total_count = original_array, (options[:limit] || default_per_page).to_i, options[:offset].to_i, options[:total_count]
- super(original_array[@_offset_value, @_limit_value] || [])
+
+ if options[:total_count]
+ super original_array
+ else
+ super(original_array[@_offset_value, @_limit_value] || [])
+ end
end
# items at the specified "page"
diff --git a/spec/models/array_spec.rb b/spec/models/array_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/models/array_spec.rb
+++ b/spec/models/array_spec.rb
@@ -106,9 +106,9 @@ describe Kaminari::PaginatableArray do
end
context 'when setting total count explicitly' do
- subject { Kaminari::PaginatableArray.new((1..100).to_a, :total_count => 9999).page(5).per(10) }
+ subject { Kaminari::PaginatableArray.new((1..10).to_a, :total_count => 9999).page(5).per(10) }
it { should have(10).items }
- its(:first) { should == 41 }
+ its(:first) { should == 1 }
its(:total_count) { should == 9999 }
end
end
|
keep the whole Array if total_count is given
|
kaminari_kaminari
|
train
|
6b5a1bf4c3cc2cd701002a09419208de43173729
|
diff --git a/classes/PodsAdmin.php b/classes/PodsAdmin.php
index <HASH>..<HASH> 100644
--- a/classes/PodsAdmin.php
+++ b/classes/PodsAdmin.php
@@ -498,7 +498,21 @@ class PodsAdmin {
if ( isset( $pod->pod_data[ 'fields' ][ 'modified' ] ) )
$manage[ 'modified' ] = $pod->pod_data[ 'fields' ][ 'modified' ][ 'label' ];
- $manage = pods_var_raw( 'ui_fields_manage', $pod->pod_data[ 'options' ], $manage, null, true );
+ $manage_fields = pods_var_raw( 'ui_fields_manage', $pod->pod_data[ 'options' ] );
+
+ if ( !empty( $manage_fields ) ) {
+ $manage_new = array();
+
+ foreach ( $manage_fields as $manage_field ) {
+ if ( isset( $pod->pod_data[ 'fields' ][ $manage_field ] ) )
+ $manage_new[ $manage_field ] = $pod->pod_data[ 'fields' ][ $manage_field ];
+ elseif ( isset( $pod->pod_data[ 'object_fields' ][ $manage_field ] ) )
+ $manage_new[ $manage_field ] = $pod->pod_data[ 'object_fields' ][ $manage_field ];
+ }
+
+ if ( !empty( $manage_new ) )
+ $manage = $manage_new;
+ }
$manage = apply_filters( 'pods_admin_ui_fields_' . $pod->pod, apply_filters( 'pods_admin_ui_fields', $manage, $pod->pod, $pod ), $pod->pod, $pod );
|
Fix to admin ui manage fields handling
|
pods-framework_pods
|
train
|
ceb65862afd30aa5b15cb78daf34b8120a82ae0a
|
diff --git a/assertpy/__init__.py b/assertpy/__init__.py
index <HASH>..<HASH> 100644
--- a/assertpy/__init__.py
+++ b/assertpy/__init__.py
@@ -1 +1 @@
-from assertpy import assert_that, contents_of, fail
+from assertpy import assert_that, contents_of, fail, __version__
diff --git a/assertpy/assertpy.py b/assertpy/assertpy.py
index <HASH>..<HASH> 100644
--- a/assertpy/assertpy.py
+++ b/assertpy/assertpy.py
@@ -28,6 +28,8 @@
"""Fluent assertion framework for better, more readable tests."""
+__version__ = '0.5'
+
import re
import os
import datetime
|
added version string, <I>
|
ActivisionGameScience_assertpy
|
train
|
f1b8ca28a6287415e8d4390aba30ea3e0044eb1a
|
diff --git a/Processor.php b/Processor.php
index <HASH>..<HASH> 100644
--- a/Processor.php
+++ b/Processor.php
@@ -926,18 +926,7 @@ class Processor
$activeprty = $this->compactIri($property, $activectx, $inversectx, $value, true);
if (is_array($activeprty)) {
- foreach ($activeprty['propGens'] as $propGen) {
- $def = $this->getPropertyDefinition($activectx, $propGen);
- if ($this->removePropertyGeneratorDuplicates($properties, $property, null, $def['@id'])) {
- $activeprty = $propGen;
- break;
- }
- }
-
- if (is_array($activeprty)) {
- // fall back to term or IRI if no property generator matches
- $activeprty = $activeprty['term'];
- }
+ $activeprty = $this->removePropertyGeneratorDuplicates($properties, $property, null, $activectx, $activeprty);
}
self::mergeIntoProperty($element, $activeprty, $value);
@@ -951,18 +940,7 @@ class Processor
$activeprty = $this->compactIri($property, $activectx, $inversectx, $item, true);
if (is_array($activeprty)) {
- foreach ($activeprty['propGens'] as $propGen) {
- $def = $this->getPropertyDefinition($activectx, $propGen);
- if ($this->removePropertyGeneratorDuplicates($properties, $property, $item, $def['@id'])) {
- $activeprty = $propGen;
- break;
- }
- }
-
- if (is_array($activeprty)) {
- // fall back to term or IRI if no property generator matches
- $activeprty = $activeprty['term'];
- }
+ $activeprty = $this->removePropertyGeneratorDuplicates($properties, $property, $item, $activectx, $activeprty);
}
$def = $this->getPropertyDefinition($activectx, $activeprty);
@@ -1190,47 +1168,55 @@ class Processor
* @return bool Returns true if the duplicates have been found and
* removed for all IRIs
*/
- private function removePropertyGeneratorDuplicates(&$properties, $property, $value, $iris)
+ private function removePropertyGeneratorDuplicates(&$properties, $property, $value, $activectx, $candidates)
{
- $valueMap = array();
+ foreach ($candidates['propGens'] as $propGen) {
+ $def = $this->getPropertyDefinition($activectx, $propGen);
- foreach ($iris as $iri) {
- if (($iri === $property) || (false === isset($properties[$iri]))) {
- continue;
- }
+ $valueMap = array();
- if (null === $value) {
- $valueMap[$iri] = null;
- }
+ foreach ($def['@id'] as $iri) {
+ if (($iri === $property) || (false === isset($properties[$iri]))) {
+ continue;
+ }
+
+ if (null === $value) {
+ $valueMap[$iri] = null;
+ }
- foreach ($properties[$iri] as $key => &$val) {
- if (self::subtreeEquals($value, $val)) {
- $valueMap[$iri] = $key;
+ foreach ($properties[$iri] as $key => &$val) {
+ if (self::subtreeEquals($value, $val)) {
+ $valueMap[$iri] = $key;
+ }
}
}
- }
- if (count($valueMap) !== (count($iris) - 1)) {
- // value wasn't found for all of the property generator's IRIs
- return false;
- }
+ if (count($valueMap) !== (count($def['@id']) - 1)) {
+ // value wasn't found for all of the property generator's IRIs,
+ // continue with next property generator
+ continue;
+ }
+
+ foreach ($valueMap as $iri => $key) {
+ if (null === $key) {
+ if (0 === count($properties[$iri])) {
+ unset($properties[$iri]);
+ }
+ continue;
+ }
- foreach ($valueMap as $iri => $key) {
- if (null === $key) {
- if (0 === count($properties[$iri])) {
+ if (1 === count($properties[$iri])) {
unset($properties[$iri]);
+ } else {
+ unset($properties[$iri][$key]);
}
- continue;
}
- if (1 === count($properties[$iri])) {
- unset($properties[$iri]);
- } else {
- unset($properties[$iri][$key]);
- }
+ return $propGen;
}
- return true;
+ // fall back to term or IRI if none of the property generators matches
+ return $candidates['term'];
}
/**
|
Refactoring: Move the complete property generator compaction logic into Processor::removePropertyGeneratorDuplicates()
|
lanthaler_JsonLD
|
train
|
414a711ec750f20b3fb3d66bfa0348b9ad58f323
|
diff --git a/packages/ember-routing/lib/system/route.js b/packages/ember-routing/lib/system/route.js
index <HASH>..<HASH> 100644
--- a/packages/ember-routing/lib/system/route.js
+++ b/packages/ember-routing/lib/system/route.js
@@ -1110,7 +1110,7 @@ var Route = EmberObject.extend(ActionHandler, {
// convert the reject into a resolve and the
// transition would continue. To propagate the
// error so that it'd be handled by the `error`
- // hook, you would have to either
+ // hook, you would have to
return Ember.RSVP.reject(e);
});
}
|
[DOC] Remove extra word from beforeModel
|
emberjs_ember.js
|
train
|
b82da5c016e55ff08cc75a252641a7e19f66d280
|
diff --git a/superset/views/core.py b/superset/views/core.py
index <HASH>..<HASH> 100755
--- a/superset/views/core.py
+++ b/superset/views/core.py
@@ -2412,7 +2412,7 @@ class Superset(BaseSupersetView): # pylint: disable=too-many-public-methods
schema = request.form.get("schema") or None
template_params = json.loads(request.form.get("templateParams") or "{}")
- if len(template_params) > 0:
+ if template_params is not None and len(template_params) > 0:
# TODO: factor the Database object out of template rendering
# or provide it as mydb so we can render template params
# without having to also persist a Query ORM object.
diff --git a/tests/integration_tests/base_tests.py b/tests/integration_tests/base_tests.py
index <HASH>..<HASH> 100644
--- a/tests/integration_tests/base_tests.py
+++ b/tests/integration_tests/base_tests.py
@@ -458,6 +458,7 @@ class SupersetTestCase(TestCase):
user_name=None,
raise_on_error=False,
database_name="examples",
+ template_params=None,
):
if user_name:
self.logout()
@@ -466,7 +467,12 @@ class SupersetTestCase(TestCase):
resp = self.get_json_resp(
"/superset/validate_sql_json/",
raise_on_error=False,
- data=dict(database_id=dbid, sql=sql, client_id=client_id),
+ data=dict(
+ database_id=dbid,
+ sql=sql,
+ client_id=client_id,
+ templateParams=template_params,
+ ),
)
if raise_on_error and "error" in resp:
raise Exception("validate_sql failed")
diff --git a/tests/integration_tests/sql_validator_tests.py b/tests/integration_tests/sql_validator_tests.py
index <HASH>..<HASH> 100644
--- a/tests/integration_tests/sql_validator_tests.py
+++ b/tests/integration_tests/sql_validator_tests.py
@@ -100,6 +100,37 @@ class TestSqlValidatorEndpoint(SupersetTestCase):
PRESTO_SQL_VALIDATORS_BY_ENGINE,
clear=True,
)
+ def test_validate_sql_endpoint_mocked_params(self, get_validator_by_name):
+ """Assert that, with a mocked validator, annotations make it back out
+ from the validate_sql_json endpoint as a list of json dictionaries"""
+ if get_example_database().backend == "hive":
+ pytest.skip("Hive validator is not implemented")
+ self.login("admin")
+
+ validator = MagicMock()
+ get_validator_by_name.return_value = validator
+ validator.validate.return_value = [
+ SQLValidationAnnotation(
+ message="This worked", line_number=4, start_column=12, end_column=42,
+ )
+ ]
+
+ resp = self.validate_sql(
+ "SELECT * FROM somewhere_over_the_rainbow",
+ client_id="1",
+ raise_on_error=False,
+ template_params="null",
+ )
+
+ self.assertEqual(1, len(resp))
+ self.assertNotIn("error,", resp[0]["message"])
+
+ @patch("superset.views.core.get_validator_by_name")
+ @patch.dict(
+ "superset.config.SQL_VALIDATORS_BY_ENGINE",
+ PRESTO_SQL_VALIDATORS_BY_ENGINE,
+ clear=True,
+ )
def test_validate_sql_endpoint_failure(self, get_validator_by_name):
"""Assert that validate_sql_json errors out when the selected validator
raises an unexpected exception"""
|
accept null params for validation (#<I>)
|
apache_incubator-superset
|
train
|
2501d9b60488dac6e5c2114ca690d4be0a159478
|
diff --git a/lib/guard/haskell.rb b/lib/guard/haskell.rb
index <HASH>..<HASH> 100644
--- a/lib/guard/haskell.rb
+++ b/lib/guard/haskell.rb
@@ -76,12 +76,12 @@ module ::Guard
when [:runtime_failure, :success],
[:compile_failure, :success]
@last_run = :success
- Notifier.notify('Success')
+ Notifier.notify('Success', image: :success)
if opts.all_on_pass
run_all
end
when [:success, :success]
- Notifier.notify('Success')
+ Notifier.notify('Success', image: :success)
when [:runtime_failure, :compile_failure],
[:runtime_failure, :runtime_failure],
[:compile_failure, :compile_failure]
|
Apapt to Guard API compatibility fiasco
|
supki_guard-haskell
|
train
|
df2c141992d444362dabb50c666eb272fa566983
|
diff --git a/README.md b/README.md
index <HASH>..<HASH> 100644
--- a/README.md
+++ b/README.md
@@ -436,7 +436,7 @@ moip.payment.getOne('PAY-6PYBC8E93M2L')
#### Create a payment refund
```javascript
-moip.payment.refund('PAY-3GALBSZIUSBE')
+moip.payment.refunds.create('PAY-3GALBSZIUSBE')
.then((response) => {
console.log(response)
}).catch((err) => {
@@ -446,7 +446,7 @@ moip.payment.refund('PAY-3GALBSZIUSBE')
#### Create an order refund
```javascript
-moip.order.refund('ORD-4GALBSZIUSBE')
+moip.order.refunds.create('ORD-4GALBSZIUSBE')
.then((response) => {
console.log(response)
}).catch((err) => {
@@ -466,7 +466,7 @@ moip.refund.get('REF-1HI7RBLWH0CZ')
#### List Payment Refunds
```javascript
-moip.payment.getRefunds('PAY-3GALBSZIUSBE')
+moip.payment.refunds.get('PAY-3GALBSZIUSBE')
.then((response) => {
console.log(response)
}).catch((err) => {
@@ -476,7 +476,7 @@ moip.payment.getRefunds('PAY-3GALBSZIUSBE')
#### List Order Refunds
```javascript
-moip.order.getRefunds('ORD-4GALBSZIUSBE')
+moip.order.refunds.get('ORD-4GALBSZIUSBE')
.then((response) => {
console.log(response)
}).catch((err) => {
diff --git a/lib/client/index.js b/lib/client/index.js
index <HASH>..<HASH> 100644
--- a/lib/client/index.js
+++ b/lib/client/index.js
@@ -1,6 +1,6 @@
import { Buffer } from 'safe-buffer'
import resources from './resources'
-import { bind, reduce } from 'lodash'
+import { bind, reduce, isFunction } from 'lodash'
const environment = (isProduction) => {
return isProduction ? 'production' : 'sandbox'
@@ -19,16 +19,19 @@ const authorization = (opts) => {
return auth
}
+const binder = (func, args) => bind(func, null, args)
+
+const looper = (result, resource, authObject) => reduce(resource, (result, func, key) => {
+ result[key] = isFunction(func) ? binder(func, authObject) : looper(result, func, authObject)
+ return result
+}, {})
+
const connect = (opts) => {
const auth = authorization(opts)
const env = environment(opts.production)
return reduce(resources, (result, resource, key) => {
- result[key] = reduce(resource, (result, func, key) => {
- result[key] = bind(func, null, {auth, env})
- return result
- }, {})
-
+ result[key] = looper(result, resource, {auth, env})
return result
}, {})
}
diff --git a/lib/resources/order.js b/lib/resources/order.js
index <HASH>..<HASH> 100644
--- a/lib/resources/order.js
+++ b/lib/resources/order.js
@@ -14,6 +14,8 @@ export default {
getOne,
getAll,
create,
- refund,
- getRefunds
+ refunds: {
+ create: refund,
+ get: getRefunds
+ }
}
diff --git a/lib/resources/payment.js b/lib/resources/payment.js
index <HASH>..<HASH> 100644
--- a/lib/resources/payment.js
+++ b/lib/resources/payment.js
@@ -18,9 +18,11 @@ const getRefunds = (opts, _id) => api.get(opts, `/payments/${_id}/refunds`)
export default {
getOne,
create,
- refund,
- getRefunds,
preAuthorizationCapture,
preAuthorizationCancel,
- _authorize
+ _authorize,
+ refunds: {
+ create: refund,
+ get: getRefunds
+ }
}
diff --git a/test/refund.spec.js b/test/refund.spec.js
index <HASH>..<HASH> 100644
--- a/test/refund.spec.js
+++ b/test/refund.spec.js
@@ -42,7 +42,7 @@ describe('Moip Payment Refunds', () => {
})
it('Should successfully refund the payment', (done) => {
- moip.payment.refund(paymentModel.id)
+ moip.payment.refunds.create(paymentModel.id)
.then(({body}) => {
body.should.have.property('id')
body.should.have.property('status')
@@ -53,7 +53,7 @@ describe('Moip Payment Refunds', () => {
})
it('Should successfully get all the payment refunds', (done) => {
- moip.payment.getRefunds(paymentModel.id)
+ moip.payment.refunds.get(paymentModel.id)
.then(() => {
done()
})
@@ -96,7 +96,7 @@ describe('Moip Order Refunds', () => {
})
it('Should successfully refund the order', (done) => {
- moip.order.refund(orderId)
+ moip.order.refunds.create(orderId)
.then(({body}) => {
refundId = body.id
body.should.have.property('id')
@@ -117,7 +117,7 @@ describe('Moip Order Refunds', () => {
})
it('Should successfully get all the order refunds', (done) => {
- moip.order.getRefunds(orderId)
+ moip.order.refunds.get(orderId)
.then(() => {
done()
})
|
Changing methods to be less verbose
|
wirecardBrasil_moip-sdk-node
|
train
|
d5102fdd92e86a9cc5dd4158015af548687fe3b7
|
diff --git a/blockstack_client/actions.py b/blockstack_client/actions.py
index <HASH>..<HASH> 100644
--- a/blockstack_client/actions.py
+++ b/blockstack_client/actions.py
@@ -505,7 +505,7 @@ def cli_price(args, config_path=CONFIG_PATH, proxy=None, password=None):
operations = getattr(args, 'operations', None)
if transfer_address is not None:
- transfer_address = str(transfer_addrss)
+ transfer_address = str(transfer_address)
if operations is not None:
operations = operations.split(',')
@@ -1183,7 +1183,7 @@ def cli_register(args, config_path=CONFIG_PATH, force_data=False, tx_fee=None,
cost = costs['total_estimated_cost']
input_prompt = (
'Registering {} will cost about {} BTC.\n'
- 'Use `blockstack price` for a cost breakdown\n'
+ 'Use `blockstack price {}` for a cost breakdown\n'
'\n'
'The entire process takes 48 confirmations, or about 5 hours.\n'
'You need to have Internet access during this time period, so\n'
@@ -1191,7 +1191,7 @@ def cli_register(args, config_path=CONFIG_PATH, force_data=False, tx_fee=None,
'times.\n\n'
'Continue? (y/N): '
)
- input_prompt = input_prompt.format(fqu, cost['btc'])
+ input_prompt = input_prompt.format(fqu, cost['btc'], fqu)
user_input = raw_input(input_prompt)
user_input = user_input.lower()
@@ -1470,12 +1470,24 @@ def cli_renew(args, config_path=CONFIG_PATH, interactive=True, password=None, pr
if tx_fee is None:
tx_fee = costs['renewal_tx_fee']['satoshis']
+
+ if not local_rpc.is_api_server(config_dir=config_dir):
+ # also verify that we own the name
+ _, owner_address, _ = get_addresses_from_file(config_dir=config_dir)
+ assert owner_address
+
+ res = get_names_owned_by_address( owner_address, proxy=proxy )
+ if 'error' in res:
+ return res
+
+ if fqu not in res:
+ return {'error': 'This wallet does not own this name'}
if interactive and os.environ.get("BLOCKSTACK_CLIENT_INTERACTIVE_YES", None) != "1":
try:
input_prompt = (
'Renewing {} will cost about {} BTC.\n'
- 'Use `blockstack price "" renewal` for a cost breakdown\n'
+ 'Use `blockstack price {} "" renewal` for a cost breakdown\n'
'\n'
'The entire process takes 12 confirmations, or about 2 hours.\n'
'You need to have Internet access during this time period, so\n'
@@ -1483,7 +1495,7 @@ def cli_renew(args, config_path=CONFIG_PATH, interactive=True, password=None, pr
'times.\n\n'
'Continue? (y/N): '
)
- input_prompt = input_prompt.format(fqu, satoshis_to_btc(cost))
+ input_prompt = input_prompt.format(fqu, cost['btc'], fqu)
user_input = raw_input(input_prompt)
user_input = user_input.lower()
|
fix some typos; on renewal, verify that we own the name in the CLI
|
blockstack_blockstack-core
|
train
|
9579719c86ed1e4868e6d36693bcd57a71b5fbb7
|
diff --git a/lib/embulk/input_redis.rb b/lib/embulk/input_redis.rb
index <HASH>..<HASH> 100644
--- a/lib/embulk/input_redis.rb
+++ b/lib/embulk/input_redis.rb
@@ -13,23 +13,13 @@ module Embulk
'db' => config.param('db', :int, :default => 0),
'key_prefix' => config.param('key_prefix', :string, :default => ''),
'encode' => config.param('encode', :string, :default => 'json'),
- 'columns' => config.param('columns', :hash, :default => nil),
}
threads = config.param('threads', :int, default: 1)
- columns =
- if cs = task['columns']
- xs = []
- cs.each_with_index do |c, i|
- xs << Column.new(i, c[0], c[1])
- end
- xs
- else
- [
- Column.new(0, 'key', :string),
- Column.new(1, 'value', :string),
- ]
- end
+ columns = [
+ Column.new(0, 'key', :string),
+ Column.new(1, 'value', :string),
+ ]
puts "Redis input started."
commit_reports = yield(task, columns, threads)
@@ -44,16 +34,10 @@ module Embulk
r = ::Redis.new(:host => task['host'], :port => task['port'], :db => task['db'])
r.keys("#{task['key_prefix']}*").each do |k|
# TODO: Use MGET or something
- v = r.get(k)
case task['encode']
when 'json'
- if task['columns']
- hash = JSON.parse(v)
- xs = [k] + hash.values
- page_builder.add([k, xs])
- else
- page_builder.add([k, v])
- end
+ v = r.get(k)
+ page_builder.add([k, v])
end
end
page_builder.finish # don't forget to call finish :-)
|
Remove `columns'
|
komamitsu_embulk-plugin-redis
|
train
|
6a4de7f1a4d2303eb87dc92c03aa3e32fb6ce140
|
diff --git a/src/resources/views/character/intel/notes.blade.php b/src/resources/views/character/intel/notes.blade.php
index <HASH>..<HASH> 100644
--- a/src/resources/views/character/intel/notes.blade.php
+++ b/src/resources/views/character/intel/notes.blade.php
@@ -14,7 +14,7 @@
<!-- Button trigger modal -->
<button type="button" data-toggle="modal" data-target="#note-create-modal"
data-object-type="{{ Seat\Eveapi\Models\Character\CharacterInfo::class }}"
- data-object-id="{{ request()->character_id }}" class="btn btn-sm btn-success">
+ data-object-id="{{ request()->character->character_id }}" class="btn btn-sm btn-success">
<i class="fas fa-plus-square"></i>
Add Note
</button>
|
fix(notes): ensure add note button is containing entity id
Closes eveseat/seat#<I>
|
eveseat_web
|
train
|
5110bcf454997a81131e92a7bbd61413443b5b5a
|
diff --git a/core/css.js b/core/css.js
index <HASH>..<HASH> 100644
--- a/core/css.js
+++ b/core/css.js
@@ -1266,7 +1266,7 @@ Blockly.Css.CONTENT = [
'}',
'.scratchCategoryMenu {',
- 'width: 72px;',
+ 'width: 60px;',
'background: $colour_toolbox;',
'color: $colour_toolboxText;',
'font-size: .7rem;',
diff --git a/core/toolbox.js b/core/toolbox.js
index <HASH>..<HASH> 100644
--- a/core/toolbox.js
+++ b/core/toolbox.js
@@ -86,10 +86,10 @@ Blockly.Toolbox = function(workspace) {
/**
* Width of the toolbox, which changes only in vertical layout.
- * This is the sum of the width of the flyout (250) and the category menu (72).
+ * This is the sum of the width of the flyout (250) and the category menu (60).
* @type {number}
*/
-Blockly.Toolbox.prototype.width = 322;
+Blockly.Toolbox.prototype.width = 310;
/**
* Height of the toolbox, which changes only in horizontal layout.
|
Widen the category menu
Add 8px to the category menu width so that more category names in other languages fit in the space. It doesn’t solve all of them, but it does help for most. The add extension button width will also need adjustment, but that’s in gui.
|
LLK_scratch-blocks
|
train
|
4097cce207fd19580c02193245762110d21e8bed
|
diff --git a/lib/cli.js b/lib/cli.js
index <HASH>..<HASH> 100644
--- a/lib/cli.js
+++ b/lib/cli.js
@@ -6,7 +6,8 @@ function help() {
' -f Output the result as a file, give the name of the file. If no filename is given, the name will be the domain of the url'
);
console.log(' --harFile the HAR file name. If no filename, the name will be $domain.har');
- console.log(' -b The browser to use. Supported values are:' + validBrowsers + ', default being chrome.');
+ console.log(' -b The browser to use. Supported values are:' + validBrowsers +
+ ', default being chrome. To use PhantomJS, you need the coming 2.0 release.');
console.log(' -n the number of times to run the test, default being 3');
console.log(
' --userAgent Set the user agent. Default is the one by the browser you use. Only works with Chrome and Firefox');
|
info about phantomjs 2
|
sitespeedio_browsertime
|
train
|
112bbb5295a24535983222f35866eeaacd6b1924
|
diff --git a/samples/demos/src/com/actionbarsherlock/sample/demos/FeatureToggles.java b/samples/demos/src/com/actionbarsherlock/sample/demos/FeatureToggles.java
index <HASH>..<HASH> 100644
--- a/samples/demos/src/com/actionbarsherlock/sample/demos/FeatureToggles.java
+++ b/samples/demos/src/com/actionbarsherlock/sample/demos/FeatureToggles.java
@@ -47,7 +47,7 @@ public class FeatureToggles extends SherlockActivity implements ActionBar.TabLis
//See 'ListNavigation.java' for an explanation about this:
int layoutRes = R.layout.sherlock_spinner_item;
- int dropRes = android.R.layout.simple_spinner_dropdown_item;
+ int dropRes = R.layout.sherlock_spinner_dropdown_item;
if (SampleList.THEME == R.style.Theme_Sherlock_Light_DarkActionBar) {
layoutRes = R.layout.sherlock_spinner_item_light_dark;
dropRes = R.layout.sherlock_spinner_dropdown_item_light_dark;
|
Update 'Feature Toggles' for new dropdown list navigation. Closes #<I>.
|
JakeWharton_ActionBarSherlock
|
train
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.