hash
stringlengths 40
40
| diff
stringlengths 131
114k
| message
stringlengths 7
980
| project
stringlengths 5
67
| split
stringclasses 1
value |
|---|---|---|---|---|
91d84c7db6e7a32d16282ec8fff036b16b73018a
|
diff --git a/ruskit/cluster.py b/ruskit/cluster.py
index <HASH>..<HASH> 100644
--- a/ruskit/cluster.py
+++ b/ruskit/cluster.py
@@ -280,8 +280,11 @@ class Cluster(object):
return len(slots) == CLUSTER_HASH_SLOTS and self.consistent()
def wait(self):
+ start = time.time()
while not self.consistent():
time.sleep(1)
+ logger.info('cluster took {} seconds to become consistent'.format(
+ time.time() - start))
if not self.healthy():
raise ClusterNotHealthy("Error: missing slots")
|
Log time spent in waiting cluster to become consistent
|
eleme_ruskit
|
train
|
8b491266b1488ad2ae1fe22fbf5eda3fb9946c21
|
diff --git a/lib/genericObject.js b/lib/genericObject.js
index <HASH>..<HASH> 100644
--- a/lib/genericObject.js
+++ b/lib/genericObject.js
@@ -2,6 +2,11 @@ function GenericObject(connection, handle) {
this.connection = connection;
this.handle = handle;
}
+GenericObject.prototype.exportData = function(FileType, Path, FileName, ExportState) {
+ return this.connection.ask(this.handle, 'ExportData', arguments).then(function(msg) {
+ return msg.qUrl;
+ });
+};
GenericObject.prototype.getLayout = function() {
return this.connection.ask(this.handle, 'GetLayout', arguments).then(function(msg) {
return msg.qLayout;
@@ -12,6 +17,11 @@ GenericObject.prototype.getListObjectData = function(Path, Pages) {
return msg.qDataPages;
});
};
+GenericObject.prototype.getHyperCubeAdaptiveGrid = function(Path, Pages, DataRanges, MaxNbrcells, QueryLevel) {
+ return this.connection.ask(this.handle, 'GetHyperCubeAdaptiveGrid', arguments).then(function(msg) {
+ return msg.qDataPages;
+ });
+};
GenericObject.prototype.getHyperCubeData = function(Path, Pages) {
return this.connection.ask(this.handle, 'GetHyperCubeData', arguments).then(function(msg) {
return msg.qDataPages;
@@ -193,4 +203,7 @@ GenericObject.prototype.getSnapshotObject = function() {
GenericObject.prototype.publish = function() {
return this.connection.ask(this.handle, 'Publish', arguments);
};
+GenericObject.prototype.unPublish = function() {
+ return this.connection.ask(this.handle, 'UnPublish', arguments);
+};
module.exports = GenericObject;
\ No newline at end of file
|
GenericObject has been updated for <I>
New methods has been added.
|
mindspank_qsocks
|
train
|
7788af127ce0dd3f34efcf671b9b43fd0c95a8fb
|
diff --git a/src/index.js b/src/index.js
index <HASH>..<HASH> 100644
--- a/src/index.js
+++ b/src/index.js
@@ -48,7 +48,7 @@ export class DefaultLoader extends Loader {
if(System.polyfilled){
define('view', [], {
- load: function (name, req, onload, config) {
+ 'load': function (name, req, onload, config) {
var entry = that.getOrCreateTemplateRegistryEntry(name),
address;
@@ -67,7 +67,7 @@ export class DefaultLoader extends Loader {
});
}else{
System.set('view', System.newModule({
- fetch: function(load, fetch) {
+ 'fetch': function(load, fetch) {
var id = load.name.substring(0, load.name.indexOf('!'));
var entry = load.metadata.templateRegistryEntry = that.getOrCreateTemplateRegistryEntry(id);
@@ -80,7 +80,7 @@ export class DefaultLoader extends Loader {
return '';
});
},
- instantiate:function(load) {
+ 'instantiate':function(load) {
return load.metadata.templateRegistryEntry;
}
}));
|
fix(loader): plugin api fetch causes problems with safari
|
aurelia_loader-default
|
train
|
c90412836d20cfa3636b75ea0fc8f3992aaa785e
|
diff --git a/OpenPNM/Physics/models/multiphase.py b/OpenPNM/Physics/models/multiphase.py
index <HASH>..<HASH> 100644
--- a/OpenPNM/Physics/models/multiphase.py
+++ b/OpenPNM/Physics/models/multiphase.py
@@ -66,7 +66,7 @@ def conduit_conductance(physics, phase, network, throat_conductance,
open_conduits = -closed_conduits
throat_value = phase[throat_conductance]
value = throat_value*open_conduits + throat_value*closed_conduits*factor
- value = value[phase.throats(physics.name)]
+ value = value[phase.throats(physics.name)]
return value
|
Removing white space for pep8
No comment!
|
PMEAL_OpenPNM
|
train
|
d6d17c08c4ec498eb7efd3c1b2d8039cc3eb3fd9
|
diff --git a/requery-processor/src/main/java/io/requery/processor/AndroidObservableExtension.java b/requery-processor/src/main/java/io/requery/processor/AndroidObservableExtension.java
index <HASH>..<HASH> 100644
--- a/requery-processor/src/main/java/io/requery/processor/AndroidObservableExtension.java
+++ b/requery-processor/src/main/java/io/requery/processor/AndroidObservableExtension.java
@@ -27,6 +27,7 @@ import javax.lang.model.element.PackageElement;
import javax.lang.model.element.TypeElement;
import javax.lang.model.util.Elements;
import java.util.Arrays;
+import java.util.Map;
import java.util.Optional;
/**
@@ -44,7 +45,7 @@ class AndroidObservableExtension implements TypeGenerationExtension, PropertyGen
private final EntityDescriptor entity;
private final ProcessingEnvironment processingEnvironment;
private final boolean observable;
- private final String modulePackage;
+ private String modulePackage;
AndroidObservableExtension(EntityDescriptor entity,
ProcessingEnvironment processingEnvironment) {
@@ -52,6 +53,16 @@ class AndroidObservableExtension implements TypeGenerationExtension, PropertyGen
this.processingEnvironment = processingEnvironment;
this.observable = isObservable();
this.modulePackage = processingEnvironment.getOptions().get(MODULE_PACKAGE_OPTION);
+
+ // this shouldn't be happening
+ if (modulePackage == null) {
+ for(Map.Entry<String, String> entry : processingEnvironment.getOptions().entrySet()) {
+ if (entry.getKey().endsWith("databinding.modulePackage")) {
+ modulePackage = entry.getValue();
+ break;
+ }
+ }
+ }
}
private boolean isObservable() {
|
Android work around for module package look up issue
|
requery_requery
|
train
|
be5f5270ec642be3e17e7b739dc4c3e06464fff4
|
diff --git a/lib/sinatra.rb b/lib/sinatra.rb
index <HASH>..<HASH> 100644
--- a/lib/sinatra.rb
+++ b/lib/sinatra.rb
@@ -149,7 +149,7 @@ module Sinatra
@param_keys = []
@options = options
regex = @path.to_s.gsub(PARAM) do
- @param_keys << $1.intern
+ @param_keys << $1
"(#{URI_CHAR}+)"
end
@@ -586,9 +586,9 @@ module Sinatra
end
def params
- @params ||= @route_params.merge(@request.params).symbolize_keys
+ @params = @route_params.merge(@request.params)
end
-
+
def stop(*args)
throw :halt, args
end
diff --git a/test/app_test.rb b/test/app_test.rb
index <HASH>..<HASH> 100644
--- a/test/app_test.rb
+++ b/test/app_test.rb
@@ -18,7 +18,7 @@ context "Sinatra" do
specify "handles events" do
get '/:name' do
- 'Hello ' + params[:name]
+ 'Hello ' + params["name"]
end
get_it '/Blake'
diff --git a/test/application_test.rb b/test/application_test.rb
index <HASH>..<HASH> 100644
--- a/test/application_test.rb
+++ b/test/application_test.rb
@@ -42,7 +42,7 @@ context "Looking up a request" do
result.should.not.be.nil
result.block.should.be block
- result.params.should.equal :foo => 'bar'
+ result.params.should.equal "foo" => 'bar'
end
end
@@ -120,7 +120,7 @@ context "Events in an app" do
specify "get access to request, response, and params" do
get '/:foo' do
- params[:foo] + params[:bar]
+ params["foo"] + params["bar"]
end
get_it '/foo?bar=baz'
diff --git a/test/events_test.rb b/test/events_test.rb
index <HASH>..<HASH> 100644
--- a/test/events_test.rb
+++ b/test/events_test.rb
@@ -28,12 +28,12 @@ context "Simple Events" do
specify "takes params in path" do
result = invoke_simple('/:foo/:bar', '/a/b')
result.should.not.be.nil
- result.params.should.equal :foo => 'a', :bar => 'b'
+ result.params.should.equal "foo" => 'a', "bar" => 'b'
# unscapes
result = invoke_simple('/:foo/:bar', '/a/blake%20mizerany')
result.should.not.be.nil
- result.params.should.equal :foo => 'a', :bar => 'blake mizerany'
+ result.params.should.equal "foo" => 'a', "bar" => 'blake mizerany'
end
specify "ignores to many /'s" do
|
bringing back the string.
Symbols are not garbage collected and I don't want to use the large (but cool) HashWithIndifferentAccess. I could use OpenStruct ala camping but that seems unnecessary.
Long live the string.
|
sinatra_sinatra
|
train
|
85b421b37dae71cd38972f8e82c43febcdd08668
|
diff --git a/src/yanwen.js b/src/yanwen.js
index <HASH>..<HASH> 100644
--- a/src/yanwen.js
+++ b/src/yanwen.js
@@ -60,8 +60,6 @@ yanwen.getInfo = function (id, callback, _try = 0) {
}
function createYanwenEntity(id, html) {
- let skipLines = 2
-
let $ = parser.load(html)
let trs = $('table tbody tr')
@@ -80,9 +78,9 @@ function createYanwenEntity(id, html) {
if(elem.children !== undefined
&& elem.children[1].children !== undefined
&& elem.children[1].children[0].children !== undefined
- && elem.children[1].children[0].children[0].data != undefined)
- if(elem.children[1].children[0].children[0].data.indexOf('Country') != -1){
- if(elem.children[1].children[0].children[0].data.indexOf('Origin') != -1){
+ && elem.children[1].children[0].children[0].data != undefined) {
+ if (elem.children[1].children[0].children[0].data.indexOf('Country') != -1) {
+ if (elem.children[1].children[0].children[0].data.indexOf('Origin') != -1) {
origin = elem.children[3].children[0].children[0].data.trim()
} else {
destiny = elem.children[3].children[0].children[0].data.trim()
@@ -90,6 +88,7 @@ function createYanwenEntity(id, html) {
return false;
}
return true;
+ }
return true;
})
diff --git a/test/yanwenTest.js b/test/yanwenTest.js
index <HASH>..<HASH> 100644
--- a/test/yanwenTest.js
+++ b/test/yanwenTest.js
@@ -5,7 +5,7 @@ const yanwen = require('../src/yanwen')
describe('yanwen', function () {
this.timeout(0)
- describe('#YanwenPost', function () {
+ describe('#Yanwen', function () {
it('should extract the messages from the website with success', function (done) {
const id = '8001077530850'
yanwen.getInfo(id, (err, info) => {
|
minor yawned fixes
|
hdnpt_geartrack
|
train
|
b52356b2b32ec1948eb2197a041e917b782d1cb5
|
diff --git a/d3-funnel.js b/d3-funnel.js
index <HASH>..<HASH> 100644
--- a/d3-funnel.js
+++ b/d3-funnel.js
@@ -1,6 +1,6 @@
(function(global) {
- /* global d3 */
+ /* global d3, $ */
/* jshint bitwise: false */
"use strict";
@@ -105,12 +105,12 @@
for (var i = 0; i < sectionPaths.length; i++) {
// Set the background color
- var fill = this.fillType !== "gradient"
- ? this.data[i][2]
- : "url(#gradient-" + i + ")";
+ var fill = this.fillType !== "gradient" ?
+ this.data[i][2] :
+ "url(#gradient-" + i + ")";
// Prepare data to assign to the section
- var data = {
+ data = {
index: i,
label: this.data[i][0],
value: this.data[i][1],
@@ -146,9 +146,9 @@
// Add the section label
var textStr = this.data[i][0] + ": " + this.data[i][1];
var textX = this.width / 2; // Center the text
- var textY = !this.isCurved // Average height of bases
- ? (paths[1][1] + paths[2][1]) / 2
- : (paths[2][1] + paths[3][1]) / 2;
+ var textY = !this.isCurved ? // Average height of bases
+ (paths[1][1] + paths[2][1]) / 2 :
+ (paths[2][1] + paths[3][1]) / 2;
group.append("text")
.text(textStr)
@@ -241,14 +241,14 @@
// Change in x direction
// Will be sharper if there is a pinch
- this.dx = this.bottomPinch > 0
- ? this.bottomLeftX / (data.length - this.bottomPinch)
- : this.bottomLeftX / data.length;
+ this.dx = this.bottomPinch > 0 ?
+ this.bottomLeftX / (data.length - this.bottomPinch) :
+ this.bottomLeftX / data.length;
// Change in y direction
// Curved chart needs reserved pixels to account for curvature
- this.dy = this.isCurved
- ? (this.height - this.curveHeight) / data.length
- : this.height / data.length;
+ this.dy = this.isCurved ?
+ (this.height - this.curveHeight) / data.length :
+ this.height / data.length;
}; // End _initialize
@@ -296,19 +296,20 @@
var slope = 2 * this.height / (this.width - this.bottomWidth);
var totalCount = 0;
+ var count = 0;
// Harvest total count
// Remove any commas that could interfere with the parser
for (var i = 0; i < this.data.length; i++) {
- var count = this.data[i][1].replace(/\,/g, "");
+ count = this.data[i][1].replace(/\,/g, "");
totalCount += parseFloat(count);
} // End for
// Create the path definition for each funnel section
// Remember to loop back to the beginning point for a closed path
- for (var i = 0; i < this.data.length; i++) {
+ for (i = 0; i < this.data.length; i++) {
- var count = this.data[i][1].replace(/\,/g, "");
+ count = this.data[i][1].replace(/\,/g, "");
count = parseFloat(count);
// Calculate dynamic shapes based on area
@@ -317,7 +318,7 @@
var ratio = count / totalCount;
var area = ratio * totalArea;
- var bottomBase = Math.sqrt((slope * topBase * topBase - (4 * area))/slope);
+ bottomBase = Math.sqrt((slope * topBase * topBase - (4 * area))/slope);
dx = (topBase / 2) - (bottomBase / 2);
dy = (area * 2) / (topBase + bottomBase);
|
Fixed several JSHint validation issues.
|
jakezatecky_d3-funnel
|
train
|
73eb68c516a291e2f8a816abab20b67999eb851b
|
diff --git a/src/java/org/apache/cassandra/locator/SimpleSeedProvider.java b/src/java/org/apache/cassandra/locator/SimpleSeedProvider.java
index <HASH>..<HASH> 100644
--- a/src/java/org/apache/cassandra/locator/SimpleSeedProvider.java
+++ b/src/java/org/apache/cassandra/locator/SimpleSeedProvider.java
@@ -17,6 +17,7 @@
*/
package org.apache.cassandra.locator;
+import java.io.IOException;
import java.io.InputStream;
import java.net.InetAddress;
import java.net.URL;
@@ -29,6 +30,7 @@ import java.util.Map;
import org.apache.cassandra.config.Config;
import org.apache.cassandra.config.DatabaseDescriptor;
import org.apache.cassandra.config.SeedProviderDef;
+import org.apache.cassandra.exceptions.ConfigurationException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.yaml.snakeyaml.Loader;
@@ -39,20 +41,36 @@ public class SimpleSeedProvider implements SeedProvider
{
private static final Logger logger = LoggerFactory.getLogger(SimpleSeedProvider.class);
- public SimpleSeedProvider(Map<String, String> args) {}
+ List<InetAddress> seeds;
+ public SimpleSeedProvider(Map<String, String> args) {
+ try
+ {
+ seeds = loadSeeds();
+ }
+ catch (Exception e)
+ {
+ throw new AssertionError(e);
+ }
+ }
public List<InetAddress> getSeeds()
{
- InputStream input;
try
{
- URL url = DatabaseDescriptor.getStorageConfigURL();
- input = url.openStream();
+ seeds = loadSeeds();
}
catch (Exception e)
{
- throw new AssertionError(e);
+ logger.warn("Could not refresh seeds from configuration file: {}", e);
}
+ return Collections.unmodifiableList(seeds);
+ }
+
+ private List<InetAddress> loadSeeds() throws IOException, ConfigurationException
+ {
+ InputStream input;
+ URL url = DatabaseDescriptor.getStorageConfigURL();
+ input = url.openStream();
org.yaml.snakeyaml.constructor.Constructor constructor = new org.yaml.snakeyaml.constructor.Constructor(Config.class);
TypeDescription seedDesc = new TypeDescription(SeedProviderDef.class);
seedDesc.putMapPropertyType("parameters", String.class, String.class);
@@ -73,6 +91,6 @@ public class SimpleSeedProvider implements SeedProvider
logger.warn("Seed provider couldn't lookup host " + host);
}
}
- return Collections.unmodifiableList(seeds);
+ return seeds;
}
}
|
Prevent SSP from erroring out when the yaml is yanked from it.
Patch by brandonwilliams, reviewed by Richard Low for CASSANDRA-<I>
|
Stratio_stratio-cassandra
|
train
|
b4b2eeb7c5782a638d80acce369e920d671134f3
|
diff --git a/setup.py b/setup.py
index <HASH>..<HASH> 100644
--- a/setup.py
+++ b/setup.py
@@ -14,7 +14,7 @@ setup(
author='Tim Heap',
author_email='heap.tim@gmail.com',
url='https://bitbucket.org/ionata/django-bleach',
- packages=['django_bleach'],
+ packages=find_packages(),
install_requires=['bleach'],
package_data={},
classifiers=[
|
Use `find_packages()` instead of naming packages
The `templatetags/` files were missed because they were not named. Using
`find_packages()` will ensure this does not happen again.
|
marksweb_django-bleach
|
train
|
75fb49b7df8f7eb9fc066b5cdb29fa038c536e50
|
diff --git a/arquillian-container-liferay/src/main/java/org/arquillian/container/liferay/remote/wait/LiferayWaitForServiceObserver.java b/arquillian-container-liferay/src/main/java/org/arquillian/container/liferay/remote/wait/LiferayWaitForServiceObserver.java
index <HASH>..<HASH> 100644
--- a/arquillian-container-liferay/src/main/java/org/arquillian/container/liferay/remote/wait/LiferayWaitForServiceObserver.java
+++ b/arquillian-container-liferay/src/main/java/org/arquillian/container/liferay/remote/wait/LiferayWaitForServiceObserver.java
@@ -23,6 +23,7 @@ import org.osgi.framework.Bundle;
import org.osgi.framework.BundleContext;
import org.osgi.framework.Filter;
import org.osgi.framework.FrameworkUtil;
+import org.osgi.framework.InvalidSyntaxException;
import org.osgi.util.tracker.ServiceTracker;
/**
@@ -31,8 +32,7 @@ import org.osgi.util.tracker.ServiceTracker;
public class LiferayWaitForServiceObserver {
public void execute(@Observes(precedence = Integer.MAX_VALUE)
- EventContext<BeforeSuite> event)
- throws Exception {
+ EventContext<BeforeSuite> event) throws InvalidSyntaxException {
Bundle bundle = FrameworkUtil.getBundle(getClass());
diff --git a/arquillian-liferay-maven-extension/src/main/java/org/arquillian/liferay/maven/internal/tasks/ExecuteDeployerTask.java b/arquillian-liferay-maven-extension/src/main/java/org/arquillian/liferay/maven/internal/tasks/ExecuteDeployerTask.java
index <HASH>..<HASH> 100644
--- a/arquillian-liferay-maven-extension/src/main/java/org/arquillian/liferay/maven/internal/tasks/ExecuteDeployerTask.java
+++ b/arquillian-liferay-maven-extension/src/main/java/org/arquillian/liferay/maven/internal/tasks/ExecuteDeployerTask.java
@@ -28,6 +28,7 @@ import java.util.Map;
import org.arquillian.liferay.maven.internal.LiferayPluginConfiguration;
import org.dom4j.Document;
+import org.dom4j.DocumentException;
import org.dom4j.io.SAXReader;
import org.jboss.shrinkwrap.api.ShrinkWrap;
@@ -112,7 +113,7 @@ public enum ExecuteDeployerTask {
public static final class SAXReaderUtil {
public static Document read(File file, boolean validate)
- throws Exception {
+ throws DocumentException {
SAXReader saxReader = new SAXReader(validate);
diff --git a/arquillian-processor-osgi-allin/src/main/java/org/arquillian/container/osgi/remote/processor/OSGiAllInProcessor.java b/arquillian-processor-osgi-allin/src/main/java/org/arquillian/container/osgi/remote/processor/OSGiAllInProcessor.java
index <HASH>..<HASH> 100644
--- a/arquillian-processor-osgi-allin/src/main/java/org/arquillian/container/osgi/remote/processor/OSGiAllInProcessor.java
+++ b/arquillian-processor-osgi-allin/src/main/java/org/arquillian/container/osgi/remote/processor/OSGiAllInProcessor.java
@@ -241,7 +241,7 @@ public class OSGiAllInProcessor implements ApplicationArchiveProcessor {
private void handleAuxiliaryArchives(
JavaArchive javaArchive, Collection<Archive<?>> auxiliaryArchives)
- throws Exception {
+ throws IOException {
for (Archive auxiliaryArchive : auxiliaryArchives) {
Map<ArchivePath, Node> remoteLoadableExtensionMap =
@@ -351,7 +351,9 @@ public class OSGiAllInProcessor implements ApplicationArchiveProcessor {
return archives;
}
- private void validateBundleArchive(Archive<?> archive) throws Exception {
+ private void validateBundleArchive(Archive<?> archive)
+ throws BundleException, IOException {
+
Manifest manifest = null;
Node node = archive.get(JarFile.MANIFEST_NAME);
|
[arquillian/arquillian-extension-liferay#<I>] Throw concrete exceptions
|
arquillian_arquillian-extension-liferay
|
train
|
7cc540c76d25c9f925d7522e7011f6bb691f3e88
|
diff --git a/lib/rgitflow/tasks/task_helpers.rb b/lib/rgitflow/tasks/task_helpers.rb
index <HASH>..<HASH> 100644
--- a/lib/rgitflow/tasks/task_helpers.rb
+++ b/lib/rgitflow/tasks/task_helpers.rb
@@ -68,6 +68,7 @@ module RGitFlow
end
@git.branch(branch).create
+ @git.branch(branch).checkout
status "Started feature branch #{branch}!"
end
|
checking out created feature branch when it's created
|
Nunnery_rgitflow
|
train
|
387924c825ee00d5bd96ff2f39a3d5edd1dc720c
|
diff --git a/source/core/Credentials.php b/source/core/Credentials.php
index <HASH>..<HASH> 100644
--- a/source/core/Credentials.php
+++ b/source/core/Credentials.php
@@ -89,8 +89,8 @@ final class Credentials {
/* only consider parameter init if all provided */
if (isset(self::$credentials_opts['path'])) {
/** do not load path twice **/
- if (!preg_match("/credentials\.json/", $credentials_opts['path'])) {
- self::$credentials_opts['path'] = self::$credentials_opts['path'] . DIRECTORY_SEPARATOR . self::$credentials_opts['file'];
+ if (!preg_match("/credentials\.json/", self::$credentials_opts['path'])) {
+ self::$credentials_opts['path'] = self::$credentials_opts['path'] . DIRECTORY_SEPARATOR . self::$credentials_opts['file'];
}
} else {
self::$credentials_opts['path'] = realpath(getcwd()) . DIRECTORY_SEPARATOR . self::$credentials_opts['file'];
|
Fixes wrong variable reference in Credentials.php
When attempting to check if the provided path contains the string "credentials.json" it was incorrectly comparing against $credentials_opts instead of self::$credentials_opts
|
Bandwidth_php-bandwidth
|
train
|
6a950609d2b34941437ddb97edb85c7d82517392
|
diff --git a/lib/watir-webdriver/window_switching.rb b/lib/watir-webdriver/window_switching.rb
index <HASH>..<HASH> 100644
--- a/lib/watir-webdriver/window_switching.rb
+++ b/lib/watir-webdriver/window_switching.rb
@@ -3,7 +3,7 @@ module Watir
def windows(*args)
all = @driver.window_handles.map { |id| Window.new(@driver, id) }
-
+
if args.empty?
all
else
@@ -25,11 +25,11 @@ module Watir
def filter_windows(args, all, method)
sel = extract_selector(args)
-
+
if sel.empty?
all.find { |w| w.current? }
end
-
+
unless sel.keys.all? { |k| [:title, :url].include? k }
raise ArgumentError, "invalid window selector: #{sel.inspect}"
end
@@ -45,7 +45,6 @@ module Watir
@driver, @id = driver, id
end
-
def inspect
'#<%s:0x%x id=%s>' % [self.class, hash*2, @id.to_s]
end
@@ -73,6 +72,11 @@ module Watir
end
def use(&blk)
+ if current?
+ yield if block_given?
+ return self
+ end
+
@driver.switch_to.window(@id, &blk)
self
end
|
Don't switch if this is the current window.
|
watir_watir
|
train
|
d23e65fbeb95ef60030a35c9a3aae233d8b9648b
|
diff --git a/library/src/com/actionbarsherlock/internal/widget/ActionBarView.java b/library/src/com/actionbarsherlock/internal/widget/ActionBarView.java
index <HASH>..<HASH> 100644
--- a/library/src/com/actionbarsherlock/internal/widget/ActionBarView.java
+++ b/library/src/com/actionbarsherlock/internal/widget/ActionBarView.java
@@ -132,6 +132,8 @@ public class ActionBarView extends AbsActionBarView {
private SpinnerAdapter mSpinnerAdapter;
private OnNavigationListener mCallback;
+ //UNUSED private Runnable mTabSelector;
+
private ExpandedActionViewMenuPresenter mExpandedMenuPresenter;
View mExpandedActionView;
@@ -381,6 +383,7 @@ public class ActionBarView extends AbsActionBarView {
@Override
public void onDetachedFromWindow() {
super.onDetachedFromWindow();
+ //UNUSED removeCallbacks(mTabSelector);
if (mActionMenuPresenter != null) {
mActionMenuPresenter.hideOverflowMenu();
mActionMenuPresenter.hideSubMenus();
|
Using `//UNUSED` comments instead of removing the unused code
|
JakeWharton_ActionBarSherlock
|
train
|
3dc7ede53fc41c47a61e60e275227f336f0bfe32
|
diff --git a/spec/lib/onebox/layout_spec.rb b/spec/lib/onebox/layout_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/lib/onebox/layout_spec.rb
+++ b/spec/lib/onebox/layout_spec.rb
@@ -3,7 +3,36 @@ require "spec_helper"
describe Onebox::Layout do
let(:cache) { Moneta.new(:Memory, expires: true, serializer: :json) }
let(:record) { {} }
- let(:html) { described_class.new("amazon", record, cache).to_html }
+ let(:onebox) { described_class.new("amazon", record, cache) }
+ let(:html) { onebox.to_html }
+
+ describe ".template_path" do
+ before(:each) do
+ Onebox.options.load_paths << "directory_b"
+ Onebox.options.load_paths << "directory_c"
+ end
+
+ let(:template_path) { onebox.template_path }
+
+ it "looks in directory C for template" do
+ File.stub(:exist?) do |path|
+ path == "directory_c"
+ end
+ expect(template_path).to eq("directory_c")
+ end
+
+ it "looks in directory B if template doesn't exist in C" do
+ expect(template_path).to eq("directory_b")
+ end
+
+ it "looks in default directory if template doesn't exist in B or C" do
+ expect(template_path).to include("template")
+ end
+
+ after(:each) do
+ Onebox.options.load_paths.pop(2)
+ end
+ end
describe "#to_html" do
class OneboxEngineLayout
|
start writing spec for .template_path [#<I>]
|
discourse_onebox
|
train
|
94dbc743415c832639508b08ccfac03fc9be6a8a
|
diff --git a/core/src/main/java/com/github/gumtreediff/actions/EditScriptGenerator.java b/core/src/main/java/com/github/gumtreediff/actions/EditScriptGenerator.java
index <HASH>..<HASH> 100644
--- a/core/src/main/java/com/github/gumtreediff/actions/EditScriptGenerator.java
+++ b/core/src/main/java/com/github/gumtreediff/actions/EditScriptGenerator.java
@@ -28,5 +28,8 @@ import com.github.gumtreediff.matchers.MappingStore;
* @see EditScript
*/
public interface EditScriptGenerator {
+ /**
+ * Compute and return the edit script for the provided mappings.
+ */
EditScript computeActions(MappingStore mappings);
}
|
doc-feat: documented editscriptgenerator.
|
GumTreeDiff_gumtree
|
train
|
a0c74b5cc6e101ee1c36cc23b7d358baa13af174
|
diff --git a/app/controllers/auto_complete_search.rb b/app/controllers/auto_complete_search.rb
index <HASH>..<HASH> 100644
--- a/app/controllers/auto_complete_search.rb
+++ b/app/controllers/auto_complete_search.rb
@@ -28,7 +28,11 @@ module AutoCompleteSearch
if !params[:filter].nil? and eval(controller_name.singularize.camelize).respond_to?('by_env')
@items = eval(controller_name.singularize.camelize).readable(current_organization).by_env(params[:filter]).complete_for(params[:search], @filter)
else
- @items = eval(controller_name.singularize.camelize).readable(current_organization).complete_for(params[:search], @filter)
+ if (controller_name == "notices")
+ @items = eval(controller_name.singularize.camelize).readable(current_user).complete_for(params[:search], @filter)
+ else
+ @items = eval(controller_name.singularize.camelize).readable(current_organization).complete_for(params[:search], @filter)
+ end
end
@items = @items.map do |item|
diff --git a/app/controllers/search_controller.rb b/app/controllers/search_controller.rb
index <HASH>..<HASH> 100644
--- a/app/controllers/search_controller.rb
+++ b/app/controllers/search_controller.rb
@@ -96,7 +96,10 @@ class SearchController < ApplicationController
# checking for path validity. This is required since the routes do not know of this prefix.
path = path.split(ENV['RAILS_RELATIVE_URL_ROOT']).last
path_details = Rails.application.routes.recognize_path(path)
- eval(path_details[:controller].singularize.camelize).complete_for(query)
+
+ eval(path_details[:controller].singularize.camelize).readable(current_organization).complete_for(query,
+ {:organization_id => current_organization})
+
rescue ScopedSearch::QueryNotSupported => error
Rails.logger.error error.to_s
errors _("Unable to save as favorite. '#{params[:favorite]}' is an invalid search.")
diff --git a/app/models/notice.rb b/app/models/notice.rb
index <HASH>..<HASH> 100644
--- a/app/models/notice.rb
+++ b/app/models/notice.rb
@@ -25,6 +25,8 @@ class Notice < ActiveRecord::Base
before_validation :set_default_notice_level
before_save :add_to_all_users
+ scope :readable, lambda { |user| joins(:users).where('users.id' => user) }
+
scoped_search :on => :level, :complete_value => true
scoped_search :on => :text, :complete_value => true, :rename => :description
scoped_search :on => :created_at, :complete_value => true, :rename => :created
|
search - fix system save and notices search
This commit contains a couple of small fixes to enable saving of favorites
for systems and search queries for notices page.
|
Katello_katello
|
train
|
06f96f4b6e28e447127a314d72f1b5d22f1e93b6
|
diff --git a/internal/handshake/crypto_setup_tls.go b/internal/handshake/crypto_setup_tls.go
index <HASH>..<HASH> 100644
--- a/internal/handshake/crypto_setup_tls.go
+++ b/internal/handshake/crypto_setup_tls.go
@@ -65,6 +65,8 @@ type cryptoSetupTLS struct {
messageErrChan chan error
// handshakeComplete is closed when the handshake completes
handshakeComplete chan<- struct{}
+ // handshakeDone is closed as soon as the go routine running qtls.Handshake() returns
+ handshakeDone chan struct{}
// transport parameters are sent on the receivedTransportParams, as soon as they are received
receivedTransportParams <-chan TransportParameters
// is closed when Close() is called
@@ -192,6 +194,7 @@ func newCryptoSetupTLS(
handshakeComplete: handshakeComplete,
logger: logger,
perspective: perspective,
+ handshakeDone: make(chan struct{}),
handshakeErrChan: make(chan struct{}),
messageErrChan: make(chan error, 1),
clientHelloWrittenChan: make(chan struct{}),
@@ -238,6 +241,7 @@ func (h *cryptoSetupTLS) RunHandshake() error {
handshakeErrChan := make(chan error, 1)
handshakeComplete := make(chan struct{})
go func() {
+ defer close(h.handshakeDone)
if err := conn.Handshake(); err != nil {
handshakeErrChan <- err
return
@@ -271,6 +275,8 @@ func (h *cryptoSetupTLS) RunHandshake() error {
func (h *cryptoSetupTLS) Close() error {
close(h.closeChan)
+ // wait until qtls.Handshake() actually returned
+ <-h.handshakeDone
return nil
}
|
wait until the Handshake() go routine returned before returning Close()
|
lucas-clemente_quic-go
|
train
|
c45096e1b3297c5c596e56846e845a05b44ef900
|
diff --git a/openstack_dashboard/dashboards/project/database_backups/tables.py b/openstack_dashboard/dashboards/project/database_backups/tables.py
index <HASH>..<HASH> 100644
--- a/openstack_dashboard/dashboards/project/database_backups/tables.py
+++ b/openstack_dashboard/dashboards/project/database_backups/tables.py
@@ -131,7 +131,7 @@ class BackupsTable(tables.DataTable):
verbose_name=_("Datastore"))
datastore_version = tables.Column(get_datastore_version,
verbose_name=_("Datastore Version"))
- created = tables.Column("created", verbose_name=_("Created At"),
+ created = tables.Column("created", verbose_name=_("Created"),
filters=[filters.parse_isotime])
instance = tables.Column(db_name, link=db_link,
verbose_name=_("Database"))
diff --git a/openstack_dashboard/dashboards/project/database_backups/templates/database_backups/details.html b/openstack_dashboard/dashboards/project/database_backups/templates/database_backups/details.html
index <HASH>..<HASH> 100644
--- a/openstack_dashboard/dashboards/project/database_backups/templates/database_backups/details.html
+++ b/openstack_dashboard/dashboards/project/database_backups/templates/database_backups/details.html
@@ -33,8 +33,10 @@
<dd>{{ backup.locationRef }}</dd>
<dt>{% trans "Initial Volume Size" %}</dt>
<dd>{{ backup.size }} {% trans "GB" %}</dd>
- <dt>{% trans "Created On" %}</dt>
- <dd>{{ backup.updated_at|date:"N jS, Y P" }}</dd>
+ <dt>{% trans "Created" %}</dt>
+ <dd>{{ backup.created|parse_isotime }}</dd>
+ <dt>{% trans "Updated" %}</dt>
+ <dd>{{ backup.updated|parse_isotime }}</dd>
<dt>{% trans "Backup Duration" %}</dt>
<dd>{{ backup.duration }}</dd>
</dl>
diff --git a/openstack_dashboard/dashboards/project/database_backups/views.py b/openstack_dashboard/dashboards/project/database_backups/views.py
index <HASH>..<HASH> 100644
--- a/openstack_dashboard/dashboards/project/database_backups/views.py
+++ b/openstack_dashboard/dashboards/project/database_backups/views.py
@@ -80,9 +80,9 @@ class DetailView(horizon_views.APIView):
backup_id = kwargs.get("backup_id")
try:
backup = api.trove.backup_get(request, backup_id)
- backup.created_at = filters.parse_isotime(backup.created)
- backup.updated_at = filters.parse_isotime(backup.updated)
- backup.duration = backup.updated_at - backup.created_at
+ created_at = filters.parse_isotime(backup.created)
+ updated_at = filters.parse_isotime(backup.updated)
+ backup.duration = updated_at - created_at
except Exception:
redirect = reverse('horizon:project:database_backups:index')
msg = _('Unable to retrieve details for backup: %s') % backup_id
diff --git a/openstack_dashboard/dashboards/project/databases/tables.py b/openstack_dashboard/dashboards/project/databases/tables.py
index <HASH>..<HASH> 100644
--- a/openstack_dashboard/dashboards/project/databases/tables.py
+++ b/openstack_dashboard/dashboards/project/databases/tables.py
@@ -246,7 +246,7 @@ class InstanceBackupsTable(tables.DataTable):
name = tables.Column("name",
link=("horizon:project:database_backups:detail"),
verbose_name=_("Name"))
- created = tables.Column("created", verbose_name=_("Created At"),
+ created = tables.Column("created", verbose_name=_("Created"),
filters=[filters.parse_isotime])
location = tables.Column(lambda obj: _("Download"),
link=lambda obj: obj.locationRef,
diff --git a/openstack_dashboard/dashboards/project/databases/templates/databases/_detail_overview.html b/openstack_dashboard/dashboards/project/databases/templates/databases/_detail_overview.html
index <HASH>..<HASH> 100644
--- a/openstack_dashboard/dashboards/project/databases/templates/databases/_detail_overview.html
+++ b/openstack_dashboard/dashboards/project/databases/templates/databases/_detail_overview.html
@@ -31,6 +31,10 @@
<dt>{% trans "Volume Size" %}</dt>
<dd>{{ instance.volume.size|diskgbformat }}</dd>
{% endif %}
+ <dt>{% trans "Created" %}</dt>
+ <dd>{{ instance.created|parse_isotime }}</dd>
+ <dt>{% trans "Updated" %}</dt>
+ <dd>{{ instance.updated|parse_isotime }}</dd>
</dl>
</div>
|
Add create and update times for trove components
Currently trove doesn't show created and updated
timestamps on databases and backups - this is
inconsistent with other dashboard components such
as compute and images
Add created and updated timestamps to details
page of databases and backups.
Backups was already display a 'Created At'
timestamp so also made the wording and formatting
of this consistent
Change-Id: Ia<I>db<I>e6d<I>ca<I>e<I>d
Closes-Bug: #<I>
|
openstack_horizon
|
train
|
374ddfa943d383620e189b21512a860f28cadedb
|
diff --git a/go-selinux/selinux_linux.go b/go-selinux/selinux_linux.go
index <HASH>..<HASH> 100644
--- a/go-selinux/selinux_linux.go
+++ b/go-selinux/selinux_linux.go
@@ -41,11 +41,11 @@ const (
)
type selinuxState struct {
- enabledSet bool
- enabled bool
- selinuxfsSet bool
- selinuxfs string
- mcsList map[string]bool
+ enabledSet bool
+ enabled bool
+ selinuxfsOnce sync.Once
+ selinuxfs string
+ mcsList map[string]bool
sync.Mutex
}
@@ -98,14 +98,6 @@ func SetDisabled() {
state.setEnable(false)
}
-func (s *selinuxState) setSELinuxfs(selinuxfs string) string {
- s.Lock()
- defer s.Unlock()
- s.selinuxfsSet = true
- s.selinuxfs = selinuxfs
- return s.selinuxfs
-}
-
func verifySELinuxfsMount(mnt string) bool {
var buf syscall.Statfs_t
for {
@@ -184,15 +176,11 @@ func findSELinuxfsMount(s *bufio.Scanner) string {
}
func (s *selinuxState) getSELinuxfs() string {
- s.Lock()
- selinuxfs := s.selinuxfs
- selinuxfsSet := s.selinuxfsSet
- s.Unlock()
- if selinuxfsSet {
- return selinuxfs
- }
+ s.selinuxfsOnce.Do(func() {
+ s.selinuxfs = findSELinuxfs()
+ })
- return s.setSELinuxfs(findSELinuxfs())
+ return s.selinuxfs
}
// getSelinuxMountPoint returns the path to the mountpoint of an selinuxfs
|
getSELinuxfs: simplify using sync.Once
There's no functional change, but rather code simplification,
as `sync.Once` seem to be ideal for such scenarios.
|
opencontainers_selinux
|
train
|
39d6cfeea82e0c6400b52b5da5ca388d10b18ed9
|
diff --git a/src/main/java/com/pinterest/secor/common/FileRegistry.java b/src/main/java/com/pinterest/secor/common/FileRegistry.java
index <HASH>..<HASH> 100644
--- a/src/main/java/com/pinterest/secor/common/FileRegistry.java
+++ b/src/main/java/com/pinterest/secor/common/FileRegistry.java
@@ -103,6 +103,11 @@ public class FileRegistry {
mWriters.put(path, writer);
mCreationTimes.put(path, System.currentTimeMillis() / 1000L);
LOG.debug("created writer for path {}", path.getLogFilePath());
+ LOG.debug("Register deleteOnExit for path {}", path.getLogFilePath());
+ FileUtil.deleteOnExit(path.getLogFileParentDir());
+ FileUtil.deleteOnExit(path.getLogFileDir());
+ FileUtil.deleteOnExit(path.getLogFilePath());
+ FileUtil.deleteOnExit(path.getLogFileCrcPath());
}
return writer;
}
diff --git a/src/main/java/com/pinterest/secor/util/FileUtil.java b/src/main/java/com/pinterest/secor/util/FileUtil.java
index <HASH>..<HASH> 100644
--- a/src/main/java/com/pinterest/secor/util/FileUtil.java
+++ b/src/main/java/com/pinterest/secor/util/FileUtil.java
@@ -23,6 +23,7 @@ import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
+import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.util.ArrayList;
@@ -141,6 +142,11 @@ public class FileUtil {
}
}
+ public static void deleteOnExit(String path) {
+ File file = new File(path);
+ file.deleteOnExit();
+ }
+
public static void moveToCloud(String srcLocalPath, String dstCloudPath) throws IOException {
Path srcPath = new Path(srcLocalPath);
Path dstPath = new Path(dstCloudPath);
|
Cleanup the local secor files on process exit.
Sometimes secor generates large chunks of local files when process died, although we have a cleanup script, but it only cleans up the files older than <I> hours. Sometimes we gather lots of local files before <I> hour cleanup file and this can cause filesystem full.
Use File.deleteOnExit to clean up the files on exit.
|
pinterest_secor
|
train
|
1fc603042e1df81c34139c5a46473b11fd356fa8
|
diff --git a/test/fuel_surcharge/chronopost_test.rb b/test/fuel_surcharge/chronopost_test.rb
index <HASH>..<HASH> 100644
--- a/test/fuel_surcharge/chronopost_test.rb
+++ b/test/fuel_surcharge/chronopost_test.rb
@@ -38,24 +38,30 @@ module FuelSurcharge
end
end
+ FRENCH_MONTHS = %w[janvier février mars avril mai juin juillet août
+ septembre octobre novembre décembre].freeze
+
def test_live_values
skip if ENV["SKIP_LIVE_TESTS"]
- live_chronopost = Chronopost.new
- live_date = Date.parse live_chronopost.time_period
+ @chronopost = Chronopost.new
+
+ time_period = @chronopost.time_period
+ current_month = FRENCH_MONTHS[Date.today.month - 1]
- assert_equal Date.today.month, live_date.month
- assert_equal Date.today.year, live_date.year
+ assert_kind_of String, time_period
+ assert time_period.downcase.start_with?(current_month)
+ assert time_period.end_with?(Date.today.year.to_s)
- assert_kind_of String, live_chronopost.air_percentage
- refute_empty live_chronopost.air_percentage
- assert_kind_of BigDecimal, live_chronopost.air_multiplier
- assert_operator live_chronopost.air_multiplier, :>=, 1.0
+ assert_kind_of String, @chronopost.air_percentage
+ refute_empty @chronopost.air_percentage
+ assert_kind_of BigDecimal, @chronopost.air_multiplier
+ assert_operator @chronopost.air_multiplier, :>=, 1.0
- assert_kind_of String, live_chronopost.road_percentage
- refute_empty live_chronopost.road_percentage
- assert_kind_of BigDecimal, live_chronopost.road_multiplier
- assert_operator live_chronopost.road_multiplier, :>=, 1.0
+ assert_kind_of String, @chronopost.road_percentage
+ refute_empty @chronopost.road_percentage
+ assert_kind_of BigDecimal, @chronopost.road_multiplier
+ assert_operator @chronopost.road_multiplier, :>=, 1.0
end
private
diff --git a/test/fuel_surcharge/colissimo_test.rb b/test/fuel_surcharge/colissimo_test.rb
index <HASH>..<HASH> 100644
--- a/test/fuel_surcharge/colissimo_test.rb
+++ b/test/fuel_surcharge/colissimo_test.rb
@@ -42,21 +42,24 @@ module FuelSurcharge
def test_live
skip if ENV["SKIP_LIVE_TESTS"]
- live_colissimo = Colissimo.new
- live_date = Date.parse live_colissimo.time_period
+ @colissimo = Colissimo.new
- assert_equal Date.today.month, live_date.month
- assert_equal Date.today.year, live_date.year
+ time_period = @colissimo.time_period
+ current_month = Date.today.month.to_s
- assert_kind_of String, live_colissimo.air_percentage
- refute_empty live_colissimo.air_percentage
- assert_kind_of BigDecimal, live_colissimo.air_multiplier
- assert_operator live_colissimo.air_multiplier, :>=, 1.0
+ assert_kind_of String, time_period
+ assert time_period.start_with?(current_month)
+ assert time_period.end_with?(Date.today.year.to_s)
- assert_kind_of String, live_colissimo.road_percentage
- refute_empty live_colissimo.road_percentage
- assert_kind_of BigDecimal, live_colissimo.road_multiplier
- assert_operator live_colissimo.road_multiplier, :>=, 1.0
+ assert_kind_of String, @colissimo.air_percentage
+ refute_empty @colissimo.air_percentage
+ assert_kind_of BigDecimal, @colissimo.air_multiplier
+ assert_operator @colissimo.air_multiplier, :>=, 1.0
+
+ assert_kind_of String, @colissimo.road_percentage
+ refute_empty @colissimo.road_percentage
+ assert_kind_of BigDecimal, @colissimo.road_multiplier
+ assert_operator @colissimo.road_multiplier, :>=, 1.0
end
private
diff --git a/test/fuel_surcharge/tnt_test.rb b/test/fuel_surcharge/tnt_test.rb
index <HASH>..<HASH> 100644
--- a/test/fuel_surcharge/tnt_test.rb
+++ b/test/fuel_surcharge/tnt_test.rb
@@ -45,11 +45,12 @@ module FuelSurcharge
skip if ENV["SKIP_LIVE_TESTS"]
@tnt = TNT.new
- time_period = @tnt.time_period
- assert_kind_of String, time_period.downcase
+ time_period = @tnt.time_period
+ current_month = FRENCH_MONTHS[Date.today.month - 1]
- assert time_period.start_with?(FRENCH_MONTHS[Date.today.month])
+ assert_kind_of String, time_period
+ assert time_period.downcase.start_with?(current_month)
assert time_period.end_with?(Date.today.year.to_s)
assert_kind_of String, @tnt.air_percentage
|
Fix and unify time_period tests
|
levups_fuel_surcharge
|
train
|
5f703fbd287a751adb5333839d387a62705d1efc
|
diff --git a/CHANGELOG.md b/CHANGELOG.md
index <HASH>..<HASH> 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -2,6 +2,10 @@
## Unreleased
+### Bug Fixes
+
+* Fix pundit policy retrieving for static pages when the pundit namespace is :active_admin. [#5777] by [@kwent]
+
## 2.1.0 [☰](https://github.com/activeadmin/activeadmin/compare/v2.0.0..v2.1.0)
### Bug Fixes
@@ -454,6 +458,7 @@ Please check [0-6-stable] for previous changes.
[#5740]: https://github.com/activeadmin/activeadmin/pull/5740
[#5751]: https://github.com/activeadmin/activeadmin/pull/5751
[#5758]: https://github.com/activeadmin/activeadmin/pull/5758
+[#5777]: https://github.com/activeadmin/activeadmin/pull/5777
[@5t111111]: https://github.com/5t111111
[@aarek]: https://github.com/aarek
@@ -490,6 +495,7 @@ Please check [0-6-stable] for previous changes.
[@johnnyshields]: https://github.com/johnnyshields
[@kjeldahl]: https://github.com/kjeldahl
[@kobeumut]: https://github.com/kobeumut
+[@kwent]: https://github.com/kwent
[@leio10]: https://github.com/leio10
[@markstory]: https://github.com/markstory
[@mauriciopasquier]: https://github.com/mauriciopasquier
diff --git a/lib/active_admin/pundit_adapter.rb b/lib/active_admin/pundit_adapter.rb
index <HASH>..<HASH> 100644
--- a/lib/active_admin/pundit_adapter.rb
+++ b/lib/active_admin/pundit_adapter.rb
@@ -57,8 +57,8 @@ module ActiveAdmin
private
def namespace(object)
- if ActiveAdmin.application.pundit_policy_namespace
- [ActiveAdmin.application.pundit_policy_namespace.to_sym, object]
+ if default_policy_namespace && !object.class.to_s.include?(default_policy_namespace.to_s.camelize)
+ [default_policy_namespace.to_sym, object]
else
object
end
@@ -72,6 +72,10 @@ module ActiveAdmin
default_policy_class.new(user, subject)
end
+ def default_policy_namespace
+ ActiveAdmin.application.pundit_policy_namespace
+ end
+
end
end
diff --git a/spec/unit/pundit_adapter_spec.rb b/spec/unit/pundit_adapter_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/unit/pundit_adapter_spec.rb
+++ b/spec/unit/pundit_adapter_spec.rb
@@ -130,5 +130,17 @@ RSpec.describe ActiveAdmin::PunditAdapter do
end
end
end
+
+ context "when retrieve_policy is given a page and namespace is :active_admin" do
+ let(:page) { namespace.register_page "Dashboard" }
+
+ subject(:policy) { auth.retrieve_policy(page) }
+
+ before do
+ allow(ActiveAdmin.application).to receive(:pundit_policy_namespace).and_return :active_admin
+ end
+
+ it("should return page policy instance") { is_expected.to be_instance_of(ActiveAdmin::PagePolicy) }
+ end
end
end
|
Fix pundit policy retrieving on an edge case (#<I>)
When retrieving the policy for an `ActiveAdmin::Page`, and the pundit
namespace is `:active_admin`, we need an extra check so that the right
policy is properly picked up.
|
activeadmin_activeadmin
|
train
|
b20819c97ac8dbbda10dc46715033bca9a13f15d
|
diff --git a/billing/tests/eway_tests.py b/billing/tests/eway_tests.py
index <HASH>..<HASH> 100644
--- a/billing/tests/eway_tests.py
+++ b/billing/tests/eway_tests.py
@@ -65,15 +65,23 @@ class EWayGatewayTestCase(TestCase):
self.assertEquals(self.credit_card.card_type, Visa)
def testPurchase(self):
- resp = self.merchant.purchase(1, self.credit_card,
+ resp = self.merchant.purchase(100, self.credit_card,
+ options=fake_options)
+ self.assertEquals(resp["status"], "SUCCESS")
+ self.assertNotEquals(resp["response"].ewayTrxnStatus, True)
+ self.assertEquals(resp["response"].ewayTrxnError,
+ "00,Transaction Approved(Test Gateway)")
+ self.assertNotEquals(resp["response"].ewayTrxnNumber, "0")
+ self.assertTrue(resp["response"].ewayReturnAmount, "100")
+
+ def testFailure(self):
+ resp = self.merchant.purchase(105, self.credit_card,
options=fake_options)
- # Eway test gateway sets the transaction status as failure
- # in test mode
self.assertEquals(resp["status"], "FAILURE")
self.assertEquals(resp["response"].ewayTrxnError,
- "1,Do Not Honour(Test Gateway)")
+ "05,Do Not Honour(Test Gateway)")
self.assertNotEquals(resp["response"].ewayTrxnNumber, "0")
- self.assertTrue(resp["response"].ewayReturnAmount, "1")
+ self.assertTrue(resp["response"].ewayReturnAmount, "100")
def testDirectPayment(self):
credit_card_details = {
diff --git a/example/app/views.py b/example/app/views.py
index <HASH>..<HASH> 100644
--- a/example/app/views.py
+++ b/example/app/views.py
@@ -74,7 +74,7 @@ def paypal(request):
def eway(request):
- amount = 1
+ amount = 100
response = None
if request.method == 'POST':
form = CreditCardForm(request.POST)
|
eway - fix purchase test, add failure test case
use <I> for success, <I> for failure according to
<URL>)
|
agiliq_merchant
|
train
|
50a811720ff180d939b4a7ae83c3b65a8186514a
|
diff --git a/ReactNativeClient/lib/components/global-style.js b/ReactNativeClient/lib/components/global-style.js
index <HASH>..<HASH> 100644
--- a/ReactNativeClient/lib/components/global-style.js
+++ b/ReactNativeClient/lib/components/global-style.js
@@ -140,7 +140,7 @@ function themeStyle(theme) {
output.raisedHighlightedColor = '#ffffff';
output.htmlColor = 'rgb(220,220,220)';
- output.htmlBackgroundColor = 'rgb(29,32,36)';
+ output.htmlBackgroundColor = 'rgb(0,0,0)';
output.htmlLinkColor = 'rgb(166,166,255)';
output.htmlDividerColor = '#3D444E';
|
Mobile: Fixes #<I>: Fixed colour of background in OLED dark theme (#<I>)
|
laurent22_joplin
|
train
|
b5fd176120ba85ef88c8d9d1b21e722975cbac63
|
diff --git a/views/js/controller/creator/creator.js b/views/js/controller/creator/creator.js
index <HASH>..<HASH> 100644
--- a/views/js/controller/creator/creator.js
+++ b/views/js/controller/creator/creator.js
@@ -73,11 +73,11 @@ define([
providerLoaderFactory()
.addList({
- previwers: {
+ previewers: {
id: 'qtiTests',
module: 'taoQtiTestPreviewer/previewer/adapter/test/qtiTest',
bundle: 'taoQtiTestPreviewer/loader/qtiPreviewer.min',
- category: 'previwers'
+ category: 'previewers'
}
})
.load(context.bundle)
|
Update views/js/controller/creator/creator.js
|
oat-sa_extension-tao-testqti
|
train
|
5a9062afa5473d648f6aedbfcfd643ec5b26ed40
|
diff --git a/qa/integration-tests-webapps/src/test/java/org/camunda/bpm/rest/test/RestIT.java b/qa/integration-tests-webapps/src/test/java/org/camunda/bpm/rest/test/RestIT.java
index <HASH>..<HASH> 100644
--- a/qa/integration-tests-webapps/src/test/java/org/camunda/bpm/rest/test/RestIT.java
+++ b/qa/integration-tests-webapps/src/test/java/org/camunda/bpm/rest/test/RestIT.java
@@ -1,24 +1,22 @@
package org.camunda.bpm.rest.test;
-import com.sun.jersey.api.client.ClientResponse;
-import com.sun.jersey.api.client.WebResource;
-import com.sun.jersey.multipart.Boundary;
-import com.sun.jersey.multipart.FormDataMultiPart;
-import com.sun.jersey.multipart.file.StreamDataBodyPart;
-import java.io.InputStream;
+import static org.junit.Assert.assertEquals;
+
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Logger;
+
import javax.ws.rs.core.MediaType;
+
import org.camunda.bpm.AbstractWebappIntegrationTest;
import org.codehaus.jettison.json.JSONArray;
import org.codehaus.jettison.json.JSONException;
import org.codehaus.jettison.json.JSONObject;
import org.junit.Assert;
-import org.junit.Before;
import org.junit.Test;
-import static org.junit.Assert.assertEquals;
+import com.sun.jersey.api.client.ClientResponse;
+import com.sun.jersey.api.client.WebResource;
public class RestIT extends AbstractWebappIntegrationTest {
@@ -36,11 +34,6 @@ public class RestIT extends AbstractWebappIntegrationTest {
return "engine-rest/";
}
- @Before
- public void deployAdditionalProcess() {
- deployProcess("jobexample.bpmn", "org/camunda/bpm/rest/test/jobexample.bpmn");
- }
-
@Test
public void testScenario() throws JSONException {
@@ -70,7 +63,7 @@ public class RestIT extends AbstractWebappIntegrationTest {
JSONArray definitionsJson = response.getEntity(JSONArray.class);
// invoice example
- assertEquals(2, definitionsJson.length());
+ assertEquals(1, definitionsJson.length());
JSONObject definitionJson = definitionsJson.getJSONObject(0);
@@ -103,22 +96,6 @@ public class RestIT extends AbstractWebappIntegrationTest {
}
@Test
- public void testDelayedProcessDefinitionSuspension() {
- log.info("Checking " + APP_BASE_PATH + PROCESS_DEFINITION_PATH + "/key/invoice/suspended");
-
- WebResource resource = client.resource(APP_BASE_PATH + PROCESS_DEFINITION_PATH + "/key/invoice/suspended");
-
- Map<String, Object> requestBody = new HashMap<String, Object>();
- requestBody.put("suspended", true);
- requestBody.put("includeProcessInstances", true);
- requestBody.put("executionDate", "2014-08-25T13:55:45");
-
- ClientResponse response = resource.accept(MediaType.APPLICATION_JSON).type(MediaType.APPLICATION_JSON).put(ClientResponse.class, requestBody);
-
- assertEquals(204, response.getStatus());
- }
-
- @Test
public void testDelayedJobDefinitionSuspension() {
log.info("Checking " + APP_BASE_PATH + JOB_DEFINITION_PATH + "/suspended");
@@ -135,25 +112,4 @@ public class RestIT extends AbstractWebappIntegrationTest {
assertEquals(204, response.getStatus());
}
- protected void deployProcess(String filename, String resourcePath) {
- WebResource resource = client.resource(APP_BASE_PATH + "deployment/create");
-
- FormDataMultiPart formDataMultiPart = new FormDataMultiPart();
- formDataMultiPart.field("deployment-name", "jobProcess");
- formDataMultiPart.field("enable-duplicate-filtering", "true");
-
- InputStream bpmnResource = getClass().getClassLoader().getResourceAsStream(resourcePath);
- StreamDataBodyPart data = new StreamDataBodyPart("data", bpmnResource, filename, MediaType.MULTIPART_FORM_DATA_TYPE);
- formDataMultiPart.bodyPart(data);
-
- ClientResponse response = resource
- // Workaround for known issue https://java.net/jira/browse/JERSEY-1424
- .type(Boundary.addBoundary(MediaType.MULTIPART_FORM_DATA_TYPE))
- .accept(MediaType.APPLICATION_JSON).post(ClientResponse.class, formDataMultiPart);
- assertEquals(200, response.getStatus());
-
- response.close();
- }
-
-
}
|
fix(qa): remove error-prone deployment by http client
- the deployment seems to be error-prone for glassfish
which leads to other problems during our CI
related to #CAM-<I>
|
camunda_camunda-bpm-platform
|
train
|
03cd644ac85c4c60e81a85b7a2882839e309c99a
|
diff --git a/agrona/src/main/java/org/agrona/concurrent/CountedErrorHandler.java b/agrona/src/main/java/org/agrona/concurrent/CountedErrorHandler.java
index <HASH>..<HASH> 100644
--- a/agrona/src/main/java/org/agrona/concurrent/CountedErrorHandler.java
+++ b/agrona/src/main/java/org/agrona/concurrent/CountedErrorHandler.java
@@ -52,11 +52,21 @@ public class CountedErrorHandler implements ErrorHandler, AutoCloseable
isClosed = true;
}
+ /**
+ * Has this instance been closed.
+ *
+ * @return true if {@link #close()} has previously be called, otherwise false.
+ */
+ public boolean isClosed()
+ {
+ return isClosed;
+ }
+
public void onError(final Throwable throwable)
{
if (isClosed)
{
- throwable.printStackTrace();
+ throwable.printStackTrace(System.err);
}
else
{
|
[Java] Add the ability to query if CountedErrorHandler has been closed.
|
real-logic_agrona
|
train
|
4e0875bccb6c3c6867174e7824ed5b246a2eae58
|
diff --git a/test/test_examples.py b/test/test_examples.py
index <HASH>..<HASH> 100644
--- a/test/test_examples.py
+++ b/test/test_examples.py
@@ -11,7 +11,8 @@ from glob import glob
# tests to exclude
excludes = ['authorization_v1.py', 'message_resonance_v1_beta.py', 'concept_expansion_v1.py',
- 'relationship_extraction_v1_beta.py', 'document_conversion_v1_experimental.py']
+ 'relationship_extraction_v1_beta.py', 'document_conversion_v1_experimental.py',
+ 'alchemy_data_news_v1.py', 'alchemy_language_v1.py', 'alchemy_vision_v1.py']
# examples path. /examples
examples_path = join(dirname(__file__), '../', 'examples', '*.py')
|
commenting out alchemy tests since key limits are often reached
|
watson-developer-cloud_python-sdk
|
train
|
b03fd637f8629d401a7397677bfaa160249041b8
|
diff --git a/index.js b/index.js
index <HASH>..<HASH> 100644
--- a/index.js
+++ b/index.js
@@ -95,7 +95,6 @@ module.exports = function(messenger, opts) {
var announceTimer = 0;
function announceOnReconnect() {
- connected = true;
signaller.announce();
}
@@ -105,6 +104,7 @@ module.exports = function(messenger, opts) {
});
messenger.addEventListener('open', function(evt) {
+ connected = true;
signaller.emit('open');
signaller.emit('connected');
});
@@ -126,6 +126,7 @@ module.exports = function(messenger, opts) {
// when the connection is open, then emit an open event and a connected event
messenger.on(opts.openEvent, function() {
+ connected = true;
signaller.emit('open');
signaller.emit('connected');
});
@@ -212,8 +213,6 @@ module.exports = function(messenger, opts) {
connected = messenger.connected || false;
if (! connected) {
signaller.once('connected', function() {
- connected = true;
-
// always announce on reconnect
signaller.on('connected', announceOnReconnect);
});
|
Set connected = true in the most reliable place
|
rtc-io_rtc-signaller
|
train
|
fd758c015f28b1304944806d71b109000078c7fa
|
diff --git a/devserver.js b/devserver.js
index <HASH>..<HASH> 100644
--- a/devserver.js
+++ b/devserver.js
@@ -51,16 +51,18 @@ var devSetup = function (cb) {
});
};
-var defaultHeaderValue = "default-src 'self'; img-src 'self' data:; font-src 'self'; " +
+const defaultHeaderValue = "default-src 'self'; img-src 'self' data:; font-src 'self'; " +
"script-src 'self' 'unsafe-eval'; style-src 'self' 'unsafe-inline';";
-var setCSP = function (res) {
+function getCspHeaders () {
if (!settings.contentSecurityPolicy) {
return;
}
- var headerValue = settings.contentSecurityPolicyHeader || defaultHeaderValue;
+ const cspHeader = settings.contentSecurityPolicyHeader || defaultHeaderValue;
- res.set('Content-Security-Policy', headerValue);
+ return {
+ 'Content-Security-Policy': cspHeader
+ };
};
var runWebpackServer = function () {
@@ -81,7 +83,8 @@ var runWebpackServer = function () {
historyApiFallback: true,
stats: {
colors: true,
- }
+ },
+ headers: getCspHeaders(),
};
var compiler = webpack(config);
@@ -104,7 +107,6 @@ var runWebpackServer = function () {
});
server.app.all('*', function (req, res, next) {
- setCSP(res);
proxy.web(req, res);
});
|
devserver: readd/fix csp header
The CSP headers were not set, as directly interacting with express
in `webpack-dev-server` to set the headers does not work.
PR: #<I>
PR-URL: <URL>
|
apache_couchdb-fauxton
|
train
|
7aef76769783b53a905a8c936634c857b040c4dc
|
diff --git a/lib/core/src/server/utils/load-custom-babel-config.js b/lib/core/src/server/utils/load-custom-babel-config.js
index <HASH>..<HASH> 100644
--- a/lib/core/src/server/utils/load-custom-babel-config.js
+++ b/lib/core/src/server/utils/load-custom-babel-config.js
@@ -41,7 +41,7 @@ function loadFromPath(babelConfigPath) {
We tried both loading as JS & JSON, neither worked.
Maybe there's a syntax error in the file?`);
logger.error(`=> From JS loading we got: ${error.js.message}`);
- logger.error(`=> From JSON loading we got: ${error.js.message}`);
+ logger.error(`=> From JSON loading we got: ${error.json && error.json.message}`);
throw error.js;
}
|
Fix JSON babel config error reporting
|
storybooks_storybook
|
train
|
565f205d16c746a7344a0239f22af73b3e449bbd
|
diff --git a/commands/configure_topic.js b/commands/configure_topic.js
index <HASH>..<HASH> 100644
--- a/commands/configure_topic.js
+++ b/commands/configure_topic.js
@@ -65,7 +65,7 @@ module.exports = {
Examples:
$ heroku kafka:configure page-visits --retention-time 86400000
- $ heroku kafka:configure HEROKU_KAFKA_BROWN_URL page-visits --partitions 100 --replication-factor 3 --retention-time 86400000 --compaction
+ $ heroku kafka:configure HEROKU_KAFKA_BROWN_URL page-visits --retention-time 86400000 --compaction
`,
needsApp: true,
needsAuth: true,
diff --git a/commands/fail.js b/commands/fail.js
index <HASH>..<HASH> 100644
--- a/commands/fail.js
+++ b/commands/fail.js
@@ -70,14 +70,14 @@ function* fail (context, heroku) {
module.exports = {
topic: 'kafka',
command: 'fail',
- description: 'triggers failure on one Kafka node in the cluster',
+ description: 'Triggers failure on one kafka node in the cluster',
help: `
Triggers failure on one node in the cluster.
Examples:
$ heroku kafka:fail
- $ heroku kafka:fail HEROKU_KAFKA_BROWN
+ $ heroku kafka:fail HEROKU_KAFKA_BROWN_URL
`,
needsApp: true,
needsAuth: true,
diff --git a/commands/info.js b/commands/info.js
index <HASH>..<HASH> 100644
--- a/commands/info.js
+++ b/commands/info.js
@@ -26,7 +26,7 @@ module.exports = {
topic: 'kafka',
command: 'info',
default: true,
- description: 'shows information about the state of your Heroku Kafka cluster',
+ description: 'Shows information about the state of your Heroku Kafka cluster',
args: [
{
name: 'CLUSTER',
@@ -39,7 +39,7 @@ module.exports = {
Examples:
$ heroku kafka:info
- $ heroku kafka:info kafka-adjacent-1337
+ $ heroku kafka:info HEROKU_KAFKA_BROWN_URL
`,
needsApp: true,
needsAuth: true,
diff --git a/commands/list_topics.js b/commands/list_topics.js
index <HASH>..<HASH> 100644
--- a/commands/list_topics.js
+++ b/commands/list_topics.js
@@ -27,9 +27,9 @@ function* listTopics (context, heroku) {
module.exports = {
topic: 'kafka',
command: 'list',
- description: 'lists available kafka topics, including their replicas and partitions',
+ description: 'Lists available kafka topics',
help: `
- Lists available kafka topics with information on replicas and partitions for each.
+ Lists available kafka topics.
Examples:
diff --git a/commands/topic.js b/commands/topic.js
index <HASH>..<HASH> 100644
--- a/commands/topic.js
+++ b/commands/topic.js
@@ -23,7 +23,7 @@ function* kafkaTopic (context, heroku) {
module.exports = {
topic: 'kafka',
command: 'topic',
- description: 'shows information about a topic in your Heroku kafka cluster',
+ description: 'Shows information about a topic in kafka',
args: [
{
name: 'TOPIC',
@@ -40,7 +40,7 @@ module.exports = {
Examples:
$ heroku kafka:info page-visits
- $ heroku kafka:info page-visits kafka-adjacent-1337
+ $ heroku kafka:info page-visits HEROKU_KAFKA_BROWN_URL
`,
needsApp: true,
needsAuth: true,
diff --git a/commands/wait.js b/commands/wait.js
index <HASH>..<HASH> 100644
--- a/commands/wait.js
+++ b/commands/wait.js
@@ -21,7 +21,7 @@ function* kafkaWait (context, heroku) {
module.exports = {
topic: 'kafka',
command: 'wait',
- description: 'Waits until the kafka cluster is ready to use',
+ description: 'Waits until kafka is ready to use',
args: [
{
name: 'CLUSTER',
@@ -32,7 +32,7 @@ module.exports = {
Examples:
$ heroku kafka:wait
- $ heroku kafka:wait HEROKU_KAFKA_BROWN
+ $ heroku kafka:wait HEROKU_KAFKA_BROWN_URL
`,
needsApp: true,
needsAuth: true,
|
standardize help text everywhere
- always say 'kafka', not 'Kafka' or 'Heroku kafka' or 'the kafka cluster'
- all commands that take a CLUSTER argument have that in the examples
- all commands that take a CLUSTER argument just include
HEROKU_KAFKA_BROWN_URL instead of using the haiku names.
|
heroku_heroku-kafka-jsplugin
|
train
|
84ef28789038e38189a715a9fbb7e3d2eaea875c
|
diff --git a/sprd/model/ShippingType.js b/sprd/model/ShippingType.js
index <HASH>..<HASH> 100644
--- a/sprd/model/ShippingType.js
+++ b/sprd/model/ShippingType.js
@@ -21,14 +21,14 @@ define(['sprd/data/SprdModel', 'sprd/entity/ShippingCountry', 'sprd/entity/Shipp
/***
* this method is necessary, because ShippingCountry should be a model, but is defined by the API as entity
*
- * @param id
+ * @param code
* @returns {*}
*/
- getShippingCountryById: function (id) {
+ getShippingCountryByCode: function (code) {
for (var i = 0; i < this.$.shippingCountries.$items.length; i++) {
var shippingCountry = this.$.shippingCountries.$items[i];
- if (shippingCountry.$.id == id) {
+ if (shippingCountry.$.code == code) {
return shippingCountry;
}
}
@@ -37,7 +37,7 @@ define(['sprd/data/SprdModel', 'sprd/entity/ShippingCountry', 'sprd/entity/Shipp
},
supportsShippingTo: function (shippingCountry) {
- return !!this.getShippingCountryById(shippingCountry.$.id);
+ return !!this.getShippingCountryByCode(shippingCountry.$.code);
}
});
|
refactored method for getting shipping country
|
spreadshirt_rAppid.js-sprd
|
train
|
1bc1561b3f89fd6ab917e2330eca177f71562351
|
diff --git a/ph-commons/src/main/java/com/helger/commons/collection/impl/CommonsArrayList.java b/ph-commons/src/main/java/com/helger/commons/collection/impl/CommonsArrayList.java
index <HASH>..<HASH> 100644
--- a/ph-commons/src/main/java/com/helger/commons/collection/impl/CommonsArrayList.java
+++ b/ph-commons/src/main/java/com/helger/commons/collection/impl/CommonsArrayList.java
@@ -38,6 +38,8 @@ import com.helger.commons.collection.CollectionHelper;
*/
public class CommonsArrayList <ELEMENTTYPE> extends ArrayList <ELEMENTTYPE> implements ICommonsList <ELEMENTTYPE>
{
+ // No logger here!
+
public CommonsArrayList ()
{}
diff --git a/ph-commons/src/main/java/com/helger/commons/io/resource/ClassPathResource.java b/ph-commons/src/main/java/com/helger/commons/io/resource/ClassPathResource.java
index <HASH>..<HASH> 100644
--- a/ph-commons/src/main/java/com/helger/commons/io/resource/ClassPathResource.java
+++ b/ph-commons/src/main/java/com/helger/commons/io/resource/ClassPathResource.java
@@ -59,6 +59,8 @@ public class ClassPathResource implements IReadableResource, IHasClassLoader
/** Internal debug logging flag */
private static final boolean DEBUG_GET_IS = false;
+ // No logger here!
+
private String m_sPath;
private final WeakReference <ClassLoader> m_aClassLoader;
private boolean m_bURLResolved = false;
diff --git a/ph-commons/src/main/java/com/helger/commons/lang/NonBlockingProperties.java b/ph-commons/src/main/java/com/helger/commons/lang/NonBlockingProperties.java
index <HASH>..<HASH> 100644
--- a/ph-commons/src/main/java/com/helger/commons/lang/NonBlockingProperties.java
+++ b/ph-commons/src/main/java/com/helger/commons/lang/NonBlockingProperties.java
@@ -82,11 +82,11 @@ import com.helger.commons.system.ENewLineMode;
*/
public class NonBlockingProperties extends CommonsLinkedHashMap <String, String>
{
+ // No logger here!
+
/**
* A property list that contains default values for any keys not found in this
* property list.
- *
- * @serial
*/
protected NonBlockingProperties m_aDefaults;
@@ -95,7 +95,7 @@ public class NonBlockingProperties extends CommonsLinkedHashMap <String, String>
*/
public NonBlockingProperties ()
{
- this (null);
+ this ((NonBlockingProperties) null);
}
/**
@@ -823,9 +823,7 @@ public class NonBlockingProperties extends CommonsLinkedHashMap <String, String>
*/
public void store (@Nonnull @WillNotClose final OutputStream aOS, @Nullable final String sComments) throws IOException
{
- _store (new NonBlockingBufferedWriter (new OutputStreamWriter (aOS, StandardCharsets.ISO_8859_1)),
- sComments,
- true);
+ _store (new NonBlockingBufferedWriter (new OutputStreamWriter (aOS, StandardCharsets.ISO_8859_1)), sComments, true);
}
private void _store (@Nonnull @WillNotClose final Writer aWriter,
@@ -906,11 +904,11 @@ public class NonBlockingProperties extends CommonsLinkedHashMap <String, String>
* <code>null</code>.
*/
@Nonnull
- public static NonBlockingProperties create (@Nullable final Map <Object, Object> aProperties)
+ public static NonBlockingProperties create (@Nullable final Map <?, ?> aProperties)
{
final NonBlockingProperties ret = new NonBlockingProperties ();
if (aProperties != null)
- for (final Map.Entry <Object, Object> aEntry : aProperties.entrySet ())
+ for (final Map.Entry <?, ?> aEntry : aProperties.entrySet ())
ret.put ((String) aEntry.getKey (), (String) aEntry.getValue ());
return ret;
}
diff --git a/ph-commons/src/main/java/com/helger/commons/lang/PropertiesHelper.java b/ph-commons/src/main/java/com/helger/commons/lang/PropertiesHelper.java
index <HASH>..<HASH> 100644
--- a/ph-commons/src/main/java/com/helger/commons/lang/PropertiesHelper.java
+++ b/ph-commons/src/main/java/com/helger/commons/lang/PropertiesHelper.java
@@ -48,6 +48,8 @@ import com.helger.commons.url.ISimpleURL;
@Immutable
public final class PropertiesHelper
{
+ // No logger here!
+
private PropertiesHelper ()
{}
@@ -57,7 +59,7 @@ public final class PropertiesHelper
{
ValueEnforcer.notNull (aProps, "Props");
- final ICommonsMap <String, String> ret = new CommonsHashMap<> ();
+ final ICommonsMap <String, String> ret = new CommonsHashMap <> ();
for (final Map.Entry <Object, Object> aEntry : aProps.entrySet ())
ret.put ((String) aEntry.getKey (), (String) aEntry.getValue ());
return ret;
|
Added note that no logger may be used in these classes
|
phax_ph-commons
|
train
|
c7619596557694253d1aa5bbbb29ba94ff52f9f9
|
diff --git a/pyemu/utils/gw_utils.py b/pyemu/utils/gw_utils.py
index <HASH>..<HASH> 100644
--- a/pyemu/utils/gw_utils.py
+++ b/pyemu/utils/gw_utils.py
@@ -9,7 +9,7 @@ def pilot_points_to_tpl(pp_file,tpl_file=None,name_prefix=None):
tpl_file = pp_file+".tpl"
pp_df = pd.read_csv(pp_file,delim_whitespace=True,header=None,
- names=["name","x","y","zone","value"])
+ names=["name","x","y","zone","parval1"])
if name_prefix is not None:
digits = str(len(str(pp_df.shape[0])))
@@ -28,6 +28,7 @@ def pilot_points_to_tpl(pp_file,tpl_file=None,name_prefix=None):
tpl_entries = ["~ {0} ~".format(name) for name in names]
pp_df.loc[:,"tpl"] = tpl_entries
+ pp_df.loc[:,"parnme"] = names
fmt = {"name":SFMT,"x":FFMT,"y":FFMT,"zone":IFMT,"tpl":SFMT}
f_tpl = open(tpl_file,'w')
|
few more tweaks to pp to tpl
|
jtwhite79_pyemu
|
train
|
66c4e39c999ba6ae1d7a0eefbd47cf149cfe8fa1
|
diff --git a/index.js b/index.js
index <HASH>..<HASH> 100644
--- a/index.js
+++ b/index.js
@@ -116,14 +116,13 @@ function watch (globString, options, renderer, initialDone) {
loader.on('change', debouncedBuild)
- // perform the initial load/render
- glob(globString, function(err, filenames) {
- if (err) {
- console.error(err)
- } else {
- build(filenames)
- }
- })
+ // return a function that allows manual triggering of a full build
+ return function () {
+ return glob(globString)
+ .then(function (filenames) {
+ build(filenames)
+ })
+ }
})
}
|
return a function that can trigger a build, rather than assuming that an initial build should be done
|
ocadotechnology_quantumjs
|
train
|
96ac3e3268571911b287599c3e83a5fc77631587
|
diff --git a/spec/hook_handler/hook_handler_hook_spec.rb b/spec/hook_handler/hook_handler_hook_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/hook_handler/hook_handler_hook_spec.rb
+++ b/spec/hook_handler/hook_handler_hook_spec.rb
@@ -3,8 +3,9 @@ require "evalhook"
describe EvalHook::HookHandler, "hook handler hooks" do
- class X
+ class X2
def foo
+ 9
end
def bar
@@ -18,7 +19,7 @@ describe EvalHook::HookHandler, "hook handler hooks" do
redirect_method(klass, recv, :bar)
end
- x = X.new
+ x = X2.new
hh.evalhook("x.foo", binding).should be == 4
end
|
fixed name of test class in first hooking test
|
tario_evalhook
|
train
|
b09a27c022e5794351eb2880302d9ad13bc3b1a4
|
diff --git a/flow/table_test.go b/flow/table_test.go
index <HASH>..<HASH> 100644
--- a/flow/table_test.go
+++ b/flow/table_test.go
@@ -224,20 +224,12 @@ func TestFlowTable_GetFlow(t *testing.T) {
}
}
-func isJSON(s string) bool {
- var js map[string]interface{}
- return json.Unmarshal([]byte(s), &js) == nil
-}
-
func TestFlowTable_JSONFlowConversationEthernetPath(t *testing.T) {
ft := NewFlowTableComplex(t)
statStr := ft.JSONFlowConversationEthernetPath()
if statStr == `{"nodes":[],"links":[]}` {
t.Error("stat should not be empty")
}
- if !isJSON(statStr) {
- t.Error("stat should be JSON format")
- }
decoded := new(interface{})
if err := json.Unmarshal([]byte(statStr), decoded); err != nil {
|
[tests] FlowTable remove unused isJSON()
Not revelant as there are a JSON schema checker.
|
skydive-project_skydive
|
train
|
cf333e82a626008400c4db784dda27c5d9d21e5d
|
diff --git a/cmd/oauth_test.go b/cmd/oauth_test.go
index <HASH>..<HASH> 100644
--- a/cmd/oauth_test.go
+++ b/cmd/oauth_test.go
@@ -14,3 +14,12 @@ func (s *S) TestClientID(c *gocheck.C) {
c.Assert(err, gocheck.IsNil)
c.Assert("someid", gocheck.Equals, clientID())
}
+
+func (s *S) TestPort(c *gocheck.C) {
+ err := os.Setenv("TSURU_AUTH_SERVER_PORT", ":4242")
+ c.Assert(err, gocheck.IsNil)
+ c.Assert(":4242", gocheck.Equals, port())
+ err = os.Setenv("TSURU_AUTH_SERVER_PORT", "")
+ c.Assert(err, gocheck.IsNil)
+ c.Assert(":0", gocheck.Equals, port())
+}
|
cmd/oauth: added test to port.
|
tsuru_tsuru
|
train
|
c1ff2379a91747aba7b950e4677d60f3dcd64122
|
diff --git a/bosh_cli/spec/spec_helper.rb b/bosh_cli/spec/spec_helper.rb
index <HASH>..<HASH> 100644
--- a/bosh_cli/spec/spec_helper.rb
+++ b/bosh_cli/spec/spec_helper.rb
@@ -4,6 +4,7 @@ require 'rspec/its'
require 'webmock'
require 'timecop'
require 'cli'
+require 'fakefs/spec_helpers'
Dir.glob(File.expand_path('../support/**/*.rb', __FILE__)).each { |f| require(f) }
diff --git a/bosh_cli/spec/unit/commands/misc_spec.rb b/bosh_cli/spec/unit/commands/misc_spec.rb
index <HASH>..<HASH> 100644
--- a/bosh_cli/spec/unit/commands/misc_spec.rb
+++ b/bosh_cli/spec/unit/commands/misc_spec.rb
@@ -3,6 +3,8 @@
require "spec_helper"
describe Bosh::Cli::Command::Misc do
+ include FakeFS::SpecHelpers
+
let(:command) { described_class.new }
let(:director) { double(Bosh::Cli::Client::Director) }
let(:versions_index) { double(Bosh::Cli::VersionsIndex) }
@@ -16,7 +18,7 @@ describe Bosh::Cli::Command::Misc do
Bosh::Cli::Release.stub(:new).and_return(release)
end
- before :all do
+ before do
@config_file = File.join(Dir.mktmpdir, "bosh_config")
end
@@ -119,4 +121,60 @@ describe Bosh::Cli::Command::Misc do
command.status
end
end
-end
\ No newline at end of file
+
+ describe '#target' do
+ context 'target is set' do
+ let(:target) { "https://fake.bosh.director:25555" }
+ let(:target_name) { "micro-fake-bosh" }
+ let(:uuid) { SecureRandom.uuid }
+
+ before do
+ File.open(@config_file, 'w+') do |f|
+ f.write(<<EOS)
+---
+target: #{target}
+target_name: #{target_name}
+target_uuid: #{uuid}
+EOS
+ end
+ end
+
+ context 'is interactive' do
+ context 'target name is set' do
+ it 'decorates target with target name' do
+ command.add_option(:config, @config_file)
+ command.should_receive(:say).with("Current target is #{target} (#{target_name})")
+ command.set_target
+ end
+ end
+
+ context 'name is not set' do
+ let(:target_name) { nil }
+
+ it 'decorates target' do
+ command.add_option(:config, @config_file)
+ command.should_receive(:say).with("Current target is #{target}")
+ command.set_target
+ end
+ end
+ end
+
+ context 'is non-interactive' do
+ it 'does not decorates target' do
+ command.add_option(:config, @config_file)
+ command.add_option(:non_interactive, true)
+ command.should_receive(:say).with("#{target}")
+ command.set_target
+ end
+ end
+ end
+
+ context 'target is not set' do
+ it 'errors' do
+ command.add_option(:config, @config_file)
+ command.should_receive(:err).with("Target not set")
+ command.set_target
+ end
+ end
+ end
+end
|
Backfill specs for `bosh target` and `bosh -n target`
|
cloudfoundry_bosh
|
train
|
51fd26489ecafb1328e10b428276287f35acaf07
|
diff --git a/librosa/display.py b/librosa/display.py
index <HASH>..<HASH> 100644
--- a/librosa/display.py
+++ b/librosa/display.py
@@ -338,7 +338,7 @@ def __envelope(x, hop):
def waveplot(y, sr=22050, max_points=5e4, x_axis='time', offset=0.0, max_sr=1000,
- **kwargs):
+ time_fmt=None, **kwargs):
'''Plot the amplitude envelope of a waveform.
If `y` is monophonic, a filled curve is drawn between `[-abs(y), abs(y)]`.
@@ -375,6 +375,11 @@ def waveplot(y, sr=22050, max_points=5e4, x_axis='time', offset=0.0, max_sr=1000
max_sr : number > 0 [scalar]
Maximum sampling rate for the visualization
+ time_fmt : None or str
+ Formatting for time axis. None (automatic) by default.
+
+ See `time_ticks`.
+
kwargs
Additional keyword arguments to `matplotlib.pyplot.fill_between`
@@ -465,7 +470,7 @@ def waveplot(y, sr=22050, max_points=5e4, x_axis='time', offset=0.0, max_sr=1000
plt.xlim([locs[0], locs[-1]])
if x_axis == 'time':
- time_ticks(locs, core.samples_to_time(locs, sr=target_sr))
+ time_ticks(locs, core.samples_to_time(locs, sr=target_sr), fmt=time_fmt)
elif x_axis is None or x_axis in ['off', 'none']:
plt.xticks([])
else:
|
added time_fmt to waveplot
|
librosa_librosa
|
train
|
0f6f3a667a5eb22f00d4551f9846cf7821d45cc2
|
diff --git a/tests/test_asymetric.py b/tests/test_asymetric.py
index <HASH>..<HASH> 100644
--- a/tests/test_asymetric.py
+++ b/tests/test_asymetric.py
@@ -80,12 +80,17 @@ class TestUtil(unittest.TestCase):
plainText = "A test string"
mech = PyKCS11.RSAOAEPMechanism(PyKCS11.CKM_SHA_1, PyKCS11.CKG_MGF1_SHA1)
- cipherText = self.session.encrypt(pubKey, plainText, mech)
- decrypted = self.session.decrypt(privKey, cipherText, mech)
+ try:
+ cipherText = self.session.encrypt(pubKey, plainText, mech)
+ decrypted = self.session.decrypt(privKey, cipherText, mech)
- text = "".join(map(chr, decrypted))
+ text = "".join(map(chr, decrypted))
- self.assertEqual(text, plainText)
+ self.assertEqual(text, plainText)
+ except PyKCS11.PyKCS11Error as e:
+ # RSA OAEP is not support by SoftHSM1
+ if not e.value == PyKCS11.CKR_MECHANISM_INVALID:
+ raise
self.session.destroyObject(pubKey)
self.session.destroyObject(privKey)
|
test_asymetric: RSA OAEP is not supported by SoftHSM1
|
LudovicRousseau_PyKCS11
|
train
|
41ac4d24772dfe2c80e7c27fab45807f0a648101
|
diff --git a/modules/upkeep.php b/modules/upkeep.php
index <HASH>..<HASH> 100644
--- a/modules/upkeep.php
+++ b/modules/upkeep.php
@@ -22,7 +22,7 @@ if ( ! class_exists('Upkeep') ) {
if ( getenv('WP_ENV') === 'production' ) {
seravo_add_postbox(
'site-status',
- __('Site Status', 'seravo'),
+ __('Update Status', 'seravo'),
array( __CLASS__, 'site_status_postbox' ),
'tools_page_upkeep_page',
'normal'
|
Rename "Site Status" postbox (Closes: #<I>)
|
Seravo_seravo-plugin
|
train
|
33ee41090e4d8802ce9c96a2cf837abbac761e55
|
diff --git a/pkg/api/serialization_test.go b/pkg/api/serialization_test.go
index <HASH>..<HASH> 100644
--- a/pkg/api/serialization_test.go
+++ b/pkg/api/serialization_test.go
@@ -91,7 +91,6 @@ func fuzzerFor(t *testing.T, version string, src rand.Source) *fuzz.Fuzzer {
j.Template = &api.PodTemplateSpec{}
}
j.Template.ObjectMeta = api.ObjectMeta{Labels: j.Template.ObjectMeta.Labels}
- j.Template.Spec.NodeSelector = nil
c.Fuzz(&j.Selector)
j.Replicas = int(c.RandUint64())
},
diff --git a/pkg/api/v1beta1/conversion.go b/pkg/api/v1beta1/conversion.go
index <HASH>..<HASH> 100644
--- a/pkg/api/v1beta1/conversion.go
+++ b/pkg/api/v1beta1/conversion.go
@@ -410,6 +410,9 @@ func init() {
return err
}
out.DesiredState.Host = in.Spec.Host
+ if err := s.Convert(&in.Spec.NodeSelector, &out.NodeSelector, 0); err != nil {
+ return err
+ }
if err := s.Convert(&in.ObjectMeta.Labels, &out.Labels, 0); err != nil {
return err
}
@@ -420,6 +423,9 @@ func init() {
return err
}
out.Spec.Host = in.DesiredState.Host
+ if err := s.Convert(&in.NodeSelector, &out.Spec.NodeSelector, 0); err != nil {
+ return err
+ }
if err := s.Convert(&in.Labels, &out.ObjectMeta.Labels, 0); err != nil {
return err
}
diff --git a/pkg/api/v1beta1/types.go b/pkg/api/v1beta1/types.go
index <HASH>..<HASH> 100644
--- a/pkg/api/v1beta1/types.go
+++ b/pkg/api/v1beta1/types.go
@@ -457,6 +457,7 @@ type ReplicationController struct {
// PodTemplate holds the information used for creating pods.
type PodTemplate struct {
DesiredState PodState `json:"desiredState,omitempty" description:"specification of the desired state of pods created from this template"`
+ NodeSelector map[string]string `json:"nodeSelector,omitempty" description:"a selector which must be true for the pod to fit on a node"`
Labels map[string]string `json:"labels,omitempty" description:"map of string keys and values that can be used to organize and categorize the pods created from the template; must match the selector of the replication controller to which the template belongs; may match selectors of services"`
}
diff --git a/pkg/api/v1beta2/conversion.go b/pkg/api/v1beta2/conversion.go
index <HASH>..<HASH> 100644
--- a/pkg/api/v1beta2/conversion.go
+++ b/pkg/api/v1beta2/conversion.go
@@ -274,6 +274,9 @@ func init() {
return err
}
out.DesiredState.Host = in.Spec.Host
+ if err := s.Convert(&in.Spec.NodeSelector, &out.NodeSelector, 0); err != nil {
+ return err
+ }
if err := s.Convert(&in.ObjectMeta.Labels, &out.Labels, 0); err != nil {
return err
}
@@ -284,6 +287,9 @@ func init() {
return err
}
out.Spec.Host = in.DesiredState.Host
+ if err := s.Convert(&in.NodeSelector, &out.Spec.NodeSelector, 0); err != nil {
+ return err
+ }
if err := s.Convert(&in.Labels, &out.ObjectMeta.Labels, 0); err != nil {
return err
}
diff --git a/pkg/api/v1beta2/types.go b/pkg/api/v1beta2/types.go
index <HASH>..<HASH> 100644
--- a/pkg/api/v1beta2/types.go
+++ b/pkg/api/v1beta2/types.go
@@ -420,6 +420,7 @@ type ReplicationController struct {
// PodTemplate holds the information used for creating pods.
type PodTemplate struct {
DesiredState PodState `json:"desiredState,omitempty" description:"specification of the desired state of pods created from this template"`
+ NodeSelector map[string]string `json:"nodeSelector,omitempty" description:"a selector which must be true for the pod to fit on a node"`
Labels map[string]string `json:"labels,omitempty" description:"map of string keys and values that can be used to organize and categorize the pods created from the template; must match the selector of the replication controller to which the template belongs; may match selectors of services"`
}
|
Add NodeSelector to the PodTemplate in v1beta1 and v1beta2
|
kubernetes_kubernetes
|
train
|
3c423f900edd74a460e7056b5fa347503312e3d7
|
diff --git a/packages/react-admin/src/mui/input/AutocompleteInput.js b/packages/react-admin/src/mui/input/AutocompleteInput.js
index <HASH>..<HASH> 100644
--- a/packages/react-admin/src/mui/input/AutocompleteInput.js
+++ b/packages/react-admin/src/mui/input/AutocompleteInput.js
@@ -122,12 +122,12 @@ export class AutocompleteInput extends React.Component {
}
if (choices !== this.props.choices) {
const selectedItem = this.getSelectedItem(nextProps);
- this.setState(({ dirty, searchText, suggestions }) => ({
+ this.setState(({ dirty, searchText }) => ({
selectedItem,
searchText: dirty
? searchText
: this.getSuggestionText(selectedItem),
- suggestions: dirty ? choices : suggestions,
+ suggestions: choices,
}));
}
}
|
Removed dirty checking on arrival of choices
|
marmelab_react-admin
|
train
|
d162f97d014239d0116882954d9b9670c3991135
|
diff --git a/lib/trello.rb b/lib/trello.rb
index <HASH>..<HASH> 100644
--- a/lib/trello.rb
+++ b/lib/trello.rb
@@ -51,8 +51,8 @@ module Trello
# Raise this when we hit a Trello error.
class Error < StandardError; end
- # This specific error is thrown when your access token has expired. Catch it, and start the process to get a new one.
- class ExpiredAccessToken < StandardError; end
+ # This specific error is thrown when your access token is invalid. You should get a new one.
+ class InvalidAccessToken < StandardError; end
def self.logger
@logger ||= Logger.new(STDOUT)
diff --git a/lib/trello/authorization.rb b/lib/trello/authorization.rb
index <HASH>..<HASH> 100644
--- a/lib/trello/authorization.rb
+++ b/lib/trello/authorization.rb
@@ -51,7 +51,7 @@ module Trello
def get_auth_header(url, verb)
require "oauth"
- self.token ||= OAuthCredential.new
+ raise InvalidAccessToken, 'No access token.' unless self.token
consumer = OAuth::Consumer.new(
consumer_credential.key,
diff --git a/lib/trello/client.rb b/lib/trello/client.rb
index <HASH>..<HASH> 100644
--- a/lib/trello/client.rb
+++ b/lib/trello/client.rb
@@ -32,7 +32,7 @@ module Trello
if response.code.to_i == 401 && response.body =~ /expired token/
Trello.logger.error("[401 #{name.to_s.upcase} #{uri}]: Your access token has expired.")
- raise ExpiredAccessToken
+ raise InvalidAccessToken, response.body
end
unless response.code.to_i == 200
|
throws an InvalidAccessToken exception when no token is present as well
|
jeremytregunna_ruby-trello
|
train
|
a3756a814fc630d787f8e498b8b8e78ce7adc0ed
|
diff --git a/js/kucoin.js b/js/kucoin.js
index <HASH>..<HASH> 100644
--- a/js/kucoin.js
+++ b/js/kucoin.js
@@ -185,6 +185,7 @@ module.exports = class kucoin extends Exchange {
'contracts/{symbol}',
'ticker',
'level2/snapshot',
+ 'level{level}',
'level{level}/depth{limit}',
'level2/depth20',
'level2/depth100',
@@ -1162,11 +1163,9 @@ module.exports = class kucoin extends Exchange {
'level': level,
};
const contract = market['contract'];
- if (contract && (limit === undefined)) {
- limit = 20; // Needs to be depth20 or depth100 for futures
- }
let method = 'privateGetMarketOrderbookLevelLevel';
if (level === 2) {
+ const errorMessageTail = contract ? '20 or 100' : 'undefined, 20 or 100';
if (limit !== undefined) {
if ((limit === 20) || (limit === 100)) {
request['limit'] = limit;
@@ -1175,11 +1174,13 @@ module.exports = class kucoin extends Exchange {
'kucoinfutures': 'futuresPublicGetLevelLevelDepthLimit',
});
} else {
- throw new ExchangeError (this.id + ' fetchOrderBook limit argument must be undefined, 20 or 100');
+ throw new BadRequest (this.id + ' fetchOrderBook limit argument must be ' + errorMessageTail);
}
+ } else if (contract) {
+ throw new BadRequest (this.id + ' fetchOrderBook limit argument must be ' + errorMessageTail);
}
} else if (contract) {
- throw new ExchangeError (this.id + ' fetchOrderBook only has order book level 2');
+ throw new BadRequest (this.id + ' fetchOrderBook level must be 2');
}
const response = await this[method] (this.extend (request, params));
// SPOT
@@ -1244,8 +1245,8 @@ module.exports = class kucoin extends Exchange {
// }
// }
const data = this.safeValue (response, 'data', {});
- const ts = Precise.stringDiv (this.safeString (data, 'ts'), '1000000');
- const timestamp = this.safeTimestamp (data, 'time', ts);
+ const ts = parseInt (Precise.stringDiv (this.safeString (data, 'ts'), '1000000'));
+ const timestamp = this.safeInteger (data, 'time', ts);
const orderbook = this.parseOrderBook (data, symbol, timestamp, 'bids', 'asks', level - 2, level - 1);
orderbook['nonce'] = this.safeInteger (data, 'sequence');
return orderbook;
diff --git a/js/kucoinfutures.js b/js/kucoinfutures.js
index <HASH>..<HASH> 100644
--- a/js/kucoinfutures.js
+++ b/js/kucoinfutures.js
@@ -5,6 +5,7 @@
const Exchange = require ('./base/Exchange');
const { ExchangeError, ExchangeNotAvailable, InsufficientFunds, OrderNotFound, InvalidOrder, AccountSuspended, InvalidNonce, NotSupported, BadRequest, AuthenticationError, BadSymbol, RateLimitExceeded, PermissionDenied } = require ('./base/errors');
const Precise = require ('./base/Precise');
+const kucoin = require ('./kucoin.js');
// ---------------------------------------------------------------------------
|
Fixed fetchOrderBook timestamp issue
|
ccxt_ccxt
|
train
|
2ebf8744c31c34eb819395da1c13f134a1008a4a
|
diff --git a/src/confluent_kafka/avro/__init__.py b/src/confluent_kafka/avro/__init__.py
index <HASH>..<HASH> 100644
--- a/src/confluent_kafka/avro/__init__.py
+++ b/src/confluent_kafka/avro/__init__.py
@@ -44,7 +44,7 @@ class AvroProducer(Producer):
"""
def __init__(self, config, default_key_schema=None,
- default_value_schema=None, schema_registry=None):
+ default_value_schema=None, schema_registry=None, **kwargs):
sr_conf = {key.replace("schema.registry.", ""): value
for key, value in config.items() if key.startswith("schema.registry")}
@@ -64,7 +64,7 @@ class AvroProducer(Producer):
elif sr_conf.get("url", None) is not None:
raise ValueError("Cannot pass schema_registry along with schema.registry.url config")
- super(AvroProducer, self).__init__(ap_conf)
+ super(AvroProducer, self).__init__(ap_conf, **kwargs)
self._serializer = MessageSerializer(schema_registry)
self._key_schema = default_key_schema
self._value_schema = default_value_schema
@@ -123,7 +123,7 @@ class AvroConsumer(Consumer):
:raises ValueError: For invalid configurations
"""
- def __init__(self, config, schema_registry=None, reader_key_schema=None, reader_value_schema=None):
+ def __init__(self, config, schema_registry=None, reader_key_schema=None, reader_value_schema=None, **kwargs):
sr_conf = {key.replace("schema.registry.", ""): value
for key, value in config.items() if key.startswith("schema.registry")}
@@ -142,7 +142,7 @@ class AvroConsumer(Consumer):
elif sr_conf.get("url", None) is not None:
raise ValueError("Cannot pass schema_registry along with schema.registry.url config")
- super(AvroConsumer, self).__init__(ap_conf)
+ super(AvroConsumer, self).__init__(ap_conf, **kwargs)
self._serializer = MessageSerializer(schema_registry, reader_key_schema, reader_value_schema)
def poll(self, timeout=None):
diff --git a/tests/test_log.py b/tests/test_log.py
index <HASH>..<HASH> 100644
--- a/tests/test_log.py
+++ b/tests/test_log.py
@@ -1,6 +1,7 @@
#!/usr/bin/env python
import confluent_kafka
+import confluent_kafka.avro
import logging
@@ -34,6 +35,26 @@ def test_logging_consumer():
kc.close()
+def test_logging_avro_consumer():
+ """ Tests that logging works """
+
+ logger = logging.getLogger('avroconsumer')
+ logger.setLevel(logging.DEBUG)
+ f = CountingFilter('avroconsumer')
+ logger.addFilter(f)
+
+ kc = confluent_kafka.avro.AvroConsumer({'schema.registry.url': 'http://example.com',
+ 'group.id': 'test',
+ 'debug': 'all'},
+ logger=logger)
+ while f.cnt == 0:
+ kc.poll(timeout=0.5)
+
+ print('%s: %d log messages seen' % (f.name, f.cnt))
+
+ kc.close()
+
+
def test_logging_producer():
""" Tests that logging works """
@@ -50,6 +71,24 @@ def test_logging_producer():
print('%s: %d log messages seen' % (f.name, f.cnt))
+def test_logging_avro_producer():
+ """ Tests that logging works """
+
+ logger = logging.getLogger('avroproducer')
+ logger.setLevel(logging.DEBUG)
+ f = CountingFilter('avroproducer')
+ logger.addFilter(f)
+
+ p = confluent_kafka.avro.AvroProducer({'schema.registry.url': 'http://example.com',
+ 'debug': 'all'},
+ logger=logger)
+
+ while f.cnt == 0:
+ p.poll(timeout=0.5)
+
+ print('%s: %d log messages seen' % (f.name, f.cnt))
+
+
def test_logging_constructor():
""" Verify different forms of constructors """
|
Added logging parameter for Avro(Consumer|Producer).
The patch introduces **kwargs and just passes them to the underlying
super calls.
Tests are included.
Closes: #<I>
|
confluentinc_confluent-kafka-python
|
train
|
76717c3a6c3bd4af303e934453df1dc18cf5d027
|
diff --git a/libstempo/toasim.py b/libstempo/toasim.py
index <HASH>..<HASH> 100644
--- a/libstempo/toasim.py
+++ b/libstempo/toasim.py
@@ -537,8 +537,16 @@ def add_ecc_cgw(psr, gwtheta, gwphi, mc, dist, F, inc, psi, gamma0,
omhat = N.array([-singwtheta*cosgwphi, -singwtheta*singwphi, -cosgwtheta])
# pulsar location
- ptheta = N.pi/2 - psr['DECJ'].val
- pphi = psr['RAJ'].val
+ if 'RAJ' and 'DECJ' in psr.pars():
+ ptheta = N.pi/2 - psr['DECJ'].val
+ pphi = psr['RAJ'].val
+ elif 'ELONG' and 'ELAT' in psr.pars():
+ fac = 180./N.pi
+ coords = ephem.Equatorial(ephem.Ecliptic(str(psr['ELONG'].val*fac), str(psr['ELAT'].val*fac)))
+
+ ptheta = N.pi/2 - float(repr(coords.dec))
+ pphi = float(repr(coords.ra))
+
# use definition from Sesana et al 2010 and Ellis et al 2012
phat = N.array([N.sin(ptheta)*N.cos(pphi), N.sin(ptheta)*N.sin(pphi),\
@@ -550,12 +558,6 @@ def add_ecc_cgw(psr, gwtheta, gwphi, mc, dist, F, inc, psi, gamma0,
# get values from pulsar object
toas = N.double(psr.toas())*86400 - tref
-
- # convert units
- pd *= eu.KPC2S # convert from kpc to seconds
-
- # get pulsar time
- tp = toas - pd * (1-cosMu)
if check:
# check that frequency is not evolving significantly over obs. time
@@ -596,6 +598,12 @@ def add_ecc_cgw(psr, gwtheta, gwphi, mc, dist, F, inc, psi, gamma0,
##### pulsar term #####
if psrTerm:
+ # convert units
+ pd *= eu.KPC2S # convert from kpc to seconds
+
+ # get pulsar time
+ tp = toas - pd * (1-cosMu)
+
# solve coupled system of equations to get pulsar term values
y = eu.solve_coupled_ecc_solution(F, e0, gamma0, l0, mc, q,
N.array([0.0, tp.min()]))
|
some minor edits to eccentricity injection code
|
vallis_libstempo
|
train
|
22073e33760fdf628d5a742ce7e71cd3b670053d
|
diff --git a/app/config/core.php b/app/config/core.php
index <HASH>..<HASH> 100644
--- a/app/config/core.php
+++ b/app/config/core.php
@@ -200,7 +200,7 @@
/**
* A random numeric string (digits only) used to encrypt/decrypt strings.
*/
- Configure::write('Security.cipher_seed', '76859309657453542496749683645');
+ Configure::write('Security.cipherSeed', '76859309657453542496749683645');
/**
* Apply timestamps with the last modified time to static assets (js, css, images).
diff --git a/cake/console/templates/skel/config/core.php b/cake/console/templates/skel/config/core.php
index <HASH>..<HASH> 100644
--- a/cake/console/templates/skel/config/core.php
+++ b/cake/console/templates/skel/config/core.php
@@ -209,7 +209,7 @@
/**
* A random numeric string (digits only) used to encrypt/decrypt strings.
*/
- Configure::write('Security.cipher_seed', '76859309657453542496749683645');
+ Configure::write('Security.cipherSeed', '76859309657453542496749683645');
/**
* Compress CSS output by removing comments, whitespace, repeating tags, etc.
diff --git a/cake/libs/debugger.php b/cake/libs/debugger.php
index <HASH>..<HASH> 100644
--- a/cake/libs/debugger.php
+++ b/cake/libs/debugger.php
@@ -674,8 +674,8 @@ class Debugger extends Object {
trigger_error(__('Please change the value of \'Security.salt\' in app/config/core.php to a salt value specific to your application', true), E_USER_NOTICE);
}
- if (Configure::read('Security.cipher_seed') == '76859309657453542496749683645') {
- trigger_error(__('Please change the value of \'Security.cipher_seed\' in app/config/core.php to a numeric (digits only) seed value specific to your application', true), E_USER_NOTICE);
+ if (Configure::read('Security.cipherSeed') == '76859309657453542496749683645') {
+ trigger_error(__('Please change the value of \'Security.cipherSeed\' in app/config/core.php to a numeric (digits only) seed value specific to your application', true), E_USER_NOTICE);
}
}
diff --git a/cake/libs/security.php b/cake/libs/security.php
index <HASH>..<HASH> 100644
--- a/cake/libs/security.php
+++ b/cake/libs/security.php
@@ -174,7 +174,7 @@ class Security extends Object {
return '';
}
- srand(Configure::read('Security.cipher_seed'));
+ srand(Configure::read('Security.cipherSeed'));
$out = '';
for ($i = 0; $i < strlen($text); $i++) {
@@ -184,6 +184,8 @@ class Security extends Object {
$mask = rand(0, 255);
$out .= chr(ord(substr($text, $i, 1)) ^ $mask);
}
+
+ srand();
return $out;
}
}
|
Renaming Configure var 'Security.cipher_seed' to 'Security.cipherSeed'. Also added a srand() call at end of Security::cipher function to reset seed. Closes #<I> , #<I> , #<I>
|
cakephp_cakephp
|
train
|
dbe8c7f5c1ed29ed5a8d5cdd65d0a32874b148de
|
diff --git a/nexusdialog/src/main/java/com/github/dkharrat/nexusdialog/FormController.java b/nexusdialog/src/main/java/com/github/dkharrat/nexusdialog/FormController.java
index <HASH>..<HASH> 100644
--- a/nexusdialog/src/main/java/com/github/dkharrat/nexusdialog/FormController.java
+++ b/nexusdialog/src/main/java/com/github/dkharrat/nexusdialog/FormController.java
@@ -180,6 +180,11 @@ public class FormController {
validationErrorDisplay.showErrors();
}
+ /**
+ * Change the display method for validation errors
+ *
+ * @param method the method to use.
+ */
public void setValidationErrorsDisplayMethod(ValidationErrorDisplayMethod method) {
method.setContext(context);
method.setController(this);
diff --git a/nexusdialog/src/main/java/com/github/dkharrat/nexusdialog/FormElementController.java b/nexusdialog/src/main/java/com/github/dkharrat/nexusdialog/FormElementController.java
index <HASH>..<HASH> 100644
--- a/nexusdialog/src/main/java/com/github/dkharrat/nexusdialog/FormElementController.java
+++ b/nexusdialog/src/main/java/com/github/dkharrat/nexusdialog/FormElementController.java
@@ -88,5 +88,10 @@ public abstract class FormElementController {
*/
public abstract void refresh();
+ /**
+ * Display an error message on the element.
+ *
+ * @param message The message to display.
+ */
public abstract void setError(String message);
-}
\ No newline at end of file
+}
diff --git a/nexusdialog/src/main/java/com/github/dkharrat/nexusdialog/validations/RequiredField.java b/nexusdialog/src/main/java/com/github/dkharrat/nexusdialog/validations/RequiredField.java
index <HASH>..<HASH> 100644
--- a/nexusdialog/src/main/java/com/github/dkharrat/nexusdialog/validations/RequiredField.java
+++ b/nexusdialog/src/main/java/com/github/dkharrat/nexusdialog/validations/RequiredField.java
@@ -12,6 +12,7 @@ public class RequiredField extends ValidationError {
* Creates a new instance with the specified field name.
*
* @param fieldName the field name
+ * @param fieldLabel the field label
*/
public RequiredField(String fieldName, String fieldLabel) {
super(fieldName, fieldLabel);
diff --git a/nexusdialog/src/main/java/com/github/dkharrat/nexusdialog/validations/ValidationError.java b/nexusdialog/src/main/java/com/github/dkharrat/nexusdialog/validations/ValidationError.java
index <HASH>..<HASH> 100644
--- a/nexusdialog/src/main/java/com/github/dkharrat/nexusdialog/validations/ValidationError.java
+++ b/nexusdialog/src/main/java/com/github/dkharrat/nexusdialog/validations/ValidationError.java
@@ -13,6 +13,7 @@ public abstract class ValidationError {
* Creates a new instance with the specified field name.
*
* @param fieldName the field name
+ * @param fieldLabel the field label
*/
public ValidationError(String fieldName, String fieldLabel) {
this.fieldName = fieldName;
diff --git a/nexusdialog/src/main/java/com/github/dkharrat/nexusdialog/validations/ValidationErrorDisplayMethod.java b/nexusdialog/src/main/java/com/github/dkharrat/nexusdialog/validations/ValidationErrorDisplayMethod.java
index <HASH>..<HASH> 100644
--- a/nexusdialog/src/main/java/com/github/dkharrat/nexusdialog/validations/ValidationErrorDisplayMethod.java
+++ b/nexusdialog/src/main/java/com/github/dkharrat/nexusdialog/validations/ValidationErrorDisplayMethod.java
@@ -8,6 +8,11 @@ import com.github.dkharrat.nexusdialog.FormElementController;
import com.github.dkharrat.nexusdialog.R;
import com.github.dkharrat.nexusdialog.utils.MessageUtil;
+/**
+ * Defines methods to display the validation errors.
+ * You MUST set the {@link ValidationErrorDisplayMethod#context} and {@link ValidationErrorDisplayMethod#controller}
+ * before calling showErrors.
+ */
public enum ValidationErrorDisplayMethod {
GENERAL {
@Override
@@ -41,5 +46,8 @@ public enum ValidationErrorDisplayMethod {
protected Context context;
protected FormController controller;
+ /**
+ * Display the validation errors using the selected method.
+ */
public abstract void showErrors();
}
|
doc: add documentation on new classes and methods
|
dkharrat_NexusDialog
|
train
|
692897b7d5575d81232cb5c1bf21adfb2e7983a1
|
diff --git a/src/phonetics/daitch-mokotoff.js b/src/phonetics/daitch-mokotoff.js
index <HASH>..<HASH> 100644
--- a/src/phonetics/daitch-mokotoff.js
+++ b/src/phonetics/daitch-mokotoff.js
@@ -7,14 +7,17 @@
* [Reference]:
* https://en.wikipedia.org/wiki/Daitch%E2%80%93Mokotoff_Soundex
*/
+import deburr from 'lodash/deburr';
/**
* Rules.
+ *
+ * [Note]:
+ * For the (RS|RZ) part, the original algo says (94, 4) but most
+ * implementations drop it to only (94).
*/
// TODO: optimize to cut O(n * m)
-// TODO: check the rules apply order
-// TODO: add some deburr
const RULES = [
[/^(AI|AJ|AY)/, 0, 1, null],
[/^AU/, 0, 7, null],
@@ -24,9 +27,9 @@ const RULES = [
[/^CHS/, 5, 54, 54],
[/^CH/, [5, 4], [5, 4], [5, 4]],
[/^CK/, [5, 45], [5, 45], [5, 45]],
- [/^(CZ|CS|CSZ|CZS)/, 4, 4, 4],
+ [/^(CSZ|CZS|CZ|CS)/, 4, 4, 4],
[/^C/, [5, 4], [5, 4], [5, 4]],
- [/^(DRZ|DRS|DS|DSH|DSZ|DZ|DZH|DZS)/, 4, 4, 4],
+ [/^(DRZ|DRS|DSH|DSZ|DZH|DZS|DS|DZ)/, 4, 4, 4],
[/^(DT|D)/, 3, 3, 3],
[/^(EI|EJ|EY)/, 0, 1, null],
[/^EU/, 1, 1, null],
@@ -47,8 +50,6 @@ const RULES = [
[/^O/, 0, null, null],
[/^(PF|PH|P)/, 7, 7, 7],
[/^Q/, 5, 5, 5],
-
- // NOTE: the original algo says (94, 4) but most implementations only 94
[/^(RZ|RS)/, [94, 4], [94, 4], [94, 4]],
[/^R/, 9, 9, 9],
[/^(SCHTSCH|SCHTSH|SCHTCH|SHTCH|SHCH|SHTSH)/, 2, 4, 4],
@@ -126,7 +127,7 @@ export default function daitchMokotoff(name) {
const code = [];
- let current = name
+ let current = deburr(name)
.toUpperCase()
.replace(/[^A-ZĄĘŢ]/g, '');
|
Cleaning up daitch-mokotoff
|
Yomguithereal_talisman
|
train
|
b13733dbd15436cbc4401f89d402d7bb5735c3ef
|
diff --git a/src/main/java/org/perfidix/element/BenchmarkElement.java b/src/main/java/org/perfidix/element/BenchmarkElement.java
index <HASH>..<HASH> 100644
--- a/src/main/java/org/perfidix/element/BenchmarkElement.java
+++ b/src/main/java/org/perfidix/element/BenchmarkElement.java
@@ -451,6 +451,35 @@ public final class BenchmarkElement {
}
/**
+ * Getting the number of runs corresponding to a given method. The method
+ * MUST be a benchmarkable method, otherwise an IllegalStateException
+ * exception arises. The number of runs of an annotated method is more
+ * powerful than the number of runs as denoted by the benchclass annotation.
+ *
+ * @return the number of runs of this benchmarkable-method
+ * @throws IllegalStateException
+ * if the given method is not benchmarkable.
+ */
+ public final int getNumberOfRuns() throws IllegalStateException {
+ if (checkThisMethodAsBenchmarkable()) {
+ final Bench benchAnno =
+ getMethodToBench().getAnnotation(Bench.class);
+ final BenchClass benchClassAnno =
+ getMethodToBench().getDeclaringClass().getAnnotation(
+ BenchClass.class);
+ if (benchAnno != null) {
+ return benchAnno.runs();
+ } else {
+ return benchClassAnno.runs();
+ }
+ } else {
+ throw new IllegalStateException(new StringBuilder("Method ")
+ .append(this.methodToBench.toString()).append(
+ " is actually not benchmarkable!").toString());
+ }
+ }
+
+ /**
* Simple getter for encapsulated method.
*
* @return the methodToBench
diff --git a/src/test/java/org/perfidix/AnnotationRunsTest.java b/src/test/java/org/perfidix/AnnotationRunsTest.java
index <HASH>..<HASH> 100644
--- a/src/test/java/org/perfidix/AnnotationRunsTest.java
+++ b/src/test/java/org/perfidix/AnnotationRunsTest.java
@@ -22,6 +22,7 @@ package org.perfidix;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
+import org.perfidix.Benchmark;
import org.perfidix.annotation.Bench;
import org.perfidix.annotation.BenchClass;
diff --git a/src/test/java/org/perfidix/element/BenchmarkElementTest.java b/src/test/java/org/perfidix/element/BenchmarkElementTest.java
index <HASH>..<HASH> 100644
--- a/src/test/java/org/perfidix/element/BenchmarkElementTest.java
+++ b/src/test/java/org/perfidix/element/BenchmarkElementTest.java
@@ -21,6 +21,7 @@
package org.perfidix.element;
import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.lang.annotation.ElementType;
@@ -37,6 +38,7 @@ import org.perfidix.annotation.AfterLastRun;
import org.perfidix.annotation.BeforeEachRun;
import org.perfidix.annotation.BeforeFirstRun;
import org.perfidix.annotation.Bench;
+import org.perfidix.annotation.BenchClass;
import org.perfidix.annotation.SkipBench;
/**
@@ -442,6 +444,55 @@ public class BenchmarkElementTest {
}
}
+ /**
+ * Test method for
+ * {@link org.perfidix.element.BenchmarkElement#getNumberOfRuns()}.
+ */
+ @Test
+ public void testRuns1() {
+ try {
+ currentClassToTest = new TestRuns();
+ final Method[] meths =
+ currentClassToTest.getClass().getDeclaredMethods();
+ BenchmarkElement elem = null;
+ for (final Method meth : meths) {
+ elem = new BenchmarkElement(meth);
+ if (meth.getName().equals("bench1")) {
+ assertEquals(10, elem.getNumberOfRuns());
+ } else if (meth.getName().equals("bench2")) {
+ assertEquals(20, elem.getNumberOfRuns());
+ } else if (meth.getName().equals("bench3")) {
+ try {
+ elem.getNumberOfRuns();
+ fail("Must throw IllegalStateException!");
+ } catch (IllegalStateException e) {
+ assertTrue(e.getMessage().startsWith("Method"));
+ }
+ } else {
+ fail("Should never occur!");
+ }
+ }
+ } catch (Exception e) {
+ fail("Should never fail in testRuns!");
+ }
+ }
+
+ @BenchClass(runs = 20)
+ class TestRuns {
+
+ @Bench(runs = 10)
+ public void bench1() {
+ }
+
+ public void bench2() {
+ }
+
+ public int bench3() {
+ return -1;
+ }
+
+ }
+
class TestAfterLastRun2 {
@AfterLastRun
|
added #runs in BenchmarkElement-class
|
sebastiangraf_perfidix
|
train
|
a2774014b6d23a0440edf8b669f378a48d71d715
|
diff --git a/driver-core/src/main/com/mongodb/operation/ListDatabasesOperation.java b/driver-core/src/main/com/mongodb/operation/ListDatabasesOperation.java
index <HASH>..<HASH> 100644
--- a/driver-core/src/main/com/mongodb/operation/ListDatabasesOperation.java
+++ b/driver-core/src/main/com/mongodb/operation/ListDatabasesOperation.java
@@ -172,7 +172,7 @@ public class ListDatabasesOperation<T> implements AsyncReadOperation<AsyncBatchC
} else {
executeWrappedCommandProtocolAsync(binding, "admin", getCommand(),
CommandResultDocumentCodec.create(decoder, "databases"), connection, asyncTransformer(source, connection),
- releasingCallback(errHandlingCallback, connection));
+ releasingCallback(errHandlingCallback, source, connection));
}
}
});
|
JAVA-<I>: Release AsyncConnectionSource in ListDatabasesOperation
|
mongodb_mongo-java-driver
|
train
|
1e29d6216610afc5da27c981b75b3bdc74a5d2b6
|
diff --git a/trunk/JLanguageTool/website/www/usage/index.php b/trunk/JLanguageTool/website/www/usage/index.php
index <HASH>..<HASH> 100644
--- a/trunk/JLanguageTool/website/www/usage/index.php
+++ b/trunk/JLanguageTool/website/www/usage/index.php
@@ -2,7 +2,7 @@
$page = "usage";
$title = "LanguageTool";
$title2 = "Usage";
-$lastmod = "2011-08-07 16:20:00 CET";
+$lastmod = "2012-01-03 20:20:00 CET";
include("../../include/header.php");
include('../../include/geshi/geshi.php');
?>
@@ -15,8 +15,7 @@ with OpenOffice.org.</p>
<ul class="largelist">
<li><strong>As a stand-alone application</strong>:
- Rename the *.oxt file so it ends with ".zip" and unzip it. If you're
- using Java 6.0, also unzip the <tt>standalone-libs.zip</tt> that will be created.
+ Rename the *.oxt file so it ends with ".zip" and unzip it.
Then start <tt>LanguageToolGUI.jar</tt> by double clicking on it. If your computer isn't
configured to start jar archives, start it from the command line using<br />
<tt>java -jar LanguageToolGUI.jar</tt><br />
|
remove outdated information about standalone-libs.zip
|
languagetool-org_languagetool
|
train
|
5b5a31e49e0826856beac570b1b0a7d8469eddd9
|
diff --git a/client/lib/post-normalizer/rule-content-make-images-safe.js b/client/lib/post-normalizer/rule-content-make-images-safe.js
index <HASH>..<HASH> 100644
--- a/client/lib/post-normalizer/rule-content-make-images-safe.js
+++ b/client/lib/post-normalizer/rule-content-make-images-safe.js
@@ -60,7 +60,7 @@ function isCandidateForContentImage( imageUrl ) {
} );
}
-export default function( maxWidth ) {
+export default function( maxWidth = false ) {
return function makeImagesSafe( post, dom ) {
let content_images = [],
images;
diff --git a/client/state/reader/posts/normalization-rules.js b/client/state/reader/posts/normalization-rules.js
index <HASH>..<HASH> 100644
--- a/client/state/reader/posts/normalization-rules.js
+++ b/client/state/reader/posts/normalization-rules.js
@@ -156,7 +156,7 @@ const fastPostNormalizationRules = flow( [
withContentDom( [
removeStyles,
removeElementsBySelector,
- makeImagesSafe( READER_CONTENT_WIDTH ),
+ makeImagesSafe(),
discoverFullBleedImages,
makeEmbedsSafe,
disableAutoPlayOnEmbeds,
|
Reader: Stop resizing images in content (#<I>)
This was a misguided attempt to get bigger images for features, from a long time ago.
Sadly, it breaks things that use photon or the wp image api to make images a specific size.
We'll revisit this later if necessary.
|
Automattic_wp-calypso
|
train
|
38f3583e25f92a29b860993c72fb7c5b1121b636
|
diff --git a/skosprovider/skos.py b/skosprovider/skos.py
index <HASH>..<HASH> 100644
--- a/skosprovider/skos.py
+++ b/skosprovider/skos.py
@@ -124,7 +124,12 @@ class Note:
def __init__(self, note, type="note", language="und", markup=None):
self.note = note
self.type = type
- self.language = language
+ if not language:
+ language = 'und'
+ if tags.check(language):
+ self.language = language
+ else:
+ raise ValueError('%s is not a valid IANA language tag.' % language)
self.markup = markup
def __eq__(self, other):
diff --git a/tests/test_skos.py b/tests/test_skos.py
index <HASH>..<HASH> 100644
--- a/tests/test_skos.py
+++ b/tests/test_skos.py
@@ -89,6 +89,20 @@ class NoteTest(unittest.TestCase):
self.assertEqual('note', n.type)
self.assertEqual('nl-BE', n.language)
+ def testConstructorInvalidLanguage(self):
+ with self.assertRaises(ValueError):
+ n = Note(
+ 'Een gemeente in West-Vlaanderen.',
+ type="note",
+ language='nederlands'
+ )
+ n = Note(
+ 'Een gemeente in West-Vlaanderen.',
+ type="note",
+ language=None
+ )
+ assert n.language == 'und'
+
def testEquality(self):
n1 = Note('A note.')
n2 = Note('A note.', 'note', 'und')
|
Note is more strict in handling languages.
|
koenedaele_skosprovider
|
train
|
97236cfe60a8b4cffac3dd7a0462442771597de9
|
diff --git a/lib/couchbase/view_row.rb b/lib/couchbase/view_row.rb
index <HASH>..<HASH> 100644
--- a/lib/couchbase/view_row.rb
+++ b/lib/couchbase/view_row.rb
@@ -26,12 +26,20 @@ module Couchbase
module Java::ComCouchbaseClientProtocolViews::ViewRow
def doc
- {
- 'meta' => {
- 'id' => self['id']
- },
- 'value' => document
- }
+ if self.is_a? ViewRowNoDocs
+ {
+ id: getId,
+ key: getKey,
+ value: getValue
+ }
+ else
+ {
+ 'meta' => {
+ 'id' => self['id']
+ },
+ 'value' => document
+ }
+ end
end
def [](key)
|
Ensure we don't fetch docs from views when asked not to
|
mje113_couchbase-jruby-client
|
train
|
9556a028ce816938f82ae1f8276a10d89c5daae1
|
diff --git a/server/kiwi.js b/server/kiwi.js
index <HASH>..<HASH> 100755
--- a/server/kiwi.js
+++ b/server/kiwi.js
@@ -5,6 +5,7 @@ var fs = require('fs'),
config = require('./configuration.js'),
modules = require('./modules.js'),
Identd = require('./identd.js'),
+ Proxy = require('./proxy.js'),
ControlInterface = require('./controlinterface.js');
@@ -229,26 +230,49 @@ if (global.config.identd && global.config.identd.enabled) {
// Start up a weblistener for each found in the config
_.each(global.config.servers, function (server) {
- var wl = new WebListener(server, global.config.transports);
+ if (server.type == 'proxy') {
+ // Start up a kiwi proxy server
+ var serv = new Proxy.ProxyServer();
+ serv.listen(server.port, server.address);
+
+ serv.on('listening', function() {
+ console.log('Kiwi proxy listening on %s:%s %s SSL', server.address, server.port, (server.ssl ? 'with' : 'without'));
+ });
+
+ serv.on('connection_open', function(pipe) {
+ pipe.identd_pair = pipe.irc_socket.localPort.toString() + '_' + pipe.irc_socket.remotePort.toString();
+ console.log('[IDENTD] opened ' + pipe.identd_pair);
+ global.clients.port_pairs[pipe.identd_pair] = pipe.meta;
+ });
+
+ serv.on('connection_close', function(pipe) {
+ console.log('[IDENTD] closed ' + pipe.identd_pair);
+ delete global.clients.port_pairs[pipe.identd_pair];
+ });
- wl.on('connection', function (client) {
- clients.add(client);
- });
-
- wl.on('client_dispose', function (client) {
- clients.remove(client);
- });
-
- wl.on('listening', function () {
- console.log('Listening on %s:%s %s SSL', server.address, server.port, (server.ssl ? 'with' : 'without'));
- webListenerRunning();
- });
-
- wl.on('error', function (err) {
- console.log('Error listening on %s:%s: %s', server.address, server.port, err.code);
- // TODO: This should probably be refactored. ^JA
- webListenerRunning();
- });
+ } else {
+ // Start up a kiwi web server
+ var wl = new WebListener(server, global.config.transports);
+
+ wl.on('connection', function (client) {
+ clients.add(client);
+ });
+
+ wl.on('client_dispose', function (client) {
+ clients.remove(client);
+ });
+
+ wl.on('listening', function () {
+ console.log('Listening on %s:%s %s SSL', server.address, server.port, (server.ssl ? 'with' : 'without'));
+ webListenerRunning();
+ });
+
+ wl.on('error', function (err) {
+ console.log('Error listening on %s:%s: %s', server.address, server.port, err.code);
+ // TODO: This should probably be refactored. ^JA
+ webListenerRunning();
+ });
+ }
});
// Once all the listeners are listening, set the processes UID/GID
diff --git a/server/proxy.js b/server/proxy.js
index <HASH>..<HASH> 100644
--- a/server/proxy.js
+++ b/server/proxy.js
@@ -11,7 +11,7 @@ module.exports = {
};
function debug() {
- console.log.apply(console, arguments);
+ //console.log.apply(console, arguments);
}
// Socket connection responses
@@ -40,7 +40,9 @@ ProxyServer.prototype.listen = function(listen_port, listen_addr) {
// Start listening for proxy connections connections
this.server = new net.Server();
- this.server.listen(listen_port, listen_addr);
+ this.server.listen(listen_port, listen_addr, function() {
+ that.emit('listening');
+ });
this.server.on('connection', function(socket) {
new ProxyPipe(socket, that);
|
Proxy server type in config file
|
prawnsalad_KiwiIRC
|
train
|
45dd6474d2b281031f2f5765f04b515df14266b0
|
diff --git a/src/main/java/de/thetaphi/forbiddenapis/gradle/GradleTask.java b/src/main/java/de/thetaphi/forbiddenapis/gradle/GradleTask.java
index <HASH>..<HASH> 100644
--- a/src/main/java/de/thetaphi/forbiddenapis/gradle/GradleTask.java
+++ b/src/main/java/de/thetaphi/forbiddenapis/gradle/GradleTask.java
@@ -143,18 +143,6 @@ public class GradleTask extends DefaultTask {
public boolean failOnViolation = true;
/**
- * The default compiler target version used to expand references to bundled JDK signatures.
- * E.g., if you use "jdk-deprecated", it will expand to this version.
- * This setting should be identical to the target version used in the compiler plugin.
- * <p>
- * If undefined, it is taken from the project property {@code targetCompatibility}.
- * @since 1.0
- */
- @Optional
- @Input
- public JavaVersion targetVersion = null;
-
- /**
* List of patterns matching all class files to be parsed from the classesDirectory.
* Can be changed to e.g. exclude several files (using excludes).
* The default is a single include with pattern '**/*.class'
@@ -188,13 +176,12 @@ public class GradleTask extends DefaultTask {
@Input
public List<String> suppressAnnotations;
- private JavaVersion getTargetVersion() {
- return (targetVersion != null) ?
- targetVersion : (JavaVersion) getProject().property("targetCompatibility");
- }
-
@TaskAction
public void checkForbidden() {
+ if (classesDir == null || classpath == null) {
+ throw new InvalidUserDataException("Missing 'classesDir' or 'classpath' property.");
+ }
+
final Logger log = new Logger() {
public void error(String msg) {
getLogger().error(msg);
@@ -283,9 +270,9 @@ public class GradleTask extends DefaultTask {
checker.parseSignaturesString(sb.toString());
}
if (bundledSignatures != null) {
- JavaVersion targetVersion = getTargetVersion();
+ final JavaVersion targetVersion = (JavaVersion) getProject().property("targetCompatibility");
if (targetVersion == null) {
- log.warn("The 'targetVersion' parameter or 'targetCompatibility' project property is missing. " +
+ log.warn("The 'targetCompatibility' project property is missing. " +
"Trying to read bundled JDK signatures without compiler target. " +
"You have to explicitely specify the version in the resource name.");
}
|
Remove targetVersion property. Gradle does not allow to set it on compileJava tasks, so we also don't allow it.
|
policeman-tools_forbidden-apis
|
train
|
fc067f51acf2ed7af325eb0726d9fcef746e410b
|
diff --git a/pgmpy/factors/discrete/CPD.py b/pgmpy/factors/discrete/CPD.py
index <HASH>..<HASH> 100644
--- a/pgmpy/factors/discrete/CPD.py
+++ b/pgmpy/factors/discrete/CPD.py
@@ -258,7 +258,7 @@ class TabularCPD(DiscreteFactor):
self.get_values(),
evidence,
evidence_card,
- state_names=self.state_names,
+ state_names=self.state_names.copy(),
)
def normalize(self, inplace=True):
diff --git a/pgmpy/tests/test_factors/test_discrete/test_Factor.py b/pgmpy/tests/test_factors/test_discrete/test_Factor.py
index <HASH>..<HASH> 100644
--- a/pgmpy/tests/test_factors/test_discrete/test_Factor.py
+++ b/pgmpy/tests/test_factors/test_discrete/test_Factor.py
@@ -1150,6 +1150,10 @@ class TestTabularCPDMethods(unittest.TestCase):
def test_copy_state_names(self):
copy_cpd = self.cpd.copy()
self.assertEqual(self.cpd.state_names, copy_cpd.state_names)
+ copy_cpd.state_names.clear()
+ self.assertNotEqual(self.cpd.state_names, copy_cpd.state_names)
+ self.assertFalse(copy_cpd.state_names)
+ self.assertTrue(self.cpd.state_names)
def test_reduce_1(self):
self.cpd.reduce([("diff", "low")])
|
Fix for Tabular CPD copy() function (#<I>)
Fixes copy method of TabularCPD:
1. TabularCPD.copy didn't use to make a copy of state_names which results in a change in the copied cpd's state names if there's any change in original.
2. Adds tests for the same.
|
pgmpy_pgmpy
|
train
|
2568ffb391149d8457d75594d6ad3fff878e7d39
|
diff --git a/lib/requester/requester.js b/lib/requester/requester.js
index <HASH>..<HASH> 100644
--- a/lib/requester/requester.js
+++ b/lib/requester/requester.js
@@ -295,7 +295,12 @@ _.assign(Requester.prototype, /** @lends Requester.prototype */ {
onStart = function (response) {
var responseStartEventName = RESPONSE_START_EVENT_BASE + id,
sdkResponse,
- history;
+ history,
+ done = function () {
+ // emit the response.start event which eventually
+ // triggers responseStart callback
+ self.emit(responseStartEventName, null, sdkResponse, request, cookies, history);
+ };
// @todo get rid of jsonifyResponse
responseJSON = core.jsonifyResponse(response, requestOptions);
@@ -313,18 +318,27 @@ _.assign(Requester.prototype, /** @lends Requester.prototype */ {
// add missing request headers so that they get bubbled up into the UI
addMissingRequestHeaders(responseJSON.request && responseJSON.request.headers);
- // Pull out cookies from the cookie jar, and make them chrome compatible.
- cookies = (cookieJar && _.isFunction(cookieJar.getCookies)) ?
- _.transform(cookieJar.getCookies(requestOptions.url), function (acc, cookie) {
- acc.push(toChromeCookie(cookie));
- }, []) : [];
-
// prepare history from request debug data
history = getExecutionHistory(_.get(response, 'request._debug'));
- // finally, emit the response.start event which eventually
- // triggers responseStart callback
- self.emit(responseStartEventName, null, sdkResponse, request, cookies, history);
+ // Pull out cookies from the cookie jar, and make them chrome compatible.
+ if (cookieJar && _.isFunction(cookieJar.getCookies)) {
+ cookieJar.getCookies(requestOptions.url, function (err, cookiesFromJar) {
+ if (err) {
+ return done();
+ }
+
+ cookies = _.transform(cookiesFromJar, function (acc, cookie) {
+ acc.push(toChromeCookie(cookie));
+ }, []);
+
+ done();
+ });
+ }
+ else {
+ cookies = [];
+ done();
+ }
};
// at this point the request could have come from collection, auth or sandbox
diff --git a/lib/runner/extensions/event.command.js b/lib/runner/extensions/event.command.js
index <HASH>..<HASH> 100644
--- a/lib/runner/extensions/event.command.js
+++ b/lib/runner/extensions/event.command.js
@@ -260,7 +260,7 @@ module.exports = {
var self = this,
dispatchEvent = EXECUTION_COOKIES_EVENT_BASE + executionId,
- cookieStore = _.get(self, 'requester.options.cookieJar._jar.store');
+ cookieStore = _.get(self, 'requester.options.cookieJar.store');
if (!cookieStore) {
return self.host.dispatch(dispatchEvent, eventId,
|
Add support for async cookie jar
|
postmanlabs_postman-runtime
|
train
|
52ebd35785e681488b63bd1d8b66bd1fa8218597
|
diff --git a/application/Espo/Services/Record.php b/application/Espo/Services/Record.php
index <HASH>..<HASH> 100644
--- a/application/Espo/Services/Record.php
+++ b/application/Espo/Services/Record.php
@@ -280,6 +280,18 @@ class Record extends \Espo\Core\Services\Base
}
}
+ protected function loadLinkMultipleFieldsForList(Entity $entity, $selectAttributeList)
+ {
+ foreach ($selectAttributeList as $attribute) {
+ if ($entity->getAttributeParam($attribute, 'isLinkMultipleIdList')) {
+ $field = $entity->getAttributeParam($attribute, 'relation');
+ if (!$field) continue;
+ if ($entity->has($attribute)) continue;
+ $entity->loadLinkMultipleField($field);
+ }
+ }
+ }
+
protected function loadLinkFields(Entity $entity)
{
$fieldDefs = $this->getMetadata()->get('entityDefs.' . $entity->getEntityType() . '.fields', array());
@@ -920,6 +932,9 @@ class Record extends \Espo\Core\Services\Base
if (!empty($params['loadAdditionalFields'])) {
$this->loadAdditionalFields($e);
}
+ if (!empty($selectAttributeList)) {
+ $this->loadLinkMultipleFieldsForList($e, $selectAttributeList);
+ }
$this->prepareEntityForOutput($e);
}
@@ -1128,6 +1143,9 @@ class Record extends \Espo\Core\Services\Base
if (!empty($params['loadAdditionalFields'])) {
$recordService->loadAdditionalFields($e);
}
+ if (!empty($selectAttributeList)) {
+ $this->loadLinkMultipleFieldsForList($e, $selectAttributeList);
+ }
$recordService->prepareEntityForOutput($e);
}
diff --git a/client/src/views/admin/layouts/list.js b/client/src/views/admin/layouts/list.js
index <HASH>..<HASH> 100644
--- a/client/src/views/admin/layouts/list.js
+++ b/client/src/views/admin/layouts/list.js
@@ -159,9 +159,7 @@ Espo.define('views/admin/layouts/list', 'views/admin/layouts/rows', function (De
},
checkFieldType: function (type) {
- if (['linkMultiple'].indexOf(type) != -1) {
- return false;
- }
+
return true;
},
|
supporting link multiple field on the list view
|
espocrm_espocrm
|
train
|
44204cf037a0080a5ea62630e0749d520dc77cb8
|
diff --git a/rails_generators/cucumber/templates/env.rb b/rails_generators/cucumber/templates/env.rb
index <HASH>..<HASH> 100644
--- a/rails_generators/cucumber/templates/env.rb
+++ b/rails_generators/cucumber/templates/env.rb
@@ -1,7 +1,17 @@
# IMPORTANT: This file was generated by Cucumber <%= Cucumber::VERSION %>
+#
+# (::) (::) (::) (::) (::) (::) (::) (::) (::) (::) (::) (::) (::) (::) (::)
+#
+# D O N ' T A D D Y O U R O W N C O D E T O
+# T H I S F I L E . O N L Y C H A N G E V A L U E S .
+#
+# (::) (::) (::) (::) (::) (::) (::) (::) (::) (::) (::) (::) (::) (::) (::)
+#
# Edit at your own peril - it's recommended to regenerate this file
# in the future when you upgrade to a newer version of Cucumber.
-# Consider adding your own code to a new file instead of editing this one.
+# Consider adding your own code to a new file under the support directory
+# instead of editing this file. Cucumber loads all files under support
+# before it loads files under step_definitions.
# Sets up the Rails environment for Cucumber
ENV["RAILS_ENV"] ||= "cucumber"
|
Explain to people that they don't have to do massive edits to env.rb
|
cucumber_cucumber-ruby
|
train
|
bf9755863e19d71ef315d64de8ae918a81367e5b
|
diff --git a/bundles.py b/bundles.py
index <HASH>..<HASH> 100644
--- a/bundles.py
+++ b/bundles.py
@@ -92,6 +92,7 @@ jquery = Bundle(
"jquery.treeview": "latest", # orphan, to be replaced by jqTree
"json2": "latest", # orphan
"hogan": "~3",
+ "MathJax": "~2.4", # orphan
"swfobject": "latest", # orphan
"typeahead.js": "latest",
"uploadify": "latest" # orphan
|
global: MathJax into bundles
|
inveniosoftware_invenio-base
|
train
|
f84e96880e12365e801964861744e73eb085920e
|
diff --git a/abstract.js b/abstract.js
index <HASH>..<HASH> 100644
--- a/abstract.js
+++ b/abstract.js
@@ -491,10 +491,10 @@ ee(Object.defineProperties(PersistenceDriver.prototype, assign({
return result;
});
}),
- searchIndex: d(function (keyPath, callback) {
- return this._searchIndex(ensureString(keyPath), ensureCallable(callback));
+ searchComputed: d(function (keyPath, callback) {
+ return this._searchComputed(ensureString(keyPath), ensureCallable(callback));
}),
- _searchIndex: d(function (keyPath, callback) {
+ _searchComputed: d(function (keyPath, callback) {
var done = create(null), transient = this._transient.computed[keyPath];
if (transient) {
forEach(transient, function (data, ownerId) {
@@ -503,14 +503,14 @@ ee(Object.defineProperties(PersistenceDriver.prototype, assign({
});
}
return this._safeGet(function () {
- return this.__searchIndex(keyPath, function (ownerId, data) {
+ return this.__searchComputed(keyPath, function (ownerId, data) {
if (!done[ownerId]) callback(ownerId, data);
});
});
}),
_recalculateComputedSet: d(function (keyPath, searchValue) {
var result = new Set();
- return this._searchIndex(keyPath, function (ownerId, data) {
+ return this._searchComputed(keyPath, function (ownerId, data) {
if (resolveFilter(searchValue, data.value)) result.add(ownerId);
})(result);
}),
@@ -708,7 +708,7 @@ ee(Object.defineProperties(PersistenceDriver.prototype, assign({
return promise;
}),
__searchDirect: d(notImplemented),
- __searchIndex: d(notImplemented),
+ __searchComputed: d(notImplemented),
// Reduced data
getReduced: d(function (key) {
diff --git a/index.js b/index.js
index <HASH>..<HASH> 100644
--- a/index.js
+++ b/index.js
@@ -111,7 +111,7 @@ TextFileDriver.prototype = Object.create(PersistenceDriver.prototype, assign({
});
}, this);
}),
- __searchIndex: d(function (keyPath, callback) {
+ __searchComputed: d(function (keyPath, callback) {
return this._getIndexStorage(keyPath)(function (map) {
forEach(map, function (data, ownerId) { callback(ownerId, data); });
});
|
Rename searchIndex to searchComputed
|
medikoo_dbjs-persistence
|
train
|
58c8a334ad466fe53051e22c5edf9e26debb7b7c
|
diff --git a/pdclient/dispenser_client.go b/pdclient/dispenser_client.go
index <HASH>..<HASH> 100644
--- a/pdclient/dispenser_client.go
+++ b/pdclient/dispenser_client.go
@@ -1,9 +1,52 @@
package pdclient
+import (
+ "bytes"
+ "fmt"
+ "io"
+ "net/http"
+ "time"
+)
+
//NewClient - constructor for a new dispenser client
-func NewClient(apiKey string, client clientDoer) *PDClient {
+func NewClient(apiKey string, url string, client clientDoer) *PDClient {
return &PDClient{
APIKey: apiKey,
client: client,
+ URL: url,
}
}
+
+func (s *PDClient) PostLease(leaseId, inventoryId, skuId string) {
+ req, _ := s.createRequest("POST", s.URL, s.getRequestBody(leaseId, inventoryId, skuId))
+ s.client.Do(req)
+}
+
+func (s *PDClient) getRequestBody(leaseId, inventoryId, skuId string) (body io.Reader) {
+ var durationDays int64 = 14
+ now := time.Now()
+ expire := now.Add(time.Duration(durationDays) * 24 * time.Hour)
+ body = bytes.NewBufferString(
+ fmt.Sprintf(`{
+ "lease_id":"%s",
+ "inventory_id":"%s",
+ "username":"joe@user.net",
+ "sku":"%s",
+ "lease_duration":%d,
+ "lease_end_date":%d,
+ "lease_start_date":%d,
+ "procurement_meta":{}`,
+ leaseId,
+ inventoryId,
+ skuId,
+ durationDays,
+ expire.UnixNano(),
+ now.UnixNano()))
+ return
+}
+
+func (s *PDClient) createRequest(method string, urlStr string, body io.Reader) (req *http.Request, err error) {
+ req, err = http.NewRequest(method, urlStr, body)
+ req.Header.Add("X-API-KEY", s.APIKey)
+ return
+}
diff --git a/pdclient/dispenser_client_test.go b/pdclient/dispenser_client_test.go
index <HASH>..<HASH> 100644
--- a/pdclient/dispenser_client_test.go
+++ b/pdclient/dispenser_client_test.go
@@ -1,6 +1,10 @@
package pdclient_test
import (
+ "bytes"
+ "io/ioutil"
+ "net/http"
+
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
. "github.com/pivotal-pez/pezdispenser/pdclient"
@@ -12,19 +16,44 @@ var _ = Describe("PDClient struct", func() {
Describe("given a NewClient func", func() {
Context("when called with a valid api-key and http.Client", func() {
controlKey := "random-api-key"
+ controlURL := "api.random.io"
var pdclient *PDClient
BeforeEach(func() {
- pdclient = NewClient(controlKey, new(fake.ClientDoer))
+ pdclient = NewClient(controlKey, controlURL, new(fake.ClientDoer))
})
It("then it should return a properly initialized pdclient", func() {
Ω(pdclient.APIKey).Should(Equal(controlKey))
+ Ω(pdclient.URL).Should(Equal(controlURL))
})
})
})
- XDescribe("given a PostLease() method call", func() {
- Context("when called with a valid taskguid", func() {
- It("then it should receive the task object from the rest endpoint, parse and return it", func() {
+ Describe("given a PostLease() method", func() {
+ Context("when called with valid arguments", func() {
+ controlKey := "random-api-key"
+ controlURL := "api.random.io"
+ controlLeaseID := "fakelease"
+ controlInventoryID := "fakeinventoryid"
+ controlSkuID := "fakesku"
+ controlResponseBody := "{}"
+ var fakeClient *fake.ClientDoer
+ var pdclient *PDClient
+ BeforeEach(func() {
+ fakeClient = &fake.ClientDoer{
+ Response: &http.Response{
+ Body: ioutil.NopCloser(bytes.NewBufferString(controlResponseBody)),
+ },
+ }
+ pdclient = NewClient(controlKey, controlURL, fakeClient)
+ pdclient.PostLease(controlLeaseID, controlInventoryID, controlSkuID)
+ })
+ It("then it should create a valid request object", func() {
+ body, _ := ioutil.ReadAll(fakeClient.SpyRequest.Body)
+ Ω(body).Should(ContainSubstring(controlLeaseID))
+ Ω(body).Should(ContainSubstring(controlInventoryID))
+ Ω(body).Should(ContainSubstring(controlSkuID))
+ })
+ XIt("then it should receive the task object from the rest endpoint, parse and return it", func() {
Ω(true).Should(Equal(false))
})
})
diff --git a/pdclient/types.go b/pdclient/types.go
index <HASH>..<HASH> 100644
--- a/pdclient/types.go
+++ b/pdclient/types.go
@@ -7,6 +7,7 @@ type (
PDClient struct {
APIKey string
client clientDoer
+ URL string
}
clientDoer interface {
Do(req *http.Request) (resp *http.Response, err error)
|
[#<I>] postlease can now create a request
|
pivotal-pez_pezdispenser
|
train
|
c2bd13d448e5d7cc828ace26c9323b331f967a25
|
diff --git a/lib/eu_central_bank.rb b/lib/eu_central_bank.rb
index <HASH>..<HASH> 100644
--- a/lib/eu_central_bank.rb
+++ b/lib/eu_central_bank.rb
@@ -145,7 +145,8 @@ class EuCentralBank < Money::Bank::VariableExchange
data.each do |key, rate|
from, to = key.split(SERIALIZER_SEPARATOR)
to, date = to.split(SERIALIZER_DATE_SEPARATOR)
- store.add_rate from, to, rate, date
+
+ store.add_rate from, to, BigDecimal(rate), date
end
end
diff --git a/spec/eu_central_bank_spec.rb b/spec/eu_central_bank_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/eu_central_bank_spec.rb
+++ b/spec/eu_central_bank_spec.rb
@@ -186,6 +186,34 @@ describe "EuCentralBank" do
odd_thread.kill
end
+ describe 'export / import rates' do
+ let(:other_bank) { EuCentralBank.new }
+
+ before { @bank.update_rates(@cache_path) }
+
+ it 're-imports JSON' do
+ raw_rates = @bank.export_rates(:json)
+ other_bank.import_rates(:json, raw_rates)
+
+ expect(@bank.store.send(:index)).to eq(other_bank.store.send(:index))
+ end
+
+ it 're-imports Marshalled ruby' do
+ raw_rates = @bank.export_rates(:ruby)
+ other_bank.import_rates(:ruby, raw_rates)
+
+ expect(@bank.store.send(:index)).to eq(other_bank.store.send(:index))
+ end
+
+ it 're-imports YAML' do
+ raw_rates = @bank.export_rates(:yaml)
+ other_bank.import_rates(:yaml, raw_rates)
+
+ expect(@bank.store.send(:index)).to eq(other_bank.store.send(:index))
+ end
+ end
+
+
it "should exchange money atomically" do
# NOTE: We need to introduce an artificial delay in the core get_rate
# function, otherwise it will take a lot of iterations to hit some sort or
|
Ensure exported rates can be re-imported back (#<I>)
|
RubyMoney_eu_central_bank
|
train
|
d176cfab34de3499329e4ab20b1a6237a030a56f
|
diff --git a/src/pluggy/hooks.py b/src/pluggy/hooks.py
index <HASH>..<HASH> 100644
--- a/src/pluggy/hooks.py
+++ b/src/pluggy/hooks.py
@@ -187,6 +187,7 @@ class _HookCaller:
self._wrappers = []
self._nonwrappers = []
self._hookexec = hook_execute
+ self._call_history = None
self.spec = None
if specmodule_or_class is not None:
assert spec_opts is not None
@@ -202,7 +203,7 @@ class _HookCaller:
self._call_history = []
def is_historic(self):
- return hasattr(self, "_call_history")
+ return self._call_history is not None
def _remove_plugin(self, plugin):
def remove(wrappers):
|
Initialize HookCaller._call_history to None instead of using hasattr
hasattr is slow, can't be typed properly, and makes the code harder to
understand.
|
pytest-dev_pluggy
|
train
|
0aa81704f565cfd6a9fcba529b196c679dfd9623
|
diff --git a/packages/components/bolt-nav-indicator/index.js b/packages/components/bolt-nav-indicator/index.js
index <HASH>..<HASH> 100644
--- a/packages/components/bolt-nav-indicator/index.js
+++ b/packages/components/bolt-nav-indicator/index.js
@@ -1,5 +1,7 @@
import { polyfillLoader } from '@bolt/core-v3.x/polyfills';
-polyfillLoader.then(() => {
- import('./nav-indicator.js');
+polyfillLoader.then(res => {
+ import(
+ /* webpackMode: 'lazy', webpackChunkName: 'bolt-nav-indicator' */ './nav-indicator.js'
+ );
});
diff --git a/packages/components/bolt-nav-priority/index.js b/packages/components/bolt-nav-priority/index.js
index <HASH>..<HASH> 100644
--- a/packages/components/bolt-nav-priority/index.js
+++ b/packages/components/bolt-nav-priority/index.js
@@ -1,5 +1,7 @@
import { polyfillLoader } from '@bolt/core-v3.x/polyfills';
-polyfillLoader.then(() => {
- import('./nav-priority.js');
+polyfillLoader.then(res => {
+ import(
+ /* webpackMode: 'lazy', webpackChunkName: 'bolt-nav-priority' */ './nav-priority.js'
+ );
});
diff --git a/packages/components/bolt-navlink/index.js b/packages/components/bolt-navlink/index.js
index <HASH>..<HASH> 100644
--- a/packages/components/bolt-navlink/index.js
+++ b/packages/components/bolt-navlink/index.js
@@ -1,5 +1,7 @@
import { polyfillLoader } from '@bolt/core-v3.x/polyfills';
-polyfillLoader.then(() => {
- import('./navlink.js');
+polyfillLoader.then(res => {
+ import(
+ /* webpackMode: 'lazy', webpackChunkName: 'bolt-navlink' */ './navlink.js'
+ );
});
|
chore: port over dynamic import cleanup from epic/academy branch
|
bolt-design-system_bolt
|
train
|
fecb888e52cda7ffbc1b293687d5dc466f4aafbf
|
diff --git a/simulator/src/main/java/com/hazelcast/simulator/protocol/connector/AbstractServerConnector.java b/simulator/src/main/java/com/hazelcast/simulator/protocol/connector/AbstractServerConnector.java
index <HASH>..<HASH> 100644
--- a/simulator/src/main/java/com/hazelcast/simulator/protocol/connector/AbstractServerConnector.java
+++ b/simulator/src/main/java/com/hazelcast/simulator/protocol/connector/AbstractServerConnector.java
@@ -250,7 +250,8 @@ abstract class AbstractServerConnector implements ServerConnector {
return messageQueue.size();
}
- ResponseFuture submit(SimulatorAddress source, SimulatorAddress destination, SimulatorOperation op) {
+ @Override
+ public ResponseFuture submit(SimulatorAddress source, SimulatorAddress destination, SimulatorOperation op) {
SimulatorMessage message = createSimulatorMessage(source, destination, op);
String futureKey = createFutureKey(source, message.getMessageId(), 0);
ResponseFuture responseFuture = createInstance(messageQueueFutures, futureKey);
diff --git a/simulator/src/main/java/com/hazelcast/simulator/protocol/connector/ServerConnector.java b/simulator/src/main/java/com/hazelcast/simulator/protocol/connector/ServerConnector.java
index <HASH>..<HASH> 100644
--- a/simulator/src/main/java/com/hazelcast/simulator/protocol/connector/ServerConnector.java
+++ b/simulator/src/main/java/com/hazelcast/simulator/protocol/connector/ServerConnector.java
@@ -73,6 +73,8 @@ public interface ServerConnector {
*/
ResponseFuture submit(SimulatorAddress destination, SimulatorOperation op);
+ ResponseFuture submit(SimulatorAddress source, SimulatorAddress destination, SimulatorOperation operation);
+
/**
* Writes a {@link SimulatorOperation} to a {@link SimulatorAddress}.
*
|
Added missing method to ServerConnector
|
hazelcast_hazelcast-simulator
|
train
|
9e81845dba6f893695d6c6af9544dc8cbbaa8ac4
|
diff --git a/ipuz/structures/clue.py b/ipuz/structures/clue.py
index <HASH>..<HASH> 100644
--- a/ipuz/structures/clue.py
+++ b/ipuz/structures/clue.py
@@ -5,6 +5,14 @@ from .enumeration import validate_enumeration
def validate_clue(field_data):
+ def validate_list_of_cluenum(value):
+ if type(value) is not list:
+ return False
+ for element in value:
+ if not validate_cluenum(element):
+ return False
+ return True
+
if type(field_data) not in [list, dict] and not isinstance(field_data, six.string_types):
return False
if type(field_data) is list:
@@ -32,12 +40,8 @@ def validate_clue(field_data):
return False
if key == "number" and not validate_cluenum(value):
return False
- elif key == "numbers":
- if type(value) is not list:
- return False
- for element in value:
- if not validate_cluenum(element):
- return False
+ elif key == "numbers" and not validate_list_of_cluenum(value):
+ return False
elif key == "clue" and not isinstance(value, six.string_types):
return False
elif key == "hints":
@@ -52,12 +56,8 @@ def validate_clue(field_data):
return False
elif key == "enumeration" and not validate_enumeration(value):
return False
- elif key == "references":
- if type(value) is not list:
- return False
- for element in value:
- if not validate_cluenum(element):
- return False
+ elif key == "references" and not validate_list_of_cluenum(value):
+ return False
elif key == "see" and not validate_cluenum(value):
return False
elif key == "highlight" and type(value) is not bool:
|
Refactoring to reduce amount of code needed
|
svisser_ipuz
|
train
|
412a3036f541fb3d87e7fdabec5ddf76343ef518
|
diff --git a/bin/stimela b/bin/stimela
index <HASH>..<HASH> 100755
--- a/bin/stimela
+++ b/bin/stimela
@@ -20,4 +20,9 @@ if not os.path.exists(stimela.LOG_CONTAINERS):
if not os.path.exists(stimela.LOG_PROCESS):
with open(stimela.LOG_PROCESS, "w") as std:
pass
+
+if not os.path.exists(stimela.LOG_CABS):
+ with open(stimela.LOG_CABS, "w") as std:
+ pass
+
stimela.main()
diff --git a/stimela/__init__.py b/stimela/__init__.py
index <HASH>..<HASH> 100644
--- a/stimela/__init__.py
+++ b/stimela/__init__.py
@@ -20,10 +20,13 @@ LOG_HOME = os.path.expanduser("~/.stimela")
LOG_IMAGES = LOG_HOME + "/stimela_images.log"
LOG_CONTAINERS = LOG_HOME + "/stimela_containers.log"
LOG_PROCESS = LOG_HOME + "/stimela_process.log"
+LOG_CABS = LOG_HOME + "/stimela_cab.log"
BASE = "base simms casa meqtrees lwimager wsclean aoflagger owlcat sourcery".split()
CAB = os.listdir(cargo.CAB_PATH)
+USER = os.environ["USER"]
+
__version__ = "0.1.4"
GLOBALS = {}
@@ -51,10 +54,29 @@ def build():
parser = ArgumentParser(description='Build executor (a.k.a cab) images')
args = parser.parse_args()
+ # clear old cabs
+ img = stimela_logger.Image(LOG_CABS)
+ img.clear()
+
for image in CAB:
dockerfile = "{:s}/{:s}".format(cargo.CAB_PATH, image)
- docker.build("cab/{:s}".format(image),
+ image = "{:s}_cab/{:s}".format(USER, image)
+ docker.build(image,
dockerfile)
+ img.add(dict(name=image))
+
+ img.write()
+
+
+def cabs():
+ for i, arg in enumerate(sys.argv):
+ if (arg[0] == '-') and arg[1].isdigit(): sys.argv[i] = ' ' + arg
+
+ parser = ArgumentParser(description='List executor (a.k.a cab) images')
+ args = parser.parse_args()
+
+ img = stimela_logger.Image(LOG_CABS)
+ img.display()
def run():
@@ -201,7 +223,7 @@ def images():
img.clear()
-def cabs():
+def containers():
for i, arg in enumerate(sys.argv):
if (arg[0] == '-') and arg[1].isdigit(): sys.argv[i] = ' ' + arg
@@ -314,7 +336,7 @@ def main():
options = []
commands = dict(pull=pull, build=build, run=run,
images=images, cabs=cabs, ps=ps,
- kill=kill)
+ containers=containers, kill=kill)
command = "failed"
diff --git a/stimela/recipe.py b/stimela/recipe.py
index <HASH>..<HASH> 100644
--- a/stimela/recipe.py
+++ b/stimela/recipe.py
@@ -13,6 +13,8 @@ import inspect
import platform
from stimela.utils import stimela_logger
+USER = os.environ["USER"]
+
ekhaya = cargo.__path__[0]
@@ -102,6 +104,7 @@ class Recipe(object):
image = image.split(":")[0]
image = "{:s}:{:s}".format(image, cab_tag)
+
cont = docker.Load(image, name, label=label, logger=self.log)
cont.add_environ("MAC_OS", str(self.MAC_OS))
@@ -163,6 +166,7 @@ class Recipe(object):
cont.add_volume(self.configs_path, self.configs_path_container, perm="ro")
config = self.configs_path_container+"/"+config
+ cont.image = "{:s}_{:s}".format(USER, image)
cont.add_environ("CONFIG", config)
self.containers.append(cont)
|
label cabs for each USER
|
SpheMakh_Stimela
|
train
|
b242c33f118bd2a400214e51af15eac1819b4bcf
|
diff --git a/Model/Menu/Import/SampleFile.php b/Model/Menu/Import/SampleFile.php
index <HASH>..<HASH> 100644
--- a/Model/Menu/Import/SampleFile.php
+++ b/Model/Menu/Import/SampleFile.php
@@ -75,7 +75,7 @@ class SampleFile
public function getFileDownloadContent()
{
$data = $this->getSampleData();
- return $this->exportProcessor->generateDownloadFile('sample', $data, array_keys($data));
+ return $this->exportProcessor->generateDownloadFile('sample', $data);
}
/**
|
[<I>] Update sample file model file download content method
|
SnowdogApps_magento2-menu
|
train
|
9dee2cf13417c70db1694c0ddf4dfcceae8f6d9a
|
diff --git a/src/org/opencms/search/CmsSearchManager.java b/src/org/opencms/search/CmsSearchManager.java
index <HASH>..<HASH> 100644
--- a/src/org/opencms/search/CmsSearchManager.java
+++ b/src/org/opencms/search/CmsSearchManager.java
@@ -1742,8 +1742,6 @@ public class CmsSearchManager implements I_CmsScheduledJob, I_CmsEventListener {
*/
public void registerSolrIndex(CmsSolrIndex index) throws CmsConfigurationException {
- ensureIndexIsUnlocked(index.getPath());
-
if ((m_solrConfig == null) || !m_solrConfig.isEnabled()) {
// No solr server configured
throw new CmsConfigurationException(Messages.get().container(Messages.ERR_SOLR_NOT_ENABLED_0));
@@ -1761,57 +1759,61 @@ public class CmsSearchManager implements I_CmsScheduledJob, I_CmsEventListener {
m_coreContainer = createCoreContainer();
}
- // create a new core if no core exists for the given index
- if (!m_coreContainer.getCoreNames().contains(index.getCoreName())) {
- // Being sure the core container is not 'null',
- // we can create a core for this index if not already existent
- File dataDir = new File(index.getPath());
- if (!dataDir.exists()) {
- dataDir.mkdirs();
- if (CmsLog.INIT.isInfoEnabled()) {
- CmsLog.INIT.info(
- Messages.get().getBundle().key(
- Messages.INIT_SOLR_INDEX_DIR_CREATED_2,
- index.getName(),
- index.getPath()));
- }
+ // unload the existing core if it exists to avoid problems with forced unlock.
+ if (m_coreContainer.getCoreNames().contains(index.getCoreName())) {
+ m_coreContainer.unload(index.getCoreName(), false, false, true);
+ }
+
+ // ensure that all locks on the index are gone
+ ensureIndexIsUnlocked(index.getPath());
+
+ // load the core to the container
+ File dataDir = new File(index.getPath());
+ if (!dataDir.exists()) {
+ dataDir.mkdirs();
+ if (CmsLog.INIT.isInfoEnabled()) {
+ CmsLog.INIT.info(
+ Messages.get().getBundle().key(
+ Messages.INIT_SOLR_INDEX_DIR_CREATED_2,
+ index.getName(),
+ index.getPath()));
}
- File instanceDir = new File(
- m_solrConfig.getHome() + FileSystems.getDefault().getSeparator() + index.getName());
- if (!instanceDir.exists()) {
- instanceDir.mkdirs();
- if (CmsLog.INIT.isInfoEnabled()) {
- CmsLog.INIT.info(
- Messages.get().getBundle().key(
- Messages.INIT_SOLR_INDEX_DIR_CREATED_2,
- index.getName(),
- index.getPath()));
- }
+ }
+ File instanceDir = new File(m_solrConfig.getHome() + FileSystems.getDefault().getSeparator() + index.getName());
+ if (!instanceDir.exists()) {
+ instanceDir.mkdirs();
+ if (CmsLog.INIT.isInfoEnabled()) {
+ CmsLog.INIT.info(
+ Messages.get().getBundle().key(
+ Messages.INIT_SOLR_INDEX_DIR_CREATED_2,
+ index.getName(),
+ index.getPath()));
}
+ }
- // create the core
- // TODO: suboptimal - forces always the same schema
- SolrCore core = null;
- try {
- // creation includes registration.
- // TODO: this was the old code: core = m_coreContainer.create(descriptor, false);
- Map<String, String> properties = new HashMap<String, String>(3);
- properties.put(CoreDescriptor.CORE_DATADIR, dataDir.getAbsolutePath());
- properties.put(CoreDescriptor.CORE_CONFIGSET, "default");
- core = m_coreContainer.create(index.getCoreName(), instanceDir.toPath(), properties);
- } catch (NullPointerException e) {
- if (core != null) {
- core.close();
- }
- throw new CmsConfigurationException(
- Messages.get().container(
- Messages.ERR_SOLR_SERVER_NOT_CREATED_3,
- index.getName() + " (" + index.getCoreName() + ")",
- index.getPath(),
- m_solrConfig.getSolrConfigFile().getAbsolutePath()),
- e);
+ // create the core
+ // TODO: suboptimal - forces always the same schema
+ SolrCore core = null;
+ try {
+ // creation includes registration.
+ // TODO: this was the old code: core = m_coreContainer.create(descriptor, false);
+ Map<String, String> properties = new HashMap<String, String>(3);
+ properties.put(CoreDescriptor.CORE_DATADIR, dataDir.getAbsolutePath());
+ properties.put(CoreDescriptor.CORE_CONFIGSET, "default");
+ core = m_coreContainer.create(index.getCoreName(), instanceDir.toPath(), properties);
+ } catch (NullPointerException e) {
+ if (core != null) {
+ core.close();
}
+ throw new CmsConfigurationException(
+ Messages.get().container(
+ Messages.ERR_SOLR_SERVER_NOT_CREATED_3,
+ index.getName() + " (" + index.getCoreName() + ")",
+ index.getPath(),
+ m_solrConfig.getSolrConfigFile().getAbsolutePath()),
+ e);
}
+
if (index.isNoSolrServerSet()) {
index.setSolrServer(new EmbeddedSolrServer(m_coreContainer, index.getCoreName()));
}
|
Fixed index lock problem during installation.
Due to the forced unlocking, indexing during the installation of OpenCms
caused problems.
|
alkacon_opencms-core
|
train
|
c72402a5172445eb40968714d55e09eabacd9eb4
|
diff --git a/app/controllers/wafflemix/pages_controller.rb b/app/controllers/wafflemix/pages_controller.rb
index <HASH>..<HASH> 100644
--- a/app/controllers/wafflemix/pages_controller.rb
+++ b/app/controllers/wafflemix/pages_controller.rb
@@ -13,7 +13,7 @@ module Wafflemix
def show
if params[:id]
- @page = Page.find_by_link_url(params[:id])
+ @page = Page.find(params[:id])
else
@page = Page.find_by_link_url(params[:path].to_s.split('/').last)#(params[:path] ? params[:path].to_s.split('/').last : params[:id])
end
@@ -24,7 +24,7 @@ module Wafflemix
end
def home
- @page = Page.find_by_link_url("home")
+ @page = Page.find_by_link_url('home')
respond_to do |format|
format.html
@@ -38,7 +38,7 @@ module Wafflemix
params[:content].each do |key, value|
if key =~ /content_section/
- section = key.gsub /(content_section_|_)/, "content_section_" => "", "_" => " "
+ section = key.gsub /(content_section_|_)/, 'content_section_' => '', '_' => ''
content_to_update = page.content_parts.find_by_name(section)
content_to_update.content = value[:value]
content_to_update.save
|
Find by id if exists.
|
jrissler_wafflemix
|
train
|
168e86ff71801d79928bf52da282291e3f6495a5
|
diff --git a/tests/test_packages.py b/tests/test_packages.py
index <HASH>..<HASH> 100644
--- a/tests/test_packages.py
+++ b/tests/test_packages.py
@@ -38,25 +38,19 @@ class TestPackage(TestCase):
self.assertEqual(repr(Package.parse('foo-1')),
"Package.parse('foo-1.0.0')")
- def test_cmp(self):
- self.assertEqual(
- Package.parse('foo-1').__cmp__(Package.parse('foo-1')), 0)
- self.assertEqual(
- Package.parse('foo-1').__cmp__(Package.parse('foo-2')), -1)
- self.assertEqual(
- Package.parse('foo-1').__cmp__(Package.parse('foo-0.1')), 1)
-
- def test_cmp(self):
- self.assertEqual(
- Package.parse('foo-1').__cmp__(Package.parse('foo-1')), 0)
- self.assertEqual(
- Package.parse('foo-1').__cmp__(Package.parse('foo-2')), -1)
- self.assertEqual(
- Package.parse('foo-1').__cmp__(Package.parse('foo-0.1')), 1)
-
def test_lt(self):
self.assertTrue(Package.parse('bar-1') < Package.parse('foo-0.1'))
+ self.assertTrue(Package.parse('foo-1') < Package.parse('foo-2'))
+ self.assertFalse(Package.parse('foo-2') < Package.parse('foo-2'))
+ self.assertFalse(Package.parse('foo-3') < Package.parse('foo-2'))
def test_build_options(self):
self.assertEqual(Package.parse('foo-1+foo.bar').build_options,
set(['bar', 'foo']))
+
+ def test_eq(self):
+ self.assertTrue(Package.parse('foo-1') == 'foo-1')
+ self.assertFalse(Package.parse('foo-1') == 'foo-2')
+ self.assertFalse(Package.parse('foo-1') == 'bar-2')
+ self.assertTrue(Package.parse('foo-1+bar') == 'foo-1+bar')
+ self.assertFalse(Package.parse('foo-1+bar') == 'foo-1+baz')
diff --git a/versions/packages.py b/versions/packages.py
index <HASH>..<HASH> 100644
--- a/versions/packages.py
+++ b/versions/packages.py
@@ -91,20 +91,24 @@ class Package(object):
def __hash__(self):
return hash(self.name) ^ hash(self.version)
- def __cmp__(self, other):
- name_cmp = cmp(self.name, other.name)
- if name_cmp == 0:
- return cmp(self.version, other.version)
- else:
- return name_cmp
+ def __eq__(self, other):
+ if isinstance(other, str):
+ other = Package.parse(other)
+ return self.name == other.name and self.version == other.version and \
+ self.build_options == other.build_options
def __lt__(self, other):
- return cmp(self, other) == -1
+ if self.name < other.name:
+ return True
+ elif self.version < other.version:
+ return True
+ else:
+ return False
def __str__(self):
if self.dependencies:
dependencies = ';depends ' + \
- ';depends '.join(str(d) for d in self.dependencies)
+ ';depends '.join(sorted(map(str, self.dependencies)))
else:
dependencies = ''
return '%s-%s%s' % (self.name, self.version, dependencies)
|
removed Package().__cmp__, added __eq__ and __lt__
More python 3 friendly, same result
|
pmuller_versions
|
train
|
b4b93a57c99a8deb87cc5028a6b3b29f9e5dd0a9
|
diff --git a/includes/functions/functions_print_lists.php b/includes/functions/functions_print_lists.php
index <HASH>..<HASH> 100644
--- a/includes/functions/functions_print_lists.php
+++ b/includes/functions/functions_print_lists.php
@@ -1378,7 +1378,7 @@ function print_changes_list($change_ids, $sort, $show_parents=false) {
}
$return .= "<div style='margin-bottom:5px'>";
//-- Last change date/time & user
- $return .= WT_I18N::translate("Changed on %s by %s", $value['record']->LastChangeTimestamp(empty($SEARCH_SPIDER)), $value['record']->LastChangeUser());
+ $return .= /* I18N: [a record was] Changed on <date/time> by <user> */ WT_I18N::translate('Changed on %1$s by %2$s', $value['record']->LastChangeTimestamp(empty($SEARCH_SPIDER)), $value['record']->LastChangeUser());
$return .= "</div>"; // class='indent'
$return .= "</div>";
}
|
I<I>N: add order-indicators to messages with multiple place-holders
|
fisharebest_webtrees
|
train
|
273d9ce89de8c52afba015c40530040688f1f829
|
diff --git a/lib/ios-deploy.js b/lib/ios-deploy.js
index <HASH>..<HASH> 100644
--- a/lib/ios-deploy.js
+++ b/lib/ios-deploy.js
@@ -46,9 +46,11 @@ class IOSDeploy {
}
async isAppInstalled (bundleid) {
- let isInstalled = [`--exists`, `--id`, this.udid, `--bundle_id`, bundleid];
+ let installStatusArgs = [`--exists`, `--id`, this.udid, `--bundle_id`, bundleid];
try {
- let {stdout} = await exec(this.cmd, isInstalled);
+ logger.debug(`Calling: '${this.cmd} ${installStatusArgs.join(' ')}'`);
+ let {stdout} = await exec(this.cmd, installStatusArgs);
+ logger.debug(`Stdout: '${stdout}'`);
return (stdout && (stdout.includes('true')));
} catch (err) {
// error 255 is just ios-deploy's way of saying it is not installed
|
show ios deploy command and the stdout (#<I>)
* show ios deploy command and the stdout
* fix comments
|
appium_appium-xcuitest-driver
|
train
|
6cb72234eb2a336b683ec4f36fe129dcde86c025
|
diff --git a/morphia/src/main/java/com/google/code/morphia/DatastoreImpl.java b/morphia/src/main/java/com/google/code/morphia/DatastoreImpl.java
index <HASH>..<HASH> 100644
--- a/morphia/src/main/java/com/google/code/morphia/DatastoreImpl.java
+++ b/morphia/src/main/java/com/google/code/morphia/DatastoreImpl.java
@@ -201,13 +201,13 @@ public class DatastoreImpl implements Datastore, AdvancedDatastore {
}
public <T> void ensureIndex(Class<T> clazz, String name, String fields, boolean unique, boolean dropDupsOnCreate) {
- ensureIndex(clazz, name, QueryImpl.parseSortString(fields), unique, dropDupsOnCreate, false);
+ ensureIndex(clazz, name, QueryImpl.parseSortString(fields), unique, dropDupsOnCreate, false, false);
}
public <T> void ensureIndex(Class<T> clazz, String name, String fields, boolean unique, boolean dropDupsOnCreate, boolean background) {
- ensureIndex(clazz, name, QueryImpl.parseSortString(fields), unique, dropDupsOnCreate, background);
+ ensureIndex(clazz, name, QueryImpl.parseSortString(fields), unique, dropDupsOnCreate, background, false);
}
- protected <T> void ensureIndex(Class<T> clazz, String name, BasicDBObject fields, boolean unique, boolean dropDupsOnCreate, boolean background) {
+ protected <T> void ensureIndex(Class<T> clazz, String name, BasicDBObject fields, boolean unique, boolean dropDupsOnCreate, boolean background, boolean sparse) {
//validate field names and translate them to the stored values
BasicDBObject keys = new BasicDBObject();
for(Entry<String, Object> entry : fields.entrySet()){
@@ -226,9 +226,10 @@ public class DatastoreImpl implements Datastore, AdvancedDatastore {
keyOpts.add("dropDups", true);
}
- if (background) {
+ if (background)
keyOpts.add("background", true);
- }
+ if (sparse)
+ keyOpts.add("sparse", true);
DBCollection dbColl = getCollection(clazz);
@@ -256,7 +257,7 @@ public class DatastoreImpl implements Datastore, AdvancedDatastore {
keys.add(fieldName, dir.toIndexValue());
}
- ensureIndex(clazz, name, (BasicDBObject) keys.get(), unique, dropDupsOnCreate, background);
+ ensureIndex(clazz, name, (BasicDBObject) keys.get(), unique, dropDupsOnCreate, background, false);
}
public <T> void ensureIndex(Class<T> type, String name, IndexDirection dir) {
@@ -288,7 +289,7 @@ public class DatastoreImpl implements Datastore, AdvancedDatastore {
if (idxs != null && idxs.value() != null && idxs.value().length > 0)
for(Index index : idxs.value()) {
BasicDBObject fields = QueryImpl.parseSortString(index.value());
- ensureIndex(mc.getClazz(), index.name(), fields, index.unique(), index.dropDups(), index.background() ? index.background() : background );
+ ensureIndex(mc.getClazz(), index.name(), fields, index.unique(), index.dropDups(), index.background() ? index.background() : background, index.sparse() ? index.sparse() : false );
}
//Ensure indexes from field annotations, and embedded entities
@@ -303,7 +304,7 @@ public class DatastoreImpl implements Datastore, AdvancedDatastore {
field.append(mf.getNameToStore());
- ensureIndex(indexedClass, index.name(), new BasicDBObject(field.toString(), index.value().toIndexValue()), index.unique(), index.dropDups(), index.background() ? index.background() : background );
+ ensureIndex(indexedClass, index.name(), new BasicDBObject(field.toString(), index.value().toIndexValue()), index.unique(), index.dropDups(), index.background() ? index.background() : background , index.sparse() ? index.sparse() : false);
}
if (!mf.isTypeMongoCompatible() && !mf.hasAnnotation(Reference.class) && !mf.hasAnnotation(Serialized.class)) {
diff --git a/morphia/src/main/java/com/google/code/morphia/annotations/Index.java b/morphia/src/main/java/com/google/code/morphia/annotations/Index.java
index <HASH>..<HASH> 100644
--- a/morphia/src/main/java/com/google/code/morphia/annotations/Index.java
+++ b/morphia/src/main/java/com/google/code/morphia/annotations/Index.java
@@ -40,6 +40,9 @@ public @interface Index {
boolean unique() default false;
/** Tells the unique index to drop duplicates silently when creating; only the first will be kept*/
boolean dropDups() default false;
- /** Create the index in the background? (defaults false)*/
+ /** Create the index in the background*/
boolean background() default false;
+ /** Create the index with the sparse option*/
+ boolean sparse() default false;
+
}
diff --git a/morphia/src/main/java/com/google/code/morphia/annotations/Indexed.java b/morphia/src/main/java/com/google/code/morphia/annotations/Indexed.java
index <HASH>..<HASH> 100644
--- a/morphia/src/main/java/com/google/code/morphia/annotations/Indexed.java
+++ b/morphia/src/main/java/com/google/code/morphia/annotations/Indexed.java
@@ -26,6 +26,8 @@ public @interface Indexed {
boolean unique() default false;
/** Tells the unique index to drop duplicates silently when creating; only the first will be kept*/
boolean dropDups() default false;
- /** Create the index in the background? (defaults false)*/
+ /** Create the index in the background?*/
boolean background() default false;
+ /** Create the index with the sparse option*/
+ boolean sparse() default false;
}
|
Added sparse index support (for <I>+)
|
MorphiaOrg_morphia
|
train
|
67df72abdef7374c37c7ccd4e8b48ca253692eb6
|
diff --git a/test/test_dnsbl-client.rb b/test/test_dnsbl-client.rb
index <HASH>..<HASH> 100755
--- a/test/test_dnsbl-client.rb
+++ b/test/test_dnsbl-client.rb
@@ -44,7 +44,8 @@ class TestDNSBLClient < Minitest::Test
def test_interpret_project_honeypot_results
apikey = ENV.fetch 'PHPAPIKEY', nil
- skip 'Project Honeypot API Key Required for this test. Please set PHPAPIKEY.' if apikey
+ skip 'Project Honeypot API Key Required for this test. Please set PHPAPIKEY.' unless apikey
+
config = YAML.safe_load("---
PROJECTHONEYPOT:
domain: dnsbl.httpbl.org
|
skip Project Honeypot test without key - next try
|
chrislee35_dnsbl-client
|
train
|
b913a65ddda34f6b07681064853a1e0fc33a9f00
|
diff --git a/tensorlayer/layers/core.py b/tensorlayer/layers/core.py
index <HASH>..<HASH> 100644
--- a/tensorlayer/layers/core.py
+++ b/tensorlayer/layers/core.py
@@ -189,6 +189,7 @@ class Layer(object):
# self._outputs_shape = self.outputs.get_shape().as_list()
self._built = True
+ self.is_train = True
# TODO: need update
# self._add_layers(prev_layer.all_layers)
@@ -249,7 +250,7 @@ class Layer(object):
raise Exception("The build_weights method must be implemented by inherited class")
@abstractmethod
- def forward(self, inputs, is_train):
+ def forward(self, inputs):
# FIXME: documentation needed
"""
An abstract method which should be overwritten in derived classes to define forward feeding operations of the layer.
|
is_train as an attribute of base layer and remove is_train as argument for forward function
|
tensorlayer_tensorlayer
|
train
|
31b3a65a0d0c2958c02d0695e56cef5a95ba2cb0
|
diff --git a/lib/parser.js b/lib/parser.js
index <HASH>..<HASH> 100644
--- a/lib/parser.js
+++ b/lib/parser.js
@@ -111,11 +111,9 @@ Parser.prototype = {
var type = this.peek.type;
switch (type) {
case 'variable':
- return this.variable;
case 'property':
- return this.property;
case 'selector':
- return this.selector;
+ return this[type];
default:
throw new Error('invalid token "' + type + '"');
}
|
Refactored Parser#statement
|
stylus_stylus
|
train
|
6da9174d3eed078b4facd8dcf71f7a6064c8d418
|
diff --git a/utils/utils.go b/utils/utils.go
index <HASH>..<HASH> 100644
--- a/utils/utils.go
+++ b/utils/utils.go
@@ -132,20 +132,20 @@ func CopyFile(src, dst string) (err error) {
return
}
}
- if err = os.Link(src, dst); err == nil {
- return
- }
- err = copyFileContents(src, dst)
+ // if err = os.Link(src, dst); err == nil {
+ // return
+ // }
+ err = copyFileContents(src, dst, sfi)
return
}
-func copyFileContents(src, dst string) (err error) {
+func copyFileContents(src, dst string, sfi os.FileInfo) (err error) {
in, err := os.Open(src)
if err != nil {
return
}
defer in.Close()
- out, err := os.Create(dst)
+ out, err := os.OpenFile(dst, os.O_RDWR|os.O_CREATE|os.O_TRUNC, sfi.Mode())
if err != nil {
return
}
|
force copy files to target for user root and keep mod of source
|
blablacar_dgr
|
train
|
ab6ba8aa1c761787d9dba7d47b931da39f7b37c2
|
diff --git a/src/controls/trackpad-controls.js b/src/controls/trackpad-controls.js
index <HASH>..<HASH> 100644
--- a/src/controls/trackpad-controls.js
+++ b/src/controls/trackpad-controls.js
@@ -60,6 +60,7 @@ module.exports = AFRAME.registerComponent('trackpad-controls', {
},
onTouchStart: function (e) {
+ this.canRecordAxis = true;
this.startingAxisData = [];
e.preventDefault();
},
@@ -73,29 +74,30 @@ module.exports = AFRAME.registerComponent('trackpad-controls', {
onAxisMove: function(e){
var axis_data = e.detail.axis;
- if(this.startingAxisData.length === 0){
- this.startingAxisData[0] = axis_data[0]
- this.startingAxisData[1] = axis_data[1]
+ if(this.startingAxisData.length === 0 && this.canRecordAxis){
+ this.canRecordAxis = false;
+ this.startingAxisData[0] = axis_data[0];
+ this.startingAxisData[1] = axis_data[1];
+ this.isMoving = true;
}
if(this.startingAxisData.length > 0){
- var velX = axis_data[0] < this.startingAxisData[0] ? -1 : 1
- var velZ = axis_data[1] < this.startingAxisData[1] ? 1 : -1
+ const velX = axis_data[0] < this.startingAxisData[0] ? -1 : 1;
+ const velZ = axis_data[1] < this.startingAxisData[1] ? 1 : -1;
- var absChangeZ = Math.abs(this.startingAxisData[1] - axis_data[1])
- var absChangeX = Math.abs(this.startingAxisData[0] - axis_data[0])
+ const absChangeZ = Math.abs(this.startingAxisData[1] - axis_data[1]);
+ const absChangeX = Math.abs(this.startingAxisData[0] - axis_data[0]);
if(absChangeZ > absChangeX) {
this.xVel = 0;
this.zVel = velZ;
- this.isMoving = true;
}else{
this.zVel = 0;
- this.xVel = velX
- this.isMoving = true;
+ this.xVel = velX;
}
+
}
}
});
|
Re-add canRecordAxis var
Without it, it appears that the axismove handler is a little too
sensitive, and after any type of movement, the rig is getting pulled to
the right.
|
donmccurdy_aframe-extras
|
train
|
725ea4ec44d6e1e982655c3da1e3b72f9b8d1545
|
diff --git a/candidate.js b/candidate.js
index <HASH>..<HASH> 100644
--- a/candidate.js
+++ b/candidate.js
@@ -56,7 +56,7 @@ var partValidation = [
**/
module.exports = function(data) {
var errors = [];
- var candidate = data && data.candidate;
+ var candidate = data && (data.candidate || data);
var prefixMatch = candidate && rePrefix.exec(candidate);
var parts = prefixMatch && candidate.slice(prefixMatch[0].length).split(/\s/);
|
Allow just the candidate line to be the subject of the test
|
rtc-io_rtc-validator
|
train
|
0d8add8737bc07981b56947856ef607fc914cfab
|
diff --git a/build/rollup.js b/build/rollup.js
index <HASH>..<HASH> 100644
--- a/build/rollup.js
+++ b/build/rollup.js
@@ -169,36 +169,31 @@ function bundleOptions (format, package, env = 'development') {
options.output.globals = (id) => {
if (id === 'vue') return 'Vue'
- // if (ol[id] != null) {
- // return ol[id]
- // }
+ if (ol[id] != null) {
+ return ol[id]
+ }
}
options.input.external = (id, parent, resolved) => {
if (['vue'].includes(id)) return true
- // if (!resolved && /^ol\/.+/.test(id)) {
- // ol[id] = id.replace(/\//g, '.')
- // return true
- // }
+ if (!resolved && /^ol\/.+/.test(id)) {
+ ol[id] = id.replace(/\//g, '.')
+ return true
+ }
return false
}
options.replaces['process.env.NODE_ENV'] = `'${env}'`
options.replaces['process.env.VUELAYERS_DEBUG'] = JSON.stringify(process.env.NODE_ENV !== 'production')
- // options.minify = true
- // process.env.BABEL_ENV = 'es5-production'
- // options.defines.IS_STANDALONE = true
+ options.minify = true
break
case 'cjs':
options.input.external = external
options.patterns = patterns
- // process.env.BABEL_ENV = 'es5-production'
break
case 'es':
options.input.external = external
options.patterns = patterns
- // options.outputPath = path.join(options.outputPath, '_esm')
- // options.cssName = undefined
break
}
diff --git a/build/webpack.base.config.js b/build/webpack.base.config.js
index <HASH>..<HASH> 100644
--- a/build/webpack.base.config.js
+++ b/build/webpack.base.config.js
@@ -130,7 +130,7 @@ module.exports = {
chunkModules: false,
},
devServer: {
- open: true,
+ open: false,
hot: true,
contentBase: config.outputPath,
clientLogLevel: 'info',
|
Rollback to previous UMD build strategy
Including stuff from OpenLayers into UMD produces more problems than
convenience.
#<I>
|
ghettovoice_vuelayers
|
train
|
a21d5fe54b5cdb77abfd17e32fa3546229a3b202
|
diff --git a/dataloader.py b/dataloader.py
index <HASH>..<HASH> 100644
--- a/dataloader.py
+++ b/dataloader.py
@@ -71,6 +71,8 @@ class DataLoader:
label_value[label_map[label]] = 1.0
label_values.append(label_value)
+ self._check_data_not_empty(images)
+
return np.array(images), np.array(label_values), label_map
def _get_data_from_csv(self):
@@ -180,11 +182,9 @@ class DataLoader:
def _check_directory_arguments(self):
if not os.path.isdir(self.datapath):
- raise (FileNotFoundError('Directory does not exist: %s' % self.datapath))
+ raise (NotADirectoryError('Directory does not exist: %s' % self.datapath))
def _check_data_not_empty(self, images):
- print('HERE')
- print (len(images))
if len(images) == 0:
raise AssertionError('csv file does not contain samples of specified labels: %s' % str(self.target_labels))
diff --git a/tests/unittests/dataloader_test.py b/tests/unittests/dataloader_test.py
index <HASH>..<HASH> 100644
--- a/tests/unittests/dataloader_test.py
+++ b/tests/unittests/dataloader_test.py
@@ -54,19 +54,32 @@ def test_load_directory_data():
valid_directory_path = '../../examples/image_data/sample_image_directory.csv'
invalid_directory_path = 'invalid_directory_path'
- dummy_datapath = '../resources/dummy_data_directory'
+ dummy_directory = '../resources/dummy_data_directory'
+ dummy_empty_directory = '../resources/dummy_empty_data_directory'
# should raise error when receives an invalid directory path
- with pytest.raises(FileNotFoundError):
+ with pytest.raises(NotADirectoryError):
DataLoader(from_csv=False, datapath=invalid_directory_path)
# should assign an image's parent directory name as its label
- data_loader = DataLoader(from_csv=False, datapath=dummy_datapath)
+ data_loader = DataLoader(from_csv=False, datapath=dummy_directory)
images, labels, label_map = data_loader.get_data()
label_count = len(label_map.keys())
label = [0]*label_count
label[label_map['happiness']] = 1
assert label == labels[0]
-
+
+ # should raise error when tries to load empty directory
+ data_loader = DataLoader(from_csv=False, datapath=dummy_empty_directory)
+ with pytest.raises(AssertionError):
+ data_loader.get_data()
+
+ data_loader = DataLoader(from_csv=False, datapath=dummy_directory)
+ images, labels, label_map = data_loader.get_data()
+ # should return non-empty image and label arrays when given valid arguments
+ assert len(images) > 0 and len(labels) > 0
+ # should return same number of labels and images when given valid arguments
+ assert len(images) == len(labels)
+
if __name__ == '__main__':
pytest.main([__file__])
\ No newline at end of file
|
Updated tests for loading data from directory
|
thoughtworksarts_EmoPy
|
train
|
9edc9556b0e14aa1d44072b3f9ecd7a3ef6fb8ab
|
diff --git a/models/User.php b/models/User.php
index <HASH>..<HASH> 100644
--- a/models/User.php
+++ b/models/User.php
@@ -75,9 +75,18 @@ class User extends UserBase
*/
public function attemptActivation($code)
{
- $result = parent::attemptActivation($code);
- if ($result === false) {
- return false;
+ if ($this->trashed()) {
+ if ($code == $this->activation_code) {
+ $this->restore();
+ } else {
+ return false;
+ }
+ } else {
+ $result = parent::attemptActivation($code);
+
+ if ($result === false) {
+ return false;
+ }
}
Event::fire('rainlab.user.activate', [$this]);
|
Fix reactiving of soft-deleted users
The deactivate user action soft-deletes users in the DB. This allows the `attemptActivation()` method to restore users who were deactivated this way.
Fixes #<I>.
|
rainlab_user-plugin
|
train
|
e1387e97348a69273ab5b06192176b824c50c820
|
diff --git a/tests/FluentDOM/XMLWriterTest.php b/tests/FluentDOM/XMLWriterTest.php
index <HASH>..<HASH> 100644
--- a/tests/FluentDOM/XMLWriterTest.php
+++ b/tests/FluentDOM/XMLWriterTest.php
@@ -5,6 +5,9 @@ namespace FluentDOM {
class XMLWriterTest extends TestCase {
+ /**
+ * @covers \FluentDOM\XMLWriter
+ */
public function testWriteSomeHtmlWithoutNamespacs() {
$_ = new XMLWriter();
$_->openMemory();
@@ -29,6 +32,9 @@ namespace FluentDOM {
);
}
+ /**
+ * @covers \FluentDOM\XMLWriter
+ */
public function testWriteAtom() {
$_ = new XMLWriter();
$_->registerNamespace('atom', 'http://www.w3.org/2005/Atom');
@@ -38,7 +44,7 @@ namespace FluentDOM {
$_->startElement('atom:feed');
$_->writeElement('atom:title', 'Example Feed');
- $_->startElement('atom:link', 'Example Feed');
+ $_->startElement('atom:link');
$_->writeAttribute('href', 'http://example.org/');
$_->endElement();
$_->endElement();
@@ -54,6 +60,9 @@ namespace FluentDOM {
);
}
+ /**
+ * @covers \FluentDOM\XMLWriter
+ */
public function testWriteXmlWithAttributesInNamespace() {
$_ = new XMLWriter();
$_->registerNamespace('', 'http://example.org/xmlns/2002/document');
@@ -90,5 +99,109 @@ namespace FluentDOM {
$_->outputMemory()
);
}
+
+ /**
+ * @covers \FluentDOM\XMLWriter
+ */
+ public function testWriteElementAddingNamespace() {
+ $_ = new XMLWriter();
+ $_->registerNamespace('example', 'http://example.org/xmlns/2002/document');
+ $_->openMemory();
+ $_->startDocument();
+ $_->writeElement('example:document');
+ $_->endDocument();
+
+ $this->assertXmlStringEqualsXmlString(
+ '<?xml version="1.0"?>'.
+ '<example:document xmlns:example="http://example.org/xmlns/2002/document"/>',
+ $_->outputMemory()
+ );
+ }
+
+ /**
+ * @covers \FluentDOM\XMLWriter
+ */
+ public function testStartAttributeWithoutNamespace() {
+ $_ = new XMLWriter();
+ $_->registerNamespace('example', 'http://example.org/xmlns/2002/document');
+ $_->openMemory();
+ $_->startDocument();
+ $_->startElement('document');
+ $_->startAttribute('test');
+ $_->text('success');
+ $_->endAttribute();
+ $_->endElement();
+ $_->endDocument();
+
+ $this->assertXmlStringEqualsXmlString(
+ '<?xml version="1.0"?>'.
+ '<document test="success"/>',
+ $_->outputMemory()
+ );
+ }
+
+ /**
+ * @covers \FluentDOM\XMLWriter
+ */
+ public function testStartAttributeAddingNamespace() {
+ $_ = new XMLWriter();
+ $_->registerNamespace('example', 'http://example.org/xmlns/2002/document');
+ $_->openMemory();
+ $_->startDocument();
+ $_->startElement('document');
+ $_->startAttribute('example:test');
+ $_->text('success');
+ $_->endAttribute();
+ $_->endElement();
+ $_->endDocument();
+
+ $this->assertXmlStringEqualsXmlString(
+ '<?xml version="1.0"?>'.
+ '<document xmlns:example="http://example.org/xmlns/2002/document" example:test="success"/>',
+ $_->outputMemory()
+ );
+ }
+
+ /**
+ * @covers \FluentDOM\XMLWriter
+ */
+ public function testStartAttributeForAddedNamespace() {
+ $_ = new XMLWriter();
+ $_->registerNamespace('example', 'http://example.org/xmlns/2002/document');
+ $_->openMemory();
+ $_->startDocument();
+ $_->startElement('example:document');
+ $_->startAttribute('example:test');
+ $_->text('success');
+ $_->endAttribute();
+ $_->endElement();
+ $_->endDocument();
+
+ $this->assertXmlStringEqualsXmlString(
+ '<?xml version="1.0"?>'.
+ '<example:document xmlns:example="http://example.org/xmlns/2002/document" example:test="success"/>',
+ $_->outputMemory()
+ );
+ }
+
+ /**
+ * @covers \FluentDOM\XMLWriter
+ */
+ public function testWritettributeNSAddingNamespace() {
+ $_ = new XMLWriter();
+ $_->registerNamespace('example', 'http://example.org/xmlns/2002/document');
+ $_->openMemory();
+ $_->startDocument();
+ $_->startElement('document');
+ $_->writeAttribute('example:test', 'success');
+ $_->endElement();
+ $_->endDocument();
+
+ $this->assertXmlStringEqualsXmlString(
+ '<?xml version="1.0"?>'.
+ '<document xmlns:example="http://example.org/xmlns/2002/document" example:test="success"/>',
+ $_->outputMemory()
+ );
+ }
}
}
\ No newline at end of file
|
Tested FluentDOM\XmlWriter
|
ThomasWeinert_FluentDOM
|
train
|
68b6aa2055b795208aafcae526929e60e13beac2
|
diff --git a/molgenis-omx-biobankconnect/src/main/resources/js/ontology-tree-view.js b/molgenis-omx-biobankconnect/src/main/resources/js/ontology-tree-view.js
index <HASH>..<HASH> 100644
--- a/molgenis-omx-biobankconnect/src/main/resources/js/ontology-tree-view.js
+++ b/molgenis-omx-biobankconnect/src/main/resources/js/ontology-tree-view.js
@@ -62,9 +62,13 @@
var ontologyTerms = removeDuplicate(searchByQuery(ontology, query)).sort(function(a, b){
return molgenis.naturalSort(b.nodePath.split('.').length, a.nodePath.split('.').length);
});
- $.each(ontologyTerms, function(index, ontologyTerm){
- getParentNode(molgenisTree, ontologyTerm);
- });
+ if(ontologyTerms.length > 0){
+ $.each(ontologyTerms, function(index, ontologyTerm){
+ getParentNode(molgenisTree, ontologyTerm);
+ });
+ }else{
+ molgenis.createAlert([{'message' : 'No ontology terms are found for query "<strong>' + query + '</strong>".'}], 'error');
+ }
}
}
@@ -92,11 +96,11 @@
var molgenisTree = $('#tree-container').tree('getTree');
molgenisTree.reload();
ontologyTerm = getOntologyTerm(ontologyTerm);
+ ontologyTermInfo(ontologyTerm);
var currentNode = getParentNode(molgenisTree, ontologyTerm, true);
currentNode.setFocus();
var scroll = $(currentNode.li).position().top - $('#tree-container').position().top - $('#tree-container').height() / 3 * 2;
if(scroll > $('#tree-container').height() / 2) $('#tree-container').scrollTop(scroll);
- ontologyTermInfo(ontologyTerm);
};
function getParentNode(molgenisTree, ontologyTerm, showSibling){
@@ -110,7 +114,7 @@
var parentNode = getParentNode(molgenisTree, getParentOntologyTerm(ontologyTerm), showSibling);
//Add current node the tree
if(parentNode){
- $('#tree-container').tree('appendChildNodes', parentNode, showSibling ? removeDuplicate (parentOntologyTerm.attributes.items) : removeDuplicate([ontologyTerm]));
+ $('#tree-container').tree('appendChildNodes', parentNode, showSibling ? removeDuplicate(parentOntologyTerm.attributes.items) : removeDuplicate([ontologyTerm]));
}else{
console.log('error parent node cannot but null!');
}
@@ -152,7 +156,10 @@
uniqueNodes.push(value);
});
}
- return uniqueNodes;
+
+ return uniqueNodes.sort(function(a, b){
+ return molgenis.naturalSort(a[TREE_LABEL], b[TREE_LABEL]);
+ });
}
function getOntologyTermByIri(ontologyIRI){
diff --git a/molgenis-omx-biobankconnect/src/main/resources/js/ontology.tree.plugin.js b/molgenis-omx-biobankconnect/src/main/resources/js/ontology.tree.plugin.js
index <HASH>..<HASH> 100644
--- a/molgenis-omx-biobankconnect/src/main/resources/js/ontology.tree.plugin.js
+++ b/molgenis-omx-biobankconnect/src/main/resources/js/ontology.tree.plugin.js
@@ -86,9 +86,6 @@
},
'getTree' : function(){
return $('.molgenis-tree').fancytree('getTree');
- },
- 'locateTerm' : function(){
-
}
});
|
added error handling and sort the nodes alphabitically
|
molgenis_molgenis
|
train
|
a2b1a71e01676640434e0f0b7fc5f3ab1b9a8bde
|
diff --git a/salt/proxy/philips_hue.py b/salt/proxy/philips_hue.py
index <HASH>..<HASH> 100644
--- a/salt/proxy/philips_hue.py
+++ b/salt/proxy/philips_hue.py
@@ -119,7 +119,12 @@ def _set(lamp_id, state, method="state"):
:return:
'''
url = "{0}/lights/{1}".format(CONFIG['url'], lamp_id) + (method and "/{0}".format(method) or '')
- res = json.loads(requests.put(url, json=state).content)
+ res = None
+ try:
+ res = json.loads(requests.put(url, json=state).content)
+ except Exception, err:
+ raise CommandExecutionError(err)
+
res = len(res) > 1 and res[-1] or res[0]
if res.get('success'):
res = {'result': True}
@@ -151,7 +156,10 @@ def _get_lights():
:return:
'''
- return json.loads(requests.get(CONFIG['url'] + "/lights").content)
+ try:
+ return json.loads(requests.get(CONFIG['url'] + "/lights").content)
+ except Exception, exc:
+ raise CommandExecutionError(exc)
# Callers
|
Fix crash if the controller is down
|
saltstack_salt
|
train
|
493e53e0cb348857e3bbd61eda783c4a691f3fe1
|
diff --git a/gruntfile.js b/gruntfile.js
index <HASH>..<HASH> 100644
--- a/gruntfile.js
+++ b/gruntfile.js
@@ -85,7 +85,7 @@ function prepareGrunt(grunt) {
// grunt watch:mochaTest
mochaTest: {
files: allFiles,
- tasks: ['mochaTest:test'],
+ tasks: ['coverage'],
options:{
interrupt: true,
atBegin: true
|
changing "grunt watch" to run coverage
|
RackHD_on-core
|
train
|
dcc0642fbe0099fba90ef68c45c82cda56a87dbe
|
diff --git a/src/TricksterServiceProvider.php b/src/TricksterServiceProvider.php
index <HASH>..<HASH> 100644
--- a/src/TricksterServiceProvider.php
+++ b/src/TricksterServiceProvider.php
@@ -3,12 +3,6 @@
namespace Secrethash\Trickster;
use Illuminate\Support\ServiceProvider;
-
-use Symfony\Component\Finder\Finder;
-
-use Illuminate\Filesystem\Filesystem;
-
-
class TricksterServiceProvider extends ServiceProvider
{
@@ -21,9 +15,9 @@ class TricksterServiceProvider extends ServiceProvider
{
// loading the routes
// require __DIR__ . "/Http/routes.php";
- $this->publishes([
- __DIR__.'./config/trickster.php' => config_path('trickster.php'),
- ]);
+ $configPath = __DIR__ . '/config/trickster.php';
+ $this->publishes([$configPath => config_path('trickster.php')]);
+ $this->mergeConfigFrom($configPath, 'trickster');
}
/**
|
fix(core): publish config
|
secrethash_trickster
|
train
|
b513c08e71a0b88c430d7f06d1757dad702ba2ca
|
diff --git a/libkbfs/block_tree.go b/libkbfs/block_tree.go
index <HASH>..<HASH> 100644
--- a/libkbfs/block_tree.go
+++ b/libkbfs/block_tree.go
@@ -6,6 +6,7 @@ package libkbfs
import (
"context"
+ "fmt"
"github.com/keybase/client/go/logger"
"github.com/keybase/client/go/protocol/keybase1"
@@ -609,6 +610,45 @@ func (bt *blockTree) setParentOffsets(
return newDirtyPtrs, newUnrefs, nil
}
+func (bt *blockTree) String() string {
+ block, _, err := bt.getter(
+ nil, bt.kmd, bt.rootBlockPointer(), bt.file, blockRead)
+ if err != nil {
+ return "ERROR: " + err.Error()
+ }
+
+ level := []BlockWithPtrs{block}
+ res := "\n---------------\n"
+ for len(level) > 0 {
+ var nextLevel []BlockWithPtrs
+ for i, block := range level {
+ if !block.IsIndirect() {
+ continue
+ }
+ for j := 0; j < block.NumIndirectPtrs(); j++ {
+ info, off := block.IndirectPtr(j)
+ res += fmt.Sprintf("\"%s\" ", off)
+ if info.DirectType == DirectBlock {
+ continue
+ }
+ child, _, err := bt.getter(
+ nil, bt.kmd, info.BlockPointer, bt.file, blockRead)
+ if err != nil {
+ return "ERROR: " + err.Error()
+ }
+ nextLevel = append(nextLevel, child)
+ }
+ if i+1 < len(level) {
+ res += "| "
+ }
+ }
+ res += "\n"
+ level = nextLevel
+ }
+ res += "---------------\n"
+ return res
+}
+
// shiftBlocksToFillHole should be called after newRightBlock when the
// offset for the new block is smaller than the final offset of the
// tree. This happens when there is a hole in the file, or when
|
block_tree: useful string method to print levels of tree
Issue: KBFS-<I>
|
keybase_client
|
train
|
fc08c7a530e20ecfc056a273f084063cf805ee70
|
diff --git a/joomla/application/categories.php b/joomla/application/categories.php
index <HASH>..<HASH> 100644
--- a/joomla/application/categories.php
+++ b/joomla/application/categories.php
@@ -551,10 +551,9 @@ class JCategoryNode extends JObject
*/
function getMetadata()
{
- if(!($this->metadata instanceof JParameter))
+ if(!($this->metadata instanceof JRegistry))
{
- $this->metadata = new JParameter($this->metadata);
- //$this->metadata->loadJSON($this->metadata);
+ $this->metadata = new JRegistry($this->metadata);
}
return $this->metadata;
}
|
# Fix bug in JCategories causing failed system test
# Fix minor language issue for consistency
# Misc. fixes to system tests
--HG--
extra : convert_revision : svn%3A6f6e1ebd-4c2b-<I>-<I>f-f<I>bde<I>bce9/development/trunk/libraries%<I>
|
joomla_joomla-framework
|
train
|
9eb5cc4d460dc4184930c513066718c0c7db41fe
|
diff --git a/src/Charcoal/Admin/Widget/FormWidget.php b/src/Charcoal/Admin/Widget/FormWidget.php
index <HASH>..<HASH> 100644
--- a/src/Charcoal/Admin/Widget/FormWidget.php
+++ b/src/Charcoal/Admin/Widget/FormWidget.php
@@ -288,8 +288,7 @@ class FormWidget extends AdminWidget implements
}
if (is_array($formProperty)) {
- $formProperty = $this->getOrCreateFormProperty($propertyIdent, $formProperty);
- $formProperty->setPropertyIdent($propertyIdent);
+ $this->getOrCreateFormProperty($propertyIdent, $formProperty);
} elseif (!$formProperty instanceof FormPropertyWidget) {
throw new InvalidArgumentException(sprintf(
'Property must be an array or an instance of FormPropertyWidget, received %s',
|
Remove unnecessary ident set on newly created property
|
locomotivemtl_charcoal-admin
|
train
|
4bd6b5c526f327954034fda0f665a6e791a12a76
|
diff --git a/scheduler/ecs/ecs.go b/scheduler/ecs/ecs.go
index <HASH>..<HASH> 100644
--- a/scheduler/ecs/ecs.go
+++ b/scheduler/ecs/ecs.go
@@ -397,6 +397,8 @@ func (m *Scheduler) updateCreateService(ctx context.Context, app *scheduler.App,
return m.createService(ctx, app, p)
}
+// loadBalancer creates (or updates) a a load balancer for the given process, if
+// the process is exposed. It returns the name of the load balancer.
func (m *Scheduler) loadBalancer(ctx context.Context, app *scheduler.App, p *scheduler.Process) (string, error) {
if p.Exposure > scheduler.ExposeNone {
// Attempt to find an existing load balancer for this app.
|
Add docs to loadBalancer method.
|
remind101_empire
|
train
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.