hash
stringlengths 40
40
| diff
stringlengths 131
114k
| message
stringlengths 7
980
| project
stringlengths 5
67
| split
stringclasses 1
value |
|---|---|---|---|---|
e9f6de948faa412bae204910231c7a11055d202e
|
diff --git a/quark/ipam.py b/quark/ipam.py
index <HASH>..<HASH> 100644
--- a/quark/ipam.py
+++ b/quark/ipam.py
@@ -53,6 +53,7 @@ class QuarkIpam(object):
def allocate_ip_address(self, session, net_id, port_id):
address = session.query(models.IPAddress).\
filter(models.IPAddress.network_id == net_id).\
+ filter(models.IPAddress.port_id == None).\
filter(models.IPAddress.deallocated != 1).\
first()
if not address:
@@ -74,11 +75,12 @@ class QuarkIpam(object):
address["address"] = int(first_address)
address["address_readable"] = str(first_address)
- if address:
- address["port_id"] = port_id
address["subnet_id"] = subnet["id"]
address["network_id"] = net_id
address["tenant_id"] = subnet["tenant_id"]
+
+ if address:
+ address["port_id"] = port_id
session.add(address)
return address
raise exceptions.IpAddressGenerationFailure(net_id=net_id)
@@ -91,6 +93,7 @@ class QuarkIpam(object):
if not address:
LOG.critical("No IP assigned or already deallocated")
return
+ address["port_id"] = None
reuse_after_deallocate = kwargs.get("ipam_reuse_ip_instantly", False)
if reuse_after_deallocate:
address["deallocated"] = 0
|
Fixed allocation to not use freed ports
|
openstack_quark
|
train
|
5a03e83ceba8ab69fe8a180fa40e5686f3d97230
|
diff --git a/mungegithub/mungers/submit-queue-batch.go b/mungegithub/mungers/submit-queue-batch.go
index <HASH>..<HASH> 100644
--- a/mungegithub/mungers/submit-queue-batch.go
+++ b/mungegithub/mungers/submit-queue-batch.go
@@ -267,9 +267,9 @@ func (sq *SubmitQueue) batchIsApplicable(batch Batch) (int, error) {
func (sq *SubmitQueue) handleGithubE2EBatchMerge() {
repo := sq.githubConfig.Org + "/" + sq.githubConfig.Project
for range time.Tick(1 * time.Minute) {
- allJobs, err := getJobs(sq.ProwDataURL)
+ allJobs, err := getJobs(sq.ProwURL)
if err != nil {
- glog.Errorf("Error reading batch jobs from Prow URL %v: %v", sq.ProwDataURL, err)
+ glog.Errorf("Error reading batch jobs from Prow URL %v: %v", sq.ProwURL, err)
continue
}
batchJobs := allJobs.batch().repo(repo)
|
fix nit-refactor of prow url var in submit-queue-batch.go
|
kubernetes_test-infra
|
train
|
faa664df8116ad8fd5570aac4561b8ed61886577
|
diff --git a/pysos/sos_script.py b/pysos/sos_script.py
index <HASH>..<HASH> 100755
--- a/pysos/sos_script.py
+++ b/pysos/sos_script.py
@@ -402,6 +402,10 @@ def directive_output(*args, **kwargs):
#
if 'pattern' in kwargs:
handle_output_pattern(kwargs['pattern'], ofiles)
+ for ofile in ofiles:
+ parent_dir = os.path.split(os.path.expanduser(ofile))[0]
+ if parent_dir and not os.path.isdir(parent_dir):
+ os.makedirs(parent_dir)
env.sos_dict.set('_output', ofiles)
def directive_process(**kwargs):
@@ -904,10 +908,6 @@ class SoS_Step:
signature = RuntimeInfo(step_sig,
env.sos_dict['input'], env.sos_dict['output'], env.sos_dict['depends'])
if env.run_mode == 'run':
- for ofile in env.sos_dict['output']:
- parent_dir = os.path.split(os.path.expanduser(ofile))[0]
- if parent_dir and not os.path.isdir(parent_dir):
- os.makedirs(parent_dir)
if env.sig_mode == 'default':
if signature.validate():
# everything matches
|
Create output directory earlier to accomodate non-step process statements
|
vatlab_SoS
|
train
|
a31f3491ca25db50b5a253b30fee2ade2ae6bd9f
|
diff --git a/lib/Threading/Thread.php b/lib/Threading/Thread.php
index <HASH>..<HASH> 100644
--- a/lib/Threading/Thread.php
+++ b/lib/Threading/Thread.php
@@ -143,19 +143,21 @@ class Thread implements Strand {
list($channel, $this->socket) = $sockets;
- $this->thread = $thread = new Internal\Thread($this->socket, $this->function, $this->args);
+ $this->thread = new Internal\Thread($this->socket, $this->function, $this->args);
if (!$this->thread->start(PTHREADS_INHERIT_INI)) {
throw new ContextException('Failed to start the thread.');
}
- $this->channel = $channel = new ChannelledSocket($channel, $channel);
+ $this->channel = new ChannelledSocket($channel, $channel);
- $this->watcher = Loop::repeat(self::EXIT_CHECK_FREQUENCY, static function () use ($thread, $channel) {
- if (!$thread->isRunning()) {
- $channel->close();
+ $this->watcher = Loop::repeat(self::EXIT_CHECK_FREQUENCY, function () {
+ if (!$this->thread->isRunning()) {
+ $this->channel->close();
}
});
+
+ Loop::disable($this->watcher);
}
/**
@@ -200,6 +202,7 @@ class Thread implements Strand {
*
* @throws StatusError Thrown if the context has not been started.
* @throws SynchronizationError Thrown if an exit status object is not received.
+ * @throws ContextException If the context stops responding.
*/
public function join(): Promise {
if ($this->channel == null || $this->thread === null) {
@@ -214,9 +217,12 @@ class Thread implements Strand {
*
* @return \Generator
*
- * @throws \Amp\Parallel\SynchronizationError If the thread does not send an exit status.
+ * @throws SynchronizationError If the thread does not send an exit status.
+ * @throws ContextException If the context stops responding.
*/
private function doJoin(): \Generator {
+ Loop::enable($this->watcher);
+
try {
$response = yield $this->channel->receive();
@@ -232,6 +238,7 @@ class Thread implements Strand {
$this->kill();
throw $exception;
} finally {
+ Loop::disable($this->watcher);
$this->close();
}
@@ -250,12 +257,16 @@ class Thread implements Strand {
}
private function doReceive() {
+ Loop::enable($this->watcher);
+
try {
$data = yield $this->channel->receive();
} catch (ChannelException $exception) {
throw new ContextException(
"The context stopped responding, potentially due to a fatal error or calling exit", 0, $exception
);
+ } finally {
+ Loop::disable($this->watcher);
}
if ($data instanceof ExitResult) {
|
Only check for exit when receiving, fixes #9
|
amphp_parallel
|
train
|
e684baf3508857890e82fee99629b43c8ec46414
|
diff --git a/js/core/Component.js b/js/core/Component.js
index <HASH>..<HASH> 100644
--- a/js/core/Component.js
+++ b/js/core/Component.js
@@ -35,6 +35,7 @@ define(["require", "js/core/Element", "js/core/TextElement", "js/core/Bindable",
this.$xamlAttributes = this._getAttributesFromDescriptor(descriptor);
}
+
this.$elements = [];
this.$templates = {};
this.$configurations = [];
@@ -373,11 +374,11 @@ define(["require", "js/core/Element", "js/core/TextElement", "js/core/Bindable",
},
_isEventAttribute: function (attributeName) {
- return attributeName.indexOf("on:") == 0;
+ return attributeName.indexOf("eventHandler:") === 0;
},
_isXamlEventAttribute: function(attributeName){
- return attributeName.indexOf("on") == 0;
+ return attributeName.indexOf("on") === 0;
},
_getEventName: function(eventDefinition){
@@ -415,6 +416,8 @@ define(["require", "js/core/Element", "js/core/TextElement", "js/core/Bindable",
} else {
throw "Couldn't find callback " + value + " for " + key + " event";
}
+ } else if (this._isEventAttribute(key)) {
+ this.bind(key.split(":")[1], rootScope[value]);
}
}
}
diff --git a/js/core/Element.js b/js/core/Element.js
index <HASH>..<HASH> 100644
--- a/js/core/Element.js
+++ b/js/core/Element.js
@@ -1,7 +1,10 @@
define(["js/core/Bindable", "underscore", "js/core/BindingCreator"], function (Bindable, _, BindingCreator) {
- var undefined;
- var bindingCreator = new BindingCreator();
+ var undefined,
+ bindingCreator = new BindingCreator(),
+ prefixMap = {
+ "type:eventHandler": "eventHandler:"
+ };
function stringToPrimitive(str) {
// if it's not a string
@@ -68,6 +71,13 @@ define(["js/core/Bindable", "underscore", "js/core/BindingCreator"], function (B
// don't add xmlns attributes
if(node.nodeName.indexOf("xmlns") !== 0){
localName = this._getLocalNameFromNode(node);
+
+ var prefix = prefixMap[node.namespaceURI];
+
+ if (prefix) {
+ localName = prefix + localName;
+ }
+
attributes[localName] = stringToPrimitive(node.value);
if (node.namespaceURI) {
|
added xaml notation for non DOM event handlers
|
rappid_rAppid.js
|
train
|
48ffeaac2e392badf0eb9e7df62baa5e89148a73
|
diff --git a/structr-modules/structr-api-builder-module/src/main/java/org/structr/flow/deployment/FlowTreeDeploymentHandler.java b/structr-modules/structr-api-builder-module/src/main/java/org/structr/flow/deployment/FlowTreeDeploymentHandler.java
index <HASH>..<HASH> 100644
--- a/structr-modules/structr-api-builder-module/src/main/java/org/structr/flow/deployment/FlowTreeDeploymentHandler.java
+++ b/structr-modules/structr-api-builder-module/src/main/java/org/structr/flow/deployment/FlowTreeDeploymentHandler.java
@@ -19,6 +19,7 @@
package org.structr.flow.deployment;
import com.google.gson.Gson;
+import com.google.gson.GsonBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.structr.common.error.FrameworkException;
@@ -34,6 +35,7 @@ import org.structr.flow.impl.FlowContainerConfiguration;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
+import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;
@@ -41,9 +43,9 @@ import java.util.TreeMap;
public class FlowTreeDeploymentHandler implements FlowDeploymentInterface{
private static final Logger logger = LoggerFactory.getLogger(FlowTreeDeploymentHandler.class.getName());
- private static final Gson gson = new Gson();
+ private static final Gson gson = new GsonBuilder().setPrettyPrinting().create();
- public final static String FLOW_DEPLOYMENT_TREE_BASE_FOLDER = "flows";
+ public final static String FLOW_DEPLOYMENT_TREE_BASE_FOLDER = "flows";
private final static String FLOW_DEPLOYMENT_TREE_REL_FOLDER = "rels";
private final static String FLOW_DEPLOYMENT_TREE_NODE_FOLDER = "nodes";
private final static String FLOW_DEPLOYMENT_TREE_NODE_SCRIPTS_FOLDER = "scripts";
@@ -55,6 +57,7 @@ public class FlowTreeDeploymentHandler implements FlowDeploymentInterface{
private final static String FLOW_DEPLOYMENT_REL_FILE = "rel.json";
private final static String FLOW_DEPLOYMENT_CONFIG_FILE = "config.json";
+ private static final String[] FLOW_BLACKLISTED_REL_TYPES = {"OWNS","SECURITY"};
private static final String[] FLOW_SCRIPT_ATTRIBUTES = {"query", "script", "result"};
@@ -181,7 +184,9 @@ public class FlowTreeDeploymentHandler implements FlowDeploymentInterface{
// Remove scripts from exportData and export them seperately
for (final String key : FLOW_SCRIPT_ATTRIBUTES) {
if (exportData.containsKey(key)) {
- scriptData.put(key, exportData.get(key).toString());
+ if (exportData.get(key) != null) {
+ scriptData.put(key, exportData.get(key).toString());
+ }
exportData.remove(key);
}
}
@@ -219,15 +224,19 @@ public class FlowTreeDeploymentHandler implements FlowDeploymentInterface{
try {
- final Path relPath = Files.createDirectories(target.resolve(rel.getUuid()));
+ if (!Arrays.asList(FLOW_BLACKLISTED_REL_TYPES).contains(rel.getRelType().name())) {
+
+ final Path relPath = Files.createDirectories(target.resolve(rel.getUuid()));
- Map<String, String> attrs = new TreeMap<>();
- attrs.put("type", rel.getClass().getSimpleName());
- attrs.put("relType", ((RelationshipInterface) rel).getRelType().name());
- attrs.put("sourceId", ((RelationshipInterface) rel).getSourceNodeId());
- attrs.put("targetId", ((RelationshipInterface) rel).getTargetNodeId());
+ Map<String, String> attrs = new TreeMap<>();
+ attrs.put("type", rel.getClass().getSimpleName());
+ attrs.put("relType", ((RelationshipInterface) rel).getRelType().name());
+ attrs.put("sourceId", ((RelationshipInterface) rel).getSourceNodeId());
+ attrs.put("targetId", ((RelationshipInterface) rel).getTargetNodeId());
- writeData(relPath.resolve(FLOW_DEPLOYMENT_REL_FILE), gson.toJson(attrs));
+ writeData(relPath.resolve(FLOW_DEPLOYMENT_REL_FILE), gson.toJson(attrs));
+
+ }
} catch (IOException ex) {
diff --git a/structr-ui/src/main/resources/structr/js/flows.js b/structr-ui/src/main/resources/structr/js/flows.js
index <HASH>..<HASH> 100644
--- a/structr-ui/src/main/resources/structr/js/flows.js
+++ b/structr-ui/src/main/resources/structr/js/flows.js
@@ -402,7 +402,7 @@ var _Flows = {
if (name.indexOf(".") !== -1) {
dataObject.effectiveName = name;
} else {
- dataObject.name = name;
+ dataObject.name = name;
}
if (id !== null) {
|
Implements blacklist for flow rel types during export.
|
structr_structr
|
train
|
8cc94fba5050981338b0908488c54e69cbe4c0a8
|
diff --git a/dyno-core/src/main/java/com/netflix/dyno/connectionpool/impl/ConnectionPoolConfigurationImpl.java b/dyno-core/src/main/java/com/netflix/dyno/connectionpool/impl/ConnectionPoolConfigurationImpl.java
index <HASH>..<HASH> 100644
--- a/dyno-core/src/main/java/com/netflix/dyno/connectionpool/impl/ConnectionPoolConfigurationImpl.java
+++ b/dyno-core/src/main/java/com/netflix/dyno/connectionpool/impl/ConnectionPoolConfigurationImpl.java
@@ -43,7 +43,7 @@ public class ConnectionPoolConfigurationImpl implements ConnectionPoolConfigurat
private static final boolean DEFAULT_LOCAL_DC_AFFINITY = true;
private static final LoadBalancingStrategy DEFAULT_LB_STRATEGY = LoadBalancingStrategy.TokenAware;
private static final String DEFAULT_CONFIG_PUBLISHER_ADDRESS = null;
- private static final boolean DEFAULT_FAIL_ON_STARTUP_IFNOHOSTS = false;
+ private static final boolean DEFAULT_FAIL_ON_STARTUP_IFNOHOSTS = true;
private static final int DEFAULT_FAIL_ON_STARTUP_IFNOHOSTS_SECONDS = 60;
private HostSupplier hostSupplier;
|
Modified failOnStartupIfNoHosts property so that the default value is true (instead of false).
|
Netflix_dyno
|
train
|
0699c75030c93721e284903c2cae9591ce38f041
|
diff --git a/src/LeanOrm/Model/Collection.php b/src/LeanOrm/Model/Collection.php
index <HASH>..<HASH> 100644
--- a/src/LeanOrm/Model/Collection.php
+++ b/src/LeanOrm/Model/Collection.php
@@ -21,16 +21,26 @@ class Collection extends \GDAO\Model\Collection
}
public function deleteAll() {
-
- foreach ($this->_data as $record) {
-
- try {
- $this->getModel()->deleteSpecifiedRecord($record);
-
- } catch(\Exception $e) {
-
- throw $e;
+
+ try {
+ $model = $this->getModel();
+
+ if( $model instanceof \GDAO\Model ) {
+
+ $pri_col_name = $model->getPrimaryColName();
+ $pri_key_vals = $this->getColVals($pri_col_name);
+
+ if( count($pri_key_vals) > 0 ) {
+
+ //where pri_key in (.....)
+ $where_params = array($pri_col_name => $pri_key_vals);
+ $model->deleteRecordsMatchingSpecifiedColsNValues($where_params);
+ }
}
+
+ } catch(\Exception $e) {
+
+ throw $e;
}
unset($this->_data);
|
Re-implemented delete all in the collection to be more efficient.
|
rotexsoft_leanorm
|
train
|
3d7410bb5ead316179c95da8c379e21fd9f16015
|
diff --git a/lib/Doctrine/CouchDB/HTTP/SocketClient.php b/lib/Doctrine/CouchDB/HTTP/SocketClient.php
index <HASH>..<HASH> 100644
--- a/lib/Doctrine/CouchDB/HTTP/SocketClient.php
+++ b/lib/Doctrine/CouchDB/HTTP/SocketClient.php
@@ -100,7 +100,7 @@ class SocketClient extends AbstractHTTPClient
{
$request .= "Content-type: application/json\r\n";
$request .= "Content-Length: " . strlen( $data ) . "\r\n\r\n";
- $request .= "$data\r\n";
+ $request .= "$data";
}
else
{
|
Fixed wrong line ending in SocketClient for CouchDB <I>
|
doctrine_couchdb-odm
|
train
|
42d9d673f0de4bf1b607a6aeef8846046e8f065c
|
diff --git a/lib/data_mapper.rb b/lib/data_mapper.rb
index <HASH>..<HASH> 100644
--- a/lib/data_mapper.rb
+++ b/lib/data_mapper.rb
@@ -111,4 +111,8 @@ module DataMapper
def self.auto_migrate!(name = :default)
repository(name).auto_migrate!
end
+
+ def self.prepare(name = nil, &blk)
+ yield repository(name)
+ end
end
diff --git a/lib/data_mapper/repository.rb b/lib/data_mapper/repository.rb
index <HASH>..<HASH> 100644
--- a/lib/data_mapper/repository.rb
+++ b/lib/data_mapper/repository.rb
@@ -18,7 +18,7 @@ module DataMapper
:default
end
- attr_reader :name, :adapter
+ attr_reader :name, :adapter, :type_map
def identity_map_get(model, key)
@identity_map.get(model, key)
@@ -101,6 +101,10 @@ module DataMapper
def to_s
"#<DataMapper::Repository:#{@name}>"
end
+
+ def map(*args)
+ @type_map.map(*args)
+ end
private
@@ -110,6 +114,7 @@ module DataMapper
@name = name
@adapter = self.class.adapters[name]
@identity_map = IdentityMap.new
+ @type_map = TypeMap.new(@adapter.type_map)
end
end # class Repository
diff --git a/spec/unit/repository_spec.rb b/spec/unit/repository_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/unit/repository_spec.rb
+++ b/spec/unit/repository_spec.rb
@@ -69,4 +69,13 @@ describe DataMapper::Repository do
repository.auto_migrate!
end
end
+
+ describe "#map" do
+ it "should call @type_map.map with the arguments" do
+ repository = repository(:repository_spec)
+ repository.type_map.should_receive(:map).with(:type, :arg)
+
+ repository.map(:type, :arg)
+ end
+ end
end
|
Added Repository#type_map & Repository#map. Added DataMapper#prepare
|
datamapper_dm-core
|
train
|
d2f78ae41346ef60823e8640ba697afdb89aea20
|
diff --git a/lib/rapns/daemon/delivery_handler.rb b/lib/rapns/daemon/delivery_handler.rb
index <HASH>..<HASH> 100644
--- a/lib/rapns/daemon/delivery_handler.rb
+++ b/lib/rapns/daemon/delivery_handler.rb
@@ -37,7 +37,6 @@ module Rapns
begin
deliver(notification)
- reflect(:notification_delivered, notification)
rescue StandardError => e
Rapns.logger.error(e)
reflect(:error, e)
|
Remove duplicate call to notification_delivered reflection. Fixes #<I>.
|
ileitch_rapns
|
train
|
e56d8c8982461b407876dda913d2fa57548621a3
|
diff --git a/aegea/ssh.py b/aegea/ssh.py
index <HASH>..<HASH> 100644
--- a/aegea/ssh.py
+++ b/aegea/ssh.py
@@ -186,7 +186,7 @@ def scp(args):
"""
Transfer files to or from EC2 instance.
"""
- scp_opts = extract_passthrough_opts(args, "scp")
+ scp_opts, host_opts = extract_passthrough_opts(args, "scp"), []
user_or_hostname_chars = string.ascii_letters + string.digits
for i, arg in enumerate(args.scp_args):
if arg[0] in user_or_hostname_chars and ":" in arg:
|
aegea scp: Do not crash if no colon is found
|
kislyuk_aegea
|
train
|
591ed4b39167daea0eaceca7cf7d79802fd47bd1
|
diff --git a/gidgethub/test/test_aiohttp.py b/gidgethub/test/test_aiohttp.py
index <HASH>..<HASH> 100644
--- a/gidgethub/test/test_aiohttp.py
+++ b/gidgethub/test/test_aiohttp.py
@@ -7,12 +7,6 @@ from .. import aiohttp as gh_aiohttp
from .. import sansio
-async def call_aiohttp(what, *args, **kwargs):
- async with aiohttp.ClientSession() as session:
- gh = gh_aiohttp.GitHubAPI(session, "gidgethub")
- return await getattr(gh, what)(*args, **kwargs)
-
-
@pytest.mark.asyncio
async def test_sleep():
delay = 1
|
Delete call_aiohttp() (#8)
|
brettcannon_gidgethub
|
train
|
75a193d1dd81bd246c86d05491441ee3b6d80104
|
diff --git a/lib/eye/dsl/validation.rb b/lib/eye/dsl/validation.rb
index <HASH>..<HASH> 100644
--- a/lib/eye/dsl/validation.rb
+++ b/lib/eye/dsl/validation.rb
@@ -39,7 +39,9 @@ module Eye::Dsl::Validation
end
if self.variants[param]
- raise Error, "#{value.inspect} should within #{self.variants[param].inspect}" if value && !self.variants[param].include?(value)
+ if value && !value.is_a?(Proc) && !self.variants[param].include?(value)
+ raise Error, "#{value.inspect} should within #{self.variants[param].inspect}"
+ end
end
next if types.blank?
|
# not checking proc with params list
|
kostya_eye
|
train
|
6b3cac04fa08293dec03fadaec4d307cd63878f8
|
diff --git a/lib/loader/loader.rb b/lib/loader/loader.rb
index <HASH>..<HASH> 100644
--- a/lib/loader/loader.rb
+++ b/lib/loader/loader.rb
@@ -33,7 +33,7 @@ module Myreplicator
metadata.each do |m|
if m.export_type == "initial"
-
+ Kernel.p m
initials << m # Add initial to the list
metadata.delete(m) # Delete obj from mixed list
@@ -62,6 +62,8 @@ module Myreplicator
procs.each do |proc|
p.queue << {:params => [], :block => proc}
end
+
+ p.run
end
##
@@ -73,9 +75,8 @@ module Myreplicator
initials.each do |metadata|
procs << Proc.new {
- puts metadata.table
Log.run(:job_type => "loader",
- :name => "initial_import",
+ :name => "#{metadata.export_type}_import",
:file => metadata.filename,
:export_id => metadata.export_id) do |log|
@@ -130,7 +131,7 @@ module Myreplicator
incrementals.each do |md|
if metadata.equals(md)
group << md
- metadata.delete(md) # remove from main array
+ incrementals.delete(md) # remove from main array
end
end
diff --git a/lib/transporter/parallelizer.rb b/lib/transporter/parallelizer.rb
index <HASH>..<HASH> 100644
--- a/lib/transporter/parallelizer.rb
+++ b/lib/transporter/parallelizer.rb
@@ -45,12 +45,13 @@ module Myreplicator
sleep 1
end
end
-
+
+ # Run manager if thread size never reached max
manage_threads unless @manager_running
# Waits until all threads are completed
# Before exiting
- while !@done
+ while !done?
sleep 1
end
@@ -73,7 +74,7 @@ module Myreplicator
# If no more jobs are left, mark done
- if @queue.size == 0 && @threads.size == 0
+ if done?
@done = true
else
sleep 2 # Wait for more threads to spawn
@@ -83,5 +84,16 @@ module Myreplicator
end
end
+ ##
+ # Returns true when all jobs are processed and
+ # no thread is running
+ ##
+ def done?
+ if @queue.size == 0 && @threads.size == 0
+ return true
+ end
+ return false
+ end
+
end
end
diff --git a/lib/transporter/transporter.rb b/lib/transporter/transporter.rb
index <HASH>..<HASH> 100644
--- a/lib/transporter/transporter.rb
+++ b/lib/transporter/transporter.rb
@@ -36,9 +36,6 @@ module Myreplicator
##
# Connects to all unique database servers
# downloads export files concurrently from multiple sources
-
- # TO DO: Clean up after transfer job is done
-
##
def self.transfer
unique_jobs = Export.where("state != 'failed' and active = 1").group("source_schema")
@@ -62,7 +59,7 @@ module Myreplicator
# Gives the queue to parallelizer library to download in parallel
##
def self.parallel_download export, ssh, files
- p = Parallelizer.new(:klass => "Transporter")
+ p = Parallelizer.new(:klass => "Myreplicator::Transporter")
files.each do |filename|
puts filename
@@ -100,6 +97,9 @@ module Myreplicator
:file => dump_file, :export_id => export.id) do |log|
puts "Downloading #{dump_file}"
sftp.download!(dump_file, File.join(tmp_dir, dump_file.split("/").last))
+ # clear files
+ ssh.exec!("rm #{json_file}")
+ ssh.exec!("rm #{dump_file}")
end
end
}
@@ -135,9 +135,10 @@ module Myreplicator
##
# Command for list of done files
+ # Grep -s used to supress error messages
##
def self.get_done_files export
- cmd = "cd #{Myreplicator.configs[export.source_schema]["ssh_tmp_dir"]}; grep -l export_completed *.json"
+ cmd = "cd #{Myreplicator.configs[export.source_schema]["ssh_tmp_dir"]}; grep -ls export_completed *.json"
end
end
|
loader tested with new concurrent loads, parallelizer modified on exits to not depend on the thread. Transporter bug fixed, clean ups happen on both transporter and loader
|
Raybeam_myreplicator
|
train
|
b1c479c0f7df8bdcd050f51067073c4cec121a5c
|
diff --git a/tests/test_wsaa_crypto.py b/tests/test_wsaa_crypto.py
index <HASH>..<HASH> 100644
--- a/tests/test_wsaa_crypto.py
+++ b/tests/test_wsaa_crypto.py
@@ -1,5 +1,7 @@
import base64, subprocess
+from past.builtins import basestring
+
from pyafipws.wsaa import WSAA
@@ -9,7 +11,7 @@ def test_wsfev1_create_tra():
# TODO: return string
tra = tra.decode("utf8")
# sanity checks:
- assert isinstance(tra, str)
+ assert isinstance(tra, basestring)
assert tra.startswith(
'<?xml version="1.0" encoding="UTF-8"?>'
'<loginTicketRequest version="1.0">'
|
WSAA: fix TRA test expecting unicode in python2
|
reingart_pyafipws
|
train
|
d40c6222861d5cdff3100faf04c7c325118be743
|
diff --git a/spyderlib/widgets/externalshell/sitecustomize.py b/spyderlib/widgets/externalshell/sitecustomize.py
index <HASH>..<HASH> 100644
--- a/spyderlib/widgets/externalshell/sitecustomize.py
+++ b/spyderlib/widgets/externalshell/sitecustomize.py
@@ -85,7 +85,8 @@ except ImportError:
basestring = (str,)
def execfile(filename, namespace):
# Open a source file correctly, whatever its encoding is
- exec(compile(open(filename, 'rb').read(), filename, 'exec'), namespace)
+ with open(filename, 'rb') as f:
+ exec(compile(f.read(), filename, 'exec'), namespace)
#==============================================================================
|
Consoles: Correctly close a file when executing it on Python 3
Fixes #<I>
|
spyder-ide_spyder
|
train
|
30954fe9e5fa31aa84f03e66a570afbde9c83b5b
|
diff --git a/test/aggregate_tests.rb b/test/aggregate_tests.rb
index <HASH>..<HASH> 100644
--- a/test/aggregate_tests.rb
+++ b/test/aggregate_tests.rb
@@ -25,7 +25,7 @@ class TestSensuAggregate < TestCase
assert_equal('check_http', body.first[:check])
assert(body.first[:issued].is_a?(Array))
check_issued = body.first[:issued].first
- uri = '/aggregates/check_http/' + check_issued + '?summarize=output'
+ uri = '/aggregates/check_http/' + check_issued + '?results=true&summarize=output'
api_request(uri) do |http, body|
assert_equal(200, http.response_header.status)
assert(body.is_a?(Hash))
@@ -34,6 +34,8 @@ class TestSensuAggregate < TestCase
assert_equal(1, body[:warning])
assert(body[:outputs].is_a?(Hash))
assert_equal(2, body[:outputs].size)
+ assert(body[:results].is_a?(Array))
+ assert_equal(2, body[:results].size)
done
end
end
|
[aggregates] added results to aggregate test
|
sensu_sensu
|
train
|
9a94293b591fcfb629cac6bb36d424361671562b
|
diff --git a/go/kbfs/libkbfs/conflict_resolver.go b/go/kbfs/libkbfs/conflict_resolver.go
index <HASH>..<HASH> 100644
--- a/go/kbfs/libkbfs/conflict_resolver.go
+++ b/go/kbfs/libkbfs/conflict_resolver.go
@@ -7,6 +7,7 @@ package libkbfs
import (
"encoding/json"
"fmt"
+ "io/ioutil"
"os"
sysPath "path"
"runtime/debug"
@@ -3334,6 +3335,57 @@ func (cr *ConflictResolver) recordFinishResolve(
err = serializeAndPutConflicts(cr.config, db, key, conflictsSoFar)
}
+func (cr *ConflictResolver) makeDirtyBcache(
+ ctx context.Context, kmd KeyMetadata) (
+ dirtyBcache DirtyBlockCacheSimple, cleanupFn func(context.Context),
+ err error) {
+ var dbc *DiskBlockCacheLocal
+ if cr.config.IsTestMode() {
+ // Enable the disk limiter if one doesn't exist yet.
+ _ = cr.config.(*ConfigLocal).EnableDiskLimiter(os.TempDir())
+
+ dbc, err = newDiskBlockCacheLocalForTest(
+ cr.config, syncCacheLimitTrackerType)
+ if err != nil {
+ return nil, nil, err
+ }
+ cleanupFn = dbc.Shutdown
+ } else {
+ tempDir, err := ioutil.TempDir(cr.config.StorageRoot(), "kbfscr")
+ if err != nil {
+ return nil, nil, err
+ }
+ dirCleanupFn := func(_ context.Context) {
+ err := os.RemoveAll(tempDir)
+ if err != nil {
+ cr.log.CDebugf(ctx, "Error cleaning up tempdir %s: %+v",
+ tempDir, err)
+ }
+ }
+ dbc, err = newDiskBlockCacheLocal(
+ cr.config, crDirtyBlockCacheLimitTrackerType, tempDir)
+ if err != nil {
+ dirCleanupFn(ctx)
+ return nil, nil, err
+ }
+ cleanupFn = func(ctx context.Context) {
+ dbc.Shutdown(ctx)
+ dirCleanupFn(ctx)
+ }
+ }
+
+ err = dbc.WaitUntilStarted()
+ if err != nil {
+ if cleanupFn != nil {
+ cleanupFn(ctx)
+ }
+ return nil, nil, err
+ }
+
+ dirtyBcache = newDirtyBlockCacheDisk(cr.config, dbc, kmd, cr.fbo.branch())
+ return dirtyBcache, cleanupFn, nil
+}
+
// CRWrapError wraps an error that happens during conflict resolution.
type CRWrapError struct {
err error
@@ -3572,8 +3624,14 @@ func (cr *ConflictResolver) doResolve(ctx context.Context, ci conflictInput) {
// references for all indirect pointers inside it. If it is not
// an indirect block, just add a new reference to the block.
newFileBlocks := make(fileBlockMap)
- dirtyBcache := simpleDirtyBlockCacheStandard()
- // Simple dirty bcaches don't need to be shut down.
+ dirtyBcache, cleanupFn, err := cr.makeDirtyBcache(
+ ctx, mergedChains.mostRecentChainMDInfo)
+ if err != nil {
+ return
+ }
+ if cleanupFn != nil {
+ defer cleanupFn(ctx)
+ }
err = cr.doActions(ctx, lState, unmergedChains, mergedChains,
unmergedPaths, mergedPaths, actionMap, lbc, newFileBlocks, dirtyBcache)
|
cr: use a disk-based dirty bcache
Issue: KBFS-<I>
|
keybase_client
|
train
|
dd6d2243b34fd05e6ade789a3adad2e51394d90b
|
diff --git a/example/idp2/idp.py b/example/idp2/idp.py
index <HASH>..<HASH> 100755
--- a/example/idp2/idp.py
+++ b/example/idp2/idp.py
@@ -831,7 +831,7 @@ def info_from_cookie(kaka):
try:
key, ref = base64.b64decode(morsel.value).split(":")
return IDP.cache.uid2user[key], ref
- except KeyError:
+ except (KeyError, TypeError):
return None, None
else:
logger.debug("No idpauthn cookie")
diff --git a/example/idp2/idp_uwsgi.py b/example/idp2/idp_uwsgi.py
index <HASH>..<HASH> 100755
--- a/example/idp2/idp_uwsgi.py
+++ b/example/idp2/idp_uwsgi.py
@@ -777,7 +777,7 @@ def info_from_cookie(kaka):
try:
key, ref = base64.b64decode(morsel.value).split(":")
return IDP.cache.uid2user[key], ref
- except KeyError:
+ except (TypeError, KeyError):
return None, None
else:
logger.debug("No idpauthn cookie")
diff --git a/example/idp2_repoze/idp.py b/example/idp2_repoze/idp.py
index <HASH>..<HASH> 100755
--- a/example/idp2_repoze/idp.py
+++ b/example/idp2_repoze/idp.py
@@ -758,7 +758,7 @@ def info_from_cookie(kaka):
try:
key, ref = base64.b64decode(morsel.value).split(":")
return IDP.cache.uid2user[key], ref
- except KeyError:
+ except (KeyError, TypeError):
return None, None
else:
logger.debug("No idpauthn cookie")
|
Handle b<I>decode exception. Proposed by Seth Arnold.
|
IdentityPython_pysaml2
|
train
|
20d880a88fdddc6efd586b55fe9926aa07a215a7
|
diff --git a/lib-dempsyapi/src/main/java/com/nokia/dempsy/annotations/Output.java b/lib-dempsyapi/src/main/java/com/nokia/dempsy/annotations/Output.java
index <HASH>..<HASH> 100644
--- a/lib-dempsyapi/src/main/java/com/nokia/dempsy/annotations/Output.java
+++ b/lib-dempsyapi/src/main/java/com/nokia/dempsy/annotations/Output.java
@@ -16,10 +16,7 @@
package com.nokia.dempsy.annotations;
-import java.lang.annotation.ElementType;
-import java.lang.annotation.Retention;
-import java.lang.annotation.RetentionPolicy;
-import java.lang.annotation.Target;
+import java.lang.annotation.*;
/**
@@ -33,6 +30,7 @@ import java.lang.annotation.Target;
*/
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
+@Inherited
public @interface Output
{
// nothing to see here, move along
|
Make @Output also use @Inherited as well
|
Dempsy_dempsy
|
train
|
fefe791600ece44c118ff577984facc54daae791
|
diff --git a/lib/ood_core/job/adapters/torque.rb b/lib/ood_core/job/adapters/torque.rb
index <HASH>..<HASH> 100644
--- a/lib/ood_core/job/adapters/torque.rb
+++ b/lib/ood_core/job/adapters/torque.rb
@@ -201,7 +201,12 @@ module OodCore
# @see Adapter#info
def info(id)
id = id.to_s
- parse_job_info(*@pbs.get_job(id).flatten)
+
+ result = @pbs.get_job(id)
+
+ return parse_job_info(*result.flatten) if result.keys.length == 1
+
+ parse_job_array(id, result)
rescue PBS::UnkjobidError
# set completed status if can't find job id
Info.new(
@@ -295,8 +300,26 @@ module OodCore
end
end
+ def parse_job_array(parent_id, result)
+ child_task_statuses = []
+ results = result.to_a
+
+ # Master tasks don't actually run on a host
+ parent_task = results.first.last
+ parent_task.delete(:exec_host)
+
+ results.map do |key, value|
+ child_task_statuses << {
+ :id => key,
+ :status => STATE_MAP.fetch(value[:job_state], :undetermined)
+ }
+ end
+
+ parse_job_info(parent_id, parent_task, child_task_statuses: child_task_statuses)
+ end
+
# Parse hash describing PBS job status
- def parse_job_info(k, v)
+ def parse_job_info(k, v, child_task_statuses: [])
/^(?<job_owner>[\w-]+)@/ =~ v[:Job_Owner]
allocated_nodes = parse_nodes(v[:exec_host] || "")
procs = allocated_nodes.inject(0) { |sum, x| sum + x[:procs] }
@@ -324,7 +347,8 @@ module OodCore
cpu_time: duration_in_seconds(v.fetch(:resources_used, {})[:cput]),
submission_time: v[:ctime],
dispatch_time: v[:start_time],
- native: v
+ native: v,
+ child_task_statuses: child_task_statuses
)
end
end
diff --git a/spec/job/adapters/torque_spec.rb b/spec/job/adapters/torque_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/job/adapters/torque_spec.rb
+++ b/spec/job/adapters/torque_spec.rb
@@ -693,6 +693,39 @@ describe OodCore::Job::Adapters::Torque do
is_expected.to eq(OodCore::Job::Info.new(id: job_id, status: :completed))
end
end
+
+ context "when child tasks are returned" do
+ let(:pbs) {
+ double(
+ get_job: {
+ 'job_id[1]' => {:job_state => 'R'},
+ 'job_id[2]' => {:job_state => 'Q'},
+ 'job_id[3]' => {:job_state => 'H'},
+ }
+ )
+ }
+
+ let(:aggregate_job_info) {
+ OodCore::Job::Info.new(
+ id: 'job_id[]',
+ status: :running,
+ native: {:job_state=>"R"},
+ wallclock_time: 0,
+ wallclock_limit: 0,
+ procs: 0,
+ cpu_time: 0,
+ child_task_statuses: [
+ {:id => 'job_id[1]', :status => :running},
+ {:id => 'job_id[2]', :status => :queued},
+ {:id => 'job_id[3]', :status => :queued_held}
+ ]
+ )
+ }
+
+ it "creates the proper aggregate job info" do
+ expect( adapter.info('job_id[]') ).to eq(aggregate_job_info)
+ end
+ end
end
describe "#status" do
|
Update Torque Adapter to better report the status of array jobs
|
OSC_ood_core
|
train
|
0f622de27c96df54a7498dd59962c7985bb072c4
|
diff --git a/pipreqs/mapping b/pipreqs/mapping
index <HASH>..<HASH> 100644
--- a/pipreqs/mapping
+++ b/pipreqs/mapping
@@ -261,6 +261,7 @@ socketio:gevent_socketio
socketserver:pies2overrides
sockjs:sockjs_tornado
socks:SocksiPy_branch
+IPython:ipython
solr:solrpy
solution:Solution
sorl:sorl_thumbnail
diff --git a/pipreqs/pipreqs.py b/pipreqs/pipreqs.py
index <HASH>..<HASH> 100755
--- a/pipreqs/pipreqs.py
+++ b/pipreqs/pipreqs.py
@@ -126,8 +126,10 @@ def get_pkg_names(pkgs):
def get_name_without_alias(name):
- if "import" in name:
- name = REGEXP[0].match(name.strip()).groups(0)[0]
+ if "import " in name:
+ match = REGEXP[0].match(name.strip())
+ if match:
+ name = match.groups(0)[0]
return name.partition(' as ')[0].partition('.')[0].strip()
diff --git a/tests/_data/test.py b/tests/_data/test.py
index <HASH>..<HASH> 100644
--- a/tests/_data/test.py
+++ b/tests/_data/test.py
@@ -7,8 +7,28 @@ from sys import argv as test2 # [unused-import]
from sys import flags # [unused-import]
# +1:[unused-import,unused-import]
from collections import deque, OrderedDict, Counter
-import requests # [unused-import]
# All imports above should be ignored
+import requests # [unused-import]
+
+# setuptools
+import zipimport # command/easy_install.py
+
+# twisted
+from importlib import invalidate_caches # python/test/test_deprecate.py
+
+# astroid
+import zipimport # manager.py
+# IPython
+from importlib.machinery import all_suffixes # core/completerlib.py
+import importlib # html/notebookapp.py
+
+from IPython.utils.importstring import import_item # Many files
+
+# pyflakes
+from pyflakes.test.test_imports import Test as TestImports # test/test_doctests.py
+
+# Nose
+from nose.importer import Importer, add_path, remove_path # loader.py
import atexit
from __future__ import print_function
diff --git a/tests/test_pipreqs.py b/tests/test_pipreqs.py
index <HASH>..<HASH> 100755
--- a/tests/test_pipreqs.py
+++ b/tests/test_pipreqs.py
@@ -18,7 +18,7 @@ class TestPipreqs(unittest.TestCase):
def setUp(self):
self.modules = ['flask', 'requests', 'sqlalchemy',
- 'docopt', 'boto', 'peewee', 'ujson', 'nonexistendmodule', 'bs4',]
+ 'docopt', 'boto', 'ipython', 'pyflakes', 'nose', 'peewee', 'ujson', 'nonexistendmodule', 'bs4',]
self.modules2 = ['beautifulsoup4']
self.project = os.path.join(os.path.dirname(__file__), "_data")
self.requirements_path = os.path.join(self.project, "requirements.txt")
@@ -27,7 +27,7 @@ class TestPipreqs(unittest.TestCase):
def test_get_all_imports(self):
imports = pipreqs.get_all_imports(self.project)
- self.assertEqual(len(imports), 9)
+ self.assertEqual(len(imports), 12)
for item in imports:
self.assertTrue(
item.lower() in self.modules, "Import is missing: " + item)
@@ -42,8 +42,7 @@ class TestPipreqs(unittest.TestCase):
imports = pipreqs.get_all_imports(self.project)
with_info = pipreqs.get_imports_info(imports)
# Should contain only 5 Elements without the "nonexistendmodule"
- self.assertEqual(
- len(with_info), 7)
+ self.assertEqual(len(with_info), 10)
for item in with_info:
self.assertTrue(item['name'].lower(
) in self.modules, "Import item appears to be missing " + item['name'])
|
fix(pipreqs): ignore word "import" in package names
|
bndr_pipreqs
|
train
|
b86bad2bf9f01fdd19067f5b69254aa237f80ca2
|
diff --git a/imageio/imageio-core/src/main/java/com/twelvemonkeys/imageio/color/DiscreteAlphaIndexColorModel.java b/imageio/imageio-core/src/main/java/com/twelvemonkeys/imageio/color/DiscreteAlphaIndexColorModel.java
index <HASH>..<HASH> 100644
--- a/imageio/imageio-core/src/main/java/com/twelvemonkeys/imageio/color/DiscreteAlphaIndexColorModel.java
+++ b/imageio/imageio-core/src/main/java/com/twelvemonkeys/imageio/color/DiscreteAlphaIndexColorModel.java
@@ -153,6 +153,12 @@ public final class DiscreteAlphaIndexColorModel extends ColorModel {
(raster.getNumBands() == 2) && ((1 << size) >= icm.getMapSize()));
}
+ @Override
+ public boolean equals(Object obj) {
+ return this == obj
+ || obj != null && getClass() == obj.getClass() && icm.equals(((DiscreteAlphaIndexColorModel) obj).icm);
+ }
+
public String toString() {
return "DiscreteAlphaIndexColorModel: #pixelBits = " + pixel_bits
+ " numComponents = " + getNumComponents()
|
Equals method for DiscreteAlphaIndexColorModel, needed for Java <I>.
|
haraldk_TwelveMonkeys
|
train
|
48d9c1bf76208013b7ee668b2e34586e335651a4
|
diff --git a/pypot/sensor/imagefeature/marker.py b/pypot/sensor/imagefeature/marker.py
index <HASH>..<HASH> 100644
--- a/pypot/sensor/imagefeature/marker.py
+++ b/pypot/sensor/imagefeature/marker.py
@@ -1,3 +1,5 @@
+from multiprocessing import Process, Queue
+
from hampy import detect_markers
from ...robot.controller import SensorsController
@@ -24,7 +26,7 @@ class Marker(Sensor):
class MarkerDetector(SensorsController):
- def __init__(self, robot, name, cameras, freq):
+ def __init__(self, robot, name, cameras, freq, multiprocess=True):
SensorsController.__init__(self, None, [], freq)
self.name = name
@@ -32,11 +34,14 @@ class MarkerDetector(SensorsController):
self._robot = robot
self._names = cameras
+ self.detect = (lambda img: self._bg_detection(img)
+ if multiprocess else detect_markers(img))
+
def update(self):
if not hasattr(self, 'cameras'):
self.cameras = [getattr(self._robot, c) for c in self._names]
- self._markers = sum([detect_markers(c.frame) for c in self.cameras], [])
+ self._markers = sum([self.detect(c.frame) for c in self.cameras], [])
self.sensors = [Marker(m) for m in self._markers]
@property
@@ -46,3 +51,14 @@ class MarkerDetector(SensorsController):
@property
def registers(self):
return ['markers']
+
+ def _detect(self, q, img):
+ q.put(detect_markers(img))
+
+ def _bg_detection(self, img):
+ if not hasattr(self, 'q'):
+ self.q = Queue()
+
+ p = Process(target=self._detect, args=(self.q, img))
+ p.start()
+ return self.q.get()
|
Add the possibility to detect markers in another process.
|
poppy-project_pypot
|
train
|
bf04e3d2f6cba980e19df38eda9118a7d2cedd93
|
diff --git a/pgjdbc/src/main/java/org/postgresql/core/v3/ConnectionFactoryImpl.java b/pgjdbc/src/main/java/org/postgresql/core/v3/ConnectionFactoryImpl.java
index <HASH>..<HASH> 100644
--- a/pgjdbc/src/main/java/org/postgresql/core/v3/ConnectionFactoryImpl.java
+++ b/pgjdbc/src/main/java/org/postgresql/core/v3/ConnectionFactoryImpl.java
@@ -239,10 +239,8 @@ public class ConnectionFactoryImpl extends ConnectionFactory {
tryConnect(user, database, info, socketFactory, hostSpec, SslMode.DISABLE,gssEncMode);
LOGGER.log(Level.FINE, "Downgraded to non-encrypted connection for host {0}",
hostSpec);
- } catch (SQLException ee) {
+ } catch (SQLException | IOException ee) {
ex = ee;
- } catch (IOException ee) {
- ex = ee; // Can't use multi-catch in Java 6 :(
}
if (ex != null) {
log(Level.FINE, "sslMode==PREFER, however non-SSL connection failed as well", ex);
|
refactor: Use multi-catch for exceptions in ConnectionFactoryImpl
|
pgjdbc_pgjdbc
|
train
|
66d20b30d03185fa1d0002254438d1284ddf4200
|
diff --git a/codegen/src/test/java/org/web3j/codegen/SolidityFunctionWrapperGeneratorTest.java b/codegen/src/test/java/org/web3j/codegen/SolidityFunctionWrapperGeneratorTest.java
index <HASH>..<HASH> 100644
--- a/codegen/src/test/java/org/web3j/codegen/SolidityFunctionWrapperGeneratorTest.java
+++ b/codegen/src/test/java/org/web3j/codegen/SolidityFunctionWrapperGeneratorTest.java
@@ -45,8 +45,8 @@ public class SolidityFunctionWrapperGeneratorTest extends TempFileProvider {
@Test
public void testGreeterGeneration() throws Exception {
- testCodeGenerationJvmTypes("greeter", "greeter");
- testCodeGenerationSolidityTypes("greeter", "greeter");
+ testCodeGenerationJvmTypes("greeter", "Greeter");
+ testCodeGenerationSolidityTypes("greeter", "Greeter");
}
@Test
|
Renamed greeter to Greeter to be consistent with the other contracts
|
web3j_web3j
|
train
|
181b820da60fd67647291d491b86b393f5b9f069
|
diff --git a/lib/album.js b/lib/album.js
index <HASH>..<HASH> 100644
--- a/lib/album.js
+++ b/lib/album.js
@@ -4,3 +4,7 @@ function Album(album, _wimp){
this._wimp = _wimp;
_.merge(this, album);
}
+Album.prototype.getTracks = function(fn){
+ var wimp = this._wimp;
+ return wimp.getAlbumTracks(this.id, fn);
+};
diff --git a/lib/wimp.js b/lib/wimp.js
index <HASH>..<HASH> 100644
--- a/lib/wimp.js
+++ b/lib/wimp.js
@@ -140,7 +140,7 @@ WiMP.prototype.getTopTracks = function(artistId, fn){
fn(err, tracks);
})
};
-WiMP.prototype.getTracks = function(albumId, fn){
+WiMP.prototype.getAlbumTracks = function(albumId, fn){
var self = this;
self.agent
.get(self._buildUrl('albums', [albumId, 'tracks']))
@@ -172,6 +172,23 @@ WiMP.prototype.getPlaylists = function(fn){
fn(err, playlists);
});
};
+Wimp.prototype.getPlaylistTracks = function(playlistId, fn){
+ var self = this;
+ self.agent
+ .get(wimp._buildUrl('playlists', [playlistId, 'tracks'], {
+ limit: 9999
+ }))
+ .end(function(err, res){
+ var items = res.body.items;
+ var tracks = [];
+ _.each(items, function(track){
+ track = new Track(track, self);
+ tracks.push(track);
+ return track;
+ });
+ fn(err, tracks);
+ });
+};
WiMP.prototype.search = function(ret, query, fn){
var self = this;
if(ret == 'artists'){
|
Rename getTracks to getAlbumTracks and add getPlaylistTracks
For those who dislike OOP
|
datagutt_WiMP-api
|
train
|
f7fcfe0f6839944861d99ff5bb8d74f6c18fa5c7
|
diff --git a/test/mock.py b/test/mock.py
index <HASH>..<HASH> 100644
--- a/test/mock.py
+++ b/test/mock.py
@@ -17,7 +17,7 @@
# specific language governing permissions and limitations
# under the License.
from zopkio.deployer import Deployer, Process
-
+from zopkio import runtime
class Mock_Deployer(Deployer):
"""
@@ -36,6 +36,7 @@ class Mock_Deployer(Deployer):
def start(self, unique_id, configs=None):
import subprocess
+ runtime.set_deployer("unittest", self)
self._proc = subprocess.Popen(["sleep","150"])
if self._proc is not None:
self._pid = self._proc.pid
diff --git a/test/samples/sample_ztestsuite.py b/test/samples/sample_ztestsuite.py
index <HASH>..<HASH> 100644
--- a/test/samples/sample_ztestsuite.py
+++ b/test/samples/sample_ztestsuite.py
@@ -84,10 +84,10 @@ class SampleTestSuite(ZTestSuite):
self.test1 = SampleTest1(self)
self.test2 = SampleTest2(self)
self._deployer = deployer
- if self._deployer is not None:
- runtime.set_deployer("ztestsuite.unittest.deployer", self._deployer )
def setup_suite(self):
+ if self._deployer is not None:
+ runtime.set_deployer("ztestsuite.unittest.deployer", self._deployer )
if os.path.isdir("/tmp/ztestsute"):
shutil.rmtree("/tmp/ztestsuite")
if not os.path.isdir(runtime.get_active_config("LOGS_DIRECTORY")):
@@ -116,7 +116,6 @@ class SampleTestSuite(ZTestSuite):
if self._deployer is not None:
self._deployer.stop("ztestsuite.unittest")
-
def naarad_config(self):
return os.path.join(TEST_DIRECTORY, "samples/naarad_config.cfg")
diff --git a/test/test_test_runner.py b/test/test_test_runner.py
index <HASH>..<HASH> 100644
--- a/test/test_test_runner.py
+++ b/test/test_test_runner.py
@@ -95,8 +95,7 @@ class TestTestRunner(unittest.TestCase):
def test_copy_logs_empty_default(self):
#first set things up
- runtime.reset_collector()
- runtime.set_deployer("unittest", Mock_Deployer() )
+ runtime.reset_all()
ztestsuite = SampleTestSuite()
runtime.set_active_config(ztestsuite)
runner = TestRunner(ztestsuite=ztestsuite)
@@ -146,7 +145,7 @@ class TestTestRunner(unittest.TestCase):
#first set things up
#create a temp dir for logs
import tempfile
- runtime.reset_collector()
+ runtime.reset_all()
runtime.set_active_config(ztestsuite)
#create the log file on "remote" which is actually localhost
with open( localhost_log_file, 'wb') as f:
diff --git a/test/test_zopkio.py b/test/test_zopkio.py
index <HASH>..<HASH> 100644
--- a/test/test_zopkio.py
+++ b/test/test_zopkio.py
@@ -1,6 +1,7 @@
import os
import shutil
import unittest
+import zopkio.runtime as runtime
class Args:
def __init__(self):
@@ -41,6 +42,7 @@ class TestZopkioMainRunner(unittest.TestCase):
Run server client test suites and
compare to expected outcome on test failures/successes
"""
+ #runtime.reset_all()
args = Args()
args.testfile = "./examples/server_client/server_client.py"
succeeded, failed = self._run_zopkio(args)
diff --git a/zopkio/runtime.py b/zopkio/runtime.py
index <HASH>..<HASH> 100644
--- a/zopkio/runtime.py
+++ b/zopkio/runtime.py
@@ -121,6 +121,22 @@ def set_deployer(service_name, deployer):
"""
_deployers[service_name] = deployer
+def remove_deployer(service_name):
+ """
+ Remove the deployer with the given name, if it exists
+ :param service_name: name of deployer to remove
+ """
+ try:
+ del _deployers[service_name]
+ except:
+ pass
+
+def reset_deployers():
+ """
+ Clear all added deployers
+ """
+ global _deployers
+ _deployers = {}
def get_deployers():
"""
@@ -144,6 +160,25 @@ def reset_collector():
global _collector
_collector = ResultsCollector()
+def reset_all():
+ """
+ Clear relevant globals to start fresh
+ :return:
+ """
+ global _username
+ global _password
+ global _active_config
+ global _active_tests
+ global _machine_names
+ global _deployers
+ reset_deployers()
+ reset_collector()
+ _username = None
+ _password = None
+ _active_config = None
+ _active_tests = {}
+ _machine_names = defaultdict()
+
###
# Methods dealing with configurations
###
|
Added resets to clear globals causing test conflicts across tests
|
linkedin_Zopkio
|
train
|
d99641f31e64d63623c7cf58d4355dccea7e80d0
|
diff --git a/cmd/init.go b/cmd/init.go
index <HASH>..<HASH> 100644
--- a/cmd/init.go
+++ b/cmd/init.go
@@ -40,7 +40,7 @@ func newInitCmd() *initCmd {
return err
}
defer gitignore.Close()
- if _, err := gitignore.WriteString("dist/\n"); err != nil {
+ if _, err := gitignore.WriteString("\ndist/\n"); err != nil {
return err
}
diff --git a/cmd/init_test.go b/cmd/init_test.go
index <HASH>..<HASH> 100644
--- a/cmd/init_test.go
+++ b/cmd/init_test.go
@@ -32,7 +32,7 @@ func TestInitGitIgnoreExists(t *testing.T) {
bts, err := os.ReadFile(".gitignore")
require.NoError(t, err)
- require.Equal(t, "mybinary\ndist/\n", string(bts))
+ require.Equal(t, "mybinary\n\ndist/\n", string(bts))
}
func TestInitFileExists(t *testing.T) {
|
fix: gitignore patching needs leading newline (#<I>)
|
goreleaser_goreleaser
|
train
|
4e4bcb4c6b08ed392cd5576dcfc252ef574a1b88
|
diff --git a/activesupport/lib/active_support/multibyte/chars.rb b/activesupport/lib/active_support/multibyte/chars.rb
index <HASH>..<HASH> 100644
--- a/activesupport/lib/active_support/multibyte/chars.rb
+++ b/activesupport/lib/active_support/multibyte/chars.rb
@@ -40,13 +40,15 @@ module ActiveSupport::Multibyte #:nodoc:
# core dumps. Don't go there.
@string
end
-
+
# Make duck-typing with String possible
- def respond_to?(method)
- super || @string.respond_to?(method) || handler.respond_to?(method) ||
- (method.to_s =~ /(.*)!/ && handler.respond_to?($1)) || false
+ def respond_to?(method, include_priv = false)
+ super || @string.respond_to?(method, include_priv) ||
+ handler.respond_to?(method, include_priv) ||
+ (method.to_s =~ /(.*)!/ && handler.respond_to?($1, include_priv)) ||
+ false
end
-
+
# Create a new Chars instance.
def initialize(str)
@string = str.respond_to?(:string) ? str.string : str
diff --git a/activesupport/lib/active_support/time_with_zone.rb b/activesupport/lib/active_support/time_with_zone.rb
index <HASH>..<HASH> 100644
--- a/activesupport/lib/active_support/time_with_zone.rb
+++ b/activesupport/lib/active_support/time_with_zone.rb
@@ -248,14 +248,14 @@ module ActiveSupport
def marshal_load(variables)
initialize(variables[0], ::Time.send!(:get_zone, variables[1]), variables[2])
end
-
+
# Ensure proxy class responds to all methods that underlying time instance responds to.
- def respond_to?(sym)
+ def respond_to?(sym, include_priv = false)
# consistently respond false to acts_like?(:date), regardless of whether #time is a Time or DateTime
return false if sym.to_s == 'acts_like_date?'
- super || time.respond_to?(sym)
+ super || time.respond_to?(sym, include_priv)
end
-
+
# Send the missing method to +time+ instance, and wrap result in a new TimeWithZone with the existing +time_zone+.
def method_missing(sym, *args, &block)
result = time.__send__(sym, *args, &block)
|
Ruby <I> compat: TimeWithZone# and Chars#respond_to? pass along the include_private argument
|
rails_rails
|
train
|
80e18404141a21a509d9c33b16f8abc95e56c9d2
|
diff --git a/test/tools/javac/processing/model/type/IntersectionPropertiesTest.java b/test/tools/javac/processing/model/type/IntersectionPropertiesTest.java
index <HASH>..<HASH> 100644
--- a/test/tools/javac/processing/model/type/IntersectionPropertiesTest.java
+++ b/test/tools/javac/processing/model/type/IntersectionPropertiesTest.java
@@ -23,7 +23,7 @@
/*
* @test
- * @bug 6499673
+ * @bug 6499673 6557966
* @library /tools/javac/lib
* @build JavacTestingAbstractProcessor IntersectionPropertiesTest
* @run main IntersectionPropertiesTest
|
<I>: test needs bugID added to @bug tag
Summary: Adding forgotten bug number
Reviewed-by: vromero
|
wmdietl_jsr308-langtools
|
train
|
0e6a34c7064784eda6a0de174ffcfc87ae0ced08
|
diff --git a/ballet/validation.py b/ballet/validation.py
index <HASH>..<HASH> 100644
--- a/ballet/validation.py
+++ b/ballet/validation.py
@@ -15,7 +15,7 @@ from ballet.util.ci import (
__all__ = [
'FeatureApiValidator',
- 'PullRequestFeatureValidator'
+ 'PullRequestStructureValidator'
]
@@ -114,7 +114,11 @@ class FeatureApiValidator:
yield (method, name)
-class PullRequestFeatureValidator:
+class ProjectStructureValidator:
+ pass
+
+
+class PullRequestStructureValidator(ProjectStructureValidator):
APPROPRIATE_CHANGE_TYPES = ['A']
APPROPRIATE_FILE_EXTS = ['.py']
@@ -198,7 +202,7 @@ class PullRequestFeatureValidator:
def is_appropriate_change_type(diff):
'''File change is an addition'''
return diff.change_type in \
- PullRequestFeatureValidator.APPROPRIATE_CHANGE_TYPES
+ PullRequestStructureValidator.APPROPRIATE_CHANGE_TYPES
def within_contrib_subdirectory(diff):
'''File addition is a subdirectory of project's contrib dir'''
@@ -214,7 +218,7 @@ class PullRequestFeatureValidator:
'''File change is a python file'''
path = diff.b_path
try:
- for ext in PullRequestFeatureValidator.APPROPRIATE_FILE_EXTS:
+ for ext in PullRequestStructureValidator.APPROPRIATE_FILE_EXTS:
if path.endswith(ext):
return True
return False
diff --git a/tests/test_validation.py b/tests/test_validation.py
index <HASH>..<HASH> 100644
--- a/tests/test_validation.py
+++ b/tests/test_validation.py
@@ -13,7 +13,7 @@ from ballet.exc import UnexpectedValidationStateError
from ballet.feature import Feature
from ballet.util.git import get_diff_str_from_commits
from ballet.util.ci import TravisPullRequestBuildDiffer
-from ballet.validation import FeatureApiValidator, PullRequestFeatureValidator
+from ballet.validation import FeatureApiValidator, PullRequestStructureValidator
from .util import (
FragileTransformer, make_mock_commit, make_mock_commits, mock_repo)
@@ -148,7 +148,7 @@ class TestPullRequestFeatureValidator(TestDataMixin, unittest.TestCase):
'TRAVIS_COMMIT_RANGE': commit_range,
}
with patch.dict('os.environ', travis_env_vars):
- yield PullRequestFeatureValidator(
+ yield PullRequestStructureValidator(
repo, self.pr_num, contrib_module_path, X, y)
def test_prfv_init(self):
@@ -185,7 +185,7 @@ class TestPullRequestFeatureValidator(TestDataMixin, unittest.TestCase):
'TRAVIS_COMMIT_RANGE': commit_range,
}
with patch.dict('os.environ', travis_env_vars):
- validator = PullRequestFeatureValidator(
+ validator = PullRequestStructureValidator(
repo, self.pr_num, contrib_module_path, X, y)
validator._collect_file_diffs()
@@ -218,7 +218,7 @@ class TestPullRequestFeatureValidator(TestDataMixin, unittest.TestCase):
'TRAVIS_COMMIT_RANGE': travis_commit_range,
}
with patch.dict('os.environ', travis_env_vars):
- yield PullRequestFeatureValidator(
+ yield PullRequestStructureValidator(
repo, self.pr_num, contrib_module_path, X, y)
def test_prfv_end_to_end_failure_no_features_found(self):
|
Refactor to PullRequestStructureValidator
|
HDI-Project_ballet
|
train
|
14f9f25038c8aeacad7093dc892c47b514a4ddc9
|
diff --git a/binary.go b/binary.go
index <HASH>..<HASH> 100644
--- a/binary.go
+++ b/binary.go
@@ -6,7 +6,7 @@ import (
"strings"
"time"
- "gopkg.in/vmihailenco/msgpack.v2"
+ "github.com/getlantern/msgpack"
)
var (
diff --git a/bool.go b/bool.go
index <HASH>..<HASH> 100644
--- a/bool.go
+++ b/bool.go
@@ -3,7 +3,7 @@ package goexpr
import (
"fmt"
- "gopkg.in/vmihailenco/msgpack.v2"
+ "github.com/getlantern/msgpack"
)
// Boolean accepts the operators AND, OR and returns a short-circuiting
diff --git a/common_test.go b/common_test.go
index <HASH>..<HASH> 100644
--- a/common_test.go
+++ b/common_test.go
@@ -3,8 +3,8 @@ package goexpr
import (
"testing"
+ "github.com/getlantern/msgpack"
"github.com/stretchr/testify/assert"
- "gopkg.in/vmihailenco/msgpack.v2"
)
func msgpacked(t *testing.T, e Expr) Expr {
diff --git a/geo/geo.go b/geo/geo.go
index <HASH>..<HASH> 100644
--- a/geo/geo.go
+++ b/geo/geo.go
@@ -13,9 +13,9 @@ import (
"github.com/getlantern/goexpr"
"github.com/getlantern/golog"
+ "github.com/getlantern/msgpack"
"github.com/hashicorp/golang-lru"
geoip2 "github.com/oschwald/geoip2-golang"
- "gopkg.in/vmihailenco/msgpack.v2"
)
const (
diff --git a/goexpr.go b/goexpr.go
index <HASH>..<HASH> 100644
--- a/goexpr.go
+++ b/goexpr.go
@@ -7,7 +7,7 @@ import (
"fmt"
"time"
- "gopkg.in/vmihailenco/msgpack.v2"
+ "github.com/getlantern/msgpack"
)
func init() {
diff --git a/isp/isp.go b/isp/isp.go
index <HASH>..<HASH> 100644
--- a/isp/isp.go
+++ b/isp/isp.go
@@ -7,7 +7,7 @@ import (
"github.com/getlantern/goexpr"
"github.com/getlantern/golog"
- "gopkg.in/vmihailenco/msgpack.v2"
+ "github.com/getlantern/msgpack"
)
const (
diff --git a/redis/redis.go b/redis/redis.go
index <HASH>..<HASH> 100644
--- a/redis/redis.go
+++ b/redis/redis.go
@@ -5,8 +5,8 @@ import (
"sync/atomic"
"github.com/getlantern/golog"
+ "github.com/getlantern/msgpack"
"gopkg.in/redis.v5"
- "gopkg.in/vmihailenco/msgpack.v2"
)
var (
|
Using fork of msgpack
|
getlantern_goexpr
|
train
|
4341a4127ef32e2cddcc6c324cfcb386c17e0202
|
diff --git a/lib/client/consumer.js b/lib/client/consumer.js
index <HASH>..<HASH> 100644
--- a/lib/client/consumer.js
+++ b/lib/client/consumer.js
@@ -97,6 +97,7 @@ class RpcConsumer extends Base {
requestProps: options.requestProps,
codecType: options.codecType,
timeout: options.responseTimeout || this.options.responseTimeout,
+ ctx: options.ctx,
});
}
diff --git a/lib/client/request.js b/lib/client/request.js
index <HASH>..<HASH> 100644
--- a/lib/client/request.js
+++ b/lib/client/request.js
@@ -18,6 +18,7 @@ class RpcRequest {
this.requestProps = data.requestProps || {
service: data.serverSignature,
};
+ this.ctx = data.ctx;
this.meta = {
id: null,
resultCode: '00',
diff --git a/package.json b/package.json
index <HASH>..<HASH> 100644
--- a/package.json
+++ b/package.json
@@ -36,16 +36,16 @@
"await-first": "^1.0.0",
"byte": "^2.0.0",
"cluster-client": "^2.1.1",
- "debug": "^4.0.0",
+ "debug": "^4.0.1",
"easy-table": "^1.1.1",
"graceful": "^1.0.1",
- "is-type-of": "^1.2.0",
+ "is-type-of": "^1.2.1",
"mz-modules": "^2.1.0",
"pump": "^3.0.0",
- "sdk-base": "^3.5.0",
+ "sdk-base": "^3.5.1",
"sofa-bolt-node": "^1.0.2",
"urlencode": "^1.1.0",
- "utility": "^1.14.0",
+ "utility": "^1.15.0",
"zookeeper-cluster-client": "^2.0.1"
},
"devDependencies": {
@@ -54,8 +54,8 @@
"await-event": "^2.1.0",
"coffee": "^5.1.0",
"contributors": "^0.5.1",
- "egg-bin": "^4.8.5",
- "eslint": "^5.5.0",
+ "egg-bin": "^4.9.0",
+ "eslint": "^5.6.1",
"eslint-config-egg": "^7.1.0",
"mm": "^2.4.1",
"pedding": "^1.1.0"
diff --git a/test/client/client.test.js b/test/client/client.test.js
index <HASH>..<HASH> 100644
--- a/test/client/client.test.js
+++ b/test/client/client.test.js
@@ -57,10 +57,12 @@ describe('test/client/client.test.js', () => {
name: 'Peter',
group: 'A',
}];
- const res = await consumer.invoke('echoObj', args);
+ const ctx = { foo: 'bar' };
+ const res = await consumer.invoke('echoObj', args, { ctx });
assert.deepEqual(res, { code: 200, message: 'hello Peter, you are in A' });
assert(req && req.targetAppName === 'pb');
+ assert(req.ctx === ctx);
await client.close();
});
|
feat: append ctx to request (#<I>)
|
alipay_sofa-rpc-node
|
train
|
13d8546487bf17034879c864f57105d780ead6e9
|
diff --git a/src/main/java/org/metacsp/utility/UI/JTSDrawingPanel.java b/src/main/java/org/metacsp/utility/UI/JTSDrawingPanel.java
index <HASH>..<HASH> 100644
--- a/src/main/java/org/metacsp/utility/UI/JTSDrawingPanel.java
+++ b/src/main/java/org/metacsp/utility/UI/JTSDrawingPanel.java
@@ -124,7 +124,17 @@ public class JTSDrawingPanel extends JPanel {
private double targetTextSize = 1.0;
private double targetArrowHeadWidth = 1.0;
+
+ private double panAcceleration = 2.5;
+ private double zoomIntensity = 0.05;
+ public void setPanAcceleration(double accel) {
+ this.panAcceleration = accel;
+ }
+
+ public void setZoomIntensity(double intens) {
+ this.zoomIntensity = intens;
+ }
public void setSmoothTransitions(boolean value) {
this.smoothTransitions = value;
@@ -190,15 +200,15 @@ public class JTSDrawingPanel extends JPanel {
int x = e.getX();
int y = e.getY();
if (SwingUtilities.isRightMouseButton(e)) {
- userScale += Math.signum(y-previousY)*0.05;
+ userScale += Math.signum(y-previousY)*zoomIntensity;
if (userScale < 0.01) userScale = 0.01;
}
else if (SwingUtilities.isLeftMouseButton(e)) {
- double accel = 2.5;
- if (map != null) {
- accel *= 0.01*map.getHeight();
- }
- panTrans = AffineTransform.getTranslateInstance(panTrans.getTranslateX()+Math.signum(x-previousX)*accel*userScale, panTrans.getTranslateY()-Math.signum(y-previousY)*accel*userScale);
+// double accel = 2.5;
+// if (map != null) {
+// accel *= 0.01*map.getHeight();
+// }
+ panTrans = AffineTransform.getTranslateInstance(panTrans.getTranslateX()+Math.signum(x-previousX)*panAcceleration*userScale, panTrans.getTranslateY()-Math.signum(y-previousY)*panAcceleration*userScale);
}
previousX = x;
previousY = y;
|
Added scaling and intensity parameters in JTSDrawingPanel
|
FedericoPecora_meta-csp-framework
|
train
|
23483eee4081ad01f1f6b4000502271907519209
|
diff --git a/pymatgen/symmetry/groups.py b/pymatgen/symmetry/groups.py
index <HASH>..<HASH> 100644
--- a/pymatgen/symmetry/groups.py
+++ b/pymatgen/symmetry/groups.py
@@ -190,7 +190,6 @@ class PointGroup(SymmetryGroup):
orbit.append(pp)
return orbit
-
@cached_class
class SpaceGroup(SymmetryGroup):
"""
@@ -388,6 +387,32 @@ class SpaceGroup(SymmetryGroup):
orbit.append(pp)
return orbit
+ def get_orbit_and_generators(self, p: ArrayLike, tol: float = 1e-5) -> tuple[list, list]:
+ """
+ Returns the orbit and its generators for a point.
+
+ Args:
+ p: Point as a 3x1 array.
+ tol: Tolerance for determining if sites are the same. 1e-5 should
+ be sufficient for most purposes. Set to 0 for exact matching
+ (and also needed for symbolic orbits).
+
+ Returns:
+ ([array], [array]) Orbit and generators for point.
+ """
+ from pymatgen.core.operations import SymmOp
+
+ orbit: list[ArrayLike] = [np.array(p, dtype=float)]
+ identity = SymmOp.from_rotation_and_translation(np.eye(3), np.zeros(3))
+ generators: list[ArrayLike] = [identity]
+ for o in self.symmetry_ops:
+ pp = o.operate(p)
+ pp = np.mod(np.round(pp, decimals=10), 1)
+ if not in_array_list(orbit, pp, tol=tol):
+ orbit.append(pp)
+ generators.append(o)
+ return orbit, generators
+
def is_compatible(self, lattice: Lattice, tol: float = 1e-5, angle_tol: float = 5) -> bool:
"""
Checks whether a particular lattice is compatible with the
diff --git a/pymatgen/symmetry/tests/test_groups.py b/pymatgen/symmetry/tests/test_groups.py
index <HASH>..<HASH> 100644
--- a/pymatgen/symmetry/tests/test_groups.py
+++ b/pymatgen/symmetry/tests/test_groups.py
@@ -124,6 +124,16 @@ class SpaceGroupTest(unittest.TestCase):
p = np.random.randint(0, 100 + 1, size=(3,)) / 100
self.assertLessEqual(len(sg.get_orbit(p)), sg.order)
+ def test_get_orbit_and_generators(self):
+ sg = SpaceGroup("Fm-3m")
+ p = np.random.randint(0, 100 + 1, size=(3,)) / 100
+ orbit, generators = sg.get_orbit_and_generators(p)
+ self.assertLessEqual(len(orbit), sg.order)
+ pp = generators[0].operate(orbit[0])
+ self.assertAlmostEqual(p[0], pp[0])
+ self.assertAlmostEqual(p[1], pp[1])
+ self.assertAlmostEqual(p[2], pp[2])
+
def test_is_compatible(self):
cubic = Lattice.cubic(1)
hexagonal = Lattice.hexagonal(1, 2)
|
Added 'get_orbit_and_generators'-method to SpaceGroup to class.
|
materialsproject_pymatgen
|
train
|
b4256907e69ad315a743638910980128564acdc1
|
diff --git a/lib/gir_ffi/base.rb b/lib/gir_ffi/base.rb
index <HASH>..<HASH> 100644
--- a/lib/gir_ffi/base.rb
+++ b/lib/gir_ffi/base.rb
@@ -14,10 +14,14 @@ module GirFFI
self.class.ffi_structure
end
+ def _fake_missing *args, &block
+ method_missing method_name.to_sym, *args, &block
+ end
+
private
def method_name
- caller[0].gsub /.*`(.*)'/, '\1'
+ caller[0].gsub(/.*`(.*)'/, '\1')
end
class << self
diff --git a/test/base_test.rb b/test/base_test.rb
index <HASH>..<HASH> 100644
--- a/test/base_test.rb
+++ b/test/base_test.rb
@@ -1,22 +1,72 @@
require File.expand_path('test_helper.rb', File.dirname(__FILE__))
require 'gir_ffi/base'
-class SubClass < GirFFI::Base
- # Boilerplate to make regular #new work again.
- def initialize
- end
- def self.new
- self._real_new
- end
- def this_is_my_name
- method_name
- end
-end
-
class BaseTest < Test::Unit::TestCase
context "A class derived from GirFFI::Base" do
+ setup do
+ @klass = Class.new(GirFFI::Base) do
+ # Boilerplate to make regular #new work again.
+ def initialize; end
+ def self.new; self._real_new; end
+ end
+ end
+
should "be able to use method_name to get the names of its methods" do
- assert_equal "this_is_my_name", SubClass.new.this_is_my_name
+ @klass.class_eval do
+ def this_is_my_name
+ method_name
+ end
+ end
+ assert_equal "this_is_my_name", @klass.new.this_is_my_name
+ end
+
+ context "its #_fake_missing method" do
+ should "not be missing" do
+ assert @klass.new.respond_to? :_fake_missing
+ end
+
+ should "call method_missing" do
+ @klass.class_eval do
+ def method_missing method, *args
+ method
+ end
+ end
+ assert_equal :_fake_missing, @klass.new._fake_missing
+ end
+
+ should "pass on its arguments" do
+ @klass.class_eval do
+ def method_missing method, *args
+ args.join(', ')
+ end
+ end
+ assert_equal "a, b", @klass.new._fake_missing("a", "b")
+ end
+
+ should "pass on a given block" do
+ @klass.class_eval do
+ def method_missing method, *args
+ yield if block_given?
+ end
+ end
+ assert_equal :called, @klass.new._fake_missing { :called }
+ end
+ end
+
+ should "be able to use alias_method to create a self-defining method" do
+ @klass.class_eval do
+ def method_missing method, *args
+ self.class.class_eval "
+ undef #{method}
+ def #{method}
+ :redefined
+ end
+ "
+ self.send method
+ end
+ alias_method :new_method, :_fake_missing
+ end
+ assert_equal :redefined, @klass.new.new_method
end
end
end
|
Create Base#_fake_missing.
|
mvz_gir_ffi
|
train
|
7d997b6ecd23e5893c5783bb326f022d7be218cc
|
diff --git a/lib/DataManager/ArrayManager.php b/lib/DataManager/ArrayManager.php
index <HASH>..<HASH> 100644
--- a/lib/DataManager/ArrayManager.php
+++ b/lib/DataManager/ArrayManager.php
@@ -48,12 +48,13 @@ abstract class ArrayManager implements \ArrayAccess,\Countable,\Iterator
$this->clearCache();
$this->rewind();
- return array_keys(get_object_vars($this));
+ return ['_Container','_DataHandler'];
}
public function __wakeup ()
{
-
+ $this->resetMaxKey();
+ $this->resetCounter();
}
|
DataManager Sleep/WakeUp
|
julien-boudry_Condorcet
|
train
|
eb663ce3d894c836cf1d43761efc070a6a342d08
|
diff --git a/lib/domv.js b/lib/domv.js
index <HASH>..<HASH> 100644
--- a/lib/domv.js
+++ b/lib/domv.js
@@ -600,7 +600,8 @@ module.exports.createHtmlDomDocument = function(minimal)
{
features: {
FetchExternalResources: false,
- ProcessExternalResources: false
+ ProcessExternalResources: false,
+ MutationEvents: false
}
}
);
@@ -676,7 +677,8 @@ module.exports.parseHTMLDocument = function(markup, ownerDocument)
document = jsdom.jsdom(markup, {
features: {
FetchExternalResources: false,
- ProcessExternalResources: false
+ ProcessExternalResources: false,
+ MutationEvents: false
}
});
}
|
Disable MutationEvents for jsdom. They are rarely needed in the context of domv.
|
Joris-van-der-Wel_domv
|
train
|
1b3ef60bc0c5ba2bf35cfe5fa2a0dc39a4af8ceb
|
diff --git a/pygsp/filters.py b/pygsp/filters.py
index <HASH>..<HASH> 100644
--- a/pygsp/filters.py
+++ b/pygsp/filters.py
@@ -505,12 +505,10 @@ class Meyer(Filter):
t = G.t
print(t)
- g = []
- g.append(lambda x: kernel_meyer(t[1] * x, 'sf'))
+ g = [lambda x: kernel_meyer(t[0] * x, 'sf')]
for i in range(Nf-1):
- g.append(lambda x, ind=i: kernel_meyer(t[ind] * x,
- 'wavelet'))
+ g.append(lambda x, ind=i: kernel_meyer(t[ind] * x, 'wavelet'))
self.g = g
@@ -537,23 +535,23 @@ class Meyer(Filter):
l2 = 4./3.
l3 = 8./3.
- v = lambda x: x ** 4. * (35-84 * x+70 * x ** 2-20 * x ** 3)
+ v = lambda x: x ** 4. * (35 - 84*x + 70*x**2 - 20*x**3)
- r1ind = x >= 0 and x < l1
- r2ind = x >= l1 and x < l2
- r3ind = x >= l2 and x < l3
+ r1ind = (x < l1)
+ r2ind = (x >= l1)*(x < l2)
+ r3ind = (x >= l2)*(x < l3)
r = np.empty(x.shape)
if kerneltype is 'sf':
r[r1ind] = 1
- r[r2ind] = np.cos((pi/2) * v(np.abs(x * r2ind)/l1 - 1))
+ r[r2ind] = np.cos((pi/2) * v(np.abs(x[r2ind])/l1 - 1))
elif kerneltype is 'wavelet':
- r[r2ind] = np.sin((pi/2) * v(np.abs(x * r2ind)/l1 - 1))
- r[r3ind] = np.cos((pi/2) * v(np.abs(x * r3ind)/l2 - 1))
+ r[r2ind] = np.sin((pi/2) * v(np.abs(x[r2ind])/l1 - 1))
+ r[r3ind] = np.cos((pi/2) * v(np.abs(x[r3ind])/l2 - 1))
else:
raise TypeError('Unknown kernel type ', kerneltype)
- return r
+ return r
class SimpleTf(Filter):
diff --git a/pygsp/operators.py b/pygsp/operators.py
index <HASH>..<HASH> 100644
--- a/pygsp/operators.py
+++ b/pygsp/operators.py
@@ -424,15 +424,16 @@ def compute_cheby_coeff(f, G, m=30, N=None, i=0, *args):
print('The variable lmax has not been computed yet, it will be done \
but if you have to compute multiple times you can precompute \
it with pygsp.utils.estimate_lmax(G)')
- a_arange = range(0, int(G.lmax))
+ a_arange = [0, int(G.lmax)]
- a1 = (a_arange[2]-a_arange[1])/2
- a2 = (a_arange[2]+a_arange[1])/2
- c = np.zeros(m+1)
+ a1 = (a_arange[1] - a_arange[0])/2
+ a2 = (a_arange[1] + a_arange[0])/2
+ c = np.zeros((m+1))
for o in range(m+1):
- c[o] = np.sum(f.g[i](a1 * np.cos(pi * (np.arange(1, N)-0.5))/N) + a2 *
- np.cos(pi * (o-1) * (np.arange(1, N)-0.5)/N)) * 2/N
+ c[o] = np.sum(f.g[0](a1*np.cos(pi*(np.arange(N) + 0.5)/N) + a2)*np.cos(pi*o*(np.arange(N) + 0.5)/N)) * 2./N
+ print c[o]
+
return c
@@ -474,7 +475,7 @@ def cheby_op(G, c, signal, **kwargs):
twf_old = signal
twf_cur = (G.L * signal - a2 * signal)/a1
- Nv = len(signal[1])
+ Nv = np.shape(signal)[1] # len(signal[1])
r = np.zeros((G.N * Nscales, Nv))
for i in range(Nscales):
|
Trying to fix Meyer, compute_cheby_coeff.
|
epfl-lts2_pygsp
|
train
|
2b94050204d82d68fddfbf565cc9d326e1cd89fc
|
diff --git a/lib/model_extensions.rb b/lib/model_extensions.rb
index <HASH>..<HASH> 100644
--- a/lib/model_extensions.rb
+++ b/lib/model_extensions.rb
@@ -74,7 +74,8 @@ module OfflineMirror
@offline_mirror_readonly_bypassed = true
end
- #:nodoc#
+ private
+
def checks_bypassed?
if @offline_mirror_readonly_bypassed
@offline_mirror_readonly_bypassed = false
@@ -83,31 +84,28 @@ module OfflineMirror
return false
end
- #:nodoc#
- def verify_changed_id_columns
+ def validate_changed_id_columns
changed.each do |colname|
raise DataError.new("Cannot change id of offline-mirror tracked records") if colname == "id"
+ if !new_record? and offline_mirror_mode == :group_owned and colname == offline_mirror_group_key.to_s
+ raise DataError.new("Ownership of group-owned data cannot be transferred between groups")
+ end
+
next unless colname.end_with? "_id"
accessor_name = colname[0, colname.size-3]
next unless respond_to? accessor_name
obj = send(accessor_name)
+ raise DataError.new("Mirrored data cannot hold a foreign key to unmirrored data") unless obj.class.acts_as_mirrored_offline?
+
if self.class.offline_mirror_group_data?
- if obj.class.acts_as_mirrored_offline?
- if obj.class.offline_mirror_group_data? && obj.owning_group.id != owning_group.id
- raise DataError.new("Invalid #{colname}: Group data cannot hold a foreign key to data owned by another group")
- end
- else
- raise DataError.new("Invalid #{colname}: Group data cannot hold a foreign key to unmirrored data")
+ if obj.class.offline_mirror_group_data? && obj.owning_group.id != owning_group.id
+ raise DataError.new("Invalid #{colname}: Group data cannot hold a foreign key to data owned by another group")
end
elsif self.class.offline_mirror_global_data?
- if obj.class.acts_as_mirrored_offline?
- unless obj.class.offline_mirror_global_data?
- raise DataError.new("Invalid #{colname}: Global mirrored data cannot hold a foreign key to group data")
- end
- else
- raise DataError.new("Invalid #{colname}: Global mirrored data cannot hold a foreign key to unmirrored data")
+ unless obj.class.offline_mirror_global_data?
+ raise DataError.new("Invalid #{colname}: Global mirrored data cannot hold a foreign key to group data")
end
end
end
@@ -136,7 +134,7 @@ module OfflineMirror
def before_mirrored_data_save
return true if checks_bypassed?
ensure_online
- verify_changed_id_columns
+ validate_changed_id_columns
return true
end
@@ -238,16 +236,20 @@ module OfflineMirror
#:nodoc#
def before_mirrored_data_save
return true if checks_bypassed?
+
+ raise DataError.new("Invalid owning group") if owning_group == nil
raise ActiveRecord::ReadOnlyRecord if locked_by_offline_mirror?
+
if OfflineMirror::app_offline?
case offline_mirror_mode
when :group_base
raise DataError.new("Cannot create groups in offline mode") if new_record?
when :group_owned
- raise DataError.new("Invalid owning group") if owning_group_id != OfflineMirror::SystemState::offline_group_id
+ raise DataError.new("Owning group must be the offline group") if owning_group_id != OfflineMirror::SystemState::offline_group_id
end
end
- verify_changed_id_columns
+
+ validate_changed_id_columns
return true
end
diff --git a/test/test_helper.rb b/test/test_helper.rb
index <HASH>..<HASH> 100644
--- a/test/test_helper.rb
+++ b/test/test_helper.rb
@@ -93,6 +93,10 @@ class Test::Unit::TestCase
end
end
+def clean_test_name_string(s)
+
+end
+
# Convenience methods to create tests that apply to particular environments
def online_test(name, &block)
@@ -104,5 +108,5 @@ def offline_test(name, &block)
end
def common_test(name, &block)
- define_method ("test_" + name.to_s.gsub(" ", "_")).to_sym, &block
+ define_method ("test_" + name.to_s.gsub(/[^\w ]/, '').gsub(' ', '_')).to_sym, &block
end
\ No newline at end of file
diff --git a/test/unit/group_data_test.rb b/test/unit/group_data_test.rb
index <HASH>..<HASH> 100644
--- a/test/unit/group_data_test.rb
+++ b/test/unit/group_data_test.rb
@@ -216,11 +216,17 @@ class GroupDataTest < ActiveSupport::TestCase
end
online_test "cannot save :group_owned data with an invalid group id" do
- flunk
+ assert_raise OfflineMirror::DataError do
+ @offline_group_data.group_id = Group.maximum(:id)+1
+ @offline_group_data.save!
+ end
end
online_test "cannot move :group_owned data from one group to another" do
- flunk
+ assert_raise OfflineMirror::DataError do
+ @offline_group_data.group = @online_group
+ @offline_group_data.save!
+ end
end
end
|
Greened tests for stopping changes to group id, improved automatic test naming a bit
|
DavidMikeSimon_offroad
|
train
|
ce8e015a3e7481cc7aabd2ea10cec71e0f91b18c
|
diff --git a/integration/e2e/e2e_test.go b/integration/e2e/e2e_test.go
index <HASH>..<HASH> 100644
--- a/integration/e2e/e2e_test.go
+++ b/integration/e2e/e2e_test.go
@@ -128,6 +128,24 @@ var _ = Describe("EndToEnd", func() {
network.CreateAndJoinChannel(orderer, "testchannel")
nwo.EnableCapabilities(network, "testchannel", "Application", "V2_0", orderer, network.Peer("Org1", "peer0"), network.Peer("Org2", "peer0"))
+ By("attempting to install unsupported chaincode without docker")
+ badCC := chaincode
+ badCC.Lang = "unsupported-type"
+ badCC.Label = "chaincode-label"
+ badCC.PackageFile = filepath.Join(testDir, "unsupported-type.tar.gz")
+ nwo.PackageChaincodeBinary(badCC)
+ badCC.SetPackageIDFromPackageFile()
+ sess, err := network.PeerAdminSession(
+ network.Peer("Org1", "peer0"),
+ commands.ChaincodeInstall{
+ PackageFile: badCC.PackageFile,
+ ClientAuth: network.ClientAuthRequired,
+ },
+ )
+ Expect(err).NotTo(HaveOccurred())
+ Eventually(sess, network.EventuallyTimeout).Should(gexec.Exit(1))
+ Expect(sess.Err).To(gbytes.Say("docker build is disabled"))
+
By("deploying the chaincode")
nwo.DeployChaincode(network, "testchannel", orderer, chaincode)
diff --git a/integration/nwo/package.go b/integration/nwo/package.go
index <HASH>..<HASH> 100644
--- a/integration/nwo/package.go
+++ b/integration/nwo/package.go
@@ -32,7 +32,7 @@ func writeTarGz(c Chaincode, w io.Writer) {
tw := tar.NewWriter(gw)
defer closeAll(tw, gw)
- writeMetadataJSON(tw, c.Path, "binary", c.Label)
+ writeMetadataJSON(tw, c.Path, c.Lang, c.Label)
writeCodeTarGz(tw, c.CodeFiles)
}
diff --git a/internal/peer/node/start.go b/internal/peer/node/start.go
index <HASH>..<HASH> 100644
--- a/internal/peer/node/start.go
+++ b/internal/peer/node/start.go
@@ -152,6 +152,12 @@ func (e externalVMAdapter) Build(
return i, err
}
+type disabledDockerBuilder struct{}
+
+func (disabledDockerBuilder) Build(string, *persistence.ChaincodePackageMetadata, io.Reader) (container.Instance, error) {
+ return nil, errors.New("docker build is disabled")
+}
+
type endorserChannelAdapter struct {
peer *peer.Peer
}
@@ -517,15 +523,14 @@ func serve(args []string) error {
chaincodeConfig := chaincode.GlobalConfig()
- var client *docker.Client
- var dockerVM *dockercontroller.DockerVM
+ var dockerBuilder container.DockerBuilder
if coreConfig.VMEndpoint != "" {
- client, err = createDockerClient(coreConfig)
+ client, err := createDockerClient(coreConfig)
if err != nil {
logger.Panicf("cannot create docker client: %s", err)
}
- dockerVM = &dockercontroller.DockerVM{
+ dockerVM := &dockercontroller.DockerVM{
PeerID: coreConfig.PeerID,
NetworkID: coreConfig.NetworkID,
BuildMetrics: dockercontroller.NewBuildMetrics(opsSystem.Provider),
@@ -551,6 +556,12 @@ func serve(args []string) error {
if err := opsSystem.RegisterChecker("docker", dockerVM); err != nil {
logger.Panicf("failed to register docker health check: %s", err)
}
+ dockerBuilder = dockerVM
+ }
+
+ // docker is disabled when we're missing the docker config
+ if dockerBuilder == nil {
+ dockerBuilder = &disabledDockerBuilder{}
}
externalVM := &externalbuilder.Detector{
@@ -561,7 +572,7 @@ func serve(args []string) error {
buildRegistry := &container.BuildRegistry{}
containerRouter := &container.Router{
- DockerBuilder: dockerVM,
+ DockerBuilder: dockerBuilder,
ExternalBuilder: externalVMAdapter{externalVM},
PackageProvider: &persistence.FallbackPackageLocator{
ChaincodePackageLocator: &persistence.ChaincodePackageLocator{
|
Wire disabled docker builder when docker disabled (#<I>)
This prevents a panic during chaincode install when external builders
cannot handle the chaincode type.
[FAB-<I>]
|
hyperledger_fabric
|
train
|
2af030ab57d1d84ac9a1d22552dc9d83b16951c4
|
diff --git a/pkg/beam/data/message.go b/pkg/beam/data/message.go
index <HASH>..<HASH> 100644
--- a/pkg/beam/data/message.go
+++ b/pkg/beam/data/message.go
@@ -72,6 +72,16 @@ func (m Message) Get(k string) []string {
return v
}
+// GetOne returns the last value added at the key k,
+// or an empty string if there is no value.
+func (m Message) GetOne(k string) string {
+ var v string
+ if vals := m.Get(k); len(vals) > 0 {
+ v = vals[len(vals)-1]
+ }
+ return v
+}
+
func (m Message) Pretty() string {
data, err := Decode(string(m))
if err != nil {
diff --git a/pkg/beam/data/message_test.go b/pkg/beam/data/message_test.go
index <HASH>..<HASH> 100644
--- a/pkg/beam/data/message_test.go
+++ b/pkg/beam/data/message_test.go
@@ -51,3 +51,11 @@ func TestSetDelMessage(t *testing.T) {
t.Fatalf("'%v' != '%v'", output, expectedOutput)
}
}
+
+func TestGetOne(t *testing.T) {
+ m := Empty().Set("shadok words", "ga", "bu", "zo", "meu")
+ val := m.GetOne("shadok words")
+ if val != "meu" {
+ t.Fatalf("%#v", val)
+ }
+}
|
beam/data: Message.GetOne() returns the last value set at a key
This is a convenience for callers which are only interested in one value
per key. Similar to how HTTP headers allow multiple keys per value, but
are often used to store and retrieve only one value.
Docker-DCO-<I>-
|
containers_storage
|
train
|
815ef776f8e4cd710e510bbec61e3992db75a5b1
|
diff --git a/plugins/API/ProcessedReport.php b/plugins/API/ProcessedReport.php
index <HASH>..<HASH> 100644
--- a/plugins/API/ProcessedReport.php
+++ b/plugins/API/ProcessedReport.php
@@ -817,7 +817,10 @@ class ProcessedReport
}
// Display time in human readable
- if (strpos($columnName, 'time') !== false) {
+ if (strpos($columnName, 'time_generation') !== false) {
+ return $formatter->getPrettyTimeFromSeconds($value, true);
+ }
+ if (strpos($columnName, 'time') !== false) {
return $formatter->getPrettyTimeFromSeconds($value);
}
diff --git a/plugins/Actions/Reports/Base.php b/plugins/Actions/Reports/Base.php
index <HASH>..<HASH> 100644
--- a/plugins/Actions/Reports/Base.php
+++ b/plugins/Actions/Reports/Base.php
@@ -72,8 +72,8 @@ abstract class Base extends \Piwik\Plugin\Report
return Piwik::translate("Actions_AvgGenerationTimeTooltip", array(
$hits,
"<br />",
- $formatter->getPrettyTimeFromSeconds($min),
- $formatter->getPrettyTimeFromSeconds($max)
+ $formatter->getPrettyTimeFromSeconds($min, true),
+ $formatter->getPrettyTimeFromSeconds($max, true)
));
};
$view->config->filters[] = array('ColumnCallbackAddMetadata',
|
Format min and max generation time properly when they are added to custom reports and in the tooltip of the regular action reports.
E.g. for <I>ms print "<I>s" instead of "<I>:<I>:<I>".
|
matomo-org_matomo
|
train
|
96ad14b2bbaee3e00d423421f5d28c20ce9ee742
|
diff --git a/src/index.js b/src/index.js
index <HASH>..<HASH> 100644
--- a/src/index.js
+++ b/src/index.js
@@ -575,9 +575,9 @@ export default class BackgroundGeolocation {
*/
static getLog(success, failure) {
if (!arguments.length) {
- return NativeModule.getLog();
+ return Logger.getLog();
} else {
- NativeModule.getLog().then(success).catch(failure);
+ Logger.getLog().then(success).catch(failure);
}
}
/**
@@ -585,9 +585,9 @@ export default class BackgroundGeolocation {
*/
static destroyLog(success, failure) {
if (!arguments.length) {
- return NativeModule.destroyLog();
+ return Logger.destroyLog();
} else {
- NativeModule.destroyLog().then(success).catch(failure);
+ Logger.destroyLog().then(success).catch(failure);
}
}
/**
@@ -596,9 +596,9 @@ export default class BackgroundGeolocation {
static emailLog(email, success, failure) {
if (typeof(email) != 'string') { throw TAG + "#emailLog requires an email address as 1st argument"}
if (arguments.length == 1) {
- return NativeModule.emailLog(email);
+ return Logger.emailLog(email);
} else {
- NativeModule.emailLog(email).then(success).catch(failure);
+ Logger.emailLog(email).then(success).catch(failure);
}
}
/**
|
Fix backwards-compatibility of deprecated getLog, destroyLog, emailLog by proxying into new Logger API
|
transistorsoft_react-native-background-geolocation
|
train
|
b4bc4dfd1217ab1e1f8cfefb520830adbab65d50
|
diff --git a/discord/player.py b/discord/player.py
index <HASH>..<HASH> 100644
--- a/discord/player.py
+++ b/discord/player.py
@@ -138,7 +138,7 @@ class FFmpegPCMAudio(AudioSource):
args.extend(shlex.split(before_options))
args.append('-i')
- args.append('-' if pipe else shlex.quote(source))
+ args.append('-' if pipe else source)
args.extend(('-f', 's16le', '-ar', '48000', '-ac', '2', '-loglevel', 'warning'))
if isinstance(options, str):
|
Fix FFmpegPCMAudio not working with spaces in filename.
|
Rapptz_discord.py
|
train
|
c6da710233070ccae832a16125ec8fbeb443604c
|
diff --git a/openquake/calculators/extract.py b/openquake/calculators/extract.py
index <HASH>..<HASH> 100644
--- a/openquake/calculators/extract.py
+++ b/openquake/calculators/extract.py
@@ -19,6 +19,7 @@ from urllib.parse import parse_qs
from functools import lru_cache
import collections
import logging
+import gzip
import ast
import io
import os
@@ -1108,24 +1109,24 @@ def extract_rupture_info(dstore, what):
dtlist = [('rupid', U32), ('multiplicity', U16), ('mag', F32),
('centroid_lon', F32), ('centroid_lat', F32),
('centroid_depth', F32), ('trt', '<S50'),
- ('strike', F32), ('dip', F32), ('rake', F32),
- ('boundary', hdf5.vstr)]
+ ('strike', F32), ('dip', F32), ('rake', F32)]
rows = []
+ boundaries = []
sf = filters.SourceFilter(dstore['sitecol'], oq.maximum_distance)
for rgetter in getters.gen_rupture_getters(dstore):
rups = rgetter.get_ruptures(sf, min_mag)
rup_data = RuptureData(rgetter.trt, rgetter.rlzs_by_gsim)
for r, rup in zip(rup_data.to_array(rups), rups):
coords = ['%.5f %.5f' % xyz[:2] for xyz in zip(*r['boundaries'])]
- boundary = 'POLYGON((%s))' % ', '.join(coords)
+ boundaries.append('POLYGON((%s))' % ', '.join(coords))
rows.append(
(r['rup_id'], r['multiplicity'], r['mag'],
r['lon'], r['lat'], r['depth'],
- rgetter.trt, r['strike'], r['dip'], r['rake'],
- boundary))
+ rgetter.trt, r['strike'], r['dip'], r['rake']))
arr = numpy.array(rows, dtlist)
- arr.sort(order='rupid')
- return ArrayWrapper(arr, dict(investigation_time=oq.investigation_time))
+ geoms = gzip.compress('\n'.join(boundaries).encode('utf-8'))
+ return ArrayWrapper(arr, dict(investigation_time=oq.investigation_time,
+ boundaries=geoms))
# ##################### extraction from the WebAPI ###################### #
diff --git a/openquake/server/tests/views_test.py b/openquake/server/tests/views_test.py
index <HASH>..<HASH> 100644
--- a/openquake/server/tests/views_test.py
+++ b/openquake/server/tests/views_test.py
@@ -29,6 +29,7 @@ import time
import unittest
import numpy
import zlib
+import gzip
import tempfile
import string
import random
@@ -202,6 +203,12 @@ class EngineServerTestCase(unittest.TestCase):
self.assertGreater(len(got['magnitudes']), 1)
self.assertGreater(len(got['mean_frequency']), 1)
+ # check rupture_info
+ extract_url = '/v1/calc/%s/extract/rupture_info' % job_id
+ got = loadnpz(self.c.get(extract_url))
+ boundaries = gzip.decompress(got['boundaries']).split(b'\n')
+ self.assertEqual(len(boundaries), 33)
+
def test_classical(self):
job_id = self.postzip('classical.zip')
self.wait()
|
Gzipping the boundaries [skip hazardlib]
|
gem_oq-engine
|
train
|
4f8df220b45e61a61784c0acfe9a8323e39cba79
|
diff --git a/CHANGES.txt b/CHANGES.txt
index <HASH>..<HASH> 100644
--- a/CHANGES.txt
+++ b/CHANGES.txt
@@ -6,6 +6,9 @@ pypet 0.1b.8
* Checking if names of leaf and group nodes only contain alphanumeric characters
+* PickleParameter and PickleResult now explicitly store the pickle protocol
+ because retrieval from the pickle dump is not always possible in python 3.
+
pypet 0.1b.7
* StreamToLogger has moved to the pypetlogging.py module. The mplogging module was
diff --git a/pypet/parameter.py b/pypet/parameter.py
index <HASH>..<HASH> 100644
--- a/pypet/parameter.py
+++ b/pypet/parameter.py
@@ -1641,7 +1641,9 @@ class PickleParameter(Parameter):
If the parameter is loaded, `v_protocol` is set to the protocol used to store the data.
"""
- def __init__(self, full_name, data=None, comment='',protocol=2):
+ PROTOCOL = '__pckl_prtcl__'
+
+ def __init__(self, full_name, data=None, comment='', protocol=2):
super(PickleParameter,self).__init__(full_name,data,comment)
self._protocol=None
self.v_protocol=protocol
@@ -1698,6 +1700,7 @@ class PickleParameter(Parameter):
store_dict={}
dump = pickle.dumps(self._data, protocol=self.v_protocol)
store_dict['data'] = dump
+ store_dict[PickleParameter.PROTOCOL] = self.v_protocol
if self.f_has_range():
@@ -1733,9 +1736,9 @@ class PickleParameter(Parameter):
@staticmethod
def _get_protocol(dump):
- protolist = [tup[0].proto for tup in pickletools.genops(dump)]
- #op, fs, snd = next(pickletools.genops(dump))
- return int(max(protolist))
+ pops = pickletools.genops(dump)
+ proto = 2 if next(pops)[0].proto == 2 else int(any(op.proto for op, fst, snd in pops))
+ return proto
def _load(self,load_dict):
"""Reconstructs objects from the pickle dumps in `load_dict`.
@@ -1750,7 +1753,11 @@ class PickleParameter(Parameter):
self._data = pickle.loads(dump)
- self.v_protocol = self._get_protocol(dump)
+ try:
+ self.v_protocol= load_dict[PickleParameter.PROTOCOL]
+ except KeyError:
+ # For backwards compatibility
+ self.v_protocol = PickleParameter._get_protocol(dump)
if 'explored_data'in load_dict:
@@ -2374,6 +2381,8 @@ class PickleResult(Result):
which is the general case.
"""
+ PROTOCOL = PickleParameter.PROTOCOL
+
def __init__(self, full_name, *args, **kwargs):
self._protocol=None
protocol = kwargs.pop('protocol', 0)
@@ -2410,6 +2419,9 @@ class PickleResult(Result):
'you not explicitly overwrite the data on disk, this change '
'might be lost and not propagated to disk.')
+ if name == PickleResult.PROTOCOL:
+ raise AttributeError('You cannot name an entry `%s`' % PickleResult.PROTOCOL)
+
self._data[name] = item
@@ -2418,6 +2430,7 @@ class PickleResult(Result):
store_dict ={}
for key, val in self._data.items():
store_dict[key] = pickle.dumps(val, protocol=self.v_protocol)
+ store_dict[PickleResult.PROTOCOL] = self.v_protocol
return store_dict
def _load(self, load_dict):
@@ -2426,8 +2439,12 @@ class PickleResult(Result):
Sets the `v_protocol` property to the protocol of the first reconstructed item.
"""
+ try:
+ self.v_protocol= load_dict.pop(PickleParameter.PROTOCOL)
+ except KeyError:
+ # For backwards compatibility
+ dump = next(compat.itervalues(load_dict))
+ self.v_protocol = PickleParameter._get_protocol(dump)
for idx, key in enumerate(load_dict):
val = load_dict[key]
- self._data[key] = pickle.loads(val)
- if idx == 0:
- self.v_protocol = PickleParameter._get_protocol(val)
\ No newline at end of file
+ self._data[key] = pickle.loads(val)
\ No newline at end of file
diff --git a/pypet/tests/parameter_test.py b/pypet/tests/parameter_test.py
index <HASH>..<HASH> 100644
--- a/pypet/tests/parameter_test.py
+++ b/pypet/tests/parameter_test.py
@@ -337,7 +337,7 @@ class ParameterTest(unittest.TestCase):
if param.f_has_range():
if isinstance(param,(ArrayParameter, PickleParameter)) and \
not isinstance(param, SparseParameter):
- self.assertTrue(len(store_dict)<6)
+ self.assertTrue(len(store_dict)<7)
# For sparse parameter it is more:
if isinstance(param, SparseParameter):
self.assertTrue(len(store_dict)<23)
|
Explicitly storing pickle protocol for PickleParameter and Result
|
SmokinCaterpillar_pypet
|
train
|
580f65f87d7ae075d325332149185c43cfdb5141
|
diff --git a/packages/rev-models/typedoc.js b/packages/rev-models/typedoc.js
index <HASH>..<HASH> 100644
--- a/packages/rev-models/typedoc.js
+++ b/packages/rev-models/typedoc.js
@@ -5,6 +5,7 @@ module.exports = {
readme: './DOCINDEX.md',
includes: './src',
+ exclude: '**/{__tests__,examples}/**/*',
theme: '../../docs/typedoc/theme/',
mode: 'file',
|
Exclude tests and examples from API docs
|
RevJS_revjs
|
train
|
70c24cfcfa60896aa39f445895f70fc1d8de5377
|
diff --git a/master/buildbot/test/fake/fakebuild.py b/master/buildbot/test/fake/fakebuild.py
index <HASH>..<HASH> 100644
--- a/master/buildbot/test/fake/fakebuild.py
+++ b/master/buildbot/test/fake/fakebuild.py
@@ -41,6 +41,7 @@ class FakeBuild(properties.PropertiesMixin):
spec=workerforbuilder.WorkerForBuilder)
self.workerforbuilder.worker = mock.Mock(spec=base.Worker)
self.workerforbuilder.worker.info = properties.Properties()
+ self.workerforbuilder.worker.workername = 'workername'
self.builder.config = config.BuilderConfig(
name='bldr',
workernames=['a'],
diff --git a/master/buildbot/test/unit/process/test_buildstep.py b/master/buildbot/test/unit/process/test_buildstep.py
index <HASH>..<HASH> 100644
--- a/master/buildbot/test/unit/process/test_buildstep.py
+++ b/master/buildbot/test/unit/process/test_buildstep.py
@@ -76,6 +76,28 @@ class TestBuildStep(steps.BuildStepMixin, config.ConfigErrorsMixin,
def run(self):
return SKIPPED
+ class LockBuildStep(buildstep.BuildStep):
+
+ def __init__(self, testcase=None, lock_accesses=None, **kwargs):
+ super().__init__(**kwargs)
+ self.testcase = testcase
+ self.lock_accesses = lock_accesses
+
+ @defer.inlineCallbacks
+ def run(self):
+ botmaster = self.build.builder.botmaster
+ real_master_lock = yield botmaster.getLockFromLockAccess(self.lock_accesses[0],
+ self.build.config_version)
+ real_worker_lock = yield botmaster.getLockFromLockAccess(self.lock_accesses[1],
+ self.build.config_version)
+
+ self.testcase.assertFalse(real_master_lock.isAvailable(self.testcase,
+ self.lock_accesses[0]))
+ self.testcase.assertIn('workername', real_worker_lock.locks)
+ self.testcase.assertFalse(real_worker_lock.locks['workername'].isAvailable(
+ self.testcase, self.lock_accesses[1]))
+ return SUCCESS
+
def setUp(self):
self.setUpTestReactor()
return self.setUpBuildStep()
@@ -161,23 +183,34 @@ class TestBuildStep(steps.BuildStepMixin, config.ConfigErrorsMixin,
@defer.inlineCallbacks
def test_renderableLocks(self):
- lock1 = locks.MasterLock("masterlock")
- lock2 = locks.WorkerLock("workerlock")
+ master_lock = locks.MasterLock("masterlock")
+ worker_lock = locks.WorkerLock("workerlock")
- renderedLocks = [False]
+ lock_accesses = []
@renderer
def rendered_locks(props):
- renderedLocks[0] = True
- access1 = locks.LockAccess(lock1, 'counting')
- access2 = locks.LockAccess(lock2, 'exclusive')
- return [access1, access2]
-
- self.setupStep(self.FakeBuildStep(locks=rendered_locks))
+ master_access = locks.LockAccess(master_lock, 'counting')
+ worker_access = locks.LockAccess(worker_lock, 'exclusive')
+ lock_accesses.append(master_access)
+ lock_accesses.append(worker_access)
+ return [master_access, worker_access]
+
+ self.setupStep(self.LockBuildStep(testcase=self, lock_accesses=lock_accesses,
+ locks=rendered_locks))
self.expectOutcome(result=SUCCESS)
yield self.runStep()
- self.assertTrue(renderedLocks[0])
+ self.assertEqual(len(lock_accesses), 2)
+
+ botmaster = self.step.build.builder.botmaster
+ real_master_lock = yield botmaster.getLockFromLockAccess(lock_accesses[0],
+ self.build.config_version)
+ real_worker_lock = yield botmaster.getLockFromLockAccess(lock_accesses[1],
+ self.build.config_version)
+ self.assertTrue(real_master_lock.isAvailable(self, lock_accesses[0]))
+ self.assertIn('workername', real_worker_lock.locks)
+ self.assertTrue(real_worker_lock.locks['workername'].isAvailable(self, lock_accesses[1]))
def test_compare(self):
lbs1 = buildstep.BuildStep(name="me")
@@ -196,14 +229,25 @@ class TestBuildStep(steps.BuildStepMixin, config.ConfigErrorsMixin,
@defer.inlineCallbacks
def test_regularLocks(self):
- lock1 = locks.MasterLock("masterlock")
- lock2 = locks.WorkerLock("workerlock")
+ master_lock = locks.MasterLock("masterlock")
+ worker_lock = locks.WorkerLock("workerlock")
+ lock_accesses = [locks.LockAccess(master_lock, 'counting'),
+ locks.LockAccess(worker_lock, 'exclusive')]
- self.setupStep(self.FakeBuildStep(
- locks=[locks.LockAccess(lock1, 'counting'), locks.LockAccess(lock2, 'exclusive')]))
+ self.setupStep(self.LockBuildStep(testcase=self, lock_accesses=lock_accesses,
+ locks=lock_accesses))
self.expectOutcome(result=SUCCESS)
yield self.runStep()
+ botmaster = self.step.build.builder.botmaster
+ real_master_lock = yield botmaster.getLockFromLockAccess(lock_accesses[0],
+ self.build.config_version)
+ real_worker_lock = yield botmaster.getLockFromLockAccess(lock_accesses[1],
+ self.build.config_version)
+ self.assertTrue(real_master_lock.isAvailable(self, lock_accesses[0]))
+ self.assertIn('workername', real_worker_lock.locks)
+ self.assertTrue(real_worker_lock.locks['workername'].isAvailable(self, lock_accesses[1]))
+
@defer.inlineCallbacks
def test_cancelWhileLocksAvailable(self):
|
test: Improve locking tests to actually check whether locks happened
|
buildbot_buildbot
|
train
|
b46692aefb93dcdc6833b24f32fb0755a9c42f63
|
diff --git a/packages/mdx/mdx-hast-to-jsx.js b/packages/mdx/mdx-hast-to-jsx.js
index <HASH>..<HASH> 100644
--- a/packages/mdx/mdx-hast-to-jsx.js
+++ b/packages/mdx/mdx-hast-to-jsx.js
@@ -72,7 +72,7 @@ function toJSX(node, parentNode = {}, options = {}) {
const exportNames = exportNodes
.map(node =>
- node.value.match(/export\s*(var|const|let|class|function)?\s*(\w+)/)
+ node.value.match(/^export\s*(var|const|let|class|function)?\s*(\w+)/)
)
.map(match => (Array.isArray(match) ? match[2] : null))
.filter(Boolean)
|
Ensure compiling hast doesn't fail if path contains export (#<I>)
|
mdx-js_mdx
|
train
|
0dba8b30f8f3c3cd71bd1c12aac1e71308352cea
|
diff --git a/unicodeutil/unicodeutil.py b/unicodeutil/unicodeutil.py
index <HASH>..<HASH> 100644
--- a/unicodeutil/unicodeutil.py
+++ b/unicodeutil/unicodeutil.py
@@ -5,6 +5,7 @@ from fractions import Fraction
import codecs
import os
import re
+import struct
import six
@@ -55,7 +56,7 @@ def _unichr(i):
return six.unichr(i)
except ValueError:
# Workaround the error "ValueError: unichr() arg not in range(0x10000) (narrow Python build)"
- return ("\\U%08x" % i).decode("unicode-escape")
+ return struct.pack("i", i).decode("utf-32")
def _hexstr_to_unichr(s):
|
Fix to get things working on PyPy3 on Windows <I>.
|
leonidessaguisagjr_unicodeutil
|
train
|
a58a792ba60578ad57f0a2d585c674fab45a23a2
|
diff --git a/mod/glossary/lib.php b/mod/glossary/lib.php
index <HASH>..<HASH> 100644
--- a/mod/glossary/lib.php
+++ b/mod/glossary/lib.php
@@ -3381,6 +3381,7 @@ function glossary_get_entries_by_letter($glossary, $context, $letter, $from, $li
$qb->join_user();
$qb->add_user_fields();
$qb->order_by('concept', 'entries');
+ $qb->order_by('id', 'entries', 'ASC'); // Sort on ID to avoid random ordering when entries share an ordering value.
$qb->limit($from, $limit);
// Fetching the entries.
@@ -3424,6 +3425,7 @@ function glossary_get_entries_by_date($glossary, $context, $order, $sort, $from,
} else {
$qb->order_by('timemodified', 'entries', $sort);
}
+ $qb->order_by('id', 'entries', $sort); // Sort on ID to avoid random ordering when entries share an ordering value.
// Fetching the entries.
$count = $qb->count_records();
@@ -3469,7 +3471,9 @@ function glossary_get_entries_by_category($glossary, $context, $categoryid, $fro
$qb->where('categoryid', 'entries_categories', null);
}
+ // Sort on additional fields to avoid random ordering when entries share an ordering value.
$qb->order_by('concept', 'entries');
+ $qb->order_by('id', 'entries', 'ASC');
$qb->limit($from, $limit);
// Fetching the entries.
@@ -3517,6 +3521,7 @@ function glossary_get_entries_by_author($glossary, $context, $letter, $field, $s
$qb->add_user_fields();
$qb->order_by_author($firstnamefirst, $sort);
$qb->order_by('concept', 'entries');
+ $qb->order_by('id', 'entries', 'ASC'); // Sort on ID to avoid random ordering when entries share an ordering value.
$qb->limit($from, $limit);
// Fetching the entries.
@@ -3563,6 +3568,7 @@ function glossary_get_entries_by_author_id($glossary, $context, $authorid, $orde
} else {
$qb->order_by('concept', 'entries', $sort);
}
+ $qb->order_by('id', 'entries', $sort); // Sort on ID to avoid random ordering when entries share an ordering value.
$qb->limit($from, $limit);
@@ -3684,7 +3690,7 @@ function glossary_get_entries_by_search($glossary, $context, $query, $fullsearch
} else {
$qb->order_by('concept', 'entries', $sort);
}
-
+ $qb->order_by('id', 'entries', $sort); // Sort on ID to avoid random ordering when entries share an ordering value.
$qb->limit($from, $limit);
// Fetching the entries.
@@ -3726,6 +3732,7 @@ function glossary_get_entries_by_term($glossary, $context, $term, $from, $limit,
$qb->filter_by_term($term);
$qb->order_by('concept', 'entries');
+ $qb->order_by('id', 'entries'); // Sort on ID to avoid random ordering when entries share an ordering value.
$qb->limit($from, $limit);
// Fetching the entries.
@@ -3769,6 +3776,7 @@ function glossary_get_entries_to_approve($glossary, $context, $letter, $order, $
} else {
$qb->order_by('concept', 'entries', $sort);
}
+ $qb->order_by('id', 'entries', $sort); // Sort on ID to avoid random ordering when entries share an ordering value.
$qb->limit($from, $limit);
// Fetching the entries.
|
MDL-<I> mod_glossary: Ensure consistent order when pagination is used
|
moodle_moodle
|
train
|
837755f551a2c1c6a3a73fdd900e80c20fc47239
|
diff --git a/src/renderers/sigma.renderers.def.js b/src/renderers/sigma.renderers.def.js
index <HASH>..<HASH> 100644
--- a/src/renderers/sigma.renderers.def.js
+++ b/src/renderers/sigma.renderers.def.js
@@ -12,10 +12,14 @@
webgl = !!global.WebGLRenderingContext;
if (webgl) {
canvas = document.createElement('canvas');
- webgl = !!(
- canvas.getContext('webgl') ||
- canvas.getContext('experimental-webgl')
- );
+ try {
+ webgl = !!(
+ canvas.getContext('webgl') ||
+ canvas.getContext('experimental-webgl')
+ );
+ } catch (e) {
+ webgl = false;
+ }
}
// Copy the good renderer:
|
Added try/catch for control WebGL options in "Hard Environments"
|
jacomyal_sigma.js
|
train
|
878bb58e1326e6e3979221ad32a66756f260fcd5
|
diff --git a/src/Alumni.php b/src/Alumni.php
index <HASH>..<HASH> 100644
--- a/src/Alumni.php
+++ b/src/Alumni.php
@@ -16,7 +16,7 @@ class Alumni extends Person
/**
* @param Person $person
* @param array $attrs
- * @return Person
+ * @return Alumni
*/
protected static function fill(Person $person, array $attrs)
{
@@ -30,7 +30,7 @@ class Alumni extends Person
/**
* @param string $developmentID
- * @return null|Person
+ * @return null|Alumni
*/
public static function fromDevelopmentID($developmentID)
{
diff --git a/src/Employee.php b/src/Employee.php
index <HASH>..<HASH> 100644
--- a/src/Employee.php
+++ b/src/Employee.php
@@ -16,7 +16,7 @@ class Employee extends Person
/**
* @param Person $person
* @param array $attrs
- * @return Person
+ * @return Employee
*/
protected static function fill(Person $person, array $attrs)
{
@@ -31,7 +31,7 @@ class Employee extends Person
/**
* @param string $employeeID
- * @return null|Person
+ * @return null|Employee
*/
public static function fromEmployeeID($employeeID)
{
diff --git a/src/Student.php b/src/Student.php
index <HASH>..<HASH> 100644
--- a/src/Student.php
+++ b/src/Student.php
@@ -68,7 +68,7 @@ class Student extends Person
/**
* @param string $identifier
- * @return null|Person
+ * @return null|Student
*/
protected static function fromSimpleIdentifier($identifier)
{
@@ -91,7 +91,7 @@ class Student extends Person
/**
* @param Person $person
* @param array $attrs
- * @return Person
+ * @return Student
*/
protected static function fill(Person $person, array $attrs)
{
@@ -109,7 +109,7 @@ class Student extends Person
/**
* @param string $studentNumber
- * @return null|Person
+ * @return null|Student
*/
public static function fromStudentNumber($studentNumber)
{
|
Provide more specific PHPDoc type hinting.
|
UWEnrollmentManagement_Person
|
train
|
9f70e16d88bc3af0685c69788dca18545c909622
|
diff --git a/doc/code.go b/doc/code.go
index <HASH>..<HASH> 100644
--- a/doc/code.go
+++ b/doc/code.go
@@ -299,13 +299,13 @@ func (b *builder) printExample(e *doc.Example) (code Code, output string) {
output = e.Output
b.buf = b.buf[:0]
- err := (&printer.Config{Mode: printer.UseSpaces, Tabwidth: 4}).Fprint(
- sliceWriter{&b.buf},
- b.fset,
- &printer.CommentedNode{
- Node: e.Code,
- Comments: e.Comments,
- })
+ var n interface{}
+ if _, ok := e.Code.(*ast.File); ok {
+ n = e.Play
+ } else {
+ n = &printer.CommentedNode{Node: e.Code, Comments: e.Comments}
+ }
+ err := (&printer.Config{Mode: printer.UseSpaces, Tabwidth: 4}).Fprint(sliceWriter{&b.buf}, b.fset, n)
if err != nil {
return Code{Text: err.Error()}, output
}
|
Use play code for examples to solve issue #<I>
Thanks @garyburd for saving me of the unholiness of faulty regexps
|
golang_gddo
|
train
|
370a83a11b2664d46c7f59e66d8daf5d5dbcfa80
|
diff --git a/describe.go b/describe.go
index <HASH>..<HASH> 100644
--- a/describe.go
+++ b/describe.go
@@ -15,32 +15,45 @@ import (
)
// RE for sanitizing golang/JS layer
-var reSanitizeMermaidNodeName = regexp.MustCompile("[\\s\\W]+")
+var reSanitizeMermaidNodeName = regexp.MustCompile("[\\W\\s]+")
+var reSanitizeMermaidLabelValue = regexp.MustCompile("[\\{\\}\"']+")
-func sanitizedNodeName(sourceName string) string {
- return reSanitizeMermaidNodeName.ReplaceAllString(sourceName, "")
+func mermaidNodeName(sourceName string) string {
+ return reSanitizeMermaidNodeName.ReplaceAllString(sourceName, "x")
+}
+
+func mermaidLabelValue(labelText string) string {
+ return reSanitizeMermaidLabelValue.ReplaceAllString(labelText, "")
}
func writeNode(writer io.Writer, nodeName string, nodeColor string) {
- fmt.Fprintf(writer, "style %s fill:#%s,stroke:#000,stroke-width:1px;\n", nodeName, nodeColor)
- fmt.Fprintf(writer, "%s[%s]\n", nodeName, nodeName)
+ sanitizedName := mermaidNodeName(nodeName)
+ fmt.Fprintf(writer, "style %s fill:#%s,stroke:#000,stroke-width:1px;\n", sanitizedName, nodeColor)
+ fmt.Fprintf(writer, "%s[%s]\n", sanitizedName, mermaidLabelValue(nodeName))
}
func writeLink(writer io.Writer, fromNode string, toNode string, label string) {
+ sanitizedFrom := mermaidNodeName(fromNode)
+ sanitizedTo := mermaidNodeName(toNode)
+
if "" != label {
- fmt.Fprintf(writer, "%s-- \"%s\" -->%s\n", fromNode, label, toNode)
+ fmt.Fprintf(writer, "%s-- \"%s\" -->%s\n", sanitizedFrom, mermaidLabelValue(label), sanitizedTo)
} else {
- fmt.Fprintf(writer, "%s-->%s\n", fromNode, toNode)
+ fmt.Fprintf(writer, "%s-->%s\n", sanitizedFrom, sanitizedTo)
}
}
-func describeAPI() string {
- return ""
-}
// Describe produces a graphical representation of a service's Lambda and data sources. Typically
// automatically called as part of a compiled golang binary via the `describe` command
// line option.
-func Describe(serviceName string, serviceDescription string, lambdaAWSInfos []*LambdaAWSInfo, api *API, s3Site *S3Site, outputWriter io.Writer, logger *logrus.Logger) error {
+func Describe(serviceName string,
+ serviceDescription string,
+ lambdaAWSInfos []*LambdaAWSInfo,
+ api *API,
+ s3Site *S3Site,
+ outputWriter io.Writer,
+ logger *logrus.Logger) error {
+
var cloudFormationTemplate bytes.Buffer
err := Provision(true,
serviceName,
@@ -75,16 +88,14 @@ func Describe(serviceName string, serviceDescription string, lambdaAWSInfos []*L
for _, eachPermission := range eachLambda.Permissions {
name, link := eachPermission.descriptionInfo()
- mermaidName := sanitizedNodeName(name)
// Style it to have the Amazon color
- writeNode(&b, mermaidName, "F1702A")
- writeLink(&b, mermaidName, eachLambda.lambdaFnName, strings.Replace(link, " ", "<br>", -1))
+ writeNode(&b, name, "F1702A")
+ writeLink(&b, name, eachLambda.lambdaFnName, strings.Replace(link, " ", "<br>", -1))
}
for _, eachEventSourceMapping := range eachLambda.EventSourceMappings {
- nodeName := sanitizedNodeName(eachEventSourceMapping.EventSourceArn)
- writeNode(&b, nodeName, "F1702A")
- writeLink(&b, nodeName, eachLambda.lambdaFnName, "")
+ writeNode(&b, eachEventSourceMapping.EventSourceArn, "F1702A")
+ writeLink(&b, eachEventSourceMapping.EventSourceArn, eachLambda.lambdaFnName, "")
}
}
diff --git a/resources/describe/template.html b/resources/describe/template.html
index <HASH>..<HASH> 100644
--- a/resources/describe/template.html
+++ b/resources/describe/template.html
@@ -218,10 +218,10 @@
<div class="tab-content container-fluid">
<div role="tabpanel" class="tab-pane active" id="lambda">
<div class="mermaid spartaLayout" id="mermaidGraph">
- %% Sparta Graph
- graph LR
+%% Sparta Graph
+graph LR
- {{ .MermaidData}}
+{{ .MermaidData}}
</div>
</div>
<div role="tabpanel" class="tab-pane" id="apigateway">
diff --git a/sparta.go b/sparta.go
index <HASH>..<HASH> 100644
--- a/sparta.go
+++ b/sparta.go
@@ -879,7 +879,9 @@ func (perm SESPermission) export(serviceName string,
}
func (perm SESPermission) descriptionInfo() (string, string) {
- return perm.BasePermission.describeInfoArn(), ""
+ // SES doesn't use ARNs, but "*" breaks mermaids parser, so
+ // use entity code per: http://knsv.github.io/mermaid/#special-characters-that-break-syntax
+ return "Not Applicable", "All verified domain(s) email"
}
//
|
Patch up `describe` output s.t. Mermaid parser doesn't fail
|
mweagle_Sparta
|
train
|
971cd184b491f12e0a5e8f9811b73642b4d37f43
|
diff --git a/kaba/kaba/js.js b/kaba/kaba/js.js
index <HASH>..<HASH> 100644
--- a/kaba/kaba/js.js
+++ b/kaba/kaba/js.js
@@ -6,22 +6,13 @@
* output: string,
* ignoreLintFor: Array.<(string|RegExp)>,
* }} JsTaskConfig
- *
- * @typedef {{
- * srcDir: string,
- * output: string,
- * ignoreLintFor: Array.<(string|RegExp)>,
- * }} InternalJsTaskConfig
*/
-
let fs = require("fs");
let JsTask = require("./js/js-task");
const _ = require("lodash");
-
-
/**
* Main task for Sass
*
@@ -39,19 +30,11 @@ module.exports = function (config = {})
}, config);
// build internal config
- var srcDir = config.input.replace(/\/+$/, "") + "/";
-
- /** @var {InternalJsTaskConfig} internalConfig */
- let internalConfig = {
- // ensure exactly one slash at the end
- srcDir: srcDir,
- output: config.output,
- ignoreLintFor: config.ignoreLintFor
- };
+ config.input = config.input.replace(/\/+$/, "") + "/";
return function (done, debug)
{
- let task = new JsTask(internalConfig);
+ let task = new JsTask(config);
task.run(debug);
}
};
diff --git a/kaba/kaba/js/js-directory-task.js b/kaba/kaba/js/js-directory-task.js
index <HASH>..<HASH> 100644
--- a/kaba/kaba/js/js-directory-task.js
+++ b/kaba/kaba/js/js-directory-task.js
@@ -24,15 +24,15 @@ module.exports = class JsDirectoryTask
{
/**
* @param {string} srcDir
- * @param {InternalJsTaskConfig} options
+ * @param {JsTaskConfig} config
*/
- constructor (srcDir, options)
+ constructor (srcDir, config)
{
/**
* @private
- * @type {InternalJsTaskConfig}
+ * @type {JsTaskConfig}
*/
- this.options = options;
+ this.config = config;
/**
* @private
@@ -53,7 +53,7 @@ module.exports = class JsDirectoryTask
* @private
* @type {string}
*/
- this.outputDir = path.resolve(this.srcDir, options.output);
+ this.outputDir = path.resolve(this.srcDir, config.output);
/**
* @private
@@ -122,7 +122,7 @@ module.exports = class JsDirectoryTask
// register event listener for linter and update
browserifyInstance
.on("update", () => this.buildFromBrowserify(browserifyInstance, file, debug))
- .on("file", (file) => lint(file, this.srcDir, this.options));
+ .on("file", (file) => lint(file, this.srcDir, this.config));
}
// if not debug, build from the browserify instance
diff --git a/kaba/kaba/js/js-task.js b/kaba/kaba/js/js-task.js
index <HASH>..<HASH> 100644
--- a/kaba/kaba/js/js-task.js
+++ b/kaba/kaba/js/js-task.js
@@ -12,13 +12,13 @@ module.exports = class JsTask
{
/**
*
- * @param {InternalJsTaskConfig} config
+ * @param {JsTaskConfig} config
*/
constructor (config)
{
/**
* @private
- * @type {InternalJsTaskConfig}
+ * @type {JsTaskConfig}
*/
this.config = config;
}
@@ -30,7 +30,7 @@ module.exports = class JsTask
return new Promise (
(resolve, reject) => {
- glob(this.config.srcDir,
+ glob(this.config.input,
(error, directories) => {
if (error)
{
diff --git a/kaba/kaba/js/lint.js b/kaba/kaba/js/lint.js
index <HASH>..<HASH> 100644
--- a/kaba/kaba/js/lint.js
+++ b/kaba/kaba/js/lint.js
@@ -11,7 +11,7 @@ const filePathMatcher = require("../../lib/file-path-matcher");
*
* @param {string} file
* @param {string} srcDir
- * @param {InternalJsTaskConfig} config
+ * @param {JsTaskConfig} config
*/
module.exports = function (file, srcDir, config)
{
|
Only use one config throughout the JS task
|
Becklyn_kaba
|
train
|
2acca770eff3d78b68b0d356acba5517a9a41029
|
diff --git a/server.go b/server.go
index <HASH>..<HASH> 100644
--- a/server.go
+++ b/server.go
@@ -2,6 +2,7 @@ package yarpc
import (
"net"
+ "sync"
"encoding/binary"
"io"
@@ -48,6 +49,7 @@ type Server struct {
m map[uint8]*service
serve bool
lis net.Listener
+ lisMu sync.Mutex
}
type options struct {
@@ -117,7 +119,10 @@ func (s *Server) register(sd *ServiceDesc, ss interface{}) {
}
func (s *Server) Serve(lis net.Listener) error {
+ s.lisMu.Lock()
s.lis = lis
+ s.lisMu.Unlock()
+
for {
rawConn, err := lis.Accept()
if err != nil {
@@ -134,6 +139,9 @@ func (s *Server) Serve(lis net.Listener) error {
}
func (s *Server) Stop() {
+ s.lisMu.Lock()
+ defer s.lisMu.Unlock()
+
if s.lis != nil {
s.lis.Close()
s.lis = nil
|
Add a mutex to avoid a data race when starting/stopping a server
|
influxdata_yarpc
|
train
|
d4939a670a71e9ffc9b988829b7e87887009995c
|
diff --git a/admin_site_logs.php b/admin_site_logs.php
index <HASH>..<HASH> 100644
--- a/admin_site_logs.php
+++ b/admin_site_logs.php
@@ -212,6 +212,11 @@ $url=
'&user='.rawurlencode($user).
'&gedc='.rawurlencode($gedc);
+$gedc_array=array();
+foreach (get_all_gedcoms() as $ged_name) {
+ $gedc_array[$ged_name]=$ged_name;
+}
+
echo
WT_JS_END,
'<form name="logs" method="get" action="'.WT_SCRIPT_NAME.'">',
@@ -235,7 +240,7 @@ echo
WT_I18N::translate('User'), '<br />', select_edit_control('user', array_combine(get_all_users(), get_all_users()), '', $user, ''),
'</td>',
'<td>',
- WT_I18N::translate('Family tree'), '<br />', select_edit_control('gedc', array_combine(get_all_gedcoms(), get_all_gedcoms()), '', $gedc, WT_USER_IS_ADMIN ? '' : 'disabled'),
+ WT_I18N::translate('Family tree'), '<br />', select_edit_control('gedc', $gedc_array, '', $gedc, WT_USER_IS_ADMIN ? '' : 'disabled'),
'</td>',
'<td>',
'<input type="submit" value="', WT_I18N::translate('Filter'), '" />',
|
Fix: site-logs page fails when there are no gedcoms (e.g. immediately after installation)
|
fisharebest_webtrees
|
train
|
61838982766831a29844d07b33b36cff2e91ae30
|
diff --git a/SingularityS3Uploader/src/main/java/com/hubspot/singularity/s3uploader/SingularityS3Uploader.java b/SingularityS3Uploader/src/main/java/com/hubspot/singularity/s3uploader/SingularityS3Uploader.java
index <HASH>..<HASH> 100644
--- a/SingularityS3Uploader/src/main/java/com/hubspot/singularity/s3uploader/SingularityS3Uploader.java
+++ b/SingularityS3Uploader/src/main/java/com/hubspot/singularity/s3uploader/SingularityS3Uploader.java
@@ -9,6 +9,7 @@ import java.nio.file.PathMatcher;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.List;
+import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.Callable;
@@ -233,6 +234,16 @@ public class SingularityS3Uploader implements Closeable {
S3Object object = new S3Object(s3Bucket, file.toFile());
object.setKey(key);
+ final String fileExtension = com.google.common.io.Files.getFileExtension(file.toString());
+
+ for (Map.Entry<String, Set<String>> entry : configuration.getS3ContentEncodingFileExtensions().entrySet()) {
+ if (entry.getValue().contains(fileExtension)) {
+ LOG.debug("{} Using content encoding '{}' for file {}", logIdentifier, entry.getKey(), file);
+ object.setContentEncoding(entry.getKey());
+ break;
+ }
+ }
+
if (fileSizeBytes > configuration.getMaxSingleUploadSizeBytes()) {
multipartUpload(object);
} else {
diff --git a/SingularityS3Uploader/src/main/java/com/hubspot/singularity/s3uploader/config/SingularityS3UploaderConfiguration.java b/SingularityS3Uploader/src/main/java/com/hubspot/singularity/s3uploader/config/SingularityS3UploaderConfiguration.java
index <HASH>..<HASH> 100644
--- a/SingularityS3Uploader/src/main/java/com/hubspot/singularity/s3uploader/config/SingularityS3UploaderConfiguration.java
+++ b/SingularityS3Uploader/src/main/java/com/hubspot/singularity/s3uploader/config/SingularityS3UploaderConfiguration.java
@@ -1,7 +1,9 @@
package com.hubspot.singularity.s3uploader.config;
+import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
+import java.util.Set;
import java.util.concurrent.TimeUnit;
import javax.validation.constraints.Max;
@@ -10,6 +12,7 @@ import javax.validation.constraints.NotNull;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.google.common.base.Optional;
+import com.google.common.collect.ImmutableMap;
import com.hubspot.singularity.runner.base.configuration.BaseRunnerConfiguration;
import com.hubspot.singularity.runner.base.configuration.Configuration;
import com.hubspot.singularity.runner.base.jackson.Obfuscate;
@@ -67,6 +70,10 @@ public class SingularityS3UploaderConfiguration extends BaseRunnerConfiguration
@JsonProperty
private Map<String, SingularityS3Credentials> s3BucketCredentials = new HashMap<>();
+ @NotNull
+ @JsonProperty
+ private Map<String, Set<String>> s3ContentEncodingFileExtensions = ImmutableMap.of("gzip", Collections.singleton("gz"));
+
public SingularityS3UploaderConfiguration() {
super(Optional.of("singularity-s3uploader.log"));
}
@@ -167,6 +174,14 @@ public class SingularityS3UploaderConfiguration extends BaseRunnerConfiguration
this.s3BucketCredentials = s3BucketCredentials;
}
+ public Map<String, Set<String>> getS3ContentEncodingFileExtensions() {
+ return s3ContentEncodingFileExtensions;
+ }
+
+ public void setS3ContentEncodingFileExtensions(Map<String, Set<String>> s3ContentEncodingFileExtensions) {
+ this.s3ContentEncodingFileExtensions = s3ContentEncodingFileExtensions;
+ }
+
@Override
public String toString() {
return "SingularityS3UploaderConfiguration[" +
@@ -182,6 +197,7 @@ public class SingularityS3UploaderConfiguration extends BaseRunnerConfiguration
", retryCount=" + retryCount +
", checkForOpenFiles=" + checkForOpenFiles +
", s3BucketCredentials=" + s3BucketCredentials +
+ ", s3ContentEncodingFileExtensions=" + s3ContentEncodingFileExtensions +
']';
}
}
|
set proper Content-Encoding for s3 uploads
|
HubSpot_Singularity
|
train
|
ea8bb3c267f372f8c30634853aa737b8fa919a94
|
diff --git a/lib/jsonapi/resource_serializer.rb b/lib/jsonapi/resource_serializer.rb
index <HASH>..<HASH> 100644
--- a/lib/jsonapi/resource_serializer.rb
+++ b/lib/jsonapi/resource_serializer.rb
@@ -353,8 +353,10 @@ module JSONAPI
end
def to_one_linkage(source, relationship)
- return unless linkage_id = foreign_key_value(source, relationship)
- return unless linkage_type = format_key(relationship.type_for_source(source))
+ linkage_id = foreign_key_value(source, relationship)
+ linkage_type = format_key(relationship.type_for_source(source))
+ return unless linkage_id.present? && linkage_type.present?
+
{
type: linkage_type,
id: linkage_id,
|
test presence (catch empty strings too) of linkage_id and linkage_type
|
cerebris_jsonapi-resources
|
train
|
46f525c7d6be823684ccd183ef909d92385244c8
|
diff --git a/libnetwork/drivers/bridge/bridge_store.go b/libnetwork/drivers/bridge/bridge_store.go
index <HASH>..<HASH> 100644
--- a/libnetwork/drivers/bridge/bridge_store.go
+++ b/libnetwork/drivers/bridge/bridge_store.go
@@ -83,9 +83,9 @@ func (d *driver) populateEndpoints() error {
n, ok := d.networks[ep.nid]
if !ok {
logrus.Debugf("Network (%s) not found for restored bridge endpoint (%s)", ep.nid[0:7], ep.id[0:7])
- logrus.Debugf("Deleting stale bridge endpoint (%s) from store", ep.nid[0:7])
+ logrus.Debugf("Deleting stale bridge endpoint (%s) from store", ep.id[0:7])
if err := d.storeDelete(ep); err != nil {
- logrus.Debugf("Failed to delete stale bridge endpoint (%s) from store", ep.nid[0:7])
+ logrus.Debugf("Failed to delete stale bridge endpoint (%s) from store", ep.id[0:7])
}
continue
}
diff --git a/libnetwork/drivers/ipvlan/ipvlan_store.go b/libnetwork/drivers/ipvlan/ipvlan_store.go
index <HASH>..<HASH> 100644
--- a/libnetwork/drivers/ipvlan/ipvlan_store.go
+++ b/libnetwork/drivers/ipvlan/ipvlan_store.go
@@ -96,9 +96,9 @@ func (d *driver) populateEndpoints() error {
n, ok := d.networks[ep.nid]
if !ok {
logrus.Debugf("Network (%s) not found for restored ipvlan endpoint (%s)", ep.nid[0:7], ep.id[0:7])
- logrus.Debugf("Deleting stale ipvlan endpoint (%s) from store", ep.nid[0:7])
+ logrus.Debugf("Deleting stale ipvlan endpoint (%s) from store", ep.id[0:7])
if err := d.storeDelete(ep); err != nil {
- logrus.Debugf("Failed to delete stale ipvlan endpoint (%s) from store", ep.nid[0:7])
+ logrus.Debugf("Failed to delete stale ipvlan endpoint (%s) from store", ep.id[0:7])
}
continue
}
diff --git a/libnetwork/drivers/macvlan/macvlan_store.go b/libnetwork/drivers/macvlan/macvlan_store.go
index <HASH>..<HASH> 100644
--- a/libnetwork/drivers/macvlan/macvlan_store.go
+++ b/libnetwork/drivers/macvlan/macvlan_store.go
@@ -96,9 +96,9 @@ func (d *driver) populateEndpoints() error {
n, ok := d.networks[ep.nid]
if !ok {
logrus.Debugf("Network (%s) not found for restored macvlan endpoint (%s)", ep.nid[0:7], ep.id[0:7])
- logrus.Debugf("Deleting stale macvlan endpoint (%s) from store", ep.nid[0:7])
+ logrus.Debugf("Deleting stale macvlan endpoint (%s) from store", ep.id[0:7])
if err := d.storeDelete(ep); err != nil {
- logrus.Debugf("Failed to delete stale macvlan endpoint (%s) from store", ep.nid[0:7])
+ logrus.Debugf("Failed to delete stale macvlan endpoint (%s) from store", ep.id[0:7])
}
continue
}
diff --git a/libnetwork/drivers/overlay/overlay.go b/libnetwork/drivers/overlay/overlay.go
index <HASH>..<HASH> 100644
--- a/libnetwork/drivers/overlay/overlay.go
+++ b/libnetwork/drivers/overlay/overlay.go
@@ -111,7 +111,11 @@ func (d *driver) restoreEndpoints() error {
ep := kvo.(*endpoint)
n := d.network(ep.nid)
if n == nil {
- logrus.Debugf("Network (%s) not found for restored endpoint (%s)", ep.nid, ep.id)
+ logrus.Debugf("Network (%s) not found for restored endpoint (%s)", ep.nid[0:7], ep.id[0:7])
+ logrus.Debugf("Deleting stale overlay endpoint (%s) from store", ep.id[0:7])
+ if err := d.deleteEndpointFromStore(ep); err != nil {
+ logrus.Debugf("Failed to delete stale overlay endpoint (%s) from store", ep.id[0:7])
+ }
continue
}
n.addEndpoint(ep)
|
Overlay driver to cleanup stale endpoints
|
moby_moby
|
train
|
5577c966ca242741705ae4ad5913dc4b86ffa501
|
diff --git a/commerce-openapi-util/src/main/java/com/liferay/commerce/openapi/util/Response.java b/commerce-openapi-util/src/main/java/com/liferay/commerce/openapi/util/Response.java
index <HASH>..<HASH> 100644
--- a/commerce-openapi-util/src/main/java/com/liferay/commerce/openapi/util/Response.java
+++ b/commerce-openapi-util/src/main/java/com/liferay/commerce/openapi/util/Response.java
@@ -57,11 +57,6 @@ public class Response {
sb.append("{content={");
- for (Content content : _contents) {
- sb.append(content);
- sb.append(", ");
- }
-
Iterator<Content> iterator = _contents.iterator();
while (iterator.hasNext()) {
|
COMMERCE-<I> commerce-openapi-util - Remove duplicated section
(cherry picked from commit <I>d<I>fdc9e3a<I>d3c<I>eaac1e<I>)
|
liferay_com-liferay-commerce
|
train
|
27c3e727b073701bfc739859d8325435d27cbf35
|
diff --git a/index.js b/index.js
index <HASH>..<HASH> 100644
--- a/index.js
+++ b/index.js
@@ -97,12 +97,22 @@ class HtmlWebpackPlugin {
// Clear the cache once a new HtmlWebpackPlugin is added
childCompiler.clearCache(compiler);
- // Clear the cache if the child compiler is outdated
+ // Register all HtmlWebpackPlugins instances at the child compiler
compiler.hooks.thisCompilation.tap('HtmlWebpackPlugin', (compilation) => {
+ // Clear the cache if the child compiler is outdated
if (childCompiler.hasOutDatedTemplateCache(compilation)) {
childCompiler.clearCache(compiler);
}
+ // Add this instances template to the child compiler
childCompiler.addTemplateToCompiler(compiler, this.options.template);
+ // Add file dependencies of child compiler to parent compiler
+ // to keep them watched even if we get the result from the cache
+ compilation.hooks.additionalChunkAssets.tap('HtmlWebpackPlugin', () => {
+ const childCompilerDependencies = childCompiler.getFileDependencies(compiler);
+ childCompilerDependencies.forEach(fileDependency => {
+ compilation.compilationDependencies.add(fileDependency);
+ });
+ });
});
// setup hooks for third party plugins
diff --git a/lib/compiler.js b/lib/compiler.js
index <HASH>..<HASH> 100644
--- a/lib/compiler.js
+++ b/lib/compiler.js
@@ -37,6 +37,10 @@ class HtmlWebpackChildCompiler {
*/
this.compilationStartedTimestamp;
/**
+ * @type {number}
+ */
+ this.compilationEndedTimestamp;
+ /**
* All file dependencies of the child compiler
* @type {string[]}
*/
@@ -52,23 +56,38 @@ class HtmlWebpackChildCompiler {
* Add a templatePath to the child compiler
* The given template will be compiled by `compileTemplates`
* @param {string} template - The webpack path to the template e.g. `'!!html-loader!index.html'`
+ * @returns {boolean} true if the template is new
*/
addTemplate (template) {
const templateId = this.templates.indexOf(template);
// Don't add the template to the compiler if a similar template was already added
if (templateId !== -1) {
- return templateId;
+ return false;
}
// A child compiler can compile only once
// throw an error if a new template is added after the compilation started
- if (this.compilationPromise) {
+ if (this.isCompiling()) {
throw new Error('New templates can only be added before `compileTemplates` was called.');
}
// Add the template to the childCompiler
- const newTemplateId = this.templates.length;
this.templates.push(template);
// Mark the cache invalid
- return newTemplateId;
+ return true;
+ }
+
+ /**
+ * Returns true if the childCompiler is currently compiling
+ * @retuns {boolean}
+ */
+ isCompiling () {
+ return !this.didCompile() && this.compilationStartedTimestamp !== undefined;
+ }
+
+ /**
+ * Returns true if the childCOmpiler is done compiling
+ */
+ didCompile () {
+ return this.compilationEndedTimestamp !== undefined;
}
/**
@@ -158,6 +177,7 @@ class HtmlWebpackChildCompiler {
entry: entries[entryIndex]
};
});
+ this.compilationEndedTimestamp = new Date().getTime();
resolve(result);
});
});
@@ -266,7 +286,12 @@ function getChildCompiler (mainCompiler) {
* @param {WebpackCompiler} mainCompiler
*/
function clearCache (mainCompiler) {
- childCompilerCache.delete(mainCompiler);
+ const childCompiler = getChildCompiler(mainCompiler);
+ // If this childCompiler was already used
+ // remove the entire childCompiler from the cache
+ if (childCompiler.isCompiling() || childCompiler.didCompile()) {
+ childCompilerCache.delete(mainCompiler);
+ }
}
/**
@@ -275,7 +300,11 @@ function clearCache (mainCompiler) {
* @param {string} templatePath
*/
function addTemplateToCompiler (mainCompiler, templatePath) {
- getChildCompiler(mainCompiler).addTemplate(templatePath);
+ const childCompiler = getChildCompiler(mainCompiler);
+ const isNew = childCompiler.addTemplate(templatePath);
+ if (isNew) {
+ clearCache(mainCompiler);
+ }
}
/**
@@ -321,9 +350,21 @@ function hasOutDatedTemplateCache (compilation) {
return childCompiler ? childCompiler.hasOutDatedTemplateCache(compilation) : false;
}
+/**
+ * Return all file dependencies of the last child compilation
+ *
+ * @param {WebpackCompiler} compiler
+ * @returns {Array<string>}
+ */
+function getFileDependencies (compiler) {
+ const childCompiler = getChildCompiler(compiler);
+ return childCompiler.fileDependencies;
+}
+
module.exports = {
addTemplateToCompiler,
compileTemplate,
hasOutDatedTemplateCache,
- clearCache
+ clearCache,
+ getFileDependencies
};
|
fix: Add dependencies from the child compilation to the main compilation
|
jantimon_html-webpack-plugin
|
train
|
f866edf07a61a928c57daf590240e6f52927d687
|
diff --git a/views/js/runner/provider/qti.js b/views/js/runner/provider/qti.js
index <HASH>..<HASH> 100644
--- a/views/js/runner/provider/qti.js
+++ b/views/js/runner/provider/qti.js
@@ -118,6 +118,8 @@ define([
if (results.testMap) {
self.setTestMap(results.testMap);
+ } else {
+ updateStats();
}
load();
@@ -158,7 +160,57 @@ define([
self.getProxy().storeItemResponse(context.itemUri, self.itemRunner.getResponses())
]);
}
- return Promise.resolve();
+ return Promise.resolve([]);
+ };
+
+ /**
+ * Update the stats on the TestMap
+ * @param {Boolean} answered - if we flag the current item as answered
+ */
+ var updateStats = function updateStats(answered){
+
+ var stats = {
+ answered : 0,
+ viewed : 0
+ };
+
+ var context = self.getTestContext();
+ var testMap = self.getTestMap();
+
+ var testPart = testMap.parts[context.testPartId];
+ var section = testPart.sections[context.sectionId];
+ var item = section.items[context.itemIdentifier];
+
+ //reduce by sum up the stats
+ var accStats = function accStats(acc, level){
+ acc.answered += level.stats.answered;
+ acc.viewed += level.stats.viewed;
+ return acc;
+ };
+
+ //flag as viewed, always
+ item.viewed = true;
+ if(answered){
+ item.answered = true;
+ }
+
+ //compute section stats from it's items
+ section.stats = _.reduce(section.items, function(acc, item){
+ if(item.answered){
+ acc.answered++;
+ }
+ if(item.viewed){
+ acc.viewed++;
+ }
+ return acc;
+ }, _.clone(stats));
+
+ //compute testParts and test stats
+ testPart.stats =_.reduce(testPart.sections, accStats, _.clone(stats));
+ testMap.stats =_.reduce(testMap.parts, accStats, _.clone(stats));
+
+ //reassign the map
+ self.setTestMap(testMap);
};
//install behavior events handlers
@@ -167,8 +219,19 @@ define([
})
.on('move', function(direction, scope, position){
- store().then(function(results){
+ //Try to store the data
+ store()
+ .then(function(results){
+
+ //if we have an item session, then the item is answered
+ if(results && results[1] && results[1].itemSession){
+ updateStats(true);
+ } else {
+ updateStats();
+ }
+
+ //and then load the next item
computeNext('move', {
direction : direction,
scope : scope || 'item',
|
update and maintain test map stats client side
|
oat-sa_extension-tao-testqti
|
train
|
2223c6323769fd84e6ad10576aa4ddd247583b3e
|
diff --git a/cumulusci/cli/tests/test_config.py b/cumulusci/cli/tests/test_config.py
index <HASH>..<HASH> 100644
--- a/cumulusci/cli/tests/test_config.py
+++ b/cumulusci/cli/tests/test_config.py
@@ -47,11 +47,8 @@ class TestCliConfig(unittest.TestCase):
config.global_config.get_project_config = mock.Mock(
side_effect=ProjectConfigNotFound
)
- try:
+ with self.assertRaises(click.UsageError):
config._load_project_config()
- except click.UsageError:
- pass
- self.assertIsNone(config.project_config)
def test_load_project_config_error(self):
config = CliConfig()
|
test what you want, not what DG left
|
SFDO-Tooling_CumulusCI
|
train
|
95d346b231bfabe5d21efb516ea0b539d72c78f3
|
diff --git a/examples/blink.go b/examples/blink.go
index <HASH>..<HASH> 100644
--- a/examples/blink.go
+++ b/examples/blink.go
@@ -12,12 +12,6 @@ import (
)
func main() {
- // select which driver you're using, which depends on what kind of board you're using.
- // Here, we are using a beaglebone. These will not be required at all once hwio can
- // determine the driver directly from the running environment.
- driver := new(hwio.BeagleBoneDriver)
- hwio.SetDriver(driver)
-
// get a pin by name. You could also just use the logical pin number, but this is
// more readable. On BeagleBone, USR0 is an on-board LED.
ledPin, err := hwio.GetPin("USR1")
diff --git a/examples/pinmap.go b/examples/pinmap.go
index <HASH>..<HASH> 100644
--- a/examples/pinmap.go
+++ b/examples/pinmap.go
@@ -11,12 +11,6 @@ import (
)
func main() {
- // select which driver you're using, which depends on what kind of board you're using.
- // Here, we are using a beaglebone. These will not be required at all once hwio can
- // determine the driver directly from the running environment.
- driver := new(hwio.BeagleBoneDriver)
- hwio.SetDriver(driver)
-
hwio.DebugPinMap()
}
diff --git a/examples/shiftout.go b/examples/shiftout.go
index <HASH>..<HASH> 100644
--- a/examples/shiftout.go
+++ b/examples/shiftout.go
@@ -8,11 +8,7 @@ import (
)
func main() {
- // Select driver
- driver := new(hwio.BeagleBoneDriver)
- hwio.SetDriver(driver)
-
- // Get the pins we're going to use
+ // Get the pins we're going to use. These are on a beaglebone.
dataPin, _ := hwio.GetPin("P8.3") // connected to pin 14
clockPin, _ := hwio.GetPin("P8.4") // connected to pin 11
storePin, _ := hwio.GetPin("P8.5") // connected to pin 12
diff --git a/hwio.go b/hwio.go
index <HASH>..<HASH> 100644
--- a/hwio.go
+++ b/hwio.go
@@ -8,6 +8,8 @@ import (
"errors"
"fmt"
"time"
+ "os/exec"
+ "strings"
)
type BitShiftOrder byte
@@ -50,9 +52,20 @@ func init() {
determineDriver()
}
-// Work out the driver from environment if we can.
+// Work out the driver from environment if we can. If we have any problems,
+// don't generate an error, just return with the driver not set.
+// @todo use reflection to determine all implementors of the driver interface, and
+// @todo call a method on the interface to self-detect. init and
+// @todo constructor of drivers should do no setup in this case, esp of hardware
func determineDriver() {
- SetDriver(new(BeagleBoneDriver))
+ uname, e := exec.Command("uname", "-a").Output()
+ if e != nil {
+ return
+ }
+
+ if strings.Contains(string(uname), "beaglebone") {
+ SetDriver(new(BeagleBoneDriver))
+ }
}
// Check if the driver is assigned. If not, return an error to indicate that,
|
Autodetect beaglebone driver, and remove explicit driver assignment from examples
|
mrmorphic_hwio
|
train
|
28817f0f0ae5b3fbb71cf0cd7a73a9c72477fc6d
|
diff --git a/packages/pipelines-v5/commands/pipelines/diff.js b/packages/pipelines-v5/commands/pipelines/diff.js
index <HASH>..<HASH> 100644
--- a/packages/pipelines-v5/commands/pipelines/diff.js
+++ b/packages/pipelines-v5/commands/pipelines/diff.js
@@ -46,18 +46,19 @@ function * getAppInfo (heroku, appName, appId) {
// Find the commit hash of the latest release for this app
let slug
try {
- const release = yield heroku.request({
+ const releases = yield heroku.request({
method: 'GET',
path: `/apps/${appId}/releases`,
- headers: { 'Accept': V3_HEADER, 'Range': 'version ..; order=desc,max=1' },
+ headers: { 'Accept': V3_HEADER, 'Range': 'version ..; order=desc' },
partial: true
})
- if (release[0].slug === null) {
+ const release = releases.find((r) => r.status === 'succeeded')
+ if (!release || !release.slug) {
throw new Error(`no release found for ${appName}`)
}
slug = yield heroku.request({
method: 'GET',
- path: `/apps/${appId}/slugs/${release[0].slug.id}`,
+ path: `/apps/${appId}/slugs/${release.slug.id}`,
headers: { 'Accept': V3_HEADER }
})
} catch (err) {
diff --git a/packages/pipelines-v5/test/commands/pipelines/diff.js b/packages/pipelines-v5/test/commands/pipelines/diff.js
index <HASH>..<HASH> 100644
--- a/packages/pipelines-v5/test/commands/pipelines/diff.js
+++ b/packages/pipelines-v5/test/commands/pipelines/diff.js
@@ -145,7 +145,7 @@ describe('pipelines:diff', function () {
})
})
- it('should return an error if the target app has no release', function () {
+ it('should return an error if the target app has a release with no slug', function () {
nock(kolkrabbiApi)
.get(`/apps/${targetApp.id}/github`)
.reply(200, targetGithubApp)
@@ -159,6 +159,21 @@ describe('pipelines:diff', function () {
expect(cli.stderr).to.contain('No release was found')
})
})
+
+ it('should return an error if the target app has no release', function () {
+ nock(kolkrabbiApi)
+ .get(`/apps/${targetApp.id}/github`)
+ .reply(200, targetGithubApp)
+ const req = nock(api)
+ .get(`/apps/${targetApp.id}/releases`)
+ .reply(200, [])
+
+ return cmd.run({ app: targetApp.name })
+ .then(function () {
+ req.done()
+ expect(cli.stderr).to.contain('No release was found')
+ })
+ })
})
describe('for valid apps with a pipeline', function () {
@@ -183,9 +198,12 @@ describe('pipelines:diff', function () {
// Mock latest release/slug endpoints for two apps:
nock(api)
.get(`/apps/${targetApp.id}/releases`)
- .reply(200, [{ slug: { id: targetSlugId } }])
+ .reply(200, [{ slug: { id: targetSlugId }, status: 'succeeded' }])
.get(`/apps/${downstreamApp1.id}/releases`)
- .reply(200, [{ slug: { id: downstreamSlugId } }])
+ .reply(200, [
+ { status: 'failed' },
+ { slug: { id: downstreamSlugId }, status: 'succeeded' }
+ ])
})
it('should not compare apps if update to date NOR if repo differs', function () {
|
fix(pipelines-v5): Only consider succeeded releases in pipelines:diff
|
heroku_cli
|
train
|
75d7a6177a9e4c78af862c38637ea54fde16cf38
|
diff --git a/tests/Stub/FatalErrorTestStub.php b/tests/Stub/FatalErrorTestStub.php
index <HASH>..<HASH> 100644
--- a/tests/Stub/FatalErrorTestStub.php
+++ b/tests/Stub/FatalErrorTestStub.php
@@ -6,14 +6,13 @@ namespace Tests\Stub;
class FatalErrorTestStub extends BrokenTestBase implements BrokenTestInterface
{
- public function testBrokenTest()
+ public function testBrokenTest(): void
{
- ini_set('memory_limit', '2M');
+ $foo = new class() implements \Serializable {
+ };
- $arr = [];
+ $message = 'This assertion should not happen: ' . json_encode($foo);
- while (true) {
- $arr[] = 'Allocated memory... allocated memory everywhere!';
- }
+ self::assertTrue(true, $message);
}
}
|
Improve stub to avoid memory leak
|
facile-it_paraunit
|
train
|
e76c45f841547879e3fca0c255563fee05f451ac
|
diff --git a/packages/d3fc-extent/src/date.js b/packages/d3fc-extent/src/date.js
index <HASH>..<HASH> 100644
--- a/packages/d3fc-extent/src/date.js
+++ b/packages/d3fc-extent/src/date.js
@@ -10,10 +10,12 @@ export default function() {
const extent = linearExtent();
+ const valueOf = date => date != null ? date.valueOf() : null;
+
const instance = (data) => {
const adaptedAccessors = accessors.map(accessor => (...args) => {
const value = accessor(...args);
- return Array.isArray(value) ? value.map(date => date.valueOf()) : value.valueOf();
+ return Array.isArray(value) ? value.map(valueOf) : valueOf(value);
});
extent.accessors(adaptedAccessors)
diff --git a/packages/d3fc-extent/test/dateSpec.js b/packages/d3fc-extent/test/dateSpec.js
index <HASH>..<HASH> 100644
--- a/packages/d3fc-extent/test/dateSpec.js
+++ b/packages/d3fc-extent/test/dateSpec.js
@@ -73,4 +73,12 @@ describe('linear', () => {
dateExtent().accessors([d => [d, d]])([date]);
expect(date.valueOf).toHaveBeenCalled();
});
+
+ it('should handle null dates', function() {
+ const date1 = new Date(2014, 0, 10);
+ const date2 = null;
+ const date3 = new Date(2014, 0, 20);
+ var extent = dateExtent().accessors([d => d])([date1, date2, date3]);
+ expect(extent).toEqual([date1, date3]);
+ });
});
|
fix: handle null dates (#<I>)
* fix: handle null dates
* fix: handle null dates
|
d3fc_d3fc
|
train
|
0c87467f6989840b66419efb795be118fa50938e
|
diff --git a/e2e/ctl_v3_auth_test.go b/e2e/ctl_v3_auth_test.go
index <HASH>..<HASH> 100644
--- a/e2e/ctl_v3_auth_test.go
+++ b/e2e/ctl_v3_auth_test.go
@@ -33,8 +33,9 @@ func TestCtlV3AuthMemberAdd(t *testing.T) { testCtl(t, authTestMemberA
func TestCtlV3AuthMemberRemove(t *testing.T) {
testCtl(t, authTestMemberRemove, withQuorum(), withNoStrictReconfig())
}
-func TestCtlV3AuthMemberUpdate(t *testing.T) { testCtl(t, authTestMemberUpdate) }
-func TestCtlV3AuthCertCN(t *testing.T) { testCtl(t, authTestCertCN, withCfg(configClientTLSCertAuth)) }
+func TestCtlV3AuthMemberUpdate(t *testing.T) { testCtl(t, authTestMemberUpdate) }
+func TestCtlV3AuthCertCN(t *testing.T) { testCtl(t, authTestCertCN, withCfg(configClientTLSCertAuth)) }
+func TestCtlV3AuthRevokeWithDelete(t *testing.T) { testCtl(t, authTestRevokeWithDelete) }
func authEnableTest(cx ctlCtx) {
if err := authEnable(cx); err != nil {
@@ -562,3 +563,38 @@ func authTestCertCN(cx ctlCtx) {
cx.t.Fatal(err)
}
}
+
+func authTestRevokeWithDelete(cx ctlCtx) {
+ if err := authEnable(cx); err != nil {
+ cx.t.Fatal(err)
+ }
+
+ cx.user, cx.pass = "root", "root"
+ authSetupTestUser(cx)
+
+ // create a new role
+ cx.user, cx.pass = "root", "root"
+ if err := ctlV3Role(cx, []string{"add", "test-role2"}, "Role test-role2 created"); err != nil {
+ cx.t.Fatal(err)
+ }
+
+ // grant the new role to the user
+ if err := ctlV3User(cx, []string{"grant-role", "test-user", "test-role2"}, "Role test-role2 is granted to user test-user", nil); err != nil {
+ cx.t.Fatal(err)
+ }
+
+ // check the result
+ if err := ctlV3User(cx, []string{"get", "test-user"}, "Roles: test-role test-role2", nil); err != nil {
+ cx.t.Fatal(err)
+ }
+
+ // delete the role, test-role2 must be revoked from test-user
+ if err := ctlV3Role(cx, []string{"delete", "test-role2"}, "Role test-role2 deleted"); err != nil {
+ cx.t.Fatal(err)
+ }
+
+ // check the result
+ if err := ctlV3User(cx, []string{"get", "test-user"}, "Roles: test-role", nil); err != nil {
+ cx.t.Fatal(err)
+ }
+}
|
e2e: add a test case role delete and revoke
|
etcd-io_etcd
|
train
|
dc4c52785a656f4b47c7d94e3d6df1a743979998
|
diff --git a/samples/struct.js b/samples/struct.js
index <HASH>..<HASH> 100644
--- a/samples/struct.js
+++ b/samples/struct.js
@@ -73,6 +73,9 @@ function writeDataForStructQueries(instanceId, databaseId, projectId) {
function queryDataWithStruct(instanceId, databaseId, projectId) {
// [START spanner_create_struct_with_data]
+ // Imports the Google Cloud client library
+ const {Spanner} = require('@google-cloud/spanner');
+
const nameStruct = Spanner.struct({
FirstName: 'Elena',
LastName: 'Campbell',
@@ -80,9 +83,6 @@ function queryDataWithStruct(instanceId, databaseId, projectId) {
// [END spanner_create_struct_with_data]
// [START spanner_query_data_with_struct]
- // Imports the Google Cloud client library
- const {Spanner} = require('@google-cloud/spanner');
-
/**
* TODO(developer): Uncomment the following lines before running the sample.
*/
@@ -190,8 +190,8 @@ function queryWithArrayofStruct(instanceId, databaseId, projectId) {
// [START spanner_query_data_with_array_of_struct]
const query = {
sql:
- 'SELECT SingerId FROM Singers' +
- 'WHERE STRUCT<FirstName STRING, LastName STRING>(FirstName, LastName)' +
+ 'SELECT SingerId FROM Singers ' +
+ 'WHERE STRUCT<FirstName STRING, LastName STRING>(FirstName, LastName) ' +
'IN UNNEST(@names)',
params: {
names: bandMembers,
@@ -336,8 +336,8 @@ function queryNestedStructField(instanceId, databaseId, projectId) {
const query = {
sql:
- 'SELECT SingerId, @songInfo.SongName FROM Singers' +
- 'WHERE STRUCT<FirstName STRING, LastName STRING>(FirstName, LastName)' +
+ 'SELECT SingerId, @songInfo.SongName FROM Singers ' +
+ 'WHERE STRUCT<FirstName STRING, LastName STRING>(FirstName, LastName) ' +
'IN UNNEST(@songInfo.ArtistNames)',
params: {
songInfo: songInfoStruct,
diff --git a/samples/system-test/spanner.test.js b/samples/system-test/spanner.test.js
index <HASH>..<HASH> 100644
--- a/samples/system-test/spanner.test.js
+++ b/samples/system-test/spanner.test.js
@@ -489,7 +489,7 @@ test.serial(
`should query an example table with an array of STRUCT param`,
async t => {
const results = await tools.runAsyncWithIO(
- `${structCmd} queryWithArrayofStruct ${INSTANCE_ID} ${DATABASE_ID} ${PROJECT_ID}`,
+ `${structCmd} queryWithArrayOfStruct ${INSTANCE_ID} ${DATABASE_ID} ${PROJECT_ID}`,
cwd
);
const output = results.stdout + results.stderr;
|
Fix sample tests (#<I>)
* fix struct tests
|
googleapis_nodejs-spanner
|
train
|
fc36c41ba7333ae95622d2eefa0560e9c67e9c46
|
diff --git a/openbas/client/actuate.js b/openbas/client/actuate.js
index <HASH>..<HASH> 100644
--- a/openbas/client/actuate.js
+++ b/openbas/client/actuate.js
@@ -91,7 +91,7 @@ if (Meteor.isClient) {
};
Template.actuator_display.ploturl = function() {
- return Meteor.absoluteUrl('plot?'+getPermalink(this.ActuatorUUID));
+ return '/plot?'+getPermalink(this.ActuatorUUID);
};
Template.point_display.point = function(uuid) {
@@ -120,7 +120,7 @@ if (Meteor.isClient) {
};
Template.point_display.ploturl = function() {
- return Meteor.absoluteUrl('plot?'+getPermalink(this.uuid));
+ return '/plot?'+getPermalink(this.uuid);
};
Template.point_display.name = function() {
|
Use relative urls for plotting
|
SoftwareDefinedBuildings_XBOS
|
train
|
25453d88bf9224f4e79698acb6cc1be9efdc0922
|
diff --git a/pkg/backend/display/json.go b/pkg/backend/display/json.go
index <HASH>..<HASH> 100644
--- a/pkg/backend/display/json.go
+++ b/pkg/backend/display/json.go
@@ -45,7 +45,7 @@ func massagePropertyValue(v resource.PropertyValue, showSecrets bool) resource.P
for k, e := range v.ObjectValue() {
new[k] = massagePropertyValue(e, showSecrets)
}
- return resource.NewObjectProperty(MassageSecrets(v.ObjectValue(), showSecrets))
+ return resource.NewObjectProperty(new)
case v.IsSecret() && showSecrets:
return massagePropertyValue(v.SecretValue().Element, showSecrets)
case v.IsSecret():
|
Fix a bug in out logic for replacing secrets with `[secret]`
|
pulumi_pulumi
|
train
|
912c1c55ec640f4e6fca6334db38557781ec6588
|
diff --git a/lib/Palette.js b/lib/Palette.js
index <HASH>..<HASH> 100644
--- a/lib/Palette.js
+++ b/lib/Palette.js
@@ -9,12 +9,23 @@ var merge = function (base, mixin) {
return base;
};
-/**
- * A JASC Paint Shop Pro Palette file.
- *
- * @param {string|Buffer} buf Palette file source.
- * @constructor
- */
+// A JASC Paint Shop Pro Palette file.
+//
+// Usage:
+// Palette(buf) where `buf` is a palette file source string or Buffer
+// let pal = Palette(fs.readFileSync('palette.pal')) → a palette array parsed from source
+// let pal = Palette([ [ r0, g0, b0 ], [ r1, g1, b1 ] ]) → a new palette array
+// pal[0], pal.getColor(0) → the colour at the given index
+// pal[0] = [ r, g, b ], pal.setColor(0, [ r, g, b ]) → set colour at an index
+// pal.toString() → new palette file source string
+//
+// Palette file format:
+// ```
+// "JASC-PAL"
+// 4 character version
+// amount of lines
+// palette lines: three space-separated numbers (0-255), "<red> <green> <blue>"
+// ```
function Palette(buf) {
var _this = this;
if (!(this instanceof Palette)) return new Palette(buf);
@@ -22,11 +33,13 @@ function Palette(buf) {
if (!buf) buf = [];
var data = undefined;
+ // creating a new palette
if (Array.isArray(buf)) {
data = { colors: buf, numColors: buf.length, version: "0100" };
- } else {
+ }
+ // reading a palette
+ else {
var str = Buffer.isBuffer(buf) ? buf.toString("ascii") : buf;
- // parse
data = parse(str);
}
@@ -41,24 +54,17 @@ function Palette(buf) {
return data.colors;
}
-/**
- * Parses a palette file.
- * Format:
- * ```
- * "JASC-PAL"
- * 4 character version
- * amount of lines
- * palette lines: three space-separated numbers (0-255), "<red> <green> <blue>"
- * ```
- */
function parse(buf) {
var colors = [],
- lines = buf.split("\n");
+ lines = buf.split(/\r?\n/);
// lines[0] == "JASC-PAL\n"
var version = lines[1]; // probably always 0100
var numColors = parseInt(lines[2], 10);
+ // TODO use lines.length instead of numColors, to be more forgiving?
+ // maybe have a "loose" mode that will just do whatever is in the file
+ // and a default stricter mode that also checks whether the file is valid
for (var i = 3,
l = numColors + 3; i < l; i++) {
(function () {
@@ -71,30 +77,15 @@ function parse(buf) {
return { version: version, numColors: numColors, colors: colors };
}
-/**
- * Returns the colour at a given index in the palette.
- * @param {number} idx Colour index in the palette.
- * @return {Array.<number>|undefined} [r, g, b] colour array, or undefined if the index doesn't exist.
- */
Palette.prototype.getColor = function (idx) {
return this.colors[idx];
};
-/**
- * Sets the colour at a given index in the palette.
- * @param {number} idx Colour index in the palette.
- * @param {Array.<number>} color [r, g, b] colour array.
- * @return {Palette} This.
- */
Palette.prototype.setColor = function (idx, color) {
this.colors[idx] = color;
return this;
};
-/**
- * Returns up-to-date Palette file source.
- * @return {string} Palette file source.
- */
Palette.prototype.toString = function () {
return "JASC-PAL\n" + this.version + "\n" + this.colors.length + "\n" + this.colors.map(function (color) {
return color.join(" ");
diff --git a/package.json b/package.json
index <HASH>..<HASH> 100644
--- a/package.json
+++ b/package.json
@@ -1,6 +1,6 @@
{ "name": "jascpal"
, "description": "Paint Shop Pro Palette file reader/writer"
-, "version": "0.1.0"
+, "version": "0.1.1"
, "license": "MIT"
, "bugs": "https://github.com/goto-bus-stop/jascpal"
, "author": "goto-bus-stop <rene@kooi.me>"
diff --git a/src/Palette.js b/src/Palette.js
index <HASH>..<HASH> 100644
--- a/src/Palette.js
+++ b/src/Palette.js
@@ -49,7 +49,7 @@ export default function Palette(buf) {
function parse(buf) {
let colors = []
- , lines = buf.split('\n')
+ , lines = buf.split(/\r?\n/)
// lines[0] == "JASC-PAL\n"
let version = lines[1] // probably always 0100
diff --git a/test/Palette.js b/test/Palette.js
index <HASH>..<HASH> 100644
--- a/test/Palette.js
+++ b/test/Palette.js
@@ -42,6 +42,13 @@ describe('Palette:', function () {
assert.strictEqual(pal.toString(), read('expected-simple.pal').toString('ascii'))
})
+
+ it('supports carriage returns', function () {
+ var empty = Palette('JASC-PAL\r\n0100\r\n0\r\n')
+
+ assert.notEqual(empty.version, '0100\r')
+ assert.strictEqual(empty.version, '0100')
+ })
})
describe('creates new palettes', function () {
|
support \r\n line ends too (it's actually the more prevalent kind\!)
|
genie-js_jascpal
|
train
|
867e19d9d7e5b939dec3e87ed091ca0be457ea79
|
diff --git a/lib/ezutils/classes/ezdebug.php b/lib/ezutils/classes/ezdebug.php
index <HASH>..<HASH> 100644
--- a/lib/ezutils/classes/ezdebug.php
+++ b/lib/ezutils/classes/ezdebug.php
@@ -1937,14 +1937,14 @@ class eZDebug
{
if ( $matches[6] )
{
- if ( self::isIPInNet( $itemToMatch, $matches[1], $matches[7] ) )
+ if ( self::isIPInNet( $ipAddress, $matches[1], $matches[7] ) )
{
return true;
}
}
else
{
- if ( $matches[1] == $itemToMatch )
+ if ( $matches[1] == $ipAddress )
{
return true;
}
|
Fixed #EZP-<I>: ezpublish_legacy - DebugByIP IPV4 not working correctly
backport of ipv4 matching from ez <I>
so ip and network matching for DebugByIp settings is working now
|
ezsystems_ezpublish-legacy
|
train
|
bee169ade78c640b5dc45846340465adb8f07709
|
diff --git a/werkzeug/serving.py b/werkzeug/serving.py
index <HASH>..<HASH> 100644
--- a/werkzeug/serving.py
+++ b/werkzeug/serving.py
@@ -516,7 +516,7 @@ def run_simple(hostname, port, application, use_reloader=False,
passthrough_errors, ssl_context).serve_forever()
if os.environ.get('WERKZEUG_RUN_MAIN') != 'true':
- display_hostname = hostname or '127.0.0.1'
+ display_hostname = hostname != '*' and hostname or 'localhost'
if ':' in display_hostname:
display_hostname = '[%s]' % display_hostname
_log('info', ' * Running on %s://%s:%d/', ssl_context is None
|
Binding to '*' should now print localhost in the URL.
|
pallets_werkzeug
|
train
|
edde89adc106f52a83c3679ede1dcfa8cf558166
|
diff --git a/tests/test_progress_parameter.py b/tests/test_progress_parameter.py
index <HASH>..<HASH> 100644
--- a/tests/test_progress_parameter.py
+++ b/tests/test_progress_parameter.py
@@ -58,18 +58,15 @@ def test_log_file_verbosity_2():
tpot_obj.fit(X, y)
assert_equal(os.path.getsize(file_name) > 0, True)
-# def test_log_file_verbose_3():
-# """
-# Set verbosity as 1. Assert log_file parameter to generate log file.
-# This test will raises an exception about xgboost.
-# """
-# file_name = "progress_verbosity_3.log"
-# tracking_progress_file = open(file_name, "w")
-# tpot_obj = TPOTClassifier(
-# population_size=10,
-# generations=10,
-# verbosity=3,
-# log_file=tracking_progress_file
-# )
-# tpot_obj.fit(X, y)
-# assert_equal(os.path.getsize(file_name) > 0, True)
+def test_log_file_verbose_3():
+ """ Set verbosity as 3. Assert log_file parameter to generate log file. """
+ file_name = "progress_verbosity_3.log"
+ tracking_progress_file = open(file_name, "w")
+ tpot_obj = TPOTClassifier(
+ population_size=10,
+ generations=10,
+ verbosity=3,
+ log_file=tracking_progress_file
+ )
+ tpot_obj.fit(X, y)
+ assert_equal(os.path.getsize(file_name) > 0, True)
|
Make log_file test3 back.
|
EpistasisLab_tpot
|
train
|
2ae8ccee4ab4729c2f2c144d8438114703cda568
|
diff --git a/nodes/entity/entity.js b/nodes/entity/entity.js
index <HASH>..<HASH> 100644
--- a/nodes/entity/entity.js
+++ b/nodes/entity/entity.js
@@ -191,8 +191,7 @@ module.exports = function(RED) {
)) {
attributes.push({
property: prop,
- value: val,
- valueType: 'str'
+ value: val
});
}
} else {
|
refactor(sensor): Change attributes passed in message object to keep their type
|
zachowj_node-red-contrib-home-assistant-websocket
|
train
|
50c0bc98bef96e309fb70b8374d71847213a2d72
|
diff --git a/openquake/engine/calculators/hazard/general.py b/openquake/engine/calculators/hazard/general.py
index <HASH>..<HASH> 100644
--- a/openquake/engine/calculators/hazard/general.py
+++ b/openquake/engine/calculators/hazard/general.py
@@ -341,10 +341,12 @@ class BaseHazardCalculator(base.Calculator):
rlzs_assoc = cm.get_rlzs_assoc()
gsims_by_trt_id = rlzs_assoc.get_gsims_by_trt_id()
- for lt_model, rlzs in zip(
- self._source_models, rlzs_assoc.rlzs_by_smodel):
+ smodels = [sm for sm in self._source_models
+ if sm.trtmodel_set.filter(num_ruptures__gt=0)]
+ for lt_model, rlzs in zip(smodels, rlzs_assoc.rlzs_by_smodel):
trt_models = lt_model.trtmodel_set.filter(num_ruptures__gt=0)
for rlz in rlzs:
+ gsim_by_trt = rlzs_assoc.gsim_by_trt[rlz]
lt_rlz = models.LtRealization.objects.create(
lt_model=lt_model, gsim_lt_path=rlz.gsim_lt_path,
weight=rlz.weight, ordinal=rlz.ordinal)
@@ -354,7 +356,7 @@ class BaseHazardCalculator(base.Calculator):
# populate the association table rlz <-> trt_model
models.AssocLtRlzTrtModel.objects.create(
rlz=lt_rlz, trt_model=trt_model,
- gsim=rlzs_assoc.gsim_by_trt[rlz.ordinal][trt])
+ gsim=gsim_by_trt[trt])
trt_model.gsims = [
gsim.__class__.__name__
for gsim in gsims_by_trt_id[trt_model.id]]
|
Fixed the case when a source model does not produce ruptures (event based case_5)
Former-commit-id: f<I>cb<I>d8f6d6f<I>bf<I>c<I>a<I>
|
gem_oq-engine
|
train
|
735e03f550d16daa86849b07dfa56649303f40e4
|
diff --git a/HISTORY.rst b/HISTORY.rst
index <HASH>..<HASH> 100644
--- a/HISTORY.rst
+++ b/HISTORY.rst
@@ -4,6 +4,7 @@ Changelog
0.5.2 (unreleased)
------------------
- Fix bug with computing start and end indices of sentences.
+- Fix bug with import TextBlob if local NLTK is installed.
0.5.1 (2013-08-13)
diff --git a/text/blob.py b/text/blob.py
index <HASH>..<HASH> 100644
--- a/text/blob.py
+++ b/text/blob.py
@@ -11,7 +11,8 @@ from .decorators import cached_property
from .utils import lowerstrip, PUNCTUATION_REGEX
from .inflect import singularize as _singularize, pluralize as _pluralize
from .mixins import ComparableMixin
-from .compat import string_types, unicode, basestring, u
+from .compat import (string_types, unicode, basestring,
+ python_2_unicode_compatible, u)
from .np_extractors import BaseNPExtractor, FastNPExtractor
from .taggers import BaseTagger, PatternTagger
from .tokenizers import BaseTokenizer, WordTokenizer, SentenceTokenizer
@@ -146,7 +147,8 @@ class WordList(list):
'''Return the plural version of each word in this WordList.'''
return [word.pluralize() for word in self]
-@nltk.compat.python_2_unicode_compatible
+
+@python_2_unicode_compatible
class BaseBlob(ComparableMixin):
'''An abstract base class that all text.blob classes will inherit from.
diff --git a/text/compat.py b/text/compat.py
index <HASH>..<HASH> 100644
--- a/text/compat.py
+++ b/text/compat.py
@@ -30,3 +30,122 @@ else:
unicode = str
basestring = (str, bytes)
imap = map
+
+# ======= Compatibility layer for __str__ and __repr__ ==========
+
+import unicodedata
+import functools
+
+def remove_accents(text):
+
+ if isinstance(text, bytes):
+ text = text.decode('ascii')
+
+ category = unicodedata.category # this gives a small (~10%) speedup
+ return ''.join(
+ c for c in unicodedata.normalize('NFKD', text) if category(c) != 'Mn'
+ )
+
+# Select the best transliteration method:
+try:
+ # Older versions of Unidecode are licensed under Artistic License;
+ # assume an older version is installed.
+ from unidecode import unidecode as transliterate
+except ImportError:
+ try:
+ # text-unidecode implementation is worse than Unidecode
+ # implementation so Unidecode is preferred.
+ from text_unidecode import unidecode as transliterate
+ except ImportError:
+ # This transliteration method should be enough
+ # for many Western languages.
+ transliterate = remove_accents
+
+
+def python_2_unicode_compatible(klass):
+ """
+ This decorator defines __unicode__ method and fixes
+ __repr__ and __str__ methods under Python 2.
+
+ To support Python 2 and 3 with a single code base,
+ define __str__ and __repr__ methods returning unicode
+ text and apply this decorator to the class.
+
+ Original __repr__ and __str__ would be available
+ as unicode_repr and __unicode__ (under both Python 2
+ and Python 3).
+ """
+
+ if not issubclass(klass, object):
+ raise ValueError("This decorator doesn't work for old-style classes")
+
+ # both __unicode__ and unicode_repr are public because they
+ # may be useful in console under Python 2.x
+
+ # if __str__ or __repr__ are not overriden in a subclass,
+ # they may be already fixed by this decorator in a parent class
+ # and we shouldn't them again
+
+ if not _was_fixed(klass.__str__):
+ klass.__unicode__ = klass.__str__
+ if PY2:
+ klass.__str__ = _7bit(_transliterated(klass.__unicode__))
+
+
+ if not _was_fixed(klass.__repr__):
+ klass.unicode_repr = klass.__repr__
+ if PY2:
+ klass.__repr__ = _7bit(klass.unicode_repr)
+
+ return klass
+
+
+def unicode_repr(obj):
+ """
+ For classes that was fixed with @python_2_unicode_compatible
+ ``unicode_repr`` returns ``obj.unicode_repr()``; for unicode strings
+ the result is returned without "u" letter (to make output the
+ same under Python 2.x and Python 3.x); for other variables
+ it is the same as ``repr``.
+ """
+ if not PY2:
+ return repr(obj)
+
+ # Python 2.x
+ if hasattr(obj, 'unicode_repr'):
+ return obj.unicode_repr()
+
+ if isinstance(obj, unicode):
+ return repr(obj)[1:] # strip "u" letter from output
+
+ return repr(obj)
+
+
+def _transliterated(method):
+ def wrapper(self):
+ return transliterate(method(self))
+
+ functools.update_wrapper(wrapper, method, ["__name__", "__doc__"])
+ if hasattr(method, "_nltk_compat_7bit"):
+ wrapper._nltk_compat_7bit = method._nltk_compat_7bit
+
+ wrapper._nltk_compat_transliterated = True
+ return wrapper
+
+
+def _7bit(method):
+ def wrapper(self):
+ return method(self).encode('ascii', 'backslashreplace')
+
+ functools.update_wrapper(wrapper, method, ["__name__", "__doc__"])
+
+ if hasattr(method, "_nltk_compat_transliterated"):
+ wrapper._nltk_compat_transliterated = method._nltk_compat_transliterated
+
+ wrapper._nltk_compat_7bit = True
+ return wrapper
+
+
+def _was_fixed(method):
+ return (getattr(method, "_nltk_compat_7bit", False) or
+ getattr(method, "_nltk_compat_transliterated", False))
\ No newline at end of file
|
Fix bug with importing textblob with local nltk installed
By adding python_2_unicode_compatible decorator to text/compat.py
|
sloria_TextBlob
|
train
|
3f7b248a8f5b664aa78d5a671ce4c58920680025
|
diff --git a/intranet/apps/announcements/forms.py b/intranet/apps/announcements/forms.py
index <HASH>..<HASH> 100644
--- a/intranet/apps/announcements/forms.py
+++ b/intranet/apps/announcements/forms.py
@@ -59,7 +59,7 @@ class AnnouncementRequestForm(forms.ModelForm):
"to a specific group of students, such as the Class of 2016, enter that request here."
)
self.fields["teachers_requested"] = SortedTeacherMultipleChoiceField(
- queryset=get_user_model().objects.get_teachers_attendance_users_sorted(), show_username=True
+ queryset=get_user_model().objects.get_approve_announcements_users_sorted(), show_username=True
)
self.fields["teachers_requested"].label = "Sponsor"
self.fields["teachers_requested"].help_text = (
diff --git a/intranet/apps/announcements/tests.py b/intranet/apps/announcements/tests.py
index <HASH>..<HASH> 100644
--- a/intranet/apps/announcements/tests.py
+++ b/intranet/apps/announcements/tests.py
@@ -44,3 +44,9 @@ class AnnouncementTest(IonTestCase):
self.assertEqual(response.status_code, 200)
response = self.client.post(reverse("show_announcement"))
self.assertEqual(response.status_code, 404)
+
+ def test_announcement_approval(self):
+ teacher = get_user_model().objects.get_or_create(username="teacher", user_type="teacher", first_name="timmy", last_name="teacher")[0]
+ counselor = get_user_model().objects.get_or_create(username="counselor", user_type="counselor", first_name="c", last_name="c")[0]
+ user = get_user_model().objects.get_or_create(username="user", user_type="user", first_name="ursula", last_name="user")[0]
+ self.assertEqual(list(get_user_model().objects.get_approve_announcements_users_sorted()), [counselor, teacher, user])
diff --git a/intranet/apps/users/models.py b/intranet/apps/users/models.py
index <HASH>..<HASH> 100644
--- a/intranet/apps/users/models.py
+++ b/intranet/apps/users/models.py
@@ -134,14 +134,41 @@ class UserManager(DjangoUserManager):
"""Returns a ``QuerySet`` containing both teachers and attendance-only users sorted by
last name, then first name.
- This is used for the announcement request page.
-
Returns:
A ``QuerySet`` of teachers sorted by last name, then first name.
"""
return self.get_teachers_attendance_users().order_by("last_name", "first_name")
+ def get_approve_announcements_users(self) -> "QuerySet[User]": # noqa
+ """Returns a ``QuerySet`` containing all users except simple users, tjstar presenters,
+ alumni, service users and students.
+
+ Returns:
+ A ``QuerySet`` of all users except simple users, tjstar presenters, alumni,
+ service users and students.
+
+ """
+
+ users = User.objects.filter(user_type__in=["user", "teacher", "counselor"])
+ users = users.exclude(id__in=EXTRA)
+ users = users.exclude(Q(first_name=None) | Q(first_name="") | Q(last_name=None) | Q(last_name=""))
+
+ return users
+
+ def get_approve_announcements_users_sorted(self) -> "QuerySet[User]": # noqa
+ """Returns a ``QuerySet`` containing all users except simple users, tjstar presenters,
+ alumni, service users and students sorted by last name, then first name.
+
+ This is used for the announcement request page.
+
+ Returns:
+ A ``QuerySet`` of all users except simple users, tjstar presenters, alumni,
+ service users and students sorted by last name, then first name.
+
+ """
+ return self.get_approve_announcements_users().order_by("last_name", "first_name")
+
def exclude_from_search(
self, existing_queryset: Optional[Union[Collection["User"], QuerySet]] = None # pylint: disable=unsubscriptable-object
) -> Union[Collection["User"], QuerySet]: # pylint: disable=unsubscriptable-object
|
fix(announcements): expand groups allowed to approve announcements
|
tjcsl_ion
|
train
|
344cb03551ab155ab3799e9279374ccfd2d6c605
|
diff --git a/Swat/SwatTableViewCheckAllRow.php b/Swat/SwatTableViewCheckAllRow.php
index <HASH>..<HASH> 100644
--- a/Swat/SwatTableViewCheckAllRow.php
+++ b/Swat/SwatTableViewCheckAllRow.php
@@ -78,7 +78,6 @@ class SwatTableViewCheckAllRow extends SwatTableViewRow
{
$columns = $this->view->getColumns();
- $this->id = 'foo';
if ($this->view->model->getRowCount() < 2)
return;
|
foo?
svn commit r<I>
|
silverorange_swat
|
train
|
edddc50af77298b0d9ed61d37263924d48af036c
|
diff --git a/scripts/start.js b/scripts/start.js
index <HASH>..<HASH> 100644
--- a/scripts/start.js
+++ b/scripts/start.js
@@ -208,7 +208,7 @@ function addMiddleware(devServer) {
// So if `proxy` is specified, we need to decide which fallback to use.
// We use a heuristic: if request `accept`s text/html, we pick /index.html.
// Modern browsers include text/html into `accept` header when navigating.
- // However API calls like `fetch()` won’t generally won’t accept text/html.
+ // However API calls like `fetch()` won’t generally accept text/html.
// If this heuristic doesn’t work well for you, don’t use `proxy`.
htmlAcceptHeaders: proxy ?
['text/html'] :
|
Fixed typo in code comment (#<I>)
|
vcarl_create-react-app
|
train
|
6a49d9dcd03f5378ba09819389a87bef067b1142
|
diff --git a/cassandra/encoder.py b/cassandra/encoder.py
index <HASH>..<HASH> 100644
--- a/cassandra/encoder.py
+++ b/cassandra/encoder.py
@@ -67,7 +67,7 @@ class Encoder(object):
def __init__(self):
self.mapping = {
- float: self.cql_encode_object,
+ float: self.cql_encode_float,
bytearray: self.cql_encode_bytes,
str: self.cql_encode_str,
int: self.cql_encode_object,
@@ -138,6 +138,12 @@ class Encoder(object):
"""
return str(val)
+ def cql_encode_float(self, val):
+ """
+ Encode floats using repr to preserve precision
+ """
+ return repr(val)
+
def cql_encode_datetime(self, val):
"""
Converts a :class:`datetime.datetime` object to a (string) integer timestamp
|
CQL encode floats with repr to preserve precision.
|
datastax_python-driver
|
train
|
fbeeaec475beca4fe389da6d8f2464cdcb11f9f1
|
diff --git a/classes/util/Loop.php b/classes/util/Loop.php
index <HASH>..<HASH> 100644
--- a/classes/util/Loop.php
+++ b/classes/util/Loop.php
@@ -84,7 +84,7 @@ class Loop
/*
* Calculate max time remaining, don't sleep any longer than that.
*/
- $usecRemaining = intval(($timeout - microtime(true)) * 1e6);
+ $usecRemaining = \intval(($timeout - \microtime(true)) * 1e6);
if ($usecRemaining <= 0) {
/*
diff --git a/tests/mutex/MutexTest.php b/tests/mutex/MutexTest.php
index <HASH>..<HASH> 100644
--- a/tests/mutex/MutexTest.php
+++ b/tests/mutex/MutexTest.php
@@ -159,7 +159,6 @@ class MutexTest extends \PHPUnit_Framework_TestCase
* @param callable $mutexFactory The Mutex factory.
* @test
* @dataProvider provideMutexFactories
- * @requires PHP 7.0
*/
public function testLiveness(callable $mutexFactory)
{
@@ -190,7 +189,6 @@ class MutexTest extends \PHPUnit_Framework_TestCase
* @test
* @dataProvider provideMutexFactories
* @expectedException \DomainException
- * @requires PHP 5.6
*/
public function testSynchronizedPassesExceptionThrough(callable $mutexFactory)
{
|
Remove some PHP version constraints that no longer apply
|
php-lock_lock
|
train
|
038218f3948cd3d1a78e2a9fdfac78bb78de6ca5
|
diff --git a/src/BaseTool.php b/src/BaseTool.php
index <HASH>..<HASH> 100644
--- a/src/BaseTool.php
+++ b/src/BaseTool.php
@@ -23,7 +23,7 @@ class BaseTool {
/* Accessing these outside the class is discouraged, use or create get/setters instead */
var $displayTitle = '';
var $remoteBasePath = '';
- var $revisionId = '0.0.0';
+ var $revisionId = '';
var $styles = array();
var $scripts = array();
var $scriptsHead = array();
@@ -371,7 +371,7 @@ HTML;
$sourceInfo = $this->getSourceInfo();
- $version = $this->revisionId;
+ $version = $this->revisionId ? "v{$this->revisionId}" : '';
if ( $sourceInfo['repoCommitID'] ) {
$sourceVersion = $sourceInfo['repoCommitID'];
if ( $sourceInfo['repoCommitUrl'] ) {
@@ -388,7 +388,7 @@ HTML;
}
$version .= " ($sourceVersion)";
}
- $items[] = "Currently v$version";
+ $items[] = "Currently $version";
if ( $sourceInfo['repoViewUrl'] ) {
$items[] = Html::element( 'a', array(
|
BaseTool: Make 'revisionId' optional
Previously it defaulted to "v" due to string concatenation later
on assuming it to be non-empty.
|
Krinkle_toollabs-base
|
train
|
9fd281468b103ce2499a5fece1fd757d6baa36e2
|
diff --git a/go/libkb/version.go b/go/libkb/version.go
index <HASH>..<HASH> 100644
--- a/go/libkb/version.go
+++ b/go/libkb/version.go
@@ -12,7 +12,7 @@ import (
const Version = "1.0.0"
// Build number
-const Build = "38"
+const Build = "39"
// VersionString returns semantic version string.
func VersionString() string {
|
Bump build number to <I>
|
keybase_client
|
train
|
1ff7c69fe43d596577cd0f404c754b6400775022
|
diff --git a/etc/adapters/etcd.py b/etc/adapters/etcd.py
index <HASH>..<HASH> 100644
--- a/etc/adapters/etcd.py
+++ b/etc/adapters/etcd.py
@@ -10,6 +10,7 @@ import io
import socket
import sys
+import iso8601
import requests
from requests.packages.urllib3.exceptions import ReadTimeoutError
import six
@@ -75,7 +76,8 @@ class EtcdAdapter(Adapter):
'created_index': int(data['createdIndex'])}
ttl = data.get('ttl')
if ttl is not None:
- kwargs.update(ttl=ttl, expiration=data['expiration'])
+ expiration = iso8601.parse_date(data['expiration'])
+ kwargs.update(ttl=ttl, expiration=expiration)
if 'value' in data:
node_cls = Value
args = (data['value'],)
diff --git a/setup.py b/setup.py
index <HASH>..<HASH> 100644
--- a/setup.py
+++ b/setup.py
@@ -50,7 +50,7 @@ setup(
'Programming Language :: Python :: Implementation :: CPython',
'Programming Language :: Python :: Implementation :: PyPy',
'Topic :: Software Development'],
- install_requires=['requests'],
+ install_requires=['iso8601', 'requests'],
tests_require=['pytest'],
test_suite='...',
)
diff --git a/test.py b/test.py
index <HASH>..<HASH> 100644
--- a/test.py
+++ b/test.py
@@ -1,4 +1,5 @@
# -*- coding: utf-8 -*-
+from datetime import datetime
import os
import threading
import time
@@ -216,3 +217,8 @@ def test_compare(etcd):
etcd.delete('/etc', prev_value=u'8')
with pytest.raises(etc.KeyNotFound):
etcd.delete('/etc')
+
+
+def test_expiration(etcd):
+ r = etcd.set('/etc', u'etc', ttl=10)
+ assert isinstance(r.expiration, datetime)
|
Parse expiration as ISO-<I>
|
sublee_etc
|
train
|
45bd72fb672070d055d476ec66fa6f5e7f5ee2d1
|
diff --git a/pyphi/conf.py b/pyphi/conf.py
index <HASH>..<HASH> 100644
--- a/pyphi/conf.py
+++ b/pyphi/conf.py
@@ -455,6 +455,12 @@ class Config:
def __str__(self):
return pprint.pformat(self.__dict__, indent=2)
+ def __setattr__(self, name, value):
+ '''Before setting, check that the option is value.'''
+ if name not in self.options().keys():
+ raise ValueError('{} is not a valid config option'.format(name))
+ super().__setattr__(name, value)
+
@classmethod
def options(cls):
'''Return the dictionary ``option`` objects for this class.'''
diff --git a/test/example_config.yml b/test/example_config.yml
index <HASH>..<HASH> 100644
--- a/test/example_config.yml
+++ b/test/example_config.yml
@@ -1,3 +1,2 @@
# Test config file
-PRECISION: 100
-SOME_OTHER_CONFIG: 'loaded'
+SPEED: 'slow'
diff --git a/test/test_config.py b/test/test_config.py
index <HASH>..<HASH> 100644
--- a/test/test_config.py
+++ b/test/test_config.py
@@ -11,22 +11,26 @@ from pyphi import config
from pyphi.conf import Config, option
+class ExampleConfig(Config):
+ SPEED = option('default', values=['default', 'slow', 'fast'])
+
+
@pytest.fixture
def c():
- return Config()
+ return ExampleConfig()
def test_load_config_dict(c):
- c.load_config_dict({'KEY': 'VALUE'})
- assert c.KEY == 'VALUE'
+ c.load_config_dict({'SPEED': 'slow'})
+ assert c.SPEED == 'slow'
def test_snapshot(c):
- c.KEY = 'VALUE'
+ c.SPEED = 'slow'
snapshot = c.snapshot()
- assert snapshot == {'KEY': 'VALUE'}
- c.KEY = 'ANOTHER'
- assert snapshot == {'KEY': 'VALUE'}
+ assert snapshot == {'SPEED': 'slow'}
+ c.SPEED = 'fast'
+ assert snapshot == {'SPEED': 'slow'}
EXAMPLE_CONFIG_FILE = os.path.join(os.path.dirname(os.path.abspath(__file__)),
@@ -35,36 +39,30 @@ EXAMPLE_CONFIG_FILE = os.path.join(os.path.dirname(os.path.abspath(__file__)),
def test_load_config_file(c):
c.load_config_file(EXAMPLE_CONFIG_FILE)
- assert c.PRECISION == 100
- assert c.SOME_OTHER_CONFIG == 'loaded'
+ assert c.SPEED == 'slow'
def test_str(c):
- c.KEY = 'VALUE'
- assert str(c) == "{'KEY': 'VALUE'}"
+ c.SPEED = 'slow'
+ assert str(c) == "{'SPEED': 'slow'}"
def test_override(c):
- # Given some config value
- c.TEST_CONFIG = 1
-
- @c.override(TEST_CONFIG=1000)
+ @c.override(SPEED='slow')
def return_test_config(arg, kwarg=None):
# Decorator should still pass args
assert arg == 'arg'
assert kwarg == 3
- return c.TEST_CONFIG
+ return c.SPEED
# Should override config value in function
- assert return_test_config('arg', kwarg=3) == 1000
+ assert return_test_config('arg', kwarg=3) == 'slow'
# and revert the initial config value
- assert c.TEST_CONFIG == 1
+ assert c.SPEED == 'default'
def test_override_cleans_up_after_exception(c):
- c.TEST_CONFIG = 1
-
- @c.override(TEST_CONFIG=1000)
+ @c.override(SPEED='slow')
def raise_exception():
raise ValueError('elephants')
@@ -75,22 +73,18 @@ def test_override_cleans_up_after_exception(c):
assert e.args == ('elephants',)
# and reset original config value
- assert c.TEST_CONFIG == 1
+ assert c.SPEED == 'default'
def test_override_config_is_a_context_manager(c):
- c.TEST_CONFIG = 1
+ c.SPEED = 'slow'
- with c.override(TEST_CONFIG=1000):
+ with c.override(SPEED='fast'):
# Overriden
- assert c.TEST_CONFIG == 1000
+ assert c.SPEED == 'fast'
# Reverts original value
- assert c.TEST_CONFIG == 1
-
-
-class ExampleConfig(Config):
- SPEED = option('default', values=['default', 'slow', 'fast'])
+ assert c.SPEED == 'slow'
def test_option_descriptor():
@@ -113,6 +107,11 @@ def test_config_defaults():
assert c.defaults() == {'SPEED': 'default'}
+def test_must_be_valid_option(c):
+ with pytest.raises(ValueError):
+ c.KEY = 2
+
+
def test_option_on_change():
class Event:
def notify(self, config):
|
Don't allow non-options to be set
|
wmayner_pyphi
|
train
|
73c66c8c48c4399606b35ac02410d44284863438
|
diff --git a/base.php b/base.php
index <HASH>..<HASH> 100644
--- a/base.php
+++ b/base.php
@@ -1906,7 +1906,7 @@ class View extends Prefab {
$cached=$cache->exists($hash=$fw->hash($file),$data);
if ($cached && $cached[0]+$ttl>microtime(TRUE))
return $data;
- foreach ($fw->split($fw->get('UI')) as $dir)
+ foreach ($fw->split($fw->get('UI').';./') as $dir)
if (is_file($this->view=$fw->fixslashes($dir.$file))) {
if (isset($_COOKIE[session_name()]))
@session_start();
diff --git a/image.php b/image.php
index <HASH>..<HASH> 100644
--- a/image.php
+++ b/image.php
@@ -372,7 +372,7 @@ class Image {
function captcha($font,$size=24,$len=5,
$key=NULL,$path='',$fg=0xFFFFFF,$bg=0x000000) {
$fw=Base::instance();
- foreach ($fw->split($path?:$fw->get('UI')) as $dir)
+ foreach ($fw->split($path?:$fw->get('UI').';./') as $dir)
if (is_file($path=$dir.$font)) {
$seed=strtoupper(substr(uniqid(),-$len));
$block=$size*3;
@@ -525,7 +525,7 @@ class Image {
$fw=Base::instance();
// Create image from file
$this->file=$file;
- foreach ($fw->split($path?:$fw->get('UI')) as $dir)
+ foreach ($fw->split($path?:$fw->get('UI').';./') as $dir)
if (is_file($dir.$file)) {
$this->data=imagecreatefromstring($fw->read($dir.$file));
imagesavealpha($this->data,TRUE);
diff --git a/web.php b/web.php
index <HASH>..<HASH> 100644
--- a/web.php
+++ b/web.php
@@ -188,7 +188,7 @@ class Web extends Prefab {
$out[$file['name']]=!$file['error'] &&
is_uploaded_file($file['tmp_name']) &&
(!file_exists($file['name']) || $overwrite) &&
- (!$func || $fw->call($func,$file)!==FALSE) &&
+ (!$func || $fw->call($func,array($file))!==FALSE) &&
move_uploaded_file($file['tmp_name'],$file['name']);
}
}
@@ -503,7 +503,7 @@ class Web extends Prefab {
preg_match('/\w+$/',$files[0],$ext);
$cache=Cache::instance();
$dst='';
- foreach ($fw->split($path?:$fw->get('UI')) as $dir)
+ foreach ($fw->split($path?:$fw->get('UI').';./') as $dir)
foreach ($files as $file)
if (is_file($save=$fw->fixslashes($dir.$file))) {
if ($fw->get('CACHE') &&
|
Add base directory to UI path as fallback
|
bcosca_fatfree-core
|
train
|
d5b21278be518fd3db1fe48b17b862b103660b2c
|
diff --git a/explauto/environment/environment.py b/explauto/environment/environment.py
index <HASH>..<HASH> 100644
--- a/explauto/environment/environment.py
+++ b/explauto/environment/environment.py
@@ -4,6 +4,7 @@ from abc import ABCMeta, abstractmethod
from ..utils.config import make_configuration
from ..utils.observer import Observable
+from ..utils import rand_bounds
class Environment(Observable):
@@ -44,15 +45,8 @@ class Environment(Observable):
def compute_sensori_effect(self):
pass
- # def post_processing(self):
- # self.state = minimum(self.state, self.bounds[:,1])
- # self.state = maximum(self.state, self.bounds[:,0])
-
- def read(self):
- return self.state[self.readable]
-
- # def write(self, data):
- # self.state[self.writable] = data
+ def random_motors(self, n=1):
+ return rand_bounds(self.conf.bounds[:, self.conf.m_dims], n)
def dataset(self, orders):
n = orders.shape[0]
|
Add random_motor to Environment and clean it
|
flowersteam_explauto
|
train
|
9c9b967321ca2497f438b59a062c85ba1e08bbe1
|
diff --git a/telemetry/telemetry/tab_backend.py b/telemetry/telemetry/tab_backend.py
index <HASH>..<HASH> 100644
--- a/telemetry/telemetry/tab_backend.py
+++ b/telemetry/telemetry/tab_backend.py
@@ -94,9 +94,12 @@ class TabBackend(object):
return False
if self._runtime.Evaluate(
- 'window.chrome.gpuBenchmarking.windowSnapshotPNG === undefined'):
+ 'window.chrome.gpuBenchmarking.beginWindowSnapshotPNG === undefined'):
return False
+ # TODO(dtu): Also check for Chrome branch number, because of a bug in
+ # beginWindowSnapshotPNG in older versions. crbug.com/171592
+
return True
def Screenshot(self, timeout):
|
[Telemetry] Fix typos in Screenshot code.
We can't check the Chrome branch number yet, since we don't know what it is until this change is checked in :P
BUG=None.
TEST=None.
Review URL: <URL>
|
catapult-project_catapult
|
train
|
d453b39bf50592a0ba2a6e60751e6c3e1ea05138
|
diff --git a/tests/test_DataMatrix.py b/tests/test_DataMatrix.py
index <HASH>..<HASH> 100644
--- a/tests/test_DataMatrix.py
+++ b/tests/test_DataMatrix.py
@@ -19,18 +19,10 @@ class test_DataMatrixFromSlocusPop(unittest.TestCase):
self.pop, self.indlist, self.keys[0], self.keys[1])
self.gm = fwdpy11.sampling.genotype_matrix(
self.pop, self.indlist, self.keys[0], self.keys[1])
- self.hm_neutral = np.ndarray(
- self.hm.shape_neutral,
- buffer=self.hm.neutral, dtype=np.int8)
- self.hm_selected = np.ndarray(
- self.hm.shape_selected,
- buffer=self.hm.selected, dtype=np.int8)
- self.gm_neutral = np.ndarray(
- self.gm.shape_neutral,
- buffer=self.gm.neutral, dtype=np.int8)
- self.gm_selected = np.ndarray(
- self.gm.shape_selected,
- buffer=self.gm.selected, dtype=np.int8)
+ self.hm_neutral = np.array(self.hm.neutral)
+ self.hm_selected = np.array(self.hm.selected)
+ self.gm_neutral = np.array(self.gm.neutral)
+ self.gm_selected = np.array(self.gm.selected)
def testKeyNeutralityAndCount(self):
for i in self.keys[0]:
@@ -121,18 +113,10 @@ class test_DataMatrixFromMlocusPop(unittest.TestCase):
self.pop, self.indlist, self.nkeys, self.skeys)
self.gm = fwdpy11.sampling.genotype_matrix(
self.pop, self.indlist, self.nkeys, self.skeys)
- self.hm_neutral = np.ndarray(
- self.hm.shape_neutral,
- buffer=self.hm.neutral, dtype=np.int8)
- self.hm_selected = np.ndarray(
- self.hm.shape_selected,
- buffer=self.hm.selected, dtype=np.int8)
- self.gm_neutral = np.ndarray(
- self.gm.shape_neutral,
- buffer=self.gm.neutral, dtype=np.int8)
- self.gm_selected = np.ndarray(
- self.gm.shape_selected,
- buffer=self.gm.selected, dtype=np.int8)
+ self.hm_neutral = np.array(self.hm.neutral)
+ self.hm_selected = np.array(self.hm.selected)
+ self.gm_neutral = np.array(self.gm.neutral)
+ self.gm_selected = np.array(self.gm.selected)
def testConvertHapMatrixToSample(self):
nsample, ssample = fwdpy11.sampling.matrix_to_sample(self.hm)
|
Update unit tests of DataMatrix to reflect new Python classes.
|
molpopgen_fwdpy11
|
train
|
497f56c3e1b276fb9499833da0cebfb3b756d03b
|
diff --git a/tools/python_test_v4.py b/tools/python_test_v4.py
index <HASH>..<HASH> 100644
--- a/tools/python_test_v4.py
+++ b/tools/python_test_v4.py
@@ -843,9 +843,9 @@ for i in range(20, 40):
error_message = e.error_message
break
assert "Retry later" in error_message
-[current_project.delete() for current_project in projects]
settings.throttle_authenticated_api_enabled = False
settings.save()
+[current_project.delete() for current_project in projects]
# project import/export
ex = admin_project.exports.create({})
|
test: increase speed by disabling the rate limit faster
|
python-gitlab_python-gitlab
|
train
|
39f5cae8f08435437d5f0de24966c92417adb511
|
diff --git a/library/WT/Person.php b/library/WT/Person.php
index <HASH>..<HASH> 100644
--- a/library/WT/Person.php
+++ b/library/WT/Person.php
@@ -1680,6 +1680,9 @@ class WT_Person extends WT_GedcomRecord {
$full=$full;
}
+ // GEDCOM uses "//" to indicate an unknown surname
+ $full=preg_replace('/\/\//', '/@N.N./', $full);
+
// Extract the surname.
// Note, there may be multiple surnames, e.g. Jean /Vasquez/ y /Cortes/
if (preg_match('/\/.*\//', $full, $match)) {
|
unknown surnames not being recorded in the database
|
fisharebest_webtrees
|
train
|
8c1c912dff5d9e6bba0ef4c9fc3be640db1e84ff
|
diff --git a/src/menus/SidebarMenu.php b/src/menus/SidebarMenu.php
index <HASH>..<HASH> 100644
--- a/src/menus/SidebarMenu.php
+++ b/src/menus/SidebarMenu.php
@@ -13,7 +13,7 @@ namespace hipanel\modules\finance\menus;
use Yii;
-class SidebarMenu extends \hiqdev\menumanager\Menu
+class SidebarMenu extends \hiqdev\yii2\menus\Menu
{
public function items()
{
@@ -45,7 +45,7 @@ class SidebarMenu extends \hiqdev\menumanager\Menu
'holds' => [
'label' => Yii::t('hipanel:finance', 'Held payments'),
'url' => ['/finance/held-payments/index'],
- 'visible' => Yii::$app->user->can('resell'),
+ 'visible' => $user->can('resell'),
],
],
],
diff --git a/src/menus/TariffActionsMenu.php b/src/menus/TariffActionsMenu.php
index <HASH>..<HASH> 100644
--- a/src/menus/TariffActionsMenu.php
+++ b/src/menus/TariffActionsMenu.php
@@ -6,7 +6,7 @@ use hipanel\widgets\ModalButton;
use Yii;
use yii\helpers\Html;
-class TariffActionsMenu extends \hiqdev\menumanager\Menu
+class TariffActionsMenu extends \hiqdev\yii2\menus\Menu
{
public $model;
|
redone yii2-thememanager -> yii2-menus
|
hiqdev_hipanel-module-finance
|
train
|
e6fe0d118b96647656f45a0cfebd2b5060b3fc6c
|
diff --git a/src/main/java/org/javaspec/runner/ClassExampleGateway.java b/src/main/java/org/javaspec/runner/ClassExampleGateway.java
index <HASH>..<HASH> 100755
--- a/src/main/java/org/javaspec/runner/ClassExampleGateway.java
+++ b/src/main/java/org/javaspec/runner/ClassExampleGateway.java
@@ -118,7 +118,7 @@ final class ClassExampleGateway implements ExampleGateway {
ReflectionUtil.fieldsOfType(Establish.class, contextClass).forEach(befores::add);
ReflectionUtil.fieldsOfType(It.class, contextClass)
- .map(it -> factory.makeExample(contextClass, it, befores, null))
+ .map(it -> factory.makeExample(contextClass, it, befores, new ArrayList<Field>()))
.forEach(examples::add);
readInnerClasses(contextClass).forEach(x -> appendExamples(x, examples, befores));
}
diff --git a/src/test/java/org/javaspec/runner/ClassExampleGatewayTest.java b/src/test/java/org/javaspec/runner/ClassExampleGatewayTest.java
index <HASH>..<HASH> 100755
--- a/src/test/java/org/javaspec/runner/ClassExampleGatewayTest.java
+++ b/src/test/java/org/javaspec/runner/ClassExampleGatewayTest.java
@@ -78,26 +78,28 @@ public class ClassExampleGatewayTest {
private @Captor ArgumentCaptor<List<Field>> afters;
@Before
- public void initMocks() {
- MockitoAnnotations.initMocks(this);
- }
+ public void initMocks() { MockitoAnnotations.initMocks(this); }
- public class givenAClassWith1OrMoreNestedStaticClasses {
- @Test
- public void doesNotCreateExamplesForItFieldsDeclaredInAStaticNestedClass() {
- assertThat(extractNames(readExamples(NestedWithStaticHelperClass.class)), contains("asserts"));
+ /* Context: The (sub-)tree defined of the given context class and all its descendant, inner classes */
+
+ public class defineContext {
+ public class givenAClassWith1OrMoreNestedStaticClasses {
+ @Test
+ public void doesNotCreateExamplesForItFieldsDeclaredInAStaticNestedClass() {
+ assertThat(extractNames(readExamples(NestedWithStaticHelperClass.class)), contains("asserts"));
+ }
}
}
- public class givenAClassWith0OrMoreInnerClasses {
- public class andThereAreNoItFieldsInTheTreeOfTheClassAndItsInnerClasses {
+ public class defineExample {
+ public class givenNoItFieldsWithinTheContext {
@Test
public void returnsNoExamples() {
assertThat(readExamples(ContextClasses.Empty.class), empty());
}
}
- public class andAtLeast1ItFieldExistsSomewhereInTheTreeOfThisClassAndItsInnerClasses {
+ public class given1OrMoreItFieldsWithinTheContext {
@Test
public void returnsAnExampleForEachItField() {
readExamples(ContextClasses.NestedExamples.class, factory);
@@ -108,16 +110,46 @@ public class ClassExampleGatewayTest {
Mockito.verifyNoMoreInteractions(factory);
}
}
+ }
+
+ public class defineFixture {
+ public class givenNoFixtureFieldsInTheContext {
+ @Test
+ public void createdExamplesHaveNoFixture() {
+ readExamples(ContextClasses.OneIt.class, factory);
+ assertEmptyFixture(ContextClasses.OneIt.class, "only_test");
+ }
+ }
- public class and1OrMoreContextClassesContainsEstablishLambdas {
+ public class given2OrMoreItFieldsInTheSameScopeAnd1OrMoreFixtureFieldsVisibibleInThatScope {
+ private final ArgumentMatcher<Field> establish = field(ContextClasses.TwoItWithEstablish.class, "that");
+
+ @Test
+ public void allExamplesInTheSameScopeGetTheSameFixture() {
+ readExamples(ContextClasses.TwoItWithEstablish.class, factory);
+ assertBefores(ContextClasses.TwoItWithEstablish.class, "does_one_thing", establish);
+ assertBefores(ContextClasses.TwoItWithEstablish.class, "does_something_else", establish);
+ }
+ }
+
+ public class givenUpTo1EstablishLambdaInEachLevelOfContext {
@Test
- public void passesTheseLambdasAsBeforeLambdasForEachExample() {
+ public void theseBecomeBeforeLambdasThatRunOuterContextToInnerContext() {
readExamples(ContextClasses.NestedEstablish.class, factory);
assertBefores(ContextClasses.NestedEstablish.inner.class, "asserts",
field(ContextClasses.NestedEstablish.class, "outer_arrange"),
field(ContextClasses.NestedEstablish.inner.class, "inner_arrange"));
}
-
+ }
+
+ public class givenUpTo1BecauseLambdaInEachLevelOfContext {
+ @Test
+ public void ordersTheseLambdasInDescendingOrderStartingFromTheTopLevelContext() {
+ fail("pending");
+ }
+ }
+
+ public class and1OrMoreContextClassesContainsEstablishLambdas {
@Test @Ignore("wip")
public void ordersTheseLambdasInDescendingOrderStartingFromTheTopLevelContext() {
fail("pending");
@@ -162,6 +194,14 @@ public class ClassExampleGatewayTest {
assertThat(befores.getValue(), contains(beforeMatchers));
}
+ private void assertEmptyFixture(Class<?> itContext, String itName) {
+ verify(factory).makeExample(
+ Mockito.eq(itContext), Mockito.argThat(field(itContext, itName)),
+ befores.capture(), afters.capture());
+ assertThat(befores.getValue(), empty());
+ assertThat(afters.getValue(), empty());
+ }
+
private List<String> extractNames(List<NewExample> examples) {
return examples.stream().map(NewExample::getName).collect(toList());
}
|
Starting to do before lambdas for nested contexts.
|
kkrull_javaspec
|
train
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.