hash
stringlengths 40
40
| diff
stringlengths 131
114k
| message
stringlengths 7
980
| project
stringlengths 5
67
| split
stringclasses 1
value |
|---|---|---|---|---|
f4eeb4a52c41b04effe8fb163cc93c5e1f5fe894
|
diff --git a/unbabel/__init__.py b/unbabel/__init__.py
index <HASH>..<HASH> 100644
--- a/unbabel/__init__.py
+++ b/unbabel/__init__.py
@@ -0,0 +1,34 @@
+
+
+LOGGING = {
+ 'version': 1,
+ 'disable_existing_loggers': False,
+ 'formatters': {
+ 'verbose': {
+ 'format': ('%(asctime)s [%(process)d] [%(levelname)s] ' +
+ 'pathname=%(pathname)s lineno=%(lineno)s ' +
+ 'funcname=%(funcName)s %(message)s'),
+ 'datefmt': '%Y-%m-%d %H:%M:%S'
+ },
+ 'simple': {
+ 'format': 'lineno=%(lineno)s funcname=%(funcName)s %(levelname)s %(message)s'
+ },
+ },
+ 'handlers': {
+ 'console':{
+ 'level': 'DEBUG',
+ 'class': 'logging.StreamHandler',
+ 'formatter': 'simple'
+ },
+ },
+ 'loggers': {
+ 'unbabel-py': {
+ 'handlers': ['console'],
+ 'level':'DEBUG'
+ },
+ }
+}
+
+import logging
+logging.basicConfig()
+logger = logging.getLogger('unbabel-py.' + __name__)
\ No newline at end of file
diff --git a/unbabel/api.py b/unbabel/api.py
index <HASH>..<HASH> 100644
--- a/unbabel/api.py
+++ b/unbabel/api.py
@@ -9,7 +9,8 @@ Created on Dec 13, 2013
import requests
import json
-
+import logging
+logger = logging.getLogger('unbabel-py.' + __name__)
class UnauthorizedException(Exception):
|
working on python sdk
|
Unbabel_unbabel-py
|
train
|
fb0e34b997cd17481b49acdb97005c26d1351de5
|
diff --git a/websocket.py b/websocket.py
index <HASH>..<HASH> 100644
--- a/websocket.py
+++ b/websocket.py
@@ -861,7 +861,7 @@ class WebSocketApp(object):
if data is None:
break
self._callback(self.on_message, data)
- except Exception, e:
+ except Exception as e:
self._callback(self.on_error, e)
finally:
if thread:
|
Exception handling should be compatible with python <I> and 3.x.
|
websocket-client_websocket-client
|
train
|
cf4ba64ed99bcc449bf359e028eb706e10afc050
|
diff --git a/src/main/java/org/quartz/classloading/CascadingClassLoadHelper.java b/src/main/java/org/quartz/classloading/CascadingClassLoadHelper.java
index <HASH>..<HASH> 100644
--- a/src/main/java/org/quartz/classloading/CascadingClassLoadHelper.java
+++ b/src/main/java/org/quartz/classloading/CascadingClassLoadHelper.java
@@ -204,6 +204,7 @@ public class CascadingClassLoadHelper implements ClassLoadHelper {
*
* A comma(,) or colon(:) can be used to specify multiple packages to scan for Jobs.
*
+ *
* @param pkgname
* @return
*/
@@ -218,7 +219,6 @@ public class CascadingClassLoadHelper implements ClassLoadHelper {
}
}
else {
-
String relPath = pkgname.replace('.', '/').replace("%20", " ");
// Get a File object for the package
diff --git a/src/test/java/org/knowm/sundial/AnnotatedClassFinderTest.java b/src/test/java/org/knowm/sundial/AnnotatedClassFinderTest.java
index <HASH>..<HASH> 100644
--- a/src/test/java/org/knowm/sundial/AnnotatedClassFinderTest.java
+++ b/src/test/java/org/knowm/sundial/AnnotatedClassFinderTest.java
@@ -27,6 +27,8 @@ import org.junit.Test;
import org.knowm.sundial.Job;
import org.quartz.classloading.CascadingClassLoadHelper;
+import static org.junit.Assert.assertEquals;
+
/**
* @author timmolter
*/
@@ -55,7 +57,7 @@ public class AnnotatedClassFinderTest {
jobClassNames.add(jobClass.getSimpleName());
}
- Assert.assertEquals(EXPECTED_JOBS, jobClassNames);
+ assertEquals(EXPECTED_JOBS, jobClassNames);
}
@Test
@@ -71,6 +73,23 @@ public class AnnotatedClassFinderTest {
jobClassNames.add(jobClass.getSimpleName());
}
- Assert.assertEquals(EXPECTED_JOBS, jobClassNames);
+ assertEquals(EXPECTED_JOBS, jobClassNames);
+ }
+
+ @Test
+ public void testOnePackage() {
+
+ CascadingClassLoadHelper classLoadHelper = new CascadingClassLoadHelper();
+ classLoadHelper.initialize();
+
+ Set<Class<? extends Job>> jobClasses = classLoadHelper.getJobClasses("org.knowm.sundial.jobs2");
+
+ assertEquals(1, jobClasses.size());
+
+ Class<? extends Job> theClass = jobClasses.iterator().next();
+
+ assertEquals("org.knowm.sundial.jobs2", theClass.getPackage().getName());
+
+ assertEquals("SampleJob8", theClass.getSimpleName());
}
}
|
added unit test for when there is only one packaged specified
|
knowm_Sundial
|
train
|
e4c5058ad6dc2fa01ce75153a8e7257573a6e0bf
|
diff --git a/Kwc/Basic/LinkTag/Intern/PagesController.php b/Kwc/Basic/LinkTag/Intern/PagesController.php
index <HASH>..<HASH> 100644
--- a/Kwc/Basic/LinkTag/Intern/PagesController.php
+++ b/Kwc/Basic/LinkTag/Intern/PagesController.php
@@ -5,4 +5,12 @@ class Kwc_Basic_LinkTag_Intern_PagesController extends Kwf_Controller_Action_Com
{
return !!Kwf_Registry::get('userModel')->getAuthedUser();
}
+
+ public static function getNodeConfig($component)
+ {
+ $ret = parent::getNodeConfig($component);
+ $ret['allowDrag'] = false;
+ $ret['allowDrop'] = false;
+ return $ret;
+ }
}
diff --git a/Kwf/Controller/Action/Component/PagesAbstractController.php b/Kwf/Controller/Action/Component/PagesAbstractController.php
index <HASH>..<HASH> 100644
--- a/Kwf/Controller/Action/Component/PagesAbstractController.php
+++ b/Kwf/Controller/Action/Component/PagesAbstractController.php
@@ -63,8 +63,6 @@ abstract class Kwf_Controller_Action_Component_PagesAbstractController extends K
$data = $component->generator->getPagesControllerConfig($component);
}
$data['disabled'] = false;
- $data['allowDrag'] = false;
- $data['allowDrop'] = false;
return $data;
}
|
Don't set allowDrag/allowDrag as it comes from generator
|
koala-framework_koala-framework
|
train
|
850ed747a2d739ec3412e9c4d239c24150afffaf
|
diff --git a/lib/index.js b/lib/index.js
index <HASH>..<HASH> 100644
--- a/lib/index.js
+++ b/lib/index.js
@@ -80,7 +80,8 @@ function dotThemingFileToPath(s) {
var Builder = function(options) {
this.themeCacheMapping = {};
- this.fileUtils = fileUtilsFactory(options ? options.fs : null);
+ this.customFs = options ? options.fs : null;
+ this.fileUtils = fileUtilsFactory(this.customFs);
};
Builder.prototype.getThemeCache = function(rootPath) {
@@ -184,9 +185,9 @@ Builder.prototype.build = function(options) {
// Keep filename for later usage (see ImportCollectorPlugin) as less modifies the parserOptions.filename
var filename = parserOptions.filename;
- // Only use custom file handler when "rootPaths" are defined
+ // Only use custom file handler when "rootPaths" or custom "fs" are used
var fnFileHandler;
- if (options.rootPaths && options.rootPaths.length > 0) {
+ if (options.rootPaths && options.rootPaths.length > 0 || that.customFs) {
fnFileHandler = fileHandler;
}
|
Use custom file handler when custom "fs" is used
Otherwise less would still use the native "fs" module.
|
SAP_less-openui5
|
train
|
d25c996f6ec2cf54a8b4eedc0a9c3311d11fd9d5
|
diff --git a/packages/net/csp/client.js b/packages/net/csp/client.js
index <HASH>..<HASH> 100644
--- a/packages/net/csp/client.js
+++ b/packages/net/csp/client.js
@@ -335,6 +335,9 @@ exports.CometSession = Class(function(supr) {
// TODO: possibly catch this error in production? but not in dev
this._doOnRead(data);
}
+
+ if (this.readyState != READYSTATE.CONNECTED && this.readyState != READYSTATE.DISCONNECTING) { return; }
+
// reconnect comet last, after we process all of the packet ids
this._doConnectComet();
|
fix a bug where after a comet call the ready state might go to DISCONNECTING or DISCONNECTED (callback closes the connection), but we still try to make the next comet call with a null sessionKey
|
gameclosure_js.io
|
train
|
34a37b79a050f25ad7e3e775b8bba0d4eef430ae
|
diff --git a/src/CameraScreen/CameraKitCameraScreenBase.js b/src/CameraScreen/CameraKitCameraScreenBase.js
index <HASH>..<HASH> 100644
--- a/src/CameraScreen/CameraKitCameraScreenBase.js
+++ b/src/CameraScreen/CameraKitCameraScreenBase.js
@@ -138,6 +138,7 @@ export default class CameraScreenBase extends Component {
ref={(cam) => this.camera = cam}
style={{flex: 1, justifyContent: 'flex-end'}}
cameraOptions={this.state.cameraOptions}
+ onReadCode={this.props.onReadCode}
/>
}
</View>
|
add props with callback from native
|
wix_react-native-camera-kit
|
train
|
44a16bcc68700843e39066daa586a4725064d4d7
|
diff --git a/kytos_utils/cli/cmdline.py b/kytos_utils/cli/cmdline.py
index <HASH>..<HASH> 100644
--- a/kytos_utils/cli/cmdline.py
+++ b/kytos_utils/cli/cmdline.py
@@ -80,6 +80,10 @@ class KytosCmdLine():
napps_list.add_argument('-a', '--author',
help="List napps by Author Name")
+ # This is only for displaying help. The implementation of the commands
+ # below are in another parser. Check bin/kytos for details
+ napps_subparsers.add_parser('enable', help='Enable a NApp.')
+ napps_subparsers.add_parser('disable', help='Disable a NApp.')
def help(self, namespace):
print("Invalid syntax")
|
Add enable/disable help in previous parser
Finish the enable/disable commands and close #<I>
|
kytos_kytos-utils
|
train
|
4e7eb2c9417be16f9e1e7c907590cf13f736725f
|
diff --git a/index.js b/index.js
index <HASH>..<HASH> 100644
--- a/index.js
+++ b/index.js
@@ -73,11 +73,11 @@ module.exports = {
data = {};
}
- this.build(model, data, function(err, obj){
+ this.build(model, data, function(err, builtObj){
if (err)
throw(err);
- obj.save(function(error) {
- callback(error, obj);
+ builtObj.save(function(error, createdObj) {
+ callback(error, createdObj);
})
});
}
diff --git a/spec/factory_spec.js b/spec/factory_spec.js
index <HASH>..<HASH> 100644
--- a/spec/factory_spec.js
+++ b/spec/factory_spec.js
@@ -38,14 +38,14 @@ describe('Factory#build', function() {
})
it('uses the stored definition to seed attribute values', function() {
- var object = Factory.build('test')
+ var object = Factory.build('test')
expect(object.name).toEqual('Test Model')
expect(object.real).toEqual(false)
expect(object.dynamic).toEqual("dynamic")
})
it('takes an optional parameter to override stores attributes', function() {
- var object = Factory.build('test', { real: true })
+ var object = Factory.build('test', { real: true })
expect(object.name).toEqual('Test Model')
expect(object.real).toEqual(true)
})
@@ -95,7 +95,7 @@ describe('Factory#create', function() {
it('should override attributes like Factory#build', function() {
var object;
Factory.create('test', { name: function(){return 'Test Object';}, dynamic: "another value", called: function(cbk){return cbk(null, 'new value');} }, function(e, o) {
- object = o;
+ object = o;
})
waitsFor(function() { return object != null}, 'object creation failed', 1000);
runs(function() {
@@ -104,4 +104,15 @@ describe('Factory#create', function() {
expect(object.called).toEqual('new value');
})
})
+
+ it('should returned saved object', function() {
+ var object;
+ Factory.create('test', function(e, o) {
+ object = o;
+ })
+ waitsFor(function() { return object != null}, 'object creation failed', 1000);
+ runs(function() {
+ expect(object.isNew).toBe(false);
+ })
+ })
})
diff --git a/spec/spec_helper.js b/spec/spec_helper.js
index <HASH>..<HASH> 100644
--- a/spec/spec_helper.js
+++ b/spec/spec_helper.js
@@ -1,10 +1,12 @@
Factory = require('../')
TestModel = function TestModel(attributes) {
+ this.isNew = true;
this.name = attributes.name;
this.real = attributes.real;
this.dynamic = attributes.dynamic;
this.called = attributes.called;
}
TestModel.prototype.save = function(callback) {
- callback(null)
+ this.isNew = false;
+ callback(null, this);
}
|
Return saved object from Factory.create method
|
agoragames_factory-worker
|
train
|
b8004b85aca787da7f229e6088dc2516fdc2739f
|
diff --git a/pandas/core/computation/eval.py b/pandas/core/computation/eval.py
index <HASH>..<HASH> 100644
--- a/pandas/core/computation/eval.py
+++ b/pandas/core/computation/eval.py
@@ -1,4 +1,3 @@
-#!/usr/bin/env python3
"""
Top level ``eval`` module.
"""
diff --git a/pandas/tests/io/generate_legacy_storage_files.py b/pandas/tests/io/generate_legacy_storage_files.py
index <HASH>..<HASH> 100755
--- a/pandas/tests/io/generate_legacy_storage_files.py
+++ b/pandas/tests/io/generate_legacy_storage_files.py
@@ -1,5 +1,3 @@
-#!/usr/bin/env python3
-
"""
self-contained to write legacy storage pickle files
diff --git a/pandas/tests/plotting/common.py b/pandas/tests/plotting/common.py
index <HASH>..<HASH> 100644
--- a/pandas/tests/plotting/common.py
+++ b/pandas/tests/plotting/common.py
@@ -1,4 +1,3 @@
-#!/usr/bin/env python3
# coding: utf-8
import os
|
CLN: Remove shebang (#<I>)
|
pandas-dev_pandas
|
train
|
23a58ca4c8f846412bd009889305beda514a6dc7
|
diff --git a/Component/Drivers/PostgreSQL.php b/Component/Drivers/PostgreSQL.php
index <HASH>..<HASH> 100644
--- a/Component/Drivers/PostgreSQL.php
+++ b/Component/Drivers/PostgreSQL.php
@@ -322,7 +322,7 @@ class PostgreSQL extends DoctrineBaseDriver implements Manageble, Routable, Geog
{
$connection = $this->getConnection();
$geomFieldName = $connection->quoteIdentifier($geometryAttribute);
- $sridTo = $connection->quote($sridTo);
+ $sridTo = is_numeric($sridTo)?intval($sridTo):$connection->quote($sridTo);
return "ST_ASTEXT(ST_TRANSFORM($geomFieldName, $sridTo)) AS $geomFieldName";
}
|
Fix PostGIS/PostgreSQL driver geometry transformation
|
mapbender_data-source
|
train
|
c073596b68d3bbc0800043343bd24d27f51a3793
|
diff --git a/code/UserDefinedForm.php b/code/UserDefinedForm.php
index <HASH>..<HASH> 100755
--- a/code/UserDefinedForm.php
+++ b/code/UserDefinedForm.php
@@ -277,7 +277,6 @@ class UserDefinedForm_Controller extends Page_Controller {
$CustomDisplayRules = "";
$defaults = "";
$this->SubmitButtonText = ($this->SubmitButtonText) ? $this->SubmitButtonText : _t('UserDefinedForm.SUBMITBUTTON', 'Submit');
-
if($this->Fields()) {
foreach($this->Fields() as $field) {
@@ -413,8 +412,9 @@ class UserDefinedForm_Controller extends Page_Controller {
if($this->ShowClearButton) {
$actions->push(new ResetFormAction("clearForm"));
}
+
// return the form
- $form = new Form( $this, "Form", $fields, $actions, new RequiredFields(array_keys($fieldValidation)));
+ $form = new Form($this, "Form", $fields, $actions, new RequiredFields(array_keys($fieldValidation)));
$form->loadDataFrom($this->failover);
$FormName = $form->FormName();
@@ -475,7 +475,7 @@ JS
function process($data, $form) {
// submitted form object
$submittedForm = new SubmittedForm();
- $submittedForm->SubmittedBy = Member::currentUser();
+ $submittedForm->SubmittedByID = ($id = Member::currentUserID()) ? $id : 0;
$submittedForm->ParentID = $this->ID;
$submittedForm->Recipient = $this->EmailTo;
if(!$this->DisableSaveSubmissions) $submittedForm->write();
@@ -564,31 +564,16 @@ JS
$email->setSubject($recipient->EmailSubject);
$email->setTo($recipient->EmailAddress);
- // check to see if they are a dynamic sender. eg based on a email field
- // a user selected
+ // check to see if they are a dynamic sender. eg based on a email field a user selected
if($recipient->SendEmailFromField()) {
- $name = Convert::raw2sql($recipient->SendEmailFromField()->Name);
-
- if(defined('DB::USE_ANSI_SQL')) {
- $submittedFormField = DataObject::get_one("SubmittedFormField", "\"Name\" = '$name' AND \"ParentID\" = '$submittedForm->ID'");
- } else {
- $submittedFormField = DataObject::get_one("SubmittedFormField", "Name = '$name' AND ParentID = '$submittedForm->ID'");
- }
-
+ $submittedFormField = $submittedFields->find('Name', $recipient->SendEmailFromField()->Name);
if($submittedFormField) {
$email->setFrom($submittedFormField->Value);
}
}
- // check to see if they are a dynamic reciever eg based on a dropdown field
- // a user selected
+ // check to see if they are a dynamic reciever eg based on a dropdown field a user selected
if($recipient->SendEmailToField()) {
- $name = Convert::raw2sql($recipient->SendEmailToField()->Name);
-
- if(defined('DB::USE_ANSI_SQL')) {
- $submittedFormField = DataObject::get_one("SubmittedFormField", "\"Name\" = '$name' AND \"ParentID\" = '$submittedForm->ID'");
- } else {
- $submittedFormField = DataObject::get_one("SubmittedFormField", "Name = '$name' AND ParentID = '$submittedForm->ID'");
- }
+ $submittedFormField = $submittedFields->find('Name', $recipient->SendEmailToField()->Name);
if($submittedFormField) {
$email->setTo($submittedFormField->Value);
|
BUGFIX: fixed issue with disabling saving submissions and emailing #<I>. BUGFIX: fixed saving member object error when logged in using a form
|
silverstripe_silverstripe-userforms
|
train
|
28285ef3ed53de6b902ca004090951b736e3f719
|
diff --git a/police_api/__init__.py b/police_api/__init__.py
index <HASH>..<HASH> 100644
--- a/police_api/__init__.py
+++ b/police_api/__init__.py
@@ -50,24 +50,25 @@ class PoliceAPI(object):
return [d['date'] for d in response]
def get_latest_date(self):
- return self.service.request('GET', 'crime-last-updated')['date']
+ return self.get_dates()[0]
- def _populate_crime_categories(self):
- response = self.service.request('GET', 'crime-categories')
+ def _populate_crime_categories(self, date=None):
+ response = self.service.request('GET', 'crime-categories', date=date)
+ self.crime_categories[date] = {}
for c in filter(lambda x: x['url'] != 'all-crime', response):
- self.crime_categories[c['url']] = CrimeCategory(self, data=c)
+ self.crime_categories[date][c['url']] = CrimeCategory(self, data=c)
- def _get_crime_categories(self):
- if not self.crime_categories:
- self._populate_crime_categories()
- return self.crime_categories
+ def _get_crime_categories(self, date=None):
+ if date not in self.crime_categories:
+ self._populate_crime_categories(date=date)
+ return self.crime_categories[date]
- def get_crime_categories(self):
- return sorted(self._get_crime_categories().values(),
+ def get_crime_categories(self, date=None):
+ return sorted(self._get_crime_categories(date=date).values(),
key=lambda c: c.name)
- def get_crime_category(self, url):
- return self._get_crime_categories()[url]
+ def get_crime_category(self, url, date=None):
+ return self._get_crime_categories(date=date)[url]
def get_crime(self, persistent_id):
method = 'outcomes-for-crime/%s' % persistent_id
@@ -81,7 +82,10 @@ class PoliceAPI(object):
crime._outcomes.append(crime.Outcome(self, o))
return crime
- def get_crimes_point(self, lat, lng, date=None):
+ def get_crimes_point(self, lat, lng, date=None, category='all-crime'):
+ if isinstance(category, CrimeCategory):
+ category = category.url
+ method = 'crimes-street/%s' % category
kwargs = {
'lat': lat,
'lng': lng,
@@ -89,20 +93,21 @@ class PoliceAPI(object):
crimes = []
if date is not None:
kwargs['date'] = date
- for c in self.service.request('GET', 'crimes-street/all-crime',
- **kwargs):
+ for c in self.service.request('GET', method, **kwargs):
crimes.append(Crime(self, data=c))
return crimes
- def get_crimes_area(self, points, date=None):
+ def get_crimes_area(self, points, date=None, category='all-crime'):
+ if isinstance(category, CrimeCategory):
+ category = category.url
+ method = 'crimes-street/%s' % category
kwargs = {
'poly': encode_polygon(points),
}
crimes = []
if date is not None:
kwargs['date'] = date
- for c in self.service.request('POST', 'crimes-street/all-crime',
- **kwargs):
+ for c in self.service.request('POST', method, **kwargs):
crimes.append(Crime(self, data=c))
return crimes
|
Allow filtering crimes based on category, and fix categories cache bug
|
rkhleics_police-api-client-python
|
train
|
7927fb009e72672d76972228e68d72c7bdf2cd7e
|
diff --git a/h2o-automl/src/test/java/ai/h2o/automl/AutoMLTest.java b/h2o-automl/src/test/java/ai/h2o/automl/AutoMLTest.java
index <HASH>..<HASH> 100644
--- a/h2o-automl/src/test/java/ai/h2o/automl/AutoMLTest.java
+++ b/h2o-automl/src/test/java/ai/h2o/automl/AutoMLTest.java
@@ -119,7 +119,7 @@ public class AutoMLTest extends water.TestUtil {
fr = parse_test_file("./smalldata/logreg/prostate_train.csv");
autoMLBuildSpec.input_spec.training_frame = fr._key;
autoMLBuildSpec.input_spec.response_column = "CAPSULE";
- autoMLBuildSpec.build_models.exclude_algos = new AutoML.Algo[] {AutoML.Algo.DeepLearning, AutoML.Algo.DRF, AutoML.Algo.GLM};
+ autoMLBuildSpec.build_models.exclude_algos = new AutoML.algo[] {AutoML.algo.DeepLearning, AutoML.algo.DRF, AutoML.algo.GLM};
autoMLBuildSpec.build_control.stopping_criteria.set_max_runtime_secs(8);
// autoMLBuildSpec.build_control.stopping_criteria.set_max_runtime_secs(new Random().nextInt(30));
|
Fix AutoML test. (#<I>)
|
h2oai_h2o-3
|
train
|
2215e17ec8c9dda8680066b1774b2fd079b2235d
|
diff --git a/mybin.py b/mybin.py
index <HASH>..<HASH> 100755
--- a/mybin.py
+++ b/mybin.py
@@ -1,4 +1,4 @@
-#!/usr/bin/env python
+#!/usr/bin/python3
from pyp2rpm.bin import main
main()
diff --git a/pyp2rpm/filters.py b/pyp2rpm/filters.py
index <HASH>..<HASH> 100644
--- a/pyp2rpm/filters.py
+++ b/pyp2rpm/filters.py
@@ -24,7 +24,7 @@ def python_bin_for_python_version(name, version):
if version == settings.DEFAULT_PYTHON_VERSION:
return name
else:
- return name.replace('__python2', '__python3')
+ return name.replace('__python2', '__python{0}'.format(version))
def macroed_pkg_name(pkg_name, name):
|
Improve filters to fill correct version in macros fixes #<I>
|
fedora-python_pyp2rpm
|
train
|
8b201d7e23895f941240fa2eff921ab7f48fd8de
|
diff --git a/hwt/hdl/assignment.py b/hwt/hdl/assignment.py
index <HASH>..<HASH> 100644
--- a/hwt/hdl/assignment.py
+++ b/hwt/hdl/assignment.py
@@ -47,7 +47,7 @@ class Assignment(HdlStatement):
self.dst = dst
if not isinstance(dst, Value):
self._outputs.append(dst)
- self._enclosed_for.append(dst)
+ self._enclosed_for.add(dst)
if isReal:
dst.drivers.append(self)
|
append/add mismatch for enclosure
|
Nic30_hwt
|
train
|
54e3809cda26d806270bfd3b3764ffb09e999ac5
|
diff --git a/lib/deployml/configuration.rb b/lib/deployml/configuration.rb
index <HASH>..<HASH> 100644
--- a/lib/deployml/configuration.rb
+++ b/lib/deployml/configuration.rb
@@ -95,7 +95,7 @@ module DeploYML
@bundler = config.fetch(:bundler,false)
@framework = case config[:framework]
- when /^rails/
+ when 'rails', 'rails2', 'rails3'
:rails
when String, Symbol
config[:framework].to_sym
|
Restrict the matching of 'rails' for the framework setting.
|
postmodern_deployml
|
train
|
d07de54801db2b66f632bc994c33be779bb20f62
|
diff --git a/Generator/API.php b/Generator/API.php
index <HASH>..<HASH> 100644
--- a/Generator/API.php
+++ b/Generator/API.php
@@ -14,7 +14,7 @@ namespace ModuleBuider\Generator;
* looks for calls to module_invoke_all() and generates scaffold hook
* documentation for hook names that have the module's name as a prefix.
*/
-class API extends File {
+class API extends PHPFile {
/**
* Return an array of subcomponent types.
diff --git a/Generator/ModuleCodeFile.php b/Generator/ModuleCodeFile.php
index <HASH>..<HASH> 100644
--- a/Generator/ModuleCodeFile.php
+++ b/Generator/ModuleCodeFile.php
@@ -14,7 +14,7 @@ namespace ModuleBuider\Generator;
* system, and is currently (hello!) being forced into a new, bigger mk
* hierarchy!
*/
-class ModuleCodeFile extends File {
+class ModuleCodeFile extends PHPFile {
// TODO: declare properties that are special!
diff --git a/Generator/Tests.php b/Generator/Tests.php
index <HASH>..<HASH> 100644
--- a/Generator/Tests.php
+++ b/Generator/Tests.php
@@ -10,7 +10,7 @@ namespace ModuleBuider\Generator;
/**
* Component generator: tests.
*/
-class Tests extends File {
+class Tests extends PHPFile {
/**
* Return an array of subcomponent types.
|
Changed php file component generators to inherit from PHPFile.
|
drupal-code-builder_drupal-code-builder
|
train
|
b676c54dc3bb668637aef732b620f079c5745f81
|
diff --git a/go/vt/client/client.go b/go/vt/client/client.go
index <HASH>..<HASH> 100644
--- a/go/vt/client/client.go
+++ b/go/vt/client/client.go
@@ -171,7 +171,7 @@ func makeBindVars(args []driver.Value) map[string]interface{} {
}
bv := make(map[string]interface{}, len(args))
for i, v := range args {
- bv[fmt.Sprintf("v%d", i)] = v
+ bv[fmt.Sprintf("v%d", i+1)] = v
}
return bv
}
diff --git a/go/vt/client/fakeserver_test.go b/go/vt/client/fakeserver_test.go
index <HASH>..<HASH> 100644
--- a/go/vt/client/fakeserver_test.go
+++ b/go/vt/client/fakeserver_test.go
@@ -146,7 +146,7 @@ var execMap = map[string]struct {
execQuery: &proto.Query{
Sql: "request1",
BindVariables: map[string]interface{}{
- "v0": int64(0),
+ "v1": int64(0),
},
TabletType: topo.TYPE_RDONLY,
Session: nil,
|
go client: fix bind var numbering
|
vitessio_vitess
|
train
|
8be1ecf51f560f6d53f6c9f0859c92d8390a788b
|
diff --git a/providers/link.js b/providers/link.js
index <HASH>..<HASH> 100644
--- a/providers/link.js
+++ b/providers/link.js
@@ -15,24 +15,7 @@ fdom.link = fdom.link || {};
* @constructor
*/
fdom.link.Node = function() {
- this.id = 'Link.Node ' + Math.random();
- this.config = {};
- this.src = null;
-
- fdom.util.handleEvents(this);
-};
-
-/**
- * Emit a message from the other end of this port.
- * @method doEmit
- * @param {Event} msg
- * @private
- */
-fdom.link.Node.prototype.doEmit = function(msg) {
- if (msg.tag === 'control') {
- msg.tag = this.controlChannel;
- }
- this.emit(msg.tag, msg.msg);
+ fdom.Link.call(this);
};
/**
@@ -81,36 +64,28 @@ fdom.link.Node.prototype.stop = function() {
* @return {String} the description of this port.
*/
fdom.link.Node.prototype.toString = function() {
- return "[" + this.id + "]";
+ return "[Node" + this.id + "]";
};
/**
* Receive messages from the hub to this port.
* Received messages will be emitted from the other side of the port.
- * @method onMessage
+ * @method deliverMessage
* @param {String} flow the channel/flow of the message.
* @param {Object} message The Message.
*/
-fdom.link.Node.prototype.onMessage = function(flow, message) {
- if (flow === 'control' && !this.controlChannel) {
- if (!this.controlChannel && message.channel) {
- this.controlChannel = message.channel;
- fdom.util.mixin(this.config, message.config);
- this.start();
- }
- } else {
- if (this.obj) {
- /* //- For Debugging Purposes -
- if (this === this.config.global.directLink) {
- console.warn('->[' + flow + '] ' + JSON.stringify(message));
- } else {
- console.warn('<-[' + flow + '] ' + JSON.stringify(message));
- }
- */
- this.obj.send({tag: flow, msg: message});
+fdom.link.Node.prototype.deliverMessage = function(flow, message) {
+ if (this.obj) {
+ /* //- For Debugging Purposes -
+ if (this === this.config.global.directLink) {
+ console.warn('->[' + flow + '] ' + JSON.stringify(message));
} else {
- this.once('started', this.onMessage.bind(this, flow, message));
+ console.warn('<-[' + flow + '] ' + JSON.stringify(message));
}
+ */
+ this.obj.send({tag: flow, msg: message});
+ } else {
+ this.once('started', this.onMessage.bind(this, flow, message));
}
};
|
update for consistency w/ freedom link refactor
|
freedomjs_freedom-for-node
|
train
|
83f9e5913c4d60116c172c7ca79840057ba28521
|
diff --git a/tests/core/test_inventory.py b/tests/core/test_inventory.py
index <HASH>..<HASH> 100644
--- a/tests/core/test_inventory.py
+++ b/tests/core/test_inventory.py
@@ -247,12 +247,22 @@ class Test(object):
hosts = {"h1": h1, "h2": h2}
groups = {"g1": g1, "g2": g2}
inv = inventory.Inventory(hosts=hosts, groups=groups, defaults=defaults)
- inv.add_host(name="h3", groups=["g1"], platform="TestPlatform")
+ h3_connection_options = {"netmiko": {"extras": {"device_type": "cisco_ios"}}}
+ inv.add_host(
+ name="h3",
+ groups=["g1"],
+ platform="TestPlatform",
+ connection_options=h3_connection_options,
+ )
assert "h3" in inv.hosts
assert "g1" in inv.hosts["h3"].groups
assert "test_var" in inv.hosts["h3"].defaults.data.keys()
assert inv.hosts["h3"].defaults.data.get("test_var") == "test_value"
assert inv.hosts["h3"].platform == "TestPlatform"
+ assert (
+ inv.hosts["h3"].connection_options["netmiko"].extras["device_type"]
+ == "cisco_ios"
+ )
def test_add_group(self):
connection_options = {"username": "test_user", "password": "test_pass"}
@@ -265,14 +275,20 @@ class Test(object):
hosts = {"h1": h1, "h2": h2}
groups = {"g1": g1, "g2": g2}
inv = inventory.Inventory(hosts=hosts, groups=groups, defaults=defaults)
- inv.add_group(name="g3", username="test_user")
+ g3_connection_options = {"netmiko": {"extras": {"device_type": "cisco_ios"}}}
+ inv.add_group(
+ name="g3", username="test_user", connection_options=g3_connection_options
+ )
assert "g3" in inv.groups
assert (
inv.groups["g3"].defaults.connection_options.get("username") == "test_user"
)
assert (
- inv.groups["g3"].defaults.connection_options.get("password")
- == "test_pass"
+ inv.groups["g3"].defaults.connection_options.get("password") == "test_pass"
)
assert "test_var" in inv.groups["g3"].defaults.data.keys()
assert "test_value" == inv.groups["g3"].defaults.data.get("test_var")
+ assert (
+ inv.groups["g3"].connection_options["netmiko"].extras["device_type"]
+ == "cisco_ios"
+ )
|
Add connection_options to add_hosts and add_group
|
nornir-automation_nornir
|
train
|
9fa237ddb6e2b1a19296a701e1fd5e63b15af0fc
|
diff --git a/agent/dns.go b/agent/dns.go
index <HASH>..<HASH> 100644
--- a/agent/dns.go
+++ b/agent/dns.go
@@ -278,22 +278,23 @@ func (d *DNSServer) nameservers(edns bool) (ns []dns.RR, extra []dns.RR) {
d.logger.Println("[WARN] Unable to parse address %v, got error: %v", addr, err)
continue
}
+
ip := net.ParseIP(host)
if ip == nil {
continue
}
- // name is "name.dc" and domain is "consul."
- // we want "name.node.dc.consul."
+ // Use "NODENAME.node.DC.DOMAIN" as a unique name for the server
+ // since we use that name in other places as well.
+ // 'name' is "NODENAME.DC" so we need to split it
+ // to construct the server name.
lastdot := strings.LastIndexByte(name, '.')
- nodeName := name[:lastdot]
+ nodeName, dc := name[:lastdot], name[lastdot:]
if InvalidDnsRe.MatchString(nodeName) {
d.logger.Printf("[WARN] dns: Node name %q is not a valid dns host name, will not be added to NS record", nodeName)
continue
}
- fqdn := nodeName + ".node" + name[lastdot:] + "." + d.domain
-
- // create a consistent, unique and sanitized name for the server
+ fqdn := nodeName + ".node" + dc + "." + d.domain
fqdn = dns.Fqdn(strings.ToLower(fqdn))
servers[fqdn] = ip
@@ -304,19 +305,21 @@ func (d *DNSServer) nameservers(edns bool) (ns []dns.RR, extra []dns.RR) {
}
for name, ip := range servers {
- // the name server record
+ // NS record
nsrr := &dns.NS{
Hdr: dns.RR_Header{
Name: d.domain,
Rrtype: dns.TypeNS,
Class: dns.ClassINET,
- Ttl: 0,
+ Ttl: uint32(d.config.NodeTTL / time.Second),
},
Ns: name,
}
ns = append(ns, nsrr)
- // the glue record providing the ip address
- extra = append(extra, d.formatNodeRecord(ip.String(), name, dns.TypeANY, d.config.NodeTTL, edns)...)
+
+ // A or AAAA glue record
+ glue := d.formatNodeRecord(ip.String(), name, dns.TypeANY, d.config.NodeTTL, edns)
+ extra = append(extra, glue...)
// don't provide more than 3 servers
if len(ns) >= 3 {
@@ -504,8 +507,7 @@ RPC:
n := out.NodeServices.Node
edns := req.IsEdns0() != nil
addr := d.agent.TranslateAddress(datacenter, n.Address, n.TaggedAddresses)
- records := d.formatNodeRecord(addr,
- req.Question[0].Name, qType, d.config.NodeTTL, edns)
+ records := d.formatNodeRecord(addr, req.Question[0].Name, qType, d.config.NodeTTL, edns)
if records != nil {
resp.Answer = append(resp.Answer, records...)
}
|
dns: minor cleanups
|
hashicorp_consul
|
train
|
e28ba0d9299ddf45b8673c104fd0833313686174
|
diff --git a/enoslib/infra/enos_vagrant/Vagrantfile.j2 b/enoslib/infra/enos_vagrant/Vagrantfile.j2
index <HASH>..<HASH> 100644
--- a/enoslib/infra/enos_vagrant/Vagrantfile.j2
+++ b/enoslib/infra/enos_vagrant/Vagrantfile.j2
@@ -1,8 +1,3 @@
-# THIS FILE HAS BEEN GENERATED BY THE VBOX PROVIDER
-#
-# -*- mode: ruby -*-
-# vi: set ft=ruby :
-
$script = <<SCRIPT
cp -r /home/vagrant/.ssh /root/.
SCRIPT
@@ -10,7 +5,9 @@ SCRIPT
Vagrant.configure(2) do |config|
config.vm.box = "{{ provider_conf.box }}"
config.vm.provision "shell", inline: $script
-
+{% if provider_conf.config_extra|length %}
+ {{ provider_conf.config_extra | safe }}
+{% endif %}
{% for machine in machines %}
config.vm.define "{{ machine.name }}" do |my|
my.vm.hostname = "{{ machine.name }}"
diff --git a/enoslib/infra/enos_vagrant/configuration.py b/enoslib/infra/enos_vagrant/configuration.py
index <HASH>..<HASH> 100644
--- a/enoslib/infra/enos_vagrant/configuration.py
+++ b/enoslib/infra/enos_vagrant/configuration.py
@@ -20,6 +20,7 @@ class Configuration(BaseConfiguration):
self.backend = DEFAULT_BACKEND
self.user = DEFAULT_USER
self.box = DEFAULT_BOX
+ self.config_extra = ""
self._machine_cls = MachineConfiguration
self._network_cls = NetworkConfiguration
@@ -35,7 +36,7 @@ class Configuration(BaseConfiguration):
_networks = _resources["networks"]
self.machines = [MachineConfiguration.from_dictionnary(m) for m in _machines]
self.networks = [NetworkConfiguration.from_dictionnary(n) for n in _networks]
- for key in ["backend", "user", "box"]:
+ for key in ["backend", "user", "box", "config_extra"]:
value = dictionnary.get(key)
if value is not None:
setattr(self, key, value)
@@ -49,6 +50,7 @@ class Configuration(BaseConfiguration):
backend=self.backend,
user=self.user,
box=self.box,
+ config_extra=self.config_extra,
resources={
"machines": [m.to_dict() for m in self.machines],
"networks": [n.to_dict() for n in self.networks],
diff --git a/enoslib/infra/enos_vagrant/schema.py b/enoslib/infra/enos_vagrant/schema.py
index <HASH>..<HASH> 100644
--- a/enoslib/infra/enos_vagrant/schema.py
+++ b/enoslib/infra/enos_vagrant/schema.py
@@ -10,6 +10,7 @@ SCHEMA = {
"box": {"type": "string"},
"user": {"type": "string"},
"resources": {"$ref": "#/resources"},
+ "config_extra": {"type": "string"},
},
"additionalProperties": False,
"required": ["resources"],
|
Fix #<I> - Support customized vagrant settings
|
BeyondTheClouds_enoslib
|
train
|
cada317deec07aad030865cefc99199c0fc71072
|
diff --git a/src/Symfony/Bundle/DoctrineBundle/DependencyInjection/DoctrineExtension.php b/src/Symfony/Bundle/DoctrineBundle/DependencyInjection/DoctrineExtension.php
index <HASH>..<HASH> 100644
--- a/src/Symfony/Bundle/DoctrineBundle/DependencyInjection/DoctrineExtension.php
+++ b/src/Symfony/Bundle/DoctrineBundle/DependencyInjection/DoctrineExtension.php
@@ -192,6 +192,13 @@ class DoctrineExtension extends AbstractDoctrineExtension
}
}
+ if (isset($connection['platform-service'])) {
+ $driverOptions['platform'] = new Reference($connection['platform-service']);
+ }
+ if (isset($connection['platform_service'])) {
+ $driverOptions['platform'] = new Reference($connection['platform_service']);
+ }
+
$driverDef->setArguments(array(
$driverOptions,
new Reference(sprintf('doctrine.dbal.%s_connection.configuration', $connection['name'])),
diff --git a/src/Symfony/Bundle/DoctrineBundle/Resources/config/schema/doctrine-1.0.xsd b/src/Symfony/Bundle/DoctrineBundle/Resources/config/schema/doctrine-1.0.xsd
index <HASH>..<HASH> 100644
--- a/src/Symfony/Bundle/DoctrineBundle/Resources/config/schema/doctrine-1.0.xsd
+++ b/src/Symfony/Bundle/DoctrineBundle/Resources/config/schema/doctrine-1.0.xsd
@@ -25,6 +25,7 @@
<xsd:attribute name="unix-socket" type="xsd:string" />
<xsd:attribute name="memory" type="xsd:boolean" />
<xsd:attribute name="charset" type="xsd:string" />
+ <xsd:attribute name="platform-service" type="xsd:string" />
</xsd:complexType>
<xsd:complexType name="connections">
@@ -50,6 +51,7 @@
<xsd:attribute name="configuration-class" type="xsd:string" />
<xsd:attribute name="event-manager-class" type="xsd:string" />
<xsd:attribute name="wrapper-class" type="xsd:string" />
+ <xsd:attribute name="platform-service" type="xsd:string" />
</xsd:complexType>
<xsd:element name="orm" type="orm" />
diff --git a/src/Symfony/Bundle/DoctrineBundle/Tests/ContainerTest.php b/src/Symfony/Bundle/DoctrineBundle/Tests/ContainerTest.php
index <HASH>..<HASH> 100644
--- a/src/Symfony/Bundle/DoctrineBundle/Tests/ContainerTest.php
+++ b/src/Symfony/Bundle/DoctrineBundle/Tests/ContainerTest.php
@@ -38,11 +38,14 @@ class ContainerTest extends TestCase
'default' => array(
'driver' => 'pdo_mysql',
'charset' => 'UTF-8',
+ 'platform-service' => 'my.platform',
)
)
), $container);
$loader->ormLoad(array('bundles' => array('YamlBundle' => array())), $container);
+ $container->setDefinition('my.platform', new \Symfony\Component\DependencyInjection\Definition('Doctrine\DBAL\Platforms\MySqlPlatform'));
+
$dumper = new PhpDumper($container);
$code = $dumper->dump(array('class' => 'DoctrineBundleTestsProjectServiceContainer'));
eval(str_replace('<?php', null, $code));
@@ -70,5 +73,7 @@ class ContainerTest extends TestCase
$this->assertInstanceOf('Symfony\Bundle\DoctrineAbstractBundle\Event\EventManager', $container->get('doctrine.orm.default_entity_manager.event_manager'));
$this->assertInstanceOf('Symfony\Bundle\DoctrineAbstractBundle\Event\EventManager', $container->get('doctrine.dbal.event_manager'));
$this->assertInstanceOf('Doctrine\DBAL\Event\Listeners\MysqlSessionInit', $container->get('doctrine.dbal.default_connection.events.mysqlsessioninit'));
+
+ $this->assertSame($container->get('my.platform'), $container->get('doctrine.dbal.default_connection')->getDatabasePlatform());
}
}
\ No newline at end of file
|
Allow to override platform with your own by defining a service name.
|
symfony_symfony
|
train
|
f076652f1881b453ccf55f16dd71b1514263bb6d
|
diff --git a/Odoo.php b/Odoo.php
index <HASH>..<HASH> 100644
--- a/Odoo.php
+++ b/Odoo.php
@@ -65,6 +65,13 @@ class Odoo
protected $client;
/**
+ * XmlRpc endpoint
+ *
+ * @var string
+ */
+ protected $path;
+
+ /**
* Odoo constructor
*
* @param string $host The url
|
First call to getClient('someendpoint') threw a notice, fixed it
|
jacobsteringa_OdooClient
|
train
|
68127e3d9ef8f6d0d85b823ec62656d74efb221d
|
diff --git a/nece/models.py b/nece/models.py
index <HASH>..<HASH> 100644
--- a/nece/models.py
+++ b/nece/models.py
@@ -77,13 +77,25 @@ class TranslationModel(models.Model, TranslationMixin):
return self
def language_or_none(self, language_code):
+ language_code = self.get_language_key(language_code)
if self.is_default_language(language_code):
return self.language(language_code)
- language_code = self.get_language_key(language_code)
- if not self.translations or self.translations.get(language_code):
+ if not self.translations or not self.translations.get(language_code):
return None
return self.language(language_code)
+ def language_as_dict(self, language_code):
+ tf = self.translatable_fields
+ language_code = self.get_language_key(language_code)
+ if self.is_default_language(language_code):
+ return {k: v for k, v in self.__dict__.items() if k in tf}
+
+ translations = self.translations or {}
+ if translations:
+ translations = translations.get(language_code, {})
+ return {k: v for k, v in translations.items() if v}
+ return {}
+
def save(self, *args, **kwargs):
language_code = self._language_code
self.reset_language()
diff --git a/tests/tests.py b/tests/tests.py
index <HASH>..<HASH> 100644
--- a/tests/tests.py
+++ b/tests/tests.py
@@ -63,3 +63,12 @@ class TranslationTest(TestCase):
def test_translation_mapping(self):
self.assertTrue(Fruit.objects.language('tr').exists())
self.assertEqual(Fruit.objects.language('tr')[0].name, 'elma')
+
+ def test_language_as_dict(self):
+ fruit = Fruit.objects.get(name='apple')
+ self.assertEqual(fruit.language_as_dict('en_us'),
+ {'benefits': u'good for health', 'name': u'apple'})
+ fruit.translate('az_az', name='alma')
+ self.assertEqual(fruit.language_as_dict('az_az'),
+ {'name': 'alma'})
+ self.assertEqual(fruit.language_as_dict('non_existant'), {})
|
language_as_dict with only containing translated fields
|
tatterdemalion_django-nece
|
train
|
3160353f9f57ac37019f8738ba029d3e11c83c07
|
diff --git a/pgmpy/factors/continuous/ContinuousFactor.py b/pgmpy/factors/continuous/ContinuousFactor.py
index <HASH>..<HASH> 100644
--- a/pgmpy/factors/continuous/ContinuousFactor.py
+++ b/pgmpy/factors/continuous/ContinuousFactor.py
@@ -300,7 +300,7 @@ class ContinuousFactor(BaseFactor):
"""
phi = self if inplace else self.copy()
- phi.distriution = phi.distribution.normalize(inplace=False)
+ phi.distribution.normalize(inplace=True)
if not inplace:
return phi
diff --git a/pgmpy/tests/test_factors/test_continuous/test_ContinuousFactor.py b/pgmpy/tests/test_factors/test_continuous/test_ContinuousFactor.py
index <HASH>..<HASH> 100644
--- a/pgmpy/tests/test_factors/test_continuous/test_ContinuousFactor.py
+++ b/pgmpy/tests/test_factors/test_continuous/test_ContinuousFactor.py
@@ -259,7 +259,7 @@ class TestContinuousFactorMethods(unittest.TestCase):
self.assertEqual(phi4.scope(), phi2.scope())
for inp in np.random.rand(1, 2):
np_test.assert_almost_equal(
- phi4.pdf(inp[0], inp[1]), 2 * self.pdf2(inp[0], inp[1])
+ phi4.pdf(inp[0], inp[1]), self.pdf2(inp[0], inp[1])
)
phi2.normalize()
|
Solves a bug in the normalize() function of ContinuousFactor (#<I>).
* Fixes a typo.
* Uses inplace=True because is always safe.
|
pgmpy_pgmpy
|
train
|
6954a071915dc2a4d214ade0a6041eae8bbceb22
|
diff --git a/src/Symfony/Bridge/Doctrine/Form/ChoiceList/ORMQueryBuilderLoader.php b/src/Symfony/Bridge/Doctrine/Form/ChoiceList/ORMQueryBuilderLoader.php
index <HASH>..<HASH> 100644
--- a/src/Symfony/Bridge/Doctrine/Form/ChoiceList/ORMQueryBuilderLoader.php
+++ b/src/Symfony/Bridge/Doctrine/Form/ChoiceList/ORMQueryBuilderLoader.php
@@ -104,7 +104,7 @@ class ORMQueryBuilderLoader implements EntityLoaderInterface
// Filter out non-integer values (e.g. ""). If we don't, some
// databases such as PostgreSQL fail.
$values = array_values(array_filter($values, function ($v) {
- return (string) $v === (string) (int) $v;
+ return (string) $v === (string) (int) $v || ctype_digit($v);
}));
} elseif ('guid' === $metadata->getTypeOfField($identifier)) {
$parameterType = Connection::PARAM_STR_ARRAY;
diff --git a/src/Symfony/Bridge/Doctrine/Tests/Form/ChoiceList/ORMQueryBuilderLoaderTest.php b/src/Symfony/Bridge/Doctrine/Tests/Form/ChoiceList/ORMQueryBuilderLoaderTest.php
index <HASH>..<HASH> 100644
--- a/src/Symfony/Bridge/Doctrine/Tests/Form/ChoiceList/ORMQueryBuilderLoaderTest.php
+++ b/src/Symfony/Bridge/Doctrine/Tests/Form/ChoiceList/ORMQueryBuilderLoaderTest.php
@@ -87,7 +87,7 @@ class ORMQueryBuilderLoaderTest extends \PHPUnit_Framework_TestCase
$query->expects($this->once())
->method('setParameter')
- ->with('ORMQueryBuilderLoader_getEntitiesByIds_id', array(1, 2, 3), Connection::PARAM_INT_ARRAY)
+ ->with('ORMQueryBuilderLoader_getEntitiesByIds_id', array(1, 2, 3, '9223372036854775808'), Connection::PARAM_INT_ARRAY)
->willReturn($query);
$qb = $this->getMockBuilder('Doctrine\ORM\QueryBuilder')
@@ -103,7 +103,7 @@ class ORMQueryBuilderLoaderTest extends \PHPUnit_Framework_TestCase
->from('Symfony\Bridge\Doctrine\Tests\Fixtures\SingleIntIdEntity', 'e');
$loader = new ORMQueryBuilderLoader($qb);
- $loader->getEntitiesByIds('id', array(1, '', 2, 3, 'foo'));
+ $loader->getEntitiesByIds('id', array(1, '', 2, 3, 'foo', '9223372036854775808'));
}
public function testEmbeddedIdentifierName()
|
[Doctrine][Form] support large integers
|
symfony_symfony
|
train
|
b8ecc1eed3407b634800aeb7dc8f7feb90e7a3fc
|
diff --git a/packages/cx-google-maps/src/OverlayView.js b/packages/cx-google-maps/src/OverlayView.js
index <HASH>..<HASH> 100644
--- a/packages/cx-google-maps/src/OverlayView.js
+++ b/packages/cx-google-maps/src/OverlayView.js
@@ -1,8 +1,4 @@
import { VDOM, PureContainer } from 'cx/ui';
-import { attachEventCallbacks } from './attachEventCallbacks';
-import { shallowEquals, getTopLevelBoundingClientRect } from 'cx/util';
-import { standardSetterMap } from './standardSetterMap';
-import { autoUpdate } from './autoUpdate';
// OverlayView does not have settable properties
|
Remove extraneous imports from OverlayView
|
codaxy_cx-google-maps
|
train
|
220b60f3b2e7aaa8010aa47794ea81a9606c1670
|
diff --git a/framework/CHANGELOG.md b/framework/CHANGELOG.md
index <HASH>..<HASH> 100644
--- a/framework/CHANGELOG.md
+++ b/framework/CHANGELOG.md
@@ -4,7 +4,7 @@ Yii Framework 2 Change Log
2.0.0 under development
-----------------------
-- no changes in this release.
+- Enh #4275: Added `removeChildren()` to `yii\rbac\ManagerInterface` and implementations (samdark)
2.0.0-rc September 27, 2014
diff --git a/framework/rbac/DbManager.php b/framework/rbac/DbManager.php
index <HASH>..<HASH> 100644
--- a/framework/rbac/DbManager.php
+++ b/framework/rbac/DbManager.php
@@ -542,6 +542,16 @@ class DbManager extends BaseManager
/**
* @inheritdoc
*/
+ public function removeChildren($parent)
+ {
+ return $this->db->createCommand()
+ ->delete($this->itemChildTable, ['parent' => $parent->name])
+ ->execute() > 0;
+ }
+
+ /**
+ * @inheritdoc
+ */
public function hasChild($parent, $child)
{
return (new Query)
diff --git a/framework/rbac/ManagerInterface.php b/framework/rbac/ManagerInterface.php
index <HASH>..<HASH> 100644
--- a/framework/rbac/ManagerInterface.php
+++ b/framework/rbac/ManagerInterface.php
@@ -146,6 +146,14 @@ interface ManagerInterface
public function removeChild($parent, $child);
/**
+ * Removed all children form their parent.
+ * Note, the children items are not deleted. Only the parent-child relationships are removed.
+ * @param Item $parent
+ * @return boolean whether the removal is successful
+ */
+ public function removeChildren($parent);
+
+ /**
* Returns a value indicating whether the child already exists for the parent.
* @param Item $parent
* @param Item $child
diff --git a/framework/rbac/PhpManager.php b/framework/rbac/PhpManager.php
index <HASH>..<HASH> 100644
--- a/framework/rbac/PhpManager.php
+++ b/framework/rbac/PhpManager.php
@@ -218,6 +218,20 @@ class PhpManager extends BaseManager
/**
* @inheritdoc
*/
+ public function removeChildren($parent)
+ {
+ if (isset($this->children[$parent->name])) {
+ unset($this->children[$parent->name]);
+ $this->saveItems();
+ return true;
+ } else {
+ return false;
+ }
+ }
+
+ /**
+ * @inheritdoc
+ */
public function hasChild($parent, $child)
{
return isset($this->children[$parent->name][$child->name]);
|
Fixes #<I>: Added `removeChildren()` to `yii\rbac\ManagerInterface` and implementations
|
yiisoft_yii2
|
train
|
544e0ac2c705bf82cfc379730e9923a55bab009e
|
diff --git a/src/umbra/components/factory/scriptEditor/scriptEditor.py b/src/umbra/components/factory/scriptEditor/scriptEditor.py
index <HASH>..<HASH> 100644
--- a/src/umbra/components/factory/scriptEditor/scriptEditor.py
+++ b/src/umbra/components/factory/scriptEditor/scriptEditor.py
@@ -1460,6 +1460,11 @@ class ScriptEditor(UiComponent):
:param tabIndex: Tab index. ( Integer )
"""
+ # Ensure focus on **Editor_Status.ui.Languages_comboBox** is removed to avoid voodoo magic convolutions.
+ if QApplication.focusWidget() == self.Editor_Status.ui.Languages_comboBox:
+ self.Editor_Status.ui.Languages_comboBox.clearFocus()
+ QApplication.processEvents()
+
self.Editor_Status._Editor_Status__Languages_comboBox_setDefaultViewState()
self.__setWindowTitle()
diff --git a/src/umbra/ui/widgets/codeEditor_QPlainTextEdit.py b/src/umbra/ui/widgets/codeEditor_QPlainTextEdit.py
index <HASH>..<HASH> 100644
--- a/src/umbra/ui/widgets/codeEditor_QPlainTextEdit.py
+++ b/src/umbra/ui/widgets/codeEditor_QPlainTextEdit.py
@@ -770,7 +770,6 @@ class CodeEditor_QPlainTextEdit(QPlainTextEdit):
if self.highlighter:
self.highlighter.setParent(None)
self.highlighter = None
- QApplication.processEvents()
return True
@core.executionTrace
|
Prevent crash related to voodoo magic focus convolutions in "scriptEditor" component.
|
KelSolaar_Umbra
|
train
|
92daa9cd22fa96c4006d5b9b0071810db7f683d9
|
diff --git a/src/Downloader.php b/src/Downloader.php
index <HASH>..<HASH> 100644
--- a/src/Downloader.php
+++ b/src/Downloader.php
@@ -65,6 +65,9 @@ class Downloader
}
} elseif (\is_array($endpoint) || false !== strpos($endpoint, '.json') || 'flex://defaults' === $endpoint) {
$this->endpoints = array_values((array) $endpoint);
+ if (\is_string($endpoint) && false !== strpos($endpoint, '.json')) {
+ $this->endpoints[] = 'flex://defaults';
+ }
} else {
$this->legacyEndpoint = rtrim($endpoint, '/');
}
|
Use default endopoints as fallbacks if Composer endpoint is specified as a string
|
symfony_flex
|
train
|
a340a2614fb6c6343785dac36830bb611e1fde42
|
diff --git a/package.json b/package.json
index <HASH>..<HASH> 100644
--- a/package.json
+++ b/package.json
@@ -78,10 +78,12 @@
},
"jest": {
"collectCoverageFrom": [
+ "packages/*/src/**/*.mjs",
"packages/*/src/**/*.js",
+ "codemods/*/src/**/*.mjs",
"codemods/*/src/**/*.js"
],
- "testRegex": "./(packages|codemods)/[^/]+/test/.+\\.js$",
+ "testRegex": "./(packages|codemods)/[^/]+/test/.+\\.m?js$",
"testPathIgnorePatterns": [
"/node_modules/",
"/test/fixtures/",
@@ -90,24 +92,23 @@
"/test/tmp/",
"/test/__data__/",
"/test/helpers/",
- "<rootDir>/test/warning.js",
+ "<rootDir>/test/warning\\.js",
"<rootDir>/build/",
- "_browser.js"
+ "_browser\\.js"
],
"testEnvironment": "node",
"setupTestFrameworkScriptFile": "<rootDir>/test/testSetupFile.js",
"transformIgnorePatterns": [
"/node_modules/",
- "/test/fixtures/",
- "/test/tmp/",
- "/test/__data__/",
- "/lib/"
- ],
- "modulePaths": [
- "<rootDir>/packages/"
+ "<rootDir>/packages/babel-standalone/babel(\\.min)?\\.js",
+ "<rootDir>/packages/babel-preset-env-standalone/babel-preset-env(\\.min)?\\.js",
+ "/test/(fixtures|tmp|__data__)/",
+ "<rootDir>/(packages|codemods)/[^/]+/lib/"
],
"modulePathIgnorePatterns": [
"/test/fixtures/",
+ "/test/tmp/",
+ "/test/__data__/",
"<rootDir>/build/"
]
}
diff --git a/packages/babel-register/test/cache.js b/packages/babel-register/test/cache.js
index <HASH>..<HASH> 100644
--- a/packages/babel-register/test/cache.js
+++ b/packages/babel-register/test/cache.js
@@ -34,7 +34,7 @@ describe("@babel/register - caching", () => {
beforeEach(() => {
// Since lib/cache is a singleton we need to fully reload it
- jest.resetModuleRegistry();
+ jest.resetModules();
const cache = require("../lib/cache");
load = cache.load;
diff --git a/packages/babel-register/test/index.js b/packages/babel-register/test/index.js
index <HASH>..<HASH> 100644
--- a/packages/babel-register/test/index.js
+++ b/packages/babel-register/test/index.js
@@ -55,7 +55,7 @@ describe("@babel/register", function() {
currentHook = null;
currentOptions = null;
sourceMapSupport = false;
- jest.resetModuleRegistry();
+ jest.resetModules();
});
test("registers hook correctly", () => {
|
Fix reseting modules in jest and config (#<I>)
* Fix reseting modules in jest and config
we have lib folders inside the source folders which should not be ignored.
* Add codemods lib folder
* Support mjs
* improve ignore pattern
|
babel_babel
|
train
|
ad8d196cf9a5c021264226ca93ad581e00d1d051
|
diff --git a/src/gitgraph.js b/src/gitgraph.js
index <HASH>..<HASH> 100644
--- a/src/gitgraph.js
+++ b/src/gitgraph.js
@@ -30,6 +30,34 @@
}
/**
+ * Returns the scaling factor of given canvas `context`.
+ * Handles high-resolution displays.
+ *
+ * @param {Object} context
+ * @returns {Number}
+ * @private
+ */
+ function _getScale ( context ) {
+ var backingStorePixelRatio;
+ var scalingFactor;
+
+ // Account for high-resolution displays
+ scalingFactor = 1;
+
+ if ( window.devicePixelRatio ) {
+ backingStorePixelRatio = context.webkitBackingStorePixelRatio ||
+ context.mozBackingStorePixelRatio ||
+ context.msBackingStorePixelRatio ||
+ context.oBackingStorePixelRatio ||
+ context.backingStorePixelRatio || 1;
+
+ scalingFactor *= window.devicePixelRatio / backingStorePixelRatio;
+ }
+
+ return scalingFactor;
+ }
+
+ /**
* GitGraph
*
* @constructor
@@ -245,21 +273,7 @@
* @this GitGraph
**/
GitGraph.prototype.render = function () {
- var backingStorePixelRatio;
- var scalingFactor;
-
- // Account for high-resolution displays
- scalingFactor = 1;
-
- if ( window.devicePixelRatio ) {
- backingStorePixelRatio = this.context.webkitBackingStorePixelRatio ||
- this.context.mozBackingStorePixelRatio ||
- this.context.msBackingStorePixelRatio ||
- this.context.oBackingStorePixelRatio ||
- this.context.backingStorePixelRatio || 1;
-
- scalingFactor *= window.devicePixelRatio / backingStorePixelRatio;
- }
+ var scalingFactor = _getScale( this.context );
// Resize canvas
var unscaledResolution = {
|
Extract scaling ratio calculation into _getScale()
So we can re-use it
|
nicoespeon_gitgraph.js
|
train
|
a76abb7b68bc4309c5cdacfbb621145e0db5d501
|
diff --git a/src/config/roles.php b/src/config/roles.php
index <HASH>..<HASH> 100644
--- a/src/config/roles.php
+++ b/src/config/roles.php
@@ -20,11 +20,12 @@ return [
| Database Table Prefix
|--------------------------------------------------------------------------
|
- | If your tables have a prefix you may specify that here.
+ | By default, this pulls the prefix from your selected database connection.
+ | There is no reason to change this.
|
*/
- 'prefix' => '',
+ 'prefix' => config('database.connections.' . config('database.default') . '.prefix'),
/*
|--------------------------------------------------------------------------
|
make prefix selection automatic
make prefix selection automatic - based on what the users Laravel settings are. No need to define it twice (once in `config\database.php` and once here).
|
romanbican_roles
|
train
|
cc4fa0543fd59232770a0479312922cc28e7c6fb
|
diff --git a/jsr330activator.tests/src/test/java/no/steria/osgi/jsr330activator/tests/Jsr330ActivatorMultipleInstancesOfOneServiceIntegrationTest.java b/jsr330activator.tests/src/test/java/no/steria/osgi/jsr330activator/tests/Jsr330ActivatorMultipleInstancesOfOneServiceIntegrationTest.java
index <HASH>..<HASH> 100644
--- a/jsr330activator.tests/src/test/java/no/steria/osgi/jsr330activator/tests/Jsr330ActivatorMultipleInstancesOfOneServiceIntegrationTest.java
+++ b/jsr330activator.tests/src/test/java/no/steria/osgi/jsr330activator/tests/Jsr330ActivatorMultipleInstancesOfOneServiceIntegrationTest.java
@@ -59,6 +59,8 @@ public class Jsr330ActivatorMultipleInstancesOfOneServiceIntegrationTest extends
* Validate that a service depending on a collection injection has
* been started. Verify that the expected number of services has
* been injected.
+ *
+ * Get and use one of the services.
*/
@Test
public void testCollectionInjectionCatcherServiceFoundAndActivated() {
@@ -75,10 +77,18 @@ public class Jsr330ActivatorMultipleInstancesOfOneServiceIntegrationTest extends
/**
* Validate that a service depending on named injections of
* multiple implementations of a service have been started.
+ *
+ * Get and use one of the services.
*/
@Test
public void testOptionalInjectionCatcherServiceFoundAndActivated() {
- assertNull(namedServiceInjectionCatcher.getMessage());
+ Collection<String> serviceNames = namedServiceInjectionCatcher.getInjectedStorageServiceNames();
+ assertEquals(3, serviceNames.size());
+ UUID id = UUID.randomUUID();
+ String data = "Hi there!";
+ StorageService fileStorage = namedServiceInjectionCatcher.getStorageService("file");
+ boolean result = fileStorage.save(id, data);
+ assertTrue(result);
}
}
|
Made a real integration test for the NamedServiceInjectionCatcher service.
Accesses and uses a service.
|
sbang_jsr330activator
|
train
|
113339b029999d29be0d6a2e442391956f60cc31
|
diff --git a/src/_pytest/_io/terminalwriter.py b/src/_pytest/_io/terminalwriter.py
index <HASH>..<HASH> 100644
--- a/src/_pytest/_io/terminalwriter.py
+++ b/src/_pytest/_io/terminalwriter.py
@@ -149,7 +149,18 @@ class TerminalWriter:
msg = self.markup(msg, **markup)
- self._file.write(msg)
+ try:
+ self._file.write(msg)
+ except UnicodeEncodeError:
+ # Some environments don't support printing general Unicode
+ # strings, due to misconfiguration or otherwise; in that case,
+ # print the string escaped to ASCII.
+ # When the Unicode situation improves we should consider
+ # letting the error propagate instead of masking it (see #7475
+ # for one brief attempt).
+ msg = msg.encode("unicode-escape").decode("ascii")
+ self._file.write(msg)
+
if flush:
self.flush()
diff --git a/testing/io/test_terminalwriter.py b/testing/io/test_terminalwriter.py
index <HASH>..<HASH> 100644
--- a/testing/io/test_terminalwriter.py
+++ b/testing/io/test_terminalwriter.py
@@ -49,6 +49,15 @@ def test_terminalwriter_dumb_term_no_markup(monkeypatch: MonkeyPatch) -> None:
assert not tw.hasmarkup
+def test_terminalwriter_not_unicode() -> None:
+ """If the file doesn't support Unicode, the string is unicode-escaped (#7475)."""
+ buffer = io.BytesIO()
+ file = io.TextIOWrapper(buffer, encoding="cp1252")
+ tw = terminalwriter.TerminalWriter(file)
+ tw.write("hello 🌀 wôrld אבג", flush=True)
+ assert buffer.getvalue() == br"hello \U0001f300 w\xf4rld \u05d0\u05d1\u05d2"
+
+
win32 = int(sys.platform == "win32")
|
terminalwriter: bring back handling of printing characters not supported by stdout
|
pytest-dev_pytest
|
train
|
106fdcf49e5b4053f3afd6a01d8cc3ace5bd4818
|
diff --git a/classes/taxonomy.class.php b/classes/taxonomy.class.php
index <HASH>..<HASH> 100644
--- a/classes/taxonomy.class.php
+++ b/classes/taxonomy.class.php
@@ -68,7 +68,7 @@ class Cuztom_Taxonomy
add_action( 'init', array( &$this, 'register_taxonomy_for_object_type' ) );
}
- if( isset( $args['show_column'] ) && $args['show_column'] )
+ if( ( get_bloginfo( 'version' ) < '3.5' ) && ( isset( $args['show_column'] ) && $args['show_column'] ) )
{
add_filter( 'manage_' . $this->post_type_name . '_posts_columns', array( &$this, 'add_column' ) );
add_action( 'manage_' . $this->post_type_name . '_posts_custom_column', array( &$this, 'add_column_content' ), 10, 2 );
@@ -80,7 +80,6 @@ class Cuztom_Taxonomy
}
}
-
/**
* Registers the custom taxonomy with the given arguments
*
@@ -136,7 +135,6 @@ class Cuztom_Taxonomy
register_taxonomy( $this->name, $this->post_type_name, $args );
}
-
/**
* Used to attach the existing taxonomy to the post type
*
@@ -149,7 +147,6 @@ class Cuztom_Taxonomy
register_taxonomy_for_object_type( $this->name, $this->post_type_name );
}
-
/**
* Used to add a column head to the Post Type's List Table
*
@@ -170,7 +167,6 @@ class Cuztom_Taxonomy
return $columns;
}
-
/**
* Used to add the column content to the column head
*
@@ -189,7 +185,6 @@ class Cuztom_Taxonomy
echo implode( $terms, ', ' );
}
-
/**
* Used to make all columns sortable
*
@@ -207,7 +202,6 @@ class Cuztom_Taxonomy
return $columns;
}
-
/**
* Adds a filter to the post table filters
*
@@ -235,7 +229,6 @@ class Cuztom_Taxonomy
}
}
-
/**
* Applies the selected filter to the query
*
@@ -257,7 +250,6 @@ class Cuztom_Taxonomy
}
}
-
/**
* Notice for reserved term usage
*
|
Taxonomy admin column only for older versions
|
gizburdt_cuztom
|
train
|
fe4e202f3df00f78860a514d7fc54f1d11af789d
|
diff --git a/test/www/jxcore/bv_tests/testCreatePeerListener.js b/test/www/jxcore/bv_tests/testCreatePeerListener.js
index <HASH>..<HASH> 100644
--- a/test/www/jxcore/bv_tests/testCreatePeerListener.js
+++ b/test/www/jxcore/bv_tests/testCreatePeerListener.js
@@ -503,6 +503,7 @@ test('createPeerListener - pleaseConnect === true, connection resolves promise',
t.ok(true, 'promise should resolve');
if (connectionReceived) {
nativeServer.close();
+ t.end();
}
})
.catch(function (err) {
|
Missing t.end()
I'm trying to fix the test failure we are seeing in this test but I
can't reproduce it locally, not even with the 1% CPU trick, so I'm going
blind here. Next I'll have to try to Remote Terminal Server into Appveyor.
|
thaliproject_Thali_CordovaPlugin
|
train
|
cf5697ff32292d656465aebaf704323806bfde83
|
diff --git a/builtin/providers/aws/resource_aws_vpc.go b/builtin/providers/aws/resource_aws_vpc.go
index <HASH>..<HASH> 100644
--- a/builtin/providers/aws/resource_aws_vpc.go
+++ b/builtin/providers/aws/resource_aws_vpc.go
@@ -57,7 +57,6 @@ func resourceAwsVpc() *schema.Resource {
Computed: true,
},
-
"tags": tagsSchema(),
},
}
@@ -68,7 +67,7 @@ func resourceAwsVpcCreate(d *schema.ResourceData, meta interface{}) error {
// Create the VPC
createOpts := &ec2.CreateVpc{
- CidrBlock: d.Get("cidr_block").(string),
+ CidrBlock: d.Get("cidr_block").(string),
InstanceTenancy: d.Get("instance_tenancy").(string),
}
log.Printf("[DEBUG] VPC create config: %#v", createOpts)
@@ -115,6 +114,7 @@ func resourceAwsVpcRead(d *schema.ResourceData, meta interface{}) error {
return err
}
if vpcRaw == nil {
+ d.SetId("")
return nil
}
@@ -243,8 +243,7 @@ func VPCStateRefreshFunc(conn *ec2.EC2, id string) resource.StateRefreshFunc {
}
}
-
-func resourceAwsVpcSetDefaultNetworkAcl(conn *ec2.EC2, d *schema.ResourceData) error {
+func resourceAwsVpcSetDefaultNetworkAcl(conn *ec2.EC2, d *schema.ResourceData) error {
filter := ec2.NewFilter()
filter.Add("default", "true")
filter.Add("vpc-id", d.Id())
@@ -260,7 +259,7 @@ func resourceAwsVpcSetDefaultNetworkAcl(conn *ec2.EC2, d *schema.ResourceData) e
return nil
}
-func resourceAwsVpcSetDefaultSecurityGroup(conn *ec2.EC2, d *schema.ResourceData) error {
+func resourceAwsVpcSetDefaultSecurityGroup(conn *ec2.EC2, d *schema.ResourceData) error {
filter := ec2.NewFilter()
filter.Add("group-name", "default")
filter.Add("vpc-id", d.Id())
|
providers/aws: if a VPC doesn't exist, then remove from state
|
hashicorp_terraform
|
train
|
ee30c4fd6ce8924ac305f988602f5f0a32435340
|
diff --git a/autograd/util.py b/autograd/util.py
index <HASH>..<HASH> 100644
--- a/autograd/util.py
+++ b/autograd/util.py
@@ -130,57 +130,43 @@ def base_class(t):
return t
def flatten(value):
- """value can be any nesting of tuples, arrays, dicts.
- returns 1D numpy array and an unflatten function."""
+ """Flattens any nesting of tuples, arrays, or dicts.
+ Returns 1D numpy array and an unflatten function.
+ Doesn't preserve mixed numeric types (e.g. floats and ints).
+ Assumes dict keys are sortable."""
if isinstance(getval(value), np.ndarray):
+ shape = value.shape
def unflatten(vector):
- return np.reshape(vector, value.shape)
+ return np.reshape(vector, shape)
return np.ravel(value), unflatten
- elif isinstance(getval(value), float):
+ elif isinstance(getval(value), (float, int)):
return np.array([value]), lambda x : x[0]
- elif isinstance(getval(value), tuple):
+ elif isinstance(getval(value), (tuple, list)):
+ constructor = type(getval(value))
if not value:
- return np.array([]), lambda x : ()
- flattened_first, unflatten_first = flatten(value[0])
- flattened_rest, unflatten_rest = flatten(value[1:])
- def unflatten(vector):
- N = len(flattened_first)
- return (unflatten_first(vector[:N]),) + unflatten_rest(vector[N:])
-
- return np.concatenate((flattened_first, flattened_rest)), unflatten
+ return np.array([]), lambda x : constructor()
+ flat_pieces, unflatteners = zip(*map(flatten, value))
+ split_indices = np.cumsum([len(vec) for vec in flat_pieces])
- elif isinstance(getval(value), list):
- if not value:
- return np.array([]), lambda x : []
- flattened_first, unflatten_first = flatten(value[0])
- flattened_rest, unflatten_rest = flatten(value[1:])
def unflatten(vector):
- N = len(flattened_first)
- return [unflatten_first(vector[:N])] + unflatten_rest(vector[N:])
+ pieces = np.split(vector, split_indices)
+ return constructor(unflatten(v) for unflatten, v in zip(unflatteners, pieces))
- return np.concatenate((flattened_first, flattened_rest)), unflatten
+ return np.concatenate(flat_pieces), unflatten
elif isinstance(getval(value), dict):
- flattened = []
- unflatteners = []
- lengths = []
- keys = []
- for k, v in sorted(iteritems(value), key=itemgetter(0)):
- cur_flattened, cur_unflatten = flatten(v)
- flattened.append(cur_flattened)
- unflatteners.append(cur_unflatten)
- lengths.append(len(cur_flattened))
- keys.append(k)
+ items = sorted(iteritems(value), key=itemgetter(0))
+ keys, flat_pieces, unflatteners = zip(*[(k,) + flatten(v) for k, v in items])
+ split_indices = np.cumsum([len(vec) for vec in flat_pieces])
def unflatten(vector):
- split_ixs = np.cumsum(lengths)
- pieces = np.split(vector, split_ixs)
+ pieces = np.split(vector, split_indices)
return {key: unflattener(piece)
for piece, unflattener, key in zip(pieces, unflatteners, keys)}
- return np.concatenate(flattened), unflatten
+ return np.concatenate(flat_pieces), unflatten
else:
raise Exception("Don't know how to flatten type {}".format(type(value)))
|
polish flatten, make it faster, use less memory
|
HIPS_autograd
|
train
|
0d63d3c5b06b71d6495033b3bc1a1239ac7c8835
|
diff --git a/lib/licensed/sources/bundler.rb b/lib/licensed/sources/bundler.rb
index <HASH>..<HASH> 100644
--- a/lib/licensed/sources/bundler.rb
+++ b/lib/licensed/sources/bundler.rb
@@ -29,7 +29,7 @@ module Licensed
# `loaded_from` if available.
def spec_file
return @spec_file if defined?(@spec_file)
- return @spec_file = nil unless loaded_from && File.exist?(loaded_from)
+ return @spec_file = nil unless loaded_from && File.file?(loaded_from)
@spec_file = begin
file = { name: File.basename(loaded_from), dir: File.dirname(loaded_from) }
Licensee::ProjectFiles::PackageManagerFile.new(File.read(loaded_from), file)
|
enforce that the spec file is an actual file
|
github_licensed
|
train
|
0d9e85efa2dc0b7daa959137f1d4f6657a5a0832
|
diff --git a/isvcs/isvc.go b/isvcs/isvc.go
index <HASH>..<HASH> 100644
--- a/isvcs/isvc.go
+++ b/isvcs/isvc.go
@@ -30,7 +30,7 @@ var Mgr *Manager
const (
IMAGE_REPO = "zenoss/serviced-isvcs"
- IMAGE_TAG = "v20"
+ IMAGE_TAG = "v21"
)
func Init() {
|
bump serviced to use <I> of isvcs
|
control-center_serviced
|
train
|
62b353046f89aeb13fe19a943d1951024f5da5c9
|
diff --git a/tests/FrontControllerTest.php b/tests/FrontControllerTest.php
index <HASH>..<HASH> 100644
--- a/tests/FrontControllerTest.php
+++ b/tests/FrontControllerTest.php
@@ -451,6 +451,8 @@ class FrontControllerTest extends TestCase
*/
public function testRedirectWithRtmpStream()
{
+ $this->markTestIncomplete('We need to find another RTMP video.');
+
$this->config->stream = true;
$this->assertRequestIsOk(
'redirect',
diff --git a/tests/VideoDownloadTest.php b/tests/VideoDownloadTest.php
index <HASH>..<HASH> 100644
--- a/tests/VideoDownloadTest.php
+++ b/tests/VideoDownloadTest.php
@@ -97,7 +97,6 @@ class VideoDownloadTest extends TestCase
* @return void
* @dataProvider urlProvider
* @dataProvider m3uUrlProvider
- * @dataProvider rtmpUrlProvider
* @dataProvider remuxUrlProvider
*/
public function testGetURL(
@@ -278,7 +277,6 @@ class VideoDownloadTest extends TestCase
* @return void
* @dataProvider urlProvider
* @dataProvider m3uUrlProvider
- * @dataProvider rtmpUrlProvider
*/
public function testGetJSON($url, $format)
{
@@ -316,7 +314,6 @@ class VideoDownloadTest extends TestCase
* @return void
* @dataProvider urlProvider
* @dataProvider m3uUrlProvider
- * @dataProvider rtmpUrlProvider
* @dataProvider remuxUrlProvider
*/
public function testGetFilename($url, $format, $filename, $extension)
@@ -349,7 +346,6 @@ class VideoDownloadTest extends TestCase
* @return void
* @dataProvider urlProvider
* @dataProvider m3uUrlProvider
- * @dataProvider rtmpUrlProvider
* @dataProvider remuxUrlProvider
*/
public function testGetAudioFilename($url, $format, $filename)
@@ -490,6 +486,8 @@ class VideoDownloadTest extends TestCase
*/
public function testGetRtmpStream($url, $format)
{
+ $this->markTestIncomplete('We need to find another RTMP video.');
+
$this->assertStream(
$this->download->getRtmpStream(
$this->download->getJSON($url, $format)
|
test(phpunit): Disable RTMP tests because the video we used is not available anymore
|
Rudloff_alltube
|
train
|
0dcb3b164fa008028c881f4547a8b0ed31e1a89b
|
diff --git a/common/persistence/EnvironmentVariableKVDriver.php b/common/persistence/EnvironmentVariableKVDriver.php
index <HASH>..<HASH> 100644
--- a/common/persistence/EnvironmentVariableKVDriver.php
+++ b/common/persistence/EnvironmentVariableKVDriver.php
@@ -43,7 +43,7 @@ class EnvironmentVariableKVDriver implements common_persistence_KvDriver
*/
public function set($id, $value, $ttl = null, $nx = false)
{
- throw new common_exception_NoImplementation(__METHOD__ . '@' . __CLASS__ . 'not implemented');
+ throw new common_exception_NoImplementation(__METHOD__ . '@' . __CLASS__ . ' not implemented');
}
/**
|
Update common/persistence/EnvironmentVariableKVDriver.php
|
oat-sa_generis
|
train
|
bf0ab6b722613d69f9a8073ab8644c1a22a4a56d
|
diff --git a/builder/digitalocean/builder_acc_test.go b/builder/digitalocean/builder_acc_test.go
index <HASH>..<HASH> 100644
--- a/builder/digitalocean/builder_acc_test.go
+++ b/builder/digitalocean/builder_acc_test.go
@@ -20,6 +20,10 @@ func TestBuilderAcc_basic(t *testing.T) {
}
func TestBuilderAcc_imageId(t *testing.T) {
+ if os.Getenv("PACKER_ACC") == "" {
+ t.Skip("Acceptance tests skipped unless env 'PACKER_ACC' set")
+ }
+
builderT.Test(t, builderT.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Builder: &Builder{},
|
Force test to be skipped unless PACKER_ACC set.
|
hashicorp_packer
|
train
|
3265d13b082412f880767d6527894a5d9f070c03
|
diff --git a/splinter/driver/webdriver/phantomjs.py b/splinter/driver/webdriver/phantomjs.py
index <HASH>..<HASH> 100644
--- a/splinter/driver/webdriver/phantomjs.py
+++ b/splinter/driver/webdriver/phantomjs.py
@@ -11,12 +11,6 @@ class WebDriverElement(BaseWebDriverElement):
def double_click(self):
raise NotImplementedError('Not supported by webdriver.')
- def mouse_over(self):
- raise NotImplementedError('Not supported by webdriver.')
-
- def mouse_out(self):
- raise NotImplementedError('Not supported by webdriver.')
-
class WebDriver(BaseWebDriver):
driver_name = "PhantomJS"
diff --git a/tests/test_webdriver_phantomjs.py b/tests/test_webdriver_phantomjs.py
index <HASH>..<HASH> 100644
--- a/tests/test_webdriver_phantomjs.py
+++ b/tests/test_webdriver_phantomjs.py
@@ -32,14 +32,6 @@ class PhantomJSBrowserTest(WebDriverTests, unittest.TestCase):
with self.assertRaises(NotImplementedError):
self.browser.find_by_id('visible').double_click()
- def test_mouse_over(self):
- with self.assertRaises(NotImplementedError):
- self.browser.find_by_id('visible').first.mouse_over()
-
- def test_mouse_out(self):
- with self.assertRaises(NotImplementedError):
- self.browser.find_by_id('visible').first.mouse_out()
-
def test_access_prompts_and_be_able_to_fill_then(self):
with self.assertRaises(NotImplementedError):
self.browser.get_alert()
|
phantomjs: enabling mouse over and out.
|
cobrateam_splinter
|
train
|
059d9b7dffa3b751a380e2c822ca71b5c357a273
|
diff --git a/src/Ray/Di/Injector.php b/src/Ray/Di/Injector.php
index <HASH>..<HASH> 100644
--- a/src/Ray/Di/Injector.php
+++ b/src/Ray/Di/Injector.php
@@ -289,16 +289,10 @@ class Injector implements InjectorInterface
$module = $this->module;
$bind = $module($class, new $this->bind);
/* @var $bind \Ray\Aop\Bind */
- if ($bind->hasBinding() === true) {
- // create the new instance with aspect
- $object = $this->compiler->newInstance($class, $params, $bind);
- } else {
- // create the new instance
- $object = call_user_func_array(
- [$this->config->getReflect($class), 'newInstance'],
- $params
- );
- }
+
+ $object = $bind->hasBinding() ?
+ $this->compiler->newInstance($class, $params, $bind) : $this->newInstance($class, $params) ;
+
// call setter methods
$this->setterMethod($setter, $object);
@@ -326,6 +320,22 @@ class Injector implements InjectorInterface
}
/**
+ * Return new instance
+ *
+ * @param string $class
+ * @param array $params
+ *
+ * @return object
+ */
+ private function newInstance($class, array $params)
+ {
+ return call_user_func_array(
+ [$this->config->getReflect($class), 'newInstance'],
+ $params
+ );
+ }
+
+ /**
* Return bound object or inject info
*
* @param $class
|
refactor: readability, remove else
|
ray-di_Ray.Di
|
train
|
4e56406ab6094b46e965b75848444577d557d946
|
diff --git a/models/classes/LtiLaunchData.php b/models/classes/LtiLaunchData.php
index <HASH>..<HASH> 100644
--- a/models/classes/LtiLaunchData.php
+++ b/models/classes/LtiLaunchData.php
@@ -389,11 +389,20 @@ class LtiLaunchData implements \JsonSerializable
*/
public function getToolConsumerName()
{
- return $this->hasVariable(self::TOOL_CONSUMER_INSTANCE_NAME)
- ? $this->getVariable(self::TOOL_CONSUMER_INSTANCE_NAME)
- : $this->hasVariable(self::TOOL_CONSUMER_INSTANCE_DESCRIPTION)
- ? $this->getVariable(self::TOOL_CONSUMER_INSTANCE_DESCRIPTION)
- : null;
+ $consumerName = null;
+
+ if ($this->getVariable(self::TOOL_CONSUMER_INSTANCE_NAME)) {
+ $consumerName = $this->getVariable(self::TOOL_CONSUMER_INSTANCE_NAME);
+ }
+
+ if (
+ $consumerName === null
+ && $this->hasVariable(self::TOOL_CONSUMER_INSTANCE_DESCRIPTION)
+ ) {
+ $consumerName = $this->getVariable(self::TOOL_CONSUMER_INSTANCE_DESCRIPTION);
+ }
+
+ return $consumerName;
}
/**
|
chore: remove stacked ternaries in `LtiLaunchData` to avoid the error "PHP Deprecated: Unparenthesized.."
|
oat-sa_extension-tao-lti
|
train
|
3f850ce784bd32a0ca40e5a1b7f6c02382b5115a
|
diff --git a/larray-buffer/src/main/java/xerial/larray/buffer/LBufferAPI.java b/larray-buffer/src/main/java/xerial/larray/buffer/LBufferAPI.java
index <HASH>..<HASH> 100644
--- a/larray-buffer/src/main/java/xerial/larray/buffer/LBufferAPI.java
+++ b/larray-buffer/src/main/java/xerial/larray/buffer/LBufferAPI.java
@@ -4,9 +4,12 @@ import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
+import java.nio.BufferOverflowException;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.channels.FileChannel;
+import java.nio.channels.GatheringByteChannel;
+import java.nio.channels.WritableByteChannel;
import static xerial.larray.buffer.UnsafeUtil.unsafe;
@@ -310,6 +313,28 @@ public class LBufferAPI {
}
/**
+ * Writes the buffer contents to the given byte channel.
+ *
+ * @param channel
+ * @throws IOException
+ */
+ public void writeTo(GatheringByteChannel channel) throws IOException {
+ channel.write(toDirectByteBuffers());
+ }
+
+ /**
+ * Writes the buffer contents to the given byte channel.
+ *
+ * @param channel
+ * @throws IOException
+ */
+ public void writeTo(WritableByteChannel channel) throws IOException {
+ for (ByteBuffer buffer : toDirectByteBuffers()) {
+ channel.write(buffer);
+ }
+ }
+
+ /**
* Dump the buffer contents to a file
* @param file
* @throws IOException
@@ -324,22 +349,24 @@ public class LBufferAPI {
}
/**
- * Read the given source byte array, then overwrite the buffer contents
- * @param src
- * @param destOffset
- * @return
+ * Read the given source byte array, then overwrite this buffer's contents
+ *
+ * @param src source byte array
+ * @param destOffset offset in this buffer to read to
+ * @return the number of bytes read
*/
public int readFrom(byte[] src, long destOffset) {
return readFrom(src, 0, destOffset, src.length);
}
/**
- * Read the given source byte arrey, then overwrite the buffer contents
- * @param src
- * @param srcOffset
- * @param destOffset
- * @param length
- * @return
+ * Read the given source byte array, then overwrite this buffer's contents
+ *
+ * @param src source byte array
+ * @param srcOffset offset in source byte array to read from
+ * @param destOffset offset in this buffer to read to
+ * @param length max number of bytes to read
+ * @return the number of bytes read
*/
public int readFrom(byte[] src, int srcOffset, long destOffset, int length) {
int readLen = (int) Math.min(src.length - srcOffset, Math.min(size() - destOffset, length));
@@ -349,6 +376,21 @@ public class LBufferAPI {
return readLen;
}
+ /**
+ * Reads the given source byte buffer into this buffer at the given offset
+ * @param src source byte buffer
+ * @param destOffset offset in this buffer to read to
+ * @return the number of bytes read
+ */
+ public int readFrom(ByteBuffer src, long destOffset) {
+ if (src.remaining() + destOffset >= size())
+ throw new BufferOverflowException();
+ int readLen = src.remaining();
+ ByteBuffer b = toDirectByteBuffer(destOffset, readLen);
+ b.position(0);
+ b.put(src);
+ return readLen;
+ }
/**
* Create an LBuffer from a given file.
|
Add more ByteBuffer and Channel APIs to LBufferAPI
This adds convenience writeTo() methods for GatheringByteChannel and a
less optimized version for WritableByteChannel.
This adds a readFrom() method for reading a ByteBuffer similar to the
existing API for reading from byte arrays.
|
xerial_larray
|
train
|
db108e5be9d0b363b21de8b8952da372123f544e
|
diff --git a/stacker/providers/aws.py b/stacker/providers/aws.py
index <HASH>..<HASH> 100644
--- a/stacker/providers/aws.py
+++ b/stacker/providers/aws.py
@@ -10,7 +10,23 @@ from ..util import retry_with_backoff
logger = logging.getLogger(__name__)
-def retry_cf_throttling(fn, attempts=3, args=None, kwargs=None):
+def retry_on_throttling(fn, attempts=3, args=None, kwargs=None):
+ """Wrap retry_with_backoff to handle AWS Cloudformation Throttling.
+
+ Args:
+ fn (function): The function to call.
+ attempts (int): Maximum # of attempts to retry the function.
+ args (list): List of positional arguments to pass to the function.
+ kwargs (dict): Dict of keyword arguments to pass to the function.
+
+ Returns:
+ passthrough: This returns the result of the function call itself.
+
+ Raises:
+ passthrough: This raises any exceptions the function call raises,
+ except for boto.exception.BotoServerError, provided it doesn't
+ retry more than attempts.
+ """
def _throttling_checker(exc):
if exc.status == 400 and "Throttling" in exc.message:
logger.debug("AWS throttling calls.")
@@ -50,7 +66,7 @@ class Provider(BaseProvider):
def get_stack(self, stack_name, **kwargs):
stack = None
try:
- stack = retry_cf_throttling(self.cloudformation.describe_stacks,
+ stack = retry_on_throttling(self.cloudformation.describe_stacks,
args=[stack_name])[0]
except boto.exception.BotoServerError as e:
if 'does not exist' not in e.message:
@@ -71,7 +87,7 @@ class Provider(BaseProvider):
def destroy_stack(self, stack, **kwargs):
logger.info("Destroying stack: %s" % (stack.stack_name,))
- retry_cf_throttling(self.cloudformation.delete_stack,
+ retry_on_throttling(self.cloudformation.delete_stack,
args=[stack.stack_id])
return True
@@ -79,7 +95,7 @@ class Provider(BaseProvider):
logger.info("Stack %s not found, creating.", fqn)
logger.debug("Using parameters: %s", parameters)
logger.debug("Using tags: %s", tags)
- retry_cf_throttling(
+ retry_on_throttling(
self.cloudformation.create_stack,
args=[fqn],
kwargs=dict(template_url=template_url,
@@ -91,7 +107,7 @@ class Provider(BaseProvider):
def update_stack(self, fqn, template_url, parameters, tags, **kwargs):
try:
logger.info("Attempting to update stack %s.", fqn)
- retry_cf_throttling(
+ retry_on_throttling(
self.cloudformation.update_stack,
args=[fqn],
kwargs=dict(template_url=template_url,
|
Address @mhahn's feedback
- rename retry_cf_throttling to retry_on_throttling
- added a docstring as well
|
cloudtools_stacker
|
train
|
1ea73486ff7ec1e167fc82824f1f424c4d0a88ef
|
diff --git a/guice/hibernate/src/test/java/com/peterphi/std/guice/hibernate/largetable/MyTestDaoImpl.java b/guice/hibernate/src/test/java/com/peterphi/std/guice/hibernate/largetable/MyTestDaoImpl.java
index <HASH>..<HASH> 100644
--- a/guice/hibernate/src/test/java/com/peterphi/std/guice/hibernate/largetable/MyTestDaoImpl.java
+++ b/guice/hibernate/src/test/java/com/peterphi/std/guice/hibernate/largetable/MyTestDaoImpl.java
@@ -8,7 +8,7 @@ import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.hibernate.criterion.Subqueries;
- class MyTestDaoImpl extends HibernateDao<LargeTableSimplePKEntity, Long>
+public class MyTestDaoImpl extends HibernateDao<LargeTableSimplePKEntity, Long>
{
/**
* Run
diff --git a/guice/hibernate/src/test/java/com/peterphi/std/guice/hibernate/webquery/embeddedpktest/EmbeddedPkDaoImpl.java b/guice/hibernate/src/test/java/com/peterphi/std/guice/hibernate/webquery/embeddedpktest/EmbeddedPkDaoImpl.java
index <HASH>..<HASH> 100644
--- a/guice/hibernate/src/test/java/com/peterphi/std/guice/hibernate/webquery/embeddedpktest/EmbeddedPkDaoImpl.java
+++ b/guice/hibernate/src/test/java/com/peterphi/std/guice/hibernate/webquery/embeddedpktest/EmbeddedPkDaoImpl.java
@@ -7,7 +7,7 @@ import org.hibernate.criterion.Restrictions;
import java.util.List;
-class EmbeddedPkDaoImpl extends HibernateDao<EmbeddedPkEntity, SomePrimaryKey>
+public class EmbeddedPkDaoImpl extends HibernateDao<EmbeddedPkEntity, SomePrimaryKey>
{
@SuppressWarnings("deprecation")
public List<EmbeddedPkEntity> findByTimestamp(final long timestamp)
|
Fix visibility issues preventing AOP on test DAOs marked as package-private
|
petergeneric_stdlib
|
train
|
591a67fef87c8d3df702681ce9221379df784f9a
|
diff --git a/repository.go b/repository.go
index <HASH>..<HASH> 100644
--- a/repository.go
+++ b/repository.go
@@ -24,6 +24,24 @@ func OpenRepository(path string) (*Repository, error) {
runtime.LockOSThread()
defer runtime.UnlockOSThread()
+ ret := C.git_repository_open(&repo.ptr, cpath)
+ if ret < 0 {
+ return nil, MakeGitError(ret)
+ }
+
+ runtime.SetFinalizer(repo, (*Repository).Free)
+ return repo, nil
+}
+
+func OpenRepositoryExtended(path string) (*Repository, error) {
+ repo := new(Repository)
+
+ cpath := C.CString(path)
+ defer C.free(unsafe.Pointer(cpath))
+
+ runtime.LockOSThread()
+ defer runtime.UnlockOSThread()
+
ret := C.git_repository_open_ext(&repo.ptr, cpath, 0, nil)
if ret < 0 {
return nil, MakeGitError(ret)
|
Add function to open repository from subpaths
|
libgit2_git2go
|
train
|
cbb724a313e6014fed8976510cd3f8cabbbae4b1
|
diff --git a/DependencyInjection/Compiler/AutoRegisterServicesPass.php b/DependencyInjection/Compiler/AutoRegisterServicesPass.php
index <HASH>..<HASH> 100644
--- a/DependencyInjection/Compiler/AutoRegisterServicesPass.php
+++ b/DependencyInjection/Compiler/AutoRegisterServicesPass.php
@@ -15,6 +15,7 @@ namespace WellCommerce\Bundle\DictionaryBundle\DependencyInjection\Compiler;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use WellCommerce\Bundle\AttributeBundle\DependencyInjection\WellCommerceAttributeExtension;
use WellCommerce\Bundle\CoreBundle\DependencyInjection\Compiler\AbstractAutoRegisterServicesPass;
+use WellCommerce\Bundle\DictionaryBundle\DependencyInjection\WellCommerceDictionaryExtension;
/**
* Class MappingCompilerPass
@@ -25,6 +26,6 @@ class AutoRegisterServicesPass extends AbstractAutoRegisterServicesPass
{
protected function getExtensionConfiguration(ContainerBuilder $container)
{
- return $container->getParameter(WellCommerceAttributeExtension::EXTENSION_NAME);
+ return $container->getParameter(WellCommerceDictionaryExtension::EXTENSION_NAME);
}
}
diff --git a/DependencyInjection/Compiler/MappingCompilerPass.php b/DependencyInjection/Compiler/MappingCompilerPass.php
index <HASH>..<HASH> 100644
--- a/DependencyInjection/Compiler/MappingCompilerPass.php
+++ b/DependencyInjection/Compiler/MappingCompilerPass.php
@@ -16,6 +16,7 @@ use Symfony\Component\DependencyInjection\ContainerBuilder;
use WellCommerce\Bundle\AppBundle\DependencyInjection\WellCommerceAppExtension;
use WellCommerce\Bundle\AttributeBundle\DependencyInjection\WellCommerceAttributeExtension;
use WellCommerce\Bundle\CoreBundle\DependencyInjection\Compiler\AbstractMappingCompilerPass;
+use WellCommerce\Bundle\DictionaryBundle\DependencyInjection\WellCommerceDictionaryExtension;
/**
* Class MappingCompilerPass
@@ -26,6 +27,6 @@ class MappingCompilerPass extends AbstractMappingCompilerPass
{
protected function getExtensionConfiguration(ContainerBuilder $container)
{
- return $container->getParameter(WellCommerceAttributeExtension::EXTENSION_NAME);
+ return $container->getParameter(WellCommerceDictionaryExtension::EXTENSION_NAME);
}
}
|
Modified compiler passes to reflect auto-service changes
(cherry picked from commit <I>fc<I>c<I>a7d5b9fe<I>ef2e5fcf<I>d9a<I>)
|
WellCommerce_CouponBundle
|
train
|
abb3ba87bf356281ddc58681c60c9a0af903a0ea
|
diff --git a/tests/integration/netapi/test_client.py b/tests/integration/netapi/test_client.py
index <HASH>..<HASH> 100644
--- a/tests/integration/netapi/test_client.py
+++ b/tests/integration/netapi/test_client.py
@@ -44,6 +44,19 @@ class NetapiClientTest(TestCase):
ret.pop('jid', None)
self.assertEqual(ret, {'minions': ['minion', 'sub_minion']})
+ def test_jid(self):
+ '''
+ Tests whether a predetermined jid successfully passes through netapi to
+ salt and back.
+ '''
+ low = {'client': 'local_async', 'tgt': '*', 'fun': 'test.ping',
+ 'jid': '123abc'}
+ low.update(self.eauth_creds)
+
+ ret = self.netapi.run(low)
+
+ self.assertEqual(ret, {'jid': '123abc', 'minions': ['minion', 'sub_minion']})
+
def test_wheel(self):
low = {'client': 'wheel', 'fun': 'key.list_all'}
low.update(self.eauth_creds)
|
integration test: known JID through netapi #<I>
|
saltstack_salt
|
train
|
f8a3a3fb9a0df2727108510a183832c05570124c
|
diff --git a/question/editlib.php b/question/editlib.php
index <HASH>..<HASH> 100644
--- a/question/editlib.php
+++ b/question/editlib.php
@@ -1701,12 +1701,6 @@ function question_edit_setup($edittab, $baseurl, $requirecmid = false, $requirec
}
/**
- * Required for legacy reasons. Was originally global then changed to class static
- * as of Moodle 2.0
- */
-$QUESTION_EDITTABCAPS = question_edit_contexts::$caps;
-
-/**
* Make sure user is logged in as required in this context.
*/
function require_login_in_context($contextorid = null){
|
MDL-<I> questions: kill legacy global $QUESTION_EDITTABCAPS
|
moodle_moodle
|
train
|
d103386f55a692e8eb966fd3ab683907ab5d18b4
|
diff --git a/dallinger/experiment.py b/dallinger/experiment.py
index <HASH>..<HASH> 100644
--- a/dallinger/experiment.py
+++ b/dallinger/experiment.py
@@ -98,10 +98,10 @@ class Experiment(object):
@property
def recruiter(self):
"""Recruiter, the Dallinger class that recruits participants.
- Default is HotAirRecruiter in debug mode and PsiTurkRecruiter in other modes.
+ Default is HotAirRecruiter in debug mode and MTurkRecruiter in other modes.
"""
from dallinger.recruiters import HotAirRecruiter
- from dallinger.recruiters import PsiTurkRecruiter
+ from dallinger.recruiters import MTurkRecruiter
try:
debug_mode = config.get('mode') == 'debug'
@@ -111,7 +111,7 @@ class Experiment(object):
if debug_mode:
return HotAirRecruiter
- return PsiTurkRecruiter
+ return MTurkRecruiter.from_current_config()
def setup(self):
"""Create the networks if they don't already exist."""
@@ -398,7 +398,7 @@ class Experiment(object):
"""
import dallinger as dlgr
- # Ensure that psiTurk is in sandbox mode.
+ # Ensure that experiment runs in sandbox mode.
config.extend({
"mode": u"sandbox",
"logfile": u"-",
@@ -424,11 +424,8 @@ class Experiment(object):
run specific settings grouped by section.
"""
import dallinger as dlgr
- from psiturk.psiturk_config import PsiturkConfig
- psiturk_config = PsiturkConfig()
- psiturk_config.load_config()
- # Ensure that psiTurk is not in sandbox mode.
+ # Ensure that experiment is not in sandbox mode.
config.extend({
"mode": u"sandbox",
"logfile": u"-",
|
Use MTurkRecruiter instead of PsiTurkRecruiter
|
Dallinger_Dallinger
|
train
|
ba4b5fd10c51ca56753649abf400993f79e5087c
|
diff --git a/pushy/src/main/java/com/turo/pushy/apns/server/BaseHttp2Server.java b/pushy/src/main/java/com/turo/pushy/apns/server/BaseHttp2Server.java
index <HASH>..<HASH> 100644
--- a/pushy/src/main/java/com/turo/pushy/apns/server/BaseHttp2Server.java
+++ b/pushy/src/main/java/com/turo/pushy/apns/server/BaseHttp2Server.java
@@ -45,7 +45,7 @@ abstract class BaseHttp2Server {
private final ServerBootstrap bootstrap;
private final boolean shouldShutDownEventLoopGroup;
- private ChannelGroup allChannels;
+ private final ChannelGroup allChannels;
private static final Logger log = LoggerFactory.getLogger(BaseHttp2Server.class);
@@ -78,6 +78,8 @@ abstract class BaseHttp2Server {
this.shouldShutDownEventLoopGroup = true;
}
+ this.allChannels = new DefaultChannelGroup(this.bootstrap.config().group().next());
+
this.bootstrap.channel(ServerChannelClassUtil.getServerSocketChannelClass(this.bootstrap.config().group()));
this.bootstrap.childHandler(new ChannelInitializer<SocketChannel>() {
@@ -116,8 +118,6 @@ abstract class BaseHttp2Server {
*/
public Future<Void> start(final int port) {
final ChannelFuture channelFuture = this.bootstrap.bind(port);
-
- this.allChannels = new DefaultChannelGroup(channelFuture.channel().eventLoop(), true);
this.allChannels.add(channelFuture.channel());
return channelFuture;
@@ -137,8 +137,7 @@ abstract class BaseHttp2Server {
*/
@SuppressWarnings({ "rawtypes", "unchecked" })
public Future<Void> shutdown() {
- final Future<Void> channelCloseFuture = (this.allChannels != null) ?
- this.allChannels.close() : new SucceededFuture<Void>(GlobalEventExecutor.INSTANCE, null);
+ final Future<Void> channelCloseFuture = this.allChannels.close();
final Future<Void> disconnectFuture;
diff --git a/pushy/src/test/java/com/turo/pushy/apns/server/MockApnsServerTest.java b/pushy/src/test/java/com/turo/pushy/apns/server/MockApnsServerTest.java
index <HASH>..<HASH> 100644
--- a/pushy/src/test/java/com/turo/pushy/apns/server/MockApnsServerTest.java
+++ b/pushy/src/test/java/com/turo/pushy/apns/server/MockApnsServerTest.java
@@ -132,7 +132,6 @@ public class MockApnsServerTest extends AbstractClientServerTest {
final NioEventLoopGroup eventLoopGroup = new NioEventLoopGroup(1);
try {
-
final MockApnsServer providedGroupServer = new MockApnsServerBuilder()
.setServerCredentials(getClass().getResourceAsStream(SERVER_CERTIFICATES_FILENAME), getClass().getResourceAsStream(SERVER_KEY_FILENAME), null)
.setHandlerFactory(new AcceptAllPushNotificationHandlerFactory())
@@ -142,10 +141,6 @@ public class MockApnsServerTest extends AbstractClientServerTest {
assertTrue(providedGroupServer.start(PORT).await().isSuccess());
assertTrue(providedGroupServer.shutdown().await().isSuccess());
- // This test fails mysteriously under OpenJDK 11 (the port is already in use) if we don't yield here. I
- // have no idea why.
- Thread.yield();
-
assertTrue(providedGroupServer.start(PORT).await().isSuccess());
assertTrue(providedGroupServer.shutdown().await().isSuccess());
} finally {
|
More carefully addressed a poorly-diagnosed race condition exposed in (but not caused by) recent versions of Netty/Java.
|
relayrides_pushy
|
train
|
965fa5d008c6a6d803363d865c3ce9fc1adb5892
|
diff --git a/src/finalisers/es6.js b/src/finalisers/es6.js
index <HASH>..<HASH> 100644
--- a/src/finalisers/es6.js
+++ b/src/finalisers/es6.js
@@ -58,7 +58,7 @@ export default function es6 ( bundle, magicString ) {
const defaultExport = module.exports.lookup( 'default' );
if ( defaultExport ) {
- exportBlock += `export default ${ defaultExport.name };`;
+ exportBlock += `\nexport default ${ defaultExport.name };`;
}
if ( exportBlock ) {
diff --git a/test/form/export-all-from-internal/_config.js b/test/form/export-all-from-internal/_config.js
index <HASH>..<HASH> 100644
--- a/test/form/export-all-from-internal/_config.js
+++ b/test/form/export-all-from-internal/_config.js
@@ -1,5 +1,4 @@
module.exports = {
- // solo: true,
description: 'should be able to export * from the bundle',
options: {
moduleName: 'exposedInternals'
diff --git a/test/form/export-all-from-internal/_expected/amd.js b/test/form/export-all-from-internal/_expected/amd.js
index <HASH>..<HASH> 100644
--- a/test/form/export-all-from-internal/_expected/amd.js
+++ b/test/form/export-all-from-internal/_expected/amd.js
@@ -2,8 +2,10 @@ define(['exports'], function (exports) { 'use strict';
const a = 1;
const b = 2;
+ var internal = 42;
exports.a = a;
exports.b = b;
+ exports['default'] = internal;
});
diff --git a/test/form/export-all-from-internal/_expected/cjs.js b/test/form/export-all-from-internal/_expected/cjs.js
index <HASH>..<HASH> 100644
--- a/test/form/export-all-from-internal/_expected/cjs.js
+++ b/test/form/export-all-from-internal/_expected/cjs.js
@@ -2,6 +2,8 @@
const a = 1;
const b = 2;
+var internal = 42;
exports.a = a;
exports.b = b;
+exports['default'] = internal;
diff --git a/test/form/export-all-from-internal/_expected/es6.js b/test/form/export-all-from-internal/_expected/es6.js
index <HASH>..<HASH> 100644
--- a/test/form/export-all-from-internal/_expected/es6.js
+++ b/test/form/export-all-from-internal/_expected/es6.js
@@ -1,4 +1,6 @@
const a = 1;
const b = 2;
+var internal = 42;
export { a, b };
+export default internal;
diff --git a/test/form/export-all-from-internal/_expected/iife.js b/test/form/export-all-from-internal/_expected/iife.js
index <HASH>..<HASH> 100644
--- a/test/form/export-all-from-internal/_expected/iife.js
+++ b/test/form/export-all-from-internal/_expected/iife.js
@@ -2,8 +2,10 @@
const a = 1;
const b = 2;
+ var internal = 42;
exports.a = a;
exports.b = b;
+ exports['default'] = internal;
})((this.exposedInternals = {}));
diff --git a/test/form/export-all-from-internal/_expected/umd.js b/test/form/export-all-from-internal/_expected/umd.js
index <HASH>..<HASH> 100644
--- a/test/form/export-all-from-internal/_expected/umd.js
+++ b/test/form/export-all-from-internal/_expected/umd.js
@@ -6,8 +6,10 @@
const a = 1;
const b = 2;
+ var internal = 42;
exports.a = a;
exports.b = b;
+ exports['default'] = internal;
}));
diff --git a/test/form/export-all-from-internal/internal.js b/test/form/export-all-from-internal/internal.js
index <HASH>..<HASH> 100644
--- a/test/form/export-all-from-internal/internal.js
+++ b/test/form/export-all-from-internal/internal.js
@@ -1,2 +1,3 @@
export const a = 1;
export const b = 2;
+export default 42;
|
test default exports are re-exported from internal module with export *
|
rollup_rollup
|
train
|
b349bb4785615418026419202053ef33c4976992
|
diff --git a/Slim/Route.php b/Slim/Route.php
index <HASH>..<HASH> 100644
--- a/Slim/Route.php
+++ b/Slim/Route.php
@@ -111,6 +111,7 @@ class Route extends Routable implements RouteInterface, MiddlewareInterface
$this->identifier = 'route' . $identifier;
$this->middlewareRunner = new MiddlewareRunner();
}
+
/**
* Get route invocation strategy
*
@@ -135,10 +136,12 @@ class Route extends Routable implements RouteInterface, MiddlewareInterface
* This method enables you to override the Route's callable
*
* @param callable|string $callable
+ * @return self
*/
- public function setCallable($callable)
+ public function setCallable($callable): self
{
$this->callable = $callable;
+ return $this;
}
/**
@@ -164,9 +167,9 @@ class Route extends Routable implements RouteInterface, MiddlewareInterface
/**
* Get route name
*
- * @return null|string
+ * @return string|null
*/
- public function getName()
+ public function getName(): ?string
{
return $this->name;
}
@@ -195,39 +198,35 @@ class Route extends Routable implements RouteInterface, MiddlewareInterface
}
/**
- * Set a route argument
+ * Retrieve a specific route argument
*
* @param string $name
- * @param string $value
- * @param bool $includeInSavedArguments
- *
- * @return self
+ * @param string|null $default
+ * @return mixed
*/
- public function setArgument(string $name, string $value, bool $includeInSavedArguments = true): RouteInterface
+ public function getArgument(string $name, $default = null)
{
- if ($includeInSavedArguments) {
- $this->savedArguments[$name] = $value;
+ if (array_key_exists($name, $this->arguments)) {
+ return $this->arguments[$name];
}
-
- $this->arguments[$name] = $value;
- return $this;
+ return $default;
}
/**
- * Replace route arguments
+ * Set a route argument
*
- * @param array $arguments
+ * @param string $name
+ * @param string $value
* @param bool $includeInSavedArguments
- *
* @return self
*/
- public function setArguments(array $arguments, bool $includeInSavedArguments = true): RouteInterface
+ public function setArgument(string $name, string $value, bool $includeInSavedArguments = true): RouteInterface
{
if ($includeInSavedArguments) {
- $this->savedArguments = $arguments;
+ $this->savedArguments[$name] = $value;
}
- $this->arguments = $arguments;
+ $this->arguments[$name] = $value;
return $this;
}
@@ -242,19 +241,20 @@ class Route extends Routable implements RouteInterface, MiddlewareInterface
}
/**
- * Retrieve a specific route argument
- *
- * @param string $name
- * @param string|null $default
+ * Replace route arguments
*
- * @return mixed
+ * @param array $arguments
+ * @param bool $includeInSavedArguments
+ * @return self
*/
- public function getArgument(string $name, $default = null)
+ public function setArguments(array $arguments, bool $includeInSavedArguments = true): RouteInterface
{
- if (array_key_exists($name, $this->arguments)) {
- return $this->arguments[$name];
+ if ($includeInSavedArguments) {
+ $this->savedArguments = $arguments;
}
- return $default;
+
+ $this->arguments = $arguments;
+ return $this;
}
/**
@@ -286,8 +286,9 @@ class Route extends Routable implements RouteInterface, MiddlewareInterface
*
* @param ServerRequestInterface $request
* @param array $arguments
+ * @return void
*/
- public function prepare(ServerRequestInterface $request, array $arguments)
+ public function prepare(ServerRequestInterface $request, array $arguments): void
{
// Remove temp arguments
$this->setArguments($this->savedArguments);
@@ -300,8 +301,9 @@ class Route extends Routable implements RouteInterface, MiddlewareInterface
/**
* Finalize the route in preparation for dispatching
+ * @return void
*/
- public function finalize()
+ public function finalize(): void
{
if ($this->finalized) {
return;
@@ -329,7 +331,6 @@ class Route extends Routable implements RouteInterface, MiddlewareInterface
* back to the Application.
*
* @param ServerRequestInterface $request
- *
* @return ResponseInterface
*/
public function run(ServerRequestInterface $request): ResponseInterface
@@ -350,23 +351,18 @@ class Route extends Routable implements RouteInterface, MiddlewareInterface
*
* @param ServerRequestInterface $request The current Request object
* @param RequestHandlerInterface $handler The current RequestHandler object
- * @return \Psr\Http\Message\ResponseInterface
- * @throws \Exception if the route callable throws an exception
+ * @return ResponseInterface
*/
public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
{
- /** @var callable $callable */
$callable = $this->callableResolver->resolve($this->callable);
- /** @var InvocationStrategyInterface|RequestHandler $handler */
- $routeHandler = $this->invocationStrategy;
+ $strategy = $this->invocationStrategy;
if (is_array($callable) && $callable[0] instanceof RequestHandlerInterface) {
- // callables that implement RequestHandlerInterface use the RequestHandler strategy
- $routeHandler = new RequestHandler();
+ $strategy = new RequestHandler();
}
- // invoke route callable via invocation strategy handler
$response = $this->responseFactory->createResponse();
- return $routeHandler($callable, $request, $response, $this->arguments);
+ return $strategy($callable, $request, $response, $this->arguments);
}
}
|
add missing type hints to Route methods and rename variable assignments in process()
|
slimphp_Slim
|
train
|
6237a4e3ab39c681542cdf58a0623148befed331
|
diff --git a/dropwizard-jersey/src/main/java/io/dropwizard/jersey/errors/IllegalStateExceptionMapper.java b/dropwizard-jersey/src/main/java/io/dropwizard/jersey/errors/IllegalStateExceptionMapper.java
index <HASH>..<HASH> 100644
--- a/dropwizard-jersey/src/main/java/io/dropwizard/jersey/errors/IllegalStateExceptionMapper.java
+++ b/dropwizard-jersey/src/main/java/io/dropwizard/jersey/errors/IllegalStateExceptionMapper.java
@@ -1,7 +1,5 @@
package io.dropwizard.jersey.errors;
-import static javax.ws.rs.core.MediaType.APPLICATION_JSON_TYPE;
-
import org.glassfish.jersey.server.internal.LocalizationMessages;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -11,6 +9,8 @@ import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Response;
import javax.ws.rs.ext.Provider;
+import static javax.ws.rs.core.MediaType.APPLICATION_JSON_TYPE;
+
/**
* {@link javax.ws.rs.ext.ExceptionMapper ExceptionMapper} for {@link IllegalStateException}.
*/
@@ -30,7 +30,7 @@ public class IllegalStateExceptionMapper extends LoggingExceptionMapper<IllegalS
*/
// Logs exception with additional information for developers.
LOGGER.debug("If the HTTP method is POST and using @FormParam in a resource method"
- + ", Content-Type should be application/x-www-form-urlencoded.", exception);
+ + ", Content-Type should be application/x-www-form-urlencoded.", exception);
// Returns the same response as if NotSupportedException was thrown.
return createResponse(new NotSupportedException());
}
@@ -40,8 +40,11 @@ public class IllegalStateExceptionMapper extends LoggingExceptionMapper<IllegalS
}
private Response createResponse(final WebApplicationException exception) {
- final ErrorMessage errorMessage =
- new ErrorMessage(exception.getResponse().getStatus(), exception.getLocalizedMessage());
- return Response.status(errorMessage.getCode()).type(APPLICATION_JSON_TYPE).entity(errorMessage).build();
+ final ErrorMessage errorMessage = new ErrorMessage(exception.getResponse().getStatus(),
+ exception.getLocalizedMessage());
+ return Response.status(errorMessage.getCode())
+ .type(APPLICATION_JSON_TYPE)
+ .entity(errorMessage)
+ .build();
}
}
diff --git a/dropwizard-jersey/src/test/java/io/dropwizard/jersey/errors/IllegalStateExceptionMapperTest.java b/dropwizard-jersey/src/test/java/io/dropwizard/jersey/errors/IllegalStateExceptionMapperTest.java
index <HASH>..<HASH> 100644
--- a/dropwizard-jersey/src/test/java/io/dropwizard/jersey/errors/IllegalStateExceptionMapperTest.java
+++ b/dropwizard-jersey/src/test/java/io/dropwizard/jersey/errors/IllegalStateExceptionMapperTest.java
@@ -1,15 +1,15 @@
package io.dropwizard.jersey.errors;
-import static javax.ws.rs.core.Response.Status.UNSUPPORTED_MEDIA_TYPE;
-import static javax.ws.rs.core.Response.Status.INTERNAL_SERVER_ERROR;
-import static org.assertj.core.api.Assertions.assertThat;
-
import org.glassfish.jersey.server.internal.LocalizationMessages;
import org.junit.Test;
import javax.ws.rs.NotSupportedException;
import javax.ws.rs.core.Response;
+import static javax.ws.rs.core.Response.Status.INTERNAL_SERVER_ERROR;
+import static javax.ws.rs.core.Response.Status.UNSUPPORTED_MEDIA_TYPE;
+import static org.assertj.core.api.Assertions.assertThat;
+
public class IllegalStateExceptionMapperTest {
private final IllegalStateExceptionMapper mapper = new IllegalStateExceptionMapper();
@@ -17,17 +17,18 @@ public class IllegalStateExceptionMapperTest {
@Test
public void delegatesToParentClass() {
@SuppressWarnings("serial")
- final Response reponse = mapper.toResponse(new IllegalStateException(getClass().getName()) {});
+ final Response reponse = mapper.toResponse(new IllegalStateException(getClass().getName()) {
+ });
assertThat(reponse.getStatusInfo()).isEqualTo(INTERNAL_SERVER_ERROR);
}
@Test
public void handlesFormParamContentTypeError() {
- final Response reponse =
- mapper.toResponse(new IllegalStateException(LocalizationMessages.FORM_PARAM_CONTENT_TYPE_ERROR()));
+ final Response reponse = mapper
+ .toResponse(new IllegalStateException(LocalizationMessages.FORM_PARAM_CONTENT_TYPE_ERROR()));
assertThat(reponse.getStatusInfo()).isEqualTo(UNSUPPORTED_MEDIA_TYPE);
assertThat(reponse.getEntity()).isInstanceOf(ErrorMessage.class);
assertThat(((ErrorMessage) reponse.getEntity()).getMessage())
- .isEqualTo(new NotSupportedException().getLocalizedMessage());
+ .isEqualTo(new NotSupportedException().getLocalizedMessage());
}
}
|
Fix code style errors pointed out by Checkstyle
See #<I>
|
dropwizard_dropwizard
|
train
|
d8f53e2e76dfc688bb75f8662ad18ffccd8e1f73
|
diff --git a/resumable.js b/resumable.js
index <HASH>..<HASH> 100644
--- a/resumable.js
+++ b/resumable.js
@@ -220,7 +220,6 @@ var Resumable = function(opts){
$.test = function(){
// Set up request and listen for event
$.xhr = new XMLHttpRequest();
- $.xhr.timeout = 5000; // set a fairly low threshold before server must respond, since we'll just be retrying
var testHandler = function(e){
$.tested = true;
@@ -261,7 +260,6 @@ var Resumable = function(opts){
// Set up request and listen for event
$.xhr = new XMLHttpRequest();
- $.xhr.timeout = 5000; // set a fairly low threshold before server must respond, since we'll just be retrying
// Progress
$.xhr.upload.addEventListener("progress", function(e){
@@ -273,6 +271,7 @@ var Resumable = function(opts){
}, false);
$.loaded = 0;
$.callback('progress');
+
// Done (either done, failed or retry)
var doneHandler = function(e){
var status = $.status();
@@ -303,6 +302,7 @@ var Resumable = function(opts){
var func = ($.fileObj.file.mozSlice ? 'mozSlice' : 'webkitSlice');
formData.append($.resumableObj.opts.fileParameterName, $.fileObj.file[func]($.startByte,$.endByte));
$.xhr.open("POST", $.resumableObj.opts.target);
+ //$.xhr.open("POST", '/sandbox');
$.xhr.send(formData);
}
$.abort = function(){
@@ -480,7 +480,7 @@ var Resumable = function(opts){
totalDone += file.progress()*file.size;
totalSize += file.size;
});
- return(totalDone/totalSize);
+ return(totalSize>0 ? totalDone/totalSize : 0);
};
$.removeFile = function(file){
var files = [];
|
Firefox <I> is set to change the behaviour for . Have removed any timeout for when the server must respond.
|
23_resumable.js
|
train
|
e5e6e8aeae9e3cdbfb41a182f5b9c7996968daae
|
diff --git a/test/integration/test_mkp.py b/test/integration/test_mkp.py
index <HASH>..<HASH> 100644
--- a/test/integration/test_mkp.py
+++ b/test/integration/test_mkp.py
@@ -177,5 +177,5 @@ dist({
assert package.info['name'] == 'foo'
assert package.info['files']['agents'] == ['special/agent_test']
assert package.info['files']['checks'] == ['foo']
- assert package.info['version'] == '42'
+ assert package.info['version'] == '43'
assert package.info['version.packaged'] == 'python-mkp'
|
Break build to test github actions
|
tom-mi_python-mkp
|
train
|
272b67c865a6a62a564386f7f7de74462471ffd2
|
diff --git a/lib/replicant.js b/lib/replicant.js
index <HASH>..<HASH> 100644
--- a/lib/replicant.js
+++ b/lib/replicant.js
@@ -55,11 +55,10 @@ function Replicant(name, bundle, opts, nodecg) {
/* jshint -W093 */
function value(newVal) {
- if (typeof newVal === 'undefined') {
- return replicator.replicants[bundle][name].value;
- } else {
- return replicator.replicants[bundle][name].value = newVal;
+ if (arguments.length >= 1) {
+ replicator.replicants[bundle][name].value = newVal;
}
+ return replicator.replicants[bundle][name].value;
}
/* jshint +W093 */
|
[replicants] make server-side value getter/setter safer
|
nodecg_nodecg
|
train
|
942e3049f7810face7e17bb73309bc6cc2fae4a6
|
diff --git a/tests/dummy/app/instance-initializers/dummy.js b/tests/dummy/app/instance-initializers/dummy.js
index <HASH>..<HASH> 100644
--- a/tests/dummy/app/instance-initializers/dummy.js
+++ b/tests/dummy/app/instance-initializers/dummy.js
@@ -19,7 +19,7 @@ export default {
store.set('_applicationName', 'dummy');
let main = store.get('db.main');
- throttle(main);
+ // throttle(main);
window.store = store;
window.db = main;
|
disable throttle for dummy
--HG--
branch : feature/attachments
|
ampatspell_ember-cli-sofa
|
train
|
660163b31beae4c550db68022c568b41df75d8e9
|
diff --git a/src/Auth0.php b/src/Auth0.php
index <HASH>..<HASH> 100644
--- a/src/Auth0.php
+++ b/src/Auth0.php
@@ -535,6 +535,10 @@ class Auth0
}
if (isset($response['id_token'])) {
+ if (! $this->transientHandler->isset(self::TRANSIENT_NONCE_KEY)) {
+ throw new InvalidTokenException('Nonce value not found in application store');
+ }
+
$this->setIdToken($response['id_token']);
}
@@ -577,7 +581,7 @@ class Auth0
$this->setAccessToken($response['access_token']);
if (isset($response['id_token'])) {
- $this->setIdToken($response['id_token'], [self::TRANSIENT_NONCE_KEY => false]);
+ $this->setIdToken($response['id_token']);
}
}
@@ -618,17 +622,16 @@ class Auth0
/**
* Sets, validates, and persists the ID token.
*
- * @param string $idToken - ID token returned from the code exchange.
- * @param string $verifierOptions - ID token verifier options.
+ * @param string $idToken - ID token returned from the code exchange.
*
* @return \Auth0\SDK\Auth0
*
* @throws CoreException
* @throws InvalidTokenException
*/
- public function setIdToken($idToken, array $verifierOptions = [])
+ public function setIdToken($idToken)
{
- $this->idTokenDecoded = $this->decodeIdToken($idToken, $verifierOptions);
+ $this->idTokenDecoded = $this->decodeIdToken($idToken);
if (in_array('id_token', $this->persistantMap)) {
$this->store->set('id_token', $idToken);
@@ -666,10 +669,6 @@ class Auth0
self::TRANSIENT_NONCE_KEY => $this->transientHandler->getOnce(self::TRANSIENT_NONCE_KEY)
];
- if (false !== $verifierOptions[self::TRANSIENT_NONCE_KEY] && empty( $verifierOptions[self::TRANSIENT_NONCE_KEY] )) {
- throw new InvalidTokenException('Nonce value not found in application store');
- }
-
$idTokenVerifier = new IdTokenVerifier($idTokenIss, $this->clientId, $sigVerifier);
return $idTokenVerifier->verify($idToken, $verifierOptions);
}
diff --git a/tests/Auth0Test.php b/tests/Auth0Test.php
index <HASH>..<HASH> 100644
--- a/tests/Auth0Test.php
+++ b/tests/Auth0Test.php
@@ -548,27 +548,6 @@ class Auth0Test extends TestCase
/**
* @throws CoreException
*/
- public function testThatEmptyApplicationNonceFailsIdTokenValidation()
- {
- $custom_config = self::$baseConfig + ['id_token_alg' => 'HS256'];
- $auth0 = new Auth0( $custom_config );
- $id_token = self::getIdToken();
-
- $this->assertArrayNotHasKey('auth0__nonce', $_SESSION);
-
- $e_message = 'No exception caught';
- try {
- $auth0->setIdToken( $id_token );
- } catch (InvalidTokenException $e) {
- $e_message = $e->getMessage();
- }
-
- $this->assertStringStartsWith('Nonce value not found in application store', $e_message);
- }
-
- /**
- * @throws CoreException
- */
public function testThatIdTokenNonceIsCheckedWhenSet()
{
$custom_config = self::$baseConfig + ['id_token_alg' => 'HS256'];
|
Move nonce failure exception into Auth0->exchange()
|
auth0_auth0-PHP
|
train
|
629d270ed39beaba16d91e9457704344254d9e34
|
diff --git a/addons/cb.git/client.js b/addons/cb.git/client.js
index <HASH>..<HASH> 100644
--- a/addons/cb.git/client.js
+++ b/addons/cb.git/client.js
@@ -15,7 +15,7 @@ define(["views/dialog"], function(GitDialog) {
return rpc.execute("git/status")
.then(function() {
updateMenu(true);
- return updateBranchesMenu();
+ return updateBranchesMenu(false);
}, function(err) {
updateMenu(false);
})
@@ -27,7 +27,7 @@ define(["views/dialog"], function(GitDialog) {
'type': "menu",
'offline': false
});
- var updateBranchesMenu = function() {
+ var updateBranchesMenu = function(doUpdateStatus) {
return rpc.execute("git/branches")
.then(function(branches) {
branchesMenu.menu.reset(_.map(branches, function(branch) {
@@ -42,10 +42,14 @@ define(["views/dialog"], function(GitDialog) {
})
}, {
title: "Checkout '"+ref+"'"
- }).then(updateBranchesMenu);
+ })
+ .then(updateBranchesMenu);
}
}
}));
+ }, function(err) {
+ if (doUpdateStatus !== false) updateStatus();
+ return Q.reject(err);
});
};
|
Update status when refresh of branches list is incorrect
|
CodeboxIDE_codebox
|
train
|
a4be39956fde41793f4a756e7c1e7360e3b2f145
|
diff --git a/lib/sky-pages-route-generator.js b/lib/sky-pages-route-generator.js
index <HASH>..<HASH> 100644
--- a/lib/sky-pages-route-generator.js
+++ b/lib/sky-pages-route-generator.js
@@ -24,7 +24,7 @@ function generateDefinition(skyPagesConfig, file, name, params) {
});
const definition =
-`// BEGIN AUTO GENERATED ROUTE COMPONENT: ${name}
+`// AUTO GENERATED FROM: ${file}
@Component({
${templateProp}
})
@@ -45,15 +45,12 @@ ${paramsConstructors}
public ngOnDestroy() {
this.sub.unsubscribe();
}
-}
-// END AUTO GENERATED ROUTE COMPONENT: ${name}
-`;
+}`;
return definition;
}
-function parseFileIntoEntity(skyPagesConfig, file) {
+function parseFileIntoEntity(skyPagesConfig, file, index) {
- let componentName = '';
let routePath = [];
let routeParams = [];
@@ -74,13 +71,9 @@ function parseFileIntoEntity(skyPagesConfig, file) {
} else {
routePath.push(param);
}
-
- // Creates a friendly-looking component name
- const componentNamePart = param.replace(/\W+/g, '').toLowerCase();
- componentName += componentNamePart[0].toUpperCase() + componentNamePart.substring(1);
});
- componentName = `SPR_${componentName}_IndexComponent`;
+ const componentName = `SPR_${index}_IndexComponent`;
const componentDefinition = generateDefinition(
skyPagesConfig,
file,
@@ -97,9 +90,10 @@ function parseFileIntoEntity(skyPagesConfig, file) {
}
function generateRoutes(skyPagesConfig) {
+ let counter = 0;
let entities = glob
.sync(path.join(skyPagesConfig.srcPath, skyPagesConfig.routesPattern))
- .map(file => parseFileIntoEntity(skyPagesConfig, file));
+ .map(file => parseFileIntoEntity(skyPagesConfig, file, counter++));
if (skyPagesConfig.handle404) {
entities.push({
diff --git a/test/sky-pages-route-generator.spec.js b/test/sky-pages-route-generator.spec.js
index <HASH>..<HASH> 100644
--- a/test/sky-pages-route-generator.spec.js
+++ b/test/sky-pages-route-generator.spec.js
@@ -20,7 +20,7 @@ describe('SKY Pages route generator', () => {
const routes = generator.getRoutes({
srcPath: ''
});
- expect(routes.names).toContain('SPR_CustomNested_IndexComponent');
+ expect(routes.names).toContain('SPR_0_IndexComponent');
});
it('should support route parameters', () => {
@@ -35,7 +35,7 @@ describe('SKY Pages route generator', () => {
expect(routes.declarations).toContain("path: ':custom'");
expect(routes.definitions).toContain("this.custom = params['custom'];");
expect(routes.definitions).toContain(
- 'class SPR_Custom_IndexComponent implements OnInit, OnDestroy {'
+ 'class SPR_0_IndexComponent implements OnInit, OnDestroy {'
);
});
|
Incorporated additional feedback to increment component names
|
blackbaud_skyux-builder
|
train
|
944a2d04b4437aae3a3747df073c858f57906245
|
diff --git a/src/main/java/io/vlingo/http/resource/Resource.java b/src/main/java/io/vlingo/http/resource/Resource.java
index <HASH>..<HASH> 100644
--- a/src/main/java/io/vlingo/http/resource/Resource.java
+++ b/src/main/java/io/vlingo/http/resource/Resource.java
@@ -13,7 +13,6 @@ import java.util.Collections;
import java.util.List;
import java.util.concurrent.atomic.AtomicLong;
-import io.vlingo.actors.Actor;
import io.vlingo.actors.Definition;
import io.vlingo.actors.Stage;
import io.vlingo.common.compiler.DynaClassLoader;
|
Pass World as argument to ResourceHandler if compatible constructor.
|
vlingo_vlingo-http
|
train
|
e36e1eb2889eae3189c7d3466c25264e7d15e0b4
|
diff --git a/Lib/extractor/formats/ttx.py b/Lib/extractor/formats/ttx.py
index <HASH>..<HASH> 100644
--- a/Lib/extractor/formats/ttx.py
+++ b/Lib/extractor/formats/ttx.py
@@ -10,7 +10,7 @@ def isTTX(pathOrFile):
font = TTFont()
font.importXML(pathOrFile)
del font
- except TTLibError:
+ except:
return False
return True
|
Only listening for TTLibError will ignore lots of other errors, especially ExpatError. So, blindly try/except.
|
robotools_extractor
|
train
|
ed69a722f73572643deb4209b038accf82f4b18f
|
diff --git a/cmd/peco/peco.go b/cmd/peco/peco.go
index <HASH>..<HASH> 100644
--- a/cmd/peco/peco.go
+++ b/cmd/peco/peco.go
@@ -17,7 +17,7 @@ Usage: percol [options] [FILE]
Options:
-h, --help show this help message and exit
- --rcfile=RCFILE path to the settings file
+ --rcfile=RCFILE path to the settings file
--query=QUERY pre-input query
`
os.Stderr.Write([]byte(v))
|
s/\t/ /
|
peco_peco
|
train
|
0f2a421359af90bcb4936cf1b90efc2ccef8a464
|
diff --git a/core/src/main/java/com/orientechnologies/orient/core/db/record/ORecordLazySet.java b/core/src/main/java/com/orientechnologies/orient/core/db/record/ORecordLazySet.java
index <HASH>..<HASH> 100755
--- a/core/src/main/java/com/orientechnologies/orient/core/db/record/ORecordLazySet.java
+++ b/core/src/main/java/com/orientechnologies/orient/core/db/record/ORecordLazySet.java
@@ -130,6 +130,11 @@ public class ORecordLazySet extends ORecordTrackedSet implements Set<OIdentifiab
if (e instanceof ORecord && e.getIdentity().isNew()) {
ORecordInternal.addIdentityChangeListener((ORecord) e, this);
map.put(e, e);
+ } else if (!e.getIdentity().isPersistent()){
+ //record id is not fixed yet, so we need to be able to watch for id changes, so get the record for this id to be able to do this.
+ ORecord record = e.getRecord();
+ ORecordInternal.addIdentityChangeListener(record, this);
+ map.put(e, record);
} else
map.put(e, ENTRY_REMOVAL);
setDirty();
|
Fix for <I>, fix for records in lazy sets with ids that are not persisted
cordLazySet.java
|
orientechnologies_orientdb
|
train
|
cf982c85557c50b43d7bfa46d0ca59d1af298be0
|
diff --git a/resource_openstack_networking_subnet_v2.go b/resource_openstack_networking_subnet_v2.go
index <HASH>..<HASH> 100644
--- a/resource_openstack_networking_subnet_v2.go
+++ b/resource_openstack_networking_subnet_v2.go
@@ -245,9 +245,9 @@ func resourceNetworkingSubnetV2Update(d *schema.ResourceData, meta interface{})
}
if d.HasChange("no_gateway") {
- noGateway := d.Get("no_gateway").(bool)
- if noGateway {
- updateOpts.GatewayIP = nil
+ if d.Get("no_gateway").(bool) {
+ gatewayIP := ""
+ updateOpts.GatewayIP = &gatewayIP
}
}
|
provider/openstack: gophercloud migration: Only set 'gateway_ip' to "" if 'no_gateway' == true.
|
terraform-providers_terraform-provider-openstack
|
train
|
fd4366699f506b8b8efb347ac418f856c86d24a7
|
diff --git a/index.d.ts b/index.d.ts
index <HASH>..<HASH> 100644
--- a/index.d.ts
+++ b/index.d.ts
@@ -1191,7 +1191,7 @@ declare namespace Eris {
addSelfPremiumSubscription(token: string, plan: string): Promise<void>;
deleteSelfPremiumSubscription(): Promise<void>;
getRESTChannel(channelID: string): Promise<AnyChannel>;
- getRESTGuild(guildID: string): Promise<Guild>;
+ getRESTGuild(guildID: string, withCounts?: boolean): Promise<Guild>;
getRESTGuilds(limit?: number, before?: string, after?: string): Promise<Guild[]>;
getRESTGuildChannels(guildID: string): Promise<AnyGuildChannel[]>;
getRESTGuildEmojis(guildID: string): Promise<Emoji[]>;
@@ -1380,6 +1380,8 @@ declare namespace Eris {
rulesChannelID: string;
widgetEnabled?: boolean | null;
widgetChannelID?: string | null;
+ approximateMemberCount?: number;
+ approximatePresenceCount?: number;
constructor(data: BaseData, client: Client);
fetchAllMembers(timeout?: number): Promise<number>;
dynamicIconURL(format?: string, size?: number): string;
diff --git a/lib/Client.js b/lib/Client.js
index <HASH>..<HASH> 100644
--- a/lib/Client.js
+++ b/lib/Client.js
@@ -1948,13 +1948,16 @@ class Client extends EventEmitter {
/**
* Get a guild's data via the REST API. REST mode is required to use this endpoint.
* @arg {String} guildID The ID of the guild
+ * @arg {Boolean} [withCounts=false] Whether the guild object will have approximateMemberCount and approximatePresenceCount
* @returns {Promise<Guild>}
*/
- getRESTGuild(guildID) {
+ getRESTGuild(guildID, withCounts = false) {
if(!this.options.restMode) {
return Promise.reject(new Error("Eris REST mode is not enabled"));
}
- return this.requestHandler.request("GET", Endpoints.GUILD(guildID), true).then((guild) => new Guild(guild, this));
+ return this.requestHandler.request("GET", Endpoints.GUILD(guildID), true, {
+ with_counts: withCounts
+ }).then((guild) => new Guild(guild, this));
}
/**
diff --git a/lib/structures/Guild.js b/lib/structures/Guild.js
index <HASH>..<HASH> 100644
--- a/lib/structures/Guild.js
+++ b/lib/structures/Guild.js
@@ -51,6 +51,8 @@ const VoiceState = require("./VoiceState");
* @prop {String?} rulesChannelID The channel where "PUBLIC" guilds display rules and/or guidelines
* @prop {Boolean?} widgetEnabled Whether the guild widget is enabled. REST only.
* @prop {Number?} widgetChannelID The channel id that the widget will generate an invite to. REST only.
+* @prop {Number?} approximateMemberCount The approximate number of members in the guild (REST only)
+* @prop {Number?} approximatePresenceCount The approximate number of presences in the guild (REST only)
*/
class Guild extends Base {
constructor(data, client) {
@@ -72,6 +74,13 @@ class Guild extends Base {
this.widgetChannelID = data.widget_channel_id;
}
+ if(data.approximate_member_count !== undefined) {
+ this.approximateMemberCount = data.approximate_member_count;
+ }
+ if(data.approximate_presence_count !== undefined) {
+ this.approximatePresenceCount = data.approximate_presence_count;
+ }
+
if(data.roles) {
for(const role of data.roles) {
this.roles.add(role, this);
|
Support getting Guild with counts (#<I>)
|
abalabahaha_eris
|
train
|
0007a580b2c6155c49051d6ffc1fe3a59f45cfb4
|
diff --git a/server/handlers/websocket_handler_test.go b/server/handlers/websocket_handler_test.go
index <HASH>..<HASH> 100644
--- a/server/handlers/websocket_handler_test.go
+++ b/server/handlers/websocket_handler_test.go
@@ -1,7 +1,6 @@
package handlers_test
import (
- "io"
"net/http"
"net/http/httptest"
"time"
@@ -138,7 +137,7 @@ var _ = Describe("WebsocketHandler", func() {
Expect(err).NotTo(HaveOccurred())
close(messagesChan)
_, _, err = ws.ReadMessage()
- Expect(err).To(Equal(io.EOF))
+ Expect(err.Error()).To(ContainSubstring("websocket: close 1000"))
})
Context("when the KeepAlive expires", func() {
|
Gorilla Websocket updated its close message format for normal closures. The tests had to be changed accordingly
|
cloudfoundry-attic_loggregatorlib
|
train
|
223e81e0644fd29d3b4a725b705960f085809c53
|
diff --git a/hearthstone/hslog/packets.py b/hearthstone/hslog/packets.py
index <HASH>..<HASH> 100644
--- a/hearthstone/hslog/packets.py
+++ b/hearthstone/hslog/packets.py
@@ -108,6 +108,22 @@ class ChosenEntities(Packet):
self.choices = []
+class Options(Packet):
+ def __init__(self, id):
+ self.entity = None
+ self.id = id
+ self.options = []
+
+
+class Option(Packet):
+ def __init__(self, entity, id, type, optype):
+ self.entity = entity
+ self.id = id
+ self.type = type
+ self.optype = optype
+ self.options = []
+
+
class SendOption(Packet):
def __init__(self, option, suboption, target, position):
self.entity = None
diff --git a/hearthstone/hslog/parser.py b/hearthstone/hslog/parser.py
index <HASH>..<HASH> 100644
--- a/hearthstone/hslog/parser.py
+++ b/hearthstone/hslog/parser.py
@@ -43,6 +43,9 @@ ENTITIES_CHOSEN_RE = re.compile(r"id=(\d+) Player=%s EntitiesCount=(\d+)$" % _E)
ENTITIES_CHOSEN_ENTITIES_RE = re.compile(r"Entities\[(\d+)\]=%s$" % _E)
# Options
+OPTIONS_ENTITY_RE = re.compile(r"id=(\d+)$")
+OPTIONS_OPTION_RE = re.compile(r"option (\d+) type=(\w+) mainEntity=%s?$" % _E)
+OPTIONS_SUBOPTION_RE = re.compile(r"(subOption|target) (\d+) entity=%s?$" % _E)
SEND_OPTION_RE = re.compile(r"selectedOption=(\d+) selectedSubOption=(-1|\d+) selectedTarget=(\d+) selectedPosition=(\d+)")
@@ -256,9 +259,43 @@ class OptionsHandler:
def add_data(self, ts, callback, msg):
if callback == self.parse_method("SendOption"):
self.handle_send_option(ts, msg)
+ elif callback == self.parse_method("DebugPrintOptions"):
+ self.handle_options(ts, msg)
else:
super().add_data(ts, callback, msg)
+ def handle_options(self, ts, msg):
+ data = msg.strip()
+ if data.startswith("id="):
+ sre = OPTIONS_ENTITY_RE.match(data)
+ id, = sre.groups()
+ id = int(id)
+ self._options_packet = packets.Options(id)
+ self._options_packet.ts = ts
+ self.current_node.packets.append(self._options_packet)
+ elif data.startswith("option "):
+ sre = OPTIONS_OPTION_RE.match(data)
+ id, type, entity = sre.groups()
+ id = int(id)
+ type = parse_enum(enums.OptionType, type)
+ entity = self.parse_entity(entity) if entity else None
+ self._option_packet = packets.Option(entity, id, type, "option")
+ self._option_packet.ts = ts
+ self._options_packet.options.append(self._option_packet)
+ self._suboption_packet = None
+ elif data.startswith(("subOption ", "target ")):
+ sre = OPTIONS_SUBOPTION_RE.match(data)
+ type, id, entity = sre.groups()
+ id = int(id)
+ entity = self.parse_entity(entity)
+ packet = packets.Option(entity, id, None, type)
+ if type == "subOption":
+ self._suboption_packet = packet
+ node = self._option_packet
+ elif type == "target":
+ node = self._suboption_packet or self._option_packet
+ node.options.append(packet)
+
def handle_send_option(self, ts, msg):
data = msg.strip()
if data.startswith("selectedOption="):
|
hslog: Add support for options and suboptions
|
HearthSim_python-hearthstone
|
train
|
a7c9c327fba04a9b5c425a2f30af248ab97f6de4
|
diff --git a/salesforce/tests/test_integration.py b/salesforce/tests/test_integration.py
index <HASH>..<HASH> 100644
--- a/salesforce/tests/test_integration.py
+++ b/salesforce/tests/test_integration.py
@@ -342,3 +342,16 @@ class BasicSOQLTest(TestCase):
self.skipTest('Django 1.3 has no bulk operations.')
objects = [Contact(LastName='sf_test a'), Contact(LastName='sf_test b')]
self.assertRaises(AssertionError, Contact.objects.bulk_create, objects)
+
+ def test_escape_single_quote(self):
+ """
+ Test that single quotes in strings used in filtering a QuerySet
+ are escaped properly.
+ """
+ account_name = '''Dr. Evil's Giant "Laser", LLC'''
+ account = Account(Name=account_name)
+ account.save()
+ try:
+ self.assertTrue(Account.objects.filter(Name=account_name).exists())
+ finally:
+ account.delete()
|
Add test for escaping single quotes.
|
django-salesforce_django-salesforce
|
train
|
6d311bd826f1955b8a76ea107161b2165c0b69e0
|
diff --git a/src/device.js b/src/device.js
index <HASH>..<HASH> 100644
--- a/src/device.js
+++ b/src/device.js
@@ -29,7 +29,7 @@ class Device {
this.model = model;
this.data = Object.assign({}, data);
this.data.model = model;
- if (!alias == null) this.data.alias = alias;
+ if (alias != null) this.data.alias = alias;
let SpecificDevice = require(`./devices/${model}`);
this._deviceInfo = new SpecificDevice(this.data);
|
fix: not setting alias passed in device constructor
fixes #<I>
|
plasticrake_tplink-smarthome-simulator
|
train
|
f4bb0a62cba9d0035eb636b2d33eb98d0fe616af
|
diff --git a/lib/ApiCLI.php b/lib/ApiCLI.php
index <HASH>..<HASH> 100644
--- a/lib/ApiCLI.php
+++ b/lib/ApiCLI.php
@@ -377,14 +377,15 @@ class ApiCLI extends AbstractView
}
/** Load config if necessary and look up corresponding setting */
function getConfig($path, $default_value = undefined){
+
/**
* For given path such as 'dsn' or 'logger/log_dir' returns
- * corresponding config value. Throws ExceptionNotConfigured if not set.
+ * corresponding config value. Throws Exception_NotConfigured if not set.
*
* To find out if config is set, do this:
*
* $var_is_set=true;
- * try { $api->getConfig($path); } catch ExceptionNotConfigured($e) { $var_is_set=false; };
+ * try { $api->getConfig($path); } catch Exception_NotConfigured($e) { $var_is_set=false; };
*/
if(is_null($this->config)){
$this->readConfig('config-default.php');
|
fixed name of Exception class in documentation
|
atk4_atk4
|
train
|
b53d6143382d732d7cda7dd27a5a3f4fadaaed59
|
diff --git a/ruby_event_store/spec/client_spec.rb b/ruby_event_store/spec/client_spec.rb
index <HASH>..<HASH> 100644
--- a/ruby_event_store/spec/client_spec.rb
+++ b/ruby_event_store/spec/client_spec.rb
@@ -435,5 +435,68 @@ module RubyEventStore
expect{ client.read_all_streams_forward(count: -1) }.to raise_error(InvalidPageSize)
expect{ client.read_all_streams_backward(count: -1) }.to raise_error(InvalidPageSize)
end
+
+ specify 'create successfully event' do
+ client = RubyEventStore::Client.new(repository: InMemoryRepository.new)
+ event = OrderCreated.new(event_id: 'b2d506fd-409d-4ec7-b02f-c6d2295c7edd')
+ client.append_to_stream(event, stream_name: 'stream_name')
+ saved_events = client.read_stream_events_forward('stream_name')
+ expect(saved_events[0]).to eq(event)
+ end
+
+ specify 'generate guid and create successfully event' do
+ client = RubyEventStore::Client.new(repository: InMemoryRepository.new)
+ event = OrderCreated.new
+ client.append_to_stream(event, stream_name: 'stream_name')
+ saved_events = client.read_stream_events_forward('stream_name')
+ expect(saved_events[0]).to eq(event)
+ end
+
+ specify 'raise exception if expected version incorrect' do
+ client = RubyEventStore::Client.new(repository: InMemoryRepository.new)
+ event = OrderCreated.new
+ client.append_to_stream(event, stream_name: 'stream_name')
+ expect { client.publish_event(event, stream_name: 'stream_name', expected_version: 100) }.to raise_error(WrongExpectedEventVersion)
+ end
+
+ specify 'create event with optimistic locking' do
+ client = RubyEventStore::Client.new(repository: InMemoryRepository.new)
+ event = OrderCreated.new(event_id: 'b2d506fd-409d-4ec7-b02f-c6d2295c7edd')
+ client.append_to_stream(event, stream_name: 'stream_name')
+
+ event = OrderCreated.new(event_id: '724dd49d-6e20-40e6-bc32-ed75258f886b')
+ client.append_to_stream(event, stream_name: 'stream_name', expected_version: 0)
+ end
+
+ specify 'expect no event handler is called' do
+ client = RubyEventStore::Client.new(repository: InMemoryRepository.new)
+ handler = double(:event_handler)
+ expect(handler).not_to receive(:call)
+ event = OrderCreated.new
+ client.subscribe_to_all_events(handler)
+ client.append_to_stream(event, stream_name: 'stream_name')
+ saved_events = client.read_stream_events_forward('stream_name')
+ expect(saved_events[0]).to eq(event)
+ end
+
+ specify 'expect publish to call event handlers' do
+ client = RubyEventStore::Client.new(repository: InMemoryRepository.new)
+ handler = double(:event_handler)
+ expect(handler).to receive(:call)
+ event = OrderCreated.new
+ client.subscribe_to_all_events(handler)
+ client.publish_event(event, stream_name: 'stream_name')
+ saved_events = client.read_stream_events_forward('stream_name')
+ expect(saved_events[0]).to eq(event)
+ end
+
+ specify 'create global event without stream name' do
+ client = RubyEventStore::Client.new(repository: InMemoryRepository.new)
+ event = OrderCreated.new
+ client.publish_event(event)
+ saved_events = client.read_stream_events_forward('all')
+ expect(saved_events[0]).to eq(event)
+ end
+
end
end
|
Readd specs missed in previous commit
It turns out that in the previous commit where we merged client specs
into client_spec we forgot to add specs from one file:
spec/actions/create_events_in_stream_spec.rb
...which we deleted. We just noticed that the overall number of examples
dropped.
What's intriguing: why didn't mutant fail? Are some specs redundant
here?
|
RailsEventStore_rails_event_store
|
train
|
ae968bbcb5fc85305b17494e59de5cf6e778279a
|
diff --git a/compile/service.go b/compile/service.go
index <HASH>..<HASH> 100644
--- a/compile/service.go
+++ b/compile/service.go
@@ -316,7 +316,7 @@ func (rs *ResultSpec) Link(scope Scope) (err error) {
if !ok || spec.Type != ast.ExceptionType {
return notAnExceptionError{
FieldName: exception.ThriftName(),
- TypeName: spec.ThriftName(),
+ TypeName: exception.Type.ThriftName(),
}
}
}
diff --git a/compile/service_test.go b/compile/service_test.go
index <HASH>..<HASH> 100644
--- a/compile/service_test.go
+++ b/compile/service_test.go
@@ -432,6 +432,27 @@ func TestLinkServiceFailure(t *testing.T) {
},
},
{
+ "unexpected exception type",
+ `
+ service Foo {
+ void foo()
+ throws (
+ 1: i64 a
+ )
+ }
+ `,
+ scope(
+ "SomeException", &StructSpec{
+ Name: "SomeException",
+ Type: ast.ExceptionType,
+ Fields: make(FieldGroup, 0),
+ },
+ ),
+ []string{
+ `field "a" with type "i64" is not an exception`,
+ },
+ },
+ {
"unknown return type",
"service Foo { Baz bar() }",
nil,
|
compile/service: fix nil deref for exception (#<I>)
If you attempt to use a type that isn't user defined as an exception,
the system panics instead of returning an error.
This change fixes the issue and adds a failing test case.
|
thriftrw_thriftrw-go
|
train
|
e9ec56fff117203eab723c0245e75e0f756dc5d3
|
diff --git a/compiler/prelude.go b/compiler/prelude.go
index <HASH>..<HASH> 100644
--- a/compiler/prelude.go
+++ b/compiler/prelude.go
@@ -490,6 +490,25 @@ var go$structType = function(fields) {
this[fields[i][0]] = arguments[i];
}
});
+ // collect methods for anonymous fields
+ var i, j;
+ for (i = 0; i < fields.length; i++) {
+ var field = fields[i];
+ if (field[1] === "") {
+ var methods = field[3].methods;
+ for (j = 0; j < methods.length; j++) {
+ var m = methods[j].slice(0, 6).concat([i]);
+ typ.methods.push(m);
+ typ.Ptr.methods.push(m);
+ }
+ if (field[3].kind === "Struct") {
+ var methods = field[3].Ptr.methods;
+ for (j = 0; j < methods.length; j++) {
+ typ.Ptr.methods.push(methods[j].slice(0, 6).concat([i]));
+ }
+ }
+ }
+ }
typ.init(fields);
go$structTypes[string] = typ;
}
|
collect methods for anonymous fields of anonymous structs
|
gopherjs_gopherjs
|
train
|
8258b7b525f6692607ecd344837ae8391d7392e0
|
diff --git a/enju_leaf.gemspec b/enju_leaf.gemspec
index <HASH>..<HASH> 100644
--- a/enju_leaf.gemspec
+++ b/enju_leaf.gemspec
@@ -16,7 +16,7 @@ Gem::Specification.new do |s|
s.files = Dir["{app,config,db,lib,vendor}/**/*"] + ["MIT-LICENSE", "Rakefile", "README.rdoc"]
s.test_files = Dir["spec/**/*"] - Dir["spec/dummy/log/*"] - Dir["spec/dummy/solr/{data,pids}/*"]
- s.add_dependency "enju_biblio", "~> 0.1.0.pre41"
+ s.add_dependency "enju_biblio", "~> 0.1.0.pre42"
s.add_dependency "enju_library", "~> 0.1.0.pre24"
s.add_dependency "enju_manifestation_viewer", "~> 0.1.0.pre11"
s.add_dependency "redcarpet"
diff --git a/lib/enju_leaf/controller.rb b/lib/enju_leaf/controller.rb
index <HASH>..<HASH> 100644
--- a/lib/enju_leaf/controller.rb
+++ b/lib/enju_leaf/controller.rb
@@ -4,6 +4,8 @@ module EnjuLeaf
include EnjuLeaf::InstanceMethods
include EnjuLeaf::Controller
include Mobylette::RespondToMobileRequests
+ enju_biblio
+ enju_library
end
private
diff --git a/lib/generators/enju_leaf/setup/setup_generator.rb b/lib/generators/enju_leaf/setup/setup_generator.rb
index <HASH>..<HASH> 100644
--- a/lib/generators/enju_leaf/setup/setup_generator.rb
+++ b/lib/generators/enju_leaf/setup/setup_generator.rb
@@ -45,8 +45,6 @@ EOS
inject_into_class "app/controllers/application_controller.rb", ApplicationController do
<<"EOS"
enju_leaf
- enju_biblio
- enju_library
mobylette_config do |config|
config[:skip_xhr_requests] = false
diff --git a/spec/dummy/app/controllers/application_controller.rb b/spec/dummy/app/controllers/application_controller.rb
index <HASH>..<HASH> 100644
--- a/spec/dummy/app/controllers/application_controller.rb
+++ b/spec/dummy/app/controllers/application_controller.rb
@@ -1,8 +1,6 @@
class ApplicationController < ActionController::Base
protect_from_forgery
enju_leaf
- enju_biblio
- enju_library
mobylette_config do |config|
config[:skip_xhr_requests] = false
|
load enju_biblio and enju_library
|
next-l_enju_leaf
|
train
|
b3964b9406dea4d4b6aaaca6d96638c25c42ff19
|
diff --git a/bundles/org.eclipse.orion.client.ui/web/orion/projectCommands.js b/bundles/org.eclipse.orion.client.ui/web/orion/projectCommands.js
index <HASH>..<HASH> 100644
--- a/bundles/org.eclipse.orion.client.ui/web/orion/projectCommands.js
+++ b/bundles/org.eclipse.orion.client.ui/web/orion/projectCommands.js
@@ -1067,7 +1067,8 @@ define(['i18n!orion/navigate/nls/messages', 'orion/webui/littlelib', 'orion/comm
tootlip: deployService.tooltip,
id: "orion.project.deploy." + deployService.id,
callback: function(data){
- var item = forceSingleItem(data.items);
+// var item = forceSingleItem(data.items);
+ var item = forceSingleItem(explorer.selection.getSelections());
var project = item.Project;
var appPath;
|
run the deploy command with the selection of the explorer instead of treeRoot
|
eclipse_orion.client
|
train
|
0292061542817627cb443ffe68cef143defec8ef
|
diff --git a/cmd/shield/archives_cli.go b/cmd/shield/archives_cli.go
index <HASH>..<HASH> 100644
--- a/cmd/shield/archives_cli.go
+++ b/cmd/shield/archives_cli.go
@@ -103,16 +103,13 @@ func processListArchivesRequest(cmd *cobra.Command, args []string) {
}
t := tui.NewTable("UUID", "Target Type", "Target Name", "Store Type", "Taken at", "Expires at", "Notes")
- var targets []Target
- var targetName string
+ target := map[string]Target{}
+ targets, _ := GetTargets(TargetFilter{})
+ for _, t := range targets {
+ target[t.UUID] = t
+ }
for _, archive := range data {
- targets, _ = FetchTargetsList(archive.TargetPlugin, "")
- for _, target := range targets {
- if target.UUID == archive.TargetUUID {
- targetName = target.Name
- }
- }
- t.Row(archive.UUID, archive.TargetPlugin, targetName, archive.StorePlugin,
+ t.Row(archive.UUID, archive.TargetPlugin, target[archive.TargetUUID].Name, archive.StorePlugin,
archive.TakenAt.Format(time.RFC1123Z),
archive.ExpiresAt.Format(time.RFC1123Z),
archive.Notes)
|
Less derpy way to get target name
|
starkandwayne_shield
|
train
|
c37a05ac4f17b20ac2488ad47a61e7dc3fdcebda
|
diff --git a/src/PhpFileCache.php b/src/PhpFileCache.php
index <HASH>..<HASH> 100755
--- a/src/PhpFileCache.php
+++ b/src/PhpFileCache.php
@@ -101,23 +101,21 @@ class PhpFileCache extends FileCache {
$timeOut = time() + $timeToLive;
}
- if (is_object($value) && !method_exists($value, '__set_state')) {
- throw new \InvalidArgumentException(
- "Invalid argument given, PhpFileCache only allows objects that implement __set_state() " .
- "and fully support var_export(). You can use the FileCache to save arbitrary object " .
- "graphs using serialize()/deserialize()."
- );
- }
-
$data = array(
'lifetime' => $timeOut,
'data' => $value
);
- $data = var_export($data, true);
- $code = sprintf('<?php return %s;', $data);
+ $serializeData = serialize($data);
+ if(strpos($serializeData, 'r:') !== false){
+ $code = sprintf('<?php return unserialize(%s);', var_export($serializeData, true));
+ file_put_contents($filename, $code);
+ }else{
+ $data = var_export($data, true);
+ $code = sprintf('<?php return %s;', $data);
+ file_put_contents($filename, $code);
+ }
- file_put_contents($filename, $code);
// Cache is shared with group, not with the rest of the world.
chmod($filename, 0660);
|
Handle circular references in PhpFileCache
|
thecodingmachine_utils.cache.file-cache
|
train
|
67199f81b40d603d191a8a3a006c885071e0e9ed
|
diff --git a/test/stats-gputime.js b/test/stats-gputime.js
index <HASH>..<HASH> 100644
--- a/test/stats-gputime.js
+++ b/test/stats-gputime.js
@@ -6,7 +6,10 @@ tape('test gpuTime', function (t) {
var gl = createContext(100, 100)
t.equals(gl.getError(), 0, 'error code ok')
- var regl = createREGL(gl)
+ var regl = createREGL({
+ gl: gl,
+ optionalExtensions: 'ext_disjoint_timer_query'
+ })
if (regl.hasExtension('ext_disjoint_timer_query')) {
var obj = {
|
make gputime test always load extension for stats
|
regl-project_regl
|
train
|
b797da4e5a9252fc3258b9a95d478ae8d2726b2c
|
diff --git a/classes/task.js b/classes/task.js
index <HASH>..<HASH> 100644
--- a/classes/task.js
+++ b/classes/task.js
@@ -37,11 +37,14 @@ module.exports = class SayHello extends Task {
}
/**
+ * The main "do something" method for this task. It can be `async`. Anything returned from this metod will be logged.
+ * If error is thrown in this method, it will be logged & caught. Using middleware, you can decide to re-run the task on failure.
+ * `this` within a Task's run method is an instance of a node-resque worker. This means you can inpsect `this.job` and set `this.result` expliclity if your Task does not return a value.
+ *
* @function run
* @async
* @memberof ActionHero.Task
* @param {Object} data The data about this instance of the task, specifically params.
- * @description The main "do something" method for this task. It can be `async`. Anything returned from this metod will be logged. If error is thrown in this method, it will be logged & caught. Using middleware, you can decide to re-run the task on failure.
*/
coreProperties () {
|
note about this in a task's run method
|
actionhero_actionhero
|
train
|
d47ad9f12bbb01576a9ce320eb08b5ac4038cc90
|
diff --git a/src/bin/repl.js b/src/bin/repl.js
index <HASH>..<HASH> 100644
--- a/src/bin/repl.js
+++ b/src/bin/repl.js
@@ -270,7 +270,7 @@ function read(input) {
openParens += countOpeningParens(input);
openParens -= countClosingParens(input);
- buffer += input;
+ buffer += input + "\n";
if (openParens === 0) {
try {
|
fix(repl): preserve new lines
|
xtuc_webassemblyjs
|
train
|
c4167025f3da10c03d2ec413f2c3b7f9822c7a51
|
diff --git a/models/classes/runner/features/ManageableFeature.php b/models/classes/runner/features/ManageableFeature.php
index <HASH>..<HASH> 100644
--- a/models/classes/runner/features/ManageableFeature.php
+++ b/models/classes/runner/features/ManageableFeature.php
@@ -20,6 +20,9 @@
namespace oat\taoTests\models\runner\features;
+use oat\taoTests\models\runner\plugins\TestPluginService;
+use oat\taoTests\models\runner\plugins\TestPlugin;
+
/**
* Class ManageableFeature
*
@@ -88,6 +91,15 @@ class ManageableFeature extends TestRunnerFeature
}
/**
+ * @return TestPlugin[]
+ */
+ protected function getAllPlugins()
+ {
+ $pluginService = $this->getServiceLocator()->get(TestPluginService::SERVICE_ID);
+ return $pluginService->getAllPlugins();
+ }
+
+ /**
* @return string
* @throws \common_exception_Error
*/
diff --git a/models/classes/runner/features/TestRunnerFeature.php b/models/classes/runner/features/TestRunnerFeature.php
index <HASH>..<HASH> 100644
--- a/models/classes/runner/features/TestRunnerFeature.php
+++ b/models/classes/runner/features/TestRunnerFeature.php
@@ -117,7 +117,7 @@ abstract class TestRunnerFeature implements TestRunnerFeatureInterface, LoggerAw
$allPluginIds = [];
$inactivePluginsIds = [];
- foreach ($this->allPlugins as $plugin) {
+ foreach ($this->getAllPlugins() as $plugin) {
$allPluginIds[] = $plugin->getId();
if ($plugin->isActive() === false) {
$inactivePluginsIds[] = $plugin->getId();
@@ -177,6 +177,14 @@ abstract class TestRunnerFeature implements TestRunnerFeatureInterface, LoggerAw
}
/**
+ * @return TestPlugin[]
+ */
+ protected function getAllPlugins()
+ {
+ return $this->allPlugins;
+ }
+
+ /**
* (non-PHPdoc)
* @see \oat\oatbox\PhpSerializable::__toPhpCode()
*/
diff --git a/models/classes/runner/features/TestRunnerFeatureService.php b/models/classes/runner/features/TestRunnerFeatureService.php
index <HASH>..<HASH> 100644
--- a/models/classes/runner/features/TestRunnerFeatureService.php
+++ b/models/classes/runner/features/TestRunnerFeatureService.php
@@ -90,6 +90,7 @@ class TestRunnerFeatureService extends ConfigurableService implements LoggerAwar
/** @var TestRunnerFeatureInterface[] $features */
$features = $this->getOption(self::OPTION_AVAILABLE);
foreach ($features as $id => $feature) {
+ $feature->setServiceLocator($this->getServiceLocator());
$this->propagate($feature);
if ($filterDisabled) {
if ($feature->isActive()) {
|
set service locator into manageble feature
|
oat-sa_extension-tao-test
|
train
|
94d93992239e26406b79d496b18d9d6a5e01362d
|
diff --git a/README.md b/README.md
index <HASH>..<HASH> 100644
--- a/README.md
+++ b/README.md
@@ -52,8 +52,8 @@ Quality::Rake::Task.new { |t|
# Array of directory names which contain ruby files to analyze.
#
- # Defaults to %w{lib test spec feature}, which translates to *.rb in the base directory, as well as lib, test, spec, and feature.
- t.ruby_dirs = %w{lib test spec feature}
+ # Defaults to %w{app lib test spec feature}, which translates to *.rb in the base directory, as well as those directories.
+ t.ruby_dirs = %w{app lib test spec feature}
# Relative path to output directory where *_high_water_mark
# files will be read/written
diff --git a/lib/quality/rake/task.rb b/lib/quality/rake/task.rb
index <HASH>..<HASH> 100644
--- a/lib/quality/rake/task.rb
+++ b/lib/quality/rake/task.rb
@@ -50,8 +50,8 @@ module Quality
# Array of directory names which contain ruby files to analyze.
#
- # Defaults to %w(lib test spec feature), which translates to *.rb in
- # the base directory, as well as lib, test, and feature.
+ # Defaults to %w(app lib test spec feature), which translates to *.rb in
+ # the base directory, as well as those directories.
attr_writer :ruby_dirs
# Relative path to output directory where *_high_water_mark
@@ -184,7 +184,7 @@ module Quality
end
def ruby_dirs
- @ruby_dirs ||= %w(lib test spec feature)
+ @ruby_dirs ||= %w(app lib test spec feature)
end
def ruby_files_glob
diff --git a/test/unit/test_task.rb b/test/unit/test_task.rb
index <HASH>..<HASH> 100644
--- a/test/unit/test_task.rb
+++ b/test/unit/test_task.rb
@@ -99,7 +99,7 @@ class TestTask < Test::Unit::TestCase
def expect_find_ruby_files
expect_glob.with('*.rb').returns(['fake1.rb', 'fake2.rb'])
- expect_glob.with('{lib,test,spec,feature}/**/*.rb')
+ expect_glob.with('{app,lib,test,spec,feature}/**/*.rb')
.returns(['lib/libfake1.rb',
'test/testfake1.rb',
'features/featuresfake1.rb'])
|
Include `app` in default directories
Since Rails is so prevalent I believe it makes sense to include this.
|
apiology_quality
|
train
|
132ec39b9aca64a648e2c1353a3bd2ea25d04021
|
diff --git a/src/featherlight.js b/src/featherlight.js
index <HASH>..<HASH> 100644
--- a/src/featherlight.js
+++ b/src/featherlight.js
@@ -241,13 +241,12 @@
/* sets the content of $instance to $content */
setContent: function($content){
var self = this;
- /* we need a special class for the iframe */
- if($content.is('iframe')) {
- self.$instance.addClass(self.namespace+'-iframe');
- }
self.$instance.removeClass(self.namespace+'-loading');
+ /* we need a special class for the iframe */
+ self.$instance.toggleClass(self.namespace+'-iframe', $content.is('iframe'));
+
/* replace content by appending to existing one before it is removed
this insures that featherlight-inner remain at the same relative
position to any other items added to featherlight-content */
|
Fix -iframe class for gallery [#<I>]
|
noelboss_featherlight
|
train
|
8024b6dd506443242d472520f40625598f4f223d
|
diff --git a/pysolr.py b/pysolr.py
index <HASH>..<HASH> 100644
--- a/pysolr.py
+++ b/pysolr.py
@@ -232,7 +232,7 @@ class Solr(object):
def _create_full_url(self, path=''):
if len(path):
- return '/'.join([self.url, path.lstrip('/')])
+ return '/'.join([self.url.rstrip('/'), path.lstrip('/')])
# No path? No problem.
return self.url
diff --git a/tests/client.py b/tests/client.py
index <HASH>..<HASH> 100644
--- a/tests/client.py
+++ b/tests/client.py
@@ -440,3 +440,10 @@ class SolrTestCase(unittest.TestCase):
# correctly decoded entities and that our UTF-8 characters survived the
# round-trip:
self.assertEqual(['Test Title ☃☃'], m['title'])
+
+ def test_full_url(self):
+ self.solr.url = 'http://localhost:8983/solr/'
+ full_url = self.solr._create_full_url(path='/update')
+
+ # Make sure trailing and leading slashes do not collide:
+ self.assertEqual(full_url, 'http://localhost:8983/solr/update')
|
Make sure trailing and leading slashes do not collide
|
django-haystack_pysolr
|
train
|
e08c96ff71db94eca8a0986bc4484cabdf7d36c0
|
diff --git a/webpack.common.js b/webpack.common.js
index <HASH>..<HASH> 100644
--- a/webpack.common.js
+++ b/webpack.common.js
@@ -12,7 +12,8 @@ const nodeModules = path.join(root, '/node_modules/')
module.exports = {
entry: {
- app: ['babel-polyfill', path.resolve(demo + 'index.js')]
+ app: [path.resolve(demo + 'index.js')],
+ polyfills: [path.resolve(demo + 'polyfills.js')]
},
module: {
rules: [
|
chore(webpack): Extra polyfill bundle
|
matsp_material-components-vue
|
train
|
e51dbce48e96a1008ac0fae2cf6da1a4d0cc1626
|
diff --git a/Slim/App.php b/Slim/App.php
index <HASH>..<HASH> 100644
--- a/Slim/App.php
+++ b/Slim/App.php
@@ -523,17 +523,15 @@ class App extends \Pimple\Container
public function __invoke(RequestInterface $request, ResponseInterface $response)
{
$routeInfo = $this['router']->dispatch($request);
+ if ($routeInfo[0] === \FastRoute\Dispatcher::FOUND) {
+ return $routeInfo[1]($request->withAttributes($routeInfo[2]), $response, $routeInfo[2]);
+ }
if ($routeInfo[0] === \FastRoute\Dispatcher::NOT_FOUND) {
return $this['notFoundHandler']($request, $response);
}
-
if ($routeInfo[0] === \FastRoute\Dispatcher::METHOD_NOT_ALLOWED) {
return $this['notAllowedHandler']($request, $response, $routeInfo[1]);
}
-
- if ($routeInfo[0] === \FastRoute\Dispatcher::FOUND) {
- return $routeInfo[1]($request->withAttributes($routeInfo[2]), $response, $routeInfo[2]);
- }
}
/**
|
Prioritize most likely scenario in App __invoke method
|
slimphp_Slim
|
train
|
7a8c9e66d9c43a539fb78107ce3f51f16c7f30a2
|
diff --git a/discord/ext/tasks/__init__.py b/discord/ext/tasks/__init__.py
index <HASH>..<HASH> 100644
--- a/discord/ext/tasks/__init__.py
+++ b/discord/ext/tasks/__init__.py
@@ -40,6 +40,7 @@ class Loop:
self._is_being_cancelled = False
self._has_failed = False
self._stop_next_iteration = False
+ self._exception = None
if self.count is not None and self.count <= 0:
raise ValueError('count must be greater than 0 or None.')
@@ -81,8 +82,9 @@ class Loop:
except asyncio.CancelledError:
self._is_being_cancelled = True
raise
- except Exception:
+ except Exception as e:
self._has_failed = True
+ self._exception = e
log.exception('Internal background task failed.')
raise
finally:
@@ -91,6 +93,7 @@ class Loop:
self._current_loop = 0
self._stop_next_iteration = False
self._has_failed = False
+ self._exception = None
def __get__(self, obj, objtype):
if obj is None:
@@ -255,6 +258,16 @@ class Loop:
"""
return self._has_failed
+ def exception(self):
+ """Optional[:class:`Exception`]: The exception that the internal task failed with.
+
+ .. versionadded:: 1.3.0
+ """
+ if self._exception is not None:
+ return self._exception
+ if self._task is not None:
+ return self._task.exception()
+
def before_loop(self, coro):
"""A decorator that registers a coroutine to be called before the loop starts running.
|
[tasks] Add Loop.exception for more reliable exception retrieval.
|
Rapptz_discord.py
|
train
|
5358eba94028bb7bce186966536c8bad0c358f24
|
diff --git a/src/iogi/reflection/ClassConstructor.java b/src/iogi/reflection/ClassConstructor.java
index <HASH>..<HASH> 100644
--- a/src/iogi/reflection/ClassConstructor.java
+++ b/src/iogi/reflection/ClassConstructor.java
@@ -52,31 +52,6 @@ public class ClassConstructor {
return names;
}
- @Override
- public int hashCode() {
- final int prime = 31;
- int result = 1;
- result = prime * result + ((names == null) ? 0 : names.hashCode());
- return result;
- }
-
- @Override
- public boolean equals(Object obj) {
- if (this == obj)
- return true;
- if (obj == null)
- return false;
- if (getClass() != obj.getClass())
- return false;
- ClassConstructor other = (ClassConstructor) obj;
- if (names == null) {
- if (other.names != null)
- return false;
- } else if (!names.equals(other.names))
- return false;
- return true;
- }
-
public Object instantiate(Instantiator<?> instantiator, Parameters parameters) {
Type[] parameterTypes = constructor.getGenericParameterTypes();
String[] parameterNames = namesInOrder();
diff --git a/test/iogi/reflection/ClassConstructorTest.java b/test/iogi/reflection/ClassConstructorTest.java
index <HASH>..<HASH> 100644
--- a/test/iogi/reflection/ClassConstructorTest.java
+++ b/test/iogi/reflection/ClassConstructorTest.java
@@ -1,7 +1,6 @@
package iogi.reflection;
-import static java.util.Arrays.asList;
import static org.junit.Assert.assertEquals;
import iogi.Instantiator;
import iogi.conversion.StringConverter;
@@ -9,7 +8,6 @@ import iogi.parameters.Parameter;
import iogi.parameters.Parameters;
import java.lang.reflect.Constructor;
-import java.util.HashSet;
import org.junit.Test;
@@ -26,37 +24,6 @@ public class ClassConstructorTest {
}
@Test
- public void twoClassConstructorsWithTheSameSetOfNamesAreEqual() throws Exception {
- HashSet<String> set1 = new HashSet<String>(asList("foo", "bar", "baz"));
- HashSet<String> set2 = new HashSet<String>(asList("foo", "bar", "baz"));
-
- ClassConstructor classConstructor1 = new ClassConstructor(set1);
- ClassConstructor classConstructor2 = new ClassConstructor(set2);
-
- assertEquals(classConstructor1, classConstructor2);
- }
-
- @Test
- public void twoClassConstructorsWithTheSameSetOfNamesHaveTheSameHashcode() throws Exception {
- HashSet<String> set1 = new HashSet<String>(asList("foo", "bar", "baz"));
- HashSet<String> set2 = new HashSet<String>(asList("foo", "bar", "baz"));
-
- ClassConstructor classConstructor1 = new ClassConstructor(set1);
- ClassConstructor classConstructor2 = new ClassConstructor(set2);
-
- assertEquals(classConstructor1.hashCode(), classConstructor2.hashCode());
- }
-
- @Test
- public void canCreateAClassConstructorFromAConstructor() throws Exception {
- HashSet<String> parameterNames = new HashSet<String>(asList("one", "two"));
- ClassConstructor fromNames = new ClassConstructor(parameterNames);
- ClassConstructor fromConstructor = new ClassConstructor(fooConstructor);
-
- assertEquals(fromNames, fromConstructor);
- }
-
- @Test
public void canInstantiateFromArgumentNames() throws Exception {
ClassConstructor constructor = new ClassConstructor(fooConstructor);
ImmutableList<Parameter> parameters = ImmutableList.<Parameter>builder().add(new Parameter("two", "b")).add(new Parameter("one", "a")).build();
|
Removed overriden equals and hashcode in ClassConstructor. We don't rely on them anymore for matching appropriate constructor from desired parameters.
|
rafaeldff_Iogi
|
train
|
0d6745255a83e31aeba27b2764a8eb0029b651b3
|
diff --git a/docker-java-api/src/main/java/com/github/dockerjava/api/model/HostConfig.java b/docker-java-api/src/main/java/com/github/dockerjava/api/model/HostConfig.java
index <HASH>..<HASH> 100644
--- a/docker-java-api/src/main/java/com/github/dockerjava/api/model/HostConfig.java
+++ b/docker-java-api/src/main/java/com/github/dockerjava/api/model/HostConfig.java
@@ -70,7 +70,7 @@ public class HostConfig implements Serializable {
@JsonProperty("MemorySwappiness")
private Long memorySwappiness;
- @JsonProperty("NanoCPUs")
+ @JsonProperty("NanoCpus")
private Long nanoCPUs;
@JsonProperty("CapAdd")
diff --git a/docker-java/src/test/java/com/github/dockerjava/cmd/CreateContainerCmdIT.java b/docker-java/src/test/java/com/github/dockerjava/cmd/CreateContainerCmdIT.java
index <HASH>..<HASH> 100644
--- a/docker-java/src/test/java/com/github/dockerjava/cmd/CreateContainerCmdIT.java
+++ b/docker-java/src/test/java/com/github/dockerjava/cmd/CreateContainerCmdIT.java
@@ -1065,4 +1065,23 @@ public class CreateContainerCmdIT extends CmdIT {
InspectContainerResponse inspectContainerResponse = dockerRule.getClient().inspectContainerCmd(container.getId()).exec();
assertThat(inspectContainerResponse.getHostConfig().getTmpFs().get("/tmp"), equalTo("rw,noexec,nosuid,size=50m"));
}
+
+ @Test
+ public void createContainerWithNanoCPUs() throws DockerException {
+ Long nanoCPUs = 1000000000L;
+
+ CreateContainerResponse container = dockerRule.getClient().createContainerCmd(DEFAULT_IMAGE)
+ .withCmd("sleep", "9999")
+ .withHostConfig(newHostConfig()
+ .withNanoCPUs(nanoCPUs))
+ .exec();
+
+ LOG.info("Created container {}", container.toString());
+
+ assertThat(container.getId(), not(is(emptyString())));
+
+ InspectContainerResponse inspectContainerResponse = dockerRule.getClient().inspectContainerCmd(container.getId()).exec();
+
+ assertThat(inspectContainerResponse.getHostConfig().getNanoCPUs(), is(nanoCPUs));
+ }
}
diff --git a/docker-java/src/test/java/com/github/dockerjava/cmd/InspectContainerCmdIT.java b/docker-java/src/test/java/com/github/dockerjava/cmd/InspectContainerCmdIT.java
index <HASH>..<HASH> 100644
--- a/docker-java/src/test/java/com/github/dockerjava/cmd/InspectContainerCmdIT.java
+++ b/docker-java/src/test/java/com/github/dockerjava/cmd/InspectContainerCmdIT.java
@@ -138,4 +138,19 @@ public class InspectContainerCmdIT extends CmdIT {
assertFalse(inspectContainerResponse.getNetworkSettings().getHairpinMode());
}
+
+ @Test
+ public void inspectContainerNanoCPUs() throws DockerException {
+
+ CreateContainerResponse container = dockerRule.getClient().createContainerCmd("busybox")
+ .withCmd("env").exec();
+
+ LOG.info("Created container {}", container.toString());
+
+ assertThat(container.getId(), not(is(emptyString())));
+
+ InspectContainerResponse inspectContainerResponse = dockerRule.getClient().inspectContainerCmd(container.getId()).exec();
+
+ assertThat(inspectContainerResponse.getHostConfig().getNanoCPUs(), is(0L));
+ }
}
|
Fix HostConfig's NanoCpus JsonProperty wrong casing (#<I>)
* Fix HostConfig's NanoCpus JsonProperty wrong casing
- fixes HostConfig's NanoCpus JsonProperty casing
- adds basic tests related to HostConfig NanoCPUs
* Remove unnecessary NanoCPUs test
|
docker-java_docker-java
|
train
|
939aa2f4f2805759b50b3ba1acd0704de4b167cf
|
diff --git a/README.md b/README.md
index <HASH>..<HASH> 100644
--- a/README.md
+++ b/README.md
@@ -295,7 +295,8 @@ Keys may be retrieved with or without an index:
##### Mapping
-The `map` method allows you to modify the object being returned:
+The `map` method allows you to modify the object being returned
+without correspondingly modifying the actual object stored:
```js
server.people.
@@ -364,6 +365,8 @@ Examples:
.then(...)
```
+`modify` changes will be seen by any `map` functions.
+
`modify` can be used after: `all`, `filter`, ranges (`range`, `only`,
`bound`, `upperBound`, and `lowerBound`), `desc`, `distinct`, and `map`.
diff --git a/src/db.js b/src/db.js
index <HASH>..<HASH> 100644
--- a/src/db.js
+++ b/src/db.js
@@ -233,6 +233,7 @@
// create a function that will set in the modifyObj properties into
// the passed record.
var modifyKeys = modifyObj ? Object.keys(modifyObj) : false;
+
var modifyRecord = function (record) {
for (var i = 0; i < modifyKeys.length; i++) {
var key = modifyKeys[i];
@@ -269,12 +270,12 @@
if (matchFilter) {
counter++;
- results.push(mapper(result));
// if we're doing a modify, run it now
if (modifyObj) {
result = modifyRecord(result);
cursor.update(result);
}
+ results.push(mapper(result));
}
cursor.continue();
}
diff --git a/tests/specs/query.js b/tests/specs/query.js
index <HASH>..<HASH> 100644
--- a/tests/specs/query.js
+++ b/tests/specs/query.js
@@ -661,6 +661,34 @@
});
});
+ it('should not reflect mapper changes during modification but should reflect modifications during mapping', function (done) {
+ var spec = this;
+
+ spec.server.test
+ .query()
+ .all()
+ .map(function (value) {
+ return {
+ fullName: value.firstName + ' ' + value.lastName,
+ raw: value
+ };
+ })
+ .modify({nextAge: function (item) {
+ expect(item.fullName).toBeUndefined();
+ return item.age + 1;
+ }})
+ .execute()
+ .then(function (data) {
+ expect(data.length).toEqual(3);
+ var i;
+ for (i = 0; i < data.length; i++) {
+ var result = data[i];
+ expect(result.raw.nextAge).toEqual(result.raw.age + 1);
+ }
+ done();
+ });
+ });
+
it('should only allow `modify` from a specific query type', function (done) {
var spec = this;
|
Address issue #<I>: Ensure mapper changes will never be seen by modify; future-proof to ensure modify changes will always be seen by the mapper
|
aaronpowell_db.js
|
train
|
c2821a70cb963b50254213a6046106bc8bd6be66
|
diff --git a/docs/references/bib.bib b/docs/references/bib.bib
index <HASH>..<HASH> 100644
--- a/docs/references/bib.bib
+++ b/docs/references/bib.bib
@@ -897,6 +897,22 @@
year = {1967},
}
+@article{lentz:1976,
+ abstract = {A new method of generating the Bessel functions and ratios of Bessel functions necessary for Mie calculations is presented. Accuracy is improved while eliminating the need for extended precision word lengths or large storage capability. The algorithm uses a new technique of evaluating continued fractions that starts at the beginning rather than the tail and has a built-in error check. The continued fraction representations for both spherical Bessel functions and ratios of Bessel functions of consecutive order are presented.},
+ author = {William J. Lentz},
+ doi = {10.1364/AO.15.000668},
+ isbn = {0003-6935},
+ issn = {0003-6935},
+ journal = {Applied Optics},
+ keywords = {bessel, continued fraction},
+ number = {3},
+ pages = {668--671},
+ pmid = {20165036},
+ title = {{Generating bessel functions in Mie scattering calculations using continued fractions}},
+ volume = {15},
+ year = {1976},
+}
+
@mastersthesis{steinarsson:2013,
abstract = {As human beings, we often wish to visualize certain information in order to make better sense of it. This can be a somewhat challenging enterprise for large amounts of data and might require downsampling the data, retaining only the important visual characteristics. The focus of this thesis is to explore methods for downsampling data which can be visualized in the form of a line chart, for example, time series. Several algorithms are put forth in the thesis and their features are discussed. Also, an online survey was conducted where participants were asked to compare downsampled line charts against a non-downsampled chart. Some of the algorithms are based on a well-known technique in cartography which involves forming triangles between adjacent data points and using the area of the triangles to determine the perceptual importance of the individual points. According to the survey, algorithms based on a triangle area approach consistently proved to be effective, and one in particular when efficiency is also taken into account.},
author = {Svein Steinarsson},
diff --git a/lib/node_modules/@stdlib/math/base/tools/continued-fraction/lib/basic.js b/lib/node_modules/@stdlib/math/base/tools/continued-fraction/lib/basic.js
index <HASH>..<HASH> 100644
--- a/lib/node_modules/@stdlib/math/base/tools/continued-fraction/lib/basic.js
+++ b/lib/node_modules/@stdlib/math/base/tools/continued-fraction/lib/basic.js
@@ -123,7 +123,8 @@ function continuedFractionB( gen, factor, maxIter ) {
* Evaluates the continued fraction approximation for the supplied series generator using the modified Lentz algorithm.
*
* #### References
-* * Lentz, W.J. 1976, Applied Optics, vol. 15, pp. 668-671.
+*
+* * Lentz, William J. 1976. "Generating bessel functions in Mie scattering calculations using continued fractions." *Applied Optics* 15 (3): 668–71. doi:[10.1364/AO.15.000668](https://doi.org/10.1364/AO.15.000668).
*
* @param {Function} generator - function returning terms of continued fraction expansion
* @param {Object} [options] - function options
diff --git a/lib/node_modules/@stdlib/math/base/tools/continued-fraction/lib/generators.js b/lib/node_modules/@stdlib/math/base/tools/continued-fraction/lib/generators.js
index <HASH>..<HASH> 100644
--- a/lib/node_modules/@stdlib/math/base/tools/continued-fraction/lib/generators.js
+++ b/lib/node_modules/@stdlib/math/base/tools/continued-fraction/lib/generators.js
@@ -157,7 +157,8 @@ function continuedFractionB( gen, factor, maxIter ) {
* Evaluates the continued fraction approximation for the supplied series generator using the modified Lentz algorithm.
*
* #### References
-* * Lentz, W.J. 1976, Applied Optics, vol. 15, pp. 668-671.
+*
+* * Lentz, William J. 1976. "Generating bessel functions in Mie scattering calculations using continued fractions." *Applied Optics* 15 (3): 668–71. doi:[10.1364/AO.15.000668](https://doi.org/10.1364/AO.15.000668).
*
* @param {Function} generator - function returning terms of continued fraction expansion
* @param {Object} [options] - function options
|
Insert to bib file and update reference
|
stdlib-js_stdlib
|
train
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.