hash
stringlengths 40
40
| diff
stringlengths 131
114k
| message
stringlengths 7
980
| project
stringlengths 5
67
| split
stringclasses 1
value |
|---|---|---|---|---|
5b935700848f55a1ed12580e94ff2753ddea34ea
|
diff --git a/dev/MRecordRTC.js b/dev/MRecordRTC.js
index <HASH>..<HASH> 100644
--- a/dev/MRecordRTC.js
+++ b/dev/MRecordRTC.js
@@ -311,14 +311,30 @@ function MRecordRTC(mediaStream) {
*/
this.getDataURL = function(callback) {
this.getBlob(function(blob) {
- getDataURL(blob.audio, function(_audioDataURL) {
- getDataURL(blob.video, function(_videoDataURL) {
- callback({
- audio: _audioDataURL,
- video: _videoDataURL
+ if(blob.audio && blob.video) {
+ getDataURL(blob.audio, function(_audioDataURL) {
+ getDataURL(blob.video, function(_videoDataURL) {
+ callback({
+ audio: _audioDataURL,
+ video: _videoDataURL
+ });
});
});
- });
+ }
+ else if(blob.audio) {
+ getDataURL(blob.audio, function(_audioDataURL) {
+ callback({
+ audio: _audioDataURL
+ });
+ });
+ }
+ else if(blob.video) {
+ getDataURL(blob.video, function(_videoDataURL) {
+ callback({
+ video: _videoDataURL
+ });
+ });
+ }
});
function getDataURL(blob, callback00) {
|
Add check for in audio/video blobs exist
This effect MRecordRTC's getDataURL method when using a browser which
records in a single blob. Currently only firefox or chome(ium) > <I>.
|
muaz-khan_RecordRTC
|
train
|
164a90f76603e324658fb5f2b244511374f728d2
|
diff --git a/tinytag/tinytag.py b/tinytag/tinytag.py
index <HASH>..<HASH> 100644
--- a/tinytag/tinytag.py
+++ b/tinytag/tinytag.py
@@ -261,7 +261,7 @@ class MP4(TinyTag):
# http://sasperger.tistory.com/103
esds_atom.seek(22, os.SEEK_CUR) # jump over most data...
esds_atom.seek(4, os.SEEK_CUR) # jump over max bitrate
- avg_br = struct.unpack('>I', esds_atom.read(4))[0] / 1000 # kbit/s
+ avg_br = struct.unpack('>I', esds_atom.read(4))[0] / 1000.0 # kbit/s
return {'channels': channels, 'samplerate': sr, 'bitrate': avg_br}
@classmethod
@@ -712,7 +712,7 @@ class Ogg(TinyTag):
(channels, self.samplerate, max_bitrate, bitrate,
min_bitrate) = struct.unpack("<B4i", packet[11:28])
if not self.audio_offset:
- self.bitrate = bitrate / 1024
+ self.bitrate = bitrate / 1024.0
self.audio_offset = page_start_pos
elif packet[0:7] == b"\x03vorbis":
walker.seek(7, os.SEEK_CUR) # jump over header name
@@ -806,7 +806,7 @@ class Wave(TinyTag):
if subchunkid == b'fmt ':
_, channels, self.samplerate = struct.unpack('HHI', fh.read(8))
_, _, bitdepth = struct.unpack('<IHH', fh.read(8))
- self.bitrate = self.samplerate * channels * bitdepth / 1024
+ self.bitrate = self.samplerate * channels * bitdepth / 1024.0
elif subchunkid == b'data':
self.duration = float(subchunksize)/channels/self.samplerate/(bitdepth/8)
self.audio_offest = fh.tell() - 8 # rewind to data header
|
fixed OGG, MP4 and Wave bitrate being cast to int in python 2
|
devsnd_tinytag
|
train
|
7aac0b52539361415c3ba74e9e0de99c05813d4b
|
diff --git a/python/mxnet/contrib/onnx/onnx2mx/_op_translations.py b/python/mxnet/contrib/onnx/onnx2mx/_op_translations.py
index <HASH>..<HASH> 100644
--- a/python/mxnet/contrib/onnx/onnx2mx/_op_translations.py
+++ b/python/mxnet/contrib/onnx/onnx2mx/_op_translations.py
@@ -65,19 +65,47 @@ def sample_multinomial(attrs, inputs, proto_obj):
# Arithmetic Operations
def add(attrs, inputs, proto_obj):
"""Adding two tensors"""
- return translation_utils.broadcast_arithmetic_helper(attrs, inputs, proto_obj, 'broadcast_add')
+ new_attr = {}
+
+ if 'broadcast' in attrs and attrs['broadcast'] == 1:
+ broadcast_axis = attrs['axis']
+ op_value = translation_utils._fix_broadcast('broadcast_add', inputs,
+ broadcast_axis, proto_obj)
+ return op_value, new_attr, inputs
+ return 'broadcast_add', new_attr, inputs
def subtract(attrs, inputs, proto_obj):
"""Subtracting two tensors"""
- return translation_utils.broadcast_arithmetic_helper(attrs, inputs, proto_obj, 'broadcast_sub')
+ new_attr = {}
+
+ if 'broadcast' in attrs and attrs['broadcast'] == 1:
+ broadcast_axis = attrs['axis']
+ op_value = translation_utils._fix_broadcast('broadcast_sub', inputs,
+ broadcast_axis, proto_obj)
+ return op_value, new_attr, inputs
+ return 'broadcast_sub', new_attr, inputs
def multiply(attrs, inputs, proto_obj):
"""Multiply two tensors"""
- return translation_utils.broadcast_arithmetic_helper(attrs, inputs, proto_obj, 'broadcast_mul')
+ new_attr = {}
+
+ if 'broadcast' in attrs and attrs['broadcast'] == 1:
+ broadcast_axis = attrs['axis']
+ op_value = translation_utils._fix_broadcast('broadcast_mul', inputs,
+ broadcast_axis, proto_obj)
+ return op_value, new_attr, inputs
+ return 'broadcast_mul', new_attr, inputs
def divide(attrs, inputs, proto_obj):
"""Divide two tensors"""
- return translation_utils.broadcast_arithmetic_helper(attrs, inputs, proto_obj, 'broadcast_div')
+ new_attr = {}
+
+ if 'broadcast' in attrs and attrs['broadcast'] == 1:
+ broadcast_axis = attrs['axis']
+ op_value = translation_utils._fix_broadcast('broadcast_div', inputs,
+ broadcast_axis, proto_obj)
+ return op_value, new_attr, inputs
+ return 'broadcast_div', new_attr, inputs
def mean(attrs, inputs, proto_obj):
"""Mean of all the input tensors."""
diff --git a/python/mxnet/contrib/onnx/onnx2mx/_translation_utils.py b/python/mxnet/contrib/onnx/onnx2mx/_translation_utils.py
index <HASH>..<HASH> 100644
--- a/python/mxnet/contrib/onnx/onnx2mx/_translation_utils.py
+++ b/python/mxnet/contrib/onnx/onnx2mx/_translation_utils.py
@@ -245,17 +245,3 @@ def get_input_shape(sym, proto_obj):
result = mod.get_outputs()[0].asnumpy()
return result.shape
-
-def broadcast_arithmetic_helper(attrs, inputs, proto_obj, current_op_name):
- """Helper function for broadcast arithmetic ops."""
- new_attr = {}
- op_names = ['batchnorm, convolution, deconvolution']
- if 'broadcast' in attrs and attrs['broadcast'] == 1:
- broadcast_axis = attrs['axis']
- for op_name in op_names:
- # if input is bias which comes after conv, deconv, batchnorm operators
- # then only reshape bias term
- if inputs[0].name.startswith(op_name):
- op_value = _fix_broadcast(current_op_name, inputs, broadcast_axis, proto_obj)
- return op_value, new_attr, inputs
- return current_op_name, new_attr, inputs
|
reverting broadcasting fixes (#<I>)
|
apache_incubator-mxnet
|
train
|
bf3123f362f3d17170cb336f3ab206fce13d0c6c
|
diff --git a/src/Models/AbstractModel.php b/src/Models/AbstractModel.php
index <HASH>..<HASH> 100644
--- a/src/Models/AbstractModel.php
+++ b/src/Models/AbstractModel.php
@@ -2,10 +2,10 @@
namespace Adldap\Models;
-use Adldap\Adldap;
-use Adldap\Classes\Utilities;
use Adldap\Exceptions\AdldapException;
use Adldap\Exceptions\ModelNotFoundException;
+use Adldap\Query\Builder;
+use Adldap\Classes\Utilities;
use Adldap\Objects\DistinguishedName;
use Adldap\Schemas\ActiveDirectory;
use ArrayAccess;
@@ -23,9 +23,9 @@ abstract class AbstractModel implements ArrayAccess, JsonSerializable
/**
* The current LDAP connection instance.
*
- * @var Adldap
+ * @var Builder
*/
- protected $adldap;
+ protected $query;
/**
* Holds the current objects attributes.
@@ -51,16 +51,16 @@ abstract class AbstractModel implements ArrayAccess, JsonSerializable
/**
* Constructor.
*
- * @param array $attributes
- * @param Adldap $adldap
+ * @param array $attributes
+ * @param Builder $builder
*/
- public function __construct(array $attributes = [], Adldap $adldap)
+ public function __construct(array $attributes = [], Builder $builder)
{
$this->syncOriginal();
$this->fill($attributes);
- $this->adldap = $adldap;
+ $this->query = $builder;
}
/**
@@ -471,7 +471,7 @@ abstract class AbstractModel implements ArrayAccess, JsonSerializable
*/
public function getObjectClass()
{
- return $this->getAdldap()->search()->findByDn($this->getObjectCategoryDn());
+ return $this->query->findByDn($this->getObjectCategoryDn());
}
/**
@@ -664,10 +664,10 @@ abstract class AbstractModel implements ArrayAccess, JsonSerializable
$dn = $this->getDn();
if (count($modifications) > 0) {
- $modified = $this->getAdldap()->getConnection()->modifyBatch($dn, $modifications);
+ $modified = $this->query->getConnection()->modifyBatch($dn, $modifications);
if ($modified) {
- return $this->getAdldap()->search()->findByDn($dn);
+ return $this->query->findByDn($dn);
}
return false;
@@ -692,7 +692,7 @@ abstract class AbstractModel implements ArrayAccess, JsonSerializable
if ($this->exists) {
$add = [$attribute => $value];
- return $this->getAdldap()->getConnection()->modAdd($this->getDn(), $add);
+ return $this->query->getConnection()->modAdd($this->getDn(), $add);
}
return false;
@@ -713,10 +713,10 @@ abstract class AbstractModel implements ArrayAccess, JsonSerializable
// as it's inserted independently.
unset($attributes['dn']);
- $added = $this->getAdldap()->getConnection()->add($dn, $attributes);
+ $added = $this->query->getConnection()->add($dn, $attributes);
if ($added) {
- return $this->getAdldap()->search()->findByDn($dn);
+ return $this->query->findByDn($dn);
}
return false;
@@ -736,7 +736,7 @@ abstract class AbstractModel implements ArrayAccess, JsonSerializable
// for the attribute so AD knows to remove it.
$remove = [$attribute => []];
- return $this->getAdldap()->getConnection()->modDelete($this->getDn(), $remove);
+ return $this->query->getConnection()->modDelete($this->getDn(), $remove);
}
return false;
@@ -767,17 +767,7 @@ abstract class AbstractModel implements ArrayAccess, JsonSerializable
throw new AdldapException($message);
}
- return $this->getAdldap()->getConnection()->delete($dn);
- }
-
- /**
- * Returns the current Adldap instance.
- *
- * @return Adldap
- */
- public function getAdldap()
- {
- return $this->adldap;
+ return $this->query->getConnection()->delete($dn);
}
/**
|
Model changes
- Model is now constructed by a Builder instance instead of an Adldap
instance for less dependencies
|
Adldap2_Adldap2
|
train
|
d25119943287384a54be89770cbb7926bba48843
|
diff --git a/client/driver/docker.go b/client/driver/docker.go
index <HASH>..<HASH> 100644
--- a/client/driver/docker.go
+++ b/client/driver/docker.go
@@ -38,6 +38,10 @@ import (
)
var (
+ // createClientsLock is a lock that protects reading/writing global client
+ // variables
+ createClientsLock sync.Mutex
+
// client is a docker client with a timeout of 5 minutes. This is for doing
// all operations with the docker daemon besides which are not long running
// such as creating, killing containers, etc.
@@ -110,7 +114,7 @@ const (
// dockerHealthCheckTimeout is the length of time a request for a health
// check client can be outstanding before it is timed out.
- dockerHealthCheckTimeout = 5 * time.Minute
+ dockerHealthCheckTimeout = 1 * time.Minute
// dockerImageResKey is the CreatedResources key for docker images
dockerImageResKey = "image"
@@ -1005,7 +1009,12 @@ func (d *DockerDriver) cleanupImage(imageID string) error {
return nil
}
+// dockerHealthCheckClient creates a single *docker.Client with a timeout of
+// one minute, which will be used when performing Docker health checks.
func (d *DockerDriver) dockerHealthCheckClient() (*docker.Client, error) {
+ createClientsLock.Lock()
+ defer createClientsLock.Unlock()
+
if healthCheckClient != nil {
return healthCheckClient, nil
}
@@ -1020,6 +1029,38 @@ func (d *DockerDriver) dockerHealthCheckClient() (*docker.Client, error) {
return healthCheckClient, nil
}
+// dockerClients creates two *docker.Client, one for long running operations and
+// the other for shorter operations. In test / dev mode we can use ENV vars to
+// connect to the docker daemon. In production mode we will read docker.endpoint
+// from the config file.
+func (d *DockerDriver) dockerClients() (*docker.Client, *docker.Client, error) {
+ createClientsLock.Lock()
+ defer createClientsLock.Unlock()
+
+ if client != nil && waitClient != nil {
+ return client, waitClient, nil
+ }
+
+ var merr multierror.Error
+
+ newClient, err := d.newDockerClient(dockerTimeout)
+ if err != nil {
+ merr.Errors = append(merr.Errors, err)
+ } else {
+ client = newClient
+ }
+
+ newWaitClient, err := d.newDockerClient(0 * time.Minute)
+ if err != nil {
+ merr.Errors = append(merr.Errors, err)
+ } else {
+ waitClient = newWaitClient
+ }
+
+ return client, waitClient, merr.ErrorOrNil()
+}
+
+// newDockerClient creates a new *docker.Client with a configurable timeout
func (d *DockerDriver) newDockerClient(timeout time.Duration) (*docker.Client, error) {
var err error
var merr multierror.Error
@@ -1063,34 +1104,6 @@ func (d *DockerDriver) newDockerClient(timeout time.Duration) (*docker.Client, e
return newClient, merr.ErrorOrNil()
}
-// dockerClients creates two *docker.Client, one for long running operations and
-// the other for shorter operations. In test / dev mode we can use ENV vars to
-// connect to the docker daemon. In production mode we will read docker.endpoint
-// from the config file.
-func (d *DockerDriver) dockerClients() (*docker.Client, *docker.Client, error) {
- if client != nil && waitClient != nil {
- return client, waitClient, nil
- }
-
- var merr multierror.Error
-
- newClient, err := d.newDockerClient(dockerTimeout)
- if err != nil {
- merr.Errors = append(merr.Errors, err)
- } else {
- client = newClient
- }
-
- newWaitClient, err := d.newDockerClient(0 * time.Minute)
- if err != nil {
- merr.Errors = append(merr.Errors, err)
- } else {
- waitClient = newWaitClient
- }
-
- return client, waitClient, merr.ErrorOrNil()
-}
-
func (d *DockerDriver) containerBinds(driverConfig *DockerDriverConfig, ctx *ExecContext,
task *structs.Task) ([]string, error) {
|
group similar functions; update comments
health check timeout should be 1 minute
|
hashicorp_nomad
|
train
|
2d7f30ed7b55c7bea9e5d3bfd9973d3018ee8dbe
|
diff --git a/guacamole-common-js/src/main/resources/guacamole.js b/guacamole-common-js/src/main/resources/guacamole.js
index <HASH>..<HASH> 100644
--- a/guacamole-common-js/src/main/resources/guacamole.js
+++ b/guacamole-common-js/src/main/resources/guacamole.js
@@ -307,12 +307,14 @@ function GuacamoleClient(display, tunnel) {
var image = new Image();
image.onload = function() {
cursorImage = image;
+
+ var cursorX = cursorRectX + cursorHotspotX;
+ var cursorY = cursorRectY + cursorHotspotY;
+
cursorHotspotX = x;
cursorHotspotY = y;
- redrawCursor(
- cursorRectX + cursorHotspotX,
- cursorRectY + cursorHotspotY
- );
+
+ redrawCursor(cursorX, cursorY);
};
image.src = "data:image/png;base64," + data
|
Fixed initial draw location for new cursors
|
glyptodon_guacamole-client
|
train
|
102ef98d32a40e1c7a7526d1d0d3165885315f1c
|
diff --git a/activerecord/test/cases/schema_dumper_test.rb b/activerecord/test/cases/schema_dumper_test.rb
index <HASH>..<HASH> 100644
--- a/activerecord/test/cases/schema_dumper_test.rb
+++ b/activerecord/test/cases/schema_dumper_test.rb
@@ -229,6 +229,13 @@ class SchemaDumperTest < ActiveRecord::TestCase
def test_schema_dump_includes_tsvector_shorthand_definition
output = standard_dump
+ if %r{create_table "postgresql_hstores"} =~ output
+ assert_match %r{t.hstore "hash_store", default => ""}, output
+ end
+ end
+
+ def test_schema_dump_includes_tsvector_shorthand_definition
+ output = standard_dump
if %r{create_table "postgresql_tsvectors"} =~ output
assert_match %r{t.tsvector "text_vector"}, output
end
diff --git a/activerecord/test/schema/postgresql_specific_schema.rb b/activerecord/test/schema/postgresql_specific_schema.rb
index <HASH>..<HASH> 100644
--- a/activerecord/test/schema/postgresql_specific_schema.rb
+++ b/activerecord/test/schema/postgresql_specific_schema.rb
@@ -1,6 +1,6 @@
ActiveRecord::Schema.define do
- %w(postgresql_tsvectors postgresql_arrays postgresql_moneys postgresql_numbers postgresql_times postgresql_network_addresses postgresql_bit_strings
+ %w(postgresql_tsvectors postgresql_hstores postgresql_arrays postgresql_moneys postgresql_numbers postgresql_times postgresql_network_addresses postgresql_bit_strings
postgresql_oids postgresql_xml_data_type defaults geometrics postgresql_timestamp_with_zones).each do |table_name|
execute "DROP TABLE IF EXISTS #{quote_table_name table_name}"
end
@@ -64,6 +64,13 @@ _SQL
_SQL
execute <<_SQL
+ CREATE TABLE postgresql_hstores (
+ id SERIAL PRIMARY KEY,
+ hash_store hstore default ''::hstore
+ );
+_SQL
+
+ execute <<_SQL
CREATE TABLE postgresql_moneys (
id SERIAL PRIMARY KEY,
wealth MONEY
|
schema dumper tests for hstore
|
rails_rails
|
train
|
ea74a3103f655cdacb391eabf2e60f82e38db123
|
diff --git a/src/Commands/MonitorLists/Healthy.php b/src/Commands/MonitorLists/Healthy.php
index <HASH>..<HASH> 100644
--- a/src/Commands/MonitorLists/Healthy.php
+++ b/src/Commands/MonitorLists/Healthy.php
@@ -20,7 +20,6 @@ class Healthy
ConsoleOutput::info('================');
$rows = $healthyMonitor->map(function (Monitor $monitor) {
-
$certificateFound = '';
$certificateExpirationDate = '';
$certificateIssuer = '';
|
Apply fixes from StyleCI (#<I>)
|
spatie_laravel-uptime-monitor
|
train
|
b9c02f7b7dd0f5000889d92466030aa3006a6457
|
diff --git a/test/test_rrschedule.rb b/test/test_rrschedule.rb
index <HASH>..<HASH> 100644
--- a/test/test_rrschedule.rb
+++ b/test/test_rrschedule.rb
@@ -15,7 +15,7 @@ class TestRrschedule < Test::Unit::TestCase
assert schedule.exclude_dates.empty?
end
- should "have a dummy team when team number is odd" do
+ should "have a dummy team when number of teams is odd" do
schedule = RRSchedule::Schedule.new(
:teams => Array(1..9)
)
@@ -24,7 +24,7 @@ class TestRrschedule < Test::Unit::TestCase
assert schedule.teams.member?(:dummy), "There should always be a :dummy team when the nbr of teams is odd"
end
- should "not have a dummy team when team number is even" do
+ should "not have a dummy team when number of teams is even" do
schedule = RRSchedule::Schedule.new(
:teams => Array(1..6)
)
@@ -81,6 +81,25 @@ class TestRrschedule < Test::Unit::TestCase
end
end
+ context "Any valid schedule" do
+ setup do
+ @s = RRSchedule::Schedule.new(
+ :teams => %w(a b c d e f g h i j l m),
+ :playing_surfaces => %w(one two),
+ :game_times => ["10:00 AM", "13:00 PM"]
+ )
+ end
+
+ should "have gamedays that respect the wdays attribute" do
+ @s.wdays = [3,5]
+ @s.generate
+
+ @s.gamedays.each do |gd,games|
+ assert [3,5].include?(gd.wday), "wday is #{gd.wday.to_s} but should be 3 or 5"
+ end
+ end
+ end
+
context "A generated schedule with an odd number of teams" do
setup do
@s = RRSchedule::Schedule.new(
@@ -118,6 +137,6 @@ class TestRrschedule < Test::Unit::TestCase
assert @s.gamedays.collect{|gd,games| games}.flatten.select{
|g| [g.team_a,g.team_b].include?(:dummy)
}.size == 0
- end
- end
+ end
+ end
end
|
add test to make sure that every gamedays respect the wdays attribute
|
flamontagne_rrschedule
|
train
|
e1f6549fbd5158c54cb765e651dc06be4f7fdb6b
|
diff --git a/Entity/User.php b/Entity/User.php
index <HASH>..<HASH> 100644
--- a/Entity/User.php
+++ b/Entity/User.php
@@ -265,7 +265,7 @@ class User extends AbstractRoleSubject implements Serializable, AdvancedUserInte
/**
* @ORM\Column(name="is_mail_notified", type="boolean")
*/
- protected $isMailNotified = false;
+ protected $isMailNotified = true;
/**
* @ORM\Column(name="last_uri", length=255, nullable=true)
|
Notifications are sent by email by default.
|
claroline_CoreBundle
|
train
|
9e9d0d47b0e9e4d4b724b74056cf5624cf8fbb94
|
diff --git a/blueprints/blueprints-io/src/main/java/com/tinkerpop/blueprints/io/graphml/GraphMLWriter.java b/blueprints/blueprints-io/src/main/java/com/tinkerpop/blueprints/io/graphml/GraphMLWriter.java
index <HASH>..<HASH> 100644
--- a/blueprints/blueprints-io/src/main/java/com/tinkerpop/blueprints/io/graphml/GraphMLWriter.java
+++ b/blueprints/blueprints-io/src/main/java/com/tinkerpop/blueprints/io/graphml/GraphMLWriter.java
@@ -35,7 +35,7 @@ public class GraphMLWriter implements GraphWriter {
private Map<String, String> vertexKeyTypes = null;
private Map<String, String> edgeKeyTypes = null;
- private String xmlSchemaLocation = null;
+ private Optional<String> xmlSchemaLocation;
private Optional<String> edgeLabelKey;
/**
@@ -48,7 +48,7 @@ public class GraphMLWriter implements GraphWriter {
this.normalize = normalize;
this.vertexKeyTypes = vertexKeyTypes;
this.edgeKeyTypes = edgeKeyTypes;
- this.xmlSchemaLocation = xmlSchemaLocation;
+ this.xmlSchemaLocation = Optional.ofNullable(xmlSchemaLocation);
this.edgeLabelKey = Optional.ofNullable(edgeLabelKey);
}
@@ -111,8 +111,7 @@ public class GraphMLWriter implements GraphWriter {
XMLConstants.W3C_XML_SCHEMA_INSTANCE_NS_URI);
//XML Schema location
writer.writeAttribute(GraphMLTokens.XML_SCHEMA_NAMESPACE_TAG + ":" + GraphMLTokens.XML_SCHEMA_LOCATION_ATTRIBUTE,
- GraphMLTokens.GRAPHML_XMLNS + " " + (this.xmlSchemaLocation == null ?
- GraphMLTokens.DEFAULT_GRAPHML_SCHEMA_LOCATION : this.xmlSchemaLocation));
+ GraphMLTokens.GRAPHML_XMLNS + " " + this.xmlSchemaLocation.orElse(GraphMLTokens.DEFAULT_GRAPHML_SCHEMA_LOCATION));
// <key id="weight" for="edge" attr.name="weight" attr.type="float"/>
Collection<String> keyset;
|
Convert XMLSchemaLocation setting to Optional in GraphMLWriter.
|
apache_tinkerpop
|
train
|
6f2a574808207b64e3bbee4bd58baf276bd22105
|
diff --git a/src/extend/toDiastereotopicSVG.js b/src/extend/toDiastereotopicSVG.js
index <HASH>..<HASH> 100644
--- a/src/extend/toDiastereotopicSVG.js
+++ b/src/extend/toDiastereotopicSVG.js
@@ -5,8 +5,9 @@ module.exports = function toDiastereotopicSVG(options) {
var width=options.width||300;
var height=options.width||200;
var prefix=options.width||"ocl";
+ var svg=options.svg;
var diaIDs = this.getDiastereotopicAtomIDs();
- var svg=this.toSVG(width, height, prefix);
+ if (!svg) svg=this.toSVG(width, height, prefix);
svg=svg.replace(/Atom:[0-9]+\"/g,function(value) {
var atom=value.replace(/[^0-9]/g,'');
diff --git a/test/extend/toDiastereotopicSVG.js b/test/extend/toDiastereotopicSVG.js
index <HASH>..<HASH> 100644
--- a/test/extend/toDiastereotopicSVG.js
+++ b/test/extend/toDiastereotopicSVG.js
@@ -2,11 +2,11 @@
var OCLE = require('../..');
-
+var testSVG='<svg id="ocl" xmlns="http://www.w3.org/2000/svg" version="1.1" width="300px" height="200px" viewBox="0 0 300 200">\r <style> #ocl {pointer-events:none; } #ocl .event { pointer-events:all;} </style>\r <line x1="150" y1="94" x2="170" y2="106" style="stroke:rgb(0,0,0);stroke-width:1"/>\r <line x1="129" y1="106" x2="150" y2="94" style="stroke:rgb(0,0,0);stroke-width:1"/>\r <line id="ocl:Bond:1-0" class="event" x1="150" y1="94" x2="170" y2="106" stroke-width="8" stroke-opacity="0"/>\r <line id="ocl:Bond:2-1" class="event" x1="129" y1="106" x2="150" y2="94" stroke-width="8" stroke-opacity="0"/>\r <circle id="ocl:Atom:0" class="event" cx="170" cy="106" r="8" fill-opacity="0"/>\r <circle id="ocl:Atom:1" class="event" cx="150" cy="94" r="8" fill-opacity="0"/>\r <circle id="ocl:Atom:2" class="event" cx="129" cy="106" r="8" fill-opacity="0"/>\r</svg>';
describe('toDiastereotopicSVG on propane', function () {
var molecule=OCLE.Molecule.fromSmiles('CCC');
- var svg=molecule.toDiastereotopicSVG();
+ var svg=molecule.toDiastereotopicSVG({svg: testSVG});
it('check that is contains the diastereotopicID', function () {
svg.indexOf('data-atomid="eMBBYchGzRCaU@"').should.equal(730);
|
Add possibility to add a SVG in toDaistereotopicSVG to allow testing
|
cheminfo-js_openchemlib-extended
|
train
|
fbe46d84d37bb8541ba7211e36c58518ddeaae41
|
diff --git a/src/nwmatcher.js b/src/nwmatcher.js
index <HASH>..<HASH> 100644
--- a/src/nwmatcher.js
+++ b/src/nwmatcher.js
@@ -938,12 +938,12 @@
compileSelector =
function(selector, source) {
- var i, a, b, n, k, expr, match, result, status, test, type;
-
- k = 0;
+ var i, a, b, n, k = 0, expr, match, result, status, test, type;
while (selector) {
+ k++;
+
// *** Universal selector
// * match all (empty block, do not remove)
if ((match = selector.match(Patterns.universal))) {
@@ -1030,7 +1030,6 @@
// *** Adjacent sibling combinator
// E + F (F adiacent sibling of E)
else if ((match = selector.match(Patterns.adjacent))) {
- k++;
source = NATIVE_TRAVERSAL_API ?
'var N' + k + '=e;if(e&&(e=e.previousElementSibling)){' + source + '}e=N' + k + ';' :
'var N' + k + '=e;while(e&&(e=e.previousSibling)){if(e.nodeName>"@"){' + source + 'break;}}e=N' + k + ';';
@@ -1039,7 +1038,6 @@
// *** General sibling combinator
// E ~ F (F relative sibling of E)
else if ((match = selector.match(Patterns.relative))) {
- k++;
source = NATIVE_TRAVERSAL_API ?
('var N' + k + '=e;e=e.parentNode.firstElementChild;' +
'while(e&&e!=N' + k + '){' + source + 'e=e.nextElementSibling;}e=N' + k + ';') :
@@ -1050,14 +1048,12 @@
// *** Child combinator
// E > F (F children of E)
else if ((match = selector.match(Patterns.children))) {
- k++;
source = 'var N' + k + '=e;if(e&&e!==h&&e!==g&&(e=e.parentNode)){' + source + '}e=N' + k + ';';
}
// *** Descendant combinator
// E F (E ancestor of F)
else if ((match = selector.match(Patterns.ancestor))) {
- k++;
source = 'var N' + k + '=e;while(e&&e!==h&&e!==g&&(e=e.parentNode)){' + source + '}e=N' + k + ';';
}
|
joined increments of the same value in one place
|
dperini_nwmatcher
|
train
|
cd81a444cd0f570d9bc7ad94aea888971f835d55
|
diff --git a/pkg/cui/recipients.go b/pkg/cui/recipients.go
index <HASH>..<HASH> 100644
--- a/pkg/cui/recipients.go
+++ b/pkg/cui/recipients.go
@@ -213,6 +213,10 @@ func AskForPrivateKey(ctx context.Context, crypto backend.Crypto, name, prompt s
}
iv, err := termio.AskForInt(ctx, fmt.Sprintf("Please enter the number of a key (0-%d, [q]uit)", len(kl)-1), 0)
if err != nil {
+ if err.Error() == "user aborted" {
+ return "", err
+ }
+
continue
}
if iv >= 0 && iv < len(kl) {
|
Bail-out on q-key during initializing store (#<I>)
During initializing store, on step where gopass requests information,
which private key should use, user cannot immediately stop the process,
when he type the 'q' letter (as a quit).
|
gopasspw_gopass
|
train
|
14409fa133d8ce7d0ecf8636a5a4cccac851db33
|
diff --git a/holoviews/core/dimension.py b/holoviews/core/dimension.py
index <HASH>..<HASH> 100644
--- a/holoviews/core/dimension.py
+++ b/holoviews/core/dimension.py
@@ -252,7 +252,8 @@ class LabelledData(param.Parameterized):
the match, and so the sanitized versions of those values will
need to be provided if the match is to succeed.
"""
- if isinstance(spec, type): return isinstance(self, spec)
+ if callable(spec) and not isinstance(spec, type): return spec(self)
+ elif isinstance(spec, type): return isinstance(self, spec)
specification = (self.__class__.__name__, self.group, self.label)
identifier_specification = tuple(sanitize_identifier(ident, escape=False)
for ident in specification)
@@ -283,10 +284,7 @@ class LabelledData(param.Parameterized):
matches = specs is None
if not matches:
for spec in specs:
- if callable(spec) and not isinstance(spec, type):
- matches = spec(self)
- else:
- matches = self.matches(spec)
+ matches = self.matches(spec)
if matches: break
if matches:
accumulator.append(fn(self))
|
Moved callable matching from LabelledData.traverse to .matches
|
pyviz_holoviews
|
train
|
8b0916edcfff54942d8a7e1a2df81be521891efd
|
diff --git a/salt/modules/solaris_shadow.py b/salt/modules/solaris_shadow.py
index <HASH>..<HASH> 100644
--- a/salt/modules/solaris_shadow.py
+++ b/salt/modules/solaris_shadow.py
@@ -6,8 +6,11 @@ Manage the shadow file
import os
try:
import spwd
+ HAS_SPWD = True
except ImportError:
- pass
+ # SmartOS joyent_20130322T181205Z does not have spwd
+ HAS_SPWD = False
+ import pwd
# Import salt libs
import salt.utils
@@ -28,27 +31,87 @@ def info(name):
salt '*' shadow.info root
'''
+ if HAS_SPWD:
+ try:
+ data = spwd.getspnam(name)
+ ret = {
+ 'name': data.sp_nam,
+ 'pwd': data.sp_pwd,
+ 'lstchg': data.sp_lstchg,
+ 'min': data.sp_min,
+ 'max': data.sp_max,
+ 'warn': data.sp_warn,
+ 'inact': data.sp_inact,
+ 'expire': data.sp_expire}
+ except KeyError:
+ ret = {
+ 'name': '',
+ 'pwd': '',
+ 'lstchg': '',
+ 'min': '',
+ 'max': '',
+ 'warn': '',
+ 'inact': '',
+ 'expire': ''}
+ return ret
+
+ # SmartOS joyent_20130322T181205Z does not have spwd, but not all is lost
+ # Return what we can know
+ ret = {
+ 'name': '',
+ 'pwd': '',
+ 'lstchg': '',
+ 'min': '',
+ 'max': '',
+ 'warn': '',
+ 'inact': '',
+ 'expire': ''}
+
try:
- data = spwd.getspnam(name)
- ret = {
- 'name': data.sp_nam,
- 'pwd': data.sp_pwd,
- 'lstchg': data.sp_lstchg,
- 'min': data.sp_min,
- 'max': data.sp_max,
- 'warn': data.sp_warn,
- 'inact': data.sp_inact,
- 'expire': data.sp_expire}
+ data = pwd.getpwnam(name)
+ ret.update({
+ 'name': name,
+ 'pwd': data.pw_dir
+ })
except KeyError:
- ret = {
- 'name': '',
- 'pwd': '',
- 'lstchg': '',
- 'min': '',
- 'max': '',
- 'warn': '',
- 'inact': '',
- 'expire': ''}
+ return ret
+
+ # For SmartOS `passwd -s <username>` and the output format is:
+ # name status mm/dd/yy min max warn
+ #
+ # Fields:
+ # 1. Name: username
+ # 2. Status:
+ # - LK: locked
+ # - NL: no login
+ # - NP: No password
+ # - PS: Password
+ # 3. Last password change
+ # 4. Minimum age
+ # 5. Maximum age
+ # 6. Warning period
+
+ output = __salt__['cmd.run_all']('passwd -s {0}'.format(name))
+ if output['retcode'] != 0:
+ return ret
+
+ fields = output['stdout'].split()
+ if len(fields) == 2:
+ # For example:
+ # root NL
+ return
+ # We have all fields:
+ # buildbot L 05/09/2013 0 99999 7
+ ret.update({
+ 'name': data.pw_name,
+ 'pwd': data.pw_dir,
+ 'lstchg': fields[2],
+ 'min': int(fields[3]),
+ 'max': int(fields[4]),
+ 'warn': int(fields[5]),
+ 'inact': '',
+ 'expire': ''
+ })
return ret
|
SmartOS joyent_<I>T<I>Z does not have `spwd`. Provide an alternative.
|
saltstack_salt
|
train
|
b5f1b35ad88749993135553c75ea868add8b6241
|
diff --git a/src/__tests__/selenium-spec.js b/src/__tests__/selenium-spec.js
index <HASH>..<HASH> 100644
--- a/src/__tests__/selenium-spec.js
+++ b/src/__tests__/selenium-spec.js
@@ -314,10 +314,10 @@ describe('Selenium', function () {
describe('interrupt', function () {
- it('should return immediately by default', function () {
+ it('should return immediately in watch mode', function () {
var Selenium = require('../lib/selenium');
- var selenium = new Selenium({port: '4444'});
+ var selenium = new Selenium({port: '4444', watch: true});
var callback = jest.genMockFunction();
@@ -330,6 +330,22 @@ describe('Selenium', function () {
});
+ it('should call kill when not in watch mode', function () {
+
+ var Selenium = require('../lib/selenium');
+ var selenium = new Selenium({port: '4444'});
+
+ var callback = jest.genMockFunction();
+
+ selenium.stop = jest.genMockFn();
+
+ selenium.interrupt(callback);
+
+ expect(selenium.stop.mock.calls.length).toBe(1);
+ expect(selenium.stop.mock.calls.length).toBe(1);
+
+ });
+
it('should call kill when --clean-selenium-server is true', function () {
var Selenium = require('../lib/selenium');
|
Fix hanging selenium in non-watch mode
|
TheBrainFamily_chimpy
|
train
|
f1206035f69065812a962a816d401ce40c7565f6
|
diff --git a/setup.py b/setup.py
index <HASH>..<HASH> 100644
--- a/setup.py
+++ b/setup.py
@@ -14,6 +14,7 @@ extras_require = {
"pytest-instafail>=0.4,<1.0",
"pytest-xdist>=1.32,<2.0",
"eth-tester[py-evm]>=0.5.0b1,<0.6",
+ "py-evm==0.4.0a4", # NOTE: temporarily pinned until we have support for py-evm 0.5.0a0+
"web3==5.12.3",
"tox>=3.15,<4.0",
"lark-parser==0.10.0",
@@ -62,7 +63,7 @@ setup(
keywords="ethereum evm smart contract language",
include_package_data=True,
packages=find_packages(exclude=("tests", "docs")),
- python_requires=">=3.6",
+ python_requires=">=3.7,<3.10",
py_modules=["vyper"],
install_requires=[
"asttokens==2.0.4",
@@ -84,7 +85,9 @@ setup(
classifiers=[
"Intended Audience :: Developers",
"License :: OSI Approved :: Apache Software License",
- "Programming Language :: Python :: 3.6",
+ "Programming Language :: Python :: 3.7",
+ "Programming Language :: Python :: 3.8",
+ "Programming Language :: Python :: 3.9",
],
data_files=[("", [hash_file_rel_path])],
)
|
chore: pin supported python distributions (#<I>)
* chore: pin supported python distributions
* chore: pin py-evm
|
ethereum_vyper
|
train
|
0366b1856489f01f1c46519dfebbda3a8676f933
|
diff --git a/lib/puppet/face/certificate.rb b/lib/puppet/face/certificate.rb
index <HASH>..<HASH> 100644
--- a/lib/puppet/face/certificate.rb
+++ b/lib/puppet/face/certificate.rb
@@ -97,9 +97,9 @@ Puppet::Indirector::Face.define(:certificate, '0.0.1') do
find = get_action(:find)
find.summary "Retrieve a certificate."
find.arguments "<host>"
+ find.render_as = :s
find.returns <<-EOT
- An x509 SSL certificate. You will usually want to render this as a
- string (--render-as s).
+ An x509 SSL certificate.
Note that this action has a side effect of caching a copy of the
certificate in Puppet's `ssldir`.
diff --git a/lib/puppet/face/certificate_request.rb b/lib/puppet/face/certificate_request.rb
index <HASH>..<HASH> 100644
--- a/lib/puppet/face/certificate_request.rb
+++ b/lib/puppet/face/certificate_request.rb
@@ -15,12 +15,10 @@ Puppet::Indirector::Face.define(:certificate_request, '0.0.1') do
find = get_action(:find)
find.summary "Retrieve a single CSR."
find.arguments "<host>"
+ find.render_as = :s
find.returns <<-EOT
A single certificate request. When used from the Ruby API, returns a
Puppet::SSL::CertificateRequest object.
-
- RENDERING ISSUES: In most cases, you will want to render this as a string
- ('--render-as s').
EOT
find.examples <<-EOT
Retrieve a single CSR from the puppet master's CA:
@@ -31,10 +29,10 @@ Puppet::Indirector::Face.define(:certificate_request, '0.0.1') do
search = get_action(:search)
search.summary "Retrieve all outstanding CSRs."
search.arguments "<dummy_text>"
- A list of certificate requests; be sure to to render this as a string
- ('--render-as s'). When used from the Ruby API, returns an array of
- Puppet::SSL::CertificateRequest objects.
+ search.render_as = :s
search.returns <<-EOT
+ A list of certificate requests. When used from the Ruby API, returns an
+ array of Puppet::SSL::CertificateRequest objects.
EOT
search.short_description <<-EOT
Retrieves all outstanding certificate signing requests. Due to a known bug,
diff --git a/lib/puppet/face/certificate_revocation_list.rb b/lib/puppet/face/certificate_revocation_list.rb
index <HASH>..<HASH> 100644
--- a/lib/puppet/face/certificate_revocation_list.rb
+++ b/lib/puppet/face/certificate_revocation_list.rb
@@ -13,12 +13,10 @@ Puppet::Indirector::Face.define(:certificate_revocation_list, '0.0.1') do
find = get_action(:find)
find.summary "Retrieve the certificate revocation list."
find.arguments "<dummy_text>"
+ find.render_as = :s
find.returns <<-EOT
The certificate revocation list. When used from the Ruby API: returns an
OpenSSL::X509::CRL object.
-
- RENDERING ISSUES: this should usually be rendered as a string
- ('--render-as s').
EOT
find.short_description <<-EOT
Retrieves the certificate revocation list. Due to a known bug, this action
|
(#<I>) Set default format for SSL-related faces.
By default, the SSL-related faces should all render a strings,
not with `Object#inspect`.
Reviewed-By: Daniel Pittman
|
puppetlabs_puppet
|
train
|
1713f935bf9c7474dc317db0637b1d7668d21b11
|
diff --git a/test/simple_i18n_test.rb b/test/simple_i18n_test.rb
index <HASH>..<HASH> 100644
--- a/test/simple_i18n_test.rb
+++ b/test/simple_i18n_test.rb
@@ -58,6 +58,17 @@ class SimpleI18nTest < MiniTest::Unit::TestCase
end
end
+ test "set friendly_id should fall back default locale when none is given" do
+ transaction do
+ journalist = I18n.with_locale(:es) do
+ Journalist.create!(:name => "Juan Fulano")
+ end
+ journalist.set_friendly_id("John Doe")
+ journalist.save!
+ assert_equal "john-doe", journalist.slug_en
+ end
+ end
+
test "should sequence localized slugs" do
transaction do
journalist = Journalist.create!(:name => "John Smith")
|
Add regression test for currently incorrect usage of i<I>n API
See issue #<I>
|
norman_friendly_id
|
train
|
1c287f118dcccbaea6385550e2c1e94969ec2618
|
diff --git a/core/Access.php b/core/Access.php
index <HASH>..<HASH> 100644
--- a/core/Access.php
+++ b/core/Access.php
@@ -170,14 +170,11 @@ class Access
$auth = StaticContainer::get(SessionAuth::class);
$auth->setTokenAuth($tokenAuth);
$result = $auth->authenticate();
- if (!$result->wasAuthenticationSuccessful()) {
- /**
- * Ensures brute force logic to be executed
- * @ignore
- * @internal
- */
- Piwik::postEvent('API.Request.authenticate.failed');
- }
+ // Note: We do not post a failed login event at this point on purpose
+ // If using the SessionAuth doesn't work, the FrontController will try to reload the Auth using
+ // the token_auth only. If that works everything is "fine" and the `force_api_session` parameter was
+ // unneeded. If that fails as well it will trigger the failed login event
+ // See FrontController::init() or Request::reloadAuthUsingTokenAuth()
Session::close();
// if not successful, we will fallback to regular auth
}
|
Do not log a failed login if a valid app token_auth is sent with the request, but force_api_session parameter is present as well (#<I>)
|
matomo-org_matomo
|
train
|
dea48da4b37f94dbeb8134cfba6295b4c86547e9
|
diff --git a/spec/cabinet/local_spec.rb b/spec/cabinet/local_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/cabinet/local_spec.rb
+++ b/spec/cabinet/local_spec.rb
@@ -1,25 +1,26 @@
require File.expand_path(File.join(File.dirname(__FILE__), '..', 'spec_helper'))
describe Cabinet::Local do
- cl = Cabinet::Local.new('/tmp')
- file_name = 'cabinet.test'
- file_content = (0...50).map{('a'..'z').to_a[rand(26)]}.join
+ before(:all) do
+ @cl = Cabinet::Local.new('/tmp')
+ @file_name = 'cabinet.test'
+ @file_content = (0...50).map{('a'..'z').to_a[rand(26)]}.join
+ end
it "should create file" do
- cl.put(file_name, file_content).should == file_content.length
+ @cl.put(@file_name, @file_content).should == @file_content.length
end
it "should confirm file exists" do
- cl.exists?(file_name).should == true
+ @cl.exists?(@file_name).should == true
end
it "should confirm file does not exist" do
- random_string = file_content
- cl.exists?(random_string).should == false
+ @cl.exists?(@file_content).should == false
end
it "should read file" do
- cl.get(file_name).should == file_content
+ @cl.get(@file_name).should == @file_content
end
it "should list files" do
@@ -32,20 +33,20 @@ describe Cabinet::Local do
end
it "should gzip file" do
- gz_file_name = file_name + '.gz'
- cl.gzip(gz_file_name, file_content)
- Zlib::GzipReader.open("/tmp/#{gz_file_name}") {|gz| gz.read}.should == file_content
- cl.delete(gz_file_name)
+ gz_file_name = @file_name + '.gz'
+ @cl.gzip(gz_file_name, @file_content)
+ Zlib::GzipReader.open("/tmp/#{gz_file_name}") {|gz| gz.read}.should == @file_content
+ @cl.delete(gz_file_name)
end
it "should delete file" do
- cl.delete(file_name)
- cl.exists?(file_name).should == false
+ @cl.delete(@file_name)
+ @cl.exists?(@file_name).should == false
end
it "should bulk delete files" do
- (1..3).each {|n|cl.put("#{file_name}.#{n}", file_content)}
- cl.delete("#{file_name}*")
- (1..3).inject([]) {|arr, n| arr << cl.exists?("#{file_name}.#{n}")}.should == [false, false, false]
+ (1..3).each {|n| @cl.put("#{@file_name}.#{n}", @file_content)}
+ @cl.delete("#{@file_name}*")
+ (1..3).inject([]) {|arr, n| arr << @cl.exists?("#{@file_name}.#{n}")}.should == [false, false, false]
end
end
\ No newline at end of file
|
Add instance variables to before(:all)
|
vonconrad_cabinet
|
train
|
c70f04bbbafa9da050501383d2ffb1310a8a286c
|
diff --git a/lib/specinfra/command/darwin/base/package.rb b/lib/specinfra/command/darwin/base/package.rb
index <HASH>..<HASH> 100644
--- a/lib/specinfra/command/darwin/base/package.rb
+++ b/lib/specinfra/command/darwin/base/package.rb
@@ -1,7 +1,7 @@
class Specinfra::Command::Darwin::Base::Package < Specinfra::Command::Base::Package
class << self
def check_is_installed(package, version=nil)
- escaped_package = escape(File.basename(package))
+ escaped_package = escape(::File.basename(package))
if version
cmd = %Q[brew info #{escaped_package} | grep -E "^$(brew --prefix)/Cellar/#{escaped_package}/#{escape(version)}"]
else
@@ -13,7 +13,7 @@ class Specinfra::Command::Darwin::Base::Package < Specinfra::Command::Base::Pack
alias :check_is_installed_by_homebrew :check_is_installed
def check_is_installed_by_homebrew_cask(package, version=nil)
- escaped_package = escape(File.basename(package))
+ escaped_package = escape(::File.basename(package))
if version
cmd = "brew cask info #{escaped_package} | grep -E '^/opt/homebrew-cask/Caskroom/#{escaped_package}/#{escape(version)}'"
else
|
Resolve namespace properly for File
resolves NoMethodError: NoMethodError: undefined method 'basename' for
Specinfra::Command::Darwin::Base::File in darwin environment
|
mizzy_specinfra
|
train
|
6222f335f3b1eb5f013bb29096cdb1fe44157c07
|
diff --git a/moto/ec2/responses/nat_gateways.py b/moto/ec2/responses/nat_gateways.py
index <HASH>..<HASH> 100644
--- a/moto/ec2/responses/nat_gateways.py
+++ b/moto/ec2/responses/nat_gateways.py
@@ -6,14 +6,14 @@ from moto.ec2.utils import filters_from_querystring
class NatGateways(BaseResponse):
def create_nat_gateway(self):
- subnet_id = self.querystring.get('SubnetId')[0]
- allocation_id = self.querystring.get('AllocationId')[0]
+ subnet_id = self._get_param('SubnetId')
+ allocation_id = self._get_param('AllocationId')
nat_gateway = self.ec2_backend.create_nat_gateway(subnet_id=subnet_id, allocation_id=allocation_id)
template = self.response_template(CREATE_NAT_GATEWAY)
return template.render(nat_gateway=nat_gateway)
def delete_nat_gateway(self):
- nat_gateway_id = self.querystring.get('NatGatewayId')[0]
+ nat_gateway_id = self._get_param('NatGatewayId')
nat_gateway = self.ec2_backend.delete_nat_gateway(nat_gateway_id)
template = self.response_template(DELETE_NAT_GATEWAY_RESPONSE)
return template.render(nat_gateway=nat_gateway)
|
Refactor NatGateways methods to use _get_param()
|
spulec_moto
|
train
|
1e8c2ee56d7f02b6f35aac6d753ea7d4a958c7c4
|
diff --git a/st.js b/st.js
index <HASH>..<HASH> 100644
--- a/st.js
+++ b/st.js
@@ -104,7 +104,7 @@ function Mount (opt) {
content: AC(c.content)
}
- this._cacheControl = opt.cache === false ? 'public'
+ this._cacheControl = opt.cache === false ? 'no-cache'
: 'public, max-age=' + c.content.maxAge / 1000
}
diff --git a/test/basic.js b/test/basic.js
index <HASH>..<HASH> 100644
--- a/test/basic.js
+++ b/test/basic.js
@@ -115,7 +115,7 @@ test('multiball!', function (t) {
t.equal(res.statusCode, 200)
var cc = 'public, max-age=600'
if (opts.cache === false)
- cc = 'public'
+ cc = 'no-cache'
t.equal(res.headers['cache-control'], cc)
if (--n === 0)
|
Fix no cache option
So far `cache-control: public` was sent, which invokes more aggressive
caching than `cache-control: max-age=<I>` that's sent on cache == true
|
isaacs_st
|
train
|
895ca7dd327aa4c5b5829306b8fd66bcc98a2a2e
|
diff --git a/docs/.vuepress/config.js b/docs/.vuepress/config.js
index <HASH>..<HASH> 100644
--- a/docs/.vuepress/config.js
+++ b/docs/.vuepress/config.js
@@ -1,7 +1,7 @@
const webpack = require('webpack')
const { version } = require('../../package.json')
module.exports = {
- base: process.env.PORTAL_VUE_DOCS_PATH || '/portal-vue/',
+ base: process.env.PORTAL_VUE_DOCS_PATH || '/portal-vue/',
title: 'Portal-Vue',
description:
"A Vue component to render your component's template anywhere in the DOM.",
@@ -67,6 +67,6 @@ module.exports = {
function genOldDocsLink() {
return this.process.env.NODE_ENV === 'production'
- ? 'https://linusborg.github.io/portal-vue/v1/index.html#/guide'
- : 'http://localhost:8080/portal-vue/v1/index.html#/guide'
+ ? 'https://linusborg.github.io/portal-vue/index.html#/guide'
+ : 'http://localhost:8080/portal-vue/index.html#/guide'
}
|
fix(docs): link to old docs
|
LinusBorg_portal-vue
|
train
|
e61890bb81be0bb37555d3912a61d9f5137783f8
|
diff --git a/lib/fakefs/file.rb b/lib/fakefs/file.rb
index <HASH>..<HASH> 100644
--- a/lib/fakefs/file.rb
+++ b/lib/fakefs/file.rb
@@ -27,8 +27,8 @@ module FakeFS
FILE_CREATION_BITMASK = RealFile::CREAT
- def absolute_path(path)
- RealFile.absolute_path(path)
+ def self.absolute_path(file)
+ RealFile.absolute_path(file)
end
def self.extname(path)
diff --git a/test/fakefs_test.rb b/test/fakefs_test.rb
index <HASH>..<HASH> 100755
--- a/test/fakefs_test.rb
+++ b/test/fakefs_test.rb
@@ -1719,6 +1719,16 @@ class FakeFSTest < Test::Unit::TestCase
end
end
+ def test_absolute_path_with_absolute_path
+ FileUtils.touch('foo')
+ assert_equal '/foo/bar', File.absolute_path('/foo/bar')
+ end
+
+ def test_absolute_path_with_relative_path
+ FileUtils.touch('foo')
+ assert_equal "#{Dir.getwd}/foo/bar", File.absolute_path('foo/bar')
+ end
+
def test_extname
assert File.extname("test.doc") == ".doc"
end
@@ -2482,19 +2492,6 @@ class FakeFSTest < Test::Unit::TestCase
assert_equal File.stat('foo').gid, 1338
end
- def test_file_instance_absolute_path_with_absolute_path
- FileUtils.touch('foo')
- file = File.new('foo')
- assert_equal file.absolute_path('/foo/bar'), '/foo/bar'
- end
-
- def test_file_instance_absolute_path_with_relative_path
- FileUtils.touch('foo')
- file = File.new('foo')
- assert file.absolute_path('foo/bar') != '/foo/bar'
- end
-
-
def test_file_umask
assert_equal File.umask, RealFile.umask
File.umask(0740)
|
Make absolute_path method a class method.
|
fakefs_fakefs
|
train
|
8b450a7d58f92d440d1a68555738727908ecc089
|
diff --git a/hcl/hclsyntax/structure.go b/hcl/hclsyntax/structure.go
index <HASH>..<HASH> 100644
--- a/hcl/hclsyntax/structure.go
+++ b/hcl/hclsyntax/structure.go
@@ -279,7 +279,11 @@ func (b *Body) JustAttributes() (hcl.Attributes, hcl.Diagnostics) {
}
func (b *Body) MissingItemRange() hcl.Range {
- return b.EndRange
+ return hcl.Range{
+ Filename: b.SrcRange.Filename,
+ Start: b.SrcRange.Start,
+ End: b.SrcRange.Start,
+ }
}
// Attributes is the collection of attribute definitions within a body.
|
hclsyntax: return the starting position of a missing attr, not the end. (#<I>)
Previously, hclsyntax MissingItemRange() function returned a zero-length
range anchored at the end of the block in question. This commit changes
that to the beginning of the block. In practice, the end of a block is
generally just a "}" and not very useful in error messages.
|
hashicorp_hcl
|
train
|
19b2300ccc072ad9950aeb9d155c59c9928b8a2d
|
diff --git a/theanets/layers.py b/theanets/layers.py
index <HASH>..<HASH> 100644
--- a/theanets/layers.py
+++ b/theanets/layers.py
@@ -377,7 +377,7 @@ class Layer(Base):
'''Set up the parameters and initial values for this layer.'''
pass
- def _log_setup(self, count):
+ def log_setup(self, count):
'''Log some information about this layer.
Parameters
@@ -446,7 +446,7 @@ class Layer(Base):
return p
raise KeyError(key)
- def _add_weights(self, name, nin=None, nout=None, mean=0, std=None):
+ def add_weights(self, name, nin=None, nout=None, mean=0, std=None):
'''Helper method to create a new weight matrix.
Parameters
@@ -477,7 +477,7 @@ class Layer(Base):
name=self._fmt(name)))
return nin * nout
- def _add_bias(self, name, nout=None, mean=0, std=1):
+ def add_bias(self, name, nout=None, mean=0, std=1):
'''Helper method to create a new bias vector.
Parameters
@@ -556,9 +556,9 @@ class Feedforward(Layer):
nins = (nins, )
count = 0
for i, nin in enumerate(nins):
- count += self._add_weights(str(i), nin)
- count += self._add_bias('b')
- self._log_setup(count)
+ count += self.add_weights(str(i), nin)
+ count += self.add_bias('b')
+ self.log_setup(count)
class Tied(Feedforward):
@@ -609,7 +609,7 @@ class Tied(Feedforward):
def setup(self):
'''Set up the parameters and initial values for this layer.'''
# this layer does not create a weight matrix!
- self._log_setup(self._add_bias('b'))
+ self.log_setup(self.add_bias('b'))
class Classifier(Feedforward):
@@ -654,7 +654,7 @@ class Recurrent(Layer):
zeros = np.zeros((batch_size, self.nout), FLOAT)
self.zeros = lambda s='h': theano.shared(zeros, name=self._fmt('{}0'.format(s)))
- def _add_weights(self, name, nin=None, nout=None, mean=0, std=None):
+ def add_weights(self, name, nin=None, nout=None, mean=0, std=None):
'''Helper method to create a new weight matrix.
Parameters
@@ -725,9 +725,9 @@ class RNN(Recurrent):
def setup(self):
'''Set up the parameters and initial values for this layer.'''
- self._log_setup(self._add_weights('xh') +
- self._add_weights('hh', self.nout) +
- self._add_bias('b'))
+ self.log_setup(self.add_weights('xh') +
+ self.add_weights('hh', self.nout) +
+ self.add_bias('b'))
def transform(self, inputs):
'''Transform the inputs for this layer into an output for the layer.
@@ -770,11 +770,11 @@ class ARRNN(Recurrent):
def setup(self):
'''Set up the parameters and initial values for this layer.'''
- self._log_setup(self._add_weights('xh') +
- self._add_weights('xr') +
- self._add_weights('hh', self.nout) +
- self._add_bias('b') +
- self._add_bias('r', std=3))
+ self.log_setup(self.add_weights('xh') +
+ self.add_weights('xr') +
+ self.add_weights('hh', self.nout) +
+ self.add_bias('b') +
+ self.add_bias('r', std=3))
def transform(self, inputs):
'''Transform the inputs for this layer into an output for the layer.
@@ -819,12 +819,12 @@ class MRNN(Recurrent):
def setup(self):
'''Set up the parameters and initial values for this layer.'''
- self._log_setup(
- self._add_weights('xh', self.nin, self.nout) +
- self._add_weights('xf', self.nin, self.factors) +
- self._add_weights('hf', self.nout, self.factors) +
- self._add_weights('fh', self.factors, self.nout) +
- self._add_bias('b'))
+ self.log_setup(
+ self.add_weights('xh', self.nin, self.nout) +
+ self.add_weights('xf', self.nin, self.factors) +
+ self.add_weights('hf', self.nout, self.factors) +
+ self.add_weights('fh', self.factors, self.nout) +
+ self.add_bias('b'))
def transform(self, inputs):
'''Transform the inputs for this layer into an output for the layer.
@@ -864,14 +864,14 @@ class LSTM(Recurrent):
def setup(self):
'''Set up the parameters and initial values for this layer.'''
- self._log_setup(
- self._add_weights('xh', self.nin, 4 * self.nout) +
- self._add_weights('hh', self.nout, 4 * self.nout) +
- self._add_bias('b', 4 * self.nout, mean=3) +
+ self.log_setup(
+ self.add_weights('xh', self.nin, 4 * self.nout) +
+ self.add_weights('hh', self.nout, 4 * self.nout) +
+ self.add_bias('b', 4 * self.nout, mean=3) +
# the three "peephole" weight matrices are always diagonal.
- self._add_bias('ci', self.nout) +
- self._add_bias('cf', self.nout) +
- self._add_bias('co', self.nout))
+ self.add_bias('ci', self.nout) +
+ self.add_bias('cf', self.nout) +
+ self.add_bias('co', self.nout))
def transform(self, inputs):
'''Transform the inputs for this layer into an output for the layer.
|
Make log_setup and add_weights/bias public.
|
lmjohns3_theanets
|
train
|
2075cbaa8efd631bb1a6a6662d6c039cc12f0088
|
diff --git a/salt/client/ssh/__init__.py b/salt/client/ssh/__init__.py
index <HASH>..<HASH> 100644
--- a/salt/client/ssh/__init__.py
+++ b/salt/client/ssh/__init__.py
@@ -833,10 +833,7 @@ class Single(object):
self.opts = opts
self.tty = tty
- if kwargs.get('wipe'):
- self.wipe = 'False'
- else:
- self.wipe = 'True' if self.opts.get('ssh_wipe') else 'False'
+ self.wipe = self.opts.get('ssh_wipe')
if kwargs.get('thin_dir'):
self.thin_dir = kwargs['thin_dir']
elif self.winrm:
|
Bugfix: get a proper option for CLI and opts of wiping the tmp
|
saltstack_salt
|
train
|
a16270a6e0bb23dbe6de1513585159a1821accbf
|
diff --git a/features/support/hooks.js b/features/support/hooks.js
index <HASH>..<HASH> 100644
--- a/features/support/hooks.js
+++ b/features/support/hooks.js
@@ -40,6 +40,20 @@ Before(async function ({ gherkinDocument, pickle }) {
}
`
);
+
+ await fs.mkdir(path.join(this.tmpDir, "node_modules", "@badeball"), {
+ recursive: true,
+ });
+
+ await fs.symlink(
+ projectPath,
+ path.join(
+ this.tmpDir,
+ "node_modules",
+ "@badeball",
+ "cypress-cucumber-preprocessor"
+ )
+ );
});
After(function () {
|
Symlink library in integration tests
The integration tests previously required the user to npm-link
themselves, but this sucks as you have to do it after every install.
Furthermore, the tests don't fail with a useful message if forgotten,
unless you also run with DEBUG.
Hence, this makes development easier.
|
TheBrainFamily_cypress-cucumber-preprocessor
|
train
|
2264d0fbf93b29670b267627e691bffc4647f549
|
diff --git a/src/api/v4/dataview/time-series/index.js b/src/api/v4/dataview/time-series/index.js
index <HASH>..<HASH> 100644
--- a/src/api/v4/dataview/time-series/index.js
+++ b/src/api/v4/dataview/time-series/index.js
@@ -182,11 +182,13 @@ TimeSeries.prototype._createInternalModel = function (engine) {
offset: this._offset,
localTimezone: this._localTimezone,
sync_on_bbox_change: !!this._boundingBoxFilter,
+ sync_on_circle_change: !!this._circleFilter,
enabled: this._enabled,
column_type: 'date'
}, {
engine: engine,
- bboxFilter: this._boundingBoxFilter && this._boundingBoxFilter.$getInternalModel()
+ bboxFilter: this._boundingBoxFilter && this._boundingBoxFilter.$getInternalModel(),
+ circleFilter: this._circleFilter && this._circleFilter.$getInternalModel()
});
};
diff --git a/test/spec/api/v4/dataview/time-series.spec.js b/test/spec/api/v4/dataview/time-series.spec.js
index <HASH>..<HASH> 100644
--- a/test/spec/api/v4/dataview/time-series.spec.js
+++ b/test/spec/api/v4/dataview/time-series.spec.js
@@ -325,12 +325,10 @@ describe('api/v4/dataview/time-series', function () {
});
it('creates the internal model', function () {
- var filter = new carto.filter.BoundingBox();
dataview.disable(); // To test that it passes the ._enabled property to the internal model
dataview.setAggregation(carto.dataview.timeAggregation.WEEK);
dataview.setOffset(6);
dataview.useLocalTimezone(true);
- dataview.addFilter(filter);
dataview.$setEngine(engine);
var internalModel = dataview.$getInternalModel();
@@ -340,19 +338,9 @@ describe('api/v4/dataview/time-series', function () {
expect(internalModel.get('localTimezone')).toBe(true);
expect(internalModel.get('offset')).toBe(6 * 3600);
expect(internalModel.isEnabled()).toBe(false);
- expect(internalModel._bboxFilter).toBeDefined();
- expect(internalModel.syncsOnBoundingBoxChanges()).toBe(true);
expect(internalModel._engine).toBe(engine);
});
- it('creates the internal model with no bounding box if not provided', function () {
- dataview.$setEngine(engine);
-
- var internalModel = dataview.$getInternalModel();
- expect(internalModel._bboxFilter).not.toBeDefined();
- expect(internalModel.syncsOnBoundingBoxChanges()).toBe(false);
- });
-
it('calling twice to $setEngine does not create another internalModel', function () {
spyOn(dataview, '_createInternalModel').and.callThrough();
@@ -361,5 +349,55 @@ describe('api/v4/dataview/time-series', function () {
expect(dataview._createInternalModel.calls.count()).toBe(1);
});
+
+ describe('spatial filters', function () {
+ it('creates the internal model with BoundingBox filter if provided', function () {
+ var filter = new carto.filter.BoundingBox();
+ dataview.addFilter(filter);
+ dataview.$setEngine(engine);
+
+ var internalModel = dataview.$getInternalModel();
+ expect(internalModel._bboxFilter).toBeDefined();
+ expect(internalModel.syncsOnBoundingBoxChanges()).toBe(true);
+ });
+
+ it('allows removing a BoundingBox filter', function () {
+ var filter = new carto.filter.BoundingBox();
+ dataview.addFilter(filter);
+ dataview.$setEngine(engine);
+ expect(dataview.hasFilter(filter)).toBe(true);
+
+ dataview.removeFilter(filter);
+
+ expect(dataview.hasFilter(filter)).toBe(false);
+ var internalModel = dataview.$getInternalModel();
+ expect(internalModel._bboxFilter).toBeNull();
+ expect(internalModel.syncsOnBoundingBoxChanges()).toBe(false);
+ });
+
+ it('creates the internal model with Circle filter if provided', function () {
+ var filter = new carto.filter.Circle();
+ dataview.addFilter(filter);
+ dataview.$setEngine(engine);
+
+ var internalModel = dataview.$getInternalModel();
+ expect(internalModel._circleFilter).toBeDefined();
+ expect(internalModel.syncsOnCircleChanges()).toBe(true);
+ });
+
+ it('allows removing a Circle filter', function () {
+ var filter = new carto.filter.Circle();
+ dataview.addFilter(filter);
+ dataview.$setEngine(engine);
+ expect(dataview.hasFilter(filter)).toBe(true);
+
+ dataview.removeFilter(filter);
+
+ expect(dataview.hasFilter(filter)).toBe(false);
+ var internalModel = dataview.$getInternalModel();
+ expect(internalModel._circleFilter).toBeNull();
+ expect(internalModel.syncsOnCircleChanges()).toBe(false);
+ });
+ });
});
});
|
Add circle filter to timeseries dataview
|
CartoDB_carto.js
|
train
|
81afb6163f1f3159da3f19ac4684f77ca45b8edd
|
diff --git a/tests/test_webapp_page_agents.py b/tests/test_webapp_page_agents.py
index <HASH>..<HASH> 100644
--- a/tests/test_webapp_page_agents.py
+++ b/tests/test_webapp_page_agents.py
@@ -18,7 +18,7 @@ class TestWebAppPageAgent(unittest.TestCase):
def test_01_get_list_of_files(self):
res = page_agents.get_page()
self.assertEqual(len(res) > 40, True)
- self.assertEqual(res[0:35], '\n<TABLE border=1 valign=top width=8')
+ self.assertEqual(res[0:39], '\n<BR><TABLE border=1 valign=top width=8')
if __name__ == '__main__':
|
fix test for additional <BR>
|
acutesoftware_AIKIF
|
train
|
1bc230f6620e987bf38fcab9027f0438233b0f30
|
diff --git a/test/unit/core.js b/test/unit/core.js
index <HASH>..<HASH> 100644
--- a/test/unit/core.js
+++ b/test/unit/core.js
@@ -51,6 +51,7 @@ $(function() {
deepEqual(empty.powerTip(), empty, 'original jQuery object returned for empty selector');
deepEqual(div.powerTip('show'), div, 'original jQuery object returned for show');
deepEqual(div.powerTip('hide'), div, 'original jQuery object returned for hide');
+ deepEqual(div.powerTip('toggle'), div, 'original jQuery object returned for toggle');
deepEqual(div.powerTip('resetPosition'), div, 'original jQuery object returned for resetPosition');
deepEqual(div.powerTip('destroy'), div, 'original jQuery object returned for destroy');
ok(!element.attr('title'), 'title attribute was removed');
|
Added toggle return value test.
Part of issue #<I>.
|
stevenbenner_jquery-powertip
|
train
|
1a0846fb7219094ec7901e7a8c04ad31f9b6f907
|
diff --git a/lib/config.js b/lib/config.js
index <HASH>..<HASH> 100644
--- a/lib/config.js
+++ b/lib/config.js
@@ -66,7 +66,9 @@ require('./credentials/credential_provider_chain');
* Node.js environment.
* * **timeout** [Integer] — The number of milliseconds to wait before
* giving up on a connection attempt. Defaults to no timeout.
- *
+ * * **xhrAsync** [Boolean] — Whether the SDK will send asynchronous
+ * HTTP requests. Used in the browser environment only. Set to false to
+ * send requests synchronously. Defaults to true (async on).
* @!attribute logger
* @return [#write,#log] an object that responds to .write() (like a stream)
* or .log() (like the console object) in order to log information about
@@ -128,6 +130,9 @@ AWS.Config = AWS.util.inherit({
* Node.js environment.
* * **timeout** [Integer] — Sets the socket to timeout after timeout
* milliseconds of inactivity on the socket. Defaults to no timeout.
+ * * **xhrAsync** [Boolean] — Whether the SDK will send asynchronous
+ * HTTP requests. Used in the browser environment only. Set to false to
+ * send requests synchronously. Defaults to true (async on).
* @option options apiVersion [String, Date] a String in YYYY-MM-DD format
* (or a date) that represents the latest possible API version that can be
* used in all services (unless overridden by `apiVersions`). Specify
diff --git a/lib/http/xhr.js b/lib/http/xhr.js
index <HASH>..<HASH> 100644
--- a/lib/http/xhr.js
+++ b/lib/http/xhr.js
@@ -16,7 +16,7 @@ AWS.XHRClient = AWS.util.inherit({
}
href += httpRequest.path;
- var xhr = new XMLHttpRequest();
+ var xhr = new XMLHttpRequest(), headersEmitted = false;
httpRequest.stream = xhr;
if (httpOptions.timeout) {
@@ -28,12 +28,14 @@ AWS.XHRClient = AWS.util.inherit({
if (xhr.status === 0) return; // 0 code is invalid
} catch (e) { return; }
- if (this.readyState === this.HEADERS_RECEIVED) {
+ if (this.readyState >= this.HEADERS_RECEIVED && !headersEmitted) {
try { xhr.responseType = 'arraybuffer'; } catch (e) {}
emitter.statusCode = xhr.status;
emitter.headers = self.parseHeaders(xhr.getAllResponseHeaders());
emitter.emit('headers', emitter.statusCode, emitter.headers);
- } else if (this.readyState === this.DONE) {
+ headersEmitted = true;
+ }
+ if (this.readyState === this.DONE) {
self.finishRequest(xhr, emitter);
}
}, false);
@@ -53,7 +55,7 @@ AWS.XHRClient = AWS.util.inherit({
}, false);
callback(emitter);
- xhr.open(httpRequest.method, href, true);
+ xhr.open(httpRequest.method, href, httpOptions.xhrAsync !== false);
AWS.util.each(httpRequest.headers, function (key, value) {
if (key !== 'Content-Length' && key !== 'User-Agent' && key !== 'Host') {
xhr.setRequestHeader(key, value);
diff --git a/test/browser.spec.coffee b/test/browser.spec.coffee
index <HASH>..<HASH> 100644
--- a/test/browser.spec.coffee
+++ b/test/browser.spec.coffee
@@ -84,6 +84,16 @@ integrationTests ->
expect(httpError).toEqual(true)
expect(err.name).toEqual('NetworkingError')
+ it 'can send synchronous requests', ->
+ key = uniqueName('test')
+ opts = AWS.util.merge(config, config.s3)
+ opts.httpOptions = xhrAsync: false
+ svc = new AWS.S3(opts)
+ resp1 = svc.putObject(Key: key, Body: 'body').send()
+ resp2 = svc.getObject(Key: key).send()
+ expect(resp2.data.Body.toString()).toEqual('body')
+ svc.deleteObject(Key: key).send()
+
describe 'AWS.S3', ->
testWrite = (done, body, compareFn) ->
key = uniqueName('test')
|
Add `Config.httpOptions.xhrAsync` setting
Allows sending of synchronous HTTP requests in the browser
environment only.
|
aws_aws-sdk-js
|
train
|
cfc4f80898ec279c28f34d1ddd813234cd7cc418
|
diff --git a/lib/slideshow.rb b/lib/slideshow.rb
index <HASH>..<HASH> 100644
--- a/lib/slideshow.rb
+++ b/lib/slideshow.rb
@@ -55,7 +55,7 @@ require 'slideshow/filters/slide_filter'
module Slideshow
- VERSION = '0.9.8'
+ VERSION = '0.9.9'
# version string for generator meta tag (includes ruby version)
def Slideshow.generator
diff --git a/lib/slideshow/fetch.rb b/lib/slideshow/fetch.rb
index <HASH>..<HASH> 100644
--- a/lib/slideshow/fetch.rb
+++ b/lib/slideshow/fetch.rb
@@ -105,7 +105,7 @@ module Slideshow
# src = 'http://github.com/geraldb/sandbox/raw/13d4fec0908fbfcc456b74dfe2f88621614b5244/s5blank/s5blank.txt'
uri = URI.parse( src )
- logger.debug "host: #{uri.host}, port: #{uri.port}, path: #{uri.path}"
+ logger.debug "scheme: #{uri.scheme}, host: #{uri.host}, port: #{uri.port}, path: #{uri.path}"
dirname = File.dirname( uri.path )
basename = File.basename( uri.path, '.*' ) # e.g. fullerscreen (without extension)
@@ -114,7 +114,7 @@ module Slideshow
logger.debug "dirname: #{dirname}"
logger.debug "basename: #{basename}, filename: #{filename}"
- dlbase = "http://#{uri.host}:#{uri.port}#{dirname}"
+ dlbase = "#{uri.scheme}://#{uri.host}:#{uri.port}#{dirname}"
pkgpath = File.expand_path( "#{config_dir}/templates/#{basename}" )
logger.debug "dlpath: #{dlbase}"
|
added support for HTTPS in dlbase
|
slideshow-s9_slideshow
|
train
|
e36d2dc3de7316d4196ac263400e29ed82ef220d
|
diff --git a/src/main/java/org/jboss/netty/bootstrap/ServerBootstrap.java b/src/main/java/org/jboss/netty/bootstrap/ServerBootstrap.java
index <HASH>..<HASH> 100644
--- a/src/main/java/org/jboss/netty/bootstrap/ServerBootstrap.java
+++ b/src/main/java/org/jboss/netty/bootstrap/ServerBootstrap.java
@@ -41,7 +41,6 @@ import org.jboss.netty.channel.ChildChannelStateEvent;
import org.jboss.netty.channel.ExceptionEvent;
import org.jboss.netty.channel.ServerChannelFactory;
import org.jboss.netty.channel.SimpleChannelUpstreamHandler;
-import org.jboss.netty.channel.StaticChannelPipeline;
/**
* A helper class which creates a new server-side {@link Channel} and accepts
@@ -271,15 +270,13 @@ public class ServerBootstrap extends Bootstrap {
final BlockingQueue<ChannelFuture> futureQueue =
new LinkedBlockingQueue<ChannelFuture>();
- ChannelPipeline bossPipeline;
ChannelHandler binder = new Binder(localAddress, futureQueue);
ChannelHandler parentHandler = getParentHandler();
+
+ ChannelPipeline bossPipeline = pipeline();
+ bossPipeline.addLast("binder", binder);
if (parentHandler != null) {
- bossPipeline = pipeline();
- bossPipeline.addLast("binder", binder);
bossPipeline.addLast("userHandler", parentHandler);
- } else {
- bossPipeline = new StaticChannelPipeline(binder);
}
Channel channel = getFactory().newChannel(bossPipeline);
|
Fixed issue: NETTY-<I> (Regression NETTY-<I>: Server bootstrap bound channel pipeline has become immutable)
* ServerBootstrap now always uses the default pipeline instead of the static one
|
netty_netty
|
train
|
952298c5f5de8970964115311c4b3c9ff9a5d83a
|
diff --git a/src/RequestHeaderParser.php b/src/RequestHeaderParser.php
index <HASH>..<HASH> 100644
--- a/src/RequestHeaderParser.php
+++ b/src/RequestHeaderParser.php
@@ -63,6 +63,14 @@ class RequestHeaderParser extends EventEmitter
private function parseRequest($headers)
{
+ // additional, stricter safe-guard for request line
+ // because request parser doesn't properly cope with invalid ones
+ if (!preg_match('#^[^ ]+ [^ ]+ HTTP/\d\.\d#m', $headers)) {
+ throw new \InvalidArgumentException('Unable to parse invalid request-line');
+ }
+
+ $lines = explode("\r\n", $headers);
+
// parser does not support asterisk-form and authority-form
// remember original target and temporarily replace and re-apply below
$originalTarget = null;
diff --git a/tests/RequestHeaderParserTest.php b/tests/RequestHeaderParserTest.php
index <HASH>..<HASH> 100644
--- a/tests/RequestHeaderParserTest.php
+++ b/tests/RequestHeaderParserTest.php
@@ -176,7 +176,7 @@ class RequestHeaderParserTest extends TestCase
$this->assertSame($body, $bodyBuffer);
}
- public function testGuzzleRequestParseException()
+ public function testInvalidEmptyRequestHeadersParseException()
{
$error = null;
@@ -192,7 +192,28 @@ class RequestHeaderParserTest extends TestCase
$parser->feed("\r\n\r\n");
$this->assertInstanceOf('InvalidArgumentException', $error);
- $this->assertSame('Invalid message', $error->getMessage());
+ $this->assertSame('Unable to parse invalid request-line', $error->getMessage());
+ $this->assertSame(0, count($parser->listeners('headers')));
+ $this->assertSame(0, count($parser->listeners('error')));
+ }
+
+ public function testInvalidMalformedRequestLineParseException()
+ {
+ $error = null;
+
+ $parser = new RequestHeaderParser();
+ $parser->on('headers', $this->expectCallableNever());
+ $parser->on('error', function ($message) use (&$error) {
+ $error = $message;
+ });
+
+ $this->assertSame(1, count($parser->listeners('headers')));
+ $this->assertSame(1, count($parser->listeners('error')));
+
+ $parser->feed("GET /\r\n\r\n");
+
+ $this->assertInstanceOf('InvalidArgumentException', $error);
+ $this->assertSame('Unable to parse invalid request-line', $error->getMessage());
$this->assertSame(0, count($parser->listeners('headers')));
$this->assertSame(0, count($parser->listeners('error')));
}
|
Stricter check for invalid request-line in HTTP requests
|
reactphp_http
|
train
|
bf2d6c1c536cca1280035ca03237afbb1bf8f331
|
diff --git a/index.js b/index.js
index <HASH>..<HASH> 100644
--- a/index.js
+++ b/index.js
@@ -26,7 +26,7 @@ module.exports = function(options) {
mkdirp(dest, function(err) { if (err) throw err; });
// renaming function for the destination directory
- var renameDestDir = options.renameDestDir || function(dest, req, res) {
+ var changeDest = options.changeDest || function(dest, req, res) {
return dest;
};
@@ -87,7 +87,7 @@ module.exports = function(options) {
else { ext = ''; }
newFilename = rename(fieldname, filename.replace(ext, ''), req, res) + ext;
- newFilePath = path.join(renameDestDir(dest, req, res), newFilename);
+ newFilePath = path.join(changeDest(dest, req, res), newFilename);
var file = {
fieldname: fieldname,
diff --git a/test/functionality.js b/test/functionality.js
index <HASH>..<HASH> 100644
--- a/test/functionality.js
+++ b/test/functionality.js
@@ -108,7 +108,7 @@ describe('Functionality', function () {
var app3 = express();
app3.use(multer({
dest: './temp3',
- renameDestDir: function (dest, req, res) {
+ changeDest: function (dest, req, res) {
dest += '/user1';
if (!fs.existsSync(dest)) fs.mkdirSync(dest);
return dest;
|
lib: renameDestDir changed to changeDest
|
expressjs_multer
|
train
|
0067002db82126ec725aeabbd1dced9e3e318f01
|
diff --git a/pkg/kubelet/qos/policy_test.go b/pkg/kubelet/qos/policy_test.go
index <HASH>..<HASH> 100644
--- a/pkg/kubelet/qos/policy_test.go
+++ b/pkg/kubelet/qos/policy_test.go
@@ -109,7 +109,7 @@ var (
{
Resources: v1.ResourceRequirements{
Requests: v1.ResourceList{
- v1.ResourceName(v1.ResourceMemory): resource.MustParse(strconv.Itoa(standardMemoryAmount / 2)),
+ v1.ResourceName(v1.ResourceMemory): resource.MustParse(strconv.FormatInt(standardMemoryAmount/2, 10)),
v1.ResourceName(v1.ResourceCPU): resource.MustParse("5m"),
},
Limits: v1.ResourceList{
@@ -127,7 +127,7 @@ var (
{
Resources: v1.ResourceRequirements{
Requests: v1.ResourceList{
- v1.ResourceName(v1.ResourceMemory): resource.MustParse(strconv.Itoa(standardMemoryAmount - 1)),
+ v1.ResourceName(v1.ResourceMemory): resource.MustParse(strconv.FormatInt(standardMemoryAmount-1, 10)),
v1.ResourceName(v1.ResourceCPU): resource.MustParse("5m"),
},
},
diff --git a/pkg/volume/util/util_test.go b/pkg/volume/util/util_test.go
index <HASH>..<HASH> 100644
--- a/pkg/volume/util/util_test.go
+++ b/pkg/volume/util/util_test.go
@@ -27,6 +27,7 @@ import (
// util.go uses api.Codecs.LegacyCodec so import this package to do some
// resource initialization.
"hash/fnv"
+
_ "k8s.io/kubernetes/pkg/apis/core/install"
"k8s.io/kubernetes/pkg/apis/core/v1/helper"
"k8s.io/kubernetes/pkg/util/mount"
@@ -547,12 +548,12 @@ func createVolumeSpecWithMountOption(name string, mountOptions string, spec v1.P
return &volume.Spec{PersistentVolume: pv}
}
-func checkFnv32(t *testing.T, s string, expected int) {
+func checkFnv32(t *testing.T, s string, expected uint32) {
h := fnv.New32()
h.Write([]byte(s))
h.Sum32()
- if int(h.Sum32()) != expected {
+ if h.Sum32() != expected {
t.Fatalf("hash of %q was %v, expected %v", s, h.Sum32(), expected)
}
}
|
Make a few code paths compile cleanly with <I>-bit Go.
|
kubernetes_kubernetes
|
train
|
1ca49ef614aefde865a215b9ab64f28afd05a55f
|
diff --git a/__tests__/__snapshots__/hooks.js.snap b/__tests__/__snapshots__/hooks.js.snap
index <HASH>..<HASH> 100644
--- a/__tests__/__snapshots__/hooks.js.snap
+++ b/__tests__/__snapshots__/hooks.js.snap
@@ -303,6 +303,27 @@ Array [
]
`;
+exports[`hooks (proxy) - onDelete() when draft is a Map - delete 1`] = `
+Array [
+ Array [
+ "a",
+ ],
+ Array [
+ Object {
+ "prop": "val1",
+ },
+ ],
+]
+`;
+
+exports[`hooks (proxy) - onDelete() when draft is a Map - nested deletions 1`] = `
+Array [
+ Array [
+ "b",
+ ],
+]
+`;
+
exports[`hooks (proxy) - onDelete() when draft is an array - length = 0 1`] = `Array []`;
exports[`hooks (proxy) - onDelete() when draft is an array - pop 1`] = `
diff --git a/__tests__/hooks.js b/__tests__/hooks.js
index <HASH>..<HASH> 100644
--- a/__tests__/hooks.js
+++ b/__tests__/hooks.js
@@ -212,6 +212,40 @@ function createHookTests(useProxies) {
expectCalls(onDelete)
})
})
+
+ if (useProxies) {
+ describe("when draft is a Map -", () => {
+ test("delete", () => {
+ const key1 = {prop: "val1"}
+ const key2 = {prop: "val2"}
+ produce(new Map([["a", 0], [key1, 1], [key2, 2]]), s => {
+ s.delete("a")
+ s.delete(key1)
+ })
+ expectCalls(onDelete)
+ })
+ test("delete (no change)", () => {
+ produce(new Map(), s => {
+ s.delete("a")
+ })
+ expect(onDelete).not.toBeCalled()
+ })
+ test("nested deletions", () => {
+ const key1 = {prop: "val1"}
+ produce(
+ new Map([
+ ["a", new Map([[key1, new Map([["b", 1]])]])]
+ ]),
+ s => {
+ s.get("a")
+ .get(key1)
+ .delete("b")
+ }
+ )
+ expectCalls(onDelete)
+ })
+ })
+ }
})
describe("onCopy()", () => {
diff --git a/src/immer.js b/src/immer.js
index <HASH>..<HASH> 100644
--- a/src/immer.js
+++ b/src/immer.js
@@ -194,9 +194,9 @@ export class Immer {
// The `assigned` object is unreliable with ES5 drafts.
if (this.useProxies) {
const {assigned} = state
- for (const prop in assigned) {
- if (!assigned[prop]) this.onDelete(state, prop)
- }
+ each(assigned, (prop, assignedValue) => {
+ if (!assignedValue) this.onDelete(state, prop)
+ })
} else {
// TODO: Figure it out for Maps and Sets if we need to support ES5
const {base, copy} = state
@@ -269,7 +269,7 @@ export class Immer {
setProperty(parent, prop, value)
// Unchanged drafts are never passed to the `onAssign` hook.
- // TODO: Add tests and support for Maps and Sets
+ // TODO: Add tests and support for Sets
if (isDraftProp && value === get(state.base, prop)) return
}
// Unchanged draft properties are ignored.
diff --git a/src/proxy.js b/src/proxy.js
index <HASH>..<HASH> 100644
--- a/src/proxy.js
+++ b/src/proxy.js
@@ -215,9 +215,12 @@ const mapTraps = makeTrapsForGetters({
return state.draft
},
delete: state => key => {
- markChanged(state)
- state.assigned.set(key, false)
- return state.copy.delete(key)
+ if (source(state).has(key)) {
+ markChanged(state)
+ state.assigned.set(key, false)
+ return state.copy.delete(key)
+ }
+ return false
},
clear: state => () => {
markChanged(state)
|
feat: `onDelete` for `Maps`
|
immerjs_immer
|
train
|
f95e132555b36f1cb2a8353523e141b4c9f743fe
|
diff --git a/src/test/java/com/afrozaar/wordpress/wpapi/v2/ClientLiveTest.java b/src/test/java/com/afrozaar/wordpress/wpapi/v2/ClientLiveTest.java
index <HASH>..<HASH> 100644
--- a/src/test/java/com/afrozaar/wordpress/wpapi/v2/ClientLiveTest.java
+++ b/src/test/java/com/afrozaar/wordpress/wpapi/v2/ClientLiveTest.java
@@ -75,7 +75,7 @@ public class ClientLiveTest {
public void searchWithFilterParametersForInvalidAuthor_shouldReturnEmptyList() {
// given
- SearchRequest search = SearchRequest.Builder.aSearchRequest().withParam("filter[author]", "999").build();
+ SearchRequest<Post> search = SearchRequest.Builder.<Post>aSearchRequest().withParam("filter[author]", "999").build();
// when
final PagedResponse<Post> postPagedResponse = client.fetchPosts(search);
@@ -87,7 +87,7 @@ public class ClientLiveTest {
@Test
public void searchWithFilterParametersForValidAuthor_shouldReturnPopulatedList() {
// given
- SearchRequest search = SearchRequest.Builder.aSearchRequest().withParam("filter[author]", "1").build();
+ SearchRequest<Post> search = SearchRequest.Builder.<Post>aSearchRequest().withParam("filter[author]", "1").build();
// when
final PagedResponse<Post> postPagedResponse = client.fetchPosts(search);
|
Add type specifiers in live test.
|
Afrozaar_wp-api-v2-client-java
|
train
|
06e2d65716308f3a4f1b0a22a45b12662af5d28d
|
diff --git a/src/main/java/io/github/lukehutch/fastclasspathscanner/FastClasspathScanner.java b/src/main/java/io/github/lukehutch/fastclasspathscanner/FastClasspathScanner.java
index <HASH>..<HASH> 100644
--- a/src/main/java/io/github/lukehutch/fastclasspathscanner/FastClasspathScanner.java
+++ b/src/main/java/io/github/lukehutch/fastclasspathscanner/FastClasspathScanner.java
@@ -54,6 +54,7 @@ import java.util.Set;
import java.util.jar.Manifest;
import java.util.regex.Pattern;
import java.util.zip.ZipEntry;
+import java.util.zip.ZipException;
import java.util.zip.ZipFile;
/**
@@ -817,7 +818,7 @@ public class FastClasspathScanner {
* Scan a file.
*/
private void scanFile(final File file, final String absolutePath, final String relativePath,
- final boolean scanTimestampsOnly) throws IOException {
+ final boolean scanTimestampsOnly) {
lastModified = Math.max(lastModified, file.lastModified());
if (!scanTimestampsOnly) {
// Match file paths against path patterns
@@ -827,6 +828,10 @@ public class FastClasspathScanner {
// If there's a match, open the file as a stream and call the match processor
try (final InputStream inputStream = new FileInputStream(file)) {
fileMatcher.processMatch(relativePath, inputStream, (int) file.length());
+ } catch (IOException e) {
+ if (verbose) {
+ Log.log(e.getMessage() + " while processing file " + file.getPath());
+ }
}
filePathMatches = true;
}
@@ -841,7 +846,7 @@ public class FastClasspathScanner {
* Scan a directory for matching file path patterns.
*/
private void scanDir(final File dir, final int ignorePrefixLen, boolean inWhitelistedPath,
- final boolean scanTimestampsOnly) throws IOException {
+ final boolean scanTimestampsOnly) {
String relativePath = (ignorePrefixLen > dir.getPath().length() ? "" : dir.getPath() //
.substring(ignorePrefixLen)) + "/";
if (File.separatorChar != '/') {
@@ -902,7 +907,7 @@ public class FastClasspathScanner {
* Scan a zipfile for matching file path patterns. (Does not recurse into zipfiles within zipfiles.)
*/
private void scanZipfile(final String zipfilePath, final ZipFile zipFile, final long zipFileLastModified,
- final boolean scanTimestampsOnly) throws IOException {
+ final boolean scanTimestampsOnly) {
if (verbose) {
Log.log("Scanning jar: " + zipfilePath);
}
@@ -957,6 +962,10 @@ public class FastClasspathScanner {
// call the match processor
try (final InputStream inputStream = zipFile.getInputStream(entry)) {
fileMatcher.processMatch(path, inputStream, (int) entry.getSize());
+ } catch (IOException e) {
+ if (verbose) {
+ Log.log(e.getMessage() + " while processing file " + entry.getName());
+ }
}
}
}
@@ -974,6 +983,12 @@ public class FastClasspathScanner {
classpathElementsSet.clear();
}
+ /** Returns true if the path ends with a JAR extension */
+ private static boolean isJar(String path) {
+ String pathLower = path.toLowerCase();
+ return pathLower.endsWith(".jar") || pathLower.endsWith(".zip") || pathLower.endsWith(".war");
+ }
+
/** Add a classpath element. */
private void addClasspathElement(String pathElement) {
if (!pathElement.isEmpty()) {
@@ -996,8 +1011,7 @@ public class FastClasspathScanner {
// If this classpath element is a jar or zipfile, look for Class-Path entries in the manifest
// file. OpenJDK scans manifest-defined classpath elements after the jar that listed them, so
// we recursively call addClasspathElement if needed each time a jar is encountered.
- String pathLower = pathElement.toLowerCase();
- if (pathLower.endsWith(".jar") || pathLower.endsWith(".zip")) {
+ if (isJar(pathElement)) {
String manifestUrlStr = "jar:file:" + pathElement + "!/META-INF/MANIFEST.MF";
try (InputStream stream = new URL(manifestUrlStr).openStream()) {
// Look for Class-Path keys within manifest files
@@ -1125,10 +1139,13 @@ public class FastClasspathScanner {
// Scan within dir path element
scanDir(pathElt, path.length() + 1, false, scanTimestampsOnly);
} else if (pathElt.isFile()) {
- final String pathLower = path.toLowerCase();
- if (pathLower.endsWith(".jar") || pathLower.endsWith(".zip")) {
+ if (isJar(path)) {
// Scan within jar/zipfile path element
- scanZipfile(path, new ZipFile(pathElt), pathElt.lastModified(), scanTimestampsOnly);
+ try {
+ ZipFile zipfile = new ZipFile(pathElt);
+ scanZipfile(path, zipfile, pathElt.lastModified(), scanTimestampsOnly);
+ } catch (IOException e) {
+ }
} else {
// File listed directly on classpath
scanFile(pathElt, path, pathElt.getName(), scanTimestampsOnly);
|
Localize IOException handling, so it doesn't interrupt the remainder of
classpath scanning
|
classgraph_classgraph
|
train
|
78cbdca13a9d39fbcbb2dae0f4247e31f468a41d
|
diff --git a/src/resolver/value.js b/src/resolver/value.js
index <HASH>..<HASH> 100644
--- a/src/resolver/value.js
+++ b/src/resolver/value.js
@@ -5,13 +5,23 @@ import Node from '../graph/node';
* is greedy and matches as much as it can. This is done by checking if the
* rest of the expression can match and then after that asking the value if
* it matches.
+ *
+ * This type of node supports a few options:
+ *
+ * *
+ * `greedy` - make the node try to match as much as possible and then work
+ * backward until it finds the smallest possible match.
+ * *
+ * `onlySingle` - make the value short circuit after it has first found a
+ * value. Useful when remotely validating values and using them in
+ * conjunction with repeating things such as options.
*/
export default class Value extends Node {
- constructor(id, value) {
+ constructor(id, options) {
super();
this.id = id;
- this.value = value;
+ this.options = options;
}
match(encounter) {
@@ -36,7 +46,7 @@ export default class Value extends Node {
}
const onMatch = match => {
- return Promise.resolve(this.value.match(valueEncounter))
+ return Promise.resolve(this.options.match(valueEncounter))
.then(() => {
if(valueEncounter._matches.length === 0) return;
@@ -51,18 +61,29 @@ export default class Value extends Node {
const match = idx => {
const len = idx - currentIndex;
- if(len === 0) return Promise.resolve();
+ if((this.options.greedy && len === 0)
+ || (! this.options.greedy && idx > tokens.length)
+ ) return Promise.resolve();
valueEncounter._adjust(currentIndex, idx);
return encounter.branchWithOnMatch(onMatch, () => encounter.next(len * 0.9, len))
.then(() => {
- if(len > 1) {
- return match(idx - 1);
+ // If request to only match to keep
+ if(this.options.onlySingle && results.length > 0) return;
+
+ if(this.options.greedy) {
+ if(len > 1) {
+ return match(idx - 1);
+ }
+ } else {
+ if(idx < tokens.length) {
+ return match(idx + 1);
+ }
}
});
};
- return match(stop)
+ return match(this.options.greedy ? stop : currentIndex + 1)
.then(() => {
for(const result of results) {
encounter.match(result);
diff --git a/test/resolver.test.js b/test/resolver.test.js
index <HASH>..<HASH> 100644
--- a/test/resolver.test.js
+++ b/test/resolver.test.js
@@ -547,6 +547,62 @@ describe('Resolver', function() {
});
});
});
+
+ describe('Single enumeration-like, greedy', function() {
+ const values = [
+ 'one',
+ 'one value',
+ 'two',
+ 'three',
+ 'four five'
+ ];
+ const resolver = new Builder(lang)
+ .value('name', {
+ greedy: true,
+
+ match: function(encounter) {
+ let text = encounter.text();
+ if(encounter.partial) {
+ for(const v of values) {
+ if(v.indexOf(text) === 0) {
+ encounter.match(v);
+ }
+ }
+ } else {
+ if(values.indexOf(text) >= 0) {
+ encounter.match(text);
+ }
+ }
+ }
+ })
+ .add('{name} end')
+ .add('{name} value end')
+ .build();
+
+ it('Match', function() {
+ return resolver.match('one value end')
+ .then(results => {
+ expect(results.matches.length).to.equal(1);
+ expect(results.best.values.name).to.equal('one');
+ });
+ });
+
+ it('No match', function() {
+ return resolver.match('four value')
+ .then(results => {
+ expect(results.matches.length).to.equal(0);
+ });
+ });
+
+ it('Partial', function() {
+ return resolver.match('one value', {
+ partial: true
+ })
+ .then(results => {
+ expect(results.matches.length).to.equal(2);
+ });
+ });
+ });
});
describe('Graph contains matching expression', function() {
|
feat(values): Custom values and any now uses non-greedy matching by default
|
aholstenson_ecolect-js
|
train
|
f3e586b21f5b261cb51a2fa3159e4ad05ba25582
|
diff --git a/modelforge/backends.py b/modelforge/backends.py
index <HASH>..<HASH> 100644
--- a/modelforge/backends.py
+++ b/modelforge/backends.py
@@ -40,3 +40,18 @@ def create_backend_noexc(log: logging.Logger, name: str=None, args: str=None):
except ValueError:
log.critical("Invalid backend arguments: %s", args)
return None
+
+
+def supply_backend(name):
+ def supply_backend_inner(func):
+ def wrapped_supply_backend(args):
+ log = logging.getLogger(name)
+ if "local" in args and args.local:
+ backend = None
+ else:
+ backend = create_backend_noexc(log, args.backend, args.args)
+ if backend is None:
+ return 1
+ return func(args, backend, log)
+ return wrapped_supply_backend
+ return supply_backend_inner
diff --git a/modelforge/dump.py b/modelforge/dump.py
index <HASH>..<HASH> 100644
--- a/modelforge/dump.py
+++ b/modelforge/dump.py
@@ -1,10 +1,13 @@
+import argparse
import logging
-from modelforge.backends import create_backend_noexc
+from modelforge.registry import supply_backend
+from modelforge.storage_backend import StorageBackend
import modelforge.models as models
-def dump_model(args):
+@supply_backend("dump")
+def dump_model(args: argparse.Namespace, backend: StorageBackend, log: logging.Logger):
"""
Prints the information about the model.
@@ -12,8 +15,4 @@ def dump_model(args):
"log_level".
:return: None
"""
- log = logging.getLogger("dump")
- backend = create_backend_noexc(log, args.backend, args.args)
- if backend is None:
- return 1
print(models.GenericModel(args.input, backend=backend))
diff --git a/modelforge/registry.py b/modelforge/registry.py
index <HASH>..<HASH> 100644
--- a/modelforge/registry.py
+++ b/modelforge/registry.py
@@ -7,20 +7,8 @@ from dateutil.parser import parse as parse_datetime
from modelforge.meta import extract_index_meta
from modelforge.model import Model
from modelforge.models import GenericModel
-from modelforge.backends import create_backend_noexc
from modelforge.storage_backend import StorageBackend
-
-
-def supply_backend(name):
- def supply_backend_inner(func):
- def wrapped_supply_backend(args):
- log = logging.getLogger(name)
- backend = create_backend_noexc(log, args.backend, args.args)
- if backend is None:
- return 1
- return func(args, backend, log)
- return wrapped_supply_backend
- return supply_backend_inner
+from modelforge.backends import supply_backend
@supply_backend("publish")
|
Move supply_backend and add local arg to use it in dump command
|
src-d_modelforge
|
train
|
31ff2570010575b4558a249c33b930f6e502dd16
|
diff --git a/client/lib/post-normalizer/rule-wait-for-images-to-load.js b/client/lib/post-normalizer/rule-wait-for-images-to-load.js
index <HASH>..<HASH> 100644
--- a/client/lib/post-normalizer/rule-wait-for-images-to-load.js
+++ b/client/lib/post-normalizer/rule-wait-for-images-to-load.js
@@ -8,7 +8,6 @@ import {
forEach,
map,
pull,
- uniq
} from 'lodash';
/**
@@ -74,7 +73,7 @@ export default function waitForImagesToLoad( post ) {
resolve( post );
}
- let imagesToCheck = [];
+ const imagesToCheck = [];
if ( thumbIsLikelyImage( post.post_thumbnail ) ) {
imagesToCheck.push( post.post_thumbnail.URL );
@@ -91,9 +90,6 @@ export default function waitForImagesToLoad( post ) {
return;
}
- // dedupe the set of images
- imagesToCheck = uniq( imagesToCheck );
-
// convert to image objects to start the load process
let promises = map( imagesToCheck, promiseForURL );
diff --git a/client/lib/post-normalizer/utils.js b/client/lib/post-normalizer/utils.js
index <HASH>..<HASH> 100644
--- a/client/lib/post-normalizer/utils.js
+++ b/client/lib/post-normalizer/utils.js
@@ -168,9 +168,9 @@ export function isCandidateForCanonicalImage( image ) {
*/
export function isFeaturedImageInContent( post ) {
if ( thumbIsLikelyImage( post.post_thumbnail ) ) {
- const featuredImageUrl = url.parse( post.post_thumbnail.URL, true, true );
+ const featuredImageUrl = url.parse( post.post_thumbnail.URL );
const indexOfContentImage = findIndex( post.images, img => {
- const imgUrl = url.parse( img.src, true, true );
+ const imgUrl = url.parse( img.src );
return imgUrl.pathname === featuredImageUrl.pathname;
}, 1 ); // skip first element in post.images because it is always the featuredImage
|
Reader: fix canonical misses caused by dedupe too early (#<I>)
|
Automattic_wp-calypso
|
train
|
d8ee4e6800e9ea0796b7b355ab4214c5d9ffcfad
|
diff --git a/support/cas-server-support-oauth/src/main/java/org/apereo/cas/support/oauth/web/response/accesstoken/ext/AccessTokenPasswordGrantRequestExtractor.java b/support/cas-server-support-oauth/src/main/java/org/apereo/cas/support/oauth/web/response/accesstoken/ext/AccessTokenPasswordGrantRequestExtractor.java
index <HASH>..<HASH> 100644
--- a/support/cas-server-support-oauth/src/main/java/org/apereo/cas/support/oauth/web/response/accesstoken/ext/AccessTokenPasswordGrantRequestExtractor.java
+++ b/support/cas-server-support-oauth/src/main/java/org/apereo/cas/support/oauth/web/response/accesstoken/ext/AccessTokenPasswordGrantRequestExtractor.java
@@ -2,6 +2,8 @@ package org.apereo.cas.support.oauth.web.response.accesstoken.ext;
import org.apereo.cas.CentralAuthenticationService;
import org.apereo.cas.authentication.Authentication;
+import org.apereo.cas.authentication.AuthenticationResultBuilder;
+import org.apereo.cas.authentication.DefaultAuthenticationResult;
import org.apereo.cas.authentication.principal.Service;
import org.apereo.cas.services.RegisteredServiceAccessStrategyUtils;
import org.apereo.cas.services.ServicesManager;
@@ -12,6 +14,7 @@ import org.apereo.cas.support.oauth.authenticator.OAuth20CasAuthenticationBuilde
import org.apereo.cas.support.oauth.profile.OAuthUserProfile;
import org.apereo.cas.support.oauth.services.OAuthRegisteredService;
import org.apereo.cas.support.oauth.util.OAuth20Utils;
+import org.apereo.cas.ticket.TicketGrantingTicket;
import org.apereo.cas.ticket.registry.TicketRegistry;
import org.apereo.cas.web.support.WebUtils;
import org.pac4j.core.context.J2EContext;
@@ -62,7 +65,10 @@ public class AccessTokenPasswordGrantRequestExtractor extends BaseAccessTokenGra
LOGGER.debug("Authenticating the OAuth request indicated by [{}]", service);
final Authentication authentication = this.authenticationBuilder.build(profile.get(), registeredService, context);
RegisteredServiceAccessStrategyUtils.ensurePrincipalAccessIsAllowedForService(service, registeredService, authentication);
- return new AccessTokenRequestDataHolder(service, authentication, null, false, registeredService);
+
+ final TicketGrantingTicket ticketGrantingTicket = this.centralAuthenticationService.createTicketGrantingTicket(
+ new DefaultAuthenticationResult(authentication, service));
+ return new AccessTokenRequestDataHolder(service, authentication, registeredService, ticketGrantingTicket);
}
@Override
|
Fix oauth password grant type issue with TGTs
|
apereo_cas
|
train
|
588dbac2117b52a77d97b8209c5ec01fb967dfb5
|
diff --git a/EloquentUserProvider.php b/EloquentUserProvider.php
index <HASH>..<HASH> 100755
--- a/EloquentUserProvider.php
+++ b/EloquentUserProvider.php
@@ -68,7 +68,7 @@ class EloquentUserProvider implements UserProviderInterface {
*/
public function updateRememberToken(UserInterface $user, $token)
{
- $user->setAttribute($user->getRememberTokenName(), $token);
+ $user->setRememberToken($token);
$user->save();
}
|
Update EloquentUserProvider to use UserInterface#setRememberToken rather than Model#setAttribute directly. Closes #<I>.
|
illuminate_auth
|
train
|
507e3f113ebbc6f18947063af5f70b583c2c6b5c
|
diff --git a/signature/policy_config_test.go b/signature/policy_config_test.go
index <HASH>..<HASH> 100644
--- a/signature/policy_config_test.go
+++ b/signature/policy_config_test.go
@@ -1104,7 +1104,7 @@ func TestPRMExactReferenceUnmarshalJSON(t *testing.T) {
// Invalid "dockerReference" field
func(v mSI) { v["dockerReference"] = 1 },
},
- duplicateFields: []string{"type", "baseLayerIdentity"},
+ duplicateFields: []string{"type", "dockerReference"},
}.run(t)
}
@@ -1160,6 +1160,6 @@ func TestPRMExactRepositoryUnmarshalJSON(t *testing.T) {
// Invalid "dockerRepository" field
func(v mSI) { v["dockerRepository"] = 1 },
},
- duplicateFields: []string{"type", "baseLayerIdentity"},
+ duplicateFields: []string{"type", "dockerRepository"},
}.run(t)
}
|
Fix copy&pasted field names in duplicate field tests
|
containers_image
|
train
|
9818d96023afdc68dee254a2c225ef544156615a
|
diff --git a/lib/Client.js b/lib/Client.js
index <HASH>..<HASH> 100644
--- a/lib/Client.js
+++ b/lib/Client.js
@@ -73,7 +73,7 @@ class Client extends EventEmitter {
* @arg {Number} [options.messageLimit=100] The maximum size of a channel message cache
* @arg {Boolean} [options.opusOnly=false] Whether to suppress the node-opus not found error or not
* @arg {Boolean} [options.restMode=false] Whether to enable getting objects over REST. This should only be enabled if you are not connecting to the gateway. Bot tokens must be prefixed manually in REST mode
- * @arg {Boolean} [options.seedVoiceConnections=false] Whether to populate bot.voiceConnections with existing connections the bot account has during startup
+ * @arg {Boolean} [options.seedVoiceConnections=false] Whether to populate bot.voiceConnections with existing connections the bot account has during startup. Note that this will disconnect connections from other bot sessions
* @arg {Number} [options.sequencerWait=200] How long to wait between sending potentially ratelimited requests. This number should be at least 3/4 your ping (in milliseconds)
* @arg {Number} [options.state=true] Whether to enable state tracking. If state is false, no objects will be cached
*/
diff --git a/lib/command/Command.js b/lib/command/Command.js
index <HASH>..<HASH> 100644
--- a/lib/command/Command.js
+++ b/lib/command/Command.js
@@ -29,7 +29,8 @@ class Command {
* {
* "administrator": false,
* "manageMessages": true
- * }```
+ * }
+ * ```
* In the above example, the user must not have administrator permissions, but must have manageMessages to use the command
* @arg {Array<String>} [options.requirements.roleIDs] An array of role IDs that would allow a user to use the command
* @arg {Array<String>} [options.requirements.roleNames] An array of role names that would allow a user to use the command
diff --git a/lib/gateway/Shard.js b/lib/gateway/Shard.js
index <HASH>..<HASH> 100644
--- a/lib/gateway/Shard.js
+++ b/lib/gateway/Shard.js
@@ -424,8 +424,8 @@ class Shard extends EventEmitter {
* @prop {Object?} oldMessage.mentionedBy Object of if different things mention the bot user
* @prop {Boolean?} oldMessage.tts Whether to play the message using TTS or not
* @prop {String[]?} oldMessage.mentions Array of mentioned users' ids
- * @prop {String[]?} oldMessage.roleMentions Array of mentioned roles' ids, requires client option moreMentions
- * @prop {String[]?} oldMessage.channelMentions Array of mentions channels' ids, requires client option moreMentions
+ * @prop {String[]?} oldMessage.roleMentions Array of mentioned roles' ids.
+ * @prop {String[]?} oldMessage.channelMentions Array of mentions channels' ids.
* @prop {String?} oldMessage.cleanContent Message content with mentions replaced by names, and @everyone/@here escaped
*/
this.client.emit("messageUpdate", channel.messages.update(packet.d, this.client), oldMessage);
diff --git a/lib/structures/Permission.js b/lib/structures/Permission.js
index <HASH>..<HASH> 100644
--- a/lib/structures/Permission.js
+++ b/lib/structures/Permission.js
@@ -12,14 +12,13 @@ const Permissions = require("../Constants").Permissions;
* If a permission key is false, it is denied by the permission.
* If a permission key is true, it is allowed by the permission.
* i.e.:
-* ```
* {
* "readMessages": true,
* "sendMessages": true,
* "manageMessages": false
-* }```
+* }
* In the above example, readMessages and sendMessages are allowed permissions, and manageMessages is denied. Everything else is not explicitly set.
-* [A full list of permission nodes can be found on the docs reference page](/docs/reference#permissions)
+* [A full list of permission nodes can be found on the docs reference page](/Eris/docs/reference)
*/
class Permission extends Base {
constructor(allow, deny) {
@@ -46,7 +45,7 @@ class Permission extends Base {
/**
* Check if this permission allows a specific permission
- * @arg {String} permission The name of the permission. [A full list of permission nodes can be found on the docs reference page](/docs/reference#permissions)
+ * @arg {String} permission The name of the permission. [A full list of permission nodes can be found on the docs reference page](/Eris/docs/reference)
* @returns {Boolean} Whether the permission allows the specified permission
*/
has(permission) {
|
General Docs Fixes (#<I>)
* Permissions Docs Fixes
* Fixed old occurrences of moreMentions in docs
* Command docs code comment removal
* Update Command.js
|
abalabahaha_eris
|
train
|
c92c2217ecb0078f021fab7c9a053d9e63f12143
|
diff --git a/core/src/main/java/hudson/FilePath.java b/core/src/main/java/hudson/FilePath.java
index <HASH>..<HASH> 100644
--- a/core/src/main/java/hudson/FilePath.java
+++ b/core/src/main/java/hudson/FilePath.java
@@ -218,9 +218,12 @@ public final class FilePath implements Serializable {
this.remote = normalize(rel);
} else
if(base.isUnix()) {
- this.remote = normalize(base.remote+'/'+rel);
+ // shouldn't need this replace, but better safe than sorry
+ this.remote = normalize(base.remote+'/'+rel.replace('\\','/'));
} else {
- this.remote = normalize(base.remote+'\\'+rel);
+ // need this replace, see Slave.getWorkspaceFor and AbstractItem.getFullName, nested jobs on Windows
+ // slaves will always have a rel containing at least one '/' character. JENKINS-13649
+ this.remote = normalize(base.remote+'\\'+rel.replace('/','\\'));
}
}
|
[FIXES JENKINS-<I>] As FilePath(FilePath,String) expects multi-segment relative paths, we should ensure that the multiple segments are using the correct separator character for the remote OS
|
jenkinsci_jenkins
|
train
|
7e16b7a80f3a2896351262a02af27a60401b6a5e
|
diff --git a/ot/da.py b/ot/da.py
index <HASH>..<HASH> 100644
--- a/ot/da.py
+++ b/ot/da.py
@@ -247,7 +247,7 @@ def joint_OT_mapping_kernel(xs,xt,mu=1,eta=0.001,kerneltype='gaussian',sigma=1,b
def loss(L,G):
"""Compute full loss"""
- return np.sum((K1.dot(L)-ns*G.dot(xt))**2)+mu*np.sum(G*M)+eta*np.sum(sel(L)**2)
+ return np.sum((K1.dot(L)-ns*G.dot(xt))**2)+mu*np.sum(G*M)+eta*np.trace(L.T.dot(K0).dot(L))
def solve_L_nobias(G):
""" solve L problem with fixed G (least square)"""
@@ -450,11 +450,11 @@ class OTDA_lpl1(OTDA):
self.G=sinkhorn_lpl1_mm(ws,ys,wt,self.M,reg,eta,**kwargs)
self.computed=True
-class OTDA_mapping(OTDA):
+class OTDA_mapping_linear(OTDA):
"""Class for optimal transport with joint linear mapping estimation"""
- def __init__(self,metric='sqeuclidean'):
+ def __init__(self):
""" Class initialization"""
@@ -463,8 +463,8 @@ class OTDA_mapping(OTDA):
self.G=0
self.L=0
self.bias=False
- self.metric=metric
self.computed=False
+ self.metric='sqeuclidean'
def fit(self,xs,xt,mu=1,eta=1,bias=False,**kwargs):
""" Fit domain adaptation between samples is xs and xt (with optional
@@ -473,6 +473,7 @@ class OTDA_mapping(OTDA):
self.xt=xt
self.bias=bias
+
self.ws=unif(xs.shape[0])
self.wt=unif(xt.shape[0])
@@ -498,3 +499,42 @@ class OTDA_mapping(OTDA):
print("Warning, model not fitted yet, returning None")
return None
+class OTDA_mapping_kernel(OTDA_mapping_linear):
+ """Class for optimal transport with joint linear mapping estimation"""
+
+
+
+ def fit(self,xs,xt,mu=1,eta=1,bias=False,kerneltype='gaussian',sigma=1,**kwargs):
+ """ Fit domain adaptation between samples is xs and xt (with optional
+ weights)"""
+ self.xs=xs
+ self.xt=xt
+ self.bias=bias
+
+ self.ws=unif(xs.shape[0])
+ self.wt=unif(xt.shape[0])
+ self.kernel=kerneltype
+ self.sigma=sigma
+ self.kwargs=kwargs
+
+
+ self.G,self.L=joint_OT_mapping_kernel(xs,xt,mu=mu,eta=eta,bias=bias,**kwargs)
+ self.computed=True
+
+
+ def predict(self,x):
+ """ Out of sample mapping using the formulation from Ferradans
+
+ It basically find the source sample the nearset to the nex sample and
+ apply the difference to the displaced source sample.
+
+ """
+
+ if self.computed:
+ K=kernel(x,self.xs,method=self.kernel,sigma=self.sigma,**self.kwargs)
+ if self.bias:
+ K=np.hstack((K,np.ones((x.shape[0],1))))
+ return K.dot(self.L)
+ else:
+ print("Warning, model not fitted yet, returning None")
+ return None
\ No newline at end of file
diff --git a/ot/datasets.py b/ot/datasets.py
index <HASH>..<HASH> 100644
--- a/ot/datasets.py
+++ b/ot/datasets.py
@@ -108,9 +108,9 @@ def get_data_classif(dataset,n,nz=.5,theta=0,**kwargs):
x[y==3,:]+=2*nz*np.random.randn(sum(y==3),2)
elif dataset.lower()=='gaussrot' :
- rot=np.array([[np.cos(theta),-np.sin(theta)],[np.sin(theta),np.cos(theta)]])
- m1=np.array([-1,-1])
- m2=np.array([1,1])
+ rot=np.array([[np.cos(theta),np.sin(theta)],[-np.sin(theta),np.cos(theta)]])
+ m1=np.array([-1,1])
+ m2=np.array([1,-1])
y=np.floor((np.arange(n)*1.0/n*2))+1
n1=np.sum(y==1)
n2=np.sum(y==2)
|
add mapping estimation with kernels (still debugging)
|
rflamary_POT
|
train
|
37993da35f90e74cbb59fd11901347888e237cd3
|
diff --git a/preferencesfx-demo/src/main/java/module-info.java b/preferencesfx-demo/src/main/java/module-info.java
index <HASH>..<HASH> 100644
--- a/preferencesfx-demo/src/main/java/module-info.java
+++ b/preferencesfx-demo/src/main/java/module-info.java
@@ -6,6 +6,7 @@ module com.dlsc.preferencesfx.demo {
requires org.apache.logging.log4j.slf4j;
exports com.dlsc.preferencesfx.demo;
+ exports com.dlsc.preferencesfx.demo.visibility;
opens com.dlsc.preferencesfx.demo;
opens com.dlsc.preferencesfx.demo.extended;
diff --git a/preferencesfx/src/main/java/com/dlsc/preferencesfx/formsfx/view/renderer/PreferencesFxFormRenderer.java b/preferencesfx/src/main/java/com/dlsc/preferencesfx/formsfx/view/renderer/PreferencesFxFormRenderer.java
index <HASH>..<HASH> 100644
--- a/preferencesfx/src/main/java/com/dlsc/preferencesfx/formsfx/view/renderer/PreferencesFxFormRenderer.java
+++ b/preferencesfx/src/main/java/com/dlsc/preferencesfx/formsfx/view/renderer/PreferencesFxFormRenderer.java
@@ -59,6 +59,5 @@ public class PreferencesFxFormRenderer extends GridPane implements ViewMixin {
// Outer Padding of Category Pane
setPadding(new Insets(SPACING * 3));
setHgap(SPACING * 3);
- setVgap(SPACING * 2);
}
}
diff --git a/preferencesfx/src/main/java/com/dlsc/preferencesfx/formsfx/view/renderer/PreferencesFxGroupRenderer.java b/preferencesfx/src/main/java/com/dlsc/preferencesfx/formsfx/view/renderer/PreferencesFxGroupRenderer.java
index <HASH>..<HASH> 100644
--- a/preferencesfx/src/main/java/com/dlsc/preferencesfx/formsfx/view/renderer/PreferencesFxGroupRenderer.java
+++ b/preferencesfx/src/main/java/com/dlsc/preferencesfx/formsfx/view/renderer/PreferencesFxGroupRenderer.java
@@ -14,6 +14,8 @@ import javafx.scene.control.Label;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.Priority;
+import static com.dlsc.preferencesfx.formsfx.view.renderer.PreferencesFxFormRenderer.SPACING;
+
/**
* This class renders a group for a PreferencesFx form.
*
@@ -98,19 +100,18 @@ public class PreferencesFxGroupRenderer {
GridPane.setValignment(c.getNode(), VPos.CENTER);
GridPane.setValignment(c.getFieldLabel(), VPos.CENTER);
- // additional styling for the last setting
+ Insets margin;
if (i == elements.size() - 1) {
+ // additional styling for the last setting
styleClass.append("-last");
- GridPane.setMargin(
- c.getNode(),
- new Insets(0, 0, PreferencesFxFormRenderer.SPACING * 4, 0)
- );
- GridPane.setMargin(
- c.getFieldLabel(),
- new Insets(0, 0, PreferencesFxFormRenderer.SPACING * 4, 0)
- );
+ margin = new Insets(SPACING * 2, 0, SPACING * 4, 0);
+ } else {
+ margin = new Insets(SPACING * 2, 0, 0, 0);
}
+ GridPane.setMargin(c.getNode(), margin);
+ GridPane.setMargin(c.getFieldLabel(), margin);
+
c.getFieldLabel().getStyleClass().add(styleClass.toString() + "-label");
c.getNode().getStyleClass().add(styleClass.toString() + "-node");
}
|
Fixed issue where spacing was incorrect when elements were hidden.
|
dlemmermann_PreferencesFX
|
train
|
662e13ba362ffbd6cd955915ef46f1ccbf71de13
|
diff --git a/src/getjump/Vk/Response/Response.php b/src/getjump/Vk/Response/Response.php
index <HASH>..<HASH> 100644
--- a/src/getjump/Vk/Response/Response.php
+++ b/src/getjump/Vk/Response/Response.php
@@ -14,7 +14,7 @@ use Closure;
* Class Response
* @package getjump\Vk\Response
*/
-class Response
+class Response implements \ArrayAccess, \Countable, \Iterator
{
/**
* @var bool|array
@@ -29,6 +29,8 @@ class Response
*/
public $data = false;
+ private $pointer = 0;
+
/**
* Response constructor
* @param $data
@@ -55,6 +57,12 @@ class Response
}
}
+ // TODO: Avoid hack
+ if($this->data)
+ $this->items = &$this->data;
+ if($this->items)
+ $this->data = &$this->items;
+
if(is_object($data) && is_callable($callback))
{
$this->data = call_user_func_array($callback, [$data]);
@@ -131,4 +139,54 @@ class Response
{
return $this->data;
}
+
+ public function offsetExists($offset)
+ {
+ return isset($this->items[$offset]);
+ }
+
+ public function offsetGet($offset)
+ {
+ return $this->items[$offset];
+ }
+
+ public function offsetSet($offset, $value)
+ {
+ $this->itmes[$offset] = $value;
+ }
+
+ public function offsetUnset($offset)
+ {
+ unset($this->items[$offset]);
+ }
+
+ public function count()
+ {
+ return count($this->items);
+ }
+
+ public function rewind()
+ {
+ $this->pointer = 0;
+ }
+
+ public function current()
+ {
+ return $this->items[$this->pointer];
+ }
+
+ public function key()
+ {
+ return $this->pointer;
+ }
+
+ public function next()
+ {
+ $this->pointer++;
+ }
+
+ public function valid()
+ {
+ return isset($this[$this->pointer]);
+ }
}
|
Array Access, Iterating, Countable for Response class
|
getjump_VkApiPHP
|
train
|
9d873a20240e74265b803582ac36281e74f151e3
|
diff --git a/locator-proxy/locator-soap-proxy-service/src/main/java/org/talend/esb/locator/proxy/service/LocatorProxyServiceImpl.java b/locator-proxy/locator-soap-proxy-service/src/main/java/org/talend/esb/locator/proxy/service/LocatorProxyServiceImpl.java
index <HASH>..<HASH> 100644
--- a/locator-proxy/locator-soap-proxy-service/src/main/java/org/talend/esb/locator/proxy/service/LocatorProxyServiceImpl.java
+++ b/locator-proxy/locator-soap-proxy-service/src/main/java/org/talend/esb/locator/proxy/service/LocatorProxyServiceImpl.java
@@ -348,7 +348,7 @@ public class LocatorProxyServiceImpl implements LocatorService {
*/
private W3CEndpointReference buildEndpoint(QName serviceName, String adress) {
W3CEndpointReferenceBuilder builder = new W3CEndpointReferenceBuilder();
- builder.serviceName(serviceName);
+ //builder.serviceName(serviceName);
builder.address(adress);
return builder.build();
}
diff --git a/locator-proxy/locator-soap-proxy-service/src/main/resources/META-INF/spring/beans.xml b/locator-proxy/locator-soap-proxy-service/src/main/resources/META-INF/spring/beans.xml
index <HASH>..<HASH> 100644
--- a/locator-proxy/locator-soap-proxy-service/src/main/resources/META-INF/spring/beans.xml
+++ b/locator-proxy/locator-soap-proxy-service/src/main/resources/META-INF/spring/beans.xml
@@ -53,7 +53,7 @@
serviceName="serviceNamespace:ServiceLocatorProvider"
endpointName="serviceNamespace:ServiceLocatorProvider"
implementor="#serviceLocatorBean"
- address="/ServiceLocatorProxyService"
+ address="/ServiceLocatorService"
/>
<bean id="serviceLocatorBean"
diff --git a/locator-proxy/locator-soap-proxy-service/src/test/java/org/talend/esb/locator/proxy/service/LocatorProxyServiceTest.java b/locator-proxy/locator-soap-proxy-service/src/test/java/org/talend/esb/locator/proxy/service/LocatorProxyServiceTest.java
index <HASH>..<HASH> 100644
--- a/locator-proxy/locator-soap-proxy-service/src/test/java/org/talend/esb/locator/proxy/service/LocatorProxyServiceTest.java
+++ b/locator-proxy/locator-soap-proxy-service/src/test/java/org/talend/esb/locator/proxy/service/LocatorProxyServiceTest.java
@@ -111,7 +111,7 @@ public class LocatorProxyServiceTest extends EasyMockSupport {
W3CEndpointReference endpointRef, expectedRef;
W3CEndpointReferenceBuilder builder = new W3CEndpointReferenceBuilder();
- builder.serviceName(SERVICE_NAME);
+ //builder.serviceName(SERVICE_NAME);
builder.address(ENDPOINTURL);
expectedRef = builder.build();
@@ -142,7 +142,7 @@ public class LocatorProxyServiceTest extends EasyMockSupport {
W3CEndpointReference endpointRef, expectedRef;
W3CEndpointReferenceBuilder builder = new W3CEndpointReferenceBuilder();
- builder.serviceName(SERVICE_NAME);
+ //builder.serviceName(SERVICE_NAME);
builder.address(ENDPOINTURL);
expectedRef = builder.build();
List<W3CEndpointReference> refs;
|
- removed "proxy" word from soap proxy
|
Talend_tesb-rt-se
|
train
|
8d0fdc4c95e2b354547c1eced28834d08efa19a9
|
diff --git a/src/main/java/com/ibm/watson/developer_cloud/visual_recognition/v2_beta/VisualRecognition.java b/src/main/java/com/ibm/watson/developer_cloud/visual_recognition/v2_beta/VisualRecognition.java
index <HASH>..<HASH> 100644
--- a/src/main/java/com/ibm/watson/developer_cloud/visual_recognition/v2_beta/VisualRecognition.java
+++ b/src/main/java/com/ibm/watson/developer_cloud/visual_recognition/v2_beta/VisualRecognition.java
@@ -19,6 +19,7 @@ import java.io.FileNotFoundException;
import java.io.InputStream;
import java.lang.reflect.Type;
import java.util.List;
+import java.util.logging.Logger;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
@@ -45,12 +46,15 @@ import okhttp3.RequestBody;
* can organize image libraries, understand an individual image, and create custom classifiers for
* specific results that are tailored to your needs.
*
+ * Use visual_recognition.v3.VisualRecognition instead. The V2 service will stop at June 30th 2016.
+ *
* @version v2_beta
* @see <a href=
* "http://www.ibm.com/smarterplanet/us/en/ibmwatson/developercloud/visual-recognition.html">
* Visual Recognition</a>
* @api.version_date 2015-12-02
*/
+@Deprecated
public class VisualRecognition extends WatsonService {
private static final String CLASSIFIER_IDS = "classifier_ids";
@@ -66,6 +70,8 @@ public class VisualRecognition extends WatsonService {
private static final Type TYPE_LIST_CLASSIFIERS = new TypeToken<List<VisualClassifier>>() {}.getType();
private static final String URL = "https://gateway.watsonplatform.net/visual-recognition-beta/api";
private static final String VERBOSE = "verbose";
+
+ private static final Logger LOG = Logger.getLogger(VisualRecognition.class.getName());
/** Version date. */
public static final String VERSION_DATE_2015_12_02 = "2015-12-02";
@@ -82,6 +88,8 @@ public class VisualRecognition extends WatsonService {
super(SERVICE_NAME);
setEndPoint(URL);
this.versionDate = versionDate;
+
+ LOG.warning("VisualRecognition v2_beta will shut down at June 30th 2016. Please migrate to v3.");
}
/**
@@ -95,6 +103,8 @@ public class VisualRecognition extends WatsonService {
public VisualRecognition(String versionDate, String username, String password) {
this(versionDate);
setUsernameAndPassword(username, password);
+
+ LOG.warning("VisualRecognition v2_beta will shut down at June 30th 2016. Please migrate to v3.");
}
/**
diff --git a/src/main/java/com/ibm/watson/developer_cloud/visual_recognition/v2_beta/model/VisualClassification.java b/src/main/java/com/ibm/watson/developer_cloud/visual_recognition/v2_beta/model/VisualClassification.java
index <HASH>..<HASH> 100644
--- a/src/main/java/com/ibm/watson/developer_cloud/visual_recognition/v2_beta/model/VisualClassification.java
+++ b/src/main/java/com/ibm/watson/developer_cloud/visual_recognition/v2_beta/model/VisualClassification.java
@@ -23,8 +23,10 @@ import com.ibm.watson.developer_cloud.visual_recognition.v2_beta.VisualRecogniti
/**
* The visual classification of images used by the
* {@link VisualRecognition#classify(File, VisualClassifier...)} method.
- *
+ *
+ * Use visual_recognition.v3.VisualRecognition instead. The V2 service will stop at June 30th 2016.
*/
+@Deprecated
public class VisualClassification extends GenericModel {
/**
diff --git a/src/main/java/com/ibm/watson/developer_cloud/visual_recognition/v2_beta/model/VisualClassifier.java b/src/main/java/com/ibm/watson/developer_cloud/visual_recognition/v2_beta/model/VisualClassifier.java
index <HASH>..<HASH> 100644
--- a/src/main/java/com/ibm/watson/developer_cloud/visual_recognition/v2_beta/model/VisualClassifier.java
+++ b/src/main/java/com/ibm/watson/developer_cloud/visual_recognition/v2_beta/model/VisualClassifier.java
@@ -21,7 +21,10 @@ import com.ibm.watson.developer_cloud.visual_recognition.v2_beta.VisualRecogniti
/**
* Classifier used by the {@link VisualRecognition} V2 service.
+ *
+ * Use visual_recognition.v3.VisualRecognition instead. The V2 service will stop at June 30th 2016.
*/
+@Deprecated
public class VisualClassifier extends GenericModel {
private Date created;
|
Prepare removal of visual_recognition.v2_beta
|
watson-developer-cloud_java-sdk
|
train
|
1fe1e8997d39baa0697bee27664a3a024df3bb84
|
diff --git a/framework/core/src/Core/Search/Discussion/Gambit/AuthorGambit.php b/framework/core/src/Core/Search/Discussion/Gambit/AuthorGambit.php
index <HASH>..<HASH> 100644
--- a/framework/core/src/Core/Search/Discussion/Gambit/AuthorGambit.php
+++ b/framework/core/src/Core/Search/Discussion/Gambit/AuthorGambit.php
@@ -45,10 +45,14 @@ class AuthorGambit extends AbstractRegexGambit
throw new LogicException('This gambit can only be applied on a DiscussionSearch');
}
- $username = trim($matches[1], '"');
+ $usernames = trim($matches[1], '"');
+ $usernames = explode(',', $usernames);
- $id = $this->users->getIdForUsername($username);
+ $ids = [];
+ foreach($usernames as $username) {
+ $ids[] = $this->users->getIdForUsername($username);
+ }
- $search->getQuery()->where('start_user_id', $negate ? '!=' : '=', $id);
+ $search->getQuery()->whereIn('start_user_id', $ids, 'and', $negate);
}
}
|
#<I> Added multiple author search gambit
|
flarum_core
|
train
|
d297ee9defc61a6b9c5a79b7e64353f2d31d7958
|
diff --git a/lib/oauth2/error.rb b/lib/oauth2/error.rb
index <HASH>..<HASH> 100644
--- a/lib/oauth2/error.rb
+++ b/lib/oauth2/error.rb
@@ -27,7 +27,7 @@ module OAuth2
error_message = if opts[:error_description] && opts[:error_description].respond_to?(:encoding)
script_encoding = opts[:error_description].encoding
- response_body.encode(script_encoding)
+ response_body.encode(script_encoding, :invalid => :replace, :undef => :replace)
else
response_body
end
diff --git a/spec/oauth2/client_spec.rb b/spec/oauth2/client_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/oauth2/client_spec.rb
+++ b/spec/oauth2/client_spec.rb
@@ -9,16 +9,17 @@ describe OAuth2::Client do
subject do
OAuth2::Client.new('abc', 'def', :site => 'https://api.example.com') do |builder|
builder.adapter :test do |stub|
- stub.get('/success') { |env| [200, {'Content-Type' => 'text/awesome'}, 'yay'] }
- stub.get('/reflect') { |env| [200, {}, env[:body]] }
- stub.post('/reflect') { |env| [200, {}, env[:body]] }
- stub.get('/unauthorized') { |env| [401, {'Content-Type' => 'application/json'}, MultiJson.encode(:error => error_value, :error_description => error_description_value)] }
- stub.get('/conflict') { |env| [409, {'Content-Type' => 'text/plain'}, 'not authorized'] }
- stub.get('/redirect') { |env| [302, {'Content-Type' => 'text/plain', 'location' => '/success'}, ''] }
- stub.post('/redirect') { |env| [303, {'Content-Type' => 'text/plain', 'location' => '/reflect'}, ''] }
- stub.get('/error') { |env| [500, {'Content-Type' => 'text/plain'}, 'unknown error'] }
- stub.get('/empty_get') { |env| [204, {}, nil] }
- stub.get('/different_encoding') { |env| [500, {'Content-Type' => 'application/json'}, NKF.nkf('-We', MultiJson.encode(:error => error_value, :error_description => '∞'))] }
+ stub.get('/success') { |env| [200, {'Content-Type' => 'text/awesome'}, 'yay'] }
+ stub.get('/reflect') { |env| [200, {}, env[:body]] }
+ stub.post('/reflect') { |env| [200, {}, env[:body]] }
+ stub.get('/unauthorized') { |env| [401, {'Content-Type' => 'application/json'}, MultiJson.encode(:error => error_value, :error_description => error_description_value)] }
+ stub.get('/conflict') { |env| [409, {'Content-Type' => 'text/plain'}, 'not authorized'] }
+ stub.get('/redirect') { |env| [302, {'Content-Type' => 'text/plain', 'location' => '/success'}, ''] }
+ stub.post('/redirect') { |env| [303, {'Content-Type' => 'text/plain', 'location' => '/reflect'}, ''] }
+ stub.get('/error') { |env| [500, {'Content-Type' => 'text/plain'}, 'unknown error'] }
+ stub.get('/empty_get') { |env| [204, {}, nil] }
+ stub.get('/different_encoding') { |env| [500, {'Content-Type' => 'application/json'}, NKF.nkf('-We', MultiJson.encode(:error => error_value, :error_description => '∞'))] }
+ stub.get('/ascii_8bit_encoding') { |env| [500, {'Content-Type' => 'application/json'}, MultiJson.encode(:error => 'invalid_request', :error_description => 'é').force_encoding('ASCII-8BIT')] }
end
end
end
@@ -167,12 +168,21 @@ describe OAuth2::Client do
expect(response.error).not_to be_nil
end
- %w(/unauthorized /conflict /error /different_encoding).each do |error_path|
+ %w(/unauthorized /conflict /error /different_encoding /ascii_8bit_encoding).each do |error_path|
it "raises OAuth2::Error on error response to path #{error_path}" do
expect { subject.request(:get, error_path) }.to raise_error(OAuth2::Error)
end
end
+ it 're-encodes response body in the error message' do
+ begin
+ subject.request(:get, '/ascii_8bit_encoding')
+ rescue => ex
+ expect(ex.message.encoding.name).to eq('UTF-8')
+ expect(ex.message).to eq("invalid_request: é\n{\"error\":\"invalid_request\",\"error_description\":\"��\"}")
+ end
+ end
+
it 'parses OAuth2 standard error response' do
begin
subject.request(:get, '/unauthorized')
|
handle encoding errors more gracefully in the error class
|
oauth-xx_oauth2
|
train
|
000ba9e8aad4aff1c28551abede8dfc8cb816d5e
|
diff --git a/test/integration/command_line_sanitizing.py b/test/integration/command_line_sanitizing.py
index <HASH>..<HASH> 100755
--- a/test/integration/command_line_sanitizing.py
+++ b/test/integration/command_line_sanitizing.py
@@ -93,9 +93,8 @@ if __name__ == "__main__":
(["--active-data-extents", "-1"], exit_code_expected_on_error),
(["--active-data-extents", "5.5"], exit_code_expected_on_error),
(["--active-data-extents", "nonumber"], exit_code_expected_on_error),
- (["--flush-threshold", "-1"], exit_code_expected_on_error),
- (["--flush-threshold", "100"], exit_code_expected_on_error),
- (["--flush-threshold", "nonumber"], exit_code_expected_on_error),
+ (["--unsaved-data-limit", "-1"], exit_code_expected_on_error),
+ (["--unsaved-data-limit", "nonumber"], exit_code_expected_on_error),
(["-p", "-1"], exit_code_expected_on_error),
(["-p", "65536"], exit_code_expected_on_error),
(["-p", "string"], exit_code_expected_on_error),
|
Brought command-line sanitation test up to date.
|
rethinkdb_rethinkdb
|
train
|
3e5ede0a493b6dfb1405a8fb6eb5857dcf194949
|
diff --git a/source/test/common/test_z_gui_menu_bar.py b/source/test/common/test_z_gui_menu_bar.py
index <HASH>..<HASH> 100644
--- a/source/test/common/test_z_gui_menu_bar.py
+++ b/source/test/common/test_z_gui_menu_bar.py
@@ -300,7 +300,7 @@ def trigger_gui_signals(*args):
# wait_for_values_identical_number_state_machines(sm_manager_model, 1)
assert len(sm_manager_model.state_machines) == 1
- call_gui_callback(menubar_ctrl.on_save_as_activate, None, None, "/tmp")
+ call_gui_callback(menubar_ctrl.on_save_as_activate, None, None, testing_utils.TMP_TEST_PATH)
call_gui_callback(menubar_ctrl.on_stop_activate, None)
call_gui_callback(menubar_ctrl.on_quit_activate, None)
|
GUI menu bar test: Change tmp path to support multi-users
|
DLR-RM_RAFCON
|
train
|
3998fa5f09e9e362beea61bdd3a75d97feae9ae8
|
diff --git a/quark/db/api.py b/quark/db/api.py
index <HASH>..<HASH> 100644
--- a/quark/db/api.py
+++ b/quark/db/api.py
@@ -96,9 +96,6 @@ def _model_query(context, model, filters, fields=None):
else:
model_filters.append(model._deallocated != 1)
- if filters.get("device_id"):
- model_filters.append(models.Port.device_id.in_(filters["device_id"]))
-
if filters.get("address"):
model_filters.append(model.address == filters["address"])
@@ -119,7 +116,7 @@ def _model_query(context, model, filters, fields=None):
# This works even when a non-shared, other-tenant owned network is passed
# in because the authZ checks that happen in Neutron above us yank it back
# out of the result set.
- if "tenant_id" in filters or not context.is_admin:
+ if "tenant_id" not in filters and not context.is_admin:
filters["tenant_id"] = [context.tenant_id]
if filters.get("tenant_id"):
@@ -165,6 +162,9 @@ def port_find(context, **filters):
model_filters.append(models.Port.ip_addresses.any(
models.IPAddress.id.in_(filters["ip_address_id"])))
+ if filters.get("device_id"):
+ model_filters.append(models.Port.device_id.in_(filters["device_id"]))
+
return query.filter(*model_filters)
|
Fixed tenant_id and device_id filtering
Changes made after the network sharing busted tenant_id based filtering.
Also noticed that the model_query call was making an explicit filtering
choice on Ports for device_id, so that particular filter was moved into
the port_find method.
|
openstack_quark
|
train
|
3d9e4558cfff7f8a9383d1501364c97b7df483da
|
diff --git a/airflow/operators/python.py b/airflow/operators/python.py
index <HASH>..<HASH> 100644
--- a/airflow/operators/python.py
+++ b/airflow/operators/python.py
@@ -123,6 +123,11 @@ class PythonOperator(BaseOperator):
:param templates_exts: a list of file extensions to resolve while
processing templated fields, for examples ``['.sql', '.hql']``
:type templates_exts: list[str]
+ :param show_return_value_in_logs: a bool value whether to show return_value
+ logs. Defaults to True, which allows return value log output.
+ It can be set to False to prevent log output of return value when you return huge data
+ such as transmission a large amount of XCom to TaskAPI.
+ :type show_return_value_in_logs: bool
"""
template_fields = ('templates_dict', 'op_args', 'op_kwargs')
@@ -145,6 +150,7 @@ class PythonOperator(BaseOperator):
op_kwargs: Optional[Dict] = None,
templates_dict: Optional[Dict] = None,
templates_exts: Optional[List[str]] = None,
+ show_return_value_in_logs: bool = True,
**kwargs,
) -> None:
if kwargs.get("provide_context"):
@@ -163,6 +169,7 @@ class PythonOperator(BaseOperator):
self.templates_dict = templates_dict
if templates_exts:
self.template_ext = templates_exts
+ self.show_return_value_in_logs = show_return_value_in_logs
def execute(self, context: Dict):
context.update(self.op_kwargs)
@@ -171,7 +178,11 @@ class PythonOperator(BaseOperator):
self.op_kwargs = determine_kwargs(self.python_callable, self.op_args, context)
return_value = self.execute_callable()
- self.log.info("Done. Returned value was: %s", return_value)
+ if self.show_return_value_in_logs:
+ self.log.info("Done. Returned value was: %s", return_value)
+ else:
+ self.log.info("Done. Returned value not shown")
+
return return_value
def execute_callable(self):
diff --git a/tests/operators/test_python.py b/tests/operators/test_python.py
index <HASH>..<HASH> 100644
--- a/tests/operators/test_python.py
+++ b/tests/operators/test_python.py
@@ -314,6 +314,56 @@ class TestPythonOperator(TestPythonBase):
)
python_operator.run(start_date=DEFAULT_DATE, end_date=DEFAULT_DATE)
+ def test_return_value_log_with_show_return_value_in_logs_default(self):
+ self.dag.create_dagrun(
+ run_type=DagRunType.MANUAL,
+ execution_date=DEFAULT_DATE,
+ start_date=DEFAULT_DATE,
+ state=State.RUNNING,
+ external_trigger=False,
+ )
+
+ def func():
+ return 'test_return_value'
+
+ python_operator = PythonOperator(task_id='python_operator', python_callable=func, dag=self.dag)
+
+ with self.assertLogs('airflow.task.operators', level=logging.INFO) as cm:
+ python_operator.run(start_date=DEFAULT_DATE, end_date=DEFAULT_DATE)
+
+ assert (
+ 'INFO:airflow.task.operators:Done. Returned value was: test_return_value' in cm.output
+ ), 'Return value should be shown'
+
+ def test_return_value_log_with_show_return_value_in_logs_false(self):
+ self.dag.create_dagrun(
+ run_type=DagRunType.MANUAL,
+ execution_date=DEFAULT_DATE,
+ start_date=DEFAULT_DATE,
+ state=State.RUNNING,
+ external_trigger=False,
+ )
+
+ def func():
+ return 'test_return_value'
+
+ python_operator = PythonOperator(
+ task_id='python_operator',
+ python_callable=func,
+ dag=self.dag,
+ show_return_value_in_logs=False,
+ )
+
+ with self.assertLogs('airflow.task.operators', level=logging.INFO) as cm:
+ python_operator.run(start_date=DEFAULT_DATE, end_date=DEFAULT_DATE)
+
+ assert (
+ 'INFO:airflow.task.operators:Done. Returned value was: test_return_value' not in cm.output
+ ), 'Return value should not be shown'
+ assert (
+ 'INFO:airflow.task.operators:Done. Returned value not shown' in cm.output
+ ), 'Log message that the option is turned off should be shown'
+
class TestBranchOperator(unittest.TestCase):
@classmethod
|
Configurable logging of XCOM value in PythonOperator (#<I>)
|
apache_airflow
|
train
|
20341365c8c5d7b2790510724bc69454e9f21e10
|
diff --git a/setup.py b/setup.py
index <HASH>..<HASH> 100755
--- a/setup.py
+++ b/setup.py
@@ -284,7 +284,7 @@ except ImportError as e:
# don't use setup_requires if just checking for information
# (credit: matplotlib/setup.py)
setup_requires = []
-if '--help' not in sys.argv:
+if '--help' not in sys.argv and '--help-commands' not in sys.argv:
dist_ = Distribution({'cmdclass': cmdclass})
dist_.parse_config_files()
dist_.parse_command_line()
|
setup.py: don't add setup_requires for --help-commands
|
gwpy_gwpy
|
train
|
6bdd30c19debeafd7d3564299daef1f96d602a32
|
diff --git a/forms/gridfield/GridField.php b/forms/gridfield/GridField.php
index <HASH>..<HASH> 100644
--- a/forms/gridfield/GridField.php
+++ b/forms/gridfield/GridField.php
@@ -840,7 +840,7 @@ class GridField_FormAction extends FormAction {
'args' => $this->args,
);
- $id = preg_replace('/[^\w]+/', '_', uniqid('', true));
+ $id = md5(serialize($state));
Session::set($id, $state);
$actionData['StateID'] = $id;
|
BUG Fix gridfield storing duplicate data in session
|
silverstripe_silverstripe-framework
|
train
|
b863d3058870e773511e7e815423e169f0ea8c2f
|
diff --git a/features/support/pickle.rb b/features/support/pickle.rb
index <HASH>..<HASH> 100644
--- a/features/support/pickle.rb
+++ b/features/support/pickle.rb
@@ -20,7 +20,7 @@ module OData
# get a list of column names for a given class
def self.column_names(klass)
- klass.properties
+ klass.properties.keys
end
# Get an instance by id of the model
diff --git a/lib/ruby_odata/class_builder.rb b/lib/ruby_odata/class_builder.rb
index <HASH>..<HASH> 100644
--- a/lib/ruby_odata/class_builder.rb
+++ b/lib/ruby_odata/class_builder.rb
@@ -172,12 +172,11 @@ module OData
end
def add_class_methods(klass)
- list_of_properties = @methods.concat @nav_props
context = @context
# Retrieves a list of properties defined on a type (standard and navigation properties)
klass.send :define_singleton_method, 'properties' do
- list_of_properties
+ context.class_metadata[klass.to_s] || {}
end
# Finds a single model by ID
diff --git a/spec/service_spec.rb b/spec/service_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/service_spec.rb
+++ b/spec/service_spec.rb
@@ -503,6 +503,12 @@ module OData
Product.properties.should include 'Category'
end
+ it "should have full metadata for a property returned from the properties method" do
+ svc = OData::Service.new "http://test.com/test.svc/"
+ Product.properties['Category'].should be_a PropertyMetadata
+ Product.properties['Category'].nav_prop.should be_true
+ end
+
it "should create objects that expose an id property" do
svc = OData::Service.new "http://test.com/test.svc/"
svc.Products(1)
|
Modified properties collection to return a collection of PropertyMetadata objects instead of just a string
|
visoft_ruby_odata
|
train
|
141afddd45d29594e5e1699e54a8d817b10c660d
|
diff --git a/lib/yaml/scanner.py b/lib/yaml/scanner.py
index <HASH>..<HASH> 100644
--- a/lib/yaml/scanner.py
+++ b/lib/yaml/scanner.py
@@ -1211,7 +1211,7 @@ class Scanner:
for k in range(length):
if self.peek(k) not in '0123456789ABCDEFabcdef':
raise ScannerError("while scanning a double-quoted scalar", start_mark,
- "expected escape sequence of %d hexdecimal numbers, but found %r" %
+ "expected escape sequence of %d hexadecimal numbers, but found %r" %
(length, self.peek(k)), self.get_mark())
code = int(self.prefix(length), 16)
chunks.append(chr(code))
@@ -1403,7 +1403,7 @@ class Scanner:
for k in range(2):
if self.peek(k) not in '0123456789ABCDEFabcdef':
raise ScannerError("while scanning a %s" % name, start_mark,
- "expected URI escape sequence of 2 hexdecimal numbers, but found %r"
+ "expected URI escape sequence of 2 hexadecimal numbers, but found %r"
% self.peek(k), self.get_mark())
codes.append(int(self.prefix(2), 16))
self.forward(2)
|
Correct spelling of “hexadecimal”
|
yaml_pyyaml
|
train
|
78e313db9294ef0ca7910f64dbcaf3f1dde53588
|
diff --git a/test/ComposerRequireCheckerTest/NodeVisitor/DefinedSymbolCollectorFunctionalTest.php b/test/ComposerRequireCheckerTest/NodeVisitor/DefinedSymbolCollectorFunctionalTest.php
index <HASH>..<HASH> 100644
--- a/test/ComposerRequireCheckerTest/NodeVisitor/DefinedSymbolCollectorFunctionalTest.php
+++ b/test/ComposerRequireCheckerTest/NodeVisitor/DefinedSymbolCollectorFunctionalTest.php
@@ -55,6 +55,21 @@ final class DefinedSymbolCollectorFunctionalTest extends \PHPUnit_Framework_Test
);
}
+ public function testWillCollectFunctionDefinition()
+ {
+ $this->traverseStringAST('function foo() {}');
+
+ self::assertSameCollectedSymbols(
+ ['foo'],
+ $this->collector->getDefinedSymbols()
+ );
+ }
+
+ private function traverseStringAST(string $phpSource) : array
+ {
+ return $this->traverser->traverse($this->parser->parse('<?php ' . $phpSource));
+ }
+
private function traverseClassAST(string $className) : array
{
return $this->traverser->traverse(
|
Testing collection of defined non-namespaced functions
|
maglnet_ComposerRequireChecker
|
train
|
09fd56da70764218e27d4b37616540e93b7d212d
|
diff --git a/client/blocks/keyring-connect-button/index.js b/client/blocks/keyring-connect-button/index.js
index <HASH>..<HASH> 100644
--- a/client/blocks/keyring-connect-button/index.js
+++ b/client/blocks/keyring-connect-button/index.js
@@ -147,7 +147,11 @@ class KeyringConnectButton extends Component {
* @return {Boolean} Whether the Keyring authorization attempt succeeded
*/
didKeyringConnectionSucceed( keyringConnections ) {
- const hasAnyConnectionOptions = some( keyringConnections, { isConnected: false } );
+ const hasAnyConnectionOptions = some(
+ keyringConnections,
+ keyringConnection =>
+ keyringConnection.isConnected === false || keyringConnection.isConnected === undefined
+ );
if ( keyringConnections.length === 0 ) {
this.setState( { isConnecting: false } );
|
Fix Automatic Redirect on Google My Business Connect (#<I>)
Fix conditions on "isConnected" check of KeyringConnectButton
|
Automattic_wp-calypso
|
train
|
e7ab5a457923c905fa916983ff462f5d3e1d4d60
|
diff --git a/src/Linna/Session/Session.php b/src/Linna/Session/Session.php
index <HASH>..<HASH> 100644
--- a/src/Linna/Session/Session.php
+++ b/src/Linna/Session/Session.php
@@ -151,17 +151,20 @@ class Session
*/
public function start()
{
- //prepare session start
- $this->prepare();
+ if (session_status() !== 2)
+ {
+ //prepare session start
+ $this->prepare();
- //start session
- session_start();
-
- //set new cookie
- $this->setCookie();
+ //start session
+ session_start();
- //link session super global to $data property
- $this->data = &$_SESSION;
+ //set new cookie
+ $this->setCookie();
+
+ //link session super global to $data property
+ $this->data = &$_SESSION;
+ }
//refresh session
$this->refresh();
|
Session->start() fix
Now call session->start() more than one time don't cause a error
|
linna_framework
|
train
|
f63b08ff9b05a16a74d9d9750feb26554d4d5594
|
diff --git a/py3status/modules/mpris.py b/py3status/modules/mpris.py
index <HASH>..<HASH> 100644
--- a/py3status/modules/mpris.py
+++ b/py3status/modules/mpris.py
@@ -70,6 +70,7 @@ SERVICE_BUS = 'org.mpris.MediaPlayer2'
INTERFACE = SERVICE_BUS + '.Player'
SERVICE_BUS_URL = '/org/mpris/MediaPlayer2'
SERVICE_BUS_REGEX = '^' + re.sub(r'\.', '\.', SERVICE_BUS) + '.'
+UNKNOWN = 'Unknown'
def _get_time_str(microtime):
@@ -177,11 +178,14 @@ class Py3status:
Get the current metadatas
"""
is_video = False
- album = 'Unknown'
- artist = 'Unknown'
- state = 'Unkown'
- title = 'Unknown'
- rtime = '0'
+ album = UNKNOWN
+ artist = UNKNOWN
+ state = UNKNOWN
+ title = UNKNOWN
+ time = '0'
+ length = '0'
+ shuffle = UNKNOWN
+ loop = UNKNOWN
if self._player is None:
return (self.format_none, i3s_config['color_bad'])
|
Add unknown state for shuffle, loop and time
|
ultrabug_py3status
|
train
|
6f04e19867837d413444292f18523acd3c752bec
|
diff --git a/src/Presenters/Application/Search/SearchPanel.php b/src/Presenters/Application/Search/SearchPanel.php
index <HASH>..<HASH> 100644
--- a/src/Presenters/Application/Search/SearchPanel.php
+++ b/src/Presenters/Application/Search/SearchPanel.php
@@ -183,7 +183,7 @@ class SearchPanel extends HtmlPresenter
protected function bindEvents(Presenter $presenter)
{
- $presenter->attachEventHandler("ConfigureFilters", [$this, "OnConfigureFilters"]);
+ $presenter->attachEventHandler("GetFilter", [$this, "OnGetFilter"]);
$presenter->attachEventHandler("GetSearchControlValues", [$this, "GetSearchControlValues"]);
}
@@ -197,7 +197,7 @@ class SearchPanel extends HtmlPresenter
}
- protected function onConfigureFilters(Filter $filter = null)
+ protected function onGetFilter()
{
$group = new Group("AND");
@@ -210,18 +210,6 @@ class SearchPanel extends HtmlPresenter
return null;
}
- if ($filter === null) {
- return $group;
- }
-
- $outer = new Group("AND");
-
- $outer->addFilters
- (
- $filter,
- $group
- );
-
- return $outer;
+ return $filters;
}
}
\ No newline at end of file
diff --git a/src/Presenters/Application/Table/Table.php b/src/Presenters/Application/Table/Table.php
index <HASH>..<HASH> 100644
--- a/src/Presenters/Application/Table/Table.php
+++ b/src/Presenters/Application/Table/Table.php
@@ -368,11 +368,9 @@ class Table extends HtmlPresenter
public function configureFilters()
{
- $newFilter = $this->raiseEvent("ConfigureFilters", $this->collection->getFilter());
-
- if ($newFilter !== null && $newFilter instanceof Filter) {
- $this->collection->replaceFilter($newFilter);
- }
+ $this->raiseEvent("GetFilter", function(Filter $filter){
+ $this->collection->filter($filter);
+ });
$this->applySort();
}
diff --git a/src/Presenters/Application/Tabs/TabsPresenter.js b/src/Presenters/Application/Tabs/TabsPresenter.js
index <HASH>..<HASH> 100644
--- a/src/Presenters/Application/Tabs/TabsPresenter.js
+++ b/src/Presenters/Application/Tabs/TabsPresenter.js
@@ -14,8 +14,8 @@ tabsPresenter.prototype.attachEvents = function () {
self.raiseServerEvent("TabSelected", index);
- $('ul:first', self.element).children().removeClass('-is-selected');
- $(this).addClass('-is-selected');
+ $('ul:first', self.element).children().removeClass('selected');
+ $(this).addClass('selected');
});
};
diff --git a/src/Presenters/Application/Tabs/TabsPresenter.php b/src/Presenters/Application/Tabs/TabsPresenter.php
index <HASH>..<HASH> 100644
--- a/src/Presenters/Application/Tabs/TabsPresenter.php
+++ b/src/Presenters/Application/Tabs/TabsPresenter.php
@@ -31,11 +31,33 @@ class TabsPresenter extends HtmlPresenter
return new TabsView();
}
+ /**
+ * Override to initialise the presenter with it's model, and any other relevant settings.
+ *
+ * The view should not be instantiated or configured here however - do this in ApplyModelToView
+ */
+ protected function initialiseModel()
+ {
+ parent::initialiseModel();
+
+ $this->SelectedTab = 0;
+ }
+
+
public function setTabDefinitions($tabs = [])
{
$this->tabs = $tabs;
}
+ public function getSelectedTab()
+ {
+ if ($this->SelectedTab !== null) {
+ return $this->getTabByIndex($this->SelectedTab);
+ }
+
+ return null;
+ }
+
public function getTabDefinitions()
{
return $this->tabs;
|
Changes to how table filtering and tabs work
|
RhubarbPHP_Module.Leaf
|
train
|
e9338c24f000b944246e6d150d997428d48e1aa2
|
diff --git a/base64_test.go b/base64_test.go
index <HASH>..<HASH> 100644
--- a/base64_test.go
+++ b/base64_test.go
@@ -2,7 +2,7 @@ package enmime
import (
"bytes"
- "github.com/stretchrcom/testify/assert"
+ "github.com/stretchr/testify/assert"
"strings"
"testing"
)
diff --git a/mail_test.go b/mail_test.go
index <HASH>..<HASH> 100644
--- a/mail_test.go
+++ b/mail_test.go
@@ -4,7 +4,7 @@ import (
"bufio"
"bytes"
"fmt"
- "github.com/stretchrcom/testify/assert"
+ "github.com/stretchr/testify/assert"
"net/mail"
"os"
"path/filepath"
diff --git a/match_test.go b/match_test.go
index <HASH>..<HASH> 100644
--- a/match_test.go
+++ b/match_test.go
@@ -1,7 +1,7 @@
package enmime
import (
- "github.com/stretchrcom/testify/assert"
+ "github.com/stretchr/testify/assert"
"testing"
)
diff --git a/part_test.go b/part_test.go
index <HASH>..<HASH> 100644
--- a/part_test.go
+++ b/part_test.go
@@ -3,7 +3,7 @@ package enmime
import (
"bufio"
"fmt"
- "github.com/stretchrcom/testify/assert"
+ "github.com/stretchr/testify/assert"
"os"
"path/filepath"
"testing"
|
Update for new stretchr testify repo
|
jhillyerd_enmime
|
train
|
4fcaac6bc53c1c2094f0f25aae7363cd93b2bfa4
|
diff --git a/spec/lib/nrser/mean_streak/identity_instance_spec.rb b/spec/lib/nrser/mean_streak/identity_instance_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/lib/nrser/mean_streak/identity_instance_spec.rb
+++ b/spec/lib/nrser/mean_streak/identity_instance_spec.rb
@@ -15,7 +15,7 @@ describe_spec_file(
describe_instance do
describe_method :render do
describe_called_with "hey" do
- it { is_expected.to eq "heyy" }
+ it { is_expected.to eq "hey" }
end # called with "hey"
end
end
|
Looks like I was fiddling with a MeanStreak spec, fix it. Specs passing
|
nrser_nrser.rb
|
train
|
cd14d85f3ce3ff0f7dd66739fac60007bf1d22d4
|
diff --git a/tasks/deploy/fetch.js b/tasks/deploy/fetch.js
index <HASH>..<HASH> 100644
--- a/tasks/deploy/fetch.js
+++ b/tasks/deploy/fetch.js
@@ -36,12 +36,21 @@ module.exports = function (grunt) {
*/
function createWorkspace(cb) {
- grunt.log.writeln('Create workspace "%s"', grunt.shipit.config.workspace);
- mkdirp(grunt.shipit.config.workspace, function (err) {
- if (err) return cb(err);
- grunt.log.oklns('Workspace created.');
- cb();
- });
+ function createWorkspace() {
+ grunt.log.writeln('Create workspace "%s"', grunt.shipit.config.workspace);
+ mkdirp(grunt.shipit.config.workspace, function (err) {
+ if (err) return cb(err);
+ grunt.log.oklns('Workspace created.');
+ cb();
+ });
+ }
+
+ if (grunt.shipit.config.shallowClone) {
+ grunt.log.writeln('Deleting existing workspace "%s"', grunt.shipit.config.workspace);
+ grunt.shipit.local('rm -rf ' + grunt.shipit.config.workspace, createWorkspace);
+ } else {
+ createWorkspace();
+ }
}
/**
diff --git a/test/unit/tasks/deploy/fetch.js b/test/unit/tasks/deploy/fetch.js
index <HASH>..<HASH> 100644
--- a/test/unit/tasks/deploy/fetch.js
+++ b/test/unit/tasks/deploy/fetch.js
@@ -66,6 +66,7 @@ describe('deploy:fetch task', function () {
runTask('deploy:fetch', function (err) {
if (err) return done(err);
+ expect(grunt.shipit.local).to.be.calledWith('rm -rf /tmp/workspace');
expect(mkdirpMock).to.be.calledWith('/tmp/workspace');
expect(grunt.shipit.local).to.be.calledWith('git init', {cwd: '/tmp/workspace'});
expect(grunt.shipit.local).to.be.calledWith('git remote', {cwd: '/tmp/workspace'});
|
there is not enough data in git history to do a merge when using shallow clone; deleting workspace before init
|
shipitjs_grunt-shipit
|
train
|
a9126a0b5742a9a76ac515753d426be406eae5f4
|
diff --git a/lib/halite/spec_helper/patcher.rb b/lib/halite/spec_helper/patcher.rb
index <HASH>..<HASH> 100644
--- a/lib/halite/spec_helper/patcher.rb
+++ b/lib/halite/spec_helper/patcher.rb
@@ -15,6 +15,7 @@
#
require 'chef/resource'
+require 'chef/version'
module Halite
@@ -25,6 +26,9 @@ module Halite
# @since 1.0.0
# @api private
module Patcher
+ # Flag to disable module-name patching.
+ DISABLE_PATCH_MODULE = ::Gem::Requirement.create('> 12').satisfied_by?(::Gem::Version.create(Chef::VERSION))
+
# Patch a class in to Chef for the duration of a block.
#
# @param name [String, Symbol] Name to create in snake-case (eg. :my_name).
@@ -90,6 +94,7 @@ module Halite
# @param block [Proc] Block to execute while the name is available.
# @return [void]
def self.patch_module(mod, name, obj, &block)
+ return block.call if DISABLE_PATCH_MODULE
class_name = Chef::Mixin::ConvertToClassName.convert_to_class_name(name.to_s)
if mod.const_defined?(class_name, false)
old_class = mod.const_get(class_name, false)
|
Disable module name patching in Chef <I> since this is going away in core.
|
poise_halite
|
train
|
d928954fc4619113ccbdea7519115d3043679a5f
|
diff --git a/src/python/dxpy/bindings/dxfile_functions.py b/src/python/dxpy/bindings/dxfile_functions.py
index <HASH>..<HASH> 100644
--- a/src/python/dxpy/bindings/dxfile_functions.py
+++ b/src/python/dxpy/bindings/dxfile_functions.py
@@ -27,6 +27,7 @@ from __future__ import print_function, unicode_literals, division, absolute_impo
import os, sys, math, mmap, stat
import hashlib
import traceback
+import warnings
from collections import defaultdict
from multiprocessing import cpu_count
from concurrent.futures import ThreadPoolExecutor
@@ -223,7 +224,9 @@ def download_dxfile(dxid, filename, chunksize=dxfile.DEFAULT_BUFFER_SIZE, append
msg = "Unexpected part data size in {} part {} (expected {}, got {})"
msg = msg.format(dxfile.get_id(), part_id, parts[part_id]["size"], got_bytes)
raise DXPartLengthMismatchError(msg)
- if hasher is not None and "md5" in parts[part_id] and hasher.hexdigest() != parts[part_id]["md5"]:
+ if hasher is not None and "md5" not in parts[part_id]:
+ warnings.warn("Download of file {} is not being checked for integrity".format(dxfile.get_id()))
+ elif hasher is not None and hasher.hexdigest() != parts[part_id]["md5"]:
msg = "Checksum mismatch in {} part {} (expected {}, got {})"
msg = msg.format(dxfile.get_id(), part_id, parts[part_id]["md5"], hasher.hexdigest())
raise DXChecksumMismatchError(msg)
|
dx download: warn when unable to checksum part with missing MD5
|
dnanexus_dx-toolkit
|
train
|
70cb3fab2cf658a95f2ccae5bfb2f0ccbba0c548
|
diff --git a/cmd_server.go b/cmd_server.go
index <HASH>..<HASH> 100644
--- a/cmd_server.go
+++ b/cmd_server.go
@@ -3,6 +3,8 @@
package miniredis
import (
+ "strings"
+
"github.com/alicebob/miniredis/server"
)
@@ -32,11 +34,15 @@ func (m *Miniredis) cmdDbsize(c *server.Peer, cmd string, args []string) {
// FLUSHALL
func (m *Miniredis) cmdFlushall(c *server.Peer, cmd string, args []string) {
+ if len(args) > 0 && strings.ToLower(args[0]) == "async" {
+ args = args[1:]
+ }
if len(args) > 0 {
setDirty(c)
- c.WriteError(errWrongNumber(cmd))
+ c.WriteError(msgSyntaxError)
return
}
+
if !m.handleAuth(c) {
return
}
@@ -49,11 +55,15 @@ func (m *Miniredis) cmdFlushall(c *server.Peer, cmd string, args []string) {
// FLUSHDB
func (m *Miniredis) cmdFlushdb(c *server.Peer, cmd string, args []string) {
+ if len(args) > 0 && strings.ToLower(args[0]) == "async" {
+ args = args[1:]
+ }
if len(args) > 0 {
setDirty(c)
- c.WriteError(errWrongNumber(cmd))
+ c.WriteError(msgSyntaxError)
return
}
+
if !m.handleAuth(c) {
return
}
diff --git a/cmd_server_test.go b/cmd_server_test.go
index <HASH>..<HASH> 100644
--- a/cmd_server_test.go
+++ b/cmd_server_test.go
@@ -59,13 +59,32 @@ func TestCmdServer(t *testing.T) {
}
{
+ b, err := redis.String(c.Do("FLUSHDB", "ASYNC"))
+ ok(t, err)
+ equals(t, "OK", b)
+
+ b, err = redis.String(c.Do("FLUSHALL", "ASYNC"))
+ ok(t, err)
+ equals(t, "OK", b)
+ }
+
+ {
_, err := redis.Int(c.Do("DBSIZE", "FOO"))
assert(t, err != nil, "no DBSIZE error")
_, err = redis.Int(c.Do("FLUSHDB", "FOO"))
assert(t, err != nil, "no FLUSHDB error")
+ _, err = redis.Int(c.Do("FLUSHDB", "ASYNC", "FOO"))
+ assert(t, err != nil, "no FLUSHDB error")
+
_, err = redis.Int(c.Do("FLUSHALL", "FOO"))
assert(t, err != nil, "no FLUSHALL error")
+
+ _, err = redis.Int(c.Do("FLUSHALL", "ASYNC", "FOO"))
+ assert(t, err != nil, "no FLUSHALL error")
+
+ _, err = redis.Int(c.Do("FLUSHALL", "ASYNC", "ASYNC"))
+ assert(t, err != nil, "no FLUSHALL error")
}
}
|
FLUSHDB and FLUSHALL can have ASYNC argument in <I>
|
alicebob_miniredis
|
train
|
6e5b1ff1cb2ad26b651c98ab77e5574b783f534a
|
diff --git a/pipes/pipeline/create_pipeline.py b/pipes/pipeline/create_pipeline.py
index <HASH>..<HASH> 100644
--- a/pipes/pipeline/create_pipeline.py
+++ b/pipes/pipeline/create_pipeline.py
@@ -239,8 +239,10 @@ def main():
parser = argparse.ArgumentParser()
parser.add_argument('-d',
'--debug',
- action='store_true',
- help='DEBUG output')
+ action='store_const',
+ const=logging.DEBUG,
+ default=logging.INFO,
+ help='Set DEBUG output')
parser.add_argument("--app",
help="The application name to create",
required=True)
@@ -255,8 +257,8 @@ def main():
required=True)
args = parser.parse_args()
- if args.debug:
- log.setLevel(logging.DEBUG)
+ log.setLevel(args.debug)
+ logging.getLogger(__package__).setLevel(args.debug)
log.debug('Parsed arguments: %s', args)
|
fix: Log INFO by default
See also: PSOBAT-<I>
|
foremast_foremast
|
train
|
c6f2af347b1bac32bbc59ece45c3bd63b0b08402
|
diff --git a/sphinxgallery/docs_resolv.py b/sphinxgallery/docs_resolv.py
index <HASH>..<HASH> 100644
--- a/sphinxgallery/docs_resolv.py
+++ b/sphinxgallery/docs_resolv.py
@@ -409,17 +409,19 @@ def embed_code_links(app, exception):
"""Embed hyperlinks to documentation into example code"""
if exception is not None:
return
+
# No need to waste time embedding hyperlinks when not running the examples
# XXX: also at the time of writing this fixes make html-noplot
# for some reason I don't fully understand
if not app.builder.config.plot_gallery:
return
- print('Embedding documentation hyperlinks in examples..')
+ # Don't embed hyperlinks when a latex builder is used.
if app.builder.name == 'latex':
- # Don't embed hyperlinks when a latex builder is used.
return
+ print('Embedding documentation hyperlinks in examples..')
+
gallery_conf = app.config.sphinxgallery_conf
gallery_dirs = gallery_conf['gallery_dir']
|
Move early return before debug message
for latex builder
|
sphinx-gallery_sphinx-gallery
|
train
|
28da9149291e05c81cf503156f3446c771216a89
|
diff --git a/tests/crianza_test.py b/tests/crianza_test.py
index <HASH>..<HASH> 100644
--- a/tests/crianza_test.py
+++ b/tests/crianza_test.py
@@ -8,6 +8,7 @@ import operator
import random
import sys
import unittest
+import six
try:
import crianza.native
@@ -69,7 +70,7 @@ class TestCrianza(unittest.TestCase):
def test_random_arithmetic(self):
ops = [operator.mul, operator.add]
for op in ops:
- for _ in xrange(100):
+ for _ in range(100):
# TODO: Add negative numbers when our parser supports it
a = random.randint(0, +(2**31-1))
b = random.randint(0, +(2**31-1))
@@ -110,7 +111,7 @@ class TestCrianza(unittest.TestCase):
sequence = []
numbers_to_generate = 15
- for its in xrange(0, numbers_to_generate):
+ for its in range(0, numbers_to_generate):
sequence.append(machine.top)
machine.run(13) # next number
@@ -118,21 +119,21 @@ class TestCrianza(unittest.TestCase):
233, 377, 610])
def test_io(self):
- fin = StringIO.StringIO("Input line 1.\nInput line 2.")
- fout = StringIO.StringIO()
+ fin = six.StringIO("Input line 1.\nInput line 2.")
+ fout = six.StringIO()
result = crianza.eval('123 read "howdy" . .', input=fin, output=fout)
self.assertEqual(result, 123)
self.assertEqual(fin.getvalue()[fin.tell():], "Input line 2.")
self.assertEqual(fout.getvalue(), "howdy\nInput line 1.\n")
- def _execfile(self, filename, input=StringIO.StringIO(),
- output=StringIO.StringIO(), steps=1000):
+ def _execfile(self, filename, input=six.StringIO(),
+ output=six.StringIO(), steps=1000):
with open(filename, "rt") as f:
return crianza.execute(f, input=input, output=output, steps=steps)
def test_program_even_odd(self):
- fin = StringIO.StringIO("1\n2\n3\n")
- fout = StringIO.StringIO()
+ fin = six.StringIO("1\n2\n3\n")
+ fout = six.StringIO()
m = self._execfile("tests/even-odd.source", input=fin, output=fout)
self.assertEqual(fout.getvalue(),
"Enter a number: The number 1 is odd.\n" +
@@ -145,7 +146,7 @@ class TestCrianza(unittest.TestCase):
self.assertEqual(m.return_stack, crianza.Stack([]))
def test_program_sum_mul_1(self):
- fout = StringIO.StringIO()
+ fout = six.StringIO()
m = self._execfile("tests/sum-mul-1.source", output=fout)
self.assertEqual(fout.getvalue(), "(2+3) * 4 = 20\n")
self.assertEqual(m.top, None)
@@ -153,8 +154,8 @@ class TestCrianza(unittest.TestCase):
self.assertEqual(m.return_stack, crianza.Stack([]))
def test_program_sum_mul_2(self):
- fin = StringIO.StringIO("12\n34\n")
- fout = StringIO.StringIO()
+ fin = six.StringIO("12\n34\n")
+ fout = six.StringIO()
m = self._execfile("tests/sum-mul-2.source", input=fin, output=fout)
self.assertEqual(fout.getvalue(),
"Enter a number: " +
@@ -166,7 +167,7 @@ class TestCrianza(unittest.TestCase):
self.assertEqual(m.return_stack, crianza.Stack([]))
def test_program_subroutine_1(self):
- fout = StringIO.StringIO()
+ fout = six.StringIO()
m = self._execfile("tests/subroutine-1.source", output=fout)
self.assertEqual(fout.getvalue(), "one\ntwo\nthree\n144\nfinished\n")
self.assertEqual(m.top, 0)
@@ -174,7 +175,7 @@ class TestCrianza(unittest.TestCase):
self.assertEqual(m.return_stack, crianza.Stack([]))
def test_program_fibonacci_1(self):
- fout = StringIO.StringIO()
+ fout = six.StringIO()
m = self._execfile("tests/fibonacci.source", output=fout, steps=100)
self.assertEqual(fout.getvalue(),
"0\n1\n1\n2\n3\n5\n8\n13\n21\n34\n55\n89\n144\n233\n377\n")
@@ -183,7 +184,7 @@ class TestCrianza(unittest.TestCase):
self.assertEqual(m.return_stack, crianza.Stack([]))
def test_program_fibonacci_2(self):
- fout = StringIO.StringIO()
+ fout = six.StringIO()
m = self._execfile("tests/fibonacci-2.source", output=fout, steps=180)
self.assertEqual(fout.getvalue(),
"0\n1\n1\n2\n3\n5\n8\n13\n21\n34\n55\n89\n144\n233\n377\n")
|
update the tests to be cross compatible as well
|
cslarsen_crianza
|
train
|
37f14ab928821c7c9c01307dc88da7609437531d
|
diff --git a/django_bouncy/utils.py b/django_bouncy/utils.py
index <HASH>..<HASH> 100644
--- a/django_bouncy/utils.py
+++ b/django_bouncy/utils.py
@@ -1,8 +1,5 @@
# -*- coding: utf-8 -*-
"""Utility functions for the django_bouncy app"""
-from __future__ import absolute_import
-from __future__ import unicode_literals
-
try:
import urllib2 as urllib
except ImportError:
|
do not use unicode_literals rather mark as unicode
|
ofa_django-bouncy
|
train
|
6f74e4589061a27e598c53b02cacb3cda7af333b
|
diff --git a/test/e2e/network/ingress.go b/test/e2e/network/ingress.go
index <HASH>..<HASH> 100644
--- a/test/e2e/network/ingress.go
+++ b/test/e2e/network/ingress.go
@@ -382,7 +382,8 @@ var _ = SIGDescribe("Loadbalancing: L7", func() {
// TODO(nikhiljindal): Check the instance group annotation value and verify with a multizone cluster.
})
- It("should be able to switch between HTTPS and HTTP2 modes", func() {
+ // TODO (gau): Remove [Unreleased] label once HTTP2 is in the next Ingress release
+ It("should be able to switch between HTTPS and HTTP2 modes [Unreleased]", func() {
httpsScheme := "request_scheme=https"
By("Create a basic HTTP2 ingress")
|
add unreleased tag to http2 test
|
kubernetes_kubernetes
|
train
|
c4542fa6c28d6445b810aa4dbfc119c08e274f1f
|
diff --git a/tests/View/SummaryDoc.php b/tests/View/SummaryDoc.php
index <HASH>..<HASH> 100644
--- a/tests/View/SummaryDoc.php
+++ b/tests/View/SummaryDoc.php
@@ -91,7 +91,10 @@ class SummaryDoc
*/
public function doc3()
{
- // {{ i + 1 }}
+ /*
+ # _
+ {{ i + 1 }}
+ */
}
/**
|
docs<view>: add summary doc for view component
|
hunzhiwange_framework
|
train
|
3f09188d8839433b50daf7decf87a6b5967abe1e
|
diff --git a/tests/DateTime/DiffTest.php b/tests/DateTime/DiffTest.php
index <HASH>..<HASH> 100644
--- a/tests/DateTime/DiffTest.php
+++ b/tests/DateTime/DiffTest.php
@@ -750,7 +750,7 @@ class DiffTest extends TestCase
public function diffForHumansProvider()
{
- $now = Chronos::now();
+ $now = Chronos::parse('2020-01-04 10:01:01');
return [
[$now, $now->addYears(11), '11 years before'],
|
Fixed testing diffForHumans with relative times changes
|
cakephp_chronos
|
train
|
8ca1c356bec65f45b235ea95edb92f07b461b1e4
|
diff --git a/src/main/java/com/amazon/carbonado/repo/jdbc/JDBCConnectionCapability.java b/src/main/java/com/amazon/carbonado/repo/jdbc/JDBCConnectionCapability.java
index <HASH>..<HASH> 100644
--- a/src/main/java/com/amazon/carbonado/repo/jdbc/JDBCConnectionCapability.java
+++ b/src/main/java/com/amazon/carbonado/repo/jdbc/JDBCConnectionCapability.java
@@ -19,8 +19,10 @@
package com.amazon.carbonado.repo.jdbc;
import java.sql.Connection;
+import java.sql.SQLException;
import com.amazon.carbonado.FetchException;
+import com.amazon.carbonado.PersistException;
import com.amazon.carbonado.capability.Capability;
/**
@@ -70,6 +72,41 @@ public interface JDBCConnectionCapability extends Capability {
void yieldConnection(Connection con) throws FetchException;
/**
+ * Transforms the given throwable into an appropriate fetch exception. If
+ * it already is a fetch exception, it is simply casted.
+ *
+ * @param e required exception to transform
+ * @return FetchException, never null
+ * @since 1.2
+ */
+ FetchException toFetchException(Throwable e);
+
+ /**
+ * Transforms the given throwable into an appropriate persist exception. If
+ * it already is a persist exception, it is simply casted.
+ *
+ * @param e required exception to transform
+ * @return PersistException, never null
+ * @since 1.2
+ */
+ PersistException toPersistException(Throwable e);
+
+ /**
+ * Examines the SQLSTATE code of the given SQL exception and determines if
+ * it is a unique constaint violation.
+ *
+ * @since 1.2
+ */
+ boolean isUniqueConstraintError(SQLException e);
+
+ /**
+ * Returns true if a transaction is in progress and it is for update.
+ *
+ * @since 1.2
+ */
+ boolean isTransactionForUpdate();
+
+ /**
* Returns the name of the database product connected to.
*/
String getDatabaseProductName();
|
Preparations for hiding JDBCRepository class.
|
Carbonado_Carbonado
|
train
|
1c09b025c071bc26803c041add92f8b8f1e02d78
|
diff --git a/p2p/security/tls/crypto.go b/p2p/security/tls/crypto.go
index <HASH>..<HASH> 100644
--- a/p2p/security/tls/crypto.go
+++ b/p2p/security/tls/crypto.go
@@ -72,6 +72,7 @@ func generateConfig(privKey ic.PrivKey) (*tls.Config, error) {
return nil, err
}
return &tls.Config{
+ MinVersion: tls.VersionTLS13,
InsecureSkipVerify: true, // This is not insecure here. We will verify the cert chain ourselves.
ClientAuth: tls.RequireAnyClientCert,
Certificates: []tls.Certificate{{
diff --git a/p2p/security/tls/transport.go b/p2p/security/tls/transport.go
index <HASH>..<HASH> 100644
--- a/p2p/security/tls/transport.go
+++ b/p2p/security/tls/transport.go
@@ -4,12 +4,19 @@ import (
"context"
"crypto/tls"
"net"
+ "os"
cs "github.com/libp2p/go-conn-security"
ci "github.com/libp2p/go-libp2p-crypto"
peer "github.com/libp2p/go-libp2p-peer"
)
+// TLS 1.3 is opt-in in Go 1.12
+// Activate it by setting the tls13 GODEBUG flag.
+func init() {
+ os.Setenv("GODEBUG", os.Getenv("GODEBUG")+",tls13=1")
+}
+
// ID is the protocol ID (used when negotiating with multistream)
const ID = "/tls/1.0.0"
@@ -47,6 +54,12 @@ func (t *Transport) SecureInbound(ctx context.Context, insecure net.Conn) (cs.Co
}
// SecureOutbound runs the TLS handshake as a client.
+// Note that SecureOutbound will not return an error if the server doesn't
+// accept the certificate. This is due to the fact that in TLS 1.3, the client
+// sends its certificate and the ClientFinished in the same flight, and can send
+// application data immediately afterwards.
+// If the handshake fails, the server will close the connection. The client will
+// notice this after 1 RTT when calling Read.
func (t *Transport) SecureOutbound(ctx context.Context, insecure net.Conn, p peer.ID) (cs.Conn, error) {
cl := tls.Client(insecure, t.identity.ConfigForPeer(p))
return t.handshake(ctx, cl)
diff --git a/p2p/security/tls/transport_test.go b/p2p/security/tls/transport_test.go
index <HASH>..<HASH> 100644
--- a/p2p/security/tls/transport_test.go
+++ b/p2p/security/tls/transport_test.go
@@ -66,7 +66,7 @@ var _ = Describe("Transport", func() {
Expect(err).ToNot(HaveOccurred())
identity.Config.Certificates[0].PrivateKey = key
case *ecdsa.PrivateKey:
- key, err := ecdsa.GenerateKey(elliptic.P224(), rand.Reader)
+ key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
Expect(err).ToNot(HaveOccurred())
identity.Config.Certificates[0].PrivateKey = key
default:
@@ -195,17 +195,14 @@ var _ = Describe("Transport", func() {
go func() {
defer GinkgoRecover()
_, err := serverTransport.SecureInbound(context.Background(), serverInsecureConn)
- Expect(err).To(HaveOccurred())
- Expect(err.Error()).To(Or(
- ContainSubstring("crypto/rsa: verification error"),
- ContainSubstring("ECDSA verification failure"),
- ))
+ Expect(err).To(MatchError("tls: invalid certificate signature"))
close(done)
}()
- _, err = clientTransport.SecureOutbound(context.Background(), clientInsecureConn, serverID)
- Expect(err).To(HaveOccurred())
- Expect(err.Error()).To(ContainSubstring("tls: bad certificate"))
+ conn, err := clientTransport.SecureOutbound(context.Background(), clientInsecureConn, serverID)
+ Expect(err).ToNot(HaveOccurred())
+ _, err = conn.Read([]byte{0})
+ Expect(err).To(MatchError("remote error: tls: error decrypting message"))
Eventually(done).Should(BeClosed())
})
@@ -223,16 +220,12 @@ var _ = Describe("Transport", func() {
defer GinkgoRecover()
_, err := serverTransport.SecureInbound(context.Background(), serverInsecureConn)
Expect(err).To(HaveOccurred())
- // TLS returns a weird error here: "remote error: tls: unexpected message"
+ Expect(err.Error()).To(ContainSubstring("remote error: tls:"))
close(done)
}()
_, err = clientTransport.SecureOutbound(context.Background(), clientInsecureConn, serverID)
- Expect(err).To(HaveOccurred())
- Expect(err.Error()).To(Or(
- ContainSubstring("crypto/rsa: verification error"),
- ContainSubstring("ECDSA verification failure"),
- ))
+ Expect(err).To(MatchError("tls: invalid certificate signature"))
Eventually(done).Should(BeClosed())
})
})
|
switch to TLS <I>
TLS <I> support was recently made opt-in in Go <I>, so we need to
explicitly enable it.
|
libp2p_go-libp2p
|
train
|
2e9179df3733eb30371805cada6f13ecc7831a56
|
diff --git a/package.json b/package.json
index <HASH>..<HASH> 100644
--- a/package.json
+++ b/package.json
@@ -7,7 +7,7 @@
"lint-css": "stylelint public/js/components/*.css",
"lint-js": "eslint public/js",
"test": "mocha --compilers js:babel-register public/js/test/node-unit-tests.js",
- "test-all": "npm run test; npm run lint; npm run cypress",
+ "test-all": "npm run test; npm run lint; npm run cypress; npm run karma",
"test-paths": "mocha --compilers js:babel-register",
"mocha-server": "node bin/mocha-server.js",
"cypress-server": "node bin/cypress-server.js",
diff --git a/public/js/components/tests/Editor.js b/public/js/components/tests/Editor.js
index <HASH>..<HASH> 100644
--- a/public/js/components/tests/Editor.js
+++ b/public/js/components/tests/Editor.js
@@ -9,7 +9,7 @@ if (typeof window == "object") {
}
describe("Editor", function() {
- it("todomvc", function() {
+ xit("todomvc", function() {
const $el = renderComponent(Editor, "todomvc");
const lines = getEditorLines($el);
expect(lines.length).to.equal(46);
diff --git a/public/js/lib/devtools-sham/sham/promise.js b/public/js/lib/devtools-sham/sham/promise.js
index <HASH>..<HASH> 100644
--- a/public/js/lib/devtools-sham/sham/promise.js
+++ b/public/js/lib/devtools-sham/sham/promise.js
@@ -7,7 +7,9 @@
* and use the native web API (although building with webpack/babel, it may replace this
* with it's own version if we want to target environments that do not have `Promise`.
*/
-Promise.defer = function defer() {
+
+let p = typeof window != "undefined" ? window.Promise : Promise;
+p.defer = function defer() {
var resolve, reject;
var promise = new Promise(function() {
resolve = arguments[0];
@@ -20,4 +22,4 @@ Promise.defer = function defer() {
};
}
-module.exports = Promise;
+module.exports = p;
diff --git a/public/js/util/sources-tree.js b/public/js/util/sources-tree.js
index <HASH>..<HASH> 100644
--- a/public/js/util/sources-tree.js
+++ b/public/js/util/sources-tree.js
@@ -1,7 +1,7 @@
"use strict";
const URL = require("url");
-const { assert } = require("devtools-sham/shared/DevToolsUtils");
+// const { assert } = require("devtools-sham/shared/DevToolsUtils");
function nodeHasChildren(item) {
// Do not use `Array.isArray` because it's slower and we do not need
@@ -92,7 +92,7 @@ function addToTree(tree, source) {
//
// TODO: Be smarter about this, which we'll probably do when we
// are smarter about folders and collapsing empty ones.
- assert(nodeHasChildren(subtree), `${subtree.name} should have children`);
+ // assert(nodeHasChildren(subtree), `${subtree.name} should have children`);
const subpaths = subtree.contents;
// We want to sort alphabetically, so find the index where we
|
Fix karma
There were three issues
+ DevToolsUtils.assert was failing in karma due to `undefined.testing`
property
+ The Editor component unit test is broken due to a loading issue
(flagged off)
+ The devtools-sham promise file was loading poorly. Fixed and will move
those files to defer.js soon
|
firefox-devtools_debugger
|
train
|
2059d6edb53b53cfe0ab25f805acbb353b012a06
|
diff --git a/lib/upgradelib.php b/lib/upgradelib.php
index <HASH>..<HASH> 100644
--- a/lib/upgradelib.php
+++ b/lib/upgradelib.php
@@ -1526,7 +1526,9 @@ function print_upgrade_part_end($plugin, $installation, $verbose) {
}
}
if ($verbose) {
- echo $OUTPUT->notification(get_string('success'), 'notifysuccess');
+ $notification = new \core\output\notification(get_string('success'), \core\output\notification::NOTIFY_SUCCESS);
+ $notification->set_show_closebutton(false);
+ echo $OUTPUT->render($notification);
print_upgrade_separator();
}
}
|
MDL-<I> upgradelib: Remove close button on success notification
|
moodle_moodle
|
train
|
5bc30129b0e7a37f7f1bb562b0bffc6d4ee07491
|
diff --git a/system-test/integration_test.go b/system-test/integration_test.go
index <HASH>..<HASH> 100644
--- a/system-test/integration_test.go
+++ b/system-test/integration_test.go
@@ -58,7 +58,7 @@ retry apt-get update >/dev/null
retry apt-get -y -q install git >/dev/null
# Install desired version of Node.js
-retry curl -o- https://raw.githubusercontent.com/creationix/nvm/v0.33.8/install.sh | bash >/dev/null
+retry curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.35.3/install.sh | bash >/dev/null
export NVM_DIR="$HOME/.nvm" >/dev/null
[ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh" >/dev/null
|
chore: install newer version of nvm in integration test (#<I>)
|
googleapis_cloud-profiler-nodejs
|
train
|
ea4796fadff7f7d3c2f3481e112423bdb0f0681e
|
diff --git a/netsnmpagent.py b/netsnmpagent.py
index <HASH>..<HASH> 100644
--- a/netsnmpagent.py
+++ b/netsnmpagent.py
@@ -895,7 +895,12 @@ class netsnmpAgent(object):
def shutdown(self):
libnsa.snmp_shutdown(self.AgentName)
- libnsa.shutdown_agent()
+
+ # Unfortunately we can't safely call shutdown_agent() for the time
+ # being. All net-snmp versions up to and including 5.7.3 are unable
+ # to do proper cleanup and cause issues such as double free()s so that
+ # one effectively has to rely on the OS to release resources.
+ #libnsa.shutdown_agent()
class netsnmpAgentException(Exception):
pass
|
Do not call net-snmp's shutdown_agent() anymore
Unfortunately, the situation is even worse than described in 9c6c<I> so that
we'll have to revert that change. Calling shutdown_agent() will cause trouble
if SNMP objects have been registered (double free()s).
|
pief_python-netsnmpagent
|
train
|
d2f35e93182ebc79fe609ca01908283d0982c40a
|
diff --git a/libkbfs/prefetcher.go b/libkbfs/prefetcher.go
index <HASH>..<HASH> 100644
--- a/libkbfs/prefetcher.go
+++ b/libkbfs/prefetcher.go
@@ -41,13 +41,18 @@ func newPrefetcher(retriever blockRetriever) *blockPrefetcher {
}
func (p *blockPrefetcher) run() {
- for ch := range p.progressCh {
- ch := ch
- p.sg.Add(1)
- go func() error {
- defer p.sg.Done()
- return <-ch
- }()
+runloop:
+ for {
+ select {
+ case ch := <-p.progressCh:
+ p.sg.Add(1)
+ go func() error {
+ defer p.sg.Done()
+ return <-ch
+ }()
+ case <-p.shutdownCh:
+ break runloop
+ }
}
p.sg.Wait()
close(p.doneCh)
@@ -119,7 +124,6 @@ func (p *blockPrefetcher) HandleBlock(b Block, kmd KeyMetadata, priority int) {
p.prefetchIndirectFileBlock(b, kmd, priority)
}
case *DirBlock:
- // If this is an on-demand request:
if priority >= defaultOnDemandRequestPriority {
if b.IsInd {
p.prefetchIndirectDirBlock(b, kmd, priority)
@@ -132,7 +136,10 @@ func (p *blockPrefetcher) HandleBlock(b Block, kmd KeyMetadata, priority int) {
}
func (p *blockPrefetcher) Shutdown() <-chan struct{} {
- close(p.progressCh)
- close(p.shutdownCh)
+ select {
+ case <-p.shutdownCh:
+ default:
+ close(p.shutdownCh)
+ }
return p.doneCh
}
diff --git a/libkbfs/prefetcher_test.go b/libkbfs/prefetcher_test.go
index <HASH>..<HASH> 100644
--- a/libkbfs/prefetcher_test.go
+++ b/libkbfs/prefetcher_test.go
@@ -85,10 +85,8 @@ func TestPrefetcherIndirectFileBlock(t *testing.T) {
require.Equal(t, block1, block)
t.Log("Shutdown the prefetcher and wait until it's done prefetching.")
- go func() {
- continueCh2 <- nil
- continueCh3 <- nil
- }()
+ continueCh2 <- nil
+ continueCh3 <- nil
<-p.Shutdown()
t.Log("Ensure that the prefetched blocks are in the cache.")
@@ -131,10 +129,8 @@ func TestPrefetcherIndirectDirBlock(t *testing.T) {
require.Equal(t, block1, block)
t.Log("Shutdown the prefetcher and wait until it's done prefetching.")
- go func() {
- continueCh2 <- nil
- continueCh3 <- nil
- }()
+ continueCh2 <- nil
+ continueCh3 <- nil
<-p.Shutdown()
t.Log("Ensure that the prefetched blocks are in the cache.")
@@ -182,11 +178,9 @@ func TestPrefetcherDirectDirBlock(t *testing.T) {
require.Equal(t, dir1, block)
t.Log("Release the blocks in ascending order of their size. The largest block will error.")
- go func() {
- continueCh4 <- nil
- continueCh3 <- nil
- continueCh2 <- context.Canceled
- }()
+ continueCh4 <- nil
+ continueCh3 <- nil
+ continueCh2 <- context.Canceled
t.Log("Shutdown the prefetcher and wait until it's done prefetching.")
<-p.Shutdown()
diff --git a/test/qr_test.go b/test/qr_test.go
index <HASH>..<HASH> 100644
--- a/test/qr_test.go
+++ b/test/qr_test.go
@@ -124,6 +124,9 @@ func TestQRWithMultiBlockFiles(t *testing.T) {
func TestCRAfterQR(t *testing.T) {
test(t,
users("alice", "bob"),
+ as(bob,
+ disablePrefetch(),
+ ),
as(alice,
mkfile("a/b", "hello"),
),
|
prefetcher: Fix prefetcher_test and qr_test so they work consistently
|
keybase_client
|
train
|
473578d358a02ce1bb3aa8b990f9d0a2ab9346d6
|
diff --git a/opentracing-api/src/main/java/io/opentracing/propagation/Format.java b/opentracing-api/src/main/java/io/opentracing/propagation/Format.java
index <HASH>..<HASH> 100644
--- a/opentracing-api/src/main/java/io/opentracing/propagation/Format.java
+++ b/opentracing-api/src/main/java/io/opentracing/propagation/Format.java
@@ -27,7 +27,7 @@ import java.nio.ByteBuffer;
* <pre><code>
* Tracer tracer = ...
* io.opentracing.propagation.HttpHeaders httpCarrier = new AnHttpHeaderCarrier(httpRequest);
- * SpanContext spanCtx = tracer.extract(Format.Builtin.HTTP_HEADERS, httpHeaderReader);
+ * SpanContext spanCtx = tracer.extract(Format.Builtin.HTTP_HEADERS, httpCarrier);
* </code></pre>
*
* @see Tracer#inject(SpanContext, Format, Object)
|
Use correct reference in Javadoc (#<I>)
|
opentracing_opentracing-java
|
train
|
bc926ebf98a9ae8f2db843ce16a33a5282d18d35
|
diff --git a/lib/i18n.rb b/lib/i18n.rb
index <HASH>..<HASH> 100644
--- a/lib/i18n.rb
+++ b/lib/i18n.rb
@@ -12,7 +12,7 @@ module I18n
RESERVED_KEYS = [:scope, :default, :separator, :resolve, :object, :fallback, :format, :cascade, :throw, :raise, :deep_interpolation]
RESERVED_KEYS_PATTERN = /%\{(#{RESERVED_KEYS.join("|")})\}/
- extend(Module.new {
+ module Base
# Gets I18n configuration object.
def config
Thread.current[:i18n_config] ||= I18n::Config.new
@@ -337,5 +337,7 @@ module I18n
def normalized_key_cache
@normalized_key_cache ||= Hash.new { |h,k| h[k] = {} }
end
- })
+ end
+
+ extend Base
end
|
undo c5d9e8cfbda9bdac0dd4f<I>d<I>e5eb8a1c<I>e
This is so that I<I>n.translate will be available on rdoc
|
ruby-i18n_i18n
|
train
|
cc7006cc47f7f70ddb727eca1b799a0e46d8df3a
|
diff --git a/Tests/OrientDBCommandRecordDeleteTest.php b/Tests/OrientDBCommandRecordDeleteTest.php
index <HASH>..<HASH> 100644
--- a/Tests/OrientDBCommandRecordDeleteTest.php
+++ b/Tests/OrientDBCommandRecordDeleteTest.php
@@ -122,8 +122,9 @@ class OrientDBRecordDeleteTest extends OrientDB_TestCase
$this->db->DBOpen('demo', 'writer', 'writer');
$recPos = $this->db->recordCreate($this->clusterID, 'name:"test"');
$result = $this->db->recordDelete($this->clusterID . ':' . $recPos);
- $this->setExpectedException('OrientDBException');
+ $this->assertTrue($result);
$result = $this->db->recordDelete($this->clusterID . ':' . $recPos);
+ $this->assertFalse($result);
}
public function testRecordDeleteWithPessimisticVersion()
|
Update test to reflect changes in r<I>
|
AntonTerekhov_OrientDB-PHP
|
train
|
c9724c546fcb6380c146657a0872ec583e52dba5
|
diff --git a/php/commands/media.php b/php/commands/media.php
index <HASH>..<HASH> 100644
--- a/php/commands/media.php
+++ b/php/commands/media.php
@@ -27,11 +27,6 @@ class Media_Command extends WP_CLI_Command {
* seq 1000 2000 | xargs wp media regenerate
*/
function regenerate( $args, $assoc_args = array() ) {
- if ( !wp_image_editor_supports() ) {
- WP_CLI::error( 'No support for generating images found. ' .
- 'Please install the Imagick or GD PHP extensions.' );
- }
-
if ( empty( $args ) ) {
WP_CLI::confirm( 'Do you realy want to regenerate all images?', $assoc_args );
}
@@ -246,5 +241,12 @@ class Media_Command extends WP_CLI_Command {
}
}
-WP_CLI::add_command( 'media', 'Media_Command' );
+WP_CLI::add_command( 'media', 'Media_Command', array(
+ 'before_invoke' => function () {
+ if ( !wp_image_editor_supports() ) {
+ WP_CLI::error( 'No support for generating images found. ' .
+ 'Please install the Imagick or GD PHP extensions.' );
+ }
+ }
+) );
|
check for platform support before calling 'wp media import' too
|
wp-cli_extension-command
|
train
|
a8ad9442ceabdbd1bd4c1bf6baab4fda8484bcac
|
diff --git a/azure/src/test/java/com/microsoft/azure/TestLoadBalancer.java b/azure/src/test/java/com/microsoft/azure/TestLoadBalancer.java
index <HASH>..<HASH> 100644
--- a/azure/src/test/java/com/microsoft/azure/TestLoadBalancer.java
+++ b/azure/src/test/java/com/microsoft/azure/TestLoadBalancer.java
@@ -17,6 +17,7 @@ import com.microsoft.azure.management.compute.VirtualMachines;
import com.microsoft.azure.management.network.Backend;
import com.microsoft.azure.management.network.Frontend;
import com.microsoft.azure.management.network.HttpProbe;
+import com.microsoft.azure.management.network.InboundNatRule;
import com.microsoft.azure.management.network.InternetFrontend;
import com.microsoft.azure.management.network.LoadBalancer;
import com.microsoft.azure.management.network.LoadBalancers;
@@ -172,6 +173,11 @@ public class TestLoadBalancer extends TestTemplate<LoadBalancer, LoadBalancers>
.withLoadDistribution(LoadDistribution.SOURCE_IP)
.attach()
+ // Inbound NAT rules
+ .defineInboundNatRule("natrule1")
+ .withFrontend("frontend1")
+ .withFrontendPort(88)
+ .attach()
.create();
// Verify frontends
@@ -199,6 +205,13 @@ public class TestLoadBalancer extends TestTemplate<LoadBalancer, LoadBalancers>
Assert.assertTrue(rule.frontend().name().equalsIgnoreCase("frontend1"));
Assert.assertTrue(rule.probe().name().equalsIgnoreCase("tcpProbe1"));
+ // Verify inbound NAT rules
+ Assert.assertTrue(lb.inboundNatRules().containsKey("natrule1"));
+ Assert.assertTrue(lb.inboundNatRules().size() == 1);
+ InboundNatRule inboundNatRule = lb.inboundNatRules().get("natrule1");
+ Assert.assertTrue(inboundNatRule.frontend().name().equalsIgnoreCase("frontend1"));
+ Assert.assertTrue(inboundNatRule.frontendPort() == 88);
+ Assert.assertTrue(inboundNatRule.backendPort() == 88);
return lb;
}
@@ -209,6 +222,7 @@ public class TestLoadBalancer extends TestTemplate<LoadBalancer, LoadBalancers>
.withoutFrontend("default")
.withoutBackend("default")
.withoutLoadBalancingRule("rule1")
+ .withoutInboundNatRule("natrule1")
.withTag("tag1", "value1")
.withTag("tag2", "value2")
.apply();
@@ -303,6 +317,17 @@ public class TestLoadBalancer extends TestTemplate<LoadBalancer, LoadBalancers>
info.append("\n\t\t\tPublic IP Address ID: ").append(((InternetFrontend) frontend).publicIpAddressId());
}
}
+
+ // Show inbound NAT rules
+ info.append("\n\tInbound NAT rules:");
+ for (InboundNatRule natRule : resource.inboundNatRules().values()) {
+ info.append("\n\t\tInbound NAT rule name: ").append(natRule.name())
+ .append("\n\t\t\tFrontend: ").append(natRule.frontend().name())
+ .append("\n\t\t\tFrontend port: ").append(natRule.frontendPort())
+ .append("\n\t\t\tBackend port: ").append(natRule.backendPort())
+ .append("\n\t\t\tAssociated NIC IP config: ").append(natRule.networkInterfaceIpConfigurationId())
+ .append("\n\t\t\tFloating IP? ").append(natRule.floatingIpEnabled());
+ }
System.out.println(info.toString());
}
|
initial inbound NAT rule CRUD test
|
Azure_azure-sdk-for-java
|
train
|
26c4bffa7950ed41c72abc34bce1a09de7ddd6ac
|
diff --git a/src/protobuf_js_6_common.js b/src/protobuf_js_6_common.js
index <HASH>..<HASH> 100644
--- a/src/protobuf_js_6_common.js
+++ b/src/protobuf_js_6_common.js
@@ -64,7 +64,7 @@ exports.deserializeCls = function deserializeCls(cls, options) {
* @return {cls} The resulting object
*/
return function deserialize(arg_buf) {
- return cls.decode(arg_buf).toObject(conversion_options);
+ return cls.toObject(cls.decode(arg_buf), conversion_options);
};
};
|
Upgrade Protobuf.js 6 code to work with <I>
|
grpc_grpc-node
|
train
|
356629e17389b3557077dca97141bab0785fee14
|
diff --git a/ccxt.js b/ccxt.js
index <HASH>..<HASH> 100644
--- a/ccxt.js
+++ b/ccxt.js
@@ -3752,7 +3752,7 @@ var bitlish = {
let now = this.seconds ();
let start = now - 86400 * 30; // last 30 days
let interval = [ start.toString (), undefined ];
- return this.publicPostOhlcv (this.extend ({
+ return await this.publicPostOhlcv (this.extend ({
'time_range': interval,
}, params));
},
@@ -3846,7 +3846,7 @@ var bitlish = {
async cancelOrder (id) {
await this.loadMarkets ();
- return this.privatePostCancelTrade ({ 'id': id });
+ return await this.privatePostCancelTrade ({ 'id': id });
},
async withdraw (currency, amount, address, params = {}) {
diff --git a/ccxt/async/exchanges.py b/ccxt/async/exchanges.py
index <HASH>..<HASH> 100644
--- a/ccxt/async/exchanges.py
+++ b/ccxt/async/exchanges.py
@@ -2832,7 +2832,7 @@ class bitlish (Exchange):
now = self.seconds()
start = now - 86400 * 30 # last 30 days
interval = [str(start), None]
- return self.publicPostOhlcv(self.extend({
+ return await self.publicPostOhlcv(self.extend({
'time_range': interval,
}, params))
@@ -2916,7 +2916,7 @@ class bitlish (Exchange):
async def cancel_order(self, id):
await self.load_markets()
- return self.privatePostCancelTrade({'id': id})
+ return await self.privatePostCancelTrade({'id': id})
async def withdraw(self, currency, amount, address, params={}):
await self.load_markets()
|
bitlish async/await fixes
|
ccxt_ccxt
|
train
|
65df38f9b66802f599ed2e0c196fcf5d14c84a90
|
diff --git a/src-modules/org/opencms/workplace/tools/sites/CmsSitesList.java b/src-modules/org/opencms/workplace/tools/sites/CmsSitesList.java
index <HASH>..<HASH> 100644
--- a/src-modules/org/opencms/workplace/tools/sites/CmsSitesList.java
+++ b/src-modules/org/opencms/workplace/tools/sites/CmsSitesList.java
@@ -38,6 +38,7 @@ import org.opencms.main.CmsException;
import org.opencms.main.OpenCms;
import org.opencms.site.CmsSite;
import org.opencms.site.CmsSiteMatcher;
+import org.opencms.util.CmsStringUtil;
import org.opencms.workplace.CmsWorkplace;
import org.opencms.workplace.list.A_CmsListDialog;
import org.opencms.workplace.list.CmsListColumnAlignEnum;
@@ -179,7 +180,7 @@ public class CmsSitesList extends A_CmsListDialog {
selectedSites.add(item.getId());
}
Map<String, String[]> params = new HashMap<String, String[]>();
- params.put(PARAM_SITES, selectedSites.toArray(new String[selectedSites.size()]));
+ params.put(PARAM_SITES, new String[] {CmsStringUtil.listAsString(selectedSites, ",")});
params.put(PARAM_ACTION, new String[] {DIALOG_INITIAL});
params.put(PARAM_STYLE, new String[] {CmsToolDialog.STYLE_NEW});
getToolManager().jspForwardPage(this, PATH_REPORTS + "remove.jsp", params);
diff --git a/src-modules/org/opencms/workplace/tools/sites/CmsSitesRemoveThread.java b/src-modules/org/opencms/workplace/tools/sites/CmsSitesRemoveThread.java
index <HASH>..<HASH> 100644
--- a/src-modules/org/opencms/workplace/tools/sites/CmsSitesRemoveThread.java
+++ b/src-modules/org/opencms/workplace/tools/sites/CmsSitesRemoveThread.java
@@ -79,7 +79,7 @@ public class CmsSitesRemoveThread extends A_CmsReportThread {
for (String sitePath : CmsStringUtil.splitAsList(m_sites, ",")) {
try {
OpenCms.getSiteManager().removeSite(getCms(), OpenCms.getSiteManager().getSiteForSiteRoot(sitePath));
- getReport().print(Messages.get().container(Messages.RPT_REMOVED_SITE_SUCCESSFUL_1, sitePath));
+ getReport().println(Messages.get().container(Messages.RPT_REMOVED_SITE_SUCCESSFUL_1, sitePath));
} catch (CmsException e) {
getReport().addError(e);
}
|
Corrected remoce sites multi action for site management wp tool.
|
alkacon_opencms-core
|
train
|
ac4d0abfda0a5622a74157b01a4ed7435755a4c6
|
diff --git a/plugin/geomajas-plugin-deskmanager/framework/src/main/java/org/geomajas/plugin/deskmanager/client/gwt/geodesk/GeodeskEntryPoint.java b/plugin/geomajas-plugin-deskmanager/framework/src/main/java/org/geomajas/plugin/deskmanager/client/gwt/geodesk/GeodeskEntryPoint.java
index <HASH>..<HASH> 100644
--- a/plugin/geomajas-plugin-deskmanager/framework/src/main/java/org/geomajas/plugin/deskmanager/client/gwt/geodesk/GeodeskEntryPoint.java
+++ b/plugin/geomajas-plugin-deskmanager/framework/src/main/java/org/geomajas/plugin/deskmanager/client/gwt/geodesk/GeodeskEntryPoint.java
@@ -10,18 +10,6 @@
*/
package org.geomajas.plugin.deskmanager.client.gwt.geodesk;
-import java.util.List;
-
-import org.geomajas.configuration.client.ClientToolInfo;
-import org.geomajas.gwt.client.widget.MapWidget;
-import org.geomajas.plugin.deskmanager.client.gwt.geodesk.action.ribbon.RefreshLayersAction;
-import org.geomajas.plugin.deskmanager.client.gwt.geodesk.ribbon.MouseLocationRibbonColumn;
-import org.geomajas.plugin.deskmanager.client.gwt.geodesk.ribbon.ScaleSelectRibbonColumn;
-import org.geomajas.widget.utility.common.client.ribbon.RibbonColumn;
-import org.geomajas.widget.utility.gwt.client.ribbon.RibbonButton;
-import org.geomajas.widget.utility.gwt.client.ribbon.RibbonColumnRegistry;
-import org.geomajas.widget.utility.gwt.client.ribbon.RibbonColumnRegistry.RibbonColumnCreator;
-
import com.google.gwt.core.client.EntryPoint;
@@ -33,38 +21,12 @@ import com.google.gwt.core.client.EntryPoint;
*
*/
public class GeodeskEntryPoint implements EntryPoint {
- private static final String MOUSE_LOCATION_RIBBON_COLUMN_IDENTIFIER = "MouseLocationRibbonColumn";
- private static final String SCLE_SELECT_RIBBON_COLUMN_IDENTIFIER = "ScaleSelectRibbonColumn";
-
/*
* (non-Javadoc)
*
* @see com.google.gwt.core.client.EntryPoint#onModuleLoad()
*/
public void onModuleLoad() {
- initialize();
- }
-
- public void initialize() {
- RibbonColumnRegistry.put(MOUSE_LOCATION_RIBBON_COLUMN_IDENTIFIER, new RibbonColumnCreator() {
-
- public RibbonColumn create(List<ClientToolInfo> tools, MapWidget mapWidget) {
- return new MouseLocationRibbonColumn(mapWidget);
- }
- });
- RibbonColumnRegistry.put(SCLE_SELECT_RIBBON_COLUMN_IDENTIFIER, new RibbonColumnCreator() {
-
- public RibbonColumn create(List<ClientToolInfo> tools, MapWidget mapWidget) {
- return new ScaleSelectRibbonColumn(mapWidget);
- }
- });
- RibbonColumnRegistry.put(RefreshLayersAction.IDENTIFIER, new RibbonColumnCreator() {
-
- public RibbonColumn create(List<ClientToolInfo> tools, MapWidget mapWidget) {
- RibbonColumn rc = new RibbonButton(new RefreshLayersAction(mapWidget));
- return rc;
- }
- });
}
}
|
GDM-<I> Don't load widgets from framework, this is up to the specific applications
|
geomajas_geomajas-project-server
|
train
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.