hash
stringlengths 40
40
| diff
stringlengths 131
114k
| message
stringlengths 7
980
| project
stringlengths 5
67
| split
stringclasses 1
value |
---|---|---|---|---|
800d461bce280f83df7a0c91f06cc81997797c40 | diff --git a/src/Controllers/Extend.php b/src/Controllers/Extend.php
index <HASH>..<HASH> 100644
--- a/src/Controllers/Extend.php
+++ b/src/Controllers/Extend.php
@@ -210,7 +210,6 @@ class Extend implements ControllerProviderInterface, ServiceProviderInterface
{
$package = $request->get('package');
$version = $request->get('version');
- $app['extensions.stats']->recordInstall($package, $version);
$response = $app['extend.manager']->requirePackage(
array(
@@ -220,6 +219,9 @@ class Extend implements ControllerProviderInterface, ServiceProviderInterface
);
if ($response === 0) {
+ $app['extensions.stats']->recordInstall($package, $version);
+ $app['logger.system']->info("Installed $package $version", array('event' => 'extensions'));
+
return new Response($app['extend.manager']->getOutput());
} else {
throw new PackageManagerException($app['extend.manager']->getOutput(), $response);
@@ -349,11 +351,14 @@ class Extend implements ControllerProviderInterface, ServiceProviderInterface
*/
public function update(Silex\Application $app, Request $request)
{
- $package = $request->get('package') ? array($request->get('package')) : array();
+ $package = $request->get('package') ? $request->get('package') : null;
+ $update = $package ? array($package) : array();
- $response = $app['extend.manager']->updatePackage($package);
+ $response = $app['extend.manager']->updatePackage($update);
if ($response === 0) {
+ $app['logger.system']->info("Updated $package", array('event' => 'extensions'));
+
return new JsonResponse($app['extend.manager']->getOutput());
} else {
throw new PackageManagerException($app['extend.manager']->getOutput(), $response);
@@ -377,6 +382,8 @@ class Extend implements ControllerProviderInterface, ServiceProviderInterface
$response = $app['extend.manager']->removePackage(array($package));
if ($response === 0) {
+ $app['logger.system']->info("Uninstalled $package", array('event' => 'extensions'));
+
return new Response($app['extend.manager']->getOutput());
} else {
throw new PackageManagerException($app['extend.manager']->getOutput(), $response);
diff --git a/src/Extensions/StatService.php b/src/Extensions/StatService.php
index <HASH>..<HASH> 100644
--- a/src/Extensions/StatService.php
+++ b/src/Extensions/StatService.php
@@ -11,17 +11,25 @@ class StatService
'install' => 'stat/install/%s/%s'
);
+ /**
+ * @param Application $app
+ */
public function __construct(Application $app)
{
$this->app = $app;
}
+ /**
+ * Record an extension install.
+ *
+ * @param string $package
+ * @param string $version
+ */
public function recordInstall($package, $version)
{
$url = sprintf($this->app['extend.site'] . $this->urls['install'], $package, $version);
try {
- $this->app['logger.system']->info("Installed $package $version", array('event' => 'extensions'));
$this->app['guzzle.client']->head($url)->send();
} catch (\Exception $e) {
$this->app['logger.system']->critical($e->getMessage(), array('event' => 'exception', 'exception' => $e)); | Add a logging record for extension update and uninstall | bolt_bolt | train |
586dbb889024dc862a1bcf4c59f8480286e0499a | diff --git a/screens/RangeDemo.js b/screens/RangeDemo.js
index <HASH>..<HASH> 100644
--- a/screens/RangeDemo.js
+++ b/screens/RangeDemo.js
@@ -29,7 +29,7 @@ export class RangeExample extends React.Component {
export default function RangeDemo() {
return (
<Content padding>
- <View style={[cs.row, cs.padding, { alignItems: 'center' }]}>
+ <View style={[cs.row, cs.paddingHorizontal, { alignItems: 'center' }]}>
<Icon name="volume-down" size={24} />
<RangeExample />
<Icon name="volume-up" size={24} /> | Unify vertical space between examples in Range demo | carbon-native_carbon-native | train |
9bc6d3c7afc2f014fb55607013166af6e38f0b60 | diff --git a/test/Peach/Markup/DebugBuilderTest.php b/test/Peach/Markup/DebugBuilderTest.php
index <HASH>..<HASH> 100644
--- a/test/Peach/Markup/DebugBuilderTest.php
+++ b/test/Peach/Markup/DebugBuilderTest.php
@@ -33,7 +33,10 @@ class DebugBuilderTest extends BuilderTest
* - ใใผใใฎๆง้ ใใใใใใใใใฐๆๅญๅใ่ฟใใใจ
* - ่ฟใๅคใจๅใๆๅญๅใ่ชๅ็ใซ echo ใใใใใจ
*
+ * @covers Peach\Markup\DebugBuilder::__construct
* @covers Peach\Markup\DebugBuilder::build
+ * @covers Peach\Markup\DebugBuilder::createContext
+ * @covers Peach\Markup\Context::handle
*/
public function testBuild()
{
@@ -48,7 +51,10 @@ class DebugBuilderTest extends BuilderTest
* ใณใณในใใฉใฏใฟๅผๆฐใซ false ใๆๅฎใใฆ DebugBuilder ใๅๆๅใใๅ ดๅ,
* ่ชๅ echo ใใใใชใใใจใ็ขบ่ชใใพใ.
*
+ * @covers Peach\Markup\DebugBuilder::__construct
* @covers Peach\Markup\DebugBuilder::build
+ * @covers Peach\Markup\DebugBuilder::createContext
+ * @covers Peach\Markup\Context::handle
*/
public function testBuildNotEcho()
{ | Improved code coverage rate by adding "covers" annotation | trashtoy_PEACH2 | train |
099aef0a7f3a551e974d72c7a78d604112f26fcd | diff --git a/figtree.go b/figtree.go
index <HASH>..<HASH> 100644
--- a/figtree.go
+++ b/figtree.go
@@ -235,6 +235,10 @@ func makeMergeStruct(values ...reflect.Value) reflect.Value {
} else if typ.Kind() == reflect.Map {
for _, key := range v.MapKeys() {
keyval := reflect.ValueOf(v.MapIndex(key).Interface())
+ // skip invalid (ie nil) key values
+ if !keyval.IsValid() {
+ continue
+ }
if keyval.Kind() == reflect.Ptr && keyval.Elem().Kind() == reflect.Map {
keyval = makeMergeStruct(keyval.Elem())
} else if keyval.Kind() == reflect.Map {
@@ -276,6 +280,10 @@ func mapToStruct(src reflect.Value) reflect.Value {
for _, key := range src.MapKeys() {
structFieldName := camelCase(key.String())
keyval := reflect.ValueOf(src.MapIndex(key).Interface())
+ // skip invalid (ie nil) key values
+ if !keyval.IsValid() {
+ continue
+ }
if keyval.Kind() == reflect.Ptr && keyval.Elem().Kind() == reflect.Map {
keyval = mapToStruct(keyval.Elem()).Addr()
m.mergeStructs(dest.FieldByName(structFieldName), reflect.ValueOf(keyval.Interface()))
diff --git a/figtree_test.go b/figtree_test.go
index <HASH>..<HASH> 100644
--- a/figtree_test.go
+++ b/figtree_test.go
@@ -705,6 +705,7 @@ func TestMakeMergeStruct(t *testing.T) {
"map": map[string]interface{}{
"mapkey": "mapval2",
},
+ "nilmap": nil,
}
got := MakeMergeStruct(input)
@@ -1073,6 +1074,15 @@ func TestMergeWithZeros(t *testing.T) {
Merge(&tt.dest, &tt.src)
// })
assert.Equal(t, tt.want, tt.dest, tt.info.line)
+
+ got := MakeMergeStruct(tt.dest)
+ Merge(got, tt.dest)
+ Merge(got, tt.src)
+
+ expected := MakeMergeStruct(tt.want)
+ Merge(expected, tt.want)
+
+ assert.Equal(t, expected, got, tt.info.line)
}),
)
}
@@ -1318,6 +1328,16 @@ func TestMergeStructsWithZeros(t *testing.T) {
Merge(&tt.dest, &tt.src)
// })
assert.Equal(t, tt.want, tt.dest, tt.info.line)
+
+ got := MakeMergeStruct(tt.dest)
+ Merge(got, tt.dest)
+ Merge(got, tt.src)
+
+ expected := MakeMergeStruct(tt.want)
+ Merge(expected, tt.want)
+
+ assert.Equal(t, expected, got, tt.info.line)
+
}),
)
} | fix edge case "reflect: call of reflect.Value.Interface on zero Value" when converting maps to structs and the map has a nil value | coryb_figtree | train |
0253286fdf8fd451f621f6e7c6e4c5ad085baae1 | diff --git a/lib/Thelia/Module/BaseModule.php b/lib/Thelia/Module/BaseModule.php
index <HASH>..<HASH> 100644
--- a/lib/Thelia/Module/BaseModule.php
+++ b/lib/Thelia/Module/BaseModule.php
@@ -26,11 +26,13 @@ use Thelia\Exception\ModuleException;
use Thelia\Log\Tlog;
use Thelia\Model\Cart;
use Thelia\Model\Country;
+use Thelia\Model\Hook;
use Thelia\Model\HookQuery;
use Thelia\Model\Lang;
use Thelia\Model\Map\ModuleImageTableMap;
use Thelia\Model\Map\ModuleTableMap;
use Thelia\Model\Module;
+use Thelia\Model\ModuleConfigQuery;
use Thelia\Model\ModuleI18n;
use Thelia\Model\ModuleI18nQuery;
use Thelia\Model\ModuleImage;
@@ -53,6 +55,9 @@ class BaseModule extends ContainerAware implements BaseModuleInterface
protected $dispatcher = null;
protected $request = null;
+ // Do no use this attribute directly, use getModuleModel() instead.
+ private $_moduleModel = null;
+
public function activate($moduleModel = null)
{
if (null === $moduleModel) {
@@ -192,6 +197,36 @@ class BaseModule extends ContainerAware implements BaseModuleInterface
}
/**
+ * Get a module's configuration variable
+ *
+ * @param string $variableName the variable name
+ * @param string $defaultValue the default value, if variable is not defined
+ * @param null $valueLocale the required locale, or null to get default one
+ * @return string the variable value
+ */
+ public static function getConfigValue($variableName, $defaultValue = null, $valueLocale = null)
+ {
+ return ModuleConfigQuery::create()
+ ->getConfigValue(self::getModuleId(), $variableName, $defaultValue, $valueLocale);
+ }
+
+ /**
+ * Set module configuration variable, creating it if required
+ *
+ * @param string $variableName the variable name
+ * @param string $variableValue the variable value
+ * @param null $valueLocale the locale, or null if not required
+ * @param bool $createIfNotExists if true, the variable will be created if not already defined
+ * @throws \LogicException if variable does not exists and $createIfNotExists is false
+ * @return $this;
+ */
+ public static function setConfigValue($variableName, $variableValue, $valueLocale = null, $createIfNotExists = true)
+ {
+ ModuleConfigQuery::create()
+ ->setConfigValue(self::getModuleId(), $variableName, $variableValue, $valueLocale, $createIfNotExists);
+ }
+
+ /**
* Ensure the proper deployment of the module's images.
*
* TODO : this method does not take care of internationalization. This is a bug.
@@ -276,22 +311,49 @@ class BaseModule extends ContainerAware implements BaseModuleInterface
*/
public function getModuleModel()
{
- $moduleModel = ModuleQuery::create()->findOneByCode($this->getCode());
+ if (null === $this->_moduleModel) {
+ $this->_moduleModel = ModuleQuery::create()->findOneByCode($this->getCode());
- if (null === $moduleModel) {
- throw new ModuleException(sprintf("Module Code `%s` not found", $this->getCode()), ModuleException::CODE_NOT_FOUND);
+ if (null === $this->_moduleModel) {
+ throw new ModuleException(sprintf("Module Code `%s` not found", $this->getCode()), ModuleException::CODE_NOT_FOUND);
+ }
}
- return $moduleModel;
+ return $this->_moduleModel;
}
- public function getCode()
+ /**
+ * @return int The module id, in a static way, with a cache
+ */
+ private static $moduleId = null;
+
+ public static function getModuleId()
{
- if (null === $this->reflected) {
- $this->reflected = new \ReflectionObject($this);
+ if (self::$moduleId === null) {
+ if (null === $module = ModuleQuery::create()->findOneByCode(self::getModuleCode())) {
+ throw new ModuleException(sprintf("Module Code `%s` not found", self::getModuleCode()), ModuleException::CODE_NOT_FOUND);
+ }
+
+ self::$moduleId = $module->getId();
}
- return basename(dirname($this->reflected->getFileName()));
+ return self::$moduleId;
+ }
+
+ /**
+ * @return string The module code, in a static way
+ */
+ public static function getModuleCode()
+ {
+ return basename(get_called_class());
+ }
+
+ /*
+ * The module code
+ */
+ public function getCode()
+ {
+ return self::getModuleCode();
}
/**
@@ -535,6 +597,8 @@ class BaseModule extends ContainerAware implements BaseModuleInterface
/**
* Create or update hook db entry.
+ *
+ * @var Hook $hookModel
*/
list($hookModel, $updateData) = $this->createOrUpdateHook($hook, $dispatcher, $defaultLocale); | Added getConfigValue and setConfigValue methods | thelia_core | train |
32f4bd1faa1909288e62995891c42c0f2393a812 | diff --git a/netpyne/analysis/tools.py b/netpyne/analysis/tools.py
index <HASH>..<HASH> 100644
--- a/netpyne/analysis/tools.py
+++ b/netpyne/analysis/tools.py
@@ -228,8 +228,17 @@ def plotData(sim=None):
for funcName, kwargs in sim.cfg.analysis.items():
if kwargs == True: kwargs = {}
elif kwargs == False: continue
- func = getattr(sim.plotting, funcName) # get pointer to function
- out = func(**kwargs) # call function with user arguments
+ func = None
+ try:
+ func = getattr(sim.plotting, funcName)
+ out = func(**kwargs) # call function with user arguments
+ except:
+ try:
+ func = getattr(sim.analysis, funcName)
+ out = func(**kwargs) # call function with user arguments
+ except:
+ print('Unable to run', funcName, 'from sim.plotting and sim.analysis')
+
# Print timings
if sim.cfg.timing: | temp fix so that old plots are still generated with sim.analysis | Neurosim-lab_netpyne | train |
be5239e6b52cb5fbb9d57709c0e630217924951f | diff --git a/setup.py b/setup.py
index <HASH>..<HASH> 100644
--- a/setup.py
+++ b/setup.py
@@ -46,6 +46,7 @@ setup(
"Programming Language :: Python :: 3.2",
"Programming Language :: Python :: 3.3",
"Programming Language :: Python :: 3.4",
+ "Programming Language :: Python :: 3.5",
"Programming Language :: Python :: Implementation :: CPython",
"Programming Language :: Python :: Implementation :: PyPy",
"Topic :: Software Development :: Build Tools", | updating setup.py support for <I> | amoffat_sh | train |
31a769e8450a1da2c516fa042b1433059daa1325 | diff --git a/sonar-batch/src/main/java/org/sonar/batch/scan/ProjectReactorValidator.java b/sonar-batch/src/main/java/org/sonar/batch/scan/ProjectReactorValidator.java
index <HASH>..<HASH> 100644
--- a/sonar-batch/src/main/java/org/sonar/batch/scan/ProjectReactorValidator.java
+++ b/sonar-batch/src/main/java/org/sonar/batch/scan/ProjectReactorValidator.java
@@ -57,6 +57,8 @@ public class ProjectReactorValidator {
String rootProjectKey = ComponentKeys.createKey(reactor.getRoot().getKey(), branch);
List<String> validationMessages = new ArrayList<String>();
+ checkDeprecatedProperties(validationMessages);
+
for (ProjectDefinition moduleDef : reactor.getProjects()) {
validateModule(moduleDef, validationMessages, branch, rootProjectKey);
}
@@ -79,8 +81,6 @@ public class ProjectReactorValidator {
}
private void validateModule(ProjectDefinition moduleDef, List<String> validationMessages, @Nullable String branch, String rootProjectKey) {
- checkDeprecatedProperties(moduleDef, validationMessages);
-
if (!ComponentKeys.isValidModuleKey(moduleDef.getKey())) {
validationMessages.add(String.format("\"%s\" is not a valid project or module key. "
+ "Allowed characters are alphanumeric, '-', '_', '.' and ':', with at least one non-digit.", moduleDef.getKey()));
@@ -106,8 +106,8 @@ public class ProjectReactorValidator {
}
}
- private void checkDeprecatedProperties(ProjectDefinition moduleDef, List<String> validationMessages) {
- if (moduleDef.getProperties().getProperty(SONAR_PHASE) != null) {
+ private void checkDeprecatedProperties(List<String> validationMessages) {
+ if (settings.getString(SONAR_PHASE) != null) {
validationMessages.add(String.format("Property \"%s\" is deprecated. Please remove it from your configuration.", SONAR_PHASE));
}
}
diff --git a/sonar-batch/src/test/java/org/sonar/batch/scan/ProjectReactorValidatorTest.java b/sonar-batch/src/test/java/org/sonar/batch/scan/ProjectReactorValidatorTest.java
index <HASH>..<HASH> 100644
--- a/sonar-batch/src/test/java/org/sonar/batch/scan/ProjectReactorValidatorTest.java
+++ b/sonar-batch/src/test/java/org/sonar/batch/scan/ProjectReactorValidatorTest.java
@@ -232,7 +232,7 @@ public class ProjectReactorValidatorTest {
@Test
public void fail_with_deprecated_sonar_phase() {
ProjectReactor reactor = createProjectReactor("foo");
- reactor.getRoot().setProperty("sonar.phase", "phase");
+ settings.setProperty("sonar.phase", "phase");
thrown.expect(SonarException.class);
thrown.expectMessage("\"sonar.phase\" is deprecated"); | SONAR-<I> Fix validation when property is set from command line | SonarSource_sonarqube | train |
0e43ea278ba53c877d5e9b56e7ed4e40682b979b | diff --git a/lib/csvlint/schema.rb b/lib/csvlint/schema.rb
index <HASH>..<HASH> 100644
--- a/lib/csvlint/schema.rb
+++ b/lib/csvlint/schema.rb
@@ -17,14 +17,14 @@ module Csvlint
def validate_header(header)
reset
- if header.size != fields.size
- build_warnings(:header_count, :schema, nil, 1, "#{fields.size} header field(s) specified but found #{header.size}")
- end
+ #if header.size != fields.size
+ # build_warnings(:header_count, :schema, nil, 1, "#{fields.size} header field(s) specified but found #{header.size}")
+ #end
- header.each_with_index do |name,i|
- if fields.size < i+1 || fields[i].name != name
- build_warnings(:header_name, :schema, nil, i+1, name)
- end
+ found_header = header.join(',')
+ expected_header = @fields.map{ |f| f.name }.join(',')
+ if found_header != expected_header
+ build_warnings(:malformed_header, :schema, 1, nil, found_header, expected_header)
end
return valid?
diff --git a/spec/schema_spec.rb b/spec/schema_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/schema_spec.rb
+++ b/spec/schema_spec.rb
@@ -95,10 +95,12 @@ describe Csvlint::Schema do
expect( schema.validate_header(["wrong", "required"]) ).to eql(true)
expect( schema.warnings.size ).to eql(1)
- expect( schema.warnings.first.type ).to eql(:header_name)
- expect( schema.warnings.first.content ).to eql("wrong")
- expect( schema.warnings.first.column ).to eql(1)
+ expect( schema.warnings.first.row ).to eql(1)
+ expect( schema.warnings.first.type ).to eql(:malformed_header)
+ expect( schema.warnings.first.content ).to eql('wrong,required')
+ expect( schema.warnings.first.column ).to eql(nil)
expect( schema.warnings.first.category ).to eql(:schema)
+ expect( schema.warnings.first.constraints ).to eql('minimum,required')
expect( schema.validate_header(["minimum", "Required"]) ).to eql(true)
expect( schema.warnings.size ).to eql(1)
@@ -112,10 +114,12 @@ describe Csvlint::Schema do
expect( schema.validate_header(["minimum"]) ).to eql(true)
expect( schema.warnings.size ).to eql(1)
- expect( schema.warnings.first.type ).to eql(:header_count)
- expect( schema.warnings.first.content ).to eql("2 header field(s) specified but found 1")
- expect( schema.warnings.first.column ).to eql(1)
+ expect( schema.warnings.first.row ).to eql(1)
+ expect( schema.warnings.first.type ).to eql(:malformed_header)
+ expect( schema.warnings.first.content ).to eql("minimum")
+ expect( schema.warnings.first.column ).to eql(nil)
expect( schema.warnings.first.category ).to eql(:schema)
+ expect( schema.warnings.first.constraints ).to eql('minimum,required')
end
@@ -124,22 +128,13 @@ describe Csvlint::Schema do
schema = Csvlint::Schema.new("http://example.org", [minimum] )
expect( schema.validate_header(["wrong", "required"]) ).to eql(true)
- expect( schema.warnings.size ).to eql(3)
-
- expect( schema.warnings.first.type ).to eql(:header_count)
- expect( schema.warnings.first.content ).to eql("1 header field(s) specified but found 2")
- expect( schema.warnings.first.column ).to eql(1)
+ expect( schema.warnings.size ).to eql(1)
+ expect( schema.warnings.first.row ).to eql(1)
+ expect( schema.warnings.first.type ).to eql(:malformed_header)
+ expect( schema.warnings.first.content ).to eql("wrong,required")
+ expect( schema.warnings.first.column ).to eql(nil)
expect( schema.warnings.first.category ).to eql(:schema)
-
- expect( schema.warnings[1].type ).to eql(:header_name)
- expect( schema.warnings[1].content ).to eql("wrong")
- expect( schema.warnings[1].column ).to eql(1)
- expect( schema.warnings[1].category ).to eql(:schema)
-
- expect( schema.warnings[2].type ).to eql(:header_name)
- expect( schema.warnings[2].content ).to eql("required")
- expect( schema.warnings[2].column ).to eql(2)
- expect( schema.warnings[2].category ).to eql(:schema)
+ expect( schema.warnings.first.constraints ).to eql('minimum')
end | Check supplied vs expected header content. | theodi_csvlint.rb | train |
86fb10f0a3e6900f8da8bbacdf7cfb5a77eeee63 | diff --git a/setup.py b/setup.py
index <HASH>..<HASH> 100755
--- a/setup.py
+++ b/setup.py
@@ -31,6 +31,7 @@ sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import distutilazy
import distutilazy.clean
+import distutilazy.test
CLASSIFIERS = [
"Development Status :: 4 - Beta",
@@ -60,7 +61,11 @@ params = dict(
long_description = long_description,
license = "MIT",
classifiers = CLASSIFIERS,
- cmdclass = {"clean_pyc": distutilazy.clean.clean_pyc, "clean_all": distutilazy.clean.clean_all}
+ cmdclass = {
+ "clean_pyc": distutilazy.clean.clean_pyc,
+ "clean_all": distutilazy.clean.clean_all,
+ "test": distutilazy.test.run_tests
+ }
)
if setuptools: | Use the new test runner class as the test command for setup.py
So now runnint setup.py test runs unit tests for distutilazy. | farzadghanei_distutilazy | train |
b66e0a952220c5dd29b674b1ab119134024172ab | diff --git a/.eslintrc b/.eslintrc
index <HASH>..<HASH> 100644
--- a/.eslintrc
+++ b/.eslintrc
@@ -4,6 +4,7 @@
"node": true,
"browser": true,
"jest/globals": true,
+ "es6": true,
},
"parser": "babel-eslint",
"plugins": ["react", "jest"],
diff --git a/src/server/db.js b/src/server/db.js
index <HASH>..<HASH> 100644
--- a/src/server/db.js
+++ b/src/server/db.js
@@ -12,11 +12,9 @@
export class InMemory {
/**
* Creates a new InMemory storage.
- * @param {function} reducer - The game reducer.
*/
- constructor(reducer) {
- this.reducer = reducer;
- this.obj = {};
+ constructor() {
+ this.map = new Map();
}
/**
@@ -25,19 +23,16 @@ export class InMemory {
* @param {object} store - A Redux store to persist.
*/
set(id, store) {
- this.obj[id] = store;
+ this.map.set(id, store);
}
/**
* Read the game state from the in-memory object.
* @param {string} id - The game id.
- * @returns {object} - A Redux store with the game state, or null
+ * @returns {object} - A Redux store with the game state, or undefined
* if no game is found with this id.
*/
get(id) {
- if (id in this.obj) {
- return this.obj[id];
- }
- return null;
+ return this.map.get(id);
}
}
diff --git a/src/server/db.test.js b/src/server/db.test.js
index <HASH>..<HASH> 100644
--- a/src/server/db.test.js
+++ b/src/server/db.test.js
@@ -14,8 +14,8 @@ test('basic', () => {
const reducer = () => {};
const store = Redux.createStore(reducer);
- // Must return null when no game exists.
- expect(db.get('gameid')).toEqual(null);
+ // Must return undefined when no game exists.
+ expect(db.get('gameid')).toEqual(undefined);
// Create game.
db.set('gameid', store);
// Must return created game.
diff --git a/src/server/index.js b/src/server/index.js
index <HASH>..<HASH> 100644
--- a/src/server/index.js
+++ b/src/server/index.js
@@ -29,7 +29,7 @@ function Server({game, numPlayers}) {
const gameid = action._gameid;
const store = db.get(gameid);
- if (store == null) {
+ if (store === undefined) {
return { error: 'game not found' };
}
@@ -43,12 +43,10 @@ function Server({game, numPlayers}) {
});
socket.on('sync', gameid => {
- let store = null;
- if (db.get(gameid) == null) {
+ let store = db.get(gameid);
+ if (store === undefined) {
store = Redux.createStore(reducer);
db.set(gameid, store);
- } else {
- store = db.get(gameid);
}
const state = store.getState(); | change object to Map in db.js | nicolodavis_boardgame.io | train |
50aa5362d16b815f4f5ce0c6bcf71ccd510576ed | diff --git a/lib/excon/connection.rb b/lib/excon/connection.rb
index <HASH>..<HASH> 100644
--- a/lib/excon/connection.rb
+++ b/lib/excon/connection.rb
@@ -136,7 +136,9 @@ module Excon
elsif ! (datum[:method].to_s.casecmp('GET') == 0 && datum[:body].nil?)
# The HTTP spec isn't clear on it, but specifically, GET requests don't usually send bodies;
# if they don't, sending Content-Length:0 can cause issues.
- datum[:headers]['Content-Length'] = detect_content_length(datum[:body])
+ unless datum[:headers].has_key?('Content-Length')
+ datum[:headers]['Content-Length'] = detect_content_length(datum[:body])
+ end
end
# add headers to request | defer to user provided content-length
closes #<I> | excon_excon | train |
27bcfd75abc6344aee637cc194bb2948820ea5e6 | diff --git a/spec/cli_spec.rb b/spec/cli_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/cli_spec.rb
+++ b/spec/cli_spec.rb
@@ -360,7 +360,6 @@ describe Bosh::Spec::IntegrationTest do
end
it "can upload a release" do
- pending
release_filename = spec_asset("valid_release.tgz")
run_bosh("target http://localhost:57523")
@@ -404,7 +403,6 @@ describe Bosh::Spec::IntegrationTest do
describe "deployment process" do
it "successfully performed with minimal manifest" do
- pending
release_filename = spec_asset("valid_release.tgz") # It's a dummy release (appcloud 0.1)
deployment_manifest_filename = yaml_file("minimal", minimal_deployment_manifest)
@@ -417,7 +415,6 @@ describe Bosh::Spec::IntegrationTest do
end
it "successfully performed with simple manifest" do
- pending
release_filename = spec_asset("valid_release.tgz") # It's a dummy release (appcloud 0.1)
stemcell_filename = spec_asset("valid_stemcell.tgz") # It's a dummy stemcell (ubuntu-stemcell 1)
deployment_manifest_filename = yaml_file("simple", simple_deployment_manifest) | Re-enabled pending integration specs | cloudfoundry_bosh | train |
ef6f36c1d24ac66d4747f990edb0d2d128e1d469 | diff --git a/packages/cerebral/src/utils.js b/packages/cerebral/src/utils.js
index <HASH>..<HASH> 100644
--- a/packages/cerebral/src/utils.js
+++ b/packages/cerebral/src/utils.js
@@ -209,7 +209,7 @@ export function getWithPath (obj) {
}
export function ensureStrictPath (path, value) {
- if (isObject(value) && path.indexOf('*') === -1) {
+ if (isComplexObject(value) && path.indexOf('*') === -1) {
return `${path}.**`
}
diff --git a/packages/cerebral/src/viewFactories/react.test.js b/packages/cerebral/src/viewFactories/react.test.js
index <HASH>..<HASH> 100644
--- a/packages/cerebral/src/viewFactories/react.test.js
+++ b/packages/cerebral/src/viewFactories/react.test.js
@@ -528,6 +528,44 @@ describe('React', () => {
component.callSignal()
assert.equal(renderCount, 2)
})
+ it('should by default update when nested children update with array', () => {
+ let renderCount = 0
+ const controller = Controller({
+ state: {
+ foo: [{
+ bar: 'value'
+ }]
+ },
+ signals: {
+ methodCalled: [({state}) => state.set('foo.0.bar', 'value2')]
+ }
+ })
+ class TestComponentClass extends React.Component {
+ callSignal () {
+ this.props.methodCalled()
+ }
+ render () {
+ renderCount++
+ return (
+ <div>{this.props.foo[0].bar}</div>
+ )
+ }
+ }
+ const TestComponent = connect({
+ foo: state`foo`,
+ methodCalled: signal`methodCalled`
+ }, TestComponentClass)
+ const tree = TestUtils.renderIntoDocument((
+ <Container controller={controller}>
+ <TestComponent />
+ </Container>
+ ))
+ assert.equal(TestUtils.findRenderedDOMComponentWithTag(tree, 'div').innerHTML, 'value')
+ const component = TestUtils.findRenderedComponentWithType(tree, TestComponentClass)
+ component.callSignal()
+ assert.equal(renderCount, 2)
+ assert.equal(TestUtils.findRenderedDOMComponentWithTag(tree, 'div').innerHTML, 'value2')
+ })
it('should by default update when nested children update using COMPUTE', () => {
let renderCount = 0
const controller = Controller({ | fix(Views): fix interest in childs of arrays | cerebral_cerebral | train |
66d3cedd9310a51317bf8f39d6636e5319fcfefd | diff --git a/core/tools.php b/core/tools.php
index <HASH>..<HASH> 100644
--- a/core/tools.php
+++ b/core/tools.php
@@ -23,4 +23,20 @@ class Tools
$this->dota = new DotaTools();
}
+}
+
+class Tool {
+
+ public function getContent($url)
+ {
+ $ch = curl_init($url);
+ curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
+ $result = curl_exec($ch);
+ if (curl_getinfo($ch, CURLINFO_HTTP_CODE) != 200) {
+ $result = FALSE;
+ }
+ curl_close($ch);
+ return $result;
+ }
+
}
\ No newline at end of file
diff --git a/core/tools/apptools.php b/core/tools/apptools.php
index <HASH>..<HASH> 100644
--- a/core/tools/apptools.php
+++ b/core/tools/apptools.php
@@ -1,6 +1,6 @@
<?php
-class AppTools
+class AppTools extends Tool
{
function getAppLogoURL($app_id)
@@ -8,4 +8,24 @@ class AppTools
return 'http://cdn.steampowered.com/v/gfx/apps/' . $app_id . '/header.jpg';
}
+ function getAppDetails($appids, $cc = 'US', $language = 'english')
+ {
+ $url = 'http://store.steampowered.com/api/appdetails/?l='
+ . $language . '&cc=' . $cc . '&appids=' . implode(",", $appids);
+ return json_decode(parent::getContent($url));
+ }
+
+ function getFeaturedApps($cc = 'US', $language = 'english')
+ {
+ $url = 'http://store.steampowered.com/api/featured/?l=' . $language . '&cc=' . $cc;
+ return json_decode(parent::getContent($url));
+ }
+
+ function getFeaturedCategories($cc = 'US', $language = 'english')
+ {
+ $url = 'http://store.steampowered.com/api/featuredcategories/?l=' . $language . '&cc=' . $cc;
+ return json_decode(parent::getContent($url));
+ }
+
+
}
\ No newline at end of file
diff --git a/core/tools/dotatools.php b/core/tools/dotatools.php
index <HASH>..<HASH> 100644
--- a/core/tools/dotatools.php
+++ b/core/tools/dotatools.php
@@ -1,6 +1,6 @@
<?php
-class DotaTools
+class DotaTools extends Tool
{
function getHeroIconURL($hero_name)
diff --git a/core/tools/grouptools.php b/core/tools/grouptools.php
index <HASH>..<HASH> 100644
--- a/core/tools/grouptools.php
+++ b/core/tools/grouptools.php
@@ -3,7 +3,7 @@
define('GROUP_ID_TYPE_STEAM', 'steamid');
define('GROUP_ID_TYPE_VANITY', 'vanityid');
-class GroupTools
+class GroupTools extends Tool
{
/**
diff --git a/core/tools/usertools.php b/core/tools/usertools.php
index <HASH>..<HASH> 100644
--- a/core/tools/usertools.php
+++ b/core/tools/usertools.php
@@ -4,7 +4,7 @@ define('USER_ID_TYPE_COMMUNITY', 'communityid');
define('USER_ID_TYPE_STEAM', 'steamid');
define('USER_ID_TYPE_VANITY', 'vanityid');
-class UserTools
+class UserTools extends Tool
{
/**
@@ -124,7 +124,6 @@ class UserTools
}
-
class WrongIDException extends Exception
{
}
\ No newline at end of file | Added new functionality into app tools. | gentlecat_steam-locomotive | train |
8cf888f0f7e36579226eb32f928bf8d2a1cec95a | diff --git a/.jshintrc b/.jshintrc
index <HASH>..<HASH> 100644
--- a/.jshintrc
+++ b/.jshintrc
@@ -17,7 +17,7 @@
"loopfunc": false,
// "onevar": true,
"strict": true,
-// "undef": true,
+ "undef": true,
// "unused": true,
// "maxlen": 121,
"newcap": false,
diff --git a/lib/assets/aws/index.js b/lib/assets/aws/index.js
index <HASH>..<HASH> 100644
--- a/lib/assets/aws/index.js
+++ b/lib/assets/aws/index.js
@@ -120,9 +120,9 @@ module.exports = (function(){
internal.validateBucket = function(bucket){
this.s3.headBucket({Bucket: bucket}, function (err) {
if(err) {
- log.error(LOGGING_CATEGORY, '!!!!!!!!!!! ERROR !!!!!!!!!!!!!');
- log.error(LOGGING_CATEGORY, 'There is a problem accessing your Amazon S3 bucket.');
- log.error(LOGGING_CATEGORY, JSON.stringify(err));
+ console.log(LOGGING_CATEGORY, '!!!!!!!!!!! ERROR !!!!!!!!!!!!!');
+ console.log(LOGGING_CATEGORY, 'There is a problem accessing your Amazon S3 bucket.');
+ console.log(LOGGING_CATEGORY, JSON.stringify(err));
}
});
};
diff --git a/test/content/query.js b/test/content/query.js
index <HASH>..<HASH> 100644
--- a/test/content/query.js
+++ b/test/content/query.js
@@ -235,7 +235,6 @@ describe('Grasshopper core - content', function(){
});
it('returns distinct values within a find', function(done) {
- console.log('\n\n\n\n\n\n\n\n\n\nThis is THE test.... begin failure:');
grasshopper
.request(tokens.globalReaderToken)
.content.query({
@@ -244,8 +243,6 @@ describe('Grasshopper core - content', function(){
distinct : 'fields.label'
}
}).then(function(payload){
- console.log('inside');
- console.log(JSON.stringify(payload,null,1));
payload.results.should.deep.equal([
'Generated title',
'search test1',
@@ -259,11 +256,9 @@ describe('Grasshopper core - content', function(){
should.not.exist(err);
})
.catch(function(error) {
- console.log(error);
done(error);
})
.fail(function(error) {
- console.log(error);
done(error);
})
.done(done); | updating jshint and removing undefed vars - closes #<I> | grasshopper-cms_grasshopper-core-nodejs | train |
68498bc36ed6b92525971b6e767673f248f1ab40 | diff --git a/src/ol/event/Drag.js b/src/ol/event/Drag.js
index <HASH>..<HASH> 100644
--- a/src/ol/event/Drag.js
+++ b/src/ol/event/Drag.js
@@ -3,6 +3,7 @@ goog.provide('ol.event.Drag');
goog.require('ol.event');
goog.require('ol.event.ISequence');
+goog.require('goog.functions');
goog.require('goog.fx.Dragger');
goog.require('goog.fx.DragEvent');
goog.require('goog.fx.Dragger.EventType');
@@ -30,11 +31,9 @@ ol.event.Drag = function(target) {
this.dragger_ = dragger;
// We want to swallow the click event that gets fired after dragging.
- var stopClickRegistered = false;
- function stopClick() {
- target.unregister('click', stopClick, undefined, true);
- stopClickRegistered = false;
- return false;
+ var newSequence;
+ function unregisterClickStopper() {
+ target.unregister('click', goog.functions.FALSE, undefined, true);
}
dragger.defaultAction = function(x, y) {};
@@ -43,6 +42,7 @@ ol.event.Drag = function(target) {
evt.type = 'dragstart';
previousX = evt.clientX;
previousY = evt.clientY;
+ newSequence = true;
target.triggerEvent(evt.type, evt);
});
dragger.addEventListener(goog.fx.Dragger.EventType.DRAG, function(evt) {
@@ -51,12 +51,12 @@ ol.event.Drag = function(target) {
evt.deltaY = evt.clientY - previousY;
previousX = evt.clientX;
previousY = evt.clientY;
- if (!stopClickRegistered) {
+ if (newSequence) {
// Once we are in the drag sequence, we know that we need to
// get rid of the click event that gets fired when we are done
// dragging.
- target.register('click', stopClick, undefined, true);
- stopClickRegistered = true;
+ target.register('click', goog.functions.FALSE, undefined, true);
+ newSequence = false;
}
target.triggerEvent(evt.type, evt);
});
@@ -64,10 +64,12 @@ ol.event.Drag = function(target) {
evt.target = element;
evt.type = 'dragend';
target.triggerEvent(evt.type, evt);
+ // Unregister the click stopper in the next cycle
+ window.setTimeout(unregisterClickStopper, 0);
});
// Don't swallow the click event if our sequence cancels early.
dragger.addEventListener(
- goog.fx.Dragger.EventType.EARLY_CANCEL, stopClick
+ goog.fx.Dragger.EventType.EARLY_CANCEL, unregisterClickStopper
);
}; | Fixing the way we prevent the extra click. | openlayers_openlayers | train |
2293f6245ed451ed067744982105ad3fe5805215 | diff --git a/src/streamlink_cli/argparser.py b/src/streamlink_cli/argparser.py
index <HASH>..<HASH> 100644
--- a/src/streamlink_cli/argparser.py
+++ b/src/streamlink_cli/argparser.py
@@ -572,7 +572,7 @@ def build_parser():
{{time}}
The current timestamp, which can optionally be formatted via {{time:format}}.
This format parameter string is passed to Python's datetime.strftime() method,
- so all usual time directives are available. The default format is "%Y-%m-%d_%H-%M-%S".
+ so all usual time directives are available. The default format is "%%Y-%%m-%%d_%%H-%%M-%%S".
Examples: | cli.argparser: Fixed ValueError for streamlink --help
`ValueError: unsupported format character 'Y' (0x<I>) at index <I>` | streamlink_streamlink | train |
d314d92e988056969ae7297c081e6e5d8a8e16d0 | diff --git a/osmcha/changeset.py b/osmcha/changeset.py
index <HASH>..<HASH> 100644
--- a/osmcha/changeset.py
+++ b/osmcha/changeset.py
@@ -44,16 +44,16 @@ def get_metadata(changeset):
return ET.fromstring(requests.get(url).content).getchildren()[0]
-def get_user_details(changeset):
- """Get useful user details and return it as a dictionary.
+def get_user_details(user):
+ """Takes a user's name as input and returns user details as a dictionary.
- API: http://hdyc.neis-one.org/
+ API used: http://hdyc.neis-one.org/
"""
- url = 'http://hdyc.neis-one.org/user/{}'.format(changeset.get('user'))
+ url = 'http://hdyc.neis-one.org/user/{}'.format(user)
user_details = json.loads(requests.get(url).content)
return {
- 'blocks': user_details['contributor']['blocks'],
'name': user_details['contributor']['name'],
+ 'blocks': int(user_details['contributor']['blocks']),
}
@@ -122,7 +122,11 @@ class Analyse(object):
"""Analyse a changeset and define if it is suspect."""
def __init__(self, changeset):
if type(changeset) in [int, str]:
- self.set_fields(changeset_info(get_metadata(changeset)))
+ # self.set_fields(changeset_info(get_metadata(changeset)))
+ changeset_details = changeset_info(get_metadata(changeset))
+ user = changeset_details['user']
+ changeset_details['user_details'] = get_user_details(user)
+ self.set_fields(changeset_details)
elif type(changeset) == dict:
self.set_fields(changeset)
else:
@@ -148,6 +152,7 @@ class Analyse(object):
self.suspicion_reasons = []
self.is_suspect = False
self.powerfull_editor = False
+ self.user_details = changeset.get('user_details')
def full_analysis(self):
"""Execute count and verify_words functions."""
diff --git a/tests/test_mod.py b/tests/test_mod.py
index <HASH>..<HASH> 100644
--- a/tests/test_mod.py
+++ b/tests/test_mod.py
@@ -303,8 +303,16 @@ def test_analyse_mass_deletion():
def test_get_user_details():
- c = ChangesetList('tests/245.osm.gz')
- changeset = c.changesets[0]
- user_details = get_user_details(changeset)
- assert 'GarrettB' in user_details['name']
- assert user_details['blocks'] == "0"
+ user = 'GarrettB'
+ user_details = get_user_details(user)
+ assert user in user_details['name']
+ assert user_details['blocks'] == 0
+
+
+def test_analyse_user_details():
+ ch = Analyse(31450443)
+ ch.full_analysis()
+ assert ch.user_details
+ print ch.user_details['name']
+ assert ch.user_details['name'] == 'Tobsen Laufi'
+ assert ch.user_details['blocks'] == 0 | Return user_details as part of the Analyze object | willemarcel_osmcha | train |
ff1ce823349e9cf8d56f4111ad772eb616f7b923 | diff --git a/buff/force_field.py b/buff/force_field.py
index <HASH>..<HASH> 100644
--- a/buff/force_field.py
+++ b/buff/force_field.py
@@ -80,6 +80,20 @@ class BuffForceField(dict):
self._old_hash = new_hash
return self._parameter_struct_dict
+ @property
+ def _flattened_parameters(self):
+ fp_list = []
+ for (res, atom_dict) in sorted(self.parameter_struct_dict.items()):
+ for (atom, struct) in sorted(atom_dict.items()):
+ fp_list.append(((res, atom), struct))
+ return fp_list
+
+ @property
+ def parameter_key(self):
+ fp_list = self._flattened_parameters
+ parameter_key = {k: v for v, k in enumerate([x[0] for x in fp_list])}
+ return parameter_key
+
def _make_ff_params_dict(self):
"""Makes a dictionary containing PyAtomData structs for each element in the force field. | Added functions for finding the indices of parameters that can be assigned to atom objects, allowing faster scoring. | woolfson-group_isambard | train |
e24162dba338b30408b86d3a65bf4886a614aeed | diff --git a/src/Probability/Distribution/Continuous/Gamma.php b/src/Probability/Distribution/Continuous/Gamma.php
index <HASH>..<HASH> 100644
--- a/src/Probability/Distribution/Continuous/Gamma.php
+++ b/src/Probability/Distribution/Continuous/Gamma.php
@@ -73,4 +73,21 @@ class Gamma extends Continuous
return $ฮณ / $ฮโฎkโฏ;
}
+
+ /**
+ * Mean of the distribution
+ *
+ * ฮผ = k ฮธ
+ *
+ * @param number $k shape parameter k > 0
+ * @param number $ฮธ scale parameter ฮธ > 0
+ *
+ * @return number
+ */
+ public static function mean($k, $ฮธ)
+ {
+ Support::checkLimits(self::LIMITS, ['k' => $k, 'ฮธ' => $ฮธ]);
+
+ return $k * $ฮธ;
+ }
}
diff --git a/tests/Probability/Distribution/Continuous/GammaTest.php b/tests/Probability/Distribution/Continuous/GammaTest.php
index <HASH>..<HASH> 100644
--- a/tests/Probability/Distribution/Continuous/GammaTest.php
+++ b/tests/Probability/Distribution/Continuous/GammaTest.php
@@ -72,4 +72,23 @@ class GammaTest extends \PHPUnit_Framework_TestCase
[4, 0.5, 6, 0.7517869210100764165283],
];
}
+
+ /**
+ * @dataProvider dataProviderForMean
+ * Test data created with mental arithmetic
+ */
+ public function testMean($k, $ฮธ, $ฮผ)
+ {
+ $this->assertEquals($ฮผ, Gamma::mean($k, $ฮธ), '', 0.0001);
+ }
+
+ public function dataProviderForMean(): array
+ {
+ return [
+ [1, 1, 1.0],
+ [1, 2, 2.0],
+ [2, 1, 2.0],
+ [9, 0.5, 4.5],
+ ];
+ }
} | Add mean to gamma distribution (#<I>)
* add mean to gamma distribution
* fix cs | markrogoyski_math-php | train |
7f47dbea72052a1cb1d563d16afc315d929f0c85 | diff --git a/lib/pay/billable/stripe.rb b/lib/pay/billable/stripe.rb
index <HASH>..<HASH> 100644
--- a/lib/pay/billable/stripe.rb
+++ b/lib/pay/billable/stripe.rb
@@ -10,7 +10,7 @@ module Pay
end
def create_stripe_subscription(name, plan, options={})
- stripe_sub = customer.subscriptions.create(plan: plan)
+ stripe_sub = customer.subscriptions.create(plan: plan, trial_from_plan: true)
subscription = create_subscription(stripe_sub, 'stripe', name, plan)
subscription
end
diff --git a/lib/pay/subscription/braintree.rb b/lib/pay/subscription/braintree.rb
index <HASH>..<HASH> 100644
--- a/lib/pay/subscription/braintree.rb
+++ b/lib/pay/subscription/braintree.rb
@@ -5,7 +5,8 @@ module Pay
subscription = processor_subscription
if on_trial?
- braintree_cancel_now!
+ gateway.subscription.cancel(processor_subscription.id)
+ update(ends_at: trial_ends_at)
else
gateway.subscription.update(subscription.id, {
number_of_billing_cycles: subscription.current_billing_cycle
@@ -20,21 +21,36 @@ module Pay
end
def braintree_resume
- subscription = processor_subscription
+ if cancelled? && on_trial?
+ duration = trial_ends_at.to_date - Date.today
+
+ owner.subscribe(
+ name,
+ processor_plan,
+ processor,
+ trial_period: true,
+ trial_duration: duration,
+ trial_duration_unit: :day
+ )
- gateway.subscription.update(subscription.id, {
- never_expires: true,
- number_of_billing_cycles: nil
- })
+ else
+ subscription = processor_subscription
+
+ gateway.subscription.update(subscription.id, {
+ never_expires: true,
+ number_of_billing_cycles: nil
+ })
+ end
end
def braintree_swap(plan)
if on_grace_period? && processor_plan == plan
resume
+ return
end
if !active?
- owner.subscribe(name, plan, 'braintree', trial_period: false)
+ owner.subscribe(name, plan, processor, trial_period: false)
return
end
diff --git a/lib/pay/subscription/stripe.rb b/lib/pay/subscription/stripe.rb
index <HASH>..<HASH> 100644
--- a/lib/pay/subscription/stripe.rb
+++ b/lib/pay/subscription/stripe.rb
@@ -3,12 +3,13 @@ module Pay
module Stripe
def stripe_cancel
subscription = processor_subscription.delete(at_period_end: true)
- update(ends_at: Time.at(subscription.current_period_end))
+ new_ends_at = on_trial? ? trial_ends_at : Time.at(subscription.current_period_end)
+ update(ends_at: new_ends_at)
end
def stripe_cancel_now!
subscription = processor_subscription.delete
- update(ends_at: Time.at(subscription.current_period_end))
+ update(ends_at: Time.zone.now)
end
def stripe_resume
diff --git a/test/models/subscription_test.rb b/test/models/subscription_test.rb
index <HASH>..<HASH> 100644
--- a/test/models/subscription_test.rb
+++ b/test/models/subscription_test.rb
@@ -2,18 +2,18 @@ require 'test_helper'
class Pay::Subscription::Test < ActiveSupport::TestCase
setup do
- @subscription = Subscription.new processor: 'stripe'
+ @subscription = ::Subscription.new processor: 'stripe'
end
test 'belongs to the owner' do
- klass = Subscription.reflections['owner'].options[:class_name]
+ klass = ::Subscription.reflections['owner'].options[:class_name]
assert klass, 'User'
end
test '.for_name(name) scope' do
owner = User.create
- subscription1 = Subscription.create!(
+ subscription1 = ::Subscription.create!(
name: 'default',
owner: owner,
processor: 'stripe',
@@ -22,7 +22,7 @@ class Pay::Subscription::Test < ActiveSupport::TestCase
quantity: '1'
)
- subscription2 = Subscription.create!(
+ subscription2 = ::Subscription.create!(
name: 'superior',
owner: owner,
processor: 'stripe',
@@ -31,8 +31,8 @@ class Pay::Subscription::Test < ActiveSupport::TestCase
quantity: '1'
)
- assert_includes Subscription.for_name('default'), subscription1
- refute_includes Subscription.for_name('default'), subscription2
+ assert_includes ::Subscription.for_name('default'), subscription1
+ refute_includes ::Subscription.for_name('default'), subscription2
end
test 'active trial' do
@@ -103,10 +103,7 @@ class Pay::Subscription::Test < ActiveSupport::TestCase
end
test 'cancel_now!' do
- expiration = DateTime.now
-
cancelled_stripe = mock('cancelled_stripe_subscription')
- cancelled_stripe.expects(:current_period_end).returns(expiration)
stripe_sub = mock('stripe_subscription')
stripe_sub.expects(:delete).returns(cancelled_stripe)
@@ -114,7 +111,7 @@ class Pay::Subscription::Test < ActiveSupport::TestCase
@subscription.stubs(:processor_subscription).returns(stripe_sub)
@subscription.cancel_now!
- assert @subscription.ends_at, expiration
+ assert @subscription.ends_at <= Time.zone.now
end
test 'resume on grace period' do
diff --git a/test/pay/billable_test.rb b/test/pay/billable_test.rb
index <HASH>..<HASH> 100644
--- a/test/pay/billable_test.rb
+++ b/test/pay/billable_test.rb
@@ -103,7 +103,7 @@ class Pay::Billable::Test < ActiveSupport::TestCase
end
test 'getting a subscription by default name' do
- subscription = Subscription.create!(
+ subscription = ::Subscription.create!(
name: 'default',
owner: @billable,
processor: 'stripe', | Fix braintree cancel during trial, stripe cancel_now and tests | jasoncharnes_pay | train |
56735f125c39db909df45558ead060094e84f729 | diff --git a/src/JoomlaBrowser.php b/src/JoomlaBrowser.php
index <HASH>..<HASH> 100644
--- a/src/JoomlaBrowser.php
+++ b/src/JoomlaBrowser.php
@@ -149,7 +149,7 @@ class JoomlaBrowser extends WebDriver
$this->debug('I click Login button');
$this->click($this->locator->adminLoginButton);
$this->debug('I wait to see Administrator Control Panel');
- $this->waitForText('Control Panel', 5, $this->locator->controlPanelLocator);
+ $this->waitForText('Control Panel', TIMEOUT, $this->locator->controlPanelLocator);
if ($useSnapshot)
{ | Give more time for control panel to load | joomla-projects_joomla-browser | train |
e4cc8a6c36ea97a52d404a70b05979220d86c2c5 | diff --git a/spec/factories/accounts.rb b/spec/factories/accounts.rb
index <HASH>..<HASH> 100644
--- a/spec/factories/accounts.rb
+++ b/spec/factories/accounts.rb
@@ -3,17 +3,30 @@ FactoryGirl.define do
code '0000'
title 'Test Account'
association :account_type
- end
-
- factory :accounts_payable, :parent => :account do
- code '2000'
- title 'Accounts Payable'
- association :account_type, :factory => :outside_capital
- end
+ initialize_with { Account.find_or_create_by_code(code)}
+
+ factory :accounts_payable, :parent => :account do
+ code '2000'
+ title 'Accounts Payable'
+ association :account_type
+ end
+
+ factory :cash_account, :parent => :account do
+ code '1000'
+ title 'Cash'
+ association :account_type
+ end
+
+ factory :debit_account, :parent => :account do
+ code '1100'
+ title 'Account Receivable'
+ association :account_type, :factory => :current_assets
+ end
- factory :cash_account, :parent => :account do
- code '1000'
- title 'Cash'
- association :account_type, :factory => :current_assets
+ factory :earnings_account, :parent => :account do
+ code '3200'
+ title 'Revenue Account'
+ association :account_type, :factory => :earnings
+ end
end
end
diff --git a/spec/factories/bookings.rb b/spec/factories/bookings.rb
index <HASH>..<HASH> 100644
--- a/spec/factories/bookings.rb
+++ b/spec/factories/bookings.rb
@@ -5,5 +5,17 @@ FactoryGirl.define do
amount 37.50
association :debit_account, :factory => :accounts_payable
association :credit_account, :factory => :cash_account
+
+ factory :invoice_booking do
+ title 'Invoice'
+ association :debit_account, :factory => :debit_account
+ association :credit_account, :factory => :earnings_account
+ end
+
+ factory :payment_booking do
+ title 'Payment'
+ association :debit_account, :factory => :cash_account
+ association :credit_account, :factory => :debit_account
+ end
end
end | Refactor and enhance factoriesf for tests. | huerlisi_has_accounts | train |
cf8e109fd4dcee6d85fcbc36534948a2245c944f | diff --git a/test/unit/krane/psych_k8s_patch_test.rb b/test/unit/krane/psych_k8s_patch_test.rb
index <HASH>..<HASH> 100644
--- a/test/unit/krane/psych_k8s_patch_test.rb
+++ b/test/unit/krane/psych_k8s_patch_test.rb
@@ -9,7 +9,7 @@ class PsychK8sPatchTest < Krane::TestCase
'a: "-123e4"',
'a: "123e+4"',
'a: "123e-4"',
- 'a: "123.0e-4"'
+ 'a: "123.0e-4"',
]
EXPECTED_DEACTIVATED = [
@@ -19,7 +19,7 @@ class PsychK8sPatchTest < Krane::TestCase
%(---\n- a: "-123e4"\n), # Psych sees this as non-numeric; deviates from YAML 1.2 spec; quoted due to '-' :|
%(---\n- a: 123e+4\n), # Psych sees this as non-numeric; deviates from YAML 1.2 spec :(
%(---\n- a: 123e-4\n), # Psych sees this as non-numeric; deviates from YAML 1.2 spec :(
- %(---\n- a: '123.0e-4'\n) # Psych sees this as numeric; encapsulated with single quotes :)
+ %(---\n- a: '123.0e-4'\n), # Psych sees this as numeric; encapsulated with single quotes :)
]
EXPECTED_ACTIVATED = [
@@ -29,7 +29,7 @@ class PsychK8sPatchTest < Krane::TestCase
%(---\n- a: "-123e4"\n),
%(---\n- a: "123e+4"\n),
%(---\n- a: "123e-4"\n),
- %(---\n- a: '123.0e-4'\n)
+ %(---\n- a: '123.0e-4'\n),
]
def test_dump | Fixing Style/TrailingCommaInArrayLiteral linter offenses. | Shopify_kubernetes-deploy | train |
d1b077a9c4ef19bdddbc4444e19e6f16169c226f | diff --git a/tasks/run-command.js b/tasks/run-command.js
index <HASH>..<HASH> 100644
--- a/tasks/run-command.js
+++ b/tasks/run-command.js
@@ -6,10 +6,7 @@ module.exports = function(gulp, config) {
var spawn = require('child_process').spawn;
var env = _.extend({}, process.env, config.server.environmentVariables);
var argv = process.argv.slice(2);
- var proc = spawn('node', [command].concat(argv), { env: env });
- proc.stdout.pipe(process.stdout);
- proc.stdin.pipe(process.stdin);
- proc.stderr.pipe(process.stderr);
+ var proc = spawn('node', [command].concat(argv), { env: env, stdio: 'inherit' });
proc.on('close', function (code) {
if (code === 0) { | feat(run-command): better handling of stdio | emartech_boar-tasks-server | train |
fe5f851dbc82d21c18f3988dada63c3bf1fbe857 | diff --git a/iuwt_convolution.py b/iuwt_convolution.py
index <HASH>..<HASH> 100644
--- a/iuwt_convolution.py
+++ b/iuwt_convolution.py
@@ -29,7 +29,7 @@ def fft_convolve(in1, in2, use_gpu=False, conv_mode="linear"):
if conv_mode=="linear":
fft_in1 = pad_array(in1)
- fft_in1 = gpu_r2c_fft(fft_in1, load_gpu=True)
+ fft_in1 = gpu_r2c_fft(fft_in1, store_on_gpu=True)
fft_in2 = in2
conv_in1_in2 = fft_in1*fft_in2
@@ -41,7 +41,7 @@ def fft_convolve(in1, in2, use_gpu=False, conv_mode="linear"):
return np.fft.fftshift(conv_in1_in2)[out1_slice]
elif conv_mode=="circular":
- fft_in1 = gpu_r2c_fft(in1, load_gpu=True)
+ fft_in1 = gpu_r2c_fft(in1, store_on_gpu=True)
fft_in2 = in2
conv_in1_in2 = fft_in1*fft_in2
@@ -62,14 +62,14 @@ def fft_convolve(in1, in2, use_gpu=False, conv_mode="linear"):
elif conv_mode=="circular":
return np.fft.fftshift(np.fft.irfft2(in2*np.fft.rfft2(in1)))
-def gpu_r2c_fft(in1, is_gpuarray=False, load_gpu=False):
+def gpu_r2c_fft(in1, is_gpuarray=False, store_on_gpu=False):
"""
This function makes use of the scikits implementation of the FFT for GPUs to take the real to complex FFT.
INPUTS:
- in1 (no default): The array on which the FFT is to be performed.
- is_gpuarray (default=True): Boolean specifier for whether or not input is on the gpu.
- load_gpu (default=False): Boolean specifier for whether the result is to be left on the gpu or not.
+ in1 (no default): The array on which the FFT is to be performed.
+ is_gpuarray (default=True): Boolean specifier for whether or not input is on the gpu.
+ store_on_gpu (default=False): Boolean specifier for whether the result is to be left on the gpu or not.
OUTPUTS:
gpu_out1 (no default): The gpu array containing the result.
@@ -89,19 +89,19 @@ def gpu_r2c_fft(in1, is_gpuarray=False, load_gpu=False):
gpu_plan = Plan(gpu_in1.shape, np.float32, np.complex64)
fft(gpu_in1, gpu_out1, gpu_plan)
- if load_gpu:
+ if store_on_gpu:
return gpu_out1
else:
return gpu_out1.get()
-def gpu_c2r_ifft(in1, is_gpuarray=False, load_gpu=False):
+def gpu_c2r_ifft(in1, is_gpuarray=False, store_on_gpu=False):
"""
This function makes use of the scikits implementation of the FFT for GPUs to take the complex to real IFFT.
INPUTS:
- in1 (no default): The array on which the IFFT is to be performed.
- is_gpuarray (default=True): Boolean specifier for whether or not input is on the gpu.
- load_gpu (default=False): Boolean specifier for whether the result is to be left on the gpu or not.
+ in1 (no default): The array on which the IFFT is to be performed.
+ is_gpuarray (default=True): Boolean specifier for whether or not input is on the gpu.
+ store_on_gpu (default=False): Boolean specifier for whether the result is to be left on the gpu or not.
OUTPUTS:
gpu_out1 (no default): The gpu array containing the result.
@@ -121,7 +121,7 @@ def gpu_c2r_ifft(in1, is_gpuarray=False, load_gpu=False):
gpu_plan = Plan(output_size, np.complex64, np.float32)
ifft(gpu_in1, gpu_out1, gpu_plan, True)
- if load_gpu:
+ if store_on_gpu:
return gpu_out1
else:
return gpu_out1.get() | Renamed a variable for clarity. | ratt-ru_PyMORESANE | train |
66c3b1527a2c488a55b7a623c941711f19eddd23 | diff --git a/lib/basemate/ui/core/version.rb b/lib/basemate/ui/core/version.rb
index <HASH>..<HASH> 100644
--- a/lib/basemate/ui/core/version.rb
+++ b/lib/basemate/ui/core/version.rb
@@ -1,7 +1,7 @@
module Basemate
module Ui
module Core
- VERSION = '0.5.1'
+ VERSION = '0.6.0-pre.1'
end
end
end | Bump basemate-ui-core to <I>-pre<I> | basemate_matestack-ui-core | train |
8a98f117f5ff78193a4e7b4e3fe8c0e7c5c1b70b | diff --git a/api/app/app.go b/api/app/app.go
index <HASH>..<HASH> 100644
--- a/api/app/app.go
+++ b/api/app/app.go
@@ -15,6 +15,7 @@ import (
"github.com/globocom/tsuru/db"
"github.com/globocom/tsuru/log"
"github.com/globocom/tsuru/repository"
+ "io"
"labix.org/v2/mgo/bson"
"launchpad.net/goyaml"
"os/exec"
@@ -318,10 +319,10 @@ func restart(a *App) ([]byte, error) {
//installDeps runs the dependencies hook for the app
//and returns your output.
-func installDeps(a *App) ([]byte, error) {
+func installDeps(a *App, stdout, stderr io.Writer) ([]byte, error) {
u := a.unit()
a.log("executting hook dependencies")
- out, err := u.executeHook(nil, nil, "dependencies")
+ out, err := u.executeHook(stdout, stderr, "dependencies")
a.log(string(out))
if err != nil {
return out, err
diff --git a/api/app/app_test.go b/api/app/app_test.go
index <HASH>..<HASH> 100644
--- a/api/app/app_test.go
+++ b/api/app/app_test.go
@@ -549,11 +549,63 @@ func (s *S) TestInstallDeps(c *C) {
err = createApp(&a)
c.Assert(err, IsNil)
defer db.Session.Apps().Remove(bson.M{"name": a.Name})
- out, err := installDeps(&a)
+ out, err := installDeps(&a, nil, nil)
c.Assert(err, IsNil)
c.Assert(string(out), Equals, "ssh -o StrictHostKeyChecking no -q 4 /var/lib/tsuru/hooks/dependencies")
}
+func (s *S) TestInstallDepsWithCustomStdout(c *C) {
+ a := App{
+ Name: "someApp",
+ Framework: "django",
+ Teams: []string{s.team.Name},
+ Units: []Unit{
+ Unit{
+ AgentState: "started",
+ MachineAgentState: "running",
+ InstanceState: "running",
+ Machine: 4,
+ },
+ },
+ }
+ err := createApp(&a)
+ c.Assert(err, IsNil)
+ defer db.Session.Apps().Remove(bson.M{"name": a.Name})
+ tmpdir, err := commandmocker.Add("juju", "$*")
+ c.Assert(err, IsNil)
+ defer commandmocker.Remove(tmpdir)
+ var b bytes.Buffer
+ _, err = installDeps(&a, &b, nil)
+ c.Assert(err, IsNil)
+ c.Assert(b.String(), Matches, `.* /var/lib/tsuru/hooks/dependencies`)
+}
+
+func (s *S) TestInstallDepsWithCustomStderr(c *C) {
+ a := App{
+ Name: "someApp",
+ Framework: "django",
+ Teams: []string{s.team.Name},
+ Units: []Unit{
+ Unit{
+ AgentState: "started",
+ MachineAgentState: "running",
+ InstanceState: "running",
+ Machine: 4,
+ },
+ },
+ }
+ err := createApp(&a)
+ c.Assert(err, IsNil)
+ defer db.Session.Apps().Remove(bson.M{"name": a.Name})
+ tmpdir, err := commandmocker.Error("juju", "$*", 42)
+ c.Assert(err, IsNil)
+ defer commandmocker.Remove(tmpdir)
+ var b bytes.Buffer
+ _, err = installDeps(&a, nil, &b)
+ c.Assert(err, NotNil)
+ c.Assert(b.String(), Matches, `.* /var/lib/tsuru/hooks/dependencies`)
+}
+
func (s *S) TestRestart(c *C) {
tmpdir, err := commandmocker.Add("juju", "$*")
c.Assert(err, IsNil)
diff --git a/api/app/handler.go b/api/app/handler.go
index <HASH>..<HASH> 100644
--- a/api/app/handler.go
+++ b/api/app/handler.go
@@ -101,7 +101,7 @@ func CloneRepositoryHandler(w http.ResponseWriter, r *http.Request) error {
if err != nil {
return err
}
- out, err = installDeps(&app)
+ out, err = installDeps(&app, nil, nil)
if err != nil {
write(w, out)
return err | Running installDeps with a custom stderr and stdout.
Related to #<I>. | tsuru_tsuru | train |
f468822feba6081524ca6783f9489c8ba4dc8d9c | diff --git a/raven/__init__.py b/raven/__init__.py
index <HASH>..<HASH> 100644
--- a/raven/__init__.py
+++ b/raven/__init__.py
@@ -12,7 +12,7 @@ import os.path
__all__ = ('VERSION', 'Client', 'get_version')
-VERSION = '5.26.0'
+VERSION = '5.27.0.dev0'
def _get_git_revision(path): | This is <I>.dev0 | getsentry_raven-python | train |
96f5bea8957a8b39cd24413ec3ee5b2409e00566 | diff --git a/src/plone/app/mosaic/browser/main_template.py b/src/plone/app/mosaic/browser/main_template.py
index <HASH>..<HASH> 100644
--- a/src/plone/app/mosaic/browser/main_template.py
+++ b/src/plone/app/mosaic/browser/main_template.py
@@ -247,18 +247,18 @@ class MainTemplate(BrowserView):
@property
def template(self):
try:
- layout = getMultiAdapter((self.context, self.request),
- name='page-site-layout').index()
+ return self.layout
except NotFound:
if self.request.form.get('ajax_load'):
return self.ajax_template
else:
return self.main_template
- return self._cooked_template(layout)
-
+ @property
@volatile.cache(cacheKey, volatile.store_on_context)
- def _cooked_template(self, layout):
+ def layout(self):
+ layout = getMultiAdapter((self.context, self.request),
+ name='page-site-layout').index()
cooked = cook_layout(layout, self.request.get('ajax_load'))
pt = ViewPageTemplateString(cooked)
bound_pt = pt.__get__(self, type(self)) | Fix layout caching refactoring | plone_plone.app.mosaic | train |
b0ccb26d9aac3a4c005480eff80adf06dfaf9501 | diff --git a/src/Providers/RouterServiceProvider.php b/src/Providers/RouterServiceProvider.php
index <HASH>..<HASH> 100644
--- a/src/Providers/RouterServiceProvider.php
+++ b/src/Providers/RouterServiceProvider.php
@@ -53,6 +53,8 @@ class RouterServiceProvider extends ServiceProvider
$response = $this->app->get('router')->match($request);
+ $response = apply_filters('lumberjack_router_response', $response, $request);
+
if ($response->getStatusCode() === 404) {
return;
}
diff --git a/tests/Unit/Providers/RouterServiceProviderTest.php b/tests/Unit/Providers/RouterServiceProviderTest.php
index <HASH>..<HASH> 100644
--- a/tests/Unit/Providers/RouterServiceProviderTest.php
+++ b/tests/Unit/Providers/RouterServiceProviderTest.php
@@ -3,6 +3,7 @@
namespace Rareloop\Lumberjack\Test\Providers;
use Brain\Monkey;
+use Brain\Monkey\Filters;
use Brain\Monkey\Functions;
use PHPUnit\Framework\TestCase;
use Rareloop\Lumberjack\Application;
@@ -11,6 +12,7 @@ use Rareloop\Lumberjack\Providers\RouterServiceProvider;
use Rareloop\Lumberjack\Test\Unit\BrainMonkeyPHPUnitIntegration;
use Rareloop\Router\Router;
use Zend\Diactoros\Request;
+use Zend\Diactoros\Response\HtmlResponse;
use Zend\Diactoros\Response\TextResponse;
use Zend\Diactoros\ServerRequest;
use \Mockery;
@@ -142,6 +144,35 @@ class RouterServiceProviderTest extends TestCase
$provider->processRequest(new ServerRequest([], [], '/test/123', 'GET'));
}
+ /** @test */
+ public function lumberjack_router_response_filter_is_fired_when_request_is_processed()
+ {
+ Functions\expect('is_admin')->once()->andReturn(false);
+ $this->setSiteUrl('http://example.com/sub-path/');
+
+ $request = new ServerRequest([], [], '/test/123', 'GET');
+ $response = new HtmlResponse('testing 123');
+
+ $app = Mockery::mock(Application::class.'[shutdown]', [__DIR__.'/..']);
+ $app->shouldReceive('shutdown')->times(1)->with($response);
+ $lumberjack = new Lumberjack($app);
+ $provider = new RouterServiceProvider($app);
+
+ $app->register($provider);
+ $lumberjack->bootstrap();
+
+ $router = Mockery::mock(Router::class.'[match]', $app);
+ $router->shouldReceive('match')->andReturn($response)->once();
+
+ $app->bind('router', $router);
+
+ Filters\expectApplied('lumberjack_router_response')
+ ->once()
+ ->with($response, $request);
+
+ $provider->processRequest($request);
+ }
+
private function setSiteUrl($url) {
Functions\when('get_bloginfo')->alias(function ($key) use ($url) {
if ($key === 'url') { | Enable filtering of Router Response object
Provides an extension point so that the application can influence a response. This is useful for handling global middleware-esque behaviour. | Rareloop_lumberjack-core | train |
7a8137e9d7d9491066018c0960e2673bc1dabc9a | diff --git a/mod/lesson/db/install.xml b/mod/lesson/db/install.xml
index <HASH>..<HASH> 100644
--- a/mod/lesson/db/install.xml
+++ b/mod/lesson/db/install.xml
@@ -1,5 +1,5 @@
<?xml version="1.0" encoding="UTF-8" ?>
-<XMLDB PATH="mod/lesson/db" VERSION="20070131" COMMENT="XMLDB file for Moodle mod/lesson"
+<XMLDB PATH="mod/lesson/db" VERSION="20070201" COMMENT="XMLDB file for Moodle mod/lesson"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="../../../lib/xmldb/xmldb.xsd"
>
@@ -103,7 +103,7 @@
<FIELD NAME="answerid" TYPE="int" LENGTH="10" NOTNULL="true" UNSIGNED="true" DEFAULT="0" SEQUENCE="false" ENUM="false" PREVIOUS="userid" NEXT="retry"/>
<FIELD NAME="retry" TYPE="int" LENGTH="3" NOTNULL="true" UNSIGNED="true" DEFAULT="0" SEQUENCE="false" ENUM="false" PREVIOUS="answerid" NEXT="correct"/>
<FIELD NAME="correct" TYPE="int" LENGTH="10" NOTNULL="true" UNSIGNED="true" DEFAULT="0" SEQUENCE="false" ENUM="false" PREVIOUS="retry" NEXT="useranswer"/>
- <FIELD NAME="useranswer" TYPE="text" LENGTH="small" NOTNULL="true" SEQUENCE="false" ENUM="false" PREVIOUS="correct" NEXT="timeseen"/>
+ <FIELD NAME="useranswer" TYPE="text" LENGTH="small" NOTNULL="false" SEQUENCE="false" ENUM="false" PREVIOUS="correct" NEXT="timeseen"/>
<FIELD NAME="timeseen" TYPE="int" LENGTH="10" NOTNULL="true" UNSIGNED="true" DEFAULT="0" SEQUENCE="false" ENUM="false" PREVIOUS="useranswer"/>
</FIELDS>
<KEYS>
diff --git a/mod/lesson/db/upgrade.php b/mod/lesson/db/upgrade.php
index <HASH>..<HASH> 100644
--- a/mod/lesson/db/upgrade.php
+++ b/mod/lesson/db/upgrade.php
@@ -34,6 +34,17 @@ function xmldb_lesson_upgrade($oldversion=0) {
$result = $result && change_field_notnull($table, $field);
}
+ if ($result && $oldversion < 2006091803) {
+
+ /// Changing nullability of field useranswer on table lesson_attempts to null
+ $table = new XMLDBTable('lesson_attempts');
+ $field = new XMLDBField('useranswer');
+ $field->setAttributes(XMLDB_TYPE_TEXT, 'small', null, null, null, null, null, null, 'correct');
+
+ /// Launch change of nullability for field useranswer
+ $result = $result && change_field_notnull($table, $field);
+ }
+
return $result;
}
diff --git a/mod/lesson/version.php b/mod/lesson/version.php
index <HASH>..<HASH> 100644
--- a/mod/lesson/version.php
+++ b/mod/lesson/version.php
@@ -8,7 +8,7 @@
* @package lesson
**/
-$module->version = 2006091802; // The current module version (Date: YYYYMMDDXX)
+$module->version = 2006091803; // The current module version (Date: YYYYMMDDXX)
$module->requires = 2006080900; // Requires this Moodle version
$module->cron = 0; // Period for cron to check this module (secs) | Merged fix for MDL-<I> from MOODLE_<I>_STABLE branch | moodle_moodle | train |
d8d74953995d1701ff065e4ae4f8c81748f39793 | diff --git a/lib/attachProof.js b/lib/attachProof.js
index <HASH>..<HASH> 100644
--- a/lib/attachProof.js
+++ b/lib/attachProof.js
@@ -39,8 +39,6 @@ const {Ed25519Signature2020} = require('@digitalbazaar/ed25519-signature-2020');
* @param {object} [options.authDoc] - Auth DID Doc, required if using
* an accelerator service.
* @param {string} options.mode - Ledger mode ('test', 'live' etc).
- * @param {string} options.invocationTarget - The invocationTarget
- * (should be the ledger id or the id of a record on the ledger).
*
* @returns {Promise<object>} - An operation document with proofs attached.
*/ | Remove jsdoc for invocationTarget. | veres-one_did-veres-one | train |
e55da245d9414f4250463b66c3421ad65df40025 | diff --git a/octodns/provider/ns1.py b/octodns/provider/ns1.py
index <HASH>..<HASH> 100644
--- a/octodns/provider/ns1.py
+++ b/octodns/provider/ns1.py
@@ -341,6 +341,9 @@ class Ns1Provider(BaseProvider):
'ASIAPAC': 'AS',
'EUROPE': 'EU',
'SOUTH-AMERICA': 'SA',
+ # continent NA has been handled as part of Geofence Country filter
+ # starting from v0.9.13. These below US-* just need to continue to
+ # exist here so it doesn't break the ugrade path
'US-CENTRAL': 'NA',
'US-EAST': 'NA',
'US-WEST': 'NA', | comment for why US-* need to continue to exist under _REGION_TO_CONTINENT | github_octodns | train |
b33cc6c1e1eeaaf15dea0195e8b39d1c86c43b7d | diff --git a/src/Builder.php b/src/Builder.php
index <HASH>..<HASH> 100644
--- a/src/Builder.php
+++ b/src/Builder.php
@@ -70,10 +70,10 @@ class Builder
if (isset($this->data['filters'])) {
foreach ($this->data['filters'] as $field => $data) {
- $comparison = key($data);
- $value = reset($data);
- if (array_key_exists($comparison, $this->filters)) {
- $filters[] = new $this->filters[$comparison]($field, $value);
+ foreach($data as $operator => $value) {
+ if (array_key_exists($operator, $this->filters)) {
+ $filters[] = new $this->filters[$operator]($field, $value);
+ }
}
}
}
diff --git a/src/Transformer.php b/src/Transformer.php
index <HASH>..<HASH> 100644
--- a/src/Transformer.php
+++ b/src/Transformer.php
@@ -68,10 +68,10 @@ class Transformer
if (isset($data['filters'])) {
foreach ($data['filters'] as $field => $data) {
- $comparison = key($data);
- $value = reset($data);
- if (array_key_exists($comparison, $this->filters)) {
- $filters[] = new $this->filters[$comparison]($field, $value);
+ foreach($data as $operator => $value) {
+ if (array_key_exists($operator, $this->filters)) {
+ $filters[] = new $this->filters[$operator]($field, $value);
+ }
}
}
} | Fix for multiple filters per field (#<I>) | onemustcode_query | train |
558e5cb9ce8ded7930c786a88845ae19462cad9e | diff --git a/__tests__/PaginationBoxView-test.js b/__tests__/PaginationBoxView-test.js
index <HASH>..<HASH> 100755
--- a/__tests__/PaginationBoxView-test.js
+++ b/__tests__/PaginationBoxView-test.js
@@ -9,7 +9,7 @@ const PaginationBoxView = require('./../react_components/PaginationBoxView').def
const PageView = require('./../react_components/PageView').default;
const BreakView = require('./../react_components/BreakView').default;
-import ReactTestUtils from 'react-addons-test-utils';
+import ReactTestUtils from 'react-dom/test-utils';
describe('PaginationBoxView', () => {
const pagination = ReactTestUtils.renderIntoDocument(
diff --git a/package.json b/package.json
index <HASH>..<HASH> 100644
--- a/package.json
+++ b/package.json
@@ -36,7 +36,6 @@
"express": "^4.14.0",
"jest-cli": "^17.0.3",
"jquery": "^3.1.1",
- "react-addons-test-utils": "^15.0.0",
"react-dom": "^15.0.0",
"react-hot-loader": "^1.3.1",
"serve-static": "^1.11.1",
@@ -51,12 +50,13 @@
"demo": "webpack"
},
"jest": {
- "transform": {".*": "<rootDir>/node_modules/babel-jest"},
+ "transform": {
+ ".*": "<rootDir>/node_modules/babel-jest"
+ },
"testPathDirs": ["__tests__"],
"unmockedModulePathPatterns": [
"<rootDir>/node_modules/react",
"<rootDir>/node_modules/react-dom",
- "<rootDir>/node_modules/react-addons-test-utils",
"<rootDir>/node_modules/fbjs"
],
"modulePathIgnorePatterns": [
diff --git a/react_components/BreakView.js b/react_components/BreakView.js
index <HASH>..<HASH> 100755
--- a/react_components/BreakView.js
+++ b/react_components/BreakView.js
@@ -2,15 +2,15 @@
import React from 'react';
-export default class BreakView extends React.Component {
- render() {
- let label = this.props.breakLabel;
- let className = this.props.breakClassName || 'break';
+const BreakView = (props) => {
+ const label = props.breakLabel;
+ const className = props.breakClassName || 'break';
- return (
- <li className={className}>
- {label}
- </li>
- );
- }
-};
+ return (
+ <li className={className}>
+ {label}
+ </li>
+ );
+}
+
+export default BreakView;
diff --git a/react_components/PageView.js b/react_components/PageView.js
index <HASH>..<HASH> 100755
--- a/react_components/PageView.js
+++ b/react_components/PageView.js
@@ -2,38 +2,38 @@
import React from 'react';
-export default class PageView extends React.Component {
- render() {
- let cssClassName = this.props.pageClassName;
- const linkClassName = this.props.pageLinkClassName;
- const onClick = this.props.onClick;
- const href = this.props.href;
- let ariaLabel = 'Page ' + this.props.page +
- (this.props.extraAriaContext ? ' ' + this.props.extraAriaContext : '');
- let ariaCurrent = null;
+const PageView = (props) => {
+ let cssClassName = props.pageClassName;
+ const linkClassName = props.pageLinkClassName;
+ const onClick = props.onClick;
+ const href = props.href;
+ let ariaLabel = 'Page ' + props.page +
+ (props.extraAriaContext ? ' ' + props.extraAriaContext : '');
+ let ariaCurrent = null;
- if (this.props.selected) {
- ariaCurrent = 'page';
- ariaLabel = 'Page ' + this.props.page + ' is your current page';
- if (typeof(cssClassName) !== 'undefined') {
- cssClassName = cssClassName + ' ' + this.props.activeClassName;
- } else {
- cssClassName = this.props.activeClassName;
- }
+ if (props.selected) {
+ ariaCurrent = 'page';
+ ariaLabel = 'Page ' + props.page + ' is your current page';
+ if (typeof(cssClassName) !== 'undefined') {
+ cssClassName = cssClassName + ' ' + props.activeClassName;
+ } else {
+ cssClassName = props.activeClassName;
}
-
- return (
- <li className={cssClassName}>
- <a onClick={onClick}
- className={linkClassName}
- href={href}
- tabIndex="0"
- aria-label={ariaLabel}
- aria-current={ariaCurrent}
- onKeyPress={onClick}>
- {this.props.page}
- </a>
- </li>
- );
}
-};
+
+ return (
+ <li className={cssClassName}>
+ <a onClick={onClick}
+ className={linkClassName}
+ href={href}
+ tabIndex="0"
+ aria-label={ariaLabel}
+ aria-current={ariaCurrent}
+ onKeyPress={onClick}>
+ {props.page}
+ </a>
+ </li>
+ )
+}
+
+export default PageView; | convert from class to stateless component & fix warning in tests | AdeleD_react-paginate | train |
1817c985f49aa74f1d83ee9374ac311f1d0afadc | diff --git a/cmd/openshift-tests/openshift-tests.go b/cmd/openshift-tests/openshift-tests.go
index <HASH>..<HASH> 100644
--- a/cmd/openshift-tests/openshift-tests.go
+++ b/cmd/openshift-tests/openshift-tests.go
@@ -247,6 +247,9 @@ func (opt *runOptions) SelectSuite(suites testSuites, args []string) (*testSuite
return &suites[i], nil
}
}
+ if len(opt.Provider) > 0 {
+ return &testSuite{TestSuite: *suite, PreSuite: suiteWithProviderPreSuite}, nil
+ }
return &testSuite{TestSuite: *suite}, nil
} | test: Set provider if --provider passed with run `-f -`
The caller is responsible for setting the right options on both
parts of the segment, but assume that we don't need suite info
by default in `-f -` mode. | openshift_origin | train |
611f477b51e862e408268f929079bdbd258ef939 | diff --git a/tests/src/test/java/alluxio/master/MasterTestUtils.java b/tests/src/test/java/alluxio/master/MasterTestUtils.java
index <HASH>..<HASH> 100644
--- a/tests/src/test/java/alluxio/master/MasterTestUtils.java
+++ b/tests/src/test/java/alluxio/master/MasterTestUtils.java
@@ -14,6 +14,7 @@ package alluxio.master;
import alluxio.Configuration;
import alluxio.Constants;
import alluxio.PropertyKey;
+import alluxio.clock.ManualClock;
import alluxio.master.block.BlockMasterFactory;
import alluxio.master.file.FileSystemMaster;
import alluxio.master.file.FileSystemMasterFactory;
@@ -59,7 +60,7 @@ public class MasterTestUtils {
throws Exception {
String masterJournal = Configuration.get(PropertyKey.MASTER_JOURNAL_FOLDER);
MasterRegistry registry = new MasterRegistry();
- SafeModeManager safeModeManager = new DefaultSafeModeManager();
+ SafeModeManager safeModeManager = new DefaultSafeModeManager(new ManualClock(), false);
JournalSystem journalSystem = JournalTestUtils.createJournalSystem(masterJournal);
new BlockMasterFactory().create(registry, journalSystem, safeModeManager);
new FileSystemMasterFactory().create(registry, journalSystem, safeModeManager); | Disable safe mode by default for integration tests | Alluxio_alluxio | train |
9247c9d6c7e6caad7e3a13709074c2942e3e3f46 | diff --git a/suds/xsd/sxbasic.py b/suds/xsd/sxbasic.py
index <HASH>..<HASH> 100644
--- a/suds/xsd/sxbasic.py
+++ b/suds/xsd/sxbasic.py
@@ -569,7 +569,7 @@ class Import(SchemaObject):
if self.location is None:
log.debug("imported schema (%s) not-found", self.ns[1])
else:
- result = self.download(options)
+ result = self.__download(options)
log.debug("imported:\n%s", result)
return result
@@ -578,7 +578,7 @@ class Import(SchemaObject):
if self.ns[1] != self.schema.tns[1]:
return self.schema.locate(self.ns)
- def download(self, options):
+ def __download(self, options):
"""Download the schema."""
url = self.location
try:
@@ -632,11 +632,11 @@ class Include(SchemaObject):
return
self.opened = True
log.debug("%s, including location='%s'", self.id, self.location)
- result = self.download(options)
+ result = self.__download(options)
log.debug("included:\n%s", result)
return result
- def download(self, options):
+ def __download(self, options):
"""Download the schema."""
url = self.location
try: | mark XSD schema Include & Import download() methods as private | suds-community_suds | train |
857c56746fc1534aebbd902576ab0ea583f68001 | diff --git a/benches_test.go b/benches_test.go
index <HASH>..<HASH> 100644
--- a/benches_test.go
+++ b/benches_test.go
@@ -44,10 +44,10 @@ func BenchmarkDeserializeWithoutValidationOneIOTxPayload(b *testing.B) {
}
func BenchmarkSerializeWithValidationOneIOTxPayload(b *testing.B) {
- sigTxPayload := oneInputOutputTransaction()
+ txPayload := oneInputOutputTransaction()
b.ResetTimer()
for i := 0; i < b.N; i++ {
- sigTxPayload.Serialize(iota.DeSeriModePerformValidation)
+ txPayload.Serialize(iota.DeSeriModePerformValidation)
}
}
@@ -60,10 +60,10 @@ func BenchmarkSerializeWithoutValidationOneIOTxPayload(b *testing.B) {
}
func BenchmarkSignEd25519OneIOTxEssence(b *testing.B) {
- sigTxPayload := oneInputOutputTransaction()
+ txPayload := oneInputOutputTransaction()
b.ResetTimer()
- unsigTxData, err := sigTxPayload.Essence.Serialize(iota.DeSeriModeNoValidation)
+ txEssenceData, err := txPayload.Essence.Serialize(iota.DeSeriModeNoValidation)
must(err)
seed := randEd25519Seed()
@@ -71,36 +71,36 @@ func BenchmarkSignEd25519OneIOTxEssence(b *testing.B) {
b.ResetTimer()
for i := 0; i < b.N; i++ {
- ed25519.Sign(prvKey, unsigTxData)
+ ed25519.Sign(prvKey, txEssenceData)
}
}
func BenchmarkVerifyEd25519OneIOTxEssence(b *testing.B) {
- sigTxPayload := oneInputOutputTransaction()
+ txPayload := oneInputOutputTransaction()
b.ResetTimer()
- unsigTxData, err := sigTxPayload.Essence.Serialize(iota.DeSeriModeNoValidation)
+ txEssenceData, err := txPayload.Essence.Serialize(iota.DeSeriModeNoValidation)
must(err)
seed := randEd25519Seed()
prvKey := ed25519.NewKeyFromSeed(seed[:])
- sig := ed25519.Sign(prvKey, unsigTxData)
+ sig := ed25519.Sign(prvKey, txEssenceData)
pubKey := prvKey.Public().(ed25519.PublicKey)
b.ResetTimer()
for i := 0; i < b.N; i++ {
- ed25519.Verify(pubKey, unsigTxData, sig)
+ ed25519.Verify(pubKey, txEssenceData, sig)
}
}
func BenchmarkSerializeAndHashMessageWithTransactionPayload(b *testing.B) {
- sigTxPayload := oneInputOutputTransaction()
+ txPayload := oneInputOutputTransaction()
m := &iota.Message{
Version: 1,
Parent1: rand32ByteHash(),
Parent2: rand32ByteHash(),
- Payload: sigTxPayload,
+ Payload: txPayload,
Nonce: 0,
}
for i := 0; i < b.N; i++ {
diff --git a/transaction_test.go b/transaction_test.go
index <HASH>..<HASH> 100644
--- a/transaction_test.go
+++ b/transaction_test.go
@@ -9,7 +9,7 @@ import (
"github.com/stretchr/testify/assert"
)
-func TestSignedTransactionPayload_Deserialize(t *testing.T) {
+func TestTransaction_Deserialize(t *testing.T) {
type test struct {
name string
source []byte
@@ -18,8 +18,8 @@ func TestSignedTransactionPayload_Deserialize(t *testing.T) {
}
tests := []test{
func() test {
- sigTxPay, sigTxPayData := randTransaction()
- return test{"ok", sigTxPayData, sigTxPay, nil}
+ txPayload, txPayloadData := randTransaction()
+ return test{"ok", txPayloadData, txPayload, nil}
}(),
}
@@ -38,7 +38,7 @@ func TestSignedTransactionPayload_Deserialize(t *testing.T) {
}
}
-func TestSignedTransactionPayload_Serialize(t *testing.T) {
+func TestTransaction_Serialize(t *testing.T) {
type test struct {
name string
source *iota.Transaction
@@ -46,8 +46,8 @@ func TestSignedTransactionPayload_Serialize(t *testing.T) {
}
tests := []test{
func() test {
- sigTxPay, sigTxPayData := randTransaction()
- return test{"ok", sigTxPay, sigTxPayData}
+ txPayload, txPayloadData := randTransaction()
+ return test{"ok", txPayload, txPayloadData}
}(),
}
for _, tt := range tests {
@@ -59,7 +59,7 @@ func TestSignedTransactionPayload_Serialize(t *testing.T) {
}
}
-func TestSignedTransactionPayload_SemanticallyValidate(t *testing.T) {
+func TestTransaction_SemanticallyValidate(t *testing.T) {
identityOne := randEd25519PrivateKey()
inputAddr := iota.AddressFromEd25519PubKey(identityOne.Public().(ed25519.PublicKey))
addrKeys := iota.AddressKeys{Address: &inputAddr, Keys: identityOne} | gets rid of more instances of sigtx | iotaledger_iota.go | train |
03337fc96c66738d756f3b5dd63e0f1f10a59af1 | diff --git a/lib/manager/pipenv/extract.js b/lib/manager/pipenv/extract.js
index <HASH>..<HASH> 100644
--- a/lib/manager/pipenv/extract.js
+++ b/lib/manager/pipenv/extract.js
@@ -51,6 +51,9 @@ function extractFromSection(pipfile, section, registryUrls) {
if (requirements.version) {
currentValue = requirements.version;
pipenvNestedVersion = true;
+ } else if (requirements.git) {
+ logger.debug('Skipping git dependency');
+ return null;
} else {
currentValue = requirements;
pipenvNestedVersion = false;
diff --git a/test/manager/pipenv/extract.spec.js b/test/manager/pipenv/extract.spec.js
index <HASH>..<HASH> 100644
--- a/test/manager/pipenv/extract.spec.js
+++ b/test/manager/pipenv/extract.spec.js
@@ -26,6 +26,12 @@ describe('lib/manager/pipenv/extract', () => {
expect(res).toMatchSnapshot();
expect(res).toHaveLength(5);
});
+ it('ignores git dependencies', () => {
+ const content =
+ '[packages]\r\nflask = {git = "https://github.com/pallets/flask.git"}\r\nwerkzeug = ">=0.14"';
+ const res = extractPackageFile(content, config).deps;
+ expect(res).toHaveLength(1);
+ });
it('ignores invalid package names', () => {
const content = '[packages]\r\nfoo = "==1.0.0"\r\n_invalid = "==1.0.0"';
const res = extractPackageFile(content, config).deps; | fix(pipenv) Ignore git dependencies without versions in Pipfile (#<I>) | renovatebot_renovate | train |
772236a13ff2bd28291c911b7c25fbfe99580ed1 | diff --git a/lib/websocket-server.js b/lib/websocket-server.js
index <HASH>..<HASH> 100644
--- a/lib/websocket-server.js
+++ b/lib/websocket-server.js
@@ -297,6 +297,8 @@ class WebSocketServer extends EventEmitter {
);
}
+ if (this._state > RUNNING) return abortHandshake(socket, 503);
+
const digest = createHash('sha1')
.update(key + GUID)
.digest('base64');
diff --git a/test/websocket-server.test.js b/test/websocket-server.test.js
index <HASH>..<HASH> 100644
--- a/test/websocket-server.test.js
+++ b/test/websocket-server.test.js
@@ -613,6 +613,28 @@ describe('WebSocketServer', () => {
});
});
+ it('fails if the WebSocket server is closing or closed', (done) => {
+ const server = http.createServer();
+ const wss = new WebSocket.Server({ noServer: true });
+
+ server.on('upgrade', (req, socket, head) => {
+ wss.close();
+ wss.handleUpgrade(req, socket, head, () => {
+ done(new Error('Unexpected callback invocation'));
+ });
+ });
+
+ server.listen(0, () => {
+ const ws = new WebSocket(`ws://localhost:${server.address().port}`);
+
+ ws.on('unexpected-response', (req, res) => {
+ assert.strictEqual(res.statusCode, 503);
+ res.resume();
+ server.close(done);
+ });
+ });
+ });
+
it('handles unsupported extensions', (done) => {
const wss = new WebSocket.Server(
{ | [fix] Abort the handshake if the server is closing or closed
Prevent WebSocket connections from being established after
`WebSocketServer.prototype.close()` is called. | websockets_ws | train |
a2ddf21e2b141077ae55113a1b7d47f6116f80d2 | diff --git a/payu/experiment.py b/payu/experiment.py
index <HASH>..<HASH> 100644
--- a/payu/experiment.py
+++ b/payu/experiment.py
@@ -380,6 +380,9 @@ class Experiment(object):
# Use manifest to populate work directory
self.manifest.make_links()
+ # Copy manifests to work directory so they archived on completion
+ self.manifest.copy_manifests(self.work_path)
+
# Call the macro-model setup
if len(self.models) > 1:
self.model.setup()
diff --git a/payu/manifest.py b/payu/manifest.py
index <HASH>..<HASH> 100644
--- a/payu/manifest.py
+++ b/payu/manifest.py
@@ -136,6 +136,12 @@ class PayuManifest(YaManifest):
else:
make_symlink(self.fullpath(filepath), filepath)
+ def copy(self, path):
+ """
+ Copy myself to another location
+ """
+ shutil.copy(self.path, path)
+
class Manifest(object):
"""
A Manifest class which stores all manifests for file tracking and
@@ -266,4 +272,10 @@ class Manifest(object):
print("Checking restart manifest")
else:
print("Creating restart manifest")
- self.restart_manifest.check_fast(reproduce=self.reproduce)
\ No newline at end of file
+ self.restart_manifest.check_fast(reproduce=self.reproduce)
+
+ def copy_manifests(self, path):
+
+ self.exe_manifest.copy(path)
+ self.input_manifest.copy(path)
+ self.restart_manifest.copy(path)
\ No newline at end of file | Copy manifest files to work directory in setup. | payu-org_payu | train |
540fe0b5ed334855a09acf478d44da77002c5e50 | diff --git a/envoy/tests/test_envoy.py b/envoy/tests/test_envoy.py
index <HASH>..<HASH> 100644
--- a/envoy/tests/test_envoy.py
+++ b/envoy/tests/test_envoy.py
@@ -135,6 +135,14 @@ def test_metadata(datadog_agent):
check.log.warning.assert_called_with(
'Envoy endpoint `%s` timed out after %s seconds', 'http://localhost:8001/server_info', (10.0, 10.0)
)
+
+ with mock.patch('requests.get', side_effect=IndexError()):
+ check._collect_metadata(instance['stats_url'])
+ datadog_agent.assert_metadata_count(0)
+ check.log.warning.assert_called_with(
+ 'Error collecting Envoy version with url=`%s`. Error: %s', 'http://localhost:8001/server_info', ''
+ )
+
with mock.patch('requests.get', side_effect=requests.exceptions.RequestException('Req Exception')):
check._collect_metadata(instance['stats_url'])
datadog_agent.assert_metadata_count(0) | Add test for exception not covered (#<I>) | DataDog_integrations-core | train |
2999cd4fb5a99ee7319dad16d3ac05784099f5e5 | diff --git a/decimal.go b/decimal.go
index <HASH>..<HASH> 100644
--- a/decimal.go
+++ b/decimal.go
@@ -5,6 +5,7 @@ import (
"errors"
"math"
"math/big"
+ "runtime"
"strconv"
"strings"
@@ -881,9 +882,19 @@ func (z *Big) Shrink(saveCap ...bool) *Big {
//
func (x *Big) Sign() int {
if x.isCompact() {
- // Hacker's Delight, page 21, section 2-8.
- // This prevents the incorrect answer for -1 << 63.
- return int((x.compact >> 63) | int64(uint64(-x.compact)>>63))
+ // See: https://github.com/golang/go/issues/16203
+ if runtime.GOARCH == "amd64" {
+ // Hacker's Delight, page 21, section 2-8.
+ // This prevents the incorrect answer for -1 << 63.
+ return int((x.compact >> 63) | int64(uint64(-x.compact)>>63))
+ }
+ if x.compact == 0 {
+ return 0
+ }
+ if x.compact < 0 {
+ return -1
+ }
+ return +1
}
return x.mantissa.Sign()
}
diff --git a/decimal_test.go b/decimal_test.go
index <HASH>..<HASH> 100644
--- a/decimal_test.go
+++ b/decimal_test.go
@@ -16,7 +16,7 @@ func TestBig_Add(t *testing.T) {
res string
}
- inputs := []inp{
+ inputs := [...]inp{
0: {a: "2", b: "3", res: "5"},
1: {a: "2454495034", b: "3451204593", res: "5905699627"},
2: {a: "24544.95034", b: ".3451204593", res: "24545.2954604593"},
@@ -238,16 +238,18 @@ func TestBig_Quo(t *testing.T) {
}
func TestBig_Sign(t *testing.T) {
- for i, test := range []struct {
+ for i, test := range [...]struct {
x string
s int
}{
- {"-Inf", 0},
- {"-1", -1},
- {"-0", 0},
- {"+0", 0},
- {"+1", +1},
- {"+Inf", 0},
+ 0: {"-Inf", 0},
+ 1: {"-1", -1},
+ 2: {"-0", 0},
+ 3: {"+0", 0},
+ 4: {"+1", +1},
+ 5: {"+Inf", 0},
+ 6: {"100", 1},
+ 7: {"-100", -1},
} {
x, ok := new(Big).SetString(test.x)
if !ok {
@@ -255,8 +257,7 @@ func TestBig_Sign(t *testing.T) {
}
s := x.Sign()
if s != test.s {
- t.Errorf("#%d: %s.Sign() = %d; want %d",
- i, test.x, s, test.s)
+ t.Errorf("#%d: %s.Sign() = %d; want %d", i, test.x, s, test.s)
}
}
}
diff --git a/internal/arith/arith_go.go b/internal/arith/arith_go.go
index <HASH>..<HASH> 100644
--- a/internal/arith/arith_go.go
+++ b/internal/arith/arith_go.go
@@ -4,7 +4,7 @@ package arith
func CLZ(x int64) (n int) {
if x == 0 {
- return 0
+ return 64
}
return _W - BitLen(x)
} | Sign needs to work around compiler bug
See: <URL> | ericlagergren_decimal | train |
f38e2751daefa1b7a97f435bd87741ff49796f6f | diff --git a/src/main/groovy/groovy/lang/ExpandoMetaClass.java b/src/main/groovy/groovy/lang/ExpandoMetaClass.java
index <HASH>..<HASH> 100644
--- a/src/main/groovy/groovy/lang/ExpandoMetaClass.java
+++ b/src/main/groovy/groovy/lang/ExpandoMetaClass.java
@@ -926,8 +926,7 @@ public class ExpandoMetaClass extends MetaClassImpl implements GroovyObject {
}
public List<MetaProperty> getProperties() {
- List<MetaProperty> propertyList = new ArrayList<MetaProperty>();
- propertyList.addAll(super.getProperties());
+ List<MetaProperty> propertyList = new ArrayList<MetaProperty>(super.getProperties());
return propertyList;
}
diff --git a/src/main/groovy/groovy/util/ObservableList.java b/src/main/groovy/groovy/util/ObservableList.java
index <HASH>..<HASH> 100644
--- a/src/main/groovy/groovy/util/ObservableList.java
+++ b/src/main/groovy/groovy/util/ObservableList.java
@@ -193,8 +193,7 @@ public class ObservableList implements List {
public void clear() {
int oldSize = size();
- List values = new ArrayList();
- values.addAll(delegate);
+ List values = new ArrayList(delegate);
delegate.clear();
if (!values.isEmpty()) {
fireElementClearedEvent(values);
diff --git a/src/main/groovy/groovy/util/ObservableSet.java b/src/main/groovy/groovy/util/ObservableSet.java
index <HASH>..<HASH> 100644
--- a/src/main/groovy/groovy/util/ObservableSet.java
+++ b/src/main/groovy/groovy/util/ObservableSet.java
@@ -300,8 +300,7 @@ public class ObservableSet<E> implements Set<E> {
public void clear() {
int oldSize = size();
- List<E> values = new ArrayList<E>();
- values.addAll(delegate);
+ List<E> values = new ArrayList<E>(delegate);
delegate.clear();
if (!values.isEmpty()) {
fireElementClearedEvent(values);
diff --git a/src/main/java/org/codehaus/groovy/classgen/ExtendedVerifier.java b/src/main/java/org/codehaus/groovy/classgen/ExtendedVerifier.java
index <HASH>..<HASH> 100644
--- a/src/main/java/org/codehaus/groovy/classgen/ExtendedVerifier.java
+++ b/src/main/java/org/codehaus/groovy/classgen/ExtendedVerifier.java
@@ -267,8 +267,7 @@ public class ExtendedVerifier extends ClassCodeVisitorSupport {
MethodNode found = getDeclaredMethodCorrected(genericsSpec, mn, correctedNext);
if (found != null) break;
}
- List<ClassNode> ifaces = new ArrayList<ClassNode>();
- ifaces.addAll(Arrays.asList(next.getInterfaces()));
+ List<ClassNode> ifaces = new ArrayList<ClassNode>(Arrays.asList(next.getInterfaces()));
Map updatedGenericsSpec = new HashMap(genericsSpec);
while (!ifaces.isEmpty()) {
ClassNode origInterface = ifaces.remove(0);
diff --git a/src/main/java/org/codehaus/groovy/reflection/CachedClass.java b/src/main/java/org/codehaus/groovy/reflection/CachedClass.java
index <HASH>..<HASH> 100644
--- a/src/main/java/org/codehaus/groovy/reflection/CachedClass.java
+++ b/src/main/java/org/codehaus/groovy/reflection/CachedClass.java
@@ -362,11 +362,10 @@ public class CachedClass {
}
public MetaMethod[] getNewMetaMethods() {
- List<MetaMethod> arr = new ArrayList<MetaMethod>();
- arr.addAll(Arrays.asList(classInfo.newMetaMethods));
+ List<MetaMethod> arr = new ArrayList<MetaMethod>(Arrays.asList(classInfo.newMetaMethods));
final MetaClass metaClass = classInfo.getStrongMetaClass();
- if (metaClass != null && metaClass instanceof ExpandoMetaClass) {
+ if (metaClass instanceof ExpandoMetaClass) {
arr.addAll(((ExpandoMetaClass)metaClass).getExpandoMethods());
}
diff --git a/src/main/java/org/codehaus/groovy/transform/CategoryASTTransformation.java b/src/main/java/org/codehaus/groovy/transform/CategoryASTTransformation.java
index <HASH>..<HASH> 100644
--- a/src/main/java/org/codehaus/groovy/transform/CategoryASTTransformation.java
+++ b/src/main/java/org/codehaus/groovy/transform/CategoryASTTransformation.java
@@ -111,8 +111,7 @@ public class CategoryASTTransformation implements ASTTransformation, Opcodes {
}
private void addVariablesToStack(Parameter[] params) {
- Set<String> names = new HashSet<String>();
- names.addAll(varStack.getLast());
+ Set<String> names = new HashSet<String>(varStack.getLast());
for (Parameter param : params) {
names.add(param.getName());
} | Trivial refactoring: simplify collection initialization | apache_groovy | train |
efccac19c95065b2f4ded12a22b4cf346ace8108 | diff --git a/README.md b/README.md
index <HASH>..<HASH> 100644
--- a/README.md
+++ b/README.md
@@ -32,7 +32,7 @@ implemented already):
- All socket types:
* [x] REQ
* [x] REP
- * [ ] DEALER
+ * [x] DEALER (In progress. Waiting for: #3)
* [ ] ROUTER
* [ ] PUB
* [ ] SUB
diff --git a/azmq/socket.py b/azmq/socket.py
index <HASH>..<HASH> 100644
--- a/azmq/socket.py
+++ b/azmq/socket.py
@@ -13,6 +13,7 @@ from .common import (
cancel_on_closing,
)
from .constants import (
+ DEALER,
REP,
REQ,
)
@@ -60,6 +61,9 @@ class Socket(CompositeClosableAsyncObject):
self._current_connection = asyncio.Future(loop=self.loop)
self.recv_multipart = self._recv_rep
self.send_multipart = self._send_rep
+ elif self.type == DEALER:
+ self.recv_multipart = self._recv_dealer
+ self.send_multipart = self._send_dealer
else:
raise RuntimeError("Unsupported socket type: %r" % self.type)
@@ -169,7 +173,7 @@ class Socket(CompositeClosableAsyncObject):
"from it first",
)
- await self.fair_incoming_connections.wait_not_empty()
+ await self.fair_outgoing_connections.wait_not_empty()
connection = next(iter(self.fair_outgoing_connections))
await connection.write_frames([b''] + frames)
@@ -243,3 +247,16 @@ class Socket(CompositeClosableAsyncObject):
message = frames[delimiter_index + 1:]
self._current_connection.set_result((connection, envelope))
return message
+
+ @cancel_on_closing
+ async def _send_dealer(self, frames):
+ await self.fair_outgoing_connections.wait_not_empty()
+ # FIXME: SHALL consider a peer as available only when it has a outgoing
+ # queue that is not full.
+ connection = next(iter(self.fair_outgoing_connections))
+ await connection.write_frames(frames)
+
+ @cancel_on_closing
+ async def _recv_dealer(self):
+ connection, frames = await self._fair_recv()
+ return frames
diff --git a/tests/integration/test_interoperability.py b/tests/integration/test_interoperability.py
index <HASH>..<HASH> 100644
--- a/tests/integration/test_interoperability.py
+++ b/tests/integration/test_interoperability.py
@@ -121,6 +121,32 @@ async def test_tcp_rep_socket(event_loop, socket_factory, connect_or_bind):
'connect',
])
@pytest.mark.asyncio
+async def test_tcp_dealer_socket(event_loop, socket_factory, connect_or_bind):
+ rep_socket = socket_factory.create(zmq.REP)
+ connect_or_bind(rep_socket, 'tcp://127.0.0.1:3333', reverse=True)
+
+ def run():
+ frames = rep_socket.recv_multipart()
+ assert frames == [b'my', b'question']
+ rep_socket.send_multipart([b'your', b'answer'])
+
+ with run_in_background(run):
+ async with azmq.Context(loop=event_loop) as context:
+ socket = context.socket(azmq.DEALER)
+ connect_or_bind(socket, 'tcp://127.0.0.1:3333')
+ await asyncio.wait_for(
+ socket.send_multipart([b'', b'my', b'question']),
+ 1,
+ )
+ frames = await asyncio.wait_for(socket.recv_multipart(), 1)
+ assert frames == [b'', b'your', b'answer']
+
+
[email protected]("link", [
+ 'bind',
+ 'connect',
+])
[email protected]
async def test_tcp_big_messages(event_loop, socket_factory, connect_or_bind):
rep_socket = socket_factory.create(zmq.REP)
connect_or_bind(rep_socket, 'tcp://127.0.0.1:3333', reverse=True) | Added support for DEALER sockets | ereOn_azmq | train |
2d7ae381429392ba708cd5dda7a2a6fe7f0cb5e8 | diff --git a/lib/dossier/version.rb b/lib/dossier/version.rb
index <HASH>..<HASH> 100644
--- a/lib/dossier/version.rb
+++ b/lib/dossier/version.rb
@@ -1,3 +1,3 @@
module Dossier
- VERSION = "2.9.3"
+ VERSION = "2.10.0"
end | prepping rails <I> release | tma1_dossier | train |
d6e14b479b991f9329b0e64c10ee899ba3e67a7c | diff --git a/dev/com.ibm.ws.config/src/com/ibm/ws/config/admin/internal/ConfigurationStorageHelper.java b/dev/com.ibm.ws.config/src/com/ibm/ws/config/admin/internal/ConfigurationStorageHelper.java
index <HASH>..<HASH> 100644
--- a/dev/com.ibm.ws.config/src/com/ibm/ws/config/admin/internal/ConfigurationStorageHelper.java
+++ b/dev/com.ibm.ws.config/src/com/ibm/ws/config/admin/internal/ConfigurationStorageHelper.java
@@ -34,6 +34,7 @@ import java.util.Set;
import com.ibm.ws.config.admin.ConfigID;
import com.ibm.ws.config.admin.ConfigurationDictionary;
import com.ibm.ws.config.admin.ExtendedConfiguration;
+import com.ibm.ws.ffdc.annotation.FFDCIgnore;
import com.ibm.wsspi.kernel.service.utils.OnErrorUtil.OnError;
import com.ibm.wsspi.kernel.service.utils.SerializableProtectedString;
@@ -145,15 +146,36 @@ public class ConfigurationStorageHelper {
}
+ @FFDCIgnore(IllegalStateException.class)
public static void store(File configFile, Collection<? extends ExtendedConfiguration> configs) throws IOException {
try (DataOutputStream dos = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(configFile, false)))) {
dos.writeByte(VERSION);
- dos.writeInt(configs.size());
+ // This secondary list is needed so we can collect the valid number of configs:
+ // non-null properties and not deleted (indicated with an IllegalStateException)
+ List<Object[]> configDatas = new ArrayList<>(configs.size());
for (ExtendedConfiguration config : configs) {
- Dictionary<String, ?> properties = config.getReadOnlyProperties();
- Set<ConfigID> references = config.getReferences();
- Set<String> uniqueVars = config.getUniqueVariables();
- String bundleLocation = config.getBundleLocation();
+ try {
+ Dictionary<String, ?> properties = config.getReadOnlyProperties();
+ Set<ConfigID> references = config.getReferences();
+ Set<String> uniqueVars = config.getUniqueVariables();
+ String bundleLocation = config.getBundleLocation();
+ if (properties != null) {
+ configDatas.add(new Object[] { properties, references, uniqueVars, bundleLocation });
+ }
+ } catch (IllegalStateException e) {
+ // ignore FFDC
+ }
+ }
+ // now we have all the valid configs and their dictionaries to save
+ dos.writeInt(configDatas.size());
+ for (Object[] configData : configDatas) {
+ @SuppressWarnings("unchecked")
+ Dictionary<String, ?> properties = (Dictionary<String, ?>) configData[0];
+ @SuppressWarnings("unchecked")
+ Set<ConfigID> references = (Set<ConfigID>) configData[1];
+ @SuppressWarnings("unchecked")
+ Set<String> uniqueVars = (Set<String>) configData[2];
+ String bundleLocation = (String) configData[3];
store(dos, properties, bundleLocation, references, uniqueVars);
}
}
diff --git a/dev/com.ibm.ws.config/src/com/ibm/ws/config/admin/internal/ConfigurationStore.java b/dev/com.ibm.ws.config/src/com/ibm/ws/config/admin/internal/ConfigurationStore.java
index <HASH>..<HASH> 100644
--- a/dev/com.ibm.ws.config/src/com/ibm/ws/config/admin/internal/ConfigurationStore.java
+++ b/dev/com.ibm.ws.config/src/com/ibm/ws/config/admin/internal/ConfigurationStore.java
@@ -216,13 +216,7 @@ class ConfigurationStore implements Runnable {
}
readLock();
try {
- List<ExtendedConfigurationImpl> persistConfigs = new ArrayList<>();
- for (ExtendedConfigurationImpl persistConfig : configurations.values()) {
- if (persistConfig.getReadOnlyProperties() != null) {
- persistConfigs.add(persistConfig);
- }
- }
- ConfigurationStorageHelper.store(persistentConfig, persistConfigs);
+ ConfigurationStorageHelper.store(persistentConfig, configurations.values());
if (shutdown && currentSaveTask != null) {
currentSaveTask.cancel(false);
} | Fix IllegalStateException on ConfigurationStore
The ConfigurationStore saves all configurations
currently available in the configurations map
but this has timing issues if a Configuration
is in the process of being deleted. Additional
safeguards are needed to avoid the
IllegalStateException when saving configs | OpenLiberty_open-liberty | train |
162ae6a8557fb94d3a19b7f5baf5bff6881fd932 | diff --git a/src/main/java/tachyon/Inode.java b/src/main/java/tachyon/Inode.java
index <HASH>..<HASH> 100644
--- a/src/main/java/tachyon/Inode.java
+++ b/src/main/java/tachyon/Inode.java
@@ -79,7 +79,9 @@ public abstract class Inode implements Comparable<Inode> {
@Override
public synchronized String toString() {
StringBuilder sb = new StringBuilder("INode(");
- sb.append(mName).append(",").append(mId).append(",").append(mParentId).append(")");
+ sb.append("ID:").append(mId).append(", NAME:").append(mName);
+ sb.append(", PARENT_ID:").append(mParentId);
+ sb.append(", CREATION_TIME_MS:").append(CREATION_TIME_MS).append(")");
return sb.toString();
}
}
\ No newline at end of file
diff --git a/src/main/java/tachyon/InodeFile.java b/src/main/java/tachyon/InodeFile.java
index <HASH>..<HASH> 100644
--- a/src/main/java/tachyon/InodeFile.java
+++ b/src/main/java/tachyon/InodeFile.java
@@ -41,8 +41,9 @@ public class InodeFile extends Inode {
@Override
public String toString() {
StringBuilder sb = new StringBuilder("InodeFile(");
- sb.append(super.toString()).append(",").append(mLength).append(",");
- sb.append(mCheckpointPath).append(")");
+ sb.append(super.toString()).append(", LENGTH:").append(mLength);
+ sb.append(", CheckpointPath:").append(mCheckpointPath);
+ sb.append(", DependencyId:").append(mDependencyId).append(")");
return sb.toString();
}
diff --git a/src/main/java/tachyon/MasterInfo.java b/src/main/java/tachyon/MasterInfo.java
index <HASH>..<HASH> 100644
--- a/src/main/java/tachyon/MasterInfo.java
+++ b/src/main/java/tachyon/MasterInfo.java
@@ -380,6 +380,7 @@ public class MasterInfo {
throws InvalidPathException, FileDoesNotExistException {
Dependency dep = null;
synchronized (mRoot) {
+ LOG.info("ParentList: " + CommonUtils.listToString(parents));
List<Integer> parentsIdList = getFilesIds(parents);
List<Integer> childrenIdList = getFilesIds(children);
@@ -388,9 +389,11 @@ public class MasterInfo {
int parentId = parentsIdList.get(k);
Inode inode = mInodes.get(parentId);
if (inode.isFile()) {
+ LOG.info("PARENT DEPENDENCY ID IS " + ((InodeFile) inode).getDependencyId() + " " +
+ ((InodeFile) inode));
parentDependencyIds.add(((InodeFile) inode).getDependencyId());
} else {
- throw new InvalidPathException("Children " + children.get(k) + " is not a file.");
+ throw new InvalidPathException("Parent " + parentId + " is not a file.");
}
}
@@ -421,6 +424,8 @@ public class MasterInfo {
}
}
+ LOG.info("Dependency created: " + dep);
+
return dep.ID;
} | better toString in inodes. | Alluxio_alluxio | train |
150494fc35e93362d3bd9db669a544a75065d8f4 | diff --git a/api/opentrons/robot/robot_configs.py b/api/opentrons/robot/robot_configs.py
index <HASH>..<HASH> 100755
--- a/api/opentrons/robot/robot_configs.py
+++ b/api/opentrons/robot/robot_configs.py
@@ -15,10 +15,10 @@ MOUNT_CURRENT_LOW = 0.1
MOUNT_CURRENT_HIGH = 1.0
X_CURRENT_LOW = 0.3
-X_CURRENT_HIGH = 1.5
+X_CURRENT_HIGH = 1.25
Y_CURRENT_LOW = 0.3
-Y_CURRENT_HIGH = 1.75
+Y_CURRENT_HIGH = 1.5
HIGH_CURRENT = {
'X': X_CURRENT_HIGH,
@@ -47,8 +47,8 @@ DEFAULT_CURRENT = {
'C': LOW_CURRENT['C']
}
-X_MAX_SPEED = 500
-Y_MAX_SPEED = 300
+X_MAX_SPEED = 600
+Y_MAX_SPEED = 400
Z_MAX_SPEED = 125
A_MAX_SPEED = 125
B_MAX_SPEED = 50
diff --git a/api/tests/opentrons/drivers/test_driver.py b/api/tests/opentrons/drivers/test_driver.py
index <HASH>..<HASH> 100755
--- a/api/tests/opentrons/drivers/test_driver.py
+++ b/api/tests/opentrons/drivers/test_driver.py
@@ -132,10 +132,10 @@ def test_dwell_and_activate_axes(smoothie, monkeypatch):
smoothie.dwell_axes('BCY')
smoothie._set_saved_current()
expected = [
- ['M907 A0.1 B0.1 C0.1 X1.5 Y0.3 Z0.1 G4P0.005 M400'],
+ ['M907 A0.1 B0.1 C0.1 X1.25 Y0.3 Z0.1 G4P0.005 M400'],
['M907 A0.1 B0.1 C0.1 X0.3 Y0.3 Z0.1 G4P0.005 M400'],
- ['M907 A0.1 B0.5 C0.5 X1.5 Y1.75 Z0.1 G4P0.005 M400'],
- ['M907 A0.1 B0.5 C0.1 X0.3 Y1.75 Z0.1 G4P0.005 M400'],
+ ['M907 A0.1 B0.5 C0.5 X1.25 Y1.5 Z0.1 G4P0.005 M400'],
+ ['M907 A0.1 B0.5 C0.1 X0.3 Y1.5 Z0.1 G4P0.005 M400'],
['M907 A0.1 B0.1 C0.1 X0.3 Y0.3 Z0.1 G4P0.005 M400']
]
# from pprint import pprint
@@ -199,14 +199,14 @@ def test_plunger_commands(smoothie, monkeypatch):
['G0F3000 M400'],
['M907 A0.1 B0.1 C0.1 X0.3 Y0.8 Z0.1 G4P0.005 G91 G0Y-20 G90 M400'],
['G0F24000 M400'],
- ['M907 A0.1 B0.1 C0.1 X1.5 Y0.3 Z0.1 G4P0.005 G28.2X M400'],
+ ['M907 A0.1 B0.1 C0.1 X1.25 Y0.3 Z0.1 G4P0.005 G28.2X M400'],
['M907 A0.1 B0.1 C0.1 X0.3 Y0.3 Z0.1 G4P0.005 M400'],
- ['M907 A0.1 B0.1 C0.1 X0.3 Y1.75 Z0.1 G4P0.005 G28.2Y M400'],
+ ['M907 A0.1 B0.1 C0.1 X0.3 Y1.5 Z0.1 G4P0.005 G28.2Y M400'],
['M203.1 Y8 M400'],
['G91 G0Y-3 G90 M400'],
['G28.2Y M400'],
['G91 G0Y-3 G90 M400'],
- ['M203.1 A125 B50 C50 X500 Y300 Z125 M400'],
+ ['M203.1 A125 B50 C50 X600 Y400 Z125 M400'],
['M907 A0.1 B0.1 C0.1 X0.3 Y0.3 Z0.1 G4P0.005 M400'],
['M114.2 M400']
]
@@ -217,7 +217,7 @@ def test_plunger_commands(smoothie, monkeypatch):
smoothie.move({'X': 0, 'Y': 1.123456, 'Z': 2, 'A': 3})
expected = [
- ['M907 A1.0 B0.1 C0.1 X1.5 Y1.75 Z1.0 G4P0.005 G0.+ M400']
+ ['M907 A1.0 B0.1 C0.1 X1.25 Y1.5 Z1.0 G4P0.005 G0.+ M400']
]
# from pprint import pprint
# pprint(command_log)
@@ -243,9 +243,9 @@ def test_plunger_commands(smoothie, monkeypatch):
'C': 5})
expected = [
# Set active axes high
- ['M907 A1.0 B0.5 C0.5 X1.5 Y1.75 Z1.0 G4P0.005 G0.+[BC].+ M400'],
+ ['M907 A1.0 B0.5 C0.5 X1.25 Y1.5 Z1.0 G4P0.005 G0.+[BC].+ M400'],
# Set plunger current low
- ['M907 A1.0 B0.1 C0.1 X1.5 Y1.75 Z1.0 G4P0.005 M400'],
+ ['M907 A1.0 B0.1 C0.1 X1.25 Y1.5 Z1.0 G4P0.005 M400'],
]
# from pprint import pprint
# pprint(command_log)
@@ -356,7 +356,7 @@ def test_set_current(model):
{'C': 0.1},
{'A': 1.0},
{'A': 0.1},
- {'X': 1.5, 'Y': 1.75},
+ {'X': 1.25, 'Y': 1.5},
{'X': 0.3, 'Y': 0.3},
{'A': 1.0},
{'A': 0.42}, | decrease XY currents; bring XY speeds back up to previous values | Opentrons_opentrons | train |
581e60b12b80a5d60be838b152dd1403eadf4d05 | diff --git a/test/integration/voldemort/performance/benchmark/Benchmark.java b/test/integration/voldemort/performance/benchmark/Benchmark.java
index <HASH>..<HASH> 100644
--- a/test/integration/voldemort/performance/benchmark/Benchmark.java
+++ b/test/integration/voldemort/performance/benchmark/Benchmark.java
@@ -186,14 +186,19 @@ public class Benchmark {
public void run() {
long startTime = System.currentTimeMillis();
while(opsDone < this.opsCount) {
- if(runBenchmark) {
- if(!workLoad.doTransaction(this.db)) {
- break;
- }
- } else {
- if(!workLoad.doWrite(this.db)) {
- break;
+ try {
+ if(runBenchmark) {
+ if(!workLoad.doTransaction(this.db)) {
+ break;
+ }
+ } else {
+ if(!workLoad.doWrite(this.db)) {
+ break;
+ }
}
+ } catch(Exception e) {
+ if(this.verbose)
+ e.printStackTrace();
}
opsDone++;
if(targetThroughputPerMs > 0) {
diff --git a/test/integration/voldemort/performance/benchmark/VoldemortWrapper.java b/test/integration/voldemort/performance/benchmark/VoldemortWrapper.java
index <HASH>..<HASH> 100644
--- a/test/integration/voldemort/performance/benchmark/VoldemortWrapper.java
+++ b/test/integration/voldemort/performance/benchmark/VoldemortWrapper.java
@@ -107,7 +107,7 @@ public class VoldemortWrapper {
res = this.Ok;
}
- measurement.reportReturnCode(WRITES_STRING, this.Ok);
+ measurement.reportReturnCode(WRITES_STRING, res);
return res;
} | Fixed minor bug in Perf tool wherein return codes were not being logged correctly during writes | voldemort_voldemort | train |
2816ee40d0d7774fac42c768ad22319fc8003920 | diff --git a/src/main/java/org/jboss/wsf/spi/deployment/DeploymentAspect.java b/src/main/java/org/jboss/wsf/spi/deployment/DeploymentAspect.java
index <HASH>..<HASH> 100644
--- a/src/main/java/org/jboss/wsf/spi/deployment/DeploymentAspect.java
+++ b/src/main/java/org/jboss/wsf/spi/deployment/DeploymentAspect.java
@@ -21,11 +21,7 @@
*/
package org.jboss.wsf.spi.deployment;
-import java.util.HashSet;
import java.util.Set;
-import java.util.StringTokenizer;
-
-import org.jboss.logging.Logger;
/**
* A deployment aspect that does nothing.
@@ -36,87 +32,43 @@ import org.jboss.logging.Logger;
* @author [email protected]
* @since 20-Apr-2007
*/
-public abstract class DeploymentAspect
+public interface DeploymentAspect
{
- // provide logging
- protected final Logger log = Logger.getLogger(getClass());
-
public static final String LAST_DEPLOYMENT_ASPECT = "LAST_DEPLOYMENT_ASPECT";
- private String provides;
- private String requires;
- private int relativeOrder;
- private boolean isLast;
-
- public void setLast(boolean isLast)
- {
- this.isLast = isLast;
- }
+ public void setLast(boolean isLast);
- public boolean isLast()
- {
- return this.isLast;
- }
+ public boolean isLast();
- public String getProvides()
- {
- return provides;
- }
+ public String getProvides();
- public void setProvides(String provides)
- {
- this.provides = provides;
- }
+ public void setProvides(String provides);
- public String getRequires()
- {
- return requires;
- }
+ public String getRequires();
- public void setRequires(String requires)
- {
- this.requires = requires;
- }
+ public void setRequires(String requires);
- public void setRelativeOrder(int relativeOrder)
- {
- this.relativeOrder = relativeOrder;
- }
+ public void setRelativeOrder(int relativeOrder);
- public int getRelativeOrder()
- {
- return this.relativeOrder;
- }
+ public int getRelativeOrder();
- public void start(Deployment dep)
- {
- }
+ public void start(Deployment dep);
- public void stop(Deployment dep)
- {
- }
+ public void stop(Deployment dep);
- public Set<String> getProvidesAsSet()
- {
- Set<String> condset = new HashSet<String>();
- if (provides != null)
- {
- StringTokenizer st = new StringTokenizer(provides, ", \r\n\t");
- while (st.hasMoreTokens())
- condset.add(st.nextToken());
- }
- return condset;
- }
+ public Set<String> getProvidesAsSet();
- public Set<String> getRequiresAsSet()
- {
- Set<String> condset = new HashSet<String>();
- if (requires != null)
- {
- StringTokenizer st = new StringTokenizer(requires, ", \r\n\t");
- while (st.hasMoreTokens())
- condset.add(st.nextToken());
- }
- return condset;
- }
+ public Set<String> getRequiresAsSet();
+
+ public boolean canHandle(Deployment dep);
+
+ public boolean isForJaxWs();
+
+ public void setForJaxWs(boolean isForJaxWs);
+
+ public boolean isForJaxRpc();
+
+ public void setForJaxRpc(boolean isForJaxRpc);
+
+ public ClassLoader getLoader();
} | [JBWS-<I>] Merging from jaxrpc-cxf branch, adding support for JAXRPC with CXF and Metro stack | jbossws_jbossws-spi | train |
de13143c621ac7a4c0de70ae55cae705b2088582 | diff --git a/src/util.js b/src/util.js
index <HASH>..<HASH> 100644
--- a/src/util.js
+++ b/src/util.js
@@ -131,9 +131,9 @@ function replacer (key) {
} else if (type === 'symbol') {
return `[native Symbol ${Symbol.prototype.toString.call(val)}]`
} else if (val !== null && type === 'object') {
- if (val instanceof Map) {
+ if (val instanceof Map || val.toString() === '[object Map]') {
return encodeCache.cache(val, () => getCustomMapDetails(val))
- } else if (val instanceof Set) {
+ } else if (val instanceof Set || val.toString() === '[object Set]') {
return encodeCache.cache(val, () => getCustomSetDetails(val))
} else if (val instanceof RegExp) {
// special handling of native type | fix: detect polyfilled Map & Set objects, closes #<I> | vuejs_vue-devtools | train |
cc43fb773bd41756f100bc41aba73b2047eb0afe | diff --git a/resources/views/filter/button.blade.php b/resources/views/filter/button.blade.php
index <HASH>..<HASH> 100644
--- a/resources/views/filter/button.blade.php
+++ b/resources/views/filter/button.blade.php
@@ -1,5 +1,5 @@
<div class="btn-group" style="margin-right: 10px" data-toggle="buttons">
- <label class="btn btn-sm btn-dropbox {{ $btn_class }} {{ $expand ? 'active' : '' }}">
+ <label class="btn btn-sm btn-dropbox {{ $btn_class }} {{ $expand ? 'active' : '' }}" title="{{ trans('admin.filter') }}">
<input type="checkbox"><i class="fa fa-filter"></i><span class="hidden-xs"> {{ trans('admin.filter') }}</span>
</label>
diff --git a/resources/views/tree.blade.php b/resources/views/tree.blade.php
index <HASH>..<HASH> 100644
--- a/resources/views/tree.blade.php
+++ b/resources/views/tree.blade.php
@@ -3,23 +3,23 @@
<div class="box-header">
<div class="btn-group">
- <a class="btn btn-primary btn-sm {{ $id }}-tree-tools" data-action="expand">
+ <a class="btn btn-primary btn-sm {{ $id }}-tree-tools" data-action="expand" title="{{ trans('admin.expand') }}">
<i class="fa fa-plus-square-o"></i><span class="hidden-xs"> {{ trans('admin.expand') }}</span>
</a>
- <a class="btn btn-primary btn-sm {{ $id }}-tree-tools" data-action="collapse">
+ <a class="btn btn-primary btn-sm {{ $id }}-tree-tools" data-action="collapse" title="{{ trans('admin.collapse') }}">
<i class="fa fa-minus-square-o"></i><span class="hidden-xs"> {{ trans('admin.collapse') }}</span>
</a>
</div>
@if($useSave)
<div class="btn-group">
- <a class="btn btn-info btn-sm {{ $id }}-save"><i class="fa fa-save"></i><span class="hidden-xs"> {{ trans('admin.save') }}</span></a>
+ <a class="btn btn-info btn-sm {{ $id }}-save" title="{{ trans('admin.save') }}"><i class="fa fa-save"></i><span class="hidden-xs"> {{ trans('admin.save') }}</span></a>
</div>
@endif
@if($useRefresh)
<div class="btn-group">
- <a class="btn btn-warning btn-sm {{ $id }}-refresh"><i class="fa fa-refresh"></i><span class="hidden-xs"> {{ trans('admin.refresh') }}</span></a>
+ <a class="btn btn-warning btn-sm {{ $id }}-refresh" title="{{ trans('admin.refresh') }}"><i class="fa fa-refresh"></i><span class="hidden-xs"> {{ trans('admin.refresh') }}</span></a>
</div>
@endif | Added missing title's for buttons | z-song_laravel-admin | train |
4ec6e953bf4cfe8cb888a5e2659c1c945d57eb4b | diff --git a/clustering/ee/cache/src/main/java/org/wildfly/clustering/ee/cache/scheduler/LocalScheduler.java b/clustering/ee/cache/src/main/java/org/wildfly/clustering/ee/cache/scheduler/LocalScheduler.java
index <HASH>..<HASH> 100644
--- a/clustering/ee/cache/src/main/java/org/wildfly/clustering/ee/cache/scheduler/LocalScheduler.java
+++ b/clustering/ee/cache/src/main/java/org/wildfly/clustering/ee/cache/scheduler/LocalScheduler.java
@@ -26,6 +26,8 @@ import java.time.Duration;
import java.time.Instant;
import java.util.Iterator;
import java.util.Map;
+import java.util.concurrent.CancellationException;
+import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.ScheduledExecutorService;
@@ -114,12 +116,16 @@ public class LocalScheduler<T> implements Scheduler<T, Instant>, Iterable<T>, Ru
@Override
public synchronized void close() {
+ WildFlySecurityManager.doPrivilegedWithParameter(this.executor, DefaultExecutorService.SHUTDOWN_ACTION);
if (this.future != null) {
- if (!this.future.isDone()) {
- this.future.cancel(true);
+ try {
+ this.future.get();
+ } catch (InterruptedException e) {
+ Thread.currentThread().interrupt();
+ } catch (CancellationException | ExecutionException e) {
+ // Ignore
}
}
- WildFlySecurityManager.doPrivilegedWithParameter(this.executor, DefaultExecutorService.SHUTDOWN_ACTION);
}
@Override | LocalScheduler needs to wait for task completion on close. | wildfly_wildfly | train |
62a68137320b138b2e8aa27a28162f17ad780170 | diff --git a/docs/victory-animation/docs.js b/docs/victory-animation/docs.js
index <HASH>..<HASH> 100644
--- a/docs/victory-animation/docs.js
+++ b/docs/victory-animation/docs.js
@@ -4,7 +4,7 @@ import Ecology from "ecology";
import Radium, { Style } from "radium";
import * as docgen from "react-docgen";
import { VictoryAnimation } from "../../src/index";
-import {VictoryTheme} from "formidable-landers";
+import { VictoryTheme, appendLinkIcon } from "formidable-landers";
class Docs extends React.Component {
render() {
@@ -15,6 +15,7 @@ class Docs extends React.Component {
source={docgen.parse(require("!!raw!../../src/victory-animation/victory-animation"))}
scope={{React, ReactDOM, VictoryAnimation}}
playgroundtheme="elegant"
+ customRenderers={appendLinkIcon}
/>
<Style rules={VictoryTheme}/>
</div>
diff --git a/docs/victory-label/docs.js b/docs/victory-label/docs.js
index <HASH>..<HASH> 100644
--- a/docs/victory-label/docs.js
+++ b/docs/victory-label/docs.js
@@ -3,7 +3,7 @@ import ReactDOM from "react-dom";
import Ecology from "ecology";
import Radium, { Style } from "radium";
import * as docgen from "react-docgen";
-import { VictoryTheme } from "formidable-landers";
+import { VictoryTheme, appendLinkIcon } from "formidable-landers";
import { VictoryLabel } from "../../src/index";
class Docs extends React.Component {
@@ -15,6 +15,7 @@ class Docs extends React.Component {
source={docgen.parse(require("!!raw!../../src/victory-label/victory-label"))}
scope={{React, ReactDOM, VictoryLabel}}
playgroundtheme="elegant"
+ customRenderers={appendLinkIcon}
/>
<Style rules={VictoryTheme}/>
</div>
diff --git a/package.json b/package.json
index <HASH>..<HASH> 100644
--- a/package.json
+++ b/package.json
@@ -37,7 +37,7 @@
"devDependencies": {
"builder-victory-component-dev": "^2.3.0",
"chai": "^3.2.0",
- "ecology": "^1.3.0",
+ "ecology": "^1.5.0",
"enzyme": "^2.3.0",
"mocha": "^2.2.5",
"radium": "^0.16.2", | bump ecology, pass appendLink function | FormidableLabs_victory | train |
436921e7c155a5df4db0a701b15115f5dbd385bd | diff --git a/manager/state/raft/raft.go b/manager/state/raft/raft.go
index <HASH>..<HASH> 100644
--- a/manager/state/raft/raft.go
+++ b/manager/state/raft/raft.go
@@ -177,7 +177,7 @@ func NewNode(ctx context.Context, opts NewNodeOptions) *Node {
n := &Node{
Ctx: ctx,
cancel: cancel,
- cluster: membership.NewCluster(cfg.ElectionTick),
+ cluster: membership.NewCluster(2 * cfg.ElectionTick),
tlsCredentials: opts.TLSCredentials,
raftStore: raftStore,
Address: opts.Addr, | raft: increase member inactive timeout
This gives plenty of time to demoted node to send ProcessRaftMessage
with old certificate and receive ErrMemberRemoved. | docker_swarmkit | train |
b031c277f330e9843f2fc5cdb30e99ce1c40237a | diff --git a/Godeps/Godeps.json b/Godeps/Godeps.json
index <HASH>..<HASH> 100644
--- a/Godeps/Godeps.json
+++ b/Godeps/Godeps.json
@@ -136,7 +136,7 @@
},
{
"ImportPath": "github.com/zenoss/glog",
- "Rev": "fcea23b5c2bb2a51b26840be13d3bdb63ca4e073"
+ "Rev": "09a83f7c5c0f425c00cb1e063e9179698579f296"
},
{
"ImportPath": "github.com/zenoss/go-json-rest",
diff --git a/Godeps/_workspace/src/github.com/zenoss/glog/glog.go b/Godeps/_workspace/src/github.com/zenoss/glog/glog.go
index <HASH>..<HASH> 100644
--- a/Godeps/_workspace/src/github.com/zenoss/glog/glog.go
+++ b/Godeps/_workspace/src/github.com/zenoss/glog/glog.go
@@ -115,18 +115,16 @@ const (
warningLog
errorLog
fatalLog
- debugLog
- numSeverity = 5
+ numSeverity = 4
)
-const severityChar = "IWEFD"
+const severityChar = "IWEF"
var severityName = []string{
infoLog: "INFO",
warningLog: "WARNING",
errorLog: "ERROR",
fatalLog: "FATAL",
- debugLog: "DEBUG",
}
// get returns the value of the severity.
@@ -740,8 +738,6 @@ func (l *loggingT) output(s severity, buf *buffer) {
stderrstring = "\033[38;5;208m" + stderrstring
case infoLog:
stderrstring = "\033[94m" + stderrstring
- case debugLog:
- stderrstring = "\033[4m" + stderrstring
}
stderrstring = stderrstring + "\033[0m"
}
@@ -759,9 +755,6 @@ func (l *loggingT) output(s severity, buf *buffer) {
}
}
switch s {
- case debugLog:
- l.file[debugLog].Write(data)
- fallthrough
case fatalLog:
l.file[fatalLog].Write(data)
fallthrough
@@ -1051,25 +1044,6 @@ func V(level Level) Verbose {
return Verbose(false)
}
-// Debug logs to the DEBUG log.
-// Arguments are handled in the manner of fmt.Print; a newline is appended if missing.
-func Debug(args ...interface{}) {
- logging.print(debugLog, args...)
-}
-
-// Debugln logs to the DEBUG log.
-// Arguments are handled in the manner of fmt.Println; a newline is appended if missing.
-func Debugln(args ...interface{}) {
- logging.println(debugLog, args...)
-}
-
-// Debugf logs to the DEBUG log.
-// Arguments are handled in the manner of fmt.Printf; a newline is appended if missing.
-func Debugf(format string, args ...interface{}) {
- logging.printf(debugLog, format, args...)
-}
-
-
// Info is equivalent to the global Info function, guarded by the value of v.
// See the documentation of V for usage.
func (v Verbose) Info(args ...interface{}) {
diff --git a/Godeps/_workspace/src/github.com/zenoss/glog/glog_test.go b/Godeps/_workspace/src/github.com/zenoss/glog/glog_test.go
index <HASH>..<HASH> 100644
--- a/Godeps/_workspace/src/github.com/zenoss/glog/glog_test.go
+++ b/Godeps/_workspace/src/github.com/zenoss/glog/glog_test.go
@@ -96,20 +96,6 @@ func TestInfo(t *testing.T) {
}
}
-// Test that Debug works as advertised.
-func TestDebug(t *testing.T) {
- setFlags()
- defer logging.swap(logging.newBuffers())
- Debug("test")
- // fmt.Println(contents(debugLog))
- if !contains(debugLog, "D", t) {
- t.Errorf("Debug has wrong character: %q", contents(debugLog))
- }
- if !contains(debugLog, "test", t) {
- t.Error("Debug failed")
- }
-}
-
// Test that the header has the correct format.
func TestHeader(t *testing.T) {
setFlags() | Fixes CC-<I>: Set glog to proper level for godep
The commit ID in Godeps.json for zenoss/glog was for someone's local
commit of changes that were deemed unnecessary. So the changes were
never pushed to github.com (good) but the commit ID ended up in
Godeps.json (bad). | control-center_serviced | train |
55c4128a545999ac3c0bc469ea358c30065b24d4 | diff --git a/base/AuthManager.php b/base/AuthManager.php
index <HASH>..<HASH> 100644
--- a/base/AuthManager.php
+++ b/base/AuthManager.php
@@ -33,6 +33,18 @@ class AuthManager extends Component
return $this->isType($types);
}
+ public function canResell()
+ {
+ static $types = ['reseller' => 1, 'owner' => 1];
+ return $this->isType($types);
+ }
+
+ public function canOwn()
+ {
+ static $types = ['owner' => 1];
+ return $this->isType($types);
+ }
+
/**
* Current user.
*/ | + AuthManager canResell, canOwn | hiqdev_hipanel-core | train |
1282a056a5985d7d391be5a7df7d6f71d7a11b53 | diff --git a/PyFunceble/engine/ci/base.py b/PyFunceble/engine/ci/base.py
index <HASH>..<HASH> 100644
--- a/PyFunceble/engine/ci/base.py
+++ b/PyFunceble/engine/ci/base.py
@@ -119,11 +119,9 @@ class CIBase:
commands = [
("git remote rm origin", True),
- (
- "git remote add origin "
- f"https://{token}@{remote}", # pylint: disable=line-too-long
- False,
- ),
+ ("git remote add origin " f"https://{token}@{remote}", False),
+ ("git remote update", False),
+ ("git fetch", False),
]
self.exec_commands(commands)
diff --git a/PyFunceble/engine/ci/gitlab_ci.py b/PyFunceble/engine/ci/gitlab_ci.py
index <HASH>..<HASH> 100644
--- a/PyFunceble/engine/ci/gitlab_ci.py
+++ b/PyFunceble/engine/ci/gitlab_ci.py
@@ -98,11 +98,9 @@ class GitLabCI(CIBase):
commands = [
("git remote rm origin", True),
- (
- "git remote add origin "
- f"https://oauth2:{token}@{remote}", # pylint: disable=line-too-long
- False,
- ),
+ ("git remote add origin " f"https://oauth2:{token}@{remote}", False),
+ ("git remote update", False),
+ ("git fetch", False),
]
self.exec_commands(commands) | Ensure that we fetch the new remote before working with it. | funilrys_PyFunceble | train |
d13da158db4aa2a3e6954e35d80bf90cb1072d73 | diff --git a/go/api-frontend/aaa/authorization.go b/go/api-frontend/aaa/authorization.go
index <HASH>..<HASH> 100644
--- a/go/api-frontend/aaa/authorization.go
+++ b/go/api-frontend/aaa/authorization.go
@@ -272,8 +272,6 @@ func (tam *TokenAuthorizationMiddleware) isAuthorizedTenantId(ctx context.Contex
// Token doesn't have access to any tenant
if tokenTenantId == AccessNoTenants {
return false, errors.New("Token is prohibited from accessing data from any tenant")
- } else if !multipleTenants && requestTenantId < 2 {
- return true, nil
} else if tokenTenantId == AccessAllTenants {
return true, nil
} else if requestTenantId == tokenTenantId { | revert attempted fix related to #<I> | inverse-inc_packetfence | train |
a2988361c5699edfc22ca8567fcfb7350db9441f | diff --git a/helpers/etcd.py b/helpers/etcd.py
index <HASH>..<HASH> 100644
--- a/helpers/etcd.py
+++ b/helpers/etcd.py
@@ -104,13 +104,17 @@ class Client:
def load_members(self):
load_from_srv = False
if not self._base_uri:
+ if not 'discovery_srv' in self._config and not 'host' in self._config:
+ raise Exception('Neither discovery_srv nor host are defined in etcd section of config')
+
if 'discovery_srv' in self._config:
load_from_srv = True
self._members_cache = self.get_peers_urls_from_dns(self._config['discovery_srv'])
- elif 'host' in self._config:
+
+ if not self._members_cache and 'host' in self._config:
+ load_from_srv = False
self._members_cache = self.get_client_urls_from_dns(self._config['host'])
- else:
- raise Exception('Neither discovery_srv nor host are defined in etcd section of config')
+
self._next_server()
response, status_code = self._get('/members') | Retry with host from config when it failed to resolve SRV | zalando_patroni | train |
8cfb1c002aaac40e46dba0a826705129ade9206b | diff --git a/hupper/reloader.py b/hupper/reloader.py
index <HASH>..<HASH> 100644
--- a/hupper/reloader.py
+++ b/hupper/reloader.py
@@ -14,9 +14,6 @@ from .interfaces import IReloaderProxy
from .polling import PollingFileMonitor
-RELOADER_ENVIRON_KEY = 'HUPPER_RELOADER'
-
-
class WatchSysModules(threading.Thread):
""" Poll ``sys.modules`` for imported modules."""
poll_interval = 1
@@ -40,18 +37,19 @@ class WatchSysModules(threading.Thread):
class WatchForParentShutdown(threading.Thread):
- """ Poll the parent process to ensure it is still alive."""
- poll_interval = 1
-
- def __init__(self, parent_pid):
+ """ Monitor the channel to ensure the parent is still alive."""
+ def __init__(self, pipe):
super(WatchForParentShutdown, self).__init__()
- self.parent_pid = parent_pid
+ self.pipe = pipe
def run(self):
- # If parent shuts down (and we are adopted by a different parent
- # process), we should shut down.
- while (os.getppid() == self.parent_pid):
- time.sleep(self.poll_interval)
+ try:
+ # wait until the pipe breaks
+ while True:
+ ret = self.pipe.poll(1)
+ print(ret)
+ except EOFError:
+ pass
interrupt_main()
@@ -62,17 +60,13 @@ class WorkerProcess(multiprocessing.Process, IReloaderProxy):
The worker process object also acts as a proxy back to the reloader.
"""
- def __init__(self, worker_path, files_queue, parent_pid, environ_key):
+ def __init__(self, worker_path, files_queue, pipe):
super(WorkerProcess, self).__init__()
self.worker_path = worker_path
self.files_queue = files_queue
- self.parent_pid = parent_pid
- self.environ_key = environ_key
+ self.pipe = pipe
def run(self):
- # activate the environ
- os.environ[self.environ_key] = '1'
-
# import the worker path
modname, funcname = self.worker_path.rsplit('.', 1)
module = importlib.import_module(modname)
@@ -81,7 +75,7 @@ class WorkerProcess(multiprocessing.Process, IReloaderProxy):
poller = WatchSysModules(self.files_queue.put)
poller.start()
- parent_watcher = WatchForParentShutdown(self.parent_pid)
+ parent_watcher = WatchForParentShutdown(self.pipe)
parent_watcher.start()
# start the worker
@@ -93,7 +87,7 @@ class WorkerProcess(multiprocessing.Process, IReloaderProxy):
self.files_queue.put(file)
def trigger_reload(self):
- os.kill(self.parent_pid, signal.SIGHUP)
+ self.pipe.send(1)
class Reloader(object):
@@ -107,7 +101,6 @@ class Reloader(object):
monitor_factory,
reload_interval=1,
verbose=1,
- environ_key=RELOADER_ENVIRON_KEY,
):
self.worker_path = worker_path
self.monitor_factory = monitor_factory
@@ -115,7 +108,6 @@ class Reloader(object):
self.verbose = verbose
self.monitor = None
self.worker = None
- self.environ_key = environ_key
self.do_not_wait = False
def out(self, msg):
@@ -158,24 +150,40 @@ class Reloader(object):
def _run_worker(self):
files_queue = multiprocessing.Queue()
+ pipe, worker_pipe = multiprocessing.Pipe()
self.worker = WorkerProcess(
self.worker_path,
files_queue,
- os.getpid(),
- self.environ_key,
+ worker_pipe,
)
self.worker.daemon = True
self.worker.start()
+ # we no longer control the worker's end of the pipe
+ worker_pipe.close()
+
self.out("Starting monitor for PID %s." % self.worker.pid)
- while not self.monitor.is_changed() and self.worker.is_alive():
+ try:
+ while not self.monitor.is_changed() and self.worker.is_alive():
+ try:
+ # if the child has sent any data then restart
+ if pipe.poll(0):
+ break
+ except EOFError: # pragma: nocover
+ pass
+
+ try:
+ path = files_queue.get(timeout=self.reload_interval)
+ except queue.Empty:
+ pass
+ else:
+ self.monitor.add_path(path)
+ finally:
try:
- path = files_queue.get(timeout=self.reload_interval)
- except queue.Empty:
+ pipe.close()
+ except: # pragma: nocover
pass
- else:
- self.monitor.add_path(path)
self.monitor.clear_changes()
@@ -247,7 +255,7 @@ def start_reloader(worker_path, reload_interval=1, verbose=1):
of activity and turn up to ``2`` for extra output.
"""
- if RELOADER_ENVIRON_KEY in os.environ:
+ if is_active():
return get_reloader()
def monitor_factory():
@@ -258,7 +266,6 @@ def start_reloader(worker_path, reload_interval=1, verbose=1):
reload_interval=reload_interval,
verbose=verbose,
monitor_factory=monitor_factory,
- environ_key=RELOADER_ENVIRON_KEY,
)
return reloader.run() | drop environ keys and use a pipe instead of signals between child/parent | Pylons_hupper | train |
48708a02aff81d985d36abff03b16f42497e6f54 | diff --git a/context.go b/context.go
index <HASH>..<HASH> 100644
--- a/context.go
+++ b/context.go
@@ -268,6 +268,11 @@ func (ctx *Context) SetParams(name, val string) {
ctx.params[name] = val
}
+// ReplaceAllParams replace all current params with given params
+func (ctx *Context) ReplaceAllParams(params Params) {
+ ctx.params = params;
+}
+
// ParamsEscape returns escapred params result.
// e.g. ctx.ParamsEscape(":uname")
func (ctx *Context) ParamsEscape(name string) string { | Method to replace all params (#<I>) | go-macaron_macaron | train |
bcad596adae76263da2a0aa9af6e99a3c578932b | diff --git a/src/tests/unit/ScaffoldControllerTest.php b/src/tests/unit/ScaffoldControllerTest.php
index <HASH>..<HASH> 100644
--- a/src/tests/unit/ScaffoldControllerTest.php
+++ b/src/tests/unit/ScaffoldControllerTest.php
@@ -92,20 +92,22 @@ class ScaffoldControllerTest extends BaseTest {
*/
public function testAddControllerAndAction() {
$this->scaffoldController->_createController ( "TestNewController", [ "%baseClass%" => "ControllerBase" ] );
- $this->assertTrue ( class_exists ( "\\controllers\\TestNewController" ) );
- $this->scaffoldController->_newAction ( "\\controllers\\TestNewController", "newAction", "a,b=5", 'echo "test-".$a."-".$b;' );
- sleep ( 2 );
- $this->_initRequest ( '/TestNewController/newAction/essai/', 'GET' );
- $this->_assertDisplayContains ( function () {
- Startup::run ( $this->config );
- $this->assertEquals ( "controllers\\TestNewController", Startup::getController () );
- }, 'test-essai-5' );
-
- $this->_initRequest ( '/TestNewController/newAction/autreEssai/12/', 'GET' );
- $this->_assertDisplayContains ( function () {
- Startup::run ( $this->config );
- $this->assertEquals ( "controllers\\TestNewController", Startup::getController () );
- }, 'test-autreEssai-12' );
+ $this->assertTrue ( class_exists ( "controllers\\TestNewController" ) );
+ $this->scaffoldController->_newAction ( "controllers\\TestNewController", "newAction", "a,b=5", "echo 'test-'.\$a.'-'.\$b;", [ "path" => "/test/new/{a}/{b}/" ] );
+ $this->assertTrue ( method_exists ( new \controllers\TestNewController (), "newAction" ) );
+ /*
+ * $_GET ["c"] = '/TestNewController/newAction/essai/';
+ * $this->_assertDisplayContains ( function () {
+ * Startup::run ( $this->config );
+ * $this->assertEquals ( "controllers\\TestNewController", Startup::getController () );
+ * }, 'test-essai-5' );
+ *
+ * $_GET ["c"] = '/TestNewController/newAction/autreEssai/12/';
+ * $this->_assertDisplayContains ( function () {
+ * Startup::run ( $this->config );
+ * $this->assertEquals ( "controllers\\TestNewController", Startup::getController () );
+ * }, 'test-autreEssai-12' );
+ */
}
/** | Update ScaffoldControllerTest.php | phpMv_ubiquity | train |
e80999585e67fc846ddfd2d544cc0d9071188965 | diff --git a/wily/commands/build.py b/wily/commands/build.py
index <HASH>..<HASH> 100644
--- a/wily/commands/build.py
+++ b/wily/commands/build.py
@@ -14,6 +14,12 @@ from wily.archivers.git import InvalidGitRepositoryError
from wily.archivers import FilesystemArchiver
+def run_operator(operator, revision, config):
+ instance = operator.cls(config)
+ logger.debug(f"Running {operator.name} operator on {revision.key}")
+ return instance.run(revision, config)
+
+
def build(config, archiver, operators):
"""
Build the history given a archiver and collection of operators.
@@ -62,22 +68,21 @@ def build(config, archiver, operators):
bar = Bar("Processing", max=len(revisions) * len(operators))
state.operators = operators
try:
- pool = multiprocessing.Pool(processes=len(operators))
- for revision in revisions:
- # Checkout target revision
- archiver.checkout(revision, config.checkout_options)
- # Build a set of operators
- _operators = [operator.cls(config) for operator in operators]
-
- stats = {"operator_data": {}}
- def run_operator(operator):
- logger.debug(f"Running {operator.name} operator on {revision.key}")
- stats["operator_data"][operator.name] = operator.run(revision, config)
+ with multiprocessing.Pool(processes=len(operators)) as pool:
+ for revision in revisions:
+ # Checkout target revision
+ archiver.checkout(revision, config.checkout_options)
+
+ stats = {"operator_data": {}}
+
bar.next()
- pool.map(run_operator, _operators)
+ data = pool.starmap(run_operator, [(operator, revision, config) for operator in operators])
+ logger.debug(data)
+
+ # stats["operator_data"][operator.name] = operator.run(revision, config)
- ir = index.add(revision, operators=operators)
- ir.store(config, archiver, stats)
+ ir = index.add(revision, operators=operators)
+ ir.store(config, archiver, stats)
index.save()
bar.finish()
except Exception as e: | use starmap for multiprocessing pools | tonybaloney_wily | train |
2515c8962f4157902da7445698081765f909b398 | diff --git a/app/views/rails_admin/main/_form_fieldset.html.erb b/app/views/rails_admin/main/_form_fieldset.html.erb
index <HASH>..<HASH> 100644
--- a/app/views/rails_admin/main/_form_fieldset.html.erb
+++ b/app/views/rails_admin/main/_form_fieldset.html.erb
@@ -1,7 +1,7 @@
<% if (fields = fieldset.fields.map{ |f| f.with(:form => form, :object => object, :view => self) }.select(&:visible)).length > 0 %>
<fieldset>
<legend><%= fieldset.label %></legend>
- <%= content_tag :div, fieldset.instructions, :class => "instructions" if fieldset.instructions %>
+ <%= content_tag :div, fieldset.help, :class => "help" if fieldset.help %>
<% fields.each do |field| %>
<%= field.render -%>
<% end %>
diff --git a/lib/rails_admin/config/fields/group.rb b/lib/rails_admin/config/fields/group.rb
index <HASH>..<HASH> 100644
--- a/lib/rails_admin/config/fields/group.rb
+++ b/lib/rails_admin/config/fields/group.rb
@@ -9,7 +9,7 @@ module RailsAdmin
include RailsAdmin::Config::Hideable
attr_reader :name
- attr_accessor :instructions
+ attr_accessor :help
def initialize(parent, name)
super(parent)
@@ -54,7 +54,7 @@ module RailsAdmin
name.to_s.humanize
end
- register_instance_option(:instructions) do
+ register_instance_option(:help) do
nil
end
diff --git a/spec/requests/config/edit/rails_admin_config_edit_spec.rb b/spec/requests/config/edit/rails_admin_config_edit_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/requests/config/edit/rails_admin_config_edit_spec.rb
+++ b/spec/requests/config/edit/rails_admin_config_edit_spec.rb
@@ -3,7 +3,7 @@ require 'spec_helper'
describe "RailsAdmin Config DSL Edit Section" do
describe "field groupings" do
-
+
it "should be hideable" do
RailsAdmin.config Team do
edit do
@@ -58,52 +58,52 @@ describe "RailsAdmin Config DSL Edit Section" do
response.should have_tag("legend", :content => "Renamed group")
end
- describe "instructions" do
+ describe "help" do
- it "should show instructions section if present" do
+ it "should show help section if present" do
RailsAdmin.config Team do
edit do
group :default do
- instructions "instructions paragraph to display"
+ help "help paragraph to display"
end
end
end
get rails_admin_new_path(:model_name => "team")
- response.should have_tag('.instructions', :content => "instructions paragraph to display")
+ response.should have_tag('div.help', :content => "help paragraph to display")
end
- it "should not show instructions if not present" do
+ it "should not show help if not present" do
RailsAdmin.config Team do
edit do
group :default do
- label 'no_instructions'
+ label 'no help'
end
end
end
get rails_admin_new_path(:model_name => "team")
- response.should_not have_tag('.instructions')
+ response.should_not have_tag('div.help')
end
- it "should be able to display multiple instructions if there are multiple sections" do
+ it "should be able to display multiple help if there are multiple sections" do
RailsAdmin.config Team do
edit do
group :default do
field :name
- instructions 'instructions for default'
+ help 'help for default'
end
group :other_section do
label "Other Section"
field :division_id
- instructions 'instructions for other section'
+ help 'help for other section'
end
end
end
get rails_admin_new_path(:model_name => "team")
- response.should have_tag(".instructions", :content => 'instructions for default')
- response.should have_tag(".instructions", :content => 'instructions for other section')
- response.should have_tag(".instructions", :count => 2)
+ response.should have_tag("div.help", :content => 'help for default')
+ response.should have_tag("div.help", :content => 'help for other section')
+ response.should have_tag("div.help", :count => 2)
end
end | replaced the instruction tag with DIV.help | sferik_rails_admin | train |
e753f168e4218babf7c2c776dc945f33f175b0fc | diff --git a/tests/test_msg_changepin.py b/tests/test_msg_changepin.py
index <HASH>..<HASH> 100644
--- a/tests/test_msg_changepin.py
+++ b/tests/test_msg_changepin.py
@@ -37,6 +37,8 @@ class TestMsgChangepin(common.KeepKeyTest):
# Now we're done
self.assertIsInstance(ret, proto.Success)
+ self.client.clear_session()
+
# Check that there's PIN protection now
features = self.client.call_raw(proto.Initialize())
self.assertTrue(features.pin_protection)
@@ -52,6 +54,8 @@ class TestMsgChangepin(common.KeepKeyTest):
features = self.client.call_raw(proto.Initialize())
self.assertTrue(features.pin_protection)
+ self.client.clear_session()
+
# Check that there's PIN protection
ret = self.client.call_raw(proto.Ping(pin_protection=True))
self.assertIsInstance(ret, proto.PinMatrixRequest)
@@ -86,6 +90,8 @@ class TestMsgChangepin(common.KeepKeyTest):
# Now we're done
self.assertIsInstance(ret, proto.Success)
+ self.client.clear_session()
+
# Check that there's still PIN protection now
features = self.client.call_raw(proto.Initialize())
self.assertTrue(features.pin_protection)
@@ -101,6 +107,8 @@ class TestMsgChangepin(common.KeepKeyTest):
features = self.client.call_raw(proto.Initialize())
self.assertTrue(features.pin_protection)
+ self.client.clear_session()
+
# Check that there's PIN protection
ret = self.client.call_raw(proto.Ping(pin_protection=True))
self.assertIsInstance(ret, proto.PinMatrixRequest) | fixed test to reflect that pin is cached when pin is written to storage | keepkey_python-keepkey | train |
404cbf902fa61e7a19b04be932f5c808b4bc7af7 | diff --git a/options.go b/options.go
index <HASH>..<HASH> 100644
--- a/options.go
+++ b/options.go
@@ -91,6 +91,11 @@ type Watermark struct {
Background Color
}
+type GaussianBlur struct {
+ Sigma float64
+ MinAmpl float64
+}
+
type Options struct {
Height int
Width int
@@ -117,4 +122,5 @@ type Options struct {
Type ImageType
Interpolator Interpolator
Interpretation Interpretation
+ GaussianBlur GaussianBlur
}
diff --git a/vips.go b/vips.go
index <HASH>..<HASH> 100644
--- a/vips.go
+++ b/vips.go
@@ -432,3 +432,14 @@ func boolToInt(b bool) int {
}
return 0
}
+
+func vipsGaussianBlur(image *C.VipsImage, o GaussianBlur) (*C.VipsImage, error) {
+ var out *C.VipsImage
+ defer C.g_object_unref(C.gpointer(image))
+
+ err := C.vips__gaussblur(image, &out, C.double(o.Sigma), C.double(o.MinAmpl))
+ if err != 0 {
+ return nil, catchVipsError()
+ }
+ return out, nil
+}
diff --git a/vips.h b/vips.h
index <HASH>..<HASH> 100644
--- a/vips.h
+++ b/vips.h
@@ -16,6 +16,9 @@
*/
#if (VIPS_MAJOR_VERSION == 7 && VIPS_MINOR_VERSION < 41)
+/* we need math.h for ceil() in vips__gaussblur */
+#include <math.h>
+
#define VIPS_ANGLE_D0 VIPS_ANGLE_0
#define VIPS_ANGLE_D90 VIPS_ANGLE_90
#define VIPS_ANGLE_D180 VIPS_ANGLE_180
@@ -321,3 +324,12 @@ vips_watermark(VipsImage *in, VipsImage **out, WatermarkTextOptions *to, Waterma
g_object_unref(base);
return 0;
}
+
+int
+vips__gaussblur(VipsImage *in, VipsImage **out, double sigma, double min_ampl) {
+#if (VIPS_MAJOR_VERSION == 7 && VIPS_MINOR_VERSION < 41)
+ return vips_gaussblur(in, out, ceil(sigma), NULL);
+#else
+ return vips_gaussblur(in, out, sigma, NULL, "min_ampl", min_ampl);
+#endif
+} | vips: add a vips__gaussblur method
handle both < <I> and higher.
Prior <I>, vips_gaussblur took only a int param, the radius.
The radius was then divided by <I> (min_ampl) in vips_gaussblur.
After, you can now parameter the min_ampl and radius became sigma (and
passed from an integer to a double). | h2non_bimg | train |
cb99ca9862827f57c370555841810e98701ecfa2 | diff --git a/tools/dfu.py b/tools/dfu.py
index <HASH>..<HASH> 100755
--- a/tools/dfu.py
+++ b/tools/dfu.py
@@ -20,7 +20,7 @@ def consume(fmt, data, names):
def cstring(string):
- return string.split("\0", 1)[0]
+ return string.split(b"\0", 1)[0]
def compute_crc(data): | tools/dfu.py: Make tool work with python3 when parsing DFU files. | micropython_micropython | train |
e7fe5edc89317e8d65248e1a914ec62951153b53 | diff --git a/src/browser-client/qmachine.js b/src/browser-client/qmachine.js
index <HASH>..<HASH> 100644
--- a/src/browser-client/qmachine.js
+++ b/src/browser-client/qmachine.js
@@ -15,29 +15,26 @@
ActiveXObject, CoffeeScript, JSLINT, Q, QM, XDomainRequest,
XMLHttpRequest, a, addEventListener, adsafe, anon, appendChild, apply,
atob, attachEvent, avar, b, bitwise, body, box, browser, btoa, by,
- call, can_run_remotely, cap, charAt, charCodeAt, comm, compile, concat,
- configurable, console, constructor, contentWindow, continue,
- createElement, css, data, debug, def, defineProperty, detachEvent,
- devel, diagnostics, display, document, done, enumerable, env, epitaph,
- eqeq, errors, es5, eval, evil, exemptions, exit, f, fail, floor, forin,
- fragment, fromCharCode, get, getElementsByTagName, global,
- hasOwnProperty, head, host, ignoreCase, importScripts, indexOf, join,
- key, length, lib, load_data, load_script, location, log, map, mapf,
- mapreduce, method, multiline, navigator, newcap, node, nomen, now, on,
- onLine, onload, onreadystatechange, open, parentElement, parse,
- passfail, plusplus, ply, postMessage, predef, properties, protocol,
- prototype, push, puts, query, random, readyState, reason, recent, redf,
- reduce, regexp, removeChild, removeEventListener, replace,
- responseText, result, results, revive, rhino, run_remotely, safe, send,
- set, setTimeout, shelf, shift, slice, sloppy, source, src, status,
- stay, stringify, stupid, style, sub, submit, test, time, toJSON,
- toSource, toString, todo, undef, unparam, url, using, val, value,
- valueOf, vars, via, visibility, volunteer, when, white, window,
- windows, withCredentials, writable, x, y
+ call, can_run_remotely, cap, charAt, charCodeAt, comm, configurable,
+ console, constructor, contentWindow, continue, createElement, css,
+ data, debug, def, defineProperty, detachEvent, devel, diagnostics,
+ display, document, done, enumerable, env, epitaph, eqeq, errors, es5,
+ eval, evil, exemptions, exit, f, fail, floor, forin, fragment,
+ fromCharCode, get, getElementsByTagName, global, hasOwnProperty, head,
+ host, ignoreCase, importScripts, indexOf, join, key, length, lib,
+ load_data, load_script, location, log, map, mapreduce, method,
+ multiline, navigator, newcap, node, nomen, now, on, onLine, onload,
+ onreadystatechange, open, parentElement, parse, passfail, plusplus,
+ ply, postMessage, predef, properties, protocol, prototype, push, puts,
+ query, random, readyState, reason, recent, reduce, regexp, removeChild,
+ removeEventListener, replace, responseText, result, results, revive,
+ rhino, run_remotely, safe, send, set, setTimeout, shelf, shift, slice,
+ sloppy, source, src, status, stay, stringify, stupid, style, sub,
+ submit, test, time, toJSON, toSource, toString, todo, undef, unparam,
+ url, val, value, valueOf, vars, via, visibility, volunteer, when,
+ white, window, windows, withCredentials, writable, x, y
*/
- // Prerequisites
-
if (global.hasOwnProperty('QM')) {
// Exit early if QMachine is already present.
return;
@@ -273,10 +270,7 @@
y.val = global.CoffeeScript.eval(x);
lib_evt.exit();
return evt.exit();
- }).on('error', function (message) {
- // This function needs documentation.
- return evt.fail(message);
- });
+ }).on('error', evt.fail);
return;
});
return y;
@@ -668,10 +662,7 @@
'USE "http://wilkinson.github.com/qmachine/qm.proxy.xml";' +
'SELECT * FROM qm.proxy WHERE url="' + y.val.url + '";';
temp = lib(base + [callback, diag, format, query].join('&'));
- temp.on('error', function (message) {
- // This function needs documentation.
- return evt.fail(message);
- });
+ temp.on('error', evt.fail);
return;
};
y.on('error', function (message) {
@@ -1326,10 +1317,7 @@
};
f_evt.exit();
return evt.exit();
- }).on('error', function (message) {
- // This function needs documentation.
- return evt.fail(message);
- });
+ }).on('error', evt.fail);
return;
});
y.Q(function (evt) {
@@ -1362,17 +1350,13 @@
temp.Q(function (evt) {
// This function runs remotely on a volunteer machine.
/*global QM: false */
- var env, f, handler, temp, x;
+ var env, f, temp, x;
env = QM.avar({val: this.val.env});
f = this.val.f;
- handler = function (message) {
- // This function needs documentation.
- return evt.fail(message);
- };
temp = this;
x = QM.avar({val: this.val.x});
- env.on('error', handler);
- x.on('error', handler);
+ env.on('error', evt.fail);
+ x.on('error', evt.fail);
QM.when(env, x).Q(function (evt) {
// This function ensures that the task will not execute until
// the prerequisite scripts have finished loading. | Cleaned up /*properties*/ pragma in "qmachine.js" | qmachine_qm-nodejs | train |
5debcfe8741e5c7d57fd9a734028f8a9dfd683b5 | diff --git a/setup.py b/setup.py
index <HASH>..<HASH> 100644
--- a/setup.py
+++ b/setup.py
@@ -1,4 +1,6 @@
-VERSION = (0, 1, 1, "f", 0) # following PEP 386
+from __future__ import print_function
+
+VERSION = (0, 1, 2, "f", 0) # following PEP 386
DEV_N = None
import os
@@ -80,9 +82,7 @@ def find_package_data(
or fn.lower() == pattern.lower()):
bad_name = True
if show_ignored:
- print >> sys.stderr, (
- "Directory %s ignored by pattern %s"
- % (fn, pattern))
+ print("Directory %s ignored by pattern %s" % (fn, pattern), file=sys.stderr)
break
if bad_name:
continue | Ensure setup.py works with both Python2 and Python3. Also version
bumped. | agiliq_django-graphos | train |
21f84a0c35dee5d69b39617fdb142c72d8f6bda8 | diff --git a/app/dataformats/prottable.py b/app/dataformats/prottable.py
index <HASH>..<HASH> 100644
--- a/app/dataformats/prottable.py
+++ b/app/dataformats/prottable.py
@@ -8,6 +8,6 @@ HEADER_NO_PSM = '# PSMs'
HEADER_AREA = 'MS1 precursor area'
HEADER_NO_QUANT_PSM = '# Quantified PSMs'
HEADER_CV_QUANT_PSM = '# CV of quantified PSMs'
-HEADER_PROBABILITY = 'Protein probability'
+HEADER_PROBABILITY = 'Protein error probability'
HEADER_QVAL = 'q-value'
HEADER_PEP = 'PEP' | Better/correct column name for protein error probabilities | glormph_msstitch | train |
3a4f710bc035af25b3e45e72eb11b3eaeb777bea | diff --git a/lib/mobylette/resolvers/chained_fallback_resolver.rb b/lib/mobylette/resolvers/chained_fallback_resolver.rb
index <HASH>..<HASH> 100644
--- a/lib/mobylette/resolvers/chained_fallback_resolver.rb
+++ b/lib/mobylette/resolvers/chained_fallback_resolver.rb
@@ -1,13 +1,15 @@
module Mobylette
module Resolvers
class ChainedFallbackResolver < ::ActionView::FileSystemResolver
+ DEFAULT_PATTERN = "{:path}/:prefix/:action{.:locale,}{.:formats,}{.:handlers,}"
# Initializes the fallback resolver with a default
# mobile format.
#
- def initialize(formats = {})
- @fallback_formats = formats.reverse_merge!({ mobile: [:mobile] })
- super('app/views')
+ def initialize(formats = {}, view_paths = ['app/views'])
+ @fallback_formats = formats
+ @paths = view_paths.map { |view_path| File.expand_path(view_path)}
+ super(@paths.first, DEFAULT_PATTERN)
end
# Updates the fallback resolver replacing the
@@ -29,10 +31,12 @@ module Mobylette
# it will behave as a normal FileSystemResovler.
#
def replace_fallback_formats_chain(formats)
- @fallback_formats = formats.reverse_merge!({ mobile: [:mobile] })
+ @fallback_formats = formats
end
- # Public: finds the right template on the filesystem,
+ private
+
+ # Private: finds the right template on the filesystem,
# using fallback if needed
#
def find_templates(name, prefix, partial, details)
@@ -43,6 +47,23 @@ module Mobylette
end
super(name, prefix, partial, details)
end
+
+ # Helper for building query glob string based on resolver's pattern.
+ def build_query(path, details)
+ query = @pattern.dup
+
+ prefix = path.prefix.empty? ? "" : "#{escape_entry(path.prefix)}\\1"
+ query.gsub!(/\:prefix(\/)?/, prefix)
+
+ partial = escape_entry(path.partial? ? "_#{path.name}" : path.name)
+ query.gsub!(/\:action/, partial)
+
+ details.each do |ext, variants|
+ query.gsub!(/\:#{ext}/, "{#{variants.compact.uniq.join(',')}}")
+ end
+
+ query.gsub!(/\:path/, "{#{@paths.compact.uniq.join(',')}}")
+ end
end
end
end
diff --git a/lib/mobylette/respond_to_mobile_requests.rb b/lib/mobylette/respond_to_mobile_requests.rb
index <HASH>..<HASH> 100644
--- a/lib/mobylette/respond_to_mobile_requests.rb
+++ b/lib/mobylette/respond_to_mobile_requests.rb
@@ -43,13 +43,11 @@ module Mobylette
@@mobylette_options[:devices] = Hash.new
cattr_accessor :mobylette_resolver
- self.mobylette_resolver = Mobylette::Resolvers::ChainedFallbackResolver.new()
+ self.mobylette_resolver = Mobylette::Resolvers::ChainedFallbackResolver.new({}, self.view_paths)
self.mobylette_resolver.replace_fallback_formats_chain(@@mobylette_options[:fallback_chains])
append_view_path self.mobylette_resolver
end
-
-
module ClassMethods
# This method enables the controller do handle mobile requests
#
@@ -120,7 +118,7 @@ module Mobylette
self.mobylette_resolver.replace_fallback_formats_chain({ mobile: [:mobile, options[:fall_back]] })
else
if options[:fallback_chains]
- self.mobylette_resolver.replace_fallback_formats_chain(options[:fallback_chains])
+ self.mobylette_resolver.replace_fallback_formats_chain((options[:fallback_chains] || {}).reverse_merge({ mobile: [:mobile, :html] }))
end
end
end
diff --git a/spec/lib/resolvers/chained_fallback_resolver_spec.rb b/spec/lib/resolvers/chained_fallback_resolver_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/lib/resolvers/chained_fallback_resolver_spec.rb
+++ b/spec/lib/resolvers/chained_fallback_resolver_spec.rb
@@ -5,7 +5,6 @@ module Mobylette
describe ChainedFallbackResolver do
describe "#find_templates" do
-
context "single fallback chain" do
[
{ mobile: [:mobile, :html]},
@@ -17,7 +16,7 @@ module Mobylette
it "should change details[:formats] to the fallback array" do
details = { formats: [fallback_chain.keys.first] }
details.stub(:dup).and_return(details)
- subject.find_templates("", "", "", details)
+ subject.send(:find_templates, "", "", "", details)
details[:formats].should == fallback_chain.values.first
end
@@ -34,14 +33,26 @@ module Mobylette
it "should change details[:formats] to the fallback array" do
details = { formats: [format] }
details.stub(:dup).and_return(details)
- subject.find_templates("", "", "", details)
+ subject.send(:find_templates, "", "", "", details)
details[:formats].should == fallback_array
end
end
end
end
+ end
+ describe "#build_query" do
+ it "should merge paths, formats, and handlers" do
+ details = {:locale=>[:en], :formats=>[:mobile, :html], :handlers=>[:erb, :builder, :coffee]}
+ paths = ['/app1/home', '/app2/home']
+ path = ActionView::Resolver::Path.build('index', 'tests', nil)
+
+ resolver = Mobylette::Resolvers::ChainedFallbackResolver.new({}, paths)
+ query = subject.send :build_query, path, details
+ query.should == "{/app1/home,/app2/home}/tests/index{.{en},}{.{html},}{.{erb,builder,coffee},}"
+ end
end
+
end
end
end | Adding view_paths to resolver paths.
Resolver was using only the application path for looking for views.
Now it receives the view_paths from the controller, so it can look inside
engines for views to fallback. | tscolari_mobylette | train |
b3039c3b12b4761f260f02ff977e6a543800fc8a | diff --git a/pypiper/pypiper.py b/pypiper/pypiper.py
index <HASH>..<HASH> 100644
--- a/pypiper/pypiper.py
+++ b/pypiper/pypiper.py
@@ -806,7 +806,8 @@ class PipelineManager(object):
files = glob.glob(regex)
for file in files:
with open(self.cleanup_file, "a") as myfile:
- myfile.write("rm " + file + "\n")
+ if os.path.isfile(file): myfile.write("rm " + file + "\n")
+ elif os.path.isdir(file): myfile.write("rmdir " + file + "\n")
except:
pass
elif conditional:
@@ -834,7 +835,10 @@ class PipelineManager(object):
# and delete the files
for file in files:
print("`rm " + file + "`")
- os.remove(os.path.join(file))
+ os.remove(os.path.join(file))
+ elif os.path.isdir(file):
+ print("`rmdir " + file + "`")
+ os.rmdir(os.path.join(file))
except:
pass
@@ -849,8 +853,12 @@ class PipelineManager(object):
files = glob.glob(expr)
while files in self.cleanup_list_conditional: self.cleanup_list_conditional.remove(files)
for file in files:
- print("rm " + file)
- os.remove(os.path.join(file))
+ if os.path.isfile(file):
+ print("rm " + file)
+ os.remove(os.path.join(file))
+ elif os.path.isdir(file):
+ print("`rmdir " + file + "`")
+ os.rmdir(os.path.join(file))
except:
pass
else:
@@ -862,7 +870,8 @@ class PipelineManager(object):
files = glob.glob(expr)
for file in files:
with open(self.cleanup_file, "a") as myfile:
- myfile.write("`rm " + file + "`\n")
+ if os.path.isfile(file): myfile.write("`rm " + file + "`\n")
+ elif os.path.isdir(file): myfile.write("`rmdir " + file + "`\n")
except:
pass | Revert to rmdir capability that was erroneously removed | databio_pypiper | train |
26456f81fe7e373b55c4b1b1eb05f12e5160fbf4 | diff --git a/packages/ra-ui-materialui/src/input/AutocompleteInput.js b/packages/ra-ui-materialui/src/input/AutocompleteInput.js
index <HASH>..<HASH> 100644
--- a/packages/ra-ui-materialui/src/input/AutocompleteInput.js
+++ b/packages/ra-ui-materialui/src/input/AutocompleteInput.js
@@ -184,16 +184,9 @@ export class AutocompleteInput extends React.Component {
const { input } = this.props;
const inputValue = this.getSuggestionValue(suggestion);
- this.setState(
- {
- dirty: false,
- inputValue,
- selectedItem: suggestion,
- searchText: this.getSuggestionText(suggestion),
- suggestions: [suggestion],
- },
- () => input && input.onChange && input.onChange(inputValue)
- );
+ if (input && input.onChange) {
+ input.onChange(inputValue)
+ }
if (method === 'enter') {
event.preventDefault(); | [RFR] Fix AutocompleteInput reopen after selection
Fixes #<I> | marmelab_react-admin | train |
2b0a4d6dae45b5ae9ebd98aacf819aa72d6b2595 | diff --git a/src/org/opencms/workplace/CmsPropertyAdvanced.java b/src/org/opencms/workplace/CmsPropertyAdvanced.java
index <HASH>..<HASH> 100644
--- a/src/org/opencms/workplace/CmsPropertyAdvanced.java
+++ b/src/org/opencms/workplace/CmsPropertyAdvanced.java
@@ -1,7 +1,7 @@
/*
* File : $Source: /alkacon/cvs/opencms/src/org/opencms/workplace/Attic/CmsPropertyAdvanced.java,v $
- * Date : $Date: 2004/04/07 09:22:13 $
- * Version: $Revision: 1.9 $
+ * Date : $Date: 2004/04/08 14:46:52 $
+ * Version: $Revision: 1.10 $
*
* This library is part of OpenCms -
* the Open Source Content Mananagement System
@@ -66,7 +66,7 @@ import javax.servlet.jsp.PageContext;
* </ul>
*
* @author Andreas Zahner ([email protected])
- * @version $Revision: 1.9 $
+ * @version $Revision: 1.10 $
*
* @since 5.1
*/
@@ -934,7 +934,7 @@ public class CmsPropertyAdvanced extends CmsTabDialog implements I_CmsDialogHand
newValue = newProperty.getResourceValue();
// write the resource value if the existing resource value is not null and we want to delete the resource value
- writeResourceValue = (oldValue != null && newProperty.deleteStructureValue());
+ writeResourceValue = (oldValue != null && newProperty.deleteResourceValue());
// or if we want to write a value which is neither the delete value or an empty value
writeResourceValue |= !newValue.equals(oldValue) && !"".equalsIgnoreCase(newValue) && !CmsProperty.C_DELETE_VALUE.equalsIgnoreCase(newValue);
// set the resource value explicitly to null to leave it as is in the database | Fixed deleting of property resource values. | alkacon_opencms-core | train |
8cb19deabab00a7fb788bc39fe9f1f7b68a10776 | diff --git a/cookbooks/site/ruby-shadow/recipes/default.rb b/cookbooks/site/ruby-shadow/recipes/default.rb
index <HASH>..<HASH> 100755
--- a/cookbooks/site/ruby-shadow/recipes/default.rb
+++ b/cookbooks/site/ruby-shadow/recipes/default.rb
@@ -1,4 +1,4 @@
-site_ruby = node[:ruby_shadow][:site_ruby] || "/usr/lib/ruby/site_ruby/1.8"
+site_ruby = (node[:ruby_shadow] && node[:ruby_shadow][:site_ruby]) || "/usr/lib/ruby/site_ruby/1.8"
remote_directory "/usr/local/src/shadow-1.4.1" do
source 'shadow-1.4.1'
diff --git a/lib/solokit/version.rb b/lib/solokit/version.rb
index <HASH>..<HASH> 100644
--- a/lib/solokit/version.rb
+++ b/lib/solokit/version.rb
@@ -1,3 +1,3 @@
module Solokit
- VERSION = "0.1.13"
+ VERSION = "0.1.14"
end | Fix ruby_shadow recipie when it's not given any config. | joakimk_solokit | train |
b25c41e6d884372f7d70801f832e24dbff3e9077 | diff --git a/activerecord/lib/active_record/association_preload.rb b/activerecord/lib/active_record/association_preload.rb
index <HASH>..<HASH> 100644
--- a/activerecord/lib/active_record/association_preload.rb
+++ b/activerecord/lib/active_record/association_preload.rb
@@ -126,7 +126,7 @@ module ActiveRecord
parent_records.each do |parent_record|
association_proxy = parent_record.send(reflection_name)
association_proxy.loaded
- association_proxy.target.push *Array.wrap(associated_record)
+ association_proxy.target.push(*Array.wrap(associated_record))
association_proxy.__send__(:set_inverse_instance, associated_record, parent_record)
end | no more warning interpreted as argument prefix on association_preload.rb | rails_rails | train |
bb2573fec7dc72f6c9c575971e8f1db620c61f1e | diff --git a/benchmark/benchmark.rb b/benchmark/benchmark.rb
index <HASH>..<HASH> 100755
--- a/benchmark/benchmark.rb
+++ b/benchmark/benchmark.rb
@@ -8,6 +8,8 @@ require "clamp"
require "benchmark"
require "ostruct"
+require "jbuilder"
+
require "representative/json"
require "representative/nokogiri"
require "representative/xml"
@@ -38,7 +40,7 @@ $books = [
class RepresentativeBenchmark < Clamp::Command
- ALL_STRATEGIES = %w(builder nokogiri json to_json)
+ ALL_STRATEGIES = %w(builder nokogiri json to_json jbuilder)
def self.validate_strategy(strategy)
unless ALL_STRATEGIES.member?(strategy)
@@ -128,7 +130,7 @@ class RepresentativeBenchmark < Clamp::Command
end
def with_json
- r = Representative::Json.new
+ r = Representative::Json.new(nil, :indentation => false)
represent_books_using(r)
r.to_json
end
@@ -149,6 +151,23 @@ class RepresentativeBenchmark < Clamp::Command
book_data.to_json
end
+ def with_jbuilder
+ Jbuilder.encode do |json|
+ json.array!($books) do |json, book|
+ json.title(book.title)
+ json.authors(book.authors)
+ if book.published
+ json.published do |json|
+ json.by(book.published.by)
+ json.year(book.published.year)
+ end
+ else
+ json.published(nil)
+ end
+ end
+ end
+ end
+
end
RepresentativeBenchmark.run | Add Jbuilder example to benchmarks. | mdub_representative | train |
7d293e3efadfc4f6a09fa4c2a36bf99e1bbf6816 | diff --git a/pkg/volume/volume_linux.go b/pkg/volume/volume_linux.go
index <HASH>..<HASH> 100644
--- a/pkg/volume/volume_linux.go
+++ b/pkg/volume/volume_linux.go
@@ -89,32 +89,22 @@ func legacyOwnershipChange(mounter Mounter, fsGroup *int64) error {
}
func changeFilePermission(filename string, fsGroup *int64, readonly bool, info os.FileInfo) error {
- // chown and chmod pass through to the underlying file for symlinks.
+ err := os.Lchown(filename, -1, int(*fsGroup))
+ if err != nil {
+ klog.Errorf("Lchown failed on %v: %v", filename, err)
+ }
+
+ // chmod passes through to the underlying file for symlinks.
// Symlinks have a mode of 777 but this really doesn't mean anything.
// The permissions of the underlying file are what matter.
// However, if one reads the mode of a symlink then chmods the symlink
// with that mode, it changes the mode of the underlying file, overridden
// the defaultMode and permissions initialized by the volume plugin, which
- // is not what we want; thus, we skip chown/chmod for symlinks.
+ // is not what we want; thus, we skip chmod for symlinks.
if info.Mode()&os.ModeSymlink != 0 {
return nil
}
- stat, ok := info.Sys().(*syscall.Stat_t)
- if !ok {
- return nil
- }
-
- if stat == nil {
- klog.Errorf("Got nil stat_t for path %v while setting ownership of volume", filename)
- return nil
- }
-
- err := os.Chown(filename, int(stat.Uid), int(*fsGroup))
- if err != nil {
- klog.Errorf("Chown failed on %v: %v", filename, err)
- }
-
mask := rwMask
if readonly {
mask = roMask | volume: Change owner of symlinks too
This commit uses Lchown instead of Chown to change the owner of symlinks too.
It doesn't change any behaviour. However, it could avoid some confusions as the
symlinks are updated to the correct owner too. | kubernetes_kubernetes | train |
1a5cf06b892f5454a37b6dbd651c1cc08b16f991 | diff --git a/src/saml2/server.py b/src/saml2/server.py
index <HASH>..<HASH> 100644
--- a/src/saml2/server.py
+++ b/src/saml2/server.py
@@ -315,29 +315,37 @@ class Server(object):
return make_instance(samlp.Response, tmp)
- def filter_ava(self, ava, sp_entity_id, required=None, optional=None,
- role=""):
+ def filter_ava(self, ava, sp_entity_id, required=None, optional=None,
+ typ="idp"):
""" What attribute and attribute values returns depends on what
the SP has said it wants in the request or in the metadata file and
what the IdP/AA wants to release. An assumption is that what the SP
- asks for overrides whatever is in the metadata.
+ asks for overrides whatever is in the metadata. But of course the
+ IdP never releases anything it doesn't want to.
+
+ :param ava: All the attributes and values that are available
+ :param sp_entity_id: The entity ID of the SP
+ :param required: Attributes that the SP requires in the assertion
+ :param optional: Attributes that the SP thinks is optional
+ :param typ: IdPs and AAs does this, and they have different parts
+ of the configuration.
+ :return: A possibly modified AVA
"""
- #print self.conf["service"][role]
- #print self.conf["service"][role]["assertions"][sp_entity_id]
-
try:
- restrictions = self.conf["service"][role][
- "assertions"][sp_entity_id][
- "attribute_restrictions"]
- except KeyError:
+ assertions = self.conf["service"][typ]["assertions"]
try:
- restrictions = self.conf["service"][role]["assertions"][
- "default"]["attribute_restrictions"]
+ restrictions = assertions[sp_entity_id][
+ "attribute_restrictions"]
except KeyError:
- restrictions = None
+ try:
+ restrictions = assertions["default"][
+ "attribute_restrictions"]
+ except KeyError:
+ restrictions = None
+ except KeyError:
+ restrictions = None
- #print restrictions
if restrictions:
ava = filter_attribute_value_assertions(ava, restrictions)
@@ -380,8 +388,7 @@ class Server(object):
# Do attribute filtering
(required, optional) = self.conf["metadata"].attribute_consumer(spid)
try:
- identity = self.filter_ava( identity, spid, required,
- optional, "idp")
+ identity = self.filter_ava( identity, spid, required, optional)
resp = self.do_sso_response(
destination, # consumer_url
in_response_to, # in_response_to | More documentation, changed attribute name and assigned a default. Tests for one more situation (no assertion restrictions defined) | IdentityPython_pysaml2 | train |
382fe63a33b8a0c177ea04060e18997b33b9c6b9 | diff --git a/src/components/props/watchExpressions.js b/src/components/props/watchExpressions.js
index <HASH>..<HASH> 100644
--- a/src/components/props/watchExpressions.js
+++ b/src/components/props/watchExpressions.js
@@ -5,23 +5,38 @@ function watch (expressions, reactiveData) {
return (watchFunc) => {
// for `vprops` / `vdata`
if (isString(expressions)) {
- watchFunc(expressions, (newVal) => {
- Vue.set(reactiveData, '_v', isArray(newVal) ? [...newVal] : newVal)
- })
+ watchFunc(expressions, Vue.set.bind(Vue, reactiveData, '_v'))
return
}
// for `vprops-something`
Object.keys(expressions)
.forEach((name) => {
- watchFunc(expressions[name], (newVal) => {
- Vue.set(reactiveData._v, name, isArray(newVal) ? [...newVal] : newVal)
- })
+ watchFunc(expressions[name], Vue.set.bind(Vue, reactiveData._v, name))
})
}
}
/**
+ * @param setter Function a reactive setter from VueKS
+ * @returns Function a watch callback when the expression value is changed
+ */
+function notify (setter) {
+ return function (newVal) {
+ // `Vue.set` use a shallow comparision to detect the change, so...
+ //
+ // (1) For an array, we have to create a new one to get around the limitation that
+ // the shallow comparison cannot detect the reference change of the array element
+ // (2) For an object, we don't need to create a new one because the object is reactive
+ // and any changes of the properties will notify the reactivity system
+ // (3) If the reference is changed in Angular Scope, the shallow comparison can detect
+ // it and then trigger view updates
+ //
+ setter(isArray(newVal) ? [...newVal] : newVal)
+ }
+}
+
+/**
*
* @param dataExprsMap Object
* @param dataExprsMap.data Object|string|null
@@ -43,18 +58,18 @@ export default function watchExpressions (dataExprsMap, reactiveData, depth, sco
switch (depth) {
case 'value':
watcher((expression, setter) => {
- scope.$watch(expression, setter, true)
+ scope.$watch(expression, notify(setter), true)
})
break
case 'collection':
watcher((expression, setter) => {
- scope.$watchCollection(expression, setter)
+ scope.$watchCollection(expression, notify(setter))
})
break
case 'reference':
default:
watcher((expression, setter) => {
- scope.$watch(expression, setter)
+ scope.$watch(expression, notify(setter))
})
}
} | refactor(watch-expression): simplify the reactive setter | ngVue_ngVue | train |
77d7688b0cf739d37ff94b2cbdcdd31dc125b848 | diff --git a/src/Parsing/Html.php b/src/Parsing/Html.php
index <HASH>..<HASH> 100644
--- a/src/Parsing/Html.php
+++ b/src/Parsing/Html.php
@@ -262,7 +262,7 @@ class Html
$tokens = array();
// regexp to separate the tags from the texts
- $reg = '/(<[^>\s]+>)|([^<]+|<)/is';
+ $reg = '/(<\/?\w[^<>]*>)|([^<]+|<)/is';
// last match found
$str = ''; | fix tokenization regex to match tag with attrobutes | spipu_html2pdf | train |
269f73354c9af2d960a8f0f364f85b7d922e3a4d | diff --git a/servers/src/main/java/tachyon/worker/block/BlockMasterSync.java b/servers/src/main/java/tachyon/worker/block/BlockMasterSync.java
index <HASH>..<HASH> 100644
--- a/servers/src/main/java/tachyon/worker/block/BlockMasterSync.java
+++ b/servers/src/main/java/tachyon/worker/block/BlockMasterSync.java
@@ -50,7 +50,8 @@ import tachyon.util.ThreadFactoryUtils;
*/
public class BlockMasterSync implements Runnable {
private static final Logger LOG = LoggerFactory.getLogger(Constants.LOGGER_TYPE);
-
+ /** The thread pool to remove block */
+ private static final int DEFAULT_BLOCK_REMOVER_POOL_SIZE = 10;
/** Block data manager responsible for interacting with Tachyon and UFS storage */
private final BlockDataManager mBlockDataManager;
/** The executor service for the master client thread */
@@ -70,8 +71,6 @@ public class BlockMasterSync implements Runnable {
private volatile boolean mRunning;
/** The id of the worker */
private long mWorkerId;
- /** The thread pool to remove block */
- private static final int DEFAULT_BLOCK_REMOVER_POOL_SIZE = 10;
private final ExecutorService mFixedExecutionService =
Executors.newFixedThreadPool(DEFAULT_BLOCK_REMOVER_POOL_SIZE); | [TACHYON-<I>] Reorder variable declarations in tachyon.worker.block.BlockMasterSync | Alluxio_alluxio | train |
0f0df91630b52574e859e44002df9ed40bf42997 | diff --git a/test/test_cli.js b/test/test_cli.js
index <HASH>..<HASH> 100644
--- a/test/test_cli.js
+++ b/test/test_cli.js
@@ -29,6 +29,8 @@ function stealTools(args){
}
describe("steal-tools cli", function(){
+ this.timeout(5000);
+
describe("build", function(){
describe("basics", function(){
beforeEach(function(){
@@ -84,7 +86,6 @@ describe("steal-tools cli", function(){
});
it("uses package.json", function(done){
- this.timeout(5000);
stealTools(["--no-minify"]).then(function(){
open("test/npm/prod.html", function(browser, close){
var h1s = browser.window.document.getElementsByTagName('h1');
@@ -112,6 +113,7 @@ describe("steal-tools cli", function(){
});
it("works", function(done){
+
stealTools(["transform", "-c", "stealconfig.js", "-m",
"pluginify/pluginify", "--out", "pluginify/out.js"]).then(function(){ | Increase cli timeouts, for Travis | stealjs_steal-tools | train |
f2ea05b7b729aabeacab876eef24c846b41ed6a5 | diff --git a/lib/sfn/version.rb b/lib/sfn/version.rb
index <HASH>..<HASH> 100644
--- a/lib/sfn/version.rb
+++ b/lib/sfn/version.rb
@@ -1,4 +1,4 @@
module Sfn
# Current library version
- VERSION = Gem::Version.new('3.0.4')
+ VERSION = Gem::Version.new('3.0.5')
end | Update version for development <I> | sparkleformation_sfn | train |
209fd2b95237dc2d2f402677bf82225057cdefa3 | diff --git a/commons/proc/nfsd.go b/commons/proc/nfsd.go
index <HASH>..<HASH> 100644
--- a/commons/proc/nfsd.go
+++ b/commons/proc/nfsd.go
@@ -142,8 +142,11 @@ func parseOptions(line string) map[string]string {
return options
}
+// ProcessExportedVolumeChangeFunc is called by MonitorExportedVolume when exported volume info state changes are detected
+type ProcessExportedVolumeChangeFunc func(mountpoint string, isExported bool)
+
// MonitorExportedVolume monitors the exported volume and logs on failure
-func MonitorExportedVolume(mountpoint string, monitorInterval time.Duration, shutdown <-chan interface{}) {
+func MonitorExportedVolume(mountpoint string, monitorInterval time.Duration, shutdown <-chan interface{}, changedFunc ProcessExportedVolumeChangeFunc) {
glog.Infof("monitoring exported volume %s at polling interval: %s", mountpoint, monitorInterval)
var modtime time.Time
@@ -159,12 +162,15 @@ func MonitorExportedVolume(mountpoint string, monitorInterval time.Duration, shu
if err != nil {
if err == ErrMountPointNotExported {
glog.Warningf("volume %s is not exported - further action may be required", mountpoint)
+ changedFunc(mountpoint, false)
// TODO: take action: possibly reload nfs, restart nfs
} else {
+ changedFunc(mountpoint, false)
glog.Warningf("unable to retrieve volume export info for %s: %s", mountpoint, err)
}
} else {
+ changedFunc(mountpoint, true)
glog.Infof("DFS NFS volume %s (uuid:%+v) is exported", mountpoint, mountinfo.ClientOptions["*"]["uuid"])
}
}
diff --git a/commons/proc/nfsd_test.go b/commons/proc/nfsd_test.go
index <HASH>..<HASH> 100644
--- a/commons/proc/nfsd_test.go
+++ b/commons/proc/nfsd_test.go
@@ -147,9 +147,17 @@ func TestMonitorExportedVolume(t *testing.T) {
}
// monitor
+ expectedIsExported := true
+ processExportedVolumeChangeFunc := func(mountpoint string, actualIsExported bool) {
+ glog.Infof("==== received exported volume info changed message - isExported:%s", actualIsExported)
+ if expectedIsExported != actualIsExported {
+ t.Fatalf("expectedIsExported: %+v != actualIsExported: %+v", expectedIsExported, actualIsExported)
+ }
+ }
+
shutdown := make(chan interface{})
defer close(shutdown)
- go MonitorExportedVolume(expectedMountPoint, time.Duration(2*time.Second), shutdown)
+ go MonitorExportedVolume(expectedMountPoint, time.Duration(2*time.Second), shutdown, processExportedVolumeChangeFunc)
// wait some time
waitTime := time.Second * 6
@@ -165,6 +173,7 @@ func TestMonitorExportedVolume(t *testing.T) {
time.Sleep(waitTime)
// remove the export
+ expectedIsExported = false
noEntries := "#\n"
glog.Infof("==== clearing exports %s: %s", exportsFile, noEntries)
if err := ioutil.WriteFile(exportsFile, []byte(noEntries), 0600); err != nil {
@@ -178,7 +187,4 @@ func TestMonitorExportedVolume(t *testing.T) {
// wait some time
time.Sleep(waitTime)
-
- // TODO: ensure that the monitor saw change
-
} | pass ProcessExportedVolumeChangeFunc to be notified of state changes | control-center_serviced | train |
aa96f3254241c03f244bdc3ce064b11078400918 | diff --git a/setup.py b/setup.py
index <HASH>..<HASH> 100644
--- a/setup.py
+++ b/setup.py
@@ -31,7 +31,11 @@ setup(
author_email='[email protected]',
license='MIT',
install_requires=[
- 'beautifulsoup4>=4.4.1', 'lxml', 'Pillow', 'requests>=2.9.1',
+ 'beautifulsoup4>=4.4.1',
+ 'lxml',
+ 'Pillow',
+ 'requests>=2.9.1',
'six>=1.10.0'
],
- zip_safe=False)
+ zip_safe=False
+) # yapf: disable | disable yapf for setup.py | hellock_icrawler | train |
c09219893590dee1590d5e42b1e6d2a9ad3cb812 | diff --git a/integration_tests/blockstack_integration_tests/scenarios/name_preorder_register_update_atlas_churn.py b/integration_tests/blockstack_integration_tests/scenarios/name_preorder_register_update_atlas_churn.py
index <HASH>..<HASH> 100644
--- a/integration_tests/blockstack_integration_tests/scenarios/name_preorder_register_update_atlas_churn.py
+++ b/integration_tests/blockstack_integration_tests/scenarios/name_preorder_register_update_atlas_churn.py
@@ -138,7 +138,8 @@ def scenario( wallets, **kw ):
dest_host, dest_port = blockstack_client.config.url_to_host_port( dest_hostport )
now = int(time.time())
- offset = (now - time_start) % len(all_peers)
+ # offset = (now - time_start) % len(all_peers)
+ offset = now % len(all_peers)
sample = all_peers + all_peers
active_range = sample[offset: offset + 8]
@@ -157,8 +158,8 @@ def scenario( wallets, **kw ):
network_des = atlas_network.atlas_network_build( atlas_nodes, atlas_topology, {}, os.path.join( testlib.working_dir(**kw), "atlas_network" ) )
atlas_network.atlas_network_start( network_des, drop_probability=churn_drop )
- print "Waiting 60 seconds for the altas peers to catch up"
- time.sleep(60.0)
+ print "Waiting 120 seconds for the altas peers to catch up"
+ time.sleep(120.0)
# wait at most 30 seconds for atlas network to converge
synchronized = False | give atlas peers <I> seconds to catch up, now that we have more updates to process | blockstack_blockstack-core | train |
86e65feaf348370a655e661e4e8e36062f08e5f3 | diff --git a/src/core/flow.js b/src/core/flow.js
index <HASH>..<HASH> 100644
--- a/src/core/flow.js
+++ b/src/core/flow.js
@@ -553,14 +553,20 @@ export function Flow({ moves, phases, endIf, turn, events, plugins }) {
let { ctx } = state;
let { activePlayers, _activePlayersMoveLimit } = ctx;
+ const playerInStage = activePlayers !== null && playerID in activePlayers;
+
+ if (!arg && playerInStage) {
+ const conf = GetPhase(ctx);
+ const stage = conf.turn.stages[activePlayers[playerID]];
+ if (stage && stage.next) arg = stage.next;
+ }
+
if (next && arg) {
next.push({ fn: UpdateStage, arg, playerID });
}
// If player isnโt in a stage, there is nothing else to do.
- if (activePlayers === null || !(playerID in activePlayers)) {
- return state;
- }
+ if (!playerInStage) return state;
// Remove player from activePlayers.
activePlayers = Object.keys(activePlayers)
diff --git a/src/core/flow.test.js b/src/core/flow.test.js
index <HASH>..<HASH> 100644
--- a/src/core/flow.test.js
+++ b/src/core/flow.test.js
@@ -569,6 +569,39 @@ describe('stage events', () => {
state = flow.processEvent(state, gameEvent('endStage'));
expect(state.ctx._activePlayersNumMoves).toMatchObject({ '0': 1 });
});
+
+ test('sets to next', () => {
+ let flow = Flow({
+ turn: {
+ activePlayers: { player: 'A1', others: 'B1' },
+ stages: {
+ A1: { next: 'A2' },
+ B1: { next: 'B2' },
+ },
+ },
+ });
+ let state = { G: {}, ctx: flow.ctx(2) };
+ state = flow.init(state);
+
+ expect(state.ctx.activePlayers).toMatchObject({
+ '0': 'A1',
+ '1': 'B1',
+ });
+
+ state = flow.processEvent(state, gameEvent('endStage', null, '0'));
+
+ expect(state.ctx.activePlayers).toMatchObject({
+ '0': 'A2',
+ '1': 'B1',
+ });
+
+ state = flow.processEvent(state, gameEvent('endStage', null, '1'));
+
+ expect(state.ctx.activePlayers).toMatchObject({
+ '0': 'A2',
+ '1': 'B2',
+ });
+ });
});
}); | fix: Move player to โnextโ stage on `endStage` (#<I>)
* test: Add test for `endStage` when stage has `next` field
* feat: Move player to `next` stage on `endStage` | nicolodavis_boardgame.io | train |
fc74edf25d6a4910002e2f2f5d7a509ece5891fc | diff --git a/linenoise.go b/linenoise.go
index <HASH>..<HASH> 100644
--- a/linenoise.go
+++ b/linenoise.go
@@ -88,11 +88,12 @@ func SetMultiline(ml bool) { // void linenoiseSetMultiLine(int ml);
// CompletionHandler provides possible completions for given input
type CompletionHandler func(input string) []string
-func defaultCompletionHandler(input string) []string {
+// DefaultCompletionHandler simply returns an empty slice.
+var DefaultCompletionHandler = func(input string) []string {
return nil
}
-var complHandler = defaultCompletionHandler
+var complHandler = DefaultCompletionHandler
// SetCompletionHandler sets the CompletionHandler to be used for completion
func SetCompletionHandler(c CompletionHandler) { | Renamed defaultCompletionHandler to DefaultCompletionHandler. Exported, so it can be used externally. | GeertJohan_go.linenoise | train |
2b993d83b6dc502f47022ee3390d11d8c74e3f62 | diff --git a/gson/pom.xml b/gson/pom.xml
index <HASH>..<HASH> 100644
--- a/gson/pom.xml
+++ b/gson/pom.xml
@@ -4,7 +4,7 @@
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<packaging>jar</packaging>
- <version>1.5</version>
+ <version>1.6</version>
<inceptionYear>2008</inceptionYear>
<name>Gson</name>
<url>http://code.google.com/p/google-gson/</url>
diff --git a/gson/src/main/java/com/google/gson/GsonBuilder.java b/gson/src/main/java/com/google/gson/GsonBuilder.java
index <HASH>..<HASH> 100644
--- a/gson/src/main/java/com/google/gson/GsonBuilder.java
+++ b/gson/src/main/java/com/google/gson/GsonBuilder.java
@@ -429,9 +429,9 @@ public final class GsonBuilder {
* @param typeAdapter This object must implement at least one of the {@link InstanceCreator},
* {@link JsonSerializer}, and a {@link JsonDeserializer} interfaces.
* @return a reference to this {@code GsonBuilder} object to fulfill the "Builder" pattern
- * @since 1.5
+ * @since 1.6
*/
- GsonBuilder registerTypeHierarchyAdapter(Class<?> baseType, Object typeAdapter) {
+ public GsonBuilder registerTypeHierarchyAdapter(Class<?> baseType, Object typeAdapter) {
Preconditions.checkArgument(typeAdapter instanceof JsonSerializer<?>
|| typeAdapter instanceof JsonDeserializer<?> || typeAdapter instanceof InstanceCreator<?>);
if (typeAdapter instanceof InstanceCreator<?>) {
diff --git a/gson/src/main/java/com/google/gson/stream/JsonReader.java b/gson/src/main/java/com/google/gson/stream/JsonReader.java
index <HASH>..<HASH> 100644
--- a/gson/src/main/java/com/google/gson/stream/JsonReader.java
+++ b/gson/src/main/java/com/google/gson/stream/JsonReader.java
@@ -179,8 +179,9 @@ import java.util.List;
*
* <p>Each {@code JsonReader} may be used to read a single JSON stream. Instances
* of this class are not thread safe.
- *
+ *
* @author Jesse Wilson
+ * @since 1.6
*/
public final class JsonReader implements Closeable {
diff --git a/gson/src/main/java/com/google/gson/stream/JsonScope.java b/gson/src/main/java/com/google/gson/stream/JsonScope.java
index <HASH>..<HASH> 100644
--- a/gson/src/main/java/com/google/gson/stream/JsonScope.java
+++ b/gson/src/main/java/com/google/gson/stream/JsonScope.java
@@ -20,6 +20,7 @@ package com.google.gson.stream;
* Lexical scoping elements within a JSON reader or writer.
*
* @author Jesse Wilson
+ * @since 1.6
*/
enum JsonScope {
diff --git a/gson/src/main/java/com/google/gson/stream/JsonToken.java b/gson/src/main/java/com/google/gson/stream/JsonToken.java
index <HASH>..<HASH> 100644
--- a/gson/src/main/java/com/google/gson/stream/JsonToken.java
+++ b/gson/src/main/java/com/google/gson/stream/JsonToken.java
@@ -20,6 +20,7 @@ package com.google.gson.stream;
* A structure, name or value type in a JSON-encoded string.
*
* @author Jesse Wilson
+ * @since 1.6
*/
public enum JsonToken {
diff --git a/gson/src/main/java/com/google/gson/stream/JsonWriter.java b/gson/src/main/java/com/google/gson/stream/JsonWriter.java
index <HASH>..<HASH> 100644
--- a/gson/src/main/java/com/google/gson/stream/JsonWriter.java
+++ b/gson/src/main/java/com/google/gson/stream/JsonWriter.java
@@ -116,8 +116,9 @@ import java.util.List;
* <p>Each {@code JsonWriter} may be used to write a single JSON stream.
* Instances of this class are not thread safe. Calls that would result in a
* malformed JSON string will fail with an {@link IllegalStateException}.
- *
+ *
* @author Jesse Wilson
+ * @since 1.6
*/
public final class JsonWriter implements Closeable { | Made the GsonBuilder registerTypeHierarchyAdapter a public method.
Updated the Gson version number to <I> and added @since tag for the new classes | google_gson | train |
7873ec6832bf85960ec403bcf3e71913499467e7 | diff --git a/test/acts_as_approvable_model_test.rb b/test/acts_as_approvable_model_test.rb
index <HASH>..<HASH> 100644
--- a/test/acts_as_approvable_model_test.rb
+++ b/test/acts_as_approvable_model_test.rb
@@ -366,4 +366,17 @@ class ActsAsApprovableModelTest < Test::Unit::TestCase
end
end
end
+
+ context '.options_for_state' do
+ should 'return an array' do
+ assert_kind_of Array, Approval.options_for_state
+ end
+
+ should 'contain our states' do
+ assert Approval.options_for_state.include?(['All', 'all'])
+ assert Approval.options_for_state.include?(['Pending', 'pending'])
+ assert Approval.options_for_state.include?(['Approved', 'approved'])
+ assert Approval.options_for_state.include?(['Rejected', 'rejected'])
+ end
+ end
end | Test .options_for_state | Tapjoy_acts_as_approvable | train |
b7e554fcd7778457e9c38e2cce517a60e8fea197 | diff --git a/lib/Cake/View/Helper/FormHelper.php b/lib/Cake/View/Helper/FormHelper.php
index <HASH>..<HASH> 100644
--- a/lib/Cake/View/Helper/FormHelper.php
+++ b/lib/Cake/View/Helper/FormHelper.php
@@ -229,12 +229,11 @@ class FormHelper extends AppHelper {
if ($model !== false) {
$object = $this->_introspectModel($model);
- $this->setEntity($model . '.', true);
}
+ $this->setEntity($model, true);
- $modelEntity = $this->model();
- if ($model !== false && isset($this->fieldset[$modelEntity]['key'])) {
- $data = $this->fieldset[$modelEntity];
+ if ($model !== false && isset($this->fieldset[$model]['key'])) {
+ $data = $this->fieldset[$model];
$recordExists = (
isset($this->request->data[$model]) &&
!empty($this->request->data[$model][$data['key']]) &&
@@ -306,7 +305,8 @@ class FormHelper extends AppHelper {
case 'put':
case 'delete':
$append .= $this->hidden('_method', array(
- 'name' => '_method', 'value' => strtoupper($options['type']), 'id' => null
+ 'name' => '_method', 'value' => strtoupper($options['type']), 'id' => null,
+ 'secure' => self::SECURE_SKIP
));
default:
$htmlAttributes['method'] = 'post';
@@ -337,8 +337,9 @@ class FormHelper extends AppHelper {
$this->fields = array();
if (!empty($this->request->params['_Token'])) {
$append .= $this->hidden('_Token.key', array(
- 'value' => $this->request->params['_Token']['key'], 'id' => 'Token' . mt_rand())
- );
+ 'value' => $this->request->params['_Token']['key'], 'id' => 'Token' . mt_rand(),
+ 'secure' => self::SECURE_SKIP
+ ));
if (!empty($this->request['_Token']['unlockedFields'])) {
foreach ((array)$this->request['_Token']['unlockedFields'] as $unlocked) {
@@ -351,7 +352,6 @@ class FormHelper extends AppHelper {
$append = $this->Html->useTag('block', ' style="display:none;"', $append);
}
- $this->setEntity($model . '.', true);
return $this->Html->useTag('form', $action, $htmlAttributes) . $append;
}
@@ -1297,9 +1297,8 @@ class FormHelper extends AppHelper {
$options = $this->_initInputField($fieldName, array_merge(
$options, array('secure' => self::SECURE_SKIP)
));
- $model = $this->model();
- if ($fieldName !== '_method' && $model !== '_Token' && $secure) {
+ if ($secure && $secure !== self::SECURE_SKIP) {
$this->__secure(true, null, '' . $options['value']);
}
@@ -2349,18 +2348,20 @@ class FormHelper extends AppHelper {
$secure = (isset($this->request['_Token']) && !empty($this->request['_Token']));
}
+ $result = parent::_initInputField($field, $options);
+ if ($secure === self::SECURE_SKIP) {
+ return $result;
+ }
+
$fieldName = null;
- if ($secure && !empty($options['name'])) {
+ if (!empty($options['name'])) {
preg_match_all('/\[(.*?)\]/', $options['name'], $matches);
if (isset($matches[1])) {
$fieldName = $matches[1];
}
}
- $result = parent::_initInputField($field, $options);
- if ($secure !== self::SECURE_SKIP) {
- $this->__secure($secure, $fieldName);
- }
+ $this->__secure($secure, $fieldName);
return $result;
}
} | Starting to update FormHelper's internals to work with changes in
Helper. | cakephp_cakephp | train |
226ccb1cdde89fc24f330f166971578d39670236 | diff --git a/packages/rsvp/lib/main.js b/packages/rsvp/lib/main.js
index <HASH>..<HASH> 100644
--- a/packages/rsvp/lib/main.js
+++ b/packages/rsvp/lib/main.js
@@ -62,6 +62,7 @@ define('rsvp/-internal', [
}, promise);
}
function handleOwnThenable(promise, thenable) {
+ promise._onerror = null;
if (thenable._state === FULFILLED) {
fulfill(promise, thenable._result);
} else if (promise._state === REJECTED) {
@@ -134,6 +135,7 @@ define('rsvp/-internal', [
function subscribe(parent, child, onFulfillment, onRejection) {
var subscribers = parent._subscribers;
var length = subscribers.length;
+ parent._onerror = null;
subscribers[length] = child;
subscribers[length + FULFILLED] = onFulfillment;
subscribers[length + REJECTED] = onRejection;
@@ -539,6 +541,7 @@ define('rsvp/enumerator', [
var c = this._instanceConstructor;
if (isMaybeThenable(entry)) {
if (entry.constructor === c && entry._state !== PENDING) {
+ entry._onerror = null;
this._settledAt(entry._state, i, entry._result);
} else {
this._willSettleAt(c.resolve(entry), i); | [Bugfix] ensure RSVP.on(โerror is correctly unsubscribed | emberjs_ember.js | train |
7b5a65bdc37cca14b352d6e508417f095da4231d | diff --git a/src/Codeception/Snapshot.php b/src/Codeception/Snapshot.php
index <HASH>..<HASH> 100644
--- a/src/Codeception/Snapshot.php
+++ b/src/Codeception/Snapshot.php
@@ -19,6 +19,10 @@ abstract class Snapshot
protected $showDiff = false;
+ protected $saveAsJson = true;
+
+ protected $extension = 'json';
+
/**
* Should return data from current test run
*
@@ -45,7 +49,11 @@ abstract class Snapshot
if (!file_exists($this->getFileName())) {
return;
}
- $this->dataSet = json_decode(file_get_contents($this->getFileName()));
+ $fileContents = file_get_contents($this->getFileName());
+ if ($this->saveAsJson) {
+ $fileContents = json_decode($fileContents);
+ }
+ $this->dataSet = $fileContents;
if (!$this->dataSet) {
throw new ContentNotFound("Loaded snapshot is empty");
}
@@ -56,7 +64,11 @@ abstract class Snapshot
*/
protected function save()
{
- file_put_contents($this->getFileName(), json_encode($this->dataSet));
+ $fileContents = $this->dataSet;
+ if ($this->saveAsJson) {
+ $fileContents = json_encode($fileContents);
+ }
+ file_put_contents($this->getFileName(), $fileContents);
}
/**
@@ -67,7 +79,7 @@ abstract class Snapshot
protected function getFileName()
{
if (!$this->fileName) {
- $this->fileName = preg_replace('/\W/', '.', get_class($this)) . '.json';
+ $this->fileName = preg_replace('/\W/', '.', get_class($this)) . '.' . $this->extension;
}
return codecept_data_dir() . $this->fileName;
}
@@ -139,6 +151,16 @@ abstract class Snapshot
$this->showDiff = $showDiff;
}
+ /**
+ * json_encode/json_decode the snapshot data on storing/reading.
+ *
+ * @param bool $saveAsJson
+ */
+ public function shouldSaveAsJson($saveAsJson = true)
+ {
+ $this->saveAsJson = $saveAsJson;
+ }
+
private function printDebug($message)
{
Debug::debug(get_class($this) . ': ' . $message); | feat: implements snapshot ability to generate non-json content | Codeception_Codeception | train |
794574a557c89099f5b1172b91d63ca46291a752 | diff --git a/tests/test_menu_launcher.py b/tests/test_menu_launcher.py
index <HASH>..<HASH> 100644
--- a/tests/test_menu_launcher.py
+++ b/tests/test_menu_launcher.py
@@ -176,10 +176,6 @@ def test_running_menu():
# return to mode
child.send("[A")
child.sendline('')
- child.interact()
- child.send("[A")
- child.sendline('')
- child.send("^]")
# child.sendline('2')
child.expect('Return to Vent menu')
# go to stop | Test environment doesn't work with child.interact() - 'Inappropriate ioctl for device.' | CyberReboot_vent | train |
Subsets and Splits