hash
stringlengths
40
40
diff
stringlengths
131
114k
message
stringlengths
7
980
project
stringlengths
5
67
split
stringclasses
1 value
1fa282af186f9947a8be0d56b9b2da0e95afdb0c
diff --git a/README.md b/README.md index <HASH>..<HASH> 100644 --- a/README.md +++ b/README.md @@ -622,6 +622,15 @@ $gateway = OmniPay::create('SagePay\Form')->initialize([ The `encryptionKey` is generated in "My Sage Pay" when logged in as the administrator. +Note that this gateway will assume all inout data (names, addresses etc.) +are UTF-8 encoded. +It will then recode the data to ISO8859-1 before encrypting it for the gateway, +as the gateway strictly accepts ISO8859-1 only, regardless of what encoding is +used to submit the form from the merchant site. +If you do not want this conversion to happen, it can be disabled with this parameter: + + 'disableUtf8Decode' => true, + The authorize must be given a `returnUrl` (the return URL on success, or on failure if no separate `failureUrl` is provided). @@ -639,10 +648,11 @@ At the gateway, the user will authenticate or authorise their credit card, perform any 3D Secure actions that may be requested, then will return to the merchant site. -To get the result, the transaction is "completed": +To get the result details, the transaction is "completed": ```php -// The result will in read and decrypted from the return URL query parameters: +// The result will be read and decrypted from the return URL (or failure URL) +// query parameters: $result = $gateway->completeAuthorize()->send(); @@ -651,6 +661,14 @@ $result->getTransactionReference(); // etc. ``` +If you already have the encrypted response string, then it can be optionally +passed in: + + $result = $gateway->completeAuthorize(['crypt' => $crypt])->send(); + +This should normally not be necessary, but is handy for testing or if the +current page query parameters are not available in a particular architecture. + ### Form Purchase This is the same as `authorize()`, but the `purchase()` request is used instead, diff --git a/src/Message/Form/AuthorizeRequest.php b/src/Message/Form/AuthorizeRequest.php index <HASH>..<HASH> 100644 --- a/src/Message/Form/AuthorizeRequest.php +++ b/src/Message/Form/AuthorizeRequest.php @@ -189,18 +189,26 @@ class AuthorizeRequest extends DirectAuthorizeRequest // Build the data in a query string. - // CHECKME: what happens with UTF-8 data? Do we need to convert - // any special characters not in the correct ranges? - // What about options for URL encoding of other characters? + // The encrypted data MUST be ISO8859-1 regardless of what encoding + // is used to submit the form, because that is how the gateway treats + // the data internally. + // This package assumes input data will be UTF-8 by default, and will + // comvert it accordingly. This can be disabled if the data is already + // ISO8859-1. + // For the Server and Direct gateway methods, the POST encoding type + // will tell the gateway how to interpret the character encoding, and + // the gateway will do any encoding conversions necessary. // We cannot use http_build_query() because the gateway does // not decode the string as any standard encoded query string. // We just join the names and values with "=" and "&" and the // gateway somehow decodes ambiguous strings. + $disableUtf8Decode = (bool)$this->getDisableUtf8Decode(); + $query = []; foreach ($data as $name => $value) { - $query[] = $name . '=' . $value; + $query[] = $name . '=' . ($disableUtf8Decode ? $value : utf8_decode($value)); } $query = implode('&', $query); diff --git a/src/Traits/GatewayParamsTrait.php b/src/Traits/GatewayParamsTrait.php index <HASH>..<HASH> 100644 --- a/src/Traits/GatewayParamsTrait.php +++ b/src/Traits/GatewayParamsTrait.php @@ -237,4 +237,24 @@ trait GatewayParamsTrait { return $this->setParameter('billingForShipping', $value); } + + /** + * @return mixed + */ + public function getDisableUtf8Decode() + { + return $this->getParameter('disableUtf8Decode'); + } + + /** + * The Form API will convert all input data from an assumed UTF-8 + * encoding to ISO8859-1 by default, unless disabled here. + * + * @param mixed $value Will be evaluated as boolean. + * @return $this + */ + public function setDisableUtf8Decode($value) + { + return $this->setParameter('disableUtf8Decode', $value); + } }
Issue #<I> Recode Sage Pay Form data from UTF-8 to ISO<I>-1 by default. Provide an option to disable this for when the merchant site handles it already. In the vast number of cases, the conversion should stand. That is, until Sage Pay get their ISO<I> technical debt sorted out for good.
thephpleague_omnipay-sagepay
train
b60859551bbc40e8917cc3747509c9a21ebc0b65
diff --git a/Tests/Auth/OpenID/StoreTest.php b/Tests/Auth/OpenID/StoreTest.php index <HASH>..<HASH> 100644 --- a/Tests/Auth/OpenID/StoreTest.php +++ b/Tests/Auth/OpenID/StoreTest.php @@ -539,8 +539,9 @@ explicitly'); $db =& DB::connect($dsn); if (PEAR::isError($db)) { - $this->fail("MySQL database connection failed: " . - $db->getMessage()); + print "MySQL database connection failed: " . + $db->getMessage(); + $this->pass(); return; }
[project @ Make tests pass when MySQL connection cannot be established]
openid_php-openid
train
1a42c10ebd4fe0263d07ec969cd99c126a5fe1c9
diff --git a/src/Api/Api.php b/src/Api/Api.php index <HASH>..<HASH> 100644 --- a/src/Api/Api.php +++ b/src/Api/Api.php @@ -185,12 +185,17 @@ abstract class Api implements ApiInterface $stack->push(Middleware::mapRequest(function (RequestInterface $request) { $config = $this->config; - return $request - ->withHeader('Stripe-Version', $config->getApiVersion()) - ->withHeader('Idempotency-Key', $config->getIdempotencyKey()) - ->withHeader('User-Agent', 'Cartalyst-Stripe/'.$config->getVersion()) - ->withHeader('Authorization', 'Basic '.base64_encode($config->getApiKey())) - ; + if ($idempotencykey = $config->getIdempotencyKey()) { + $request = $request->withHeader('Idempotency-Key', $idempotencykey); + } + + $request = $request->withHeader('Stripe-Version', $config->getApiVersion()); + + $request = $request->withHeader('User-Agent', 'Cartalyst-Stripe/'.$config->getVersion()); + + $request = $request->withHeader('Authorization', 'Basic '.base64_encode($config->getApiKey())); + + return $request; })); $stack->push(Middleware::retry(function ($retries, RequestInterface $request, ResponseInterface $response = null, TransferException $exception = null) {
Fix issue with idempotency key. Fixes: #<I>
cartalyst_stripe
train
f694d3f75cddd3797f75f1f4b61c6fccf4c8125d
diff --git a/src/toil/test/src/toilContextManagerTest.py b/src/toil/test/src/toilContextManagerTest.py index <HASH>..<HASH> 100644 --- a/src/toil/test/src/toilContextManagerTest.py +++ b/src/toil/test/src/toilContextManagerTest.py @@ -13,6 +13,8 @@ # limitations under the License. from __future__ import absolute_import +import os +import tempfile from toil.common import Toil, ToilContextManagerException from toil.job import Job from toil.test import ToilTest, slow @@ -32,6 +34,25 @@ class ToilContextManagerTest(ToilTest): toil = Toil(options) self.assertRaises(ToilContextManagerException, toil.start, HelloWorld()) + def testExportAfterFailedExport(self): + options = Job.Runner.getDefaultOptions(self._getTestJobStorePath()) + exportLocation = tempfile.mkstemp() + try: + with Toil(options) as toil: + _ = toil.start(HelloWorld()) + # oh no, an error! :( + raise RuntimeError("we died after workflow completion but before our export finished") + except: + pass + options.restart = True + with Toil(options) as toil: + fileID = toil.restart() + # Hopefully the error didn't cause us to lose all our work! + toil.exportFile(fileID, 'file://' + exportLocation) + with open(exportLocation) as f: + # The file should have all our content + self.assertEquals(f.read(), "Hello, World!") + os.remove(exportLocation) class HelloWorld(Job): def __init__(self): @@ -39,7 +60,7 @@ class HelloWorld(Job): def run(self, fileStore): fileID = self.addChildJobFn(childFn, cores=1, memory='1M', disk='1M').rv() - self.addFollowOn(FollowOn(fileID)) + return self.addFollowOn(FollowOn(fileID)).rv() def childFn(job): @@ -58,4 +79,4 @@ class FollowOn(Job): tempFilePath = "/".join([tempDir, 'LocalCopy']) with fileStore.readGlobalFileStream(self.fileId) as globalFile: with open(tempFilePath, "w") as localFile: - localFile.write(globalFile.read()) + return localFile.write(globalFile.read())
Add a test to show that failures in exportFile doom your workflow
DataBiosphere_toil
train
60705961a851c5f099257555df7ea19d36d30ad5
diff --git a/lib/handlers/bin.js b/lib/handlers/bin.js index <HASH>..<HASH> 100644 --- a/lib/handlers/bin.js +++ b/lib/handlers/bin.js @@ -549,7 +549,7 @@ module.exports = Observable.extend({ edit: editPermalink, html: editPermalink, js: editPermalink, - title: utils.titleForBin(bin), + summary: utils.titleForBin(bin), allowUpdate: !!bin.streamingKey, checksum: bin.streamingKey });
Use summary in renderCreated.
jsbin_jsbin
train
5da925d7d6e1df9b50c33d599658986b73f8a27f
diff --git a/lib/mongoid/persistence.rb b/lib/mongoid/persistence.rb index <HASH>..<HASH> 100644 --- a/lib/mongoid/persistence.rb +++ b/lib/mongoid/persistence.rb @@ -164,7 +164,17 @@ module Mongoid end alias :save :upsert - module ClassMethods + # change the updated_at field to now + # + def touch + if is_a?(Mongoid::Timestamps::Updated) + collection.update( self.atomic_selector, + {'$set' => { updated_at: Time.now.utc}} ) + end + true + end + + module ClassMethods #:nodoc: # Create a new document. This will instantiate a new document and # insert it in a single call. Will always return the document diff --git a/spec/mongoid/persistence_spec.rb b/spec/mongoid/persistence_spec.rb index <HASH>..<HASH> 100644 --- a/spec/mongoid/persistence_spec.rb +++ b/spec/mongoid/persistence_spec.rb @@ -622,6 +622,35 @@ describe Mongoid::Persistence do end end + describe "#touch" do + + context "with a document include Mongoid::Timestamps::Updated" do + let(:updated_at) { 2.days.ago } + let(:agent) { Agent.create(:updated_at => updated_at) } + before { agent.touch } + let(:agent_updated_at) { Agent.find(agent.id).updated_at } + + it 'should update updated_at field' do + agent_updated_at.should_not be_within(1).of(updated_at) + end + + it 'should define updated_at field to now' do + agent_updated_at.should be_within(1).of(Time.now.utc) + end + + end + + context "with a document not include Mongoid::Timestamps::Updated" do + let(:person) { Person.create } + before { person.touch } + it 'should not update updated_at field' do + Person.collection.find_one({:_id => person.id}).keys.should_not include("updated_at") + end + + end + + end + describe "#update_attribute" do let(:post) do
add method #touch to update the updated_at field if Mongoid::Timestamps::Updated is include
mongodb_mongoid
train
ad6af34914606971ab13c0df25da7ecc20a207f8
diff --git a/lib/sitespeed.js b/lib/sitespeed.js index <HASH>..<HASH> 100644 --- a/lib/sitespeed.js +++ b/lib/sitespeed.js @@ -22,6 +22,7 @@ var crawler = require('./crawler'), urlParser = require('url'), log = require('winston'); + function Sitespeed() {} Sitespeed.prototype.run = function(config, finshedCb) { @@ -270,7 +271,6 @@ function createDataDir(dataDir, cb) { if (err) { log.log('error', 'Couldn\'t create the data dir:' + dataDir + '. Probably the user starting sitespeed doesn\'t have the privileges to create the directory. ' + err); - throw err; } cb(err, null); });
if we can't create the dir, log and exit
sitespeedio_sitespeed.io
train
7d22e75caf7a7d28de71fc703f7da6efbb4870ec
diff --git a/lib/fluent/command/binlog_reader.rb b/lib/fluent/command/binlog_reader.rb index <HASH>..<HASH> 100644 --- a/lib/fluent/command/binlog_reader.rb +++ b/lib/fluent/command/binlog_reader.rb @@ -21,6 +21,7 @@ require 'fluent/msgpack_factory' require 'fluent/formatter' require 'fluent/plugin' require 'fluent/config/element' +require 'fluent/engine' class FluentBinlogReader SUBCOMMAND = %w(cat head formats)
Error: uninitialized constant Fluent::Engine
fluent_fluentd
train
bdc3585844a3feb7025a5c2d028ac789ddef5ae3
diff --git a/foursquare/__init__.py b/foursquare/__init__.py index <HASH>..<HASH> 100644 --- a/foursquare/__init__.py +++ b/foursquare/__init__.py @@ -16,9 +16,6 @@ except ImportError: import inspect import math import time -from six.moves.urllib import parse -from six.moves import xrange -import six import sys # 3rd party libraries that might not be present during initial install @@ -26,6 +23,10 @@ import sys try: import requests + from six.moves.urllib import parse + from six.moves import xrange + import six + # Monkey patch to requests' json using ujson when available; # Otherwise it wouldn't affect anything requests.models.json = json @@ -56,7 +57,7 @@ API_VERSION_DAY = '23' API_VERSION = '{year}{month}{day}'.format(year=API_VERSION_YEAR, month=API_VERSION_MONTH, day=API_VERSION_DAY) # Library versioning matches supported foursquare API version -__version__ = '{year}.{month}.{day}'.format(year=API_VERSION_YEAR, month=API_VERSION_MONTH, day=API_VERSION_DAY) +__version__ = '{year}.{month}.{day}a'.format(year=API_VERSION_YEAR, month=API_VERSION_MONTH, day=API_VERSION_DAY) __author__ = u'Mike Lewis' AUTH_ENDPOINT = 'https://foursquare.com/oauth2/authenticate'
python3 compatability fixes and minor version bump
mLewisLogic_foursquare
train
0410e52d4bbf35b9b85d4961f0c6e4ddb74848ae
diff --git a/src/frontend/org/voltdb/compilereport/ReportMaker.java b/src/frontend/org/voltdb/compilereport/ReportMaker.java index <HASH>..<HASH> 100644 --- a/src/frontend/org/voltdb/compilereport/ReportMaker.java +++ b/src/frontend/org/voltdb/compilereport/ReportMaker.java @@ -643,17 +643,16 @@ public class ReportMaker { String nameLink = ""; // not a warning during compiling procedures, must from the schema if (procName.compareToIgnoreCase("null") == 0) { - nameLink += "<a href='#s-"; String schemaName = ""; String warningMsg = warning.getMessage().toLowerCase(); if (warningMsg.contains("table ")) { int begin = warningMsg.indexOf("table ") + 6; int end = (warningMsg.substring(begin)).indexOf(" "); - schemaName += warningMsg.substring(begin, begin + end); + schemaName = warningMsg.substring(begin, begin + end); } - nameLink += schemaName + "'>" + schemaName.toUpperCase() + "</a>"; + nameLink = "<a href='#s-" + schemaName + "'>" + schemaName.toUpperCase() + "</a>"; } else { - nameLink += "<a href='#p-" + procName.toLowerCase() + "'>" + procName + "</a>"; + nameLink = "<a href='#p-" + procName.toLowerCase() + "'>" + procName + "</a>"; } sb.append("<tr><td>").append(nameLink).append("</td><td>").append(warning.getMessage()).append("</td></tr>\n"); }
ENG-<I>, ENG-<I>, ENG-<I>, ENG-<I>: changes based on Paul's review.
VoltDB_voltdb
train
72508b7da9b95bed63bc3e8fd8f548127c601723
diff --git a/src/main/java/com/github/kongchen/swagger/docgen/spring/SpringMvcApiReader.java b/src/main/java/com/github/kongchen/swagger/docgen/spring/SpringMvcApiReader.java index <HASH>..<HASH> 100644 --- a/src/main/java/com/github/kongchen/swagger/docgen/spring/SpringMvcApiReader.java +++ b/src/main/java/com/github/kongchen/swagger/docgen/spring/SpringMvcApiReader.java @@ -106,6 +106,13 @@ public class SpringMvcApiReader { List<Authorization> authorizations = Collections.emptyList();//TODO String newBasePath=""; String description=""; + + // Add the description from the controller api + Class<?> controller = resource.getControllerClass(); + if( controller != null && controller.isAnnotationPresent(Api.class)) { + Api api = (Api) controller.getAnnotation(Api.class); + description = api.description(); + } resourcePath = resource.getControllerMapping(); newBasePath=generateBasePath(apiSource.getBasePath(),resourcePath);
Add descriptions to the api listing Noticed that the descriptions were not being populated in the api listing (in service.json). Added code to populate the description from the resouce controller's api annotation.
kongchen_swagger-maven-plugin
train
d581de11a6a971e8f51b0fa7a82b0c37a37f1d55
diff --git a/gulpfile.js b/gulpfile.js index <HASH>..<HASH> 100644 --- a/gulpfile.js +++ b/gulpfile.js @@ -46,6 +46,6 @@ gulp.task('watch', function() { gulp.task('default', ['dev']); -gulp.task('dev', ['build', 'test', 'watch']); +gulp.task('dev', ['test', 'watch']); gulp.task('build', ['test', 'scripts']); \ No newline at end of file
Update gulp dev task to no longer build scripts
jbmusso_grex
train
1000d106c3f1afaedf68981094c05be8608ba993
diff --git a/nfpm.go b/nfpm.go index <HASH>..<HASH> 100644 --- a/nfpm.go +++ b/nfpm.go @@ -153,6 +153,11 @@ func (c *Config) expandEnvVars() { c.Info.Version = os.Expand(c.Info.Version, c.envMappingFunc) c.Info.Prerelease = os.Expand(c.Info.Prerelease, c.envMappingFunc) c.Info.Arch = os.Expand(c.Info.Arch, c.envMappingFunc) + for _, override := range c.Overrides { + for i, dep := range override.Depends { + override.Depends[i] = os.Expand(dep, c.envMappingFunc) + } + } // Vendor field c.Info.Vendor = os.Expand(c.Info.Vendor, c.envMappingFunc) diff --git a/nfpm_test.go b/nfpm_test.go index <HASH>..<HASH> 100644 --- a/nfpm_test.go +++ b/nfpm_test.go @@ -301,6 +301,25 @@ func TestOptionsFromEnvironment(t *testing.T) { require.NoError(t, err) require.Equal(t, packager, info.RPM.Packager) }) + + t.Run("depends", func(t *testing.T) { + os.Clearenv() + os.Setenv("VERSION", version) + info, err := nfpm.Parse(strings.NewReader(`--- +name: foo +overrides: + deb: + depends: + - package (= ${VERSION}) + rpm: + depends: + - package = ${VERSION}`)) + require.NoError(t, err) + require.Len(t, info.Overrides["deb"].Depends, 1) + require.Equal(t, "package (= 1.0.0)", info.Overrides["deb"].Depends[0]) + require.Len(t, info.Overrides["rpm"].Depends, 1) + require.Equal(t, "package = 1.0.0", info.Overrides["rpm"].Depends[0]) + }) } func TestOverrides(t *testing.T) {
feat: expand ENV for dependencies versions (#<I>)
goreleaser_nfpm
train
5273e6c73d4db59077b7822ed0d85d4bc0b58819
diff --git a/source/org/jivesoftware/smack/ChatManager.java b/source/org/jivesoftware/smack/ChatManager.java index <HASH>..<HASH> 100644 --- a/source/org/jivesoftware/smack/ChatManager.java +++ b/source/org/jivesoftware/smack/ChatManager.java @@ -106,6 +106,10 @@ public class ChatManager { } else { chat = getThreadChat(message.getThread()); + if (chat == null) { + // Try to locate the chat based on the sender of the message + chat = getUserChat(StringUtils.parseBareAddress(message.getFrom())); + } } if(chat == null) {
Improved logic to find correct chat. If search for threadID fails then fallback to sender of message. git-svn-id: <URL>
igniterealtime_Smack
train
97da7782bc4377e1d2407be69683ed71761457a5
diff --git a/lib/waterline/utils/query/transform-populated-child-records.js b/lib/waterline/utils/query/transform-populated-child-records.js index <HASH>..<HASH> 100644 --- a/lib/waterline/utils/query/transform-populated-child-records.js +++ b/lib/waterline/utils/query/transform-populated-child-records.js @@ -191,8 +191,9 @@ module.exports = function transformPopulatedChildRecords(joins, records, WLModel // If `undefined` is specified explicitly, use `null` instead. if (_.isUndefined(record[key])) { // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // (TODO: revisit this -- would be better and more consistent to strip them out - // instead, but that needs to be verified for compatibility) + // (TODO: revisit this -- would be better and more consistent to leave them alone + // since they get verified (and a warning potentially logged) over in processAllRecords(). + // ...but that needs to be verified for compatibility) // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - record[key] = null; }//>-
Clarify TODO about RHS values of undefined coming back from the adapter in transformPopulatedChildRecords().
balderdashy_waterline
train
c11f11359b8915533ad886015d57298e3daeb821
diff --git a/flink-runtime/src/main/java/org/apache/flink/runtime/state/DefaultOperatorStateBackend.java b/flink-runtime/src/main/java/org/apache/flink/runtime/state/DefaultOperatorStateBackend.java index <HASH>..<HASH> 100644 --- a/flink-runtime/src/main/java/org/apache/flink/runtime/state/DefaultOperatorStateBackend.java +++ b/flink-runtime/src/main/java/org/apache/flink/runtime/state/DefaultOperatorStateBackend.java @@ -636,7 +636,7 @@ public class DefaultOperatorStateBackend implements OperatorStateBackend { private PartitionableListState(PartitionableListState<S> toCopy) { - this(toCopy.stateMetaInfo, toCopy.internalListCopySerializer.copy(toCopy.internalList)); + this(toCopy.stateMetaInfo.deepCopy(), toCopy.internalListCopySerializer.copy(toCopy.internalList)); } public void setStateMetaInfo(RegisteredOperatorBackendStateMetaInfo<S> stateMetaInfo) { diff --git a/flink-runtime/src/main/java/org/apache/flink/runtime/state/HeapBroadcastState.java b/flink-runtime/src/main/java/org/apache/flink/runtime/state/HeapBroadcastState.java index <HASH>..<HASH> 100644 --- a/flink-runtime/src/main/java/org/apache/flink/runtime/state/HeapBroadcastState.java +++ b/flink-runtime/src/main/java/org/apache/flink/runtime/state/HeapBroadcastState.java @@ -66,7 +66,7 @@ public class HeapBroadcastState<K, V> implements BackendWritableBroadcastState<K } private HeapBroadcastState(HeapBroadcastState<K, V> toCopy) { - this(toCopy.stateMetaInfo, toCopy.internalMapCopySerializer.copy(toCopy.backingMap)); + this(toCopy.stateMetaInfo.deepCopy(), toCopy.internalMapCopySerializer.copy(toCopy.backingMap)); } @Override diff --git a/flink-runtime/src/main/java/org/apache/flink/runtime/state/RegisteredBroadcastBackendStateMetaInfo.java b/flink-runtime/src/main/java/org/apache/flink/runtime/state/RegisteredBroadcastBackendStateMetaInfo.java index <HASH>..<HASH> 100644 --- a/flink-runtime/src/main/java/org/apache/flink/runtime/state/RegisteredBroadcastBackendStateMetaInfo.java +++ b/flink-runtime/src/main/java/org/apache/flink/runtime/state/RegisteredBroadcastBackendStateMetaInfo.java @@ -52,6 +52,23 @@ public class RegisteredBroadcastBackendStateMetaInfo<K, V> { this.valueSerializer = Preconditions.checkNotNull(valueSerializer); } + public RegisteredBroadcastBackendStateMetaInfo(RegisteredBroadcastBackendStateMetaInfo<K, V> copy) { + + Preconditions.checkNotNull(copy); + + this.name = copy.name; + this.assignmentMode = copy.assignmentMode; + this.keySerializer = copy.keySerializer.duplicate(); + this.valueSerializer = copy.valueSerializer.duplicate(); + } + + /** + * Creates a deep copy of the itself. + */ + public RegisteredBroadcastBackendStateMetaInfo<K, V> deepCopy() { + return new RegisteredBroadcastBackendStateMetaInfo<>(this); + } + public String getName() { return name; } diff --git a/flink-runtime/src/main/java/org/apache/flink/runtime/state/RegisteredOperatorBackendStateMetaInfo.java b/flink-runtime/src/main/java/org/apache/flink/runtime/state/RegisteredOperatorBackendStateMetaInfo.java index <HASH>..<HASH> 100644 --- a/flink-runtime/src/main/java/org/apache/flink/runtime/state/RegisteredOperatorBackendStateMetaInfo.java +++ b/flink-runtime/src/main/java/org/apache/flink/runtime/state/RegisteredOperatorBackendStateMetaInfo.java @@ -57,6 +57,22 @@ public class RegisteredOperatorBackendStateMetaInfo<S> { this.assignmentMode = Preconditions.checkNotNull(assignmentMode); } + private RegisteredOperatorBackendStateMetaInfo(RegisteredOperatorBackendStateMetaInfo<S> copy) { + + Preconditions.checkNotNull(copy); + + this.name = copy.name; + this.partitionStateSerializer = copy.partitionStateSerializer.duplicate(); + this.assignmentMode = copy.assignmentMode; + } + + /** + * Creates a deep copy of the itself. + */ + public RegisteredOperatorBackendStateMetaInfo<S> deepCopy() { + return new RegisteredOperatorBackendStateMetaInfo<>(this); + } + public String getName() { return name; }
[FLINK-<I>][state] Fix concurrency problem in DefaultOperatorStateBackend. This closes #<I>.
apache_flink
train
c92e9401efc712059e10cd9fb673fd87240c4792
diff --git a/ui/js/values.js b/ui/js/values.js index <HASH>..<HASH> 100644 --- a/ui/js/values.js +++ b/ui/js/values.js @@ -22,6 +22,7 @@ treeherder.value("thPlatformNameMap", { "android-2-3-armv7-api9": "Android 2.3 API9", "android-4-0": "Android 4.0", "android-4-0-armv7-api10": "Android 4.0 API10+", + "android-4-0-armv7-api11": "Android 4.0 API11+", "android-4-2-x86": "Android 4.2 x86", "android-4-2": "Android 4.2", "android-4-3": "Android 4.3",
Bug <I> - Add support for split Android APK - splits off api-<I> now
mozilla_treeherder
train
17f0c1e9e8a5bfa7c4d2e1632c3b8b91f4678f03
diff --git a/actionpack/lib/action_dispatch/testing/assertions/routing.rb b/actionpack/lib/action_dispatch/testing/assertions/routing.rb index <HASH>..<HASH> 100644 --- a/actionpack/lib/action_dispatch/testing/assertions/routing.rb +++ b/actionpack/lib/action_dispatch/testing/assertions/routing.rb @@ -168,7 +168,7 @@ module ActionDispatch # ROUTES TODO: These assertions should really work in an integration context def method_missing(selector, *args, &block) - if @controller && @router.named_routes.helpers.include?(selector) + if @controller && @router && @router.named_routes.helpers.include?(selector) @controller.send(selector, *args, &block) else super diff --git a/actionpack/test/controller/integration_test.rb b/actionpack/test/controller/integration_test.rb index <HASH>..<HASH> 100644 --- a/actionpack/test/controller/integration_test.rb +++ b/actionpack/test/controller/integration_test.rb @@ -430,3 +430,50 @@ class MetalIntegrationTest < ActionController::IntegrationTest assert_equal 'http://www.example.com/foo', url_for(:controller => "foo") end end + +class ApplicationIntegrationTest < ActionController::IntegrationTest + class TestController < ActionController::Base + def index + render :text => "index" + end + end + + def self.call(env) + routes.call(env) + end + + def self.routes + @routes ||= ActionDispatch::Routing::RouteSet.new + end + + routes.draw do + match 'foo', :to => 'application_integration_test/test#index', :as => :foo + match 'bar', :to => 'application_integration_test/test#index', :as => :bar + end + + def app + self.class + end + + test "includes route helpers" do + assert_equal '/foo', foo_path + assert_equal '/bar', bar_path + end + + test "route helpers after controller access" do + get '/foo' + assert_equal '/foo', foo_path + + get '/bar' + assert_equal '/bar', bar_path + end + + test "missing route helper before controller access" do + assert_raise(NameError) { missing_path } + end + + test "missing route helper after controller access" do + get '/foo' + assert_raise(NameError) { missing_path } + end +end
Fix stack overflow bug in integration test router helpers
rails_rails
train
0976b05ba1de93984e51a8c11c2bfb7b93955da2
diff --git a/PySimpleGUI.py b/PySimpleGUI.py index <HASH>..<HASH> 100644 --- a/PySimpleGUI.py +++ b/PySimpleGUI.py @@ -124,8 +124,6 @@ from typing import List, Any, Union, Tuple, Dict # because this code has to r from random import randint import warnings - - g_time_start = 0 g_time_end = 0 g_time_delta = 0 @@ -7249,7 +7247,9 @@ def PackFormIntoFrame(form, containing_frame, toplevel_form): element.TKColFrame = TkFixedFrame(tk_row_frame) PackFormIntoFrame(element, element.TKColFrame.TKFrame, toplevel_form) element.TKColFrame.TKFrame.update() - if element.Size[1] is not None: + if None not in (element.Size[0], element.Size[1]): + element.TKColFrame.canvas.config(width=element.Size[0], height=element.Size[1]) + elif element.Size[1] is not None: element.TKColFrame.canvas.config(height=element.Size[1]) elif element.Size[0] is not None: element.TKColFrame.canvas.config(width=element.Size[0]) @@ -9819,6 +9819,7 @@ def PopupQuick(*args, title=None, button_type=POPUP_BUTTONS_OK, button_color=Non :param grab_anywhere: If True can grab anywhere to move the window (Default = False) :param location: Location on screen to display :param location: + :param location: """ Popup(*args, title=title, button_color=button_color, background_color=background_color, text_color=text_color,
Finally a fix for Column sizes?????? YES!
PySimpleGUI_PySimpleGUI
train
da8e06af7c71649740937c007d822358b76636f8
diff --git a/Goutte/Client.php b/Goutte/Client.php index <HASH>..<HASH> 100644 --- a/Goutte/Client.php +++ b/Goutte/Client.php @@ -84,7 +84,7 @@ class Client extends BaseClient strtoupper($request->getMethod()), $request->getUri(), array_merge($this->headers, $headers), - $request->getParameters() + in_array($request->getMethod(), array('GET','HEAD')) ? null : $request->getParameters() ); if ($this->auth !== null) {
create request with body only for non-(GET|HEAD) requests Before this commit, Goutte was sending request parameters on any type of request, including GET-forms. This caused exceptions in Guzzle as it doesn't support bodies for GET requests. After this commit, body will be added to request **only** for GET|HEAD requests
FriendsOfPHP_Goutte
train
6b00dd47694c0ff1fa8b1500dffc72bf8247f9d3
diff --git a/internal/core/command/init.go b/internal/core/command/init.go index <HASH>..<HASH> 100644 --- a/internal/core/command/init.go +++ b/internal/core/command/init.go @@ -144,6 +144,10 @@ func connectToConsul(conf *ConfigurationStruct) (*ConfigurationStruct, error) { return conf, errors.New("type check failed") } conf = actual + //Check that information was successfully read from Consul + if conf.Service.Port == 0 { + return nil, errors.New("error reading from Consul") + } } return conf, err @@ -200,4 +204,4 @@ func setLoggingTarget() string { return Configuration.Clients["Logging"].Url() + clients.ApiLoggingRoute } return Configuration.Logging.File -} \ No newline at end of file +} diff --git a/internal/core/data/init.go b/internal/core/data/init.go index <HASH>..<HASH> 100644 --- a/internal/core/data/init.go +++ b/internal/core/data/init.go @@ -201,6 +201,10 @@ func connectToConsul(conf *ConfigurationStruct) (*ConfigurationStruct, error) { return conf, errors.New("type check failed") } conf = actual + //Check that information was successfully read from Consul + if conf.Service.Port == 0 { + return nil, errors.New("error reading from Consul") + } } return conf, err diff --git a/internal/core/metadata/init.go b/internal/core/metadata/init.go index <HASH>..<HASH> 100644 --- a/internal/core/metadata/init.go +++ b/internal/core/metadata/init.go @@ -151,6 +151,10 @@ func connectToConsul(conf *ConfigurationStruct) (*ConfigurationStruct, error) { return conf, errors.New("type check failed") } conf = actual + //Check that information was successfully read from Consul + if conf.Service.Port == 0 { + return nil, errors.New("error reading from Consul") + } } return conf, err @@ -242,4 +246,4 @@ func setLoggingTarget() string { return Configuration.Clients["Logging"].Url() + clients.ApiLoggingRoute } return Configuration.Logging.File -} \ No newline at end of file +} diff --git a/internal/export/client/init.go b/internal/export/client/init.go index <HASH>..<HASH> 100644 --- a/internal/export/client/init.go +++ b/internal/export/client/init.go @@ -199,6 +199,10 @@ func connectToConsul(conf *ConfigurationStruct) (*ConfigurationStruct, error) { return conf, errors.New("type check failed") } conf = actual + //Check that information was successfully read from Consul + if conf.Service.Port == 0 { + return nil, errors.New("error reading from Consul") + } } return conf, err } diff --git a/internal/export/distro/init.go b/internal/export/distro/init.go index <HASH>..<HASH> 100644 --- a/internal/export/distro/init.go +++ b/internal/export/distro/init.go @@ -114,6 +114,10 @@ func connectToConsul(conf *ConfigurationStruct) (*ConfigurationStruct, error) { return conf, errors.New("type check failed") } conf = actual + //Check that information was successfully read from Consul + if conf.Service.Port == 0 { + return nil, errors.New("error reading from Consul") + } } return conf, err } @@ -182,4 +186,3 @@ func setLoggingTarget() string { } return Configuration.Logging.File } - diff --git a/internal/support/logging/init.go b/internal/support/logging/init.go index <HASH>..<HASH> 100644 --- a/internal/support/logging/init.go +++ b/internal/support/logging/init.go @@ -133,7 +133,7 @@ func connectToConsul(conf *ConfigurationStruct) (*ConfigurationStruct, error) { } conf = actual //Check that information was successfully read from Consul - if len(conf.Persistence) == 0 { + if conf.Service.Port == 0 { return nil, errors.New("error reading from Consul") } } diff --git a/internal/support/notifications/init.go b/internal/support/notifications/init.go index <HASH>..<HASH> 100644 --- a/internal/support/notifications/init.go +++ b/internal/support/notifications/init.go @@ -187,7 +187,7 @@ func connectToConsul(conf *ConfigurationStruct) (*ConfigurationStruct, error) { } conf = actual //Check that information was successfully read from Consul - if conf.ResendLimit == 0 { + if conf.Service.Port == 0 { return nil, errors.New("error reading from Consul") } } @@ -230,4 +230,3 @@ func setLoggingTarget() string { } return Configuration.Logging.File } - diff --git a/internal/support/scheduler/init.go b/internal/support/scheduler/init.go index <HASH>..<HASH> 100644 --- a/internal/support/scheduler/init.go +++ b/internal/support/scheduler/init.go @@ -145,6 +145,10 @@ func connectToConsul(conf *ConfigurationStruct) (*ConfigurationStruct, error) { return conf, errors.New("type check failed") } conf = actual + //Check that information was successfully read from Consul + if conf.Service.Port == 0 { + return nil, errors.New("error reading from Consul") + } } return conf, err
Recheck consul connection in case of bootstrap race
edgexfoundry_edgex-go
train
7906efa0a87ebf2ae8345f66e23137a71a99b14d
diff --git a/openquake/risk/job/general.py b/openquake/risk/job/general.py index <HASH>..<HASH> 100644 --- a/openquake/risk/job/general.py +++ b/openquake/risk/job/general.py @@ -68,14 +68,12 @@ def output(fn): def output_writer(self, *args, **kwargs): """ Write the output of a block to kvs. """ fn(self, *args, **kwargs) - conditional_loss_poes = [float(x) for x in self.params.get( - 'CONDITIONAL_LOSS_POE', "").split()] for block_id in self.blocks_keys: #pylint: disable=W0212 self._write_output_for_block(self.job_id, block_id) - for loss_poe in conditional_loss_poes: + for loss_poe in conditional_loss_poes(self.params): path = os.path.join(self.base_path, self.params['OUTPUT_DIR'], "losses_at-%s.xml" % loss_poe) @@ -113,6 +111,14 @@ def _plot(curve_path, result_path, **kwargs): return plotter.filenames() +def conditional_loss_poes(params): + """Return the PoE(s) specified in the configuration file used to + compute the conditional loss.""" + + return [float(x) for x in params.get( + "CONDITIONAL_LOSS_POE", "").split()] + + @task def compute_risk(job_id, block_id, **kwargs): """ A task for computing risk, calls the mixed in compute_risk method """ diff --git a/openquake/risk/job/probabilistic.py b/openquake/risk/job/probabilistic.py index <HASH>..<HASH> 100644 --- a/openquake/risk/job/probabilistic.py +++ b/openquake/risk/job/probabilistic.py @@ -206,25 +206,17 @@ class ProbabilisticEventMixin(): # pylint: disable=W0232,W0201 point.column, point.row, asset, gmf_slice, loss_ratios) aggregate_curve.append(loss_ratios * asset["assetValue"]) - conditional_loss_poes = self._conditional_loss_poes() - if loss_ratio_curve is not None and conditional_loss_poes: + if loss_ratio_curve: loss_curve = self.compute_loss_curve( point.column, point.row, loss_ratio_curve, asset) - for loss_poe in conditional_loss_poes: + for loss_poe in general.conditional_loss_poes(self.params): self.compute_conditional_loss(point.column, point.row, loss_curve, asset, loss_poe) return aggregate_curve.losses - def _conditional_loss_poes(self): - """Return the PoE(s) specified in the configuration file used to - compute the conditional loss.""" - - return [float(x) for x in self.params.get( - "CONDITIONAL_LOSS_POE", "").split()] - def compute_loss_ratios(self, asset, gmf_slice): """For a given asset and ground motion field, computes the loss ratios used to obtain the related loss ratio curve
refactored conditional loss poes
gem_oq-engine
train
96658452cf9c3935dc9a1602c4fbb3e1977d7a6f
diff --git a/lib/devise_invitable/model.rb b/lib/devise_invitable/model.rb index <HASH>..<HASH> 100644 --- a/lib/devise_invitable/model.rb +++ b/lib/devise_invitable/model.rb @@ -25,6 +25,7 @@ module Devise attr_accessor :skip_invitation attr_accessor :completing_invite + attr_reader :raw_invitation_token included do include ::DeviseInvitable::Inviter @@ -158,6 +159,11 @@ module Devise send_devise_notification(:invitation_instructions, @raw_invitation_token) end + # provide alias to the encrypted invitation_token stored by devise + def encrypted_invitation_token + self.invitation_token + end + protected # Overriding the method in Devise's :validatable module so password is not required on inviting def password_required? @@ -272,7 +278,7 @@ module Devise def find_by_invitation_token(original_token, only_valid) invitation_token = Devise.token_generator.digest(self, :invitation_token, original_token) - + invitable = find_or_initialize_with_error_by(:invitation_token, invitation_token) if !invitable.persisted? && Devise.allow_insecure_token_lookup invitable = find_or_initialize_with_error_by(:invitation_token, original_token) diff --git a/test/models/invitable_test.rb b/test/models/invitable_test.rb index <HASH>..<HASH> 100644 --- a/test/models/invitable_test.rb +++ b/test/models/invitable_test.rb @@ -11,6 +11,10 @@ class InvitableTest < ActiveSupport::TestCase assert_nil new_user.invitation_token end + test 'should not generate the raw invitation token after creating a record' do + assert_nil new_user.raw_invitation_token + end + test 'should regenerate invitation token each time' do user = new_user user.invite! @@ -25,6 +29,21 @@ class InvitableTest < ActiveSupport::TestCase end end + test 'should alias the invitation_token method with encrypted_invitation_token' do + user = new_user + user.invite! + assert_equal user.invitation_token, user.encrypted_invitation_token + end + + test 'should return the correct raw_invitation_token ' do + user = new_user + raw, enc = Devise.token_generator.generate(user.class, :invitation_token) + #stub the generator so the tokens are the same + Devise.token_generator.stubs(:generate).returns([raw, enc]) + user.invite! + assert_equal user.raw_invitation_token, raw + end + test 'should set invitation created and sent at each time' do user = new_user user.invite! diff --git a/test/models_test.rb b/test/models_test.rb index <HASH>..<HASH> 100644 --- a/test/models_test.rb +++ b/test/models_test.rb @@ -70,5 +70,9 @@ class ModelsTest < ActiveSupport::TestCase test 'invitable attributes' do assert_nil User.new.invitation_token assert_nil User.new.invitation_sent_at + #raw token + assert_nil User.new.raw_invitation_token + #encrypted token - alias to invitation token + assert_nil User.new.encrypted_invitation_token end end
#<I> - provide standard interface for raw and encrypted tokens generated by devise
scambra_devise_invitable
train
94bd3bc6f98594c1ff8d8efbd10d0551c352ee25
diff --git a/lib/MultiCompiler.js b/lib/MultiCompiler.js index <HASH>..<HASH> 100644 --- a/lib/MultiCompiler.js +++ b/lib/MultiCompiler.js @@ -457,7 +457,7 @@ module.exports = class MultiCompiler { node.compiler, i, nodeDone.bind(null, node), - () => node.state !== "running", + () => node.state !== "done" && node.state !== "running", () => nodeChange(node), () => nodeInvalid(node) ) diff --git a/test/MultiCompiler.test.js b/test/MultiCompiler.test.js index <HASH>..<HASH> 100644 --- a/test/MultiCompiler.test.js +++ b/test/MultiCompiler.test.js @@ -363,6 +363,41 @@ describe("MultiCompiler", function () { } }); }); + + it("shouldn't hang when invalidating watchers", done => { + const entriesA = { a: "./a.js" }; + const entriesB = { b: "./b.js" }; + const compiler = webpack([ + { + name: "a", + mode: "development", + entry: () => entriesA, + context: path.join(__dirname, "fixtures") + }, + { + name: "b", + mode: "development", + entry: () => entriesB, + context: path.join(__dirname, "fixtures") + } + ]); + + compiler.watchFileSystem = { watch() {} }; + compiler.outputFileSystem = createFsFromVolume(new Volume()); + + const watching = compiler.watch({}, error => { + if (error) { + done(error); + return; + } + + entriesA.b = "./b.js"; + entriesB.a = "./a.js"; + + watching.invalidate(done); + }); + }, 2000); + it("shouldn't hang when invalidating during build", done => { const compiler = webpack( Object.assign([
fix: allow invalidation after first watch run
webpack_webpack
train
7f01f8207da9f91b97144b3d4bf799366d52bf35
diff --git a/lib/rda.rb b/lib/rda.rb index <HASH>..<HASH> 100644 --- a/lib/rda.rb +++ b/lib/rda.rb @@ -1,3 +1,4 @@ +require 'rails' require 'thor' require 'confstruct' @@ -5,6 +6,7 @@ require 'rda/railtie' require 'rda/rails' require 'rda/rvm' require 'rda/nginx' +require 'rda/app' module Rda @@config = Confstruct::Configuration.new do diff --git a/lib/rda/railtie.rb b/lib/rda/railtie.rb index <HASH>..<HASH> 100644 --- a/lib/rda/railtie.rb +++ b/lib/rda/railtie.rb @@ -1,5 +1,3 @@ -require 'rails' - module Rda class Railtie < Rails::Railtie railtie_name :rda
Moved rails requirement from railtie to rda
towerhe_rda
train
7b30be969a2b77c82e48681c2960213863d2ec4b
diff --git a/atomic_reactor/download.py b/atomic_reactor/download.py index <HASH>..<HASH> 100644 --- a/atomic_reactor/download.py +++ b/atomic_reactor/download.py @@ -24,7 +24,7 @@ from atomic_reactor.constants import ( logger = logging.getLogger(__name__) -def download_url(url, dest_dir, insecure=False, session=None): +def download_url(url, dest_dir, insecure=False, session=None, dest_filename=None): """Download file from URL, handling retries To download to a temporary directory, use: @@ -34,6 +34,7 @@ def download_url(url, dest_dir, insecure=False, session=None): :param dest_dir: existing directory to create file in :param insecure: bool, whether to perform TLS checks :param session: optional existing requests session to use + :param dest_filename: optional filename for downloaded file :return: str, path of downloaded file """ @@ -41,7 +42,8 @@ def download_url(url, dest_dir, insecure=False, session=None): session = get_retrying_requests_session() parsed_url = urlparse(url) - dest_filename = os.path.basename(parsed_url.path) + if not dest_filename: + dest_filename = os.path.basename(parsed_url.path) dest_path = os.path.join(dest_dir, dest_filename) logger.debug('downloading %s', url)
Allow explicit filename in download_url
projectatomic_atomic-reactor
train
543086ec0a23862aec3e4f126949519423c4c7c5
diff --git a/src/HasApiTokens.php b/src/HasApiTokens.php index <HASH>..<HASH> 100644 --- a/src/HasApiTokens.php +++ b/src/HasApiTokens.php @@ -26,7 +26,7 @@ trait HasApiTokens /** * Get all of the access tokens for the user. * - * @return \Illuminate\Database\Eloquent\Collection + * @return \Illuminate\Database\Eloquent\Relations\HasMany */ public function tokens() {
Correct return type of tokens relation.
laravel_passport
train
2f752af1831478b8c496635cb46b947811097061
diff --git a/makr.go b/makr.go index <HASH>..<HASH> 100644 --- a/makr.go +++ b/makr.go @@ -43,7 +43,7 @@ func (g *Generator) Add(r Runnable) { // Run all of the generators func (g *Generator) Run(rootPath string, data Data) error { - defer g.fmt(rootPath) + // defer g.fmt(rootPath) dd := Data{} for k, v := range data { dd[k] = v @@ -83,7 +83,7 @@ func (g *Generator) Run(rootPath string, data Data) error { }) } -func (g *Generator) fmt(rootPath string) { +func (g *Generator) Fmt(rootPath string) { pwd, _ := os.Getwd() files := []string{} filepath.Walk(rootPath, func(path string, info os.FileInfo, err error) error {
don't fmt always
gobuffalo_makr
train
3a100bf025585683a1a2172ae6ba14e9d9f49525
diff --git a/monolith/__init__.py b/monolith/__init__.py index <HASH>..<HASH> 100644 --- a/monolith/__init__.py +++ b/monolith/__init__.py @@ -1,7 +1,7 @@ """ monolith is an argparse based command line interface framework """ -VERSION = (0, 3, 1) +VERSION = (0, 3, 2) __version__ = '.'.join((str(each) for each in VERSION[:4])) diff --git a/monolith/cli/__init__.py b/monolith/cli/__init__.py index <HASH>..<HASH> 100644 --- a/monolith/cli/__init__.py +++ b/monolith/cli/__init__.py @@ -1,4 +1,5 @@ from .base import BaseCommand +from .base import CommandError from .base import ExecutionManager from .base import SimpleExecutionManager from .base import LabelCommand @@ -14,6 +15,7 @@ __all__ = [ 'arg', 'Parser', 'BaseCommand', + 'CommandError', 'LabelCommand', 'SingleLabelCommand', 'CompletionCommand', diff --git a/monolith/cli/base.py b/monolith/cli/base.py index <HASH>..<HASH> 100644 --- a/monolith/cli/base.py +++ b/monolith/cli/base.py @@ -5,6 +5,7 @@ from collections import namedtuple from monolith.compat import OrderedDict from monolith.compat import unicode from monolith.cli.exceptions import AlreadyRegistered +from monolith.cli.exceptions import CommandError from monolith.utils.imports import get_class @@ -130,7 +131,7 @@ class ExecutionManager(object): parser = self.get_parser() args = [cmd] + list(argv) namespace = parser.parse_args(args) - namespace.func(namespace) + self.run_command(namespace) def execute(self, argv=None): """ @@ -141,7 +142,14 @@ class ExecutionManager(object): parser = self.get_parser() namespace = parser.parse_args(argv) if hasattr(namespace, 'func'): + self.run_command(namespace) + + def run_command(self, namespace): + try: namespace.func(namespace) + except CommandError as err: + sys.stderr.write('ERROR: %s\n' % err.message) + sys.exit(err.code) def autocomplete(self): """ diff --git a/monolith/cli/exceptions.py b/monolith/cli/exceptions.py index <HASH>..<HASH> 100644 --- a/monolith/cli/exceptions.py +++ b/monolith/cli/exceptions.py @@ -1,7 +1,20 @@ -class CLIError(Exception): + +class MonolithError(Exception): + + def __init__(self, message, code=-1): + self.message = message + self.code = code + + +class CLIError(MonolithError): pass + +class CommandError(CLIError): + pass + + class AlreadyRegistered(CLIError): pass diff --git a/monolith/tests/test_cli.py b/monolith/tests/test_cli.py index <HASH>..<HASH> 100644 --- a/monolith/tests/test_cli.py +++ b/monolith/tests/test_cli.py @@ -7,6 +7,7 @@ from monolith.cli.base import arg from monolith.cli.base import ExecutionManager from monolith.cli.base import SimpleExecutionManager from monolith.cli.base import BaseCommand +from monolith.cli.base import CommandError from monolith.cli.base import LabelCommand from monolith.cli.base import SingleLabelCommand from monolith.cli.base import Parser @@ -154,6 +155,24 @@ class TestExecutionManager(unittest.TestCase): namespace = Command.handle.call_args[0][0] self.assertTrue(namespace.force) + @mock.patch('monolith.cli.base.sys.stderr') + def test_call_command_fails(self, stderr): + + class Command(BaseCommand): + args = [ + arg('-f', '--force', action='store_true', default=False), + ] + name = 'add' + + def handle(self, namespace): + raise CommandError('foo bar baz', 92) + + self.manager.register('add', Command) + with self.assertRaises(SystemExit): + self.manager.call_command('add', '-f') + + stderr.write.assert_called_once_with('ERROR: foo bar baz\n') + def test_execute_calls_handle_command(self): class Command(BaseCommand):
Added error handling. Freezying <I>
lukaszb_monolith
train
d1ffc54c06fbacf46783f5ebc84bc125c9188fd1
diff --git a/railties/lib/rails/application.rb b/railties/lib/rails/application.rb index <HASH>..<HASH> 100644 --- a/railties/lib/rails/application.rb +++ b/railties/lib/rails/application.rb @@ -93,13 +93,12 @@ module Rails initializers end - # TODO: Fix this method + # TODO: Fix this method. It loads all railties independent if :all is given + # or not, otherwise frameworks are never loaded. def plugins @plugins ||= begin plugin_names = (config.plugins || [:all]).map { |p| p.to_sym } - Railtie.plugins.select { |p| - plugin_names.include?(:all) || plugin_names.include?(p.plugin_name) - }.map { |p| p.new } + Plugin.all(plugin_names, config.paths.vendor.plugins) + Railtie.plugins.map(&:new) + Plugin.all(plugin_names, config.paths.vendor.plugins) end end
fixes the failure of config.plugins without :all option tests [#<I> status:resolved]
rails_rails
train
f73d4acc4f5f816a3dee4e205579cfaab71fe6b2
diff --git a/pgmpy/models/BayesianModel.py b/pgmpy/models/BayesianModel.py index <HASH>..<HASH> 100644 --- a/pgmpy/models/BayesianModel.py +++ b/pgmpy/models/BayesianModel.py @@ -1086,6 +1086,35 @@ class BayesianModel(nx.DiGraph): moral_graph.add_edges_from(list(itertools.combinations(parents, 2))) return moral_graph + def fit(self, data): + """ + Computes the CPD for each node from the data. + + """ + from pgmpy.factors import TabularCPD + for node in self.nodes(): + if not nx.ancestors(self, node): + state_counts = data.ix[:, node].value_counts() + self.add_cpd(TabularCPD(node, state_counts.shape[0], + (state_counts / state_counts.sum()).values)) + else: + values_series = data.groupby([node].extend(list(nx.ancestors( + self, + node)))).count( + ).ix[:, node] + values = values_series / values.sum() + parent_card = np.array([]) + for node in nx.ancestors(self, node): + parent_card.append(data.ix[:, node].value_counts( + ).shape[0]) + self.add_cpd(TabularCPD(node, data.ix[:, + node].value_counts.shape[0], + values, parent_card, + list(nx.ancestors(self, + node)))) + + + def get_factorized_product(self, latex=False): #TODO: refer to IMap class for explanation why this is not implemented. pass
fit method for BayesianModel [refs #<I>]
pgmpy_pgmpy
train
d2cd4acab13928347181b9e5d7c19103283b5165
diff --git a/report/completion/textrotate.js b/report/completion/textrotate.js index <HASH>..<HASH> 100644 --- a/report/completion/textrotate.js +++ b/report/completion/textrotate.js @@ -26,10 +26,6 @@ function textrotate_make_svg(el) text.setAttribute('text-anchor','end'); text.setAttribute('transform','rotate(90)'); - if (el.className.indexOf('completion-rplheader') != -1) { - text.setAttribute('fill','#238E23'); - } - text.appendChild(document.createTextNode(string)); // Is there an icon near the text? @@ -52,7 +48,16 @@ function textrotate_make_svg(el) el.parentNode.removeChild(el); } +function browser_supports_svg() { + return document.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1"); +} + function textrotate_init() { + if (!browser_supports_svg()) { + // Feature detect, else bail. + return; + } + YUI().use('yui2-dom', function(Y) { var elements= Y.YUI2.util.Dom.getElementsByClassName('completion-criterianame', 'span'); for(var i=0;i<elements.length;i++)
MDL-<I> report_progress: don't browser sniff for SVG support Use feature detection, its more robust and better practice.
moodle_moodle
train
403765328e4b1fa079a11ff7fb1f106e373523bf
diff --git a/lib/meshchat/cli.rb b/lib/meshchat/cli.rb index <HASH>..<HASH> 100644 --- a/lib/meshchat/cli.rb +++ b/lib/meshchat/cli.rb @@ -40,8 +40,8 @@ module MeshChat MeshChat::Command::Base::SHARE => MeshChat::Command::Share, MeshChat::Command::Base::IMPORT => MeshChat::Command::Import, MeshChat::Command::Base::EXPORT => MeshChat::Command::Share, - MeshChat::Command::Base::ONLINE => MeshChat::Command::Offline, - MeshChat::Command::Base::OFFLINE => MeshChat::Command::Online, + MeshChat::Command::Base::ONLINE => MeshChat::Command::Online, + MeshChat::Command::Base::OFFLINE => MeshChat::Command::Offline, MeshChat::Command::Base::HELP => MeshChat::Command::Help, MeshChat::Command::Base::BIND => MeshChat::Command::Bind } diff --git a/lib/meshchat/command/online.rb b/lib/meshchat/command/online.rb index <HASH>..<HASH> 100644 --- a/lib/meshchat/command/online.rb +++ b/lib/meshchat/command/online.rb @@ -6,12 +6,7 @@ module MeshChat end def handle - list = Node.online.map(&:as_info) - msg = if list.present? - list.join(", ") - else - 'no one is online' - end + msg = Node.online.map(&:as_info).join(", ").presence || 'no one is online' Display.info msg end
omg, the commands were backwards
NullVoxPopuli_meshchat-core
train
2bfdb74ee5d36505eb48435f3326c374f818f11f
diff --git a/lib/index.js b/lib/index.js index <HASH>..<HASH> 100644 --- a/lib/index.js +++ b/lib/index.js @@ -243,10 +243,10 @@ SSDP.prototype._parseCommand = function parseCommand(msg, rinfo) { * Emits `advertise-alive`, `advertise-bye` events. * * @param headers - * @param _msg - * @param _rinfo + * @param msg + * @param rinfo */ -SSDP.prototype._notify = function (headers, _msg, _rinfo) { +SSDP.prototype._notify = function (headers, msg, rinfo) { if (!headers.NTS) { this._logger('Missing NTS header: %o', headers) return @@ -255,16 +255,16 @@ SSDP.prototype._notify = function (headers, _msg, _rinfo) { switch (headers.NTS.toLowerCase()) { // Device coming to life. case 'ssdp:alive': - this.emit('advertise-alive', headers) + this.emit('advertise-alive', headers, rinfo) break // Device shutting down. case 'ssdp:byebye': - this.emit('advertise-bye', headers) + this.emit('advertise-bye', headers, rinfo) break default: - this._logger('Unhandled NOTIFY event: %o', {'message': _msg, 'rinfo': _rinfo}) + this._logger('Unhandled NOTIFY event: %o', {'message': msg, 'rinfo': rinfo}) } }
Also emit address details when a notify is received. Removed underscores to fall in line with code style from the other functions.
diversario_node-ssdp
train
3e8c8ae9bb8c0c9bc2ccb93c9455bee80b83b5a1
diff --git a/glances/processes.py b/glances/processes.py index <HASH>..<HASH> 100644 --- a/glances/processes.py +++ b/glances/processes.py @@ -187,20 +187,35 @@ class GlancesProcesses(object): def __get_mandatory_stats(self, proc, procstat): """ - Get mandatory_stats: need for the sorting/filter step. + Get mandatory_stats: for all processes. + Needed for the sorting/filter step. - => cpu_percent, memory_percent, io_counters, name, cmdline + Stats grabbed inside this method: + * 'name', 'cpu_times', 'status', 'ppid' + * 'username', 'cpu_percent', 'memory_percent' """ procstat['mandatory_stats'] = True - # Process CPU, MEM percent and name + # Name, cpu_times, status and ppid stats are in the same /proc file + # Optimisation fir issue #958 try: procstat.update(proc.as_dict( - attrs=['username', 'cpu_percent', 'memory_percent', - 'name', 'cpu_times'], ad_value='')) + attrs=['name', 'cpu_times', 'status', 'ppid'], + ad_value='')) except psutil.NoSuchProcess: - # Try/catch for issue #432 + # Try/catch for issue #432 (process no longer exist) return None + else: + procstat['status'] = str(procstat['status'])[:1].upper() + + try: + procstat.update(proc.as_dict( + attrs=['username', 'cpu_percent', 'memory_percent'], + ad_value='')) + except psutil.NoSuchProcess: + # Try/catch for issue #432 (process no longer exist) + return None + if procstat['cpu_percent'] == '' or procstat['memory_percent'] == '': # Do not display process if we cannot get the basic # cpu_percent or memory_percent stats @@ -259,35 +274,19 @@ class GlancesProcesses(object): def __get_standard_stats(self, proc, procstat): """ - Get standard_stats: for all the displayed processes. + Get standard_stats: only for displayed processes. - => username, status, memory_info, cpu_times + Stats grabbed inside this method: + * nice and memory_info """ procstat['standard_stats'] = True - # Process username (cached with internal cache) - try: - self.username_cache[procstat['pid']] - except KeyError: - try: - self.username_cache[procstat['pid']] = proc.username() - except psutil.NoSuchProcess: - self.username_cache[procstat['pid']] = "?" - except (KeyError, psutil.AccessDenied): - try: - self.username_cache[procstat['pid']] = proc.uids().real - except (KeyError, AttributeError, psutil.AccessDenied): - self.username_cache[procstat['pid']] = "?" - procstat['username'] = self.username_cache[procstat['pid']] - - # Process status, nice, memory_info, cpu_times and ppid (issue #926) + # Process nice and memory_info (issue #926) try: procstat.update( - proc.as_dict(attrs=['status', 'nice', 'memory_info', 'cpu_times', 'ppid'])) + proc.as_dict(attrs=['nice', 'memory_info'])) except psutil.NoSuchProcess: pass - else: - procstat['status'] = str(procstat['status'])[:1].upper() return procstat @@ -388,7 +387,7 @@ class GlancesProcesses(object): mandatory_stats=True, standard_stats=True, extended_stats=False): - """Get stats of running processes.""" + """Get stats of a running processes.""" # Process ID (always) procstat = proc.as_dict(attrs=['pid'])
Optimise CPU consumption #<I>
nicolargo_glances
train
b78e6119482a06206c3b9c5a7c634282318ca005
diff --git a/src/uki-core/function.js b/src/uki-core/function.js index <HASH>..<HASH> 100644 --- a/src/uki-core/function.js +++ b/src/uki-core/function.js @@ -171,6 +171,19 @@ fun.addProp = fun.addProps = function(proto, prop, setter) { } }; +function newDelegateProp(target, targetName) { + return function(value) { + var targetObj = utils.prop(this, target); + if (value === undefined) { + return targetObj ? utils.prop(targetObj, targetName) : null; + } + targetObj && utils.prop(targetObj, targetName, value); + return this; + }; +} + +fun.newDelegateProp = newDelegateProp; + fun.delegateProp = function(proto, name, target, targetName) { if (utils.isArray(name)) { utils.forEach(name, function(n, i) { @@ -178,37 +191,27 @@ fun.delegateProp = function(proto, name, target, targetName) { }); } else { targetName = targetName || name; - var propName = '_' + name; - - proto[name] = function(value) { - if (value === undefined) { - if (utils.prop(this, target)) { - return utils.prop(utils.prop(this, target), targetName); - } - return this[propName]; - } - if (utils.prop(this, target)) { - utils.prop(utils.prop(this, target), targetName, value); - } else { - this[propName] = value; - } - return this; - }; + proto[name] = newDelegateProp(target, targetName); } }; +function newDelegateCall(target, targetName) { + return function() { + var obj = utils.prop(this, target); + return obj[targetName].apply(obj, arguments); + }; +} + +fun.newDelegateCall = newDelegateCall; + fun.delegateCall = function(proto, name, target, targetName) { if (utils.isArray(name)) { utils.forEach(name, function(n, i) { fun.delegateCall(proto, n, target, targetName && targetName[i]); }); - return; } else { targetName = targetName || name; - proto[name] = function() { - var obj = utils.prop(this, target); - return obj[targetName].apply(obj, arguments); - }; + proto[name] = newDelegateCall(target, targetName); } };
newDelegateProp and newDelegateCall functions
voloko_uki
train
9126083d8e0a1f29236e7b6251cb5b2c32c3f93c
diff --git a/CHANGELOG.md b/CHANGELOG.md index <HASH>..<HASH> 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,7 @@ # Master +- [BUGFIX] Allow to type in closed multiple selects. Before the default behaviour of keydown events + was being prevented, disallowing the typing. - [BUGFIX] Ensure the public API passed to the components and to the ourside world is the same, by making it a CP and and use it as single source of truth. diff --git a/addon/components/power-select-multiple.js b/addon/components/power-select-multiple.js index <HASH>..<HASH> 100644 --- a/addon/components/power-select-multiple.js +++ b/addon/components/power-select-multiple.js @@ -51,9 +51,6 @@ export default Ember.Component.extend({ } else { select.actions.close(e); } - } else if (!select.isOpen && e.keyCode >= 48 && e.keyCode <= 90 || e.keyCode === 32) { // Keys 0-9, a-z or SPACE - // Closed multiple selects should not do anything when typing on them - e.preventDefault(); } } }, diff --git a/addon/components/power-select-multiple/trigger.js b/addon/components/power-select-multiple/trigger.js index <HASH>..<HASH> 100644 --- a/addon/components/power-select-multiple/trigger.js +++ b/addon/components/power-select-multiple/trigger.js @@ -67,6 +67,8 @@ export default Ember.Component.extend({ select.actions.search(get(lastSelection, searchField)); } } + } else if (e.keyCode >= 48 && e.keyCode <= 90 || e.keyCode === 32) { // Keys 0-9, a-z or SPACE + e.stopPropagation(); } } }, diff --git a/tests/integration/components/power-select/multiple-test.js b/tests/integration/components/power-select/multiple-test.js index <HASH>..<HASH> 100644 --- a/tests/integration/components/power-select/multiple-test.js +++ b/tests/integration/components/power-select/multiple-test.js @@ -325,7 +325,6 @@ test('Pressing ENTER over a highlighted element on a multiple select with `searc assert.ok(/two/.test($('.ember-power-select-trigger').text().trim()), 'The element was selected'); }); - test('Pressing ENTER over a highlighted element on a select with `searchEnabled=false` selects it', function(assert) { assert.expect(4);
Fix bug that disallowed the user to type in multiple selects that are closed
cibernox_ember-power-select
train
16d7e6510b93ac5b4e589a7e32dc03d739db3c73
diff --git a/src/ViewModels/DistanceLegendViewModel.js b/src/ViewModels/DistanceLegendViewModel.js index <HASH>..<HASH> 100644 --- a/src/ViewModels/DistanceLegendViewModel.js +++ b/src/ViewModels/DistanceLegendViewModel.js @@ -5,6 +5,7 @@ var Cartesian2 = require('../../third_party/cesium/Source/Core/Cartesian2'); var defined = require('../../third_party/cesium/Source/Core/defined'); var DeveloperError = require('../../third_party/cesium/Source/Core/DeveloperError'); var EllipsoidGeodesic = require('../../third_party/cesium/Source/Core/EllipsoidGeodesic'); +var getTimestamp = require('../../third_party/cesium/Source/Core/getTimestamp'); var knockout = require('../../third_party/cesium/Source/ThirdParty/knockout'); var loadView = require('../Core/loadView'); @@ -15,7 +16,8 @@ var DistanceLegendViewModel = function(application) { } this.application = application; - this.removeSubscription = undefined; + this._removeSubscription = undefined; + this._lastLegendUpdate = undefined; this.distanceLabel = undefined; this.barWidth = undefined; @@ -23,9 +25,9 @@ var DistanceLegendViewModel = function(application) { knockout.track(this, ['distanceLabel', 'barWidth']); this.application.beforeViewerChanged.addEventListener(function() { - if (defined(this.removeSubscription)) { - this.removeSubscription(); - this.removeSubscription = undefined; + if (defined(this._removeSubscription)) { + this._removeSubscription(); + this._removeSubscription = undefined; } }, this); @@ -34,7 +36,7 @@ var DistanceLegendViewModel = function(application) { function addUpdateSubscription() { if (defined(that.application.cesium)) { var scene = that.application.cesium.scene; - that.removeSubscription = scene.postRender.addEventListener(function() { + that._removeSubscription = scene.postRender.addEventListener(function() { updateDistanceLegendCesium(this, scene); }, that); } else if (defined(that.application.leaflet)) { @@ -44,7 +46,7 @@ var DistanceLegendViewModel = function(application) { updateDistanceLegendLeaflet(that, map); }; - that.removeSubscription = function() { + that._removeSubscription = function() { map.off('zoomend', potentialChangeCallback); map.off('moveend', potentialChangeCallback); }; @@ -80,6 +82,13 @@ var distances = [ 10000000, 20000000, 30000000, 50000000]; function updateDistanceLegendCesium(viewModel, scene) { + var now = getTimestamp(); + if (now < viewModel._lastLegendUpdate + 250) { + return; + } + + viewModel._lastLegendUpdate = now; + // Find the distance between two pixels at the bottom center of the screen. var width = scene.canvas.clientWidth; var height = scene.canvas.clientHeight;
Only update the distance legend once every <I>ms. This results in a substantial performance improvement in Safari and possibly in other browsers as well.
TerriaJS_terriajs
train
c85cc33ca9de96820d494f289db61f8e22986f46
diff --git a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/plugin/ResolveMainClassName.java b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/plugin/ResolveMainClassName.java index <HASH>..<HASH> 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/plugin/ResolveMainClassName.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/plugin/ResolveMainClassName.java @@ -28,7 +28,9 @@ import org.gradle.api.DefaultTask; import org.gradle.api.InvalidUserDataException; import org.gradle.api.Project; import org.gradle.api.Task; +import org.gradle.api.Transformer; import org.gradle.api.file.FileCollection; +import org.gradle.api.file.RegularFile; import org.gradle.api.file.RegularFileProperty; import org.gradle.api.plugins.BasePlugin; import org.gradle.api.plugins.Convention; @@ -136,19 +138,7 @@ public class ResolveMainClassName extends DefaultTask { } Provider<String> readMainClassName() { - return this.outputFile.map((file) -> { - if (file.getAsFile().length() == 0) { - throw new InvalidUserDataException( - "Main class name has not been configured and it could not be resolved"); - } - Path output = file.getAsFile().toPath(); - try { - return new String(Files.readAllBytes(output), StandardCharsets.UTF_8); - } - catch (IOException ex) { - throw new RuntimeException("Failed to read main class name from '" + output + "'"); - } - }); + return this.outputFile.map(new ClassNameReader()); } static TaskProvider<ResolveMainClassName> registerForTask(String taskName, Project project, @@ -189,4 +179,23 @@ public class ResolveMainClassName extends DefaultTask { } } + private static final class ClassNameReader implements Transformer<String, RegularFile> { + + @Override + public String transform(RegularFile file) { + if (file.getAsFile().length() == 0) { + throw new InvalidUserDataException( + "Main class name has not been configured and it could not be resolved"); + } + Path output = file.getAsFile().toPath(); + try { + return new String(Files.readAllBytes(output), StandardCharsets.UTF_8); + } + catch (IOException ex) { + throw new RuntimeException("Failed to read main class name from '" + output + "'"); + } + } + + } + } diff --git a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/tasks/bundling/AbstractBootArchiveIntegrationTests.java b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/tasks/bundling/AbstractBootArchiveIntegrationTests.java index <HASH>..<HASH> 100644 --- a/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/tasks/bundling/AbstractBootArchiveIntegrationTests.java +++ b/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/test/java/org/springframework/boot/gradle/tasks/bundling/AbstractBootArchiveIntegrationTests.java @@ -198,6 +198,8 @@ abstract class AbstractBootArchiveIntegrationTests { Attributes mainAttributes = jarFile.getManifest().getMainAttributes(); assertThat(mainAttributes.getValue("Start-Class")).isEqualTo("com.example.main.CustomMainClass"); } + assertThat(this.gradleBuild.build(this.taskName).task(":" + this.taskName).getOutcome()) + .isEqualTo(TaskOutcome.UP_TO_DATE); } private void copyMainClassApplication() throws IOException {
Fix main class resolution failure when loaded from config cache See gh-<I>
spring-projects_spring-boot
train
ecd5700bfad2b8cc412b33740a81dd8802067dba
diff --git a/src/Codeception/TestCase/WPTestCase.php b/src/Codeception/TestCase/WPTestCase.php index <HASH>..<HASH> 100644 --- a/src/Codeception/TestCase/WPTestCase.php +++ b/src/Codeception/TestCase/WPTestCase.php @@ -221,9 +221,9 @@ class WPTestCase extends \tad\WPBrowser\Compat\Codeception\Unit * Check on what methods `\Codeception\Test\Unit` provides to call the correct one depending on the PHPUnit and * Codeception versions. */ - $parentSetup = [Unit::class, Compatibility::setupMethodFor(Unit::class)]; + $parentSetup = Compatibility::setupMethodFor(Unit::class); - is_callable($parentSetup) && $parentSetup(); + is_callable($parentSetup) && Unit::$parentSetup(); } public function scan_user_uploads()
fix(WPTestCase.php) looping call issue
lucatume_wp-browser
train
57bc0d462a7b678e848fcc3710b5d105effb5218
diff --git a/lib/helper/Puppeteer.js b/lib/helper/Puppeteer.js index <HASH>..<HASH> 100644 --- a/lib/helper/Puppeteer.js +++ b/lib/helper/Puppeteer.js @@ -1198,10 +1198,11 @@ class Puppeteer extends Helper { /** * {{> ../webapi/saveScreenshot }} */ - async saveScreenshot(fileName, fullPage = this.options.fullPageScreenshots) { + async saveScreenshot(fileName, fullPage) { + const fullPageOption = fullPage || this.options.fullPageScreenshots; const outputFile = path.join(global.output_dir, fileName); this.debug(`Screenshot is saving to ${outputFile}`); - return this.page.screenshot({ path: outputFile, fullPage, type: 'png' }); + return this.page.screenshot({ path: outputFile, fullPage: fullPageOption, type: 'png' }); } async _failed(test) {
[Puppeteer] Fixed issue when generating the list of commands. Fixes #<I> (#<I>)
Codeception_CodeceptJS
train
e6d87c0706d178407ffccaab5c3ffc13a9e7b02e
diff --git a/volume/store/store.go b/volume/store/store.go index <HASH>..<HASH> 100644 --- a/volume/store/store.go +++ b/volume/store/store.go @@ -267,7 +267,9 @@ func (s *VolumeStore) create(name, driverName string, opts, labels map[string]st if err != nil { return nil, err } + s.globalLock.Lock() s.labels[name] = labels + s.globalLock.Unlock() if s.db != nil { metadata := &volumeMetadata{ @@ -362,7 +364,10 @@ func (s *VolumeStore) getVolume(name string) (volume.Volume, error) { } logrus.Debugf("Getting volume reference for name: %s", name) - if v, exists := s.names[name]; exists { + s.globalLock.Lock() + v, exists := s.names[name] + s.globalLock.Unlock() + if exists { vd, err := volumedrivers.GetDriver(v.DriverName()) if err != nil { return nil, err
volume/store: fix couple of races with accessing maps
containers_storage
train
4a7d533613584a23238d32b7f61cf336b5bfdda5
diff --git a/lib/money.js b/lib/money.js index <HASH>..<HASH> 100644 --- a/lib/money.js +++ b/lib/money.js @@ -39,8 +39,8 @@ Money.prototype.minus = function plus(that) { }; Money.prototype.times = function times(that) { - if (!Number.isInteger(that)) { - throw new TypeError('Money multiplication needs an integer'); + if (typeof that !== 'number') { + throw new TypeError('Money multiplication needs a Number'); } return new Money(this.amount.times(that), this.currency); }; diff --git a/test/money.js b/test/money.js index <HASH>..<HASH> 100644 --- a/test/money.js +++ b/test/money.js @@ -70,15 +70,16 @@ describe('Money', () => { should.throws(() => a.minus(c)); }); - it('should multiply with an integer value', () => { + it('should multiply with a Number', () => { let a = new Money(0.30, 'NZD'); a.times(10).amount.should.eql(new Big(3.0)); a.times(10).currency.should.equal('NZD'); a.times(10.0).amount.should.eql(new Big(3.0)); a.times(10.0).currency.should.equal('NZD'); + a.times(10.1).amount.should.eql(new Big(3.03)); + a.times(10.1).currency.should.equal('NZD'); - should.throws(() => a.times(10.1)); should.throws(() => a.times('10.1')); should.throws(() => a.times(new Money(10, 'NZD'))); });
fix(money): multiple with a Number
richardschneider_money-works
train
5297a97765245a80d337a6053d796985333240a6
diff --git a/lib/generators/connector/install_generator.rb b/lib/generators/connector/install_generator.rb index <HASH>..<HASH> 100644 --- a/lib/generators/connector/install_generator.rb +++ b/lib/generators/connector/install_generator.rb @@ -71,5 +71,10 @@ module Connector def copy_oauth_controller copy_file 'oauth_controller.rb', 'app/controllers/oauth_controller.rb' end + + def cleanup + # The connector framework already provide a working implementation of this controller + remove_file 'app/controllers/maestrano/account/groups_controller.rb' + end end end
Fix account deletion controller The connector framework provides a working implementation so we can delete the generated file from maestrano-rails.
maestrano_maestrano-connector-rails
train
8d9951bc7bcffb80281ed6768e256e6212f89c50
diff --git a/pywb/warcserver/test/testutils.py b/pywb/warcserver/test/testutils.py index <HASH>..<HASH> 100644 --- a/pywb/warcserver/test/testutils.py +++ b/pywb/warcserver/test/testutils.py @@ -5,7 +5,7 @@ import shutil import yaml import time -from fakeredis import FakeStrictRedis +from fakeredis import FakeStrictRedis, DATABASES from mock import patch from pywb.warcserver.basewarcserver import BaseWarcServer @@ -64,6 +64,10 @@ class FakeRedisTests(object): @classmethod def setup_class(cls, redis_url='redis://localhost:6379/2'): super(FakeRedisTests, cls).setup_class() + + PUBSUBS.clear() + DATABASES.clear() + cls.redismock = patch('redis.StrictRedis', FakeStrictRedisSharedPubSub) cls.redismock.start() diff --git a/tests/test_record_replay.py b/tests/test_record_replay.py index <HASH>..<HASH> 100644 --- a/tests/test_record_replay.py +++ b/tests/test_record_replay.py @@ -63,15 +63,15 @@ class TestRecordReplay(CollsDirMixin, BaseConfigTest): assert '"C": "D"' in res.text def test_record_again_1(self): - res = self.testapp.get('/test/record/mp_/http://httpbin.org/get?C=D') - assert '"C": "D"' in res.text + res = self.testapp.get('/test/record/mp_/http://httpbin.org/get?C=D2') + assert '"C": "D2"' in res.text def test_replay_again_1(self, fmod): self.ensure_empty() fmod_slash = fmod + '/' if fmod else '' - res = self.get('/test/{0}http://httpbin.org/get?C=D', fmod_slash) - assert '"C": "D"' in res.text + res = self.get('/test/{0}http://httpbin.org/get?C=D2', fmod_slash) + assert '"C": "D2"' in res.text assert len(os.listdir(os.path.join(self.root_dir, '_test_colls', 'test', 'archive'))) == 1 @@ -104,12 +104,12 @@ class TestRecordReplay(CollsDirMixin, BaseConfigTest): assert cdxj_lines[0]['url'] == 'http://httpbin.org/get?A=B' assert cdxj_lines[1]['url'] == 'http://httpbin.org/get?A=B' assert cdxj_lines[2]['url'] == 'http://httpbin.org/get?C=D' - assert cdxj_lines[3]['url'] == 'http://httpbin.org/get?C=D' + assert cdxj_lines[3]['url'] == 'http://httpbin.org/get?C=D2' assert cdxj_lines[0]['urlkey'] == 'org,httpbin)/get?__pywb_method=head&a=b' assert cdxj_lines[1]['urlkey'] == 'org,httpbin)/get?a=b' assert cdxj_lines[2]['urlkey'] == 'org,httpbin)/get?c=d' - assert cdxj_lines[3]['urlkey'] == 'org,httpbin)/get?c=d' + assert cdxj_lines[3]['urlkey'] == 'org,httpbin)/get?c=d2' assert cdxj_lines[0]['source'] == to_path('test/indexes/autoindex.cdxj') assert cdxj_lines[1]['source'] == to_path('test/indexes/autoindex.cdxj') @@ -126,10 +126,10 @@ class TestRecordReplay(CollsDirMixin, BaseConfigTest): def test_timemap_all_coll(self): res = self.testapp.get('/all/timemap/link/http://httpbin.org/get?C=D') link_lines = res.text.rstrip().split('\n') - assert len(link_lines) == 5 + assert len(link_lines) == 4 assert to_path('collection="test2"') in link_lines[3] - assert to_path('collection="test"') in link_lines[4] + #assert to_path('collection="test"') in link_lines[4] # ============================================================================
misc test fixes: make record_replay tests for consistent, use different url to ensure consistent ordering fakeredistests: fix for fakenewredis, clear fakeredis databases and pubsub list
webrecorder_pywb
train
9debdcc6ff7970d5a280b314a4b88756511512c2
diff --git a/app/assets/javascripts/systems/systems.controller.js b/app/assets/javascripts/systems/systems.controller.js index <HASH>..<HASH> 100644 --- a/app/assets/javascripts/systems/systems.controller.js +++ b/app/assets/javascripts/systems/systems.controller.js @@ -14,11 +14,12 @@ angular.module('Katello').factory('SystemTable', ['Nutupane', function(Nutupane){ var SystemTable = {}; - SystemTable.get = function(sort, callback){ + SystemTable.get = function(sort, offset, callback){ Nutupane.get({ url: '/katello/api/systems/', sort: sort, callback: callback, + offset: offset, transform: SystemTable.transform }); }; @@ -85,17 +86,23 @@ angular.module('Katello').controller('SystemsController', ['$scope', 'SystemTabl var fetch = function(callback){ $scope.table.working = true; - SystemTable.get(sort, function(data){ - $scope.table.data.rows = data.data.rows; - $scope.table.total = data.total; - $scope.table.start = data.data.rows.length; - $scope.table.offset = data.subtotal; + SystemTable.get(sort, $scope.table.start, function(data){ + + if( !$scope.table.loading_more ){ + $scope.table.start = data.data.rows.length; + $scope.table.data.rows = data.data.rows; + $scope.table.total = data.total; + $scope.table.offset = data.subtotal; + } else { + $scope.table.start += data.data.rows.length; + $scope.table.data.rows = $scope.table.data.rows.concat(data.data.rows); + } if ( callback ){ callback(); } - $scope.table.working = false; + $scope.table.working = false; }); }; @@ -132,6 +139,18 @@ angular.module('Katello').controller('SystemsController', ['$scope', 'SystemTabl fetch(); }; + $scope.table.next_page = function(){ + if ($scope.table.loading_more || $scope.table.start === $scope.table.offset) { + return; + } + + $scope.table.loading_more = true; + + fetch(function(){ + $scope.table.loading_more = false; + }); + }; + fetch(); }]); diff --git a/app/assets/javascripts/widgets/nutupane.js b/app/assets/javascripts/widgets/nutupane.js index <HASH>..<HASH> 100644 --- a/app/assets/javascripts/widgets/nutupane.js +++ b/app/assets/javascripts/widgets/nutupane.js @@ -21,7 +21,8 @@ angular.module('Katello').factory('Nutupane', ['$location', '$http', 'current_or 'search': $location.search().search, 'sort_by': options.sort.by, 'sort_order': options.sort.order, - 'paged': true + 'paged': true, + 'offset': options.offset } }) .then(function(response){ diff --git a/app/views/systems/index_nutupane.html.haml b/app/views/systems/index_nutupane.html.haml index <HASH>..<HASH> 100644 --- a/app/views/systems/index_nutupane.html.haml +++ b/app/views/systems/index_nutupane.html.haml @@ -1,4 +1,4 @@ -= javascript 'systems/systems.controller', 'widgets/nutupane' += javascript 'systems/systems.controller', 'widgets/nutupane', 'ng-infinite-scroll' = stylesheet 'widgets/nutupane' %div{ 'ng-controller' => 'SystemsController' }
Systems Nutupane - Adds infinite scroll support to systems nutupane table.
Katello_katello
train
6da1cf8afbaf2feb8ed291042eb4ef692ca4ed14
diff --git a/index.js b/index.js index <HASH>..<HASH> 100644 --- a/index.js +++ b/index.js @@ -116,7 +116,7 @@ function Field(){ // shortcut for adding a `notEmpty` validator Field.prototype.required = function(){ this.isRequired = true; - this.validators.push('notEmpty'); + this.validators.push(['notEmpty']); return this; }; @@ -170,9 +170,30 @@ Field.prototype.set = function(val){ }; Field.prototype.validate = function(){ - if(this.isRequired && (!this.value || this.value.length === 0)){ - throw new ValidationError(this.name + ' is required'); - } + var checker = check(this.value), + sanitizer = sanitize(this.value), + self = this; + + this.validators.map(function(validatorArgs){ + if(validatorArgs.length === 0){ + return; + } + var method = validatorArgs.pop(); + checker[method].apply(checker, validatorArgs); + }); + + this.filters.map(function(filter){ + if(typeof filter === 'function'){ + self.value = filter(self.value); + } + else { + self.value = sanitizer[filter](); + } + }); + + // if(this.isRequired && (!this.value || this.value.length === 0)){ + // throw new ValidationError(this.name + ' is required'); + // } }; // No way. A String! diff --git a/test/index.test.js b/test/index.test.js index <HASH>..<HASH> 100644 --- a/test/index.test.js +++ b/test/index.test.js @@ -69,7 +69,21 @@ describe('forro', function(){ assert(new AuthForm({'username': 'a', 'password':'b'}).validate()); }); - it('should access actual field values correctly'); + it('should run the simplest filters', function(){ + var AuthForm = forro({ + 'username': forro.string().required(), + 'password': forro.string().required() + }), form; + + form = new AuthForm({'username': ' a ', 'password':'b'}); + form.validate(); + + assert.equal(form.val('username'), 'a'); + }); + + it('should correctly cast Date fields from strings'); + + it('should correctly cast Date fields from timestamps as strings'); it('should not automatically supply a default value if none specified'); }); \ No newline at end of file
Pretty close. Some edge cases and actual casting to do
imlucas_node-forro
train
022c51c0bc65b3041f5933fab483b0d5dfb1da86
diff --git a/salt/modules/mysql.py b/salt/modules/mysql.py index <HASH>..<HASH> 100644 --- a/salt/modules/mysql.py +++ b/salt/modules/mysql.py @@ -43,6 +43,9 @@ def __virtual__(): if any(k.startswith('mysql.') for k in list(__opts__)): if has_mysqldb: return 'mysql' + elif any(k.startswith('mysql.') for k in list(__pillar__)): + if has_mysqldb: + return 'mysql' return False @@ -87,14 +90,17 @@ def connect(**kwargs): def _connarg(name, key=None): ''' Add key to connargs, only if name exists in our - kwargs or as mysql.<name> in __opts__ + kwargs or as mysql.<name> in __opts__ or __pillar__ + Evaluate in said order - kwargs, opts then pillar ''' if key is None: key = name if name in kwargs: connargs[key] = kwargs[name] - elif 'mysql.%s' % name in __opts__: - connargs[key] = __opts__['mysql.%s' % name] + elif 'mysql.{0}'.format(name) in __opts__: + connargs[key] = __opts__['mysql.{0}'.format(name)] + elif 'mysql.{0}'.format(name) in __pillar__: + connargs[key] = __pillar__['mysql.{0}'.format(name)] _connarg('host') _connarg('user')
Can now pass mysql options in pillar, Fix #<I>
saltstack_salt
train
0f8738ef3273dfb87d5903da026f3724051a228f
diff --git a/zipline/pipeline/loaders/blaze/core.py b/zipline/pipeline/loaders/blaze/core.py index <HASH>..<HASH> 100644 --- a/zipline/pipeline/loaders/blaze/core.py +++ b/zipline/pipeline/loaders/blaze/core.py @@ -137,11 +137,10 @@ from datashape import ( Date, DateTime, Option, - float64, floating, isrecord, isscalar, - promote, + String ) import numpy as np from odo import odo @@ -170,7 +169,7 @@ from zipline.pipeline.loaders.utils import ( normalize_timestamp_to_query_time, ) from zipline.pipeline.term import NotSpecified -from zipline.lib.adjusted_array import AdjustedArray +from zipline.lib.adjusted_array import AdjustedArray, can_represent_dtype from zipline.lib.adjustment import Float64Overwrite from zipline.utils.enum import enum from zipline.utils.input_validation import ( @@ -312,21 +311,17 @@ def new_dataset(expr, deltas, missing_values): if name in (SID_FIELD_NAME, TS_FIELD_NAME): continue try: - # TODO: This should support datetime and bool columns. - if promote(type_, float64, promote_option=False) != float64: - raise NotPipelineCompatible() if isinstance(type_, Option): type_ = type_.ty - except NotPipelineCompatible: - col = NonPipelineField(name, type_) - except TypeError: - col = NonNumpyField(name, type_) - else: + type_ = type_.to_numpy_dtype() + if not isinstance(type_, String) and not can_represent_dtype(type_): + raise NotPipelineCompatible() col = Column( - type_.to_numpy_dtype(), + type_, missing_values.get(name, NotSpecified), ) - + except NotPipelineCompatible: + col = NonPipelineField(name, type_) columns[name] = col name = expr._name
MAINT: remove restrictions on strings for generic loader MAINT: remove catch for NonNumpyCompatible since it's a subset of NonPipelineCompatible
quantopian_zipline
train
5c0c8954f9053ce7023300493e340cd6c02e1e50
diff --git a/test/test.js b/test/test.js index <HASH>..<HASH> 100644 --- a/test/test.js +++ b/test/test.js @@ -109,9 +109,11 @@ listZipFiles(path.join(__dirname, "failure")).forEach(function(zipfilePath) { yauzl.open(zipfilePath, function(err, zipfile) { if (err) return checkErrorMessage(err); zipfile.on("error", function(err) { + noEventsAllowedAfterError(); checkErrorMessage(err); }); zipfile.on("entry", function(entry) { + noEventsAllowedAfterError(); // let's also try to read directories, cuz whatever. operationsInProgress += 1; zipfile.openReadStream(entry, function(err, stream) { @@ -129,6 +131,7 @@ listZipFiles(path.join(__dirname, "failure")).forEach(function(zipfilePath) { }); operationsInProgress += 1; zipfile.on("end", function() { + noEventsAllowedAfterError(); doneWithSomething(); }); function doneWithSomething() { @@ -149,6 +152,9 @@ listZipFiles(path.join(__dirname, "failure")).forEach(function(zipfilePath) { operationsInProgress = -Infinity; cb(); } + function noEventsAllowedAfterError() { + if (failedYet) throw new Error("events emitted after error event"); + } }); });
test for no events emitted after error event
thejoshwolfe_yauzl
train
4925eea3df71d3c0dd064085fefae997c1ead5e2
diff --git a/applications/jupyter-extension/nteract_on_jupyter/epics/index.js b/applications/jupyter-extension/nteract_on_jupyter/epics/index.js index <HASH>..<HASH> 100644 --- a/applications/jupyter-extension/nteract_on_jupyter/epics/index.js +++ b/applications/jupyter-extension/nteract_on_jupyter/epics/index.js @@ -2,6 +2,7 @@ import { loadEpic } from "./contents"; import { listKernelSpecsEpic } from "./kernelspecs"; import { setNotebookEpic } from "./notebook"; +import { fetchKernelspecsEpic } from "@nteract/core/epics"; import { executeCellEpic, @@ -14,6 +15,7 @@ import { // TODO: Bring desktop's wrapEpic over to @nteract/core so we can use it here const epics = [ + fetchKernelspecsEpic, executeCellEpic, updateDisplayEpic, commListenEpic, diff --git a/applications/jupyter-extension/nteract_on_jupyter/index.js b/applications/jupyter-extension/nteract_on_jupyter/index.js index <HASH>..<HASH> 100644 --- a/applications/jupyter-extension/nteract_on_jupyter/index.js +++ b/applications/jupyter-extension/nteract_on_jupyter/index.js @@ -12,6 +12,8 @@ import type { JupyterConfigData } from "./store"; import { NotebookApp } from "@nteract/core/providers"; +import { fetchKernelspecs } from "@nteract/core/actions"; + function createApp(jupyterConfigData: JupyterConfigData) { const store = configureStore({ config: jupyterConfigData }); window.store = store; @@ -19,8 +21,14 @@ function createApp(jupyterConfigData: JupyterConfigData) { class App extends React.Component<*> { notificationSystem: NotificationSystem; + // TODO: the kernelspecsRef is hard-coded to be 'single-server' in this + // application because we only anticipate _one_ set of possible kernelspecs. + // However, since `/core` assumes that a generic notebook application may + // be able to connect to multiple servers and thus have many kernelspecs, + // it needs a ref to complete the action. componentDidMount(): void { store.dispatch({ type: "LOAD", path: jupyterConfigData.contentsPath }); + store.dispatch(fetchKernelspecs({ kernelspecsRef: "single-server" })); } render(): React$Element<any> { diff --git a/applications/jupyter-extension/nteract_on_jupyter/store.js b/applications/jupyter-extension/nteract_on_jupyter/store.js index <HASH>..<HASH> 100644 --- a/applications/jupyter-extension/nteract_on_jupyter/store.js +++ b/applications/jupyter-extension/nteract_on_jupyter/store.js @@ -6,7 +6,13 @@ import { List as ImmutableList, Map as ImmutableMap } from "immutable"; const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose; -import { document, comms, config, app } from "@nteract/core/reducers"; +import { + document, + comms, + config, + app, + entitiesKernelspecsByRef +} from "@nteract/core/reducers"; import { makeAppRecord, @@ -39,7 +45,10 @@ const rootReducer = combineReducers({ app, document, comms, - config + config, + entities: combineReducers({ + kernelspecsByRef: entitiesKernelspecsByRef + }) }); export default function configureStore({
feat: hookup core kernelspecs to jupyter-ext
nteract_nteract
train
9332317e678e831961a4b5f4e3faf58544377ae3
diff --git a/expression/builtin_time_vec.go b/expression/builtin_time_vec.go index <HASH>..<HASH> 100644 --- a/expression/builtin_time_vec.go +++ b/expression/builtin_time_vec.go @@ -165,3 +165,74 @@ func (b *builtinTimestamp1ArgSig) vecEvalTime(input *chunk.Chunk, result *chunk. func (b *builtinTimestamp1ArgSig) vectorized() bool { return true } + +func (b *builtinTimestamp2ArgsSig) vecEvalTime(input *chunk.Chunk, result *chunk.Column) error { + n := input.NumRows() + buf0, err := b.bufAllocator.get(types.ETString, n) + if err != nil { + return err + } + defer b.bufAllocator.put(buf0) + if err := b.args[0].VecEvalString(b.ctx, input, buf0); err != nil { + return err + } + + buf1, err := b.bufAllocator.get(types.ETString, n) + if err != nil { + return err + } + defer b.bufAllocator.put(buf1) + if err := b.args[1].VecEvalString(b.ctx, input, buf1); err != nil { + return err + } + + result.ResizeTime(n, false) + result.MergeNulls(buf0, buf1) + times := result.Times() + sc := b.ctx.GetSessionVars().StmtCtx + var tm types.Time + for i := 0; i < n; i++ { + if result.IsNull(i) { + continue + } + arg0 := buf0.GetString(i) + arg1 := buf1.GetString(i) + + if b.isFloat { + tm, err = types.ParseTimeFromFloatString(sc, arg0, mysql.TypeDatetime, types.GetFsp(arg0)) + } else { + tm, err = types.ParseTime(sc, arg0, mysql.TypeDatetime, types.GetFsp(arg0)) + } + if err != nil { + if err = handleInvalidTimeError(b.ctx, err); err != nil { + return err + } + result.SetNull(i, true) + continue + } + + if !isDuration(arg1) { + result.SetNull(i, true) + continue + } + + duration, err := types.ParseDuration(sc, arg1, types.GetFsp(arg1)) + if err != nil { + if err = handleInvalidTimeError(b.ctx, err); err != nil { + return err + } + result.SetNull(i, true) + continue + } + tmp, err := tm.Add(sc, duration) + if err != nil { + return err + } + times[i] = tmp + } + return nil +} + +func (b *builtinTimestamp2ArgsSig) vectorized() bool { + return true +} diff --git a/expression/builtin_time_vec_test.go b/expression/builtin_time_vec_test.go index <HASH>..<HASH> 100644 --- a/expression/builtin_time_vec_test.go +++ b/expression/builtin_time_vec_test.go @@ -39,6 +39,12 @@ var vecBuiltinTimeCases = map[string][]vecExprBenchCase{ {retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETString}, geners: []dataGenerator{new(timeStrGener)}}, {retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETString}, geners: []dataGenerator{new(dataStrGener)}}, {retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETString}}, + {retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETString, types.ETString}, + geners: []dataGenerator{new(dataTimeStrGener), new(dataStrGener)}}, + {retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETString, types.ETString}, + geners: []dataGenerator{new(dataTimeStrGener), nil}}, + {retEvalType: types.ETDatetime, childrenTypes: []types.EvalType{types.ETString, types.ETString}, + geners: []dataGenerator{nil, new(dataStrGener)}}, }, }
expression: implement vectorized evaluation for `builtinTimestamp2ArgsSig` (#<I>)
pingcap_tidb
train
1855ac9ce12468638b70bb3464bc1c48763c1cc1
diff --git a/billy/web/public/urls.py b/billy/web/public/urls.py index <HASH>..<HASH> 100644 --- a/billy/web/public/urls.py +++ b/billy/web/public/urls.py @@ -74,6 +74,6 @@ urlpatterns = patterns('billy.web.public.views', urlpatterns += patterns('', # other views url(r'^downloads/$', 'billy.web.public.views_other.downloads', name='downloads'), - url(r'^find_your_legislator/$', 'find_your_legislator', + url(r'^find_your_legislator/$', 'billy.web.public.views.find_your_legislator', name='find_your_legislator'), ) diff --git a/billy/web/public/views.py b/billy/web/public/views.py index <HASH>..<HASH> 100644 --- a/billy/web/public/views.py +++ b/billy/web/public/views.py @@ -369,14 +369,11 @@ def chamber_select(request, collection_name): def find_your_legislator(request): - - form = FindYourLegislatorForm(request.GET) - - url = 'http://rpc.geocoder.us/service/csv?address=%s' - url = url % form.data['address'].replace(' ', '+') - resp = requests.get(url) - lat, lng, _ = resp.text.split(',', 2) - import pdb;pdb.set_trace() + # check if lat/lon are set, or if leg_search is set. + return render_to_response( + template_name=templatename('find_your_legislator'), + dictionary=dict(), + context_instance=RequestContext(request, default_context)) def legislators(request, abbr):
more small tweaks to the find page
openstates_billy
train
efa7ea4fdee9e9a21815068547804250f7f28159
diff --git a/src/ocrmypdf/_pipeline.py b/src/ocrmypdf/_pipeline.py index <HASH>..<HASH> 100644 --- a/src/ocrmypdf/_pipeline.py +++ b/src/ocrmypdf/_pipeline.py @@ -163,7 +163,7 @@ def repair_and_parse_pdf( copyfile(input_file, output_file) try: - pdfinfo = PdfInfo(output_file) + pdfinfo = PdfInfo(output_file, log=log) except pikepdf.PasswordError as e: raise EncryptedPdfError() except pikepdf.PdfError as e: diff --git a/src/ocrmypdf/pdfinfo.py b/src/ocrmypdf/pdfinfo.py index <HASH>..<HASH> 100644 --- a/src/ocrmypdf/pdfinfo.py +++ b/src/ocrmypdf/pdfinfo.py @@ -16,13 +16,14 @@ # You should have received a copy of the GNU General Public License # along with OCRmyPDF. If not, see <http://www.gnu.org/licenses/>. +from collections import namedtuple from decimal import Decimal +from enum import Enum from math import hypot, isclose -import re -from collections import namedtuple from pathlib import Path -from enum import Enum from unittest.mock import Mock +import re +import xml.etree.ElementTree as ET from .exec import ghostscript from .helpers import fspath @@ -597,8 +598,9 @@ def _pdf_get_pageinfo(pdf, pageno: int, infile, xmltext): return pageinfo -def _pdf_get_all_pageinfo(infile, log=Mock()): - import xml.etree.ElementTree as ET +def _pdf_get_all_pageinfo(infile, log=None): + if not log: + log = Mock() pdf = pikepdf.open(infile) @@ -715,7 +717,7 @@ class PdfInfo: """ def __init__(self, infile, log=None): self._infile = infile - self._pages, pdf = _pdf_get_all_pageinfo(infile, log) + self._pages, pdf = _pdf_get_all_pageinfo(infile, log=log) self._needs_rendering = pdf.root.get('/NeedsRendering', False) @property
Fix log.error where log is None
jbarlow83_OCRmyPDF
train
2cece432eb3bb681c0c19919b848504b2557cfc0
diff --git a/pymatgen/electronic_structure/dos.py b/pymatgen/electronic_structure/dos.py index <HASH>..<HASH> 100644 --- a/pymatgen/electronic_structure/dos.py +++ b/pymatgen/electronic_structure/dos.py @@ -867,9 +867,8 @@ class CompleteDos(Dos): erange: List[float] = None, ) -> float: """ - Get the orbital-projected band width, defined in Vojvodic et al., Top. Catal., 57, 25-32 (2014) - and given by the following expression: - 4*sqrt(int_{-inf}^{+inf} rho(E)*(E-E_center)^2 dE/int_{-inf}^{+inf} rho(E) dE) + Get the orbital-projected band width given by the following expression: + sqrt(int_{-inf}^{+inf} rho(E)*(E-E_center)^2 dE/int_{-inf}^{+inf} rho(E) dE) where E_center is the orbital-projected band center, the limits of the integration can be modified by erange, and E is the set of energies taken with respect to the Fermi level. Note that the band width is often highly sensitive to the selected erange. @@ -905,7 +904,7 @@ class CompleteDos(Dos): second_moment = np.trapz((energies - band_center) ** 2 * densities, x=energies) / np.trapz( densities, x=energies ) - band_width = 4 * np.sqrt(second_moment) + band_width = np.sqrt(second_moment) return band_width
Use the sqrt definition of the bandwidth
materialsproject_pymatgen
train
ed119aa5d608d66bcb45f79324167142086fb2be
diff --git a/activerecord/test/cases/associations/inner_join_association_test.rb b/activerecord/test/cases/associations/inner_join_association_test.rb index <HASH>..<HASH> 100644 --- a/activerecord/test/cases/associations/inner_join_association_test.rb +++ b/activerecord/test/cases/associations/inner_join_association_test.rb @@ -10,7 +10,7 @@ require 'models/tagging' require 'models/tag' class InnerJoinAssociationTest < ActiveRecord::TestCase - fixtures :authors, :posts, :comments, :categories, :categories_posts, :categorizations, + fixtures :authors, :essays, :posts, :comments, :categories, :categories_posts, :categorizations, :taggings, :tags def test_construct_finder_sql_applies_aliases_tables_on_association_conditions
Fixed InnerJoinAssociationTest. Need to load essays fixture.
rails_rails
train
25d1e3ef0a1d961bd550cce4f5b75029e2e60b7e
diff --git a/app/controllers/concerns/hyrax/works_controller_behavior.rb b/app/controllers/concerns/hyrax/works_controller_behavior.rb index <HASH>..<HASH> 100644 --- a/app/controllers/concerns/hyrax/works_controller_behavior.rb +++ b/app/controllers/concerns/hyrax/works_controller_behavior.rb @@ -187,8 +187,11 @@ module Hyrax else form = build_form - @curation_concern = form.validate(params[hash_key_for_curation_concern]) && - transactions['change_set.create_work'].call(form).value! + @curation_concern = + form.validate(params[hash_key_for_curation_concern]) && + transactions['change_set.create_work'] + .with_step_args('work_resource.add_file_sets' => { uploaded_files: uploaded_files }) + .call(form).value! end end @@ -199,8 +202,11 @@ module Hyrax else form = build_form - @curation_concern = form.validate(params[hash_key_for_curation_concern]) && - transactions['change_set.update_work'].call(form).value! + @curation_concern = + form.validate(params[hash_key_for_curation_concern]) && + transactions['change_set.update_work'] + .with_step_args('work_resource.add_file_sets' => { uploaded_files: uploaded_files }) + .call(form).value! end end @@ -412,5 +418,9 @@ module Hyrax Hyrax.custom_queries.find_child_fileset_ids(resource: curation_concern).any? end end + + def uploaded_files + UploadedFile.find(params.fetch(:uploaded_files, [])) + end end end diff --git a/lib/hyrax/transactions/update_work.rb b/lib/hyrax/transactions/update_work.rb index <HASH>..<HASH> 100644 --- a/lib/hyrax/transactions/update_work.rb +++ b/lib/hyrax/transactions/update_work.rb @@ -4,7 +4,8 @@ module Hyrax ## # @since 3.0.0 class UpdateWork < Transaction - DEFAULT_STEPS = ['change_set.apply'].freeze + DEFAULT_STEPS = ['change_set.apply', + 'work_resource.add_file_sets'].freeze ## # @see Hyrax::Transactions::Transaction diff --git a/spec/controllers/concerns/hyrax/works_controller_behavior_spec.rb b/spec/controllers/concerns/hyrax/works_controller_behavior_spec.rb index <HASH>..<HASH> 100644 --- a/spec/controllers/concerns/hyrax/works_controller_behavior_spec.rb +++ b/spec/controllers/concerns/hyrax/works_controller_behavior_spec.rb @@ -63,7 +63,6 @@ RSpec.describe Hyrax::WorksControllerBehavior, :clean_repo, type: :controller do let(:uploads) { FactoryBot.create_list(:uploaded_file, 2, user: user) } it 'attaches the files' do - pending 'it should actually attach the files' params = { test_simple_work: { title: 'comet in moominland' }, uploaded_files: uploads.map(&:id) } @@ -315,6 +314,18 @@ RSpec.describe Hyrax::WorksControllerBehavior, :clean_repo, type: :controller do expect(Hyrax.query_service.find_by(id: id)) .to have_attributes title: contain_exactly('new title') end + + context 'and files' do + let(:uploads) { FactoryBot.create_list(:uploaded_file, 2, user: user) } + + it 'attaches the files' do + params = { id: id, test_simple_work: { title: 'comet in moominland' }, + uploaded_files: uploads.map(&:id) } + + get :update, params: params + expect(assigns(:curation_concern)).to have_file_set_members(be_persisted, be_persisted) + end + end end end end diff --git a/spec/factories/hyrax_work.rb b/spec/factories/hyrax_work.rb index <HASH>..<HASH> 100644 --- a/spec/factories/hyrax_work.rb +++ b/spec/factories/hyrax_work.rb @@ -60,6 +60,12 @@ FactoryBot.define do end end + trait :with_member_file_sets do + transient do + members { [valkyrie_create(:hyrax_file_set), valkyrie_create(:hyrax_file_set)] } + end + end + trait :as_collection_member do member_of_collection_ids { [valkyrie_create(:hyrax_collection).id] } end diff --git a/spec/services/hyrax/work_uploads_handler_spec.rb b/spec/services/hyrax/work_uploads_handler_spec.rb index <HASH>..<HASH> 100644 --- a/spec/services/hyrax/work_uploads_handler_spec.rb +++ b/spec/services/hyrax/work_uploads_handler_spec.rb @@ -45,5 +45,20 @@ RSpec.describe Hyrax::WorkUploadsHandler do be_a_resource_with_permissions(have_attributes(mode: :read, agent: 'group/public'))) end end + + context 'with existing file_sets' do + let(:work) { FactoryBot.valkyrie_create(:hyrax_work, :public, :with_member_file_sets) } + + it 'appends the new file sets' do + first_id, second_id = work.member_ids + + service.add(files: uploads).attach + expect(work).to have_file_set_members(have_attributes(id: first_id), + have_attributes(id: second_id), + be_persisted, + be_persisted, + be_persisted) + end + end end end
handle file uploads for valkyrie work models this is only the most basic file upload case, but it wires all the pieces in and should work end-to-end for `#create` and `#update`.
samvera_hyrax
train
00de631330a894fd6b2afdb273c26e89aa6c4de3
diff --git a/cachalot/tests/models.py b/cachalot/tests/models.py index <HASH>..<HASH> 100644 --- a/cachalot/tests/models.py +++ b/cachalot/tests/models.py @@ -4,7 +4,7 @@ from __future__ import unicode_literals from django.conf import settings from django.db.models import ( - Model, CharField, ForeignKey, BooleanField, DateField, DateTimeField, ManyToManyField) + Model, CharField, ForeignKey, BooleanField, DateField, DateTimeField) class Test(Model): @@ -32,12 +32,3 @@ class TestChild(TestParent): class Meta(object): app_label = 'cachalot' - - -class TestOne(Model): - name = CharField(max_length=20) - have_lots_of_these = ManyToManyField('TestThese', blank=True, null=True) - - -class TestThese(Model): - name = CharField(max_length=20) diff --git a/cachalot/tests/write.py b/cachalot/tests/write.py index <HASH>..<HASH> 100644 --- a/cachalot/tests/write.py +++ b/cachalot/tests/write.py @@ -14,7 +14,7 @@ from django.db import connection, transaction from django.db.models import Count from django.test import TransactionTestCase, skipUnlessDBFeature -from .models import Test, TestParent, TestChild, TestOne, TestThese +from .models import Test, TestParent, TestChild class WriteTestCase(TransactionTestCase): @@ -373,6 +373,16 @@ class WriteTestCase(TransactionTestCase): ) self.assertListEqual(data10, []) + with self.assertNumQueries(1): + data11 = list(User.objects.exclude(user_permissions=None)) + self.assertListEqual(data11, [u]) + + u.user_permissions.clear() + + with self.assertNumQueries(1): + data12 = list(User.objects.exclude(user_permissions=None)) + self.assertListEqual(data12, []) + def test_invalidate_nested_subqueries(self): with self.assertNumQueries(1): data1 = list( @@ -810,88 +820,6 @@ class WriteTestCase(TransactionTestCase): list(Test.objects.values_list('name', flat=True)), []) - def test_clear_with_filters(self): - names = ['Thing 1', 'Thing 2', 'Thing 3'] - for name in names: - thing = TestThese() - thing.name = name - thing.save() - hub = TestOne() - hub.name = 'Has lots' - hub.save() - for thing in TestThese.objects.all(): - hub.have_lots_of_these.add(thing) - hub.save() - # read the number of things that hub has got - with self.assertNumQueries(1): - nt = list(hub.have_lots_of_these.all()) - self.assertEqual(3, len(nt)) - - # read it again - with self.assertNumQueries(0): - list(hub.have_lots_of_these.all()) - - # read the number of TestOnes that have no things - with self.assertNumQueries(1): - ns = TestOne.objects.filter(have_lots_of_these=None).count() - self.assertEqual(ns, 0) - - # now do a .clear on hub (which is a TestOne) and make sure db is queried for subsequent read - hub.have_lots_of_these.clear() - with self.assertNumQueries(1): - things = list(hub.have_lots_of_these.all()) - self.assertEqual(0, len(things)) - - # again, query for the number of TestOnes that have no things. There - # should be one now - with self.assertNumQueries(1): - ns = TestOne.objects.filter(have_lots_of_these=None).count() - # there should now be one - self.assertEqual(ns, 1) - - def test_clear_with_excludes(self): - ''' - same test as above but using excludes rather than filters - ''' - names = ['Thing 1', 'Thing 2', 'Thing 3'] - for name in names: - thing = TestThese() - thing.name = name - thing.save() - hub = TestOne() - hub.name = 'Has lots' - hub.save() - for thing in TestThese.objects.all(): - hub.have_lots_of_these.add(thing) - hub.save() - - # read the number of things that hub has got - with self.assertNumQueries(1): - nt = list(hub.have_lots_of_these.all()) - self.assertEqual(3, len(nt)) - - # read it again - with self.assertNumQueries(0): - list(hub.have_lots_of_these.all()) - - # read the number of TestOnes that have things via an exclude - # there should be one - with self.assertNumQueries(1): - ns = TestOne.objects.exclude(have_lots_of_these=None).count() - self.assertEqual(ns, 1) - - # now do a .clear on hub (which is a TestOne) and make sure db is queried for subsequent read - hub.have_lots_of_these.clear() - with self.assertNumQueries(1): - things = list(hub.have_lots_of_these.all()) - self.assertEqual(0, len(things)) - - # again, query for the number of TestOnes that have things. There - # should be none now - with self.assertNumQueries(1): - ns = TestOne.objects.exclude(have_lots_of_these=None).count() - self.assertEqual(ns, 0) - class DatabaseCommandTestCase(TransactionTestCase): def setUp(self):
Rewrites #<I> in a minimal way, using an existing test and the models.
noripyt_django-cachalot
train
f65bd8db2c9181a3c006ffc55e8298ce48572074
diff --git a/src/main/java/org/dmfs/iterators/ArrayIterator.java b/src/main/java/org/dmfs/iterators/ArrayIterator.java index <HASH>..<HASH> 100644 --- a/src/main/java/org/dmfs/iterators/ArrayIterator.java +++ b/src/main/java/org/dmfs/iterators/ArrayIterator.java @@ -57,10 +57,6 @@ public final class ArrayIterator<E> extends AbstractBaseIterator<E> @Override public E next() { - // wipe the values as we iterate, so we don't keep any values around longer than we need to. - E next = mValue[mNext]; - mValue[mNext] = null; - mNext += 1; - return next; + return mValue[mNext++]; } } \ No newline at end of file
Fix ArrayIterator. Make sure it doesn't delete values in the array. Fixes #<I> (#<I>)
dmfs_iterators
train
4206472557b08bc068859a75b90c2cd715d66738
diff --git a/src/Synapse/Application/Routes.php b/src/Synapse/Application/Routes.php index <HASH>..<HASH> 100644 --- a/src/Synapse/Application/Routes.php +++ b/src/Synapse/Application/Routes.php @@ -3,6 +3,7 @@ namespace Synapse\Application; use Symfony\Component\HttpFoundation\Response; +use Symfony\Component\HttpFoundation\JsonResponse; use Synapse\Application; /** @@ -16,6 +17,11 @@ class Routes implements RoutesInterface */ public function define(Application $app) { + $app->error(function (\Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException $e, $code) { + $body = ['error' => 'Access denied']; + return new JsonResponse($body, 403); + }); + $app->error(function (\Synapse\Rest\Exception\MethodNotImplementedException $e, $code) { $response = new Response('Method not implemented'); $response->setStatusCode(501);
Refs #<I> - Catch access denied exceptions and return JSON response.
synapsestudios_synapse-base
train
f2386026af0b0d98e4ae210766ae9b86359e6205
diff --git a/gcloud/pubsub/__init__.py b/gcloud/pubsub/__init__.py index <HASH>..<HASH> 100644 --- a/gcloud/pubsub/__init__.py +++ b/gcloud/pubsub/__init__.py @@ -32,6 +32,8 @@ from gcloud.pubsub._implicit_environ import get_default_connection from gcloud.pubsub.api import list_subscriptions from gcloud.pubsub.api import list_topics from gcloud.pubsub.connection import Connection +from gcloud.pubsub.subscription import Subscription +from gcloud.pubsub.topic import Topic SCOPE = ('https://www.googleapis.com/auth/pubsub',
Make Subscription / Topic importable from pubsub.
googleapis_google-cloud-python
train
435fe6f690e4ba7b83fbe2bdf0676054b804fea6
diff --git a/better_figures_and_images/better_figures_and_images.py b/better_figures_and_images/better_figures_and_images.py index <HASH>..<HASH> 100644 --- a/better_figures_and_images/better_figures_and_images.py +++ b/better_figures_and_images/better_figures_and_images.py @@ -45,6 +45,9 @@ def content_object_init(instance): img_path = img_path[10:] elif img_path.startswith('/static'): img_path = img_path[7:] + elif img_path.startswith('data:image'): + # Image is encoded in-line (not a file). + break else: logger.warning('Better Fig. Error: img_path should start with either {filename}, |filename| or /static')
Add exception for in-line encoded images Adds a simple exception for images which are encoded in-line (base<I>, etc). This allows Better Fig. to be used with the [Graphviz](<URL>) plugin (which is exactly my use-case, heh).
getpelican_pelican-plugins
train
ac6ce2299d816fb734749e96b41bda249e5ed48d
diff --git a/src/bbn/Appui/Task.php b/src/bbn/Appui/Task.php index <HASH>..<HASH> 100644 --- a/src/bbn/Appui/Task.php +++ b/src/bbn/Appui/Task.php @@ -954,7 +954,8 @@ class Task extends bbn\Models\Cls\Db 'deadline' => $cfg['deadline'] ?? NULL, 'id_user' => $this->id_user ?: NULL, 'state' => $cfg['state'] ?? $this->idState('opened'), - 'creation_date' => $this->date ?: date('Y-m-d H:i:s') + 'creation_date' => $this->date ?: date('Y-m-d H:i:s'), + 'cfg' => \json_encode(['widgets' => []]) ]) ){ $id = $this->db->lastId(); $this->addLog($id, 'insert');
Added cfg field on insert method
nabab_bbn
train
e2b24fd37dc9ce6d6f7fe1b8942a773988ffe9b0
diff --git a/src/StackFormation/Blueprint.php b/src/StackFormation/Blueprint.php index <HASH>..<HASH> 100644 --- a/src/StackFormation/Blueprint.php +++ b/src/StackFormation/Blueprint.php @@ -66,15 +66,21 @@ class Blueprint return null; } - public function getPreprocessedTemplate($gatherDependencies = true, $force = false) + public function getTemplates() { - if (empty($this->blueprintConfig['template']) || !is_array($this->blueprintConfig['template'])) { - throw new \Exception('No template(s) found'); - } + return (array_key_exists('template', $this->blueprintConfig) ? (array)$this->blueprintConfig['template'] : array()); + } + + public function getOptionalTemplates() + { + return (array_key_exists('optionalTemplates', $this->blueprintConfig) ? (array)$this->blueprintConfig['optionalTemplates'] : array()); + } + public function getPreprocessedTemplate($gatherDependencies = true, $force = false) + { // convert templates paths to template objects $templates = []; - foreach ($this->blueprintConfig['template'] as $key => $templateFile) { + foreach ($this->getTemplates() as $key => $templateFile) { $templateFile = $this->getBasePath() . '/' . $this->valueResolver->resolvePlaceholders($templateFile, $this, 'template'); $realTemplateFile = realpath($templateFile); if ($realTemplateFile === false || !is_file($realTemplateFile) || !is_readable($realTemplateFile)) { @@ -82,7 +88,7 @@ class Blueprint } $templates[] = (is_int($key) ? new Template($realTemplateFile) : new PrefixedTemplate($key, $realTemplateFile)); }; - foreach ($this->blueprintConfig['optionalTemplates'] as $key => $templateFile) { + foreach ($this->getOptionalTemplates() as $key => $templateFile) { $templateFile = $this->getBasePath() . '/' . $this->valueResolver->resolvePlaceholders($templateFile, $this, 'optionalTemplates'); $realTemplateFiles = glob($templateFile); foreach ($realTemplateFiles as $realTemplateFile) { @@ -92,6 +98,10 @@ class Blueprint } }; + if (count($templates) === 0) { + throw new \Exception('No template(s) found'); + } + // Create blueprint reference if ($gatherDependencies) { $this->gatherDependencies(); @@ -130,12 +140,12 @@ class Blueprint } $prefixes = []; - foreach (array_keys($this->blueprintConfig['template']) as $key) { + foreach (array_keys($this->getTemplates()) as $key) { if (!is_int($key)) { $prefixes[] = $key; } } - foreach (array_keys($this->blueprintConfig['optionalTemplates']) as $key) { + foreach (array_keys($this->getOptionalTemplates()) as $key) { if (!is_int($key)) { $prefixes[] = $key; }
Add helper methods to access the template and optionalTemplates arrays
AOEpeople_StackFormation
train
6a63e76fc8d81cceec41459500dc22747c9bc8a9
diff --git a/asammdf/mdf_v4.py b/asammdf/mdf_v4.py index <HASH>..<HASH> 100644 --- a/asammdf/mdf_v4.py +++ b/asammdf/mdf_v4.py @@ -888,7 +888,7 @@ class MDF4(object): attachment_addr = channel['attachment_0_addr'] if attachment_addr not in self._dbc_cache: attachment, at_name = self.extract_attachment(address=attachment_addr) - if not at_name.lower().endswith(('dbc', 'arxml')): + if not at_name.lower().endswith(('dbc', 'arxml')) or not attachment: warnings.warn('Expected .dbc or .arxml file as CAN channel attachment but got "{}"'.format(at_name)) grp['channel_group']['flags'] &= ~v4c.FLAG_CG_BUS_EVENT else:
ignore bus logging if database attachment is not available
danielhrisca_asammdf
train
f138c5b18b9521bacd3f530dc7ba4582d14679b7
diff --git a/webit-script/src/main/java/webit/script/asm/AsmResolverGenerator.java b/webit-script/src/main/java/webit/script/asm/AsmResolverGenerator.java index <HASH>..<HASH> 100644 --- a/webit-script/src/main/java/webit/script/asm/AsmResolverGenerator.java +++ b/webit-script/src/main/java/webit/script/asm/AsmResolverGenerator.java @@ -273,9 +273,9 @@ public class AsmResolverGenerator implements Opcodes { } private void attachIfFieldMatchCode(GeneratorAdapter mg, FieldInfo fieldInfo, Label elseJumpTo) { - mg.loadArg(1); //property mg.push(fieldInfo.getName()); - mg.invokeVirtual(ASMUtil.TYPE_OBJECT, METHOD_EQUALS); + mg.loadArg(1); //property + mg.invokeVirtual(ASMUtil.TYPE_STRING, METHOD_EQUALS); mg.ifZCmp(GeneratorAdapter.EQ, elseJumpTo); // if == 0 jump }
AsmResolverGenerator small adjust
febit_wit
train
06fd9d67f79061f6791d75e5b6f3fb760172f680
diff --git a/scripts/bcbio_fastq_umi_prep.py b/scripts/bcbio_fastq_umi_prep.py index <HASH>..<HASH> 100755 --- a/scripts/bcbio_fastq_umi_prep.py +++ b/scripts/bcbio_fastq_umi_prep.py @@ -38,8 +38,8 @@ transform_json = r"""{ """ duplex_transform = r"""{ - "read1": "(?P<name>[^\\s]+).*\\n(?P<CB1>.{%s})(?P<seq>.*)\\n\\+(.*)\\n(.{%s})(?P<qual>.*)\\n", - "read2": "(?P<name>[^\\s]+).*\\n(?P<CB2>.{%s})(?P<seq>.*)\\n\\+(.*)\\n(.{%s})(?P<qual>.*)\\n" + "read1": "(?P<name>@.*)\\n(?P<CB1>.{%s})(?P<seq>.*)\\n\\+(.*)\\n(.{%s})(?P<qual>.*)\\n", + "read2": "(?P<name>@.*)\\n(?P<CB2>.{%s})(?P<seq>.*)\\n\\+(.*)\\n(.{%s})(?P<qual>.*)\\n" }""" def run_single(args):
UMI: Pass full fastq name for duplex prep The previous regex only passed the first part of a name, dropping secondary tag information already present from bcl2fastq.
bcbio_bcbio-nextgen
train
c412f5eed586203205f82449a9869640b8093246
diff --git a/tests/common.py b/tests/common.py index <HASH>..<HASH> 100644 --- a/tests/common.py +++ b/tests/common.py @@ -52,7 +52,7 @@ class TrezorBootloaderTest(unittest.TestCase): def reconnect(self): self.client.close() - time.sleep(5) + time.sleep(10) config.enumerate_hid() self.debug_transport = config.DEBUG_TRANSPORT(*config.DEBUG_TRANSPORT_ARGS, **config.DEBUG_TRANSPORT_KWARGS)
increase delay between device renumuration
keepkey_python-keepkey
train
2dcff138562aa5875b0439ca34d41341bcd6255d
diff --git a/lib/engine_ws.js b/lib/engine_ws.js index <HASH>..<HASH> 100644 --- a/lib/engine_ws.js +++ b/lib/engine_ws.js @@ -112,9 +112,11 @@ WSEngine.prototype.compile = function (tasks, scenarioSpec, ee) { if (err) { debug(err); } - if (context.ws) { + + if (context && context.ws) { context.ws.close(); } + return callback(err, context); }); };
Fix: prevent from crashing when context is null/undefined
artilleryio_artillery
train
0f8e5174adf63174202560a12c66a68d07b06082
diff --git a/CHANGELOG.md b/CHANGELOG.md index <HASH>..<HASH> 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,7 @@ next release / 2014-02-?? * added `publicKey` property * added `pubKeyHash`/`publicHash` property * added `publicPoint`, removed `getPubPoint()` +* removed `getPub()`, use `publicKey` instead 0.3.0 / 2014-02-03 ------------------ diff --git a/lib/eckey.js b/lib/eckey.js index <HASH>..<HASH> 100644 --- a/lib/eckey.js +++ b/lib/eckey.js @@ -97,7 +97,7 @@ Object.defineProperty(ECKey.prototype, 'privateKey', { Object.defineProperty(ECKey.prototype, 'publicKey', { get: function() { - return new Buffer(this.getPub()); + return new Buffer(this.publicPoint.getEncoded(this.compressed)); } }) @@ -151,16 +151,7 @@ ECKey.prototype.setCompressed = function (v) { this.compressed = !!v; }; -/** - * Return public key in DER encoding. - */ -ECKey.prototype.getPub = function () { - var shit = this.publicPoint.getEncoded(this.compressed); - //console.log(shit.length) - //console.log(shit.join(', ')); - //process.exit(); - return shit; -}; + /** @@ -172,7 +163,7 @@ ECKey.prototype.getPub = function () { ECKey.prototype.getPubKeyHash = function () { if (this._pubKeyHash) return this._pubKeyHash; - return this._pubKeyHash = hashing.sha256ripe160(this.getPub(), {in: 'bytes', out: 'bytes'}); + return this._pubKeyHash = hashing.sha256ripe160(this.publicKey, {in: 'buffer', out: 'bytes'}); }; ECKey.prototype.getAddress = function (address_type) { diff --git a/test/eckey.test.js b/test/eckey.test.js index <HASH>..<HASH> 100644 --- a/test/eckey.test.js +++ b/test/eckey.test.js @@ -116,28 +116,6 @@ describe('ECKey', function() { }) - describe('- getPub()', function() { - describe('> when not compressed', function() { - it('should generate the public key uncompressed', function() { - var privateKeyBytes = conv("1184CD2CDD640CA42CFC3A091C51D549B2F016D454B2774019C2B2D2E08529FD", {in: 'hex', out: 'bytes'}) - var eckey = new ECKey(privateKeyBytes) - var publicKeyHex = conv(eckey.getPub(), {in: 'bytes', out: 'hex'}) - EQ (publicKeyHex, "04d0988bfa799f7d7ef9ab3de97ef481cd0f75d2367ad456607647edde665d6f6fbdd594388756a7beaf73b4822bc22d36e9bda7db82df2b8b623673eefc0b7495") - }) - }) - - describe('> when compressed', function() { - it('should generate the public key uncompressed', function() { - var privateKeyBytes = conv("1184CD2CDD640CA42CFC3A091C51D549B2F016D454B2774019C2B2D2E08529FD", {in: 'hex', out: 'bytes'}) - var eckey = new ECKey(privateKeyBytes) - eckey.compressed = true - var publicKeyHex = conv(eckey.getPub(), {in: 'bytes', out: 'hex'}) - EQ (publicKeyHex, "03d0988bfa799f7d7ef9ab3de97ef481cd0f75d2367ad456607647edde665d6f6f") //this feels wrong, extra '6f' on the end? investigate - - }) - }) - }) - describe('- getBitcoinAddress()', function() { describe('> when not compressed', function() { it('should generate the address of the uncompressed public key', function() {
got rid of `getPub`
cryptocoinjs_eckey
train
caa2d4e1ed77562eb539ded1a9f21ea4651d16a8
diff --git a/heartbeat.go b/heartbeat.go index <HASH>..<HASH> 100644 --- a/heartbeat.go +++ b/heartbeat.go @@ -130,7 +130,7 @@ func (k *Kite) sendHeartbeats(interval time.Duration, kiteURL *url.URL) { errRegisterAgain := errors.New("register again") heartbeatFunc := func() error { - k.Log.Info("Sending heartbeat to %s", u.String()) + k.Log.Debug("Sending heartbeat to %s", u.String()) resp, err := http.Get(u.String()) if err != nil { @@ -145,7 +145,7 @@ func (k *Kite) sendHeartbeats(interval time.Duration, kiteURL *url.URL) { return err } - k.Log.Info("Heartbeat response received '%s'", string(body)) + k.Log.Debug("Heartbeat response received '%s'", string(body)) switch string(body) { case "pong":
heartbeat: don't use info for those
koding_kite
train
9477bd2e5893a83a40a031244fe298995bd6f554
diff --git a/structr-core/src/main/java/org/structr/core/Services.java b/structr-core/src/main/java/org/structr/core/Services.java index <HASH>..<HASH> 100644 --- a/structr-core/src/main/java/org/structr/core/Services.java +++ b/structr-core/src/main/java/org/structr/core/Services.java @@ -149,20 +149,16 @@ public class Services implements StructrServices { final String configFileName = "structr.conf"; final File configFile = new File(configFileName); - if (!configFile.exists()) { + if (Settings.Testing.getValue()) { - if (Settings.Testing.getValue()) { - - // simulate fully configured system - hasConfigFile = true; - logger.info("Starting Structr for testing.."); - - } else { + // simulate fully configured system + hasConfigFile = true; + logger.info("Starting Structr for testing.."); + } else if (!configFile.exists()) { - hasConfigFile = false; - logger.info("{} not found, starting configuration wizard..", configFileName); - } + hasConfigFile = false; + logger.info("{} not found, starting configuration wizard..", configFileName); } else {
Modifies Services.java to ignore structr.conf when the "testing" flag is set.
structr_structr
train
3c81c090cc4dd933c61c733fdb9aec39c873b93a
diff --git a/setup.py b/setup.py index <HASH>..<HASH> 100644 --- a/setup.py +++ b/setup.py @@ -4,7 +4,7 @@ from os import path from distutils.version import LooseVersion from setuptools import find_packages, setup -VERSION = '1.15.0' +VERSION = '1.15.1' # Import README.md into long_description pwd = path.abspath(path.dirname(__file__))
Bump package version to <I>
instana_python-sensor
train
b424d3dcd01017076f62dcb2ae25e6bd7cd2f30c
diff --git a/shardingsphere-jdbc/shardingsphere-jdbc-spring/shardingsphere-jdbc-spring-infra/shardingsphere-jdbc-spring-namespace-infra/src/main/java/org/apache/shardingsphere/spring/namespace/parser/ShardingSphereAlgorithmBeanRegistry.java b/shardingsphere-jdbc/shardingsphere-jdbc-spring/shardingsphere-jdbc-spring-infra/shardingsphere-jdbc-spring-namespace-infra/src/main/java/org/apache/shardingsphere/spring/namespace/parser/ShardingSphereAlgorithmBeanRegistry.java index <HASH>..<HASH> 100644 --- a/shardingsphere-jdbc/shardingsphere-jdbc-spring/shardingsphere-jdbc-spring-infra/shardingsphere-jdbc-spring-namespace-infra/src/main/java/org/apache/shardingsphere/spring/namespace/parser/ShardingSphereAlgorithmBeanRegistry.java +++ b/shardingsphere-jdbc/shardingsphere-jdbc-spring/shardingsphere-jdbc-spring-infra/shardingsphere-jdbc-spring-namespace-infra/src/main/java/org/apache/shardingsphere/spring/namespace/parser/ShardingSphereAlgorithmBeanRegistry.java @@ -39,7 +39,8 @@ public final class ShardingSphereAlgorithmBeanRegistry { * @param algorithmFactoryBeanClass ShardingSphere algorithm factory bean class * @return ShardingSphere algorithm bean references */ - public static Map<String, RuntimeBeanReference> getAlgorithmBeanReferences(final ParserContext parserContext, final Class<? extends ShardingSphereAlgorithmFactoryBean> algorithmFactoryBeanClass) { + public static Map<String, RuntimeBeanReference> getAlgorithmBeanReferences(final ParserContext parserContext, + final Class<? extends ShardingSphereAlgorithmFactoryBean<?>> algorithmFactoryBeanClass) { String[] beanDefinitionNames = parserContext.getRegistry().getBeanDefinitionNames(); String algorithmFactoryBeanClassName = algorithmFactoryBeanClass.getName(); Map<String, RuntimeBeanReference> result = new ManagedMap<>(beanDefinitionNames.length);
Refactor ShardingSphereAlgorithmBeanRegistry
apache_incubator-shardingsphere
train
265459962c8130a76b457e9cd2fb548bd00cd9d0
diff --git a/grunt/exec.js b/grunt/exec.js index <HASH>..<HASH> 100644 --- a/grunt/exec.js +++ b/grunt/exec.js @@ -44,7 +44,7 @@ const testConfig = (name, rawCommand, parameters) => { let command; - if (isWindows && rawCommand.indexOf(" ") !== -1) { + if (isWindows && rawCommand.includes(" ")) { command = `"${rawCommand}"`; } else { command = rawCommand;
no-magic-numbers (#<I>)
ArnaudBuchholz_gpf-js
train
dc0d0dca6d1a285fdd8cb990438a47fb46ccf578
diff --git a/src/collection/dimensions.js b/src/collection/dimensions.js index <HASH>..<HASH> 100644 --- a/src/collection/dimensions.js +++ b/src/collection/dimensions.js @@ -221,6 +221,8 @@ fn = elesfn = ({ var updated = []; function update( parent ){ + if( !parent.isParent() ){ return; } + var _p = parent._private; var children = parent.children(); var includeLabels = parent.pstyle( 'compound-sizing-wrt-labels' ).value === 'include'; @@ -260,7 +262,7 @@ fn = elesfn = ({ } // go up, level by level - var eles = this.parent(); + var eles = this; while( eles.nonempty() ){ // update each parent node in this level
Updating compound bounds should happen from the current level up #<I>
cytoscape_cytoscape.js
train
5cbb66dfc3e0cdacc5101d2baf9a949918cff0a8
diff --git a/packages/ra-ui-materialui/src/button/BulkDeleteWithConfirmButton.js b/packages/ra-ui-materialui/src/button/BulkDeleteWithConfirmButton.js index <HASH>..<HASH> 100644 --- a/packages/ra-ui-materialui/src/button/BulkDeleteWithConfirmButton.js +++ b/packages/ra-ui-materialui/src/button/BulkDeleteWithConfirmButton.js @@ -46,6 +46,8 @@ const BulkDeleteWithConfirmButton = ({ crudDeleteMany, icon, label, + confirmTitle = 'ra.message.bulk_delete_title', + confirmContent = 'ra.message.bulk_delete_content', onClick, resource, selectedIds, @@ -105,8 +107,8 @@ const BulkDeleteWithConfirmButton = ({ <Confirm isOpen={isOpen} loading={loading} - title="ra.message.bulk_delete_title" - content="ra.message.bulk_delete_content" + title={confirmTitle} + content={confirmContent} translateOptions={{ smart_count: selectedIds.length, name: inflection.humanize(
Provide props to customize Confirm title and content for delete buttons.
marmelab_react-admin
train
a261c7817e4bad7f1a9f196c7287f8879dabf0c1
diff --git a/gui/src/main/java/org/jboss/as/console/client/core/UIConstants.java b/gui/src/main/java/org/jboss/as/console/client/core/UIConstants.java index <HASH>..<HASH> 100644 --- a/gui/src/main/java/org/jboss/as/console/client/core/UIConstants.java +++ b/gui/src/main/java/org/jboss/as/console/client/core/UIConstants.java @@ -619,4 +619,6 @@ public interface UIConstants extends Constants { String subsys_jgroups_err_protocols_required(); String subsys_modcluster_desc(); + + String subsys_jca_err_prop_required(); } diff --git a/gui/src/main/java/org/jboss/as/console/client/core/UIConstants.properties b/gui/src/main/java/org/jboss/as/console/client/core/UIConstants.properties index <HASH>..<HASH> 100644 --- a/gui/src/main/java/org/jboss/as/console/client/core/UIConstants.properties +++ b/gui/src/main/java/org/jboss/as/console/client/core/UIConstants.properties @@ -253,4 +253,5 @@ subsys_security_providerModules=Provider Modules subsys_security_typeField=Type subsys_threads_sizing=Sizing subsys_ws_endpoints=Endpoints -subsys_ws_provider=Provider \ No newline at end of file +subsys_ws_provider=Provider +subsys_jca_err_prop_required=At least one XA property is required (i.e. url). \ No newline at end of file diff --git a/gui/src/main/java/org/jboss/as/console/client/shared/subsys/jca/wizard/XADatasourceStep3.java b/gui/src/main/java/org/jboss/as/console/client/shared/subsys/jca/wizard/XADatasourceStep3.java index <HASH>..<HASH> 100644 --- a/gui/src/main/java/org/jboss/as/console/client/shared/subsys/jca/wizard/XADatasourceStep3.java +++ b/gui/src/main/java/org/jboss/as/console/client/shared/subsys/jca/wizard/XADatasourceStep3.java @@ -47,6 +47,7 @@ public class XADatasourceStep3 implements PropertyManagement { private PropertyEditor propEditor; private List<PropertyRecord> properties; private BeanFactory factory = GWT.create(BeanFactory.class); + private HTML errorMessages; public XADatasourceStep3(NewXADatasourceWizard wizard) { this.wizard = wizard; @@ -81,6 +82,8 @@ public class XADatasourceStep3 implements PropertyManagement { properties.add(proto); propEditor.setProperties("", properties); + + errorMessages.setVisible(false); } @Override @@ -96,13 +99,25 @@ public class XADatasourceStep3 implements PropertyManagement { propEditor = new PropertyEditor(this, true); + errorMessages = new HTML(Console.CONSTANTS.subsys_jca_err_prop_required()); + errorMessages.setStyleName("error-panel"); + errorMessages.setVisible(false); + + layout.add(errorMessages); + Widget widget = propEditor.asWidget(); layout.add(widget); ClickHandler submitHandler = new ClickHandler() { @Override public void onClick(ClickEvent event) { - wizard.onConfigureProperties(properties); + + boolean hasProperties = propEditor.getPropertyTable().getRowCount() > 0; + + if(!hasProperties) + errorMessages.setVisible(true); + else + wizard.onConfigureProperties(properties); } };
prevent creation of XA datasources w/o connection properties
hal_core
train
d7026a10e4de58aa34708e82f338a9c89f8ad72c
diff --git a/lib/obj.js b/lib/obj.js index <HASH>..<HASH> 100644 --- a/lib/obj.js +++ b/lib/obj.js @@ -141,14 +141,14 @@ if (!obj) return; var clone = {}; for (var i in obj) { - if (obj.hasOwnProperty(i)) { + //if (obj.hasOwnProperty(i)) { if ( 'object' === typeof obj[i] ) { clone[i] = OBJ.clone(obj[i]); } else { clone[i] = obj[i]; } - } + //} } return clone; };
Creating GameTable widget. not finished
nodeGame_JSUS
train
eed3e8d56fbcc8288a3a225b2303b96802ad5b89
diff --git a/setup.py b/setup.py index <HASH>..<HASH> 100644 --- a/setup.py +++ b/setup.py @@ -34,7 +34,7 @@ def runSetup(): gcs = 'google-cloud-storage==1.6.0' gcs_oauth2_boto_plugin = 'gcs_oauth2_boto_plugin==1.14' apacheLibcloud = 'apache-libcloud==2.2.1' - cwltool = 'cwltool==1.0.20190815141648' + cwltool = 'cwltool==1.0.20190906054215' schemaSalad = 'schema-salad<5,>=4.5.20190815125611' galaxyLib = 'galaxy-lib==18.9.2' htcondor = 'htcondor>=8.6.0'
use cwltool with needed prov fixes
DataBiosphere_toil
train
0a2e583b4d2e0ed16174cc351ec81a3d46f442ed
diff --git a/multiqc/utils/report.py b/multiqc/utils/report.py index <HASH>..<HASH> 100644 --- a/multiqc/utils/report.py +++ b/multiqc/utils/report.py @@ -376,7 +376,21 @@ def save_htmlid(html_id, skiplint=False): def compress_json(data): """ Take a Python data object. Convert to JSON and compress using lzstring """ json_string = json.dumps(data).encode('utf-8', 'ignore').decode('utf-8') - # JSON.parse() doesn't handle `NaN`, but it does handle `null`. - json_string = json_string.replace('NaN', 'null'); + json_string = sanitise_json(json_string) x = lzstring.LZString() return x.compressToBase64(json_string) + +def sanitise_json(json_string): + """ + The Python json module uses a bunch of values which are valid JavaScript + but invalid JSON. These crash the browser when parsing the JSON. + Nothing in the MultiQC front-end uses these values, so instead we just + do a find-and-replace for them and switch them with `null`, which works fine. + + Side effect: Any string values that include the word "Infinity" + (case-sensitive) will have it switched for "null". Hopefully that doesn't happen + a lot, otherwise we'll have to do this in a more complicated manner. + """ + json_string = re.sub(r'\bNaN\b', 'null', json_string) + json_string = re.sub(r'\b-?Infinity\b', 'null', json_string) + return json_string
Sanitise JSON string to remove Infinity. Fixes nf-core/Sarek#<I> and provides a more general fix for #<I>
ewels_MultiQC
train
78bfe5a31e71fc83605aeeef6d27966968764afc
diff --git a/wireless/Wireless.py b/wireless/Wireless.py index <HASH>..<HASH> 100644 --- a/wireless/Wireless.py +++ b/wireless/Wireless.py @@ -46,7 +46,6 @@ class Wireless: response = cmd('nmcli --version') parts = response.split() ver = parts[-1] - print 'test: '+ver compare = self.vercmp(ver, "0.9.9.0") if compare >= 0: return 'nmcli0990'
remove debug line also fixes python version error
joshvillbrandt_wireless
train
7886497a367ded5ffa5a45784c36b1e442d7c5dc
diff --git a/core/src/main/java/org/kohsuke/stapler/MetaClassLoader.java b/core/src/main/java/org/kohsuke/stapler/MetaClassLoader.java index <HASH>..<HASH> 100644 --- a/core/src/main/java/org/kohsuke/stapler/MetaClassLoader.java +++ b/core/src/main/java/org/kohsuke/stapler/MetaClassLoader.java @@ -52,8 +52,11 @@ public class MetaClassLoader extends TearOffSupport { try { String path = System.getProperty("stapler.resourcePath"); if(path!=null) { - debugLoader = new MetaClassLoader( - new URLClassLoader(new URL[]{new File(path).toURI().toURL()})); + String[] tokens = path.split(";"); + URL[] urls = new URL[tokens.length]; + for (int i=0; i<tokens.length; i++) + urls[i] = new File(tokens[i]).toURI().toURL(); + debugLoader = new MetaClassLoader(new URLClassLoader(urls)); } } catch (MalformedURLException e) { throw new Error(e);
support multiple locations in stapler.resourcePath, separated by ";"
stapler_stapler
train
51dd80def214d05b5c46fdcd2771cd8efcf22dc0
diff --git a/pyramid_orb/rest/resources.py b/pyramid_orb/rest/resources.py index <HASH>..<HASH> 100644 --- a/pyramid_orb/rest/resources.py +++ b/pyramid_orb/rest/resources.py @@ -50,7 +50,8 @@ class Resource(RestService): raise KeyError(key) def get(self): - return self.record.json() + lookup = get_lookup(self.request) + return self.record.json(lookup=lookup) def patch(self): values = collect_params(self.request)
passing in the lookup options to the model
orb-framework_pyramid_orb
train
f04e57c80254b19b3f448ed335f90de02d54f1bb
diff --git a/src/events/http/Http.js b/src/events/http/Http.js index <HASH>..<HASH> 100644 --- a/src/events/http/Http.js +++ b/src/events/http/Http.js @@ -17,7 +17,7 @@ export default class Http { return this.#httpServer.stop(timeout) } - _create(functionKey, rawHttpEventDefinition, handler) { + #createEvent(functionKey, rawHttpEventDefinition, handler) { const httpEvent = new HttpEventDefinition(rawHttpEventDefinition) this.#httpServer.createRoutes(functionKey, httpEvent, handler) @@ -25,7 +25,7 @@ export default class Http { create(events) { events.forEach(({ functionKey, handler, http }) => { - this._create(functionKey, http, handler) + this.#createEvent(functionKey, http, handler) }) this.#httpServer.writeRoutesTerminal() diff --git a/src/events/websocket/WebSocket.js b/src/events/websocket/WebSocket.js index <HASH>..<HASH> 100644 --- a/src/events/websocket/WebSocket.js +++ b/src/events/websocket/WebSocket.js @@ -48,7 +48,7 @@ export default class WebSocket { ]) } - _create(functionKey, rawWebSocketEventDefinition) { + #createEvent(functionKey, rawWebSocketEventDefinition) { const webSocketEvent = new WebSocketEventDefinition( rawWebSocketEventDefinition, ) @@ -58,7 +58,7 @@ export default class WebSocket { create(events) { events.forEach(({ functionKey, websocket }) => { - this._create(functionKey, websocket) + this.#createEvent(functionKey, websocket) }) } } diff --git a/src/lambda/Lambda.js b/src/lambda/Lambda.js index <HASH>..<HASH> 100644 --- a/src/lambda/Lambda.js +++ b/src/lambda/Lambda.js @@ -25,14 +25,14 @@ export default class Lambda { ) } - _create(functionKey, functionDefinition) { + #createEvent(functionKey, functionDefinition) { this.#lambdas.set(functionKey, functionDefinition) this.#lambdaFunctionNamesKeys.set(functionDefinition.name, functionKey) } create(lambdas) { lambdas.forEach(({ functionKey, functionDefinition }) => { - this._create(functionKey, functionDefinition) + this.#createEvent(functionKey, functionDefinition) }) } diff --git a/src/lambda/handler-runner/go-runner/GoRunner.js b/src/lambda/handler-runner/go-runner/GoRunner.js index <HASH>..<HASH> 100644 --- a/src/lambda/handler-runner/go-runner/GoRunner.js +++ b/src/lambda/handler-runner/go-runner/GoRunner.js @@ -161,7 +161,7 @@ export default class GoRunner { // refresh go.mod sync('go', ['mod', 'tidy']) chdir(this.#codeDir) - } catch (e) { + } catch { // @ignore }
refactor: use private methods (#<I>)
dherault_serverless-offline
train
9a11e9d9bbeaad88f49a81eb9ee21f8690078dd0
diff --git a/server/src/main/java/io/atomix/copycat/server/state/ServerState.java b/server/src/main/java/io/atomix/copycat/server/state/ServerState.java index <HASH>..<HASH> 100644 --- a/server/src/main/java/io/atomix/copycat/server/state/ServerState.java +++ b/server/src/main/java/io/atomix/copycat/server/state/ServerState.java @@ -67,6 +67,7 @@ public class ServerState { private Duration heartbeatInterval = Duration.ofMillis(150); private Scheduled joinTimer; private Scheduled leaveTimer; + private boolean joined; private int leader; private long term; private int lastVotedFor; @@ -223,6 +224,7 @@ public class ServerState { this.leader = leader; LOGGER.info("{} - Found leader {}", cluster.getMember().serverAddress(), member.serverAddress()); electionListeners.forEach(l -> l.accept(member.serverAddress())); + joinLeader(member); } } @@ -298,7 +300,7 @@ public class ServerState { ServerState setLastVotedFor(int candidate) { // If we've already voted for another candidate in this term then the last voted for candidate cannot be overridden. Assert.stateNot(lastVotedFor != 0 && candidate != 0l, "Already voted for another candidate"); - Assert.stateNot (leader != 0 && candidate != 0, "Cannot cast vote - leader already exists"); + Assert.stateNot(leader != 0 && candidate != 0, "Cannot cast vote - leader already exists"); Member member = cluster.getMember(candidate); Assert.state(member != null, "unknown candidate: %d", candidate); this.lastVotedFor = candidate; @@ -551,6 +553,9 @@ public class ServerState { // Cancel the join timer. cancelJoinTimer(); + // No need to send further join requests since this node manually joined the cluster. + joined = true; + // If the local member type is null, that indicates it's not a part of the configuration. MemberType type = cluster.getMember().type(); if (type == null) { @@ -614,6 +619,25 @@ public class ServerState { } /** + * Sends a join request to the given leader once found. + */ + private void joinLeader(Member leader) { + if (!joined && !cluster.getMember().equals(leader)) { + LOGGER.debug("{} - Sending server identification to {}", cluster.getMember().serverAddress(), leader.serverAddress()); + connections.getConnection(leader.serverAddress()).thenCompose(connection -> { + JoinRequest request = JoinRequest.builder() + .withMember(cluster.getMember()) + .build(); + return connection.<JoinRequest, JoinResponse>send(request); + }).whenComplete((response, error) -> { + if (error == null) { + joined = true; + } + }); + } + } + + /** * Leaves the cluster. */ public CompletableFuture<Void> leave() {
Send join request to first leader found if necessary.
atomix_copycat
train
757f1a88126ff3f4c76ac22b6a82af8aadad2d7f
diff --git a/tests/unit/nupic/regions/tm_region_test.py b/tests/unit/nupic/regions/tm_region_test.py index <HASH>..<HASH> 100644 --- a/tests/unit/nupic/regions/tm_region_test.py +++ b/tests/unit/nupic/regions/tm_region_test.py @@ -24,10 +24,15 @@ import tempfile import unittest +try: + import capnp +except ImportError: + capnp = None import numpy as np from nupic.regions.tm_region import TMRegion -from nupic.regions.tm_region_capnp import TMRegionProto +if capnp: + from nupic.regions.tm_region_capnp import TMRegionProto @@ -97,19 +102,26 @@ class TMRegionTest(unittest.TestCase): output2["lrnActiveStateT"])) + @unittest.skipUnless( + capnp, "pycapnp is not installed, skipping serialization test.") def testWriteReadPy(self): self.checkTMRegionImpl("py") + @unittest.skipUnless( + capnp, "pycapnp is not installed, skipping serialization test.") def testWriteReadCpp(self): self.checkTMRegionImpl("cpp") + @unittest.skipUnless( + capnp, "pycapnp is not installed, skipping serialization test.") def testWriteReadTMPy(self): self.checkTMRegionImpl("tm_py") - + @unittest.skipUnless( + capnp, "pycapnp is not installed, skipping serialization test.") def testWriteReadTMCpp(self): self.checkTMRegionImpl("tm_cpp")
Put capnp import checks in place for Windows
numenta_nupic
train
91bb3fb0eeb449425d5be48614f48c7a4dc5f2f5
diff --git a/js/runner.go b/js/runner.go index <HASH>..<HASH> 100644 --- a/js/runner.go +++ b/js/runner.go @@ -197,6 +197,7 @@ func (r *Runner) newVU(id int64, samplesOut chan<- stats.SampleContainer) (*VU, Console: r.console, BPool: bpool.NewBufferPool(100), Samples: samplesOut, + runMutex: sync.Mutex{}, } vu.Runtime.Set("__VU", vu.ID) vu.Runtime.Set("console", common.Bind(vu.Runtime, vu.Console, vu.Context)) @@ -367,6 +368,7 @@ type VU struct { Samples chan<- stats.SampleContainer + runMutex sync.Mutex setupData goja.Value } @@ -376,7 +378,6 @@ var _ lib.InitializedVU = &VU{} // ActiveVU holds a VU and its activation parameters type ActiveVU struct { - runMutex *sync.Mutex *VU *lib.VUActivationParams } @@ -394,7 +395,7 @@ func (u *VU) Activate(params *lib.VUActivationParams) lib.ActiveVU { } }() - return &ActiveVU{&sync.Mutex{}, u, params} + return &ActiveVU{u, params} } // RunOnce runs the default function once.
Move runMutex to js.VU Tests that share a VU like TestVURunInterruptDoesntPanic need to access the same mutex instance, otherwise it panics while reading setupData. This could be fixed in the test itself, but protecting against panics should be transparent to user code.
loadimpact_k6
train
6861331420285550a87417938924e96b318b4374
diff --git a/src/Controller/Plugin/MailPlugin.php b/src/Controller/Plugin/MailPlugin.php index <HASH>..<HASH> 100644 --- a/src/Controller/Plugin/MailPlugin.php +++ b/src/Controller/Plugin/MailPlugin.php @@ -24,12 +24,16 @@ class MailPlugin extends AbstractPlugin implements MailServiceAwareInterface } /** - * @param MailOptions $options + * @param MailOptions|array $options * @return MailServiceInterface */ - public function __invoke(MailOptions $options = null) + public function __invoke($options = null) { if (isset($options)) { + if (is_array($options)) { + $options = new MailOptions($options); + } + $this->configServiceFromOptions($options); }
Updated MailPlugin to accept options both as a MailOptions instance or an array
acelaya_ZF-AcMailer
train
756da8877121054a8de5371a25044fedac7d0d13
diff --git a/sebastian/core/transforms.py b/sebastian/core/transforms.py index <HASH>..<HASH> 100644 --- a/sebastian/core/transforms.py +++ b/sebastian/core/transforms.py @@ -155,7 +155,7 @@ def lilypond(point): if m > 0: modifier_string = "is" * m elif m < 0: - modifier_string = "es" * m + modifier_string = "es" * -m else: modifier_string = "" pitch_string = letter(pitch).lower() + modifier_string diff --git a/tests/test_transforms.py b/tests/test_transforms.py index <HASH>..<HASH> 100644 --- a/tests/test_transforms.py +++ b/tests/test_transforms.py @@ -275,12 +275,12 @@ class TestTransforms(TestCase): 'octave': 4, 'pitch': 11}, {'duration_64': 8, - 'lilypond': 'b8', + 'lilypond': 'bes8', 'midi_pitch': 58, 'octave': 4, 'pitch': -4}, {'duration_64': 8, - 'lilypond': 'b8', + 'lilypond': 'beses8', 'midi_pitch': 57, 'octave': 4, 'pitch': -11}
fixed bug in lilypond flat handling and test that was masking it
jtauber_sebastian
train
9c1fa60bcb73fc7bcd48e9f1487fb96cf9179882
diff --git a/lib/sgf/parser.rb b/lib/sgf/parser.rb index <HASH>..<HASH> 100644 --- a/lib/sgf/parser.rb +++ b/lib/sgf/parser.rb @@ -90,6 +90,10 @@ module SGF end end + def still_inside_node? + !NODE_DELIMITERS.include?(@sgf_stream.peek_skipping_whitespace) + end + def add_properties_to_current_node @current_node.add_properties @node_properties end @@ -125,6 +129,10 @@ module SGF @property.gsub! "\\]", "]" end + def still_inside_comment? char + char != "]" || (char == "]" && @property[-1..-1] == "\\") + end + def parse_multi_property while char = @sgf_stream.next_character and still_inside_multi_property? char @property << char @@ -132,23 +140,15 @@ module SGF @property = @property.gsub("][", ",").split(",") end - def parse_generic_property - while char = @sgf_stream.next_character and char != "]" - @property << char - end - end - - def still_inside_node? - !NODE_DELIMITERS.include?(@sgf_stream.peek_skipping_whitespace) - end - def still_inside_multi_property? char return true if char != "]" @sgf_stream.peek_skipping_whitespace == "[" end - def still_inside_comment? char - char != "]" || (char == "]" && @property[-1..-1] == "\\") + def parse_generic_property + while char = @sgf_stream.next_character and char != "]" + @property << char + end end end
Rearranged methods to express symmetry. Put each still_inside_ method next to its corresponding parse_ method. This also reveals that one parse method doesn't have a corresponding still_inside.
Trevoke_SGFParser
train
73f94e88ff8222d80e19e6b91db1036213080701
diff --git a/grade/report/singleview/version.php b/grade/report/singleview/version.php index <HASH>..<HASH> 100755 --- a/grade/report/singleview/version.php +++ b/grade/report/singleview/version.php @@ -22,6 +22,8 @@ * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ +defined('MOODLE_INTERNAL') || die(); + $plugin->component = 'gradereport_singleview'; // Full name of the plugin (used for diagnostics). $plugin->version = 2013081002; $plugin->requires = 2010090501;
MDL-<I> gradereport_singleview: missing MOODLE_INTERNAL
moodle_moodle
train
252c4dd0f923a955833a85f358914eedc0636a1f
diff --git a/holoviews/streams.py b/holoviews/streams.py index <HASH>..<HASH> 100644 --- a/holoviews/streams.py +++ b/holoviews/streams.py @@ -76,24 +76,6 @@ class Stream(param.Parameterized): for subscriber in subscribers: subscriber(union) - def update(self, trigger=True, **kwargs): - """ - The update method updates the stream parameters in response to - some event. - - If trigger is enabled, the trigger classmethod is invoked on - this particular Stream instance. - """ - params = self.params().values() - constants = [p.constant for p in params] - for param in params: - param.constant = False - self.set_param(**kwargs) - for (param, const) in zip(params, constants): - param.constant = const - - if trigger: - self.trigger([self]) @classmethod def find(cls, obj): @@ -102,6 +84,7 @@ class Stream(param.Parameterized): """ return set(v for v in cls.registry.values() if v.source is obj) + def __init__(self, preprocessors=[], source=None, subscribers=[], **params): """ Mapping allows multiple streams with similar event state to be @@ -120,6 +103,7 @@ class Stream(param.Parameterized): super(Stream, self).__init__(**params) self.registry[self.uuid] = self + @property def value(self): remapped = {k:v for k,v in self.get_param_values() if k!= 'name' } @@ -127,6 +111,27 @@ class Stream(param.Parameterized): remapped = preprocessor(remapped) return remapped + + def update(self, trigger=True, **kwargs): + """ + The update method updates the stream parameters in response to + some event. + + If trigger is enabled, the trigger classmethod is invoked on + this particular Stream instance. + """ + params = self.params().values() + constants = [p.constant for p in params] + for param in params: + param.constant = False + self.set_param(**kwargs) + for (param, const) in zip(params, constants): + param.constant = const + + if trigger: + self.trigger([self]) + + def __repr__(self): cls_name = self.__class__.__name__ kwargs = ','.join('%s=%r' % (k,v) @@ -136,6 +141,7 @@ class Stream(param.Parameterized): else: return '%s(%r, %s)' % (cls_name, self.preprocessors, kwargs) + def __str__(self): return repr(self)
Reordered Stream methods and spacing fixes
pyviz_holoviews
train
079d4c7dd148b992002b581e29887e6e8a5ed306
diff --git a/lang/en/moodle.php b/lang/en/moodle.php index <HASH>..<HASH> 100644 --- a/lang/en/moodle.php +++ b/lang/en/moodle.php @@ -943,6 +943,7 @@ $string['institution'] = 'Institution'; $string['instudentview'] = 'in student view'; $string['interests'] = 'Interests'; $string['interestslist'] = 'List of interests'; +$string['interestslist_help'] = 'Enter your interests separated by commas. Your interests will be displayed on your profile page as tags.'; $string['invalidemail'] = 'Invalid email address'; $string['invalidlogin'] = 'Invalid login, please try again'; $string['invalidusername'] = 'The username can only contain alphanumeric lowercase characters, underscore (_), hyphen (-), period (.) or at symbol (@)'; @@ -1161,6 +1162,7 @@ line at the top of your web browser window. Cheers from the \'{$a->sitename}\' administrator, {$a->signoff}'; $string['newpicture'] = 'New picture'; +$string['newpicture_help'] = 'To add a new picture, browse and select an image (in JPG or PNG format) then click "Update profile". The image will be cropped to a square and resized to 100x100 pixels.'; $string['newsitem'] = 'news item'; $string['newsitems'] = 'news items'; $string['newsitemsnumber'] = 'News items to show';
MDL-<I> adding help strings
moodle_moodle
train
b1e9cccf5996133cc51eba6e79661d19a79726d3
diff --git a/solve_basic_test.go b/solve_basic_test.go index <HASH>..<HASH> 100644 --- a/solve_basic_test.go +++ b/solve_basic_test.go @@ -1272,10 +1272,6 @@ func (sm *depspecSourceManager) SyncSourceFor(id ProjectIdentifier) error { return nil } -func (sm *depspecSourceManager) VendorCodeExists(id ProjectIdentifier) (bool, error) { - return false, nil -} - func (sm *depspecSourceManager) Release() {} func (sm *depspecSourceManager) ExportProject(id ProjectIdentifier, v Version, to string) error { @@ -1337,6 +1333,10 @@ func (b *depspecBridge) ListPackages(id ProjectIdentifier, v Version) (PackageTr return b.sm.(fixSM).ListPackages(id, v) } +func (sm *depspecBridge) vendorCodeExists(id ProjectIdentifier) (bool, error) { + return false, nil +} + // enforce interfaces var _ Manifest = depspec{} var _ Lock = dummyLock{}
Relocate vendorCodeExists() method Fixes #<I>, even if sloppy.
sdboyer_gps
train
94452463042a9fd98e2280673f8d7316f49d353e
diff --git a/lib/appsignal/tracer.rb b/lib/appsignal/tracer.rb index <HASH>..<HASH> 100644 --- a/lib/appsignal/tracer.rb +++ b/lib/appsignal/tracer.rb @@ -47,8 +47,8 @@ module Appsignal :action => "#{self.class}##{method_name}", :kind => 'background', :duration => 1000.0 * (end_time - start_time), - :time => start_time, - :end => end_time + :time => start_time.to_f, + :end => end_time.to_f } end diff --git a/spec/appsignal/tracer_spec.rb b/spec/appsignal/tracer_spec.rb index <HASH>..<HASH> 100644 --- a/spec/appsignal/tracer_spec.rb +++ b/spec/appsignal/tracer_spec.rb @@ -82,8 +82,8 @@ describe Appsignal::Tracer do ).should == { :action => "Job#perform", :duration => 10000.0, - :time => start_time, - :end => end_time, + :time => 1325376000.0, + :end => 1325376010.0, :kind => "background" } end
Start and end time in log_entry are floats
appsignal_appsignal-ruby
train
936d712d5f6ee51d1a67ac7a575d08b3905f15d1
diff --git a/src/ORM/Association/BelongsToMany.php b/src/ORM/Association/BelongsToMany.php index <HASH>..<HASH> 100644 --- a/src/ORM/Association/BelongsToMany.php +++ b/src/ORM/Association/BelongsToMany.php @@ -252,7 +252,7 @@ class BelongsToMany extends Association { public function transformRow($row, $joined = false) { $alias = $this->junction()->alias(); if ($joined) { - $row[$this->target()->alias()]['_joinData'] = $row[$alias]; + $row[$this->target()->alias()][$this->_junctionProperty] = $row[$alias]; unset($row[$alias]); } $row = $this->_transformRow($row); diff --git a/tests/TestCase/ORM/QueryTest.php b/tests/TestCase/ORM/QueryTest.php index <HASH>..<HASH> 100644 --- a/tests/TestCase/ORM/QueryTest.php +++ b/tests/TestCase/ORM/QueryTest.php @@ -1870,12 +1870,24 @@ class QueryTest extends TestCase { $this->assertSame($expected, $results); } +/** + * Tests that it is possible to use the same association aliases in the association + * chain for contain + * + * @return void + */ public function testRepeatedAssociationAliases() { $table = TableRegistry::get('ArticlesTags'); $table->belongsTo('Articles'); $table->belongsTo('Tags'); TableRegistry::get('Tags')->belongsToMany('Articles'); $results = $table->find()->contain(['Articles', 'Tags.Articles'])->hydrate(false)->toArray(); + $this->assertNotEmpty($results[0]['tag']['articles']); + $this->assertNotEmpty($results[0]['article']); + $this->assertNotEmpty($results[1]['tag']['articles']); + $this->assertNotEmpty($results[1]['article']); + $this->assertNotEmpty($results[2]['tag']['articles']); + $this->assertNotEmpty($results[2]['article']); } }
Completing test for showing it is possible to use duplicate associaiton alaises in contain
cakephp_cakephp
train
0879513ad35b165a7b1fe9f8611ba2025282fe84
diff --git a/autograd/numpy/linalg.py b/autograd/numpy/linalg.py index <HASH>..<HASH> 100644 --- a/autograd/numpy/linalg.py +++ b/autograd/numpy/linalg.py @@ -2,7 +2,7 @@ from __future__ import absolute_import from functools import partial import numpy as onp import numpy.linalg as npla -from .numpy_wrapper import wrap_namespace, dot +from .numpy_wrapper import wrap_namespace from . import numpy_wrapper as anp from ..core import primitive from builtins import range
Minor tweak: Removed uncessary dot import
HIPS_autograd
train
b7c2d52c13609dd529d129d3255026adbc28bc39
diff --git a/Controller/VarietyCRUDController.php b/Controller/VarietyCRUDController.php index <HASH>..<HASH> 100644 --- a/Controller/VarietyCRUDController.php +++ b/Controller/VarietyCRUDController.php @@ -20,27 +20,6 @@ class VarietyCRUDController extends BaseCRUDController } /** - * Duplicate action - * - * @return response - */ - public function duplicateAction() - { - $id = $this->getRequest()->get($this->admin->getIdParameter()); - $object = $this->admin->getObject($id); - $new = clone $object; - - $this->duplicateFiles($object, $new); - - $preResponse = $this->preDuplicate($new); - if ($preResponse !== null) { - return $preResponse; - } - - return $this->createAction($new); - } - - /** * Creates a strain from a variety and passes it to create action * * @return Response @@ -196,15 +175,4 @@ class VarietyCRUDController extends BaseCRUDController } } - - protected function duplicateFiles($object, $clone) - { - foreach($object->getImages() as $image) - { - $new = clone $image; - $new->setVariety(null); - $clone->addImage($new); - } - } - }
Removed duplicateAction and duplicateFiles as they are already defined in parent class
sil-project_VarietyBundle
train
412678b72e418402b31e7deb5b4a58b6f69fabe3
diff --git a/TYPO3.Neos/Resources/Public/JavaScript/InlineEditing/Editors/Aloha/UiPlugin/multiSplit.js b/TYPO3.Neos/Resources/Public/JavaScript/InlineEditing/Editors/Aloha/UiPlugin/multiSplit.js index <HASH>..<HASH> 100644 --- a/TYPO3.Neos/Resources/Public/JavaScript/InlineEditing/Editors/Aloha/UiPlugin/multiSplit.js +++ b/TYPO3.Neos/Resources/Public/JavaScript/InlineEditing/Editors/Aloha/UiPlugin/multiSplit.js @@ -52,13 +52,9 @@ define([ }); select.append(options); - var selectedValue; select.off('change').on('change', function() { var value = $(this).val(); - if (value !== selectedValue) { - selectedValue = value; - buttons[value].click(); - } + buttons[value].click(); }); $('body').click(function (event) {
There internal selectedValue of the tag name selection for aloha get's out of sync when changing via curor/mouse. Since aloha already handles "changes" to same state well, no need to have this logic again. NEOS-<I> #close
neos_neos-development-collection
train