hash
stringlengths 40
40
| diff
stringlengths 131
114k
| message
stringlengths 7
980
| project
stringlengths 5
67
| split
stringclasses 1
value |
|---|---|---|---|---|
b2bf0ce51185f065ff8c2f6b30436661ceb046f9
|
diff --git a/ui/admin/src/main/java/org/openengsb/ui/admin/testClient/TestClient.java b/ui/admin/src/main/java/org/openengsb/ui/admin/testClient/TestClient.java
index <HASH>..<HASH> 100644
--- a/ui/admin/src/main/java/org/openengsb/ui/admin/testClient/TestClient.java
+++ b/ui/admin/src/main/java/org/openengsb/ui/admin/testClient/TestClient.java
@@ -62,7 +62,7 @@ import org.apache.wicket.model.Model;
import org.apache.wicket.model.PropertyModel;
import org.apache.wicket.model.StringResourceModel;
import org.apache.wicket.request.mapper.parameter.PageParameters;
-import org.openengsb.connector.usernamepassword.Password;
+import org.openengsb.core.api.security.model.Password;
import org.openengsb.core.api.ConnectorManager;
import org.openengsb.core.api.ConnectorProvider;
import org.openengsb.core.api.Constants;
diff --git a/ui/admin/src/main/java/org/openengsb/ui/admin/xlink/mocking/XLinkMockImpl.java b/ui/admin/src/main/java/org/openengsb/ui/admin/xlink/mocking/XLinkMockImpl.java
index <HASH>..<HASH> 100644
--- a/ui/admin/src/main/java/org/openengsb/ui/admin/xlink/mocking/XLinkMockImpl.java
+++ b/ui/admin/src/main/java/org/openengsb/ui/admin/xlink/mocking/XLinkMockImpl.java
@@ -23,7 +23,7 @@ import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
-import org.openengsb.connector.usernamepassword.Password;
+import org.openengsb.core.api.security.model.Password;
import org.openengsb.core.api.LinkingSupport;
import org.openengsb.core.api.OsgiServiceNotAvailableException;
import org.openengsb.core.api.OsgiUtilsService;
|
[OPENENGSB-<I>] admin ui should use the Password in the security api
|
openengsb_openengsb
|
train
|
23e1bf25246753eda284f15e9242de64608ab170
|
diff --git a/py/dynesty/dynamicsampler.py b/py/dynesty/dynamicsampler.py
index <HASH>..<HASH> 100644
--- a/py/dynesty/dynamicsampler.py
+++ b/py/dynesty/dynamicsampler.py
@@ -229,7 +229,7 @@ def stopping_function(results,
realizations of the input using a provided `'error'` keyword (either
`'jitter'` or `'simulate'`, which call related functions :meth:`jitter_run`
and :meth:`simulate_run` in :mod:`dynesty.utils`, respectively, or
- `'sim_approx'`, which boosts `'jitter'` by a factor of two).
+ `'sim_approx'`
Returns the boolean `stop <= 1`. If `True`, the :class:`DynamicSampler`
will stop adding new samples to our results.
@@ -302,9 +302,6 @@ def stopping_function(results,
"The chosen `'error'` option {0} is not valid.".format(error))
if error == 'sim_approx':
error = 'jitter'
- boost = 2.
- else:
- boost = 1.
approx = args.get('approx', True)
# Compute realizations of ln(evidence) and the KL divergence.
@@ -319,11 +316,11 @@ def stopping_function(results,
# Evidence stopping value.
lnz_std = np.std(lnz_arr)
- stop_evid = np.sqrt(boost) * lnz_std / evid_thresh
+ stop_evid = lnz_std / evid_thresh
# Posterior stopping value.
kld_mean, kld_std = np.mean(kld_arr), np.std(kld_arr)
- stop_post = boost * (kld_std / kld_mean) / post_thresh
+ stop_post = (kld_std / kld_mean) / post_thresh
# Effective stopping value.
stop = pfrac * stop_post + (1. - pfrac) * stop_evid
|
get rid of boost in the stopping function
|
joshspeagle_dynesty
|
train
|
ecb16bbac48e98f97f3c920887fc41e67f1ece4f
|
diff --git a/CHANGES b/CHANGES
index <HASH>..<HASH> 100644
--- a/CHANGES
+++ b/CHANGES
@@ -16,6 +16,7 @@ Here you can see the list of changes between each Holocron release.
- Fixed security issue when content author may steal private data through
content's meta header.
- Fixed YAML header parser for documents with multiple ``---`` signs.
+- Fixed rebuilding of HTML produced by Tags and Feed extensions.
- Default theme is more responsive for smartphones & tablets now.
diff --git a/holocron/ext/index.py b/holocron/ext/index.py
index <HASH>..<HASH> 100644
--- a/holocron/ext/index.py
+++ b/holocron/ext/index.py
@@ -49,9 +49,9 @@ class Index(abc.Extension, abc.Generator):
}
def __init__(self, app):
+ self._app = app
self._conf = Conf(self._default_conf, app.conf.get('ext.index', {}))
self._encoding = app.conf['encoding.output']
- self._template = app.jinja_env.get_template(self._conf['template'])
# An output filename. Why this? Because we want to see this page
# by typing site url in a browser and http servers are usually
@@ -65,5 +65,6 @@ class Index(abc.Extension, abc.Generator):
# shown in a some sort of navigation bar
posts = (doc for doc in documents if isinstance(doc, Post))
+ template = self._app.jinja_env.get_template(self._conf['template'])
with open(self._save_as, 'w', encoding=self._encoding) as f:
- f.write(self._template.render(posts=posts))
+ f.write(template.render(posts=posts))
diff --git a/holocron/ext/tags.py b/holocron/ext/tags.py
index <HASH>..<HASH> 100644
--- a/holocron/ext/tags.py
+++ b/holocron/ext/tags.py
@@ -67,9 +67,9 @@ class Tags(abc.Extension, abc.Generator):
}
def __init__(self, app):
+ self._app = app
self._conf = Conf(self._default_conf, app.conf.get('ext.tags', {}))
self._encoding = app.conf['encoding.output']
- self._template = app.jinja_env.get_template(self._conf['template'])
self._save_as = os.path.join(
app.conf['paths.output'], self._conf['output'], 'index.html')
@@ -100,9 +100,11 @@ class Tags(abc.Extension, abc.Generator):
post.tags = tag_objects
+ template = self._app.jinja_env.get_template(self._conf['template'])
+
for tag in tags:
save_as = self._save_as.format(tag=tag)
mkdir(os.path.dirname(save_as))
with open(save_as, 'w', encoding=self._encoding) as f:
- f.write(self._template.render(posts=tags[tag]))
+ f.write(template.render(posts=tags[tag]))
|
Fix rebuilding of html produced by tags and feed
Previously, when you run ``serve`` command only blog core was able to
recognize changes commited to theme templates. Those changes weren't
recognized by both Tags and Feed generators (due to caching). Since now
it's fixed.
Closed #<I>
|
ikalnytskyi_holocron
|
train
|
124cfa43171d0145e5f6a1265bce28a5e172f526
|
diff --git a/spec/integration/aws_route_table_spec.rb b/spec/integration/aws_route_table_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/integration/aws_route_table_spec.rb
+++ b/spec/integration/aws_route_table_spec.rb
@@ -33,7 +33,7 @@ describe Chef::Resource::AwsRouteTable do
}.to create_an_aws_route_table('test_route_table',
routes: Set[
{ destination_cidr_block: '10.0.0.0/16', gateway_id: 'local', state: "active" },
- { destination_cidr_block: '0.0.0.0/0', gateway_id: test_vpc.aws_object.internet_gateway.id, state: "active" }
+ { destination_cidr_block: '0.0.0.0/0', gateway_id: test_vpc.aws_object.internet_gateways.first.id, state: "active" }
]
).and be_idempotent
end
@@ -57,7 +57,7 @@ describe Chef::Resource::AwsRouteTable do
routes: Set[
{ destination_cidr_block: '10.0.0.0/16', gateway_id: 'local', state: "active" },
{ destination_cidr_block: '172.31.0.0/16', network_interface_id: test_network_interface.aws_object.id, state: "blackhole" },
- { destination_cidr_block: '0.0.0.0/0', gateway_id: test_vpc.aws_object.internet_gateway.id, state: "active" },
+ { destination_cidr_block: '0.0.0.0/0', gateway_id: test_vpc.aws_object.internet_gateways.first.id, state: "active" },
]
).and be_idempotent
end
@@ -78,9 +78,9 @@ describe Chef::Resource::AwsRouteTable do
end
}.to update_an_aws_route_table('test_route_table',
routes: Set[
- { destination_cidr_block: '2.0.0.0/8', gateway_id: test_vpc.aws_object.internet_gateway.id, state: "active" },
+ { destination_cidr_block: '2.0.0.0/8', gateway_id: test_vpc.aws_object.internet_gateways.first.id, state: "active" },
{ destination_cidr_block: '10.0.0.0/16', gateway_id: 'local', state: "active" },
- { destination_cidr_block: '0.0.0.0/0', gateway_id: test_vpc.aws_object.internet_gateway.id, state: "active" },
+ { destination_cidr_block: '0.0.0.0/0', gateway_id: test_vpc.aws_object.internet_gateways.first.id, state: "active" },
]
).and be_idempotent
end
@@ -129,7 +129,7 @@ describe Chef::Resource::AwsRouteTable do
routes: Set[
{ destination_cidr_block: '10.0.0.0/16', gateway_id: 'local', state: "active" },
{ destination_cidr_block: '11.0.0.0/8', instance_id: test_machine.aws_object.id, state: "active" },
- { destination_cidr_block: '0.0.0.0/0', gateway_id: test_vpc.aws_object.internet_gateway.id, state: "active" },
+ { destination_cidr_block: '0.0.0.0/0', gateway_id: test_vpc.aws_object.internet_gateways.first.id, state: "active" },
]
).and be_idempotent
end
@@ -217,7 +217,7 @@ describe Chef::Resource::AwsRouteTable do
routes: Set[
{ destination_cidr_block: '10.0.0.0/24', gateway_id: 'local', state: "active" },
{ destination_cidr_block: '100.100.0.0/16', vpc_peering_connection_id: pcx.aws_object.id, state: "active" },
- { destination_cidr_block: '0.0.0.0/0', gateway_id: test_vpc_1.aws_object.internet_gateway.id, state: "active" }
+ { destination_cidr_block: '0.0.0.0/0', gateway_id: test_vpc_1.aws_object.internet_gateways.first.id, state: "active" }
]
).and be_idempotent
end
|
Fixed few more specs which was failing due to v2 changes and skipped in super slow tag
|
chef_chef-provisioning-aws
|
train
|
6c9e3dd8608c79466b5c27aee0d62ae0aaff3a28
|
diff --git a/src/main/java/org/mapdb/AsyncWriteEngine.java b/src/main/java/org/mapdb/AsyncWriteEngine.java
index <HASH>..<HASH> 100644
--- a/src/main/java/org/mapdb/AsyncWriteEngine.java
+++ b/src/main/java/org/mapdb/AsyncWriteEngine.java
@@ -163,21 +163,8 @@ public class AsyncWriteEngine extends EngineWrapper implements Engine {
try{
for(;;){
if(closeInProgress || threadFailedException !=null) return;
- while(!commitLock.readLock().tryLock(1000,TimeUnit.MILLISECONDS)){
- if(closeInProgress || threadFailedException !=null) return;
- }
- if(closeInProgress || threadFailedException !=null) return;
- Long newRecid;
- try{
- newRecid = getWrappedEngine().put(Utils.EMPTY_STRING, Serializer.EMPTY_SERIALIZER);
-
- }finally {
- commitLock.readLock().unlock();
- }
-
- while(!newRecids.offer(newRecid,1,TimeUnit.SECONDS)){
- if(closeInProgress || threadFailedException !=null) return;
- }
+ Long newRecid = getWrappedEngine().put(Utils.EMPTY_STRING, Serializer.EMPTY_SERIALIZER);
+ newRecids.put(newRecid);
}
} catch (Throwable e) {
threadFailedException = e;
|
Revert fix which was causing deadlocks.
|
jankotek_mapdb
|
train
|
4e9be7d914b2be8e37c719e11152b456d4356de4
|
diff --git a/fudge/__init__.py b/fudge/__init__.py
index <HASH>..<HASH> 100644
--- a/fudge/__init__.py
+++ b/fudge/__init__.py
@@ -27,6 +27,9 @@ class Registry(object):
for exp in self.get_expected_calls():
exp.assert_called()
finally:
+ # reset all calls
+ for exp in self.get_expected_calls():
+ exp.was_called = False
self.clear()
def expect_call(self, expected_call):
diff --git a/fudge/tests/test_fudge.py b/fudge/tests/test_fudge.py
index <HASH>..<HASH> 100644
--- a/fudge/tests/test_fudge.py
+++ b/fudge/tests/test_fudge.py
@@ -66,8 +66,10 @@ class TestRegistry(unittest.TestCase):
exp = ExpectedCall(self.fake, 'callMe')
self.reg.expect_call(exp)
exp()
+ eq_(exp.was_called, True)
eq_(len(self.reg.get_expected_calls()), 1)
self.reg.finish()
+ eq_(exp.was_called, False, "expected call was not reset by finish()")
eq_(len(self.reg.get_expected_calls()), 0)
def test_global_finish(self):
|
finish() also resets all calls made
|
fudge-py_fudge
|
train
|
0d6cfca19cf9438986d7730904b2fde76a8cce36
|
diff --git a/includes/Views/AdminParams.php b/includes/Views/AdminParams.php
index <HASH>..<HASH> 100644
--- a/includes/Views/AdminParams.php
+++ b/includes/Views/AdminParams.php
@@ -51,9 +51,11 @@ class AdminParams
*/
public function __construct()
{
- $this->possible_search_params = ['all', 'keyword', 'url', 'title', 'ip'];
- $this->possible_sort_params = ['keyword', 'url', 'title', 'ip', 'timestamp', 'clicks'];
- $this->params_translations = [
+ $this->possible_search_params = yourls_apply_filter('admin_params_possible_search',
+ ['all', 'keyword', 'url', 'title', 'ip']);
+ $this->possible_sort_params = yourls_apply_filter('admin_params_possible_sort',
+ ['keyword', 'url', 'title', 'ip', 'timestamp', 'clicks']);
+ $this->params_translations = yourls_apply_filter('admin_params_possible_translations',[
'all' => yourls__('All fields'),
'keyword' => yourls__('Short URL'),
'url' => yourls__('URL'),
@@ -61,8 +63,9 @@ class AdminParams
'ip' => yourls__('IP Address'),
'timestamp' => yourls__('Date'),
'clicks' => yourls__('Clicks'),
- ];
- $this->possible_date_sorting = ['before', 'after', 'between'];
+ ]);
+ $this->possible_date_sorting = yourls_apply_filter('admin_params_possible_date_sort',
+ ['before', 'after', 'between']);
}
/**
diff --git a/includes/functions-html.php b/includes/functions-html.php
index <HASH>..<HASH> 100644
--- a/includes/functions-html.php
+++ b/includes/functions-html.php
@@ -369,6 +369,8 @@ function yourls_html_tfooter( $params = array() ) {
* @return string HTML content of the select element
*/
function yourls_html_select( $name, $options, $selected = '', $display = false, $label = '' ) {
+ // Allow plugins to filter the options -- see #3262
+ $options = yourls_apply_filter( 'html_select_options', $options, $name, $selected, $display, $label );
$html = "<select aria-label='$label' name='$name' id='$name' size='1'>\n";
foreach( $options as $value => $text ) {
$html .= "<option value='$value' ";
|
More hooks for the admin view & search (#<I>)
Will fix #<I> and #<I>
|
YOURLS_YOURLS
|
train
|
da760c138c6c5925d3bab3d4a9b66d8bed82fd4f
|
diff --git a/lib/esi/client.rb b/lib/esi/client.rb
index <HASH>..<HASH> 100644
--- a/lib/esi/client.rb
+++ b/lib/esi/client.rb
@@ -4,12 +4,30 @@ require 'active_support/core_ext/string'
require 'set'
module Esi
+ # The Esi Client class
+ # @!attribute [rw] refresh_callback
+ # @return [#callback] the refresh_token callback method
+ # @!attribute [rw] access_token
+ # @return [String] the esi access_token
+ # @!attribute [rw] refresh_token
+ # @return [String] the esi refresh_token string
+ # @!attribute [rw] expires_at
+ # @return [Time] the timestamp of the esi token expire
+ # @!attribute [r] logger
+ # @return [Logger] the logger class for the gem
+ # @!attribute [r] oauth
+ # @return [Esi::Oauth] the oauth instance for the client
class Client
+ # @return [Fixnum] The max amount of request attempst Client will make
MAX_ATTEMPTS = 2
attr_accessor :refresh_callback, :access_token, :refresh_token, :expires_at
attr_reader :logger, :oauth
+ # Create a new instance of Client
+ # @param [String] token the esi access_token
+ # @param [String] refresh_token the esi refresh_token
+ # @param [Time] expires_at the time stamp the esi token expires_at
def initialize(token: nil, refresh_token: nil, expires_at: nil)
@logger = Esi.logger
@access_token = token
@@ -18,31 +36,58 @@ module Esi
@oauth = init_oauth
end
+ # Set the current thread's Esi::Client
+ # @params [Esi::Client] the client to set
+ # @return [Esi::Client] the current thread's Esi::Client
def self.current=(client)
Thread.current[:esi_client] = client
end
+ # Get the current thread's Esi::Client
+ # @return [Esi::Client] the current thread's Esi::Client
def self.current
Thread.current[:esi_client] ||= new
end
+ # Switch to default Esi::Client (Esi::Client.new)
+ # @return [Esi::Client] the current thread's Esi::Client
def self.switch_to_default
self.current = new
end
+ # Switch current thread's client to instance of Esi::Client
+ # @return [self] the instance calling switch to
def switch_to
Esi::Client.current = self
end
+ # Yield block with instance of Esi::Client and revert to
+ # previous client or default client
+ #
+ # @example Call an Esi::Client method using an instance of client
+ # new_client = Esi::Client.new(token: 'foo', refresh_token: 'foo', expires_at: 30.minutes.from_now)
+ # new_client.with_client do |client|
+ # client.character(1234)
+ # end
+ # #=> Esi::Response<#>
+ #
+ # @yieldreturn [#block] the passed block.
def with_client
initial_client = Esi::Client.current
switch_to
- yield if block_given?
+ yield(self) if block_given?
ensure
initial_client.switch_to if initial_client
Esi::Client.switch_to_default unless initial_client
end
+ # Intercept Esi::Client method_missing and attempt to call an Esi::Request
+ # with an Esi::Calls
+ # @param [Symbol|String] name the name of the method called
+ # @param [Array] *args the arguments to call the method with
+ # @param [#block] &block the block to pass to the underlying method
+ # @raise [NameError] If the Esi::Calls does not exist
+ # @return [Esi::Response] the response given for the call
def method_missing(name, *args, &block)
klass = nil
ActiveSupport::Notifications.instrument('esi.client.detect_call') do
@@ -56,6 +101,9 @@ module Esi
cached_response(klass, *args, &block)
end
+ # Test if the Esi::Client has a method
+ # @param [Symbol] name the name of the method to test
+ # @return [Boolean] wether or not the method exists
def method?(name)
begin
klass = Esi::Calls.const_get(method_to_class_name(name))
@@ -65,15 +113,24 @@ module Esi
!klass.nil?
end
+ # Test if the Esi::Client has a pluralized version of a method
+ # @param [Symbol] name the name of the method to test
+ # @return [Boolean] wether or not the pluralized method exists
def plural_method?(name)
plural = name.to_s.pluralize.to_sym
method? plural
end
+ # Log a message
+ # @param [String] message the message to log
+ # @return [void] the Logger.info method with message
def log(message)
logger.info message
end
+ # Log a message with debug
+ # @param [String] message the message to log
+ # @return [void] the Logger.debug method with message
def debug(message)
logger.debug message
end
|
added docs to Esi::Client
|
dhiemstra_esi
|
train
|
a4cf187f898cd43028161e80e03e82365a52b0e2
|
diff --git a/core/java/com/google/instrumentation/common/Function.java b/core/java/com/google/instrumentation/common/Function.java
index <HASH>..<HASH> 100644
--- a/core/java/com/google/instrumentation/common/Function.java
+++ b/core/java/com/google/instrumentation/common/Function.java
@@ -15,7 +15,7 @@ package com.google.instrumentation.common;
/**
* Used to specify matching functions for use encoding tagged unions (i.e. sum types) in Java. See
- * {@link com.google.instrumentation.AggregationDescriptor} for an example of it's use.
+ * {@link com.google.instrumentation.stats.AggregationDescriptor} for an example of it's use.
*
* <p>Note: This class is based on the java.util.Function class added in Java 1.8.
*/
|
Updates javadoc to fix lint issue (2nd attempt).
|
census-instrumentation_opencensus-java
|
train
|
a327d8018ffc055c6661d375cfdd6ede023f940e
|
diff --git a/lib/hypercuke/cli.rb b/lib/hypercuke/cli.rb
index <HASH>..<HASH> 100644
--- a/lib/hypercuke/cli.rb
+++ b/lib/hypercuke/cli.rb
@@ -4,14 +4,8 @@ require 'hypercuke/cli/builder'
module Hypercuke
class CLI
def self.exec(argv, opts = {})
- cli = new(argv)
-
- if out = opts[:output_to]
- out.puts cli.cucumber_command_with_env_var
- end
-
- ENV[Hypercuke::LAYER_NAME_ENV_VAR] = cli.layer_name
- Kernel.exec cli.cucumber_command
+ cli = new(argv, opts[:output_to])
+ cli.run!
end
# NB: .bundler_present? is not covered by tests, because I can't
@@ -20,8 +14,17 @@ module Hypercuke
!! (`which bundle` =~ /bundle/) # parens are significant
end
- def initialize(argv)
- @argv = argv
+ def initialize(argv, output = nil, environment = ENV, kernel = Kernel)
+ @argv = argv
+ @output = output
+ @environment = environment
+ @kernel = kernel
+ end
+
+ def run!
+ output && output.puts(cucumber_command_with_env_var)
+ environment[Hypercuke::LAYER_NAME_ENV_VAR] = layer_name
+ kernel.exec cucumber_command
end
def layer_name
@@ -37,7 +40,7 @@ module Hypercuke
end
private
- attr_reader :argv
+ attr_reader :argv, :output, :environment, :kernel
def parser
@parser ||= Hypercuke::CLI::Parser.new(argv)
diff --git a/spec/cli_spec.rb b/spec/cli_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/cli_spec.rb
+++ b/spec/cli_spec.rb
@@ -28,8 +28,8 @@ require 'spec_helper'
describe Hypercuke::CLI do
- def cli_for(hcu_command)
- described_class.new(hcu_command)
+ def cli_for(hcu_command, *args)
+ described_class.new(hcu_command, *args)
end
describe "cucumber command line generation" do
@@ -110,4 +110,26 @@ expected: #{expected_output.inspect}
expect( cli_for('hcu ui') .layer_name ).to eq( 'ui' )
end
end
+
+ describe "#run!" do
+ let(:cli) { cli_for('fudge_ripple', output, environment, kernel) }
+ let(:output) { double('output', puts: nil) }
+ let(:kernel) { double('Kernel', exec: nil) }
+ let(:environment) { Hash.new }
+
+ it "prints the generated Cucumber command to output" do
+ expect(output).to receive(:puts).with(cli.cucumber_command_with_env_var)
+ cli.run!
+ end
+
+ it "sets an environment variable with the given layer name" do
+ cli.run!
+ expect( environment[Hypercuke::LAYER_NAME_ENV_VAR] ).to eq( 'fudge_ripple' )
+ end
+
+ it "uses exec to run the Cucumber command" do
+ expect(kernel).to receive(:exec).with(cli.cucumber_command)
+ cli.run!
+ end
+ end
end
|
Cover more of the CLI with tests
|
livingsocial_hypercuke
|
train
|
bb6cdf0fe264865d626c2eedd56c1eae7f8ca300
|
diff --git a/public/js/chrome/save.js b/public/js/chrome/save.js
index <HASH>..<HASH> 100644
--- a/public/js/chrome/save.js
+++ b/public/js/chrome/save.js
@@ -139,7 +139,7 @@ function saveCode(method, ajax, ajaxCallback) {
var $binGroup,
edit;
- $('form').attr('action', data.url + '/save');
+ $form.attr('action', data.url + '/save');
ajaxCallback && ajaxCallback(data);
sessionStorage.setItem('checksum', data.checksum);
|
Fixed the damn illusive logging out posting to save. Finally fixes #<I>
|
jsbin_jsbin
|
train
|
e1a3cd0446f1fe4f10154df06b1f0fea0424a256
|
diff --git a/src/Symfony/Bundle/CompatAssetsBundle/Templating/Helper/JavascriptsHelper.php b/src/Symfony/Bundle/CompatAssetsBundle/Templating/Helper/JavascriptsHelper.php
index <HASH>..<HASH> 100644
--- a/src/Symfony/Bundle/CompatAssetsBundle/Templating/Helper/JavascriptsHelper.php
+++ b/src/Symfony/Bundle/CompatAssetsBundle/Templating/Helper/JavascriptsHelper.php
@@ -83,15 +83,6 @@ class JavascriptsHelper extends Helper
}
/**
- * Outputs HTML representation of the links to JavaScripts.
- *
- */
- public function output()
- {
- echo $this->render();
- }
-
- /**
* Returns a string representation of this helper as HTML.
*
* @return string The HTML representation of the JavaScripts
diff --git a/src/Symfony/Bundle/CompatAssetsBundle/Templating/Helper/StylesheetsHelper.php b/src/Symfony/Bundle/CompatAssetsBundle/Templating/Helper/StylesheetsHelper.php
index <HASH>..<HASH> 100644
--- a/src/Symfony/Bundle/CompatAssetsBundle/Templating/Helper/StylesheetsHelper.php
+++ b/src/Symfony/Bundle/CompatAssetsBundle/Templating/Helper/StylesheetsHelper.php
@@ -83,15 +83,6 @@ class StylesheetsHelper extends Helper
}
/**
- * Outputs HTML representation of the links to stylesheets.
- *
- */
- public function output()
- {
- echo $this->render();
- }
-
- /**
* Returns a string representation of this helper as HTML.
*
* @return string The HTML representation of the stylesheets
diff --git a/src/Symfony/Bundle/FrameworkBundle/Templating/Helper/ActionsHelper.php b/src/Symfony/Bundle/FrameworkBundle/Templating/Helper/ActionsHelper.php
index <HASH>..<HASH> 100644
--- a/src/Symfony/Bundle/FrameworkBundle/Templating/Helper/ActionsHelper.php
+++ b/src/Symfony/Bundle/FrameworkBundle/Templating/Helper/ActionsHelper.php
@@ -34,19 +34,6 @@ class ActionsHelper extends Helper
}
/**
- * Outputs the Response content for a given controller.
- *
- * @param string $controller A controller name to execute (a string like BlogBundle:Post:index), or a relative URI
- * @param array $options An array of options
- *
- * @see render()
- */
- public function output($controller, array $attributes = array(), array $options = array())
- {
- echo $this->render($controller, $attributes, $options);
- }
-
- /**
* Returns the Response content for a given controller or URI.
*
* @param string $controller A controller name to execute (a string like BlogBundle:Post:index), or a relative URI
|
removed output() methods, which are only shortcut for 'echo render'
|
symfony_symfony
|
train
|
e0dc94c7d29b1501b143da11ab75a672d7a2d7bd
|
diff --git a/lib/Issuing/Transaction.php b/lib/Issuing/Transaction.php
index <HASH>..<HASH> 100644
--- a/lib/Issuing/Transaction.php
+++ b/lib/Issuing/Transaction.php
@@ -32,6 +32,7 @@ namespace Stripe\Issuing;
* @property \Stripe\StripeObject $metadata Set of <a href="https://stripe.com/docs/api/metadata">key-value pairs</a> that you can attach to an object. This can be useful for storing additional information about the object in a structured format.
* @property null|\Stripe\StripeObject $purchase_details Additional purchase information that is optionally provided by the merchant.
* @property string $type The nature of the transaction.
+ * @property null|string $wallet The digital wallet used for this transaction. One of <code>apple_pay</code>, <code>google_pay</code>, or <code>samsung_pay</code>.
*/
class Transaction extends \Stripe\ApiResource
{
|
Codegen for openapi adfc<I>f (#<I>)
|
stripe_stripe-php
|
train
|
be6685b3615e4a0ae12171954218f892e67bf1f2
|
diff --git a/api/server/version.go b/api/server/version.go
index <HASH>..<HASH> 100644
--- a/api/server/version.go
+++ b/api/server/version.go
@@ -7,7 +7,7 @@ import (
)
// Version of IronFunctions
-var Version = "0.1.17"
+var Version = "0.1.18"
func handleVersion(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{"version": Version})
|
functions: <I> release [skip ci]
|
iron-io_functions
|
train
|
280757ea2728c77fc36f01a57ead505658760e16
|
diff --git a/disqusapi/__init__.py b/disqusapi/__init__.py
index <HASH>..<HASH> 100644
--- a/disqusapi/__init__.py
+++ b/disqusapi/__init__.py
@@ -89,10 +89,16 @@ class Resource(object):
if node:
tree = tree + (node,)
self.tree = tree
+ self.interfaces_by_method = {}
+
+ def update_interface(self, interface):
+ raise NotImplemented
def __getattr__(self, attr):
if attr in getattr(self, '__dict__'):
return getattr(self, attr)
+ if attr == 'interface':
+ raise InterfaceNotDefined('You must use ``update_interface`` now.')
interface = {}
try:
interface = self.interfaces[attr]
diff --git a/disqusapi/tests.py b/disqusapi/tests.py
index <HASH>..<HASH> 100644
--- a/disqusapi/tests.py
+++ b/disqusapi/tests.py
@@ -6,6 +6,22 @@ import unittest
import disqusapi
from disqusapi.compat import xrange
+extra_interface = {
+ "reserved": {
+ "global": {
+ "word": {
+ "method": "GET",
+ "required": [
+ "text",
+ ],
+ "formats": [
+ "json",
+ ],
+ }
+ }
+ }
+}
+
def requires(*env_vars):
def wrapped(func):
@@ -120,6 +136,14 @@ class DisqusAPITest(unittest.TestCase):
self.assertEquals(len(response1), len(response2))
+ def test_update_interface_legacy(self):
+ api = disqusapi.DisqusAPI(self.API_SECRET, self.API_PUBLIC)
+ with self.assertRaises(disqusapi.InterfaceNotDefined):
+ api.interface.update(extra_interface)
+
+ def test_update_interface(self):
+ api = disqusapi.DisqusAPI(self.API_SECRET, self.API_PUBLIC)
+ api.update_interface(extra_interface)
if __name__ == '__main__':
unittest.main()
|
Fixed recursion error when
disqus.interface.update(dict)
is used. Now throws InterfaceNotDefined expection.
disqus.update_interface(dict)
must be used now.
|
disqus_disqus-python
|
train
|
07047a024b0946bdc34c99947f5cd5c2687cd990
|
diff --git a/src/com/opencms/workplace/CmsDownloadBrowser.java b/src/com/opencms/workplace/CmsDownloadBrowser.java
index <HASH>..<HASH> 100644
--- a/src/com/opencms/workplace/CmsDownloadBrowser.java
+++ b/src/com/opencms/workplace/CmsDownloadBrowser.java
@@ -2,8 +2,8 @@ package com.opencms.workplace;
/*
* File : $Source: /alkacon/cvs/opencms/src/com/opencms/workplace/Attic/CmsDownloadBrowser.java,v $
- * Date : $Date: 2000/08/08 14:08:30 $
- * Version: $Revision: 1.9 $
+ * Date : $Date: 2001/01/10 10:11:20 $
+ * Version: $Revision: 1.10 $
*
* Copyright (C) 2000 The OpenCms Group
*
@@ -42,7 +42,7 @@ import javax.servlet.http.*;
* <P>
*
* @author Mario Stanke
- * @version $Revision: 1.9 $ $Date: 2000/08/08 14:08:30 $
+ * @version $Revision: 1.10 $ $Date: 2001/01/10 10:11:20 $
* @see com.opencms.workplace.CmsXmlWpTemplateFile
*/
public class CmsDownloadBrowser extends CmsWorkplaceDefault implements I_CmsFileListUsers {
@@ -160,7 +160,16 @@ public class CmsDownloadBrowser extends CmsWorkplaceDefault implements I_CmsFile
String servletPath = ((HttpServletRequest) cms.getRequestContext().getRequest().getOriginalRequest()).getServletPath();
String downloadPath = servletPath + res.getAbsolutePath();
filelistTemplate.setData("fullpath", downloadPath);
- filelistTemplate.setData("name_value", res.getName());
+ filelistTemplate.setData("name_value", res.getName());
+ String title="";
+ try {
+ title=cms.readProperty(res.getAbsolutePath(),C_PROPERTY_TITLE);
+ } catch (CmsException e) {
+ }
+ if (title==null) {
+ title="";
+ }
+ filelistTemplate.setData("title_value", title);
}
public Integer getDownGalleryNames(CmsObject cms, CmsXmlLanguageFile lang, Vector names, Vector values, Hashtable parameters)
throws CmsException {
@@ -300,7 +309,7 @@ public class CmsDownloadBrowser extends CmsWorkplaceDefault implements I_CmsFile
* @param cms Cms object for accessing system resources.
* @param prefs Old bit pattern.
* @return New modified bit pattern.
- * @see I_CmsFileListUsers
+ * @see I_CmsFileListUsers
*/
public int modifyDisplayedColumns(CmsObject cms, int prefs) {
// not display the following columns
@@ -310,6 +319,7 @@ public class CmsDownloadBrowser extends CmsWorkplaceDefault implements I_CmsFile
prefs = ((prefs & C_FILELIST_GROUP) == 0) ? prefs : (prefs - C_FILELIST_GROUP);
prefs = ((prefs & C_FILELIST_ACCESS) == 0) ? prefs : (prefs - C_FILELIST_ACCESS);
prefs = ((prefs & C_FILELIST_STATE) == 0) ? prefs : (prefs - C_FILELIST_STATE);
+ prefs = ((prefs & C_FILELIST_LOCKED) == 0) ? prefs : (prefs - C_FILELIST_LOCKED);
return prefs;
}
/**
|
bugfix: in the window downloadlist the titel was not displayed.
|
alkacon_opencms-core
|
train
|
73e6006e532c802435516494e0a78ae1dc023645
|
diff --git a/src/flapjack/resources/base.py b/src/flapjack/resources/base.py
index <HASH>..<HASH> 100644
--- a/src/flapjack/resources/base.py
+++ b/src/flapjack/resources/base.py
@@ -574,7 +574,7 @@ class Base(six.with_metaclass(meta.Resource)):
# could easily be an iterable.
return [self.item_prepare(x) for x in obj]
- except TypeError:
+ except TypeError as ex:
pass
# Just prepare the one item.
@@ -597,11 +597,11 @@ class Base(six.with_metaclass(meta.Resource)):
def item_prepare(self, original):
# Initialize the item object; we like to remember the order of the
# fields.
- if not isinstance(original, Mapping):
- item = vars(original)
+ #if not isinstance(original, Sequence) and not isinstance(original, Mapping):
+ # item = vars(original)
- else:
- item = original
+ #else:
+ item = original
obj = OrderedDict()
@@ -617,14 +617,15 @@ class Base(six.with_metaclass(meta.Resource)):
# TODO: If we can refactor to avoid this ONE getattr call; speed
# of execution goes up by a factor of 10
- # try:
- # # Attempt to grab this field from the item.
- # value = getattr(item, name)
-
- # except:
- # try:
- # Maybe we have a dictionary
- value = item.get(name)
+ try:
+ # Attempt to grab this field from the item.
+ value = getattr(item, name)
+
+ except AttributeError:
+ # try:
+ # Maybe we have a dictionary
+ value = item.get(name)
+ # print(value)
# except:
# # Something fun happened here.. ?
|
removed naive optimizations that were breaking the test case. Byebye!
|
armet_python-armet
|
train
|
c16cc1e0764ef30d90524041278f24314484b25a
|
diff --git a/src/Tomahawk/Auth/Handlers/EloquentAuthHandler.php b/src/Tomahawk/Auth/Handlers/EloquentAuthHandler.php
index <HASH>..<HASH> 100644
--- a/src/Tomahawk/Auth/Handlers/EloquentAuthHandler.php
+++ b/src/Tomahawk/Auth/Handlers/EloquentAuthHandler.php
@@ -8,17 +8,26 @@ use Tomahawk\Hashing\HasherInterface;
class EloquentAuthHandler implements AuthHandlerInterface
{
+ /**
+ * @var string
+ */
protected $model;
+
/**
* @var \Tomahawk\Hashing\HasherInterface
*/
protected $hasher;
+ /**
+ * @var string
+ */
+ protected $passwordField;
- public function __construct(HasherInterface $hasher, $model)
+ public function __construct(HasherInterface $hasher, $model, $passwordField = null)
{
$this->hasher = $hasher;
$this->model = $model;
+ $this->passwordField = $passwordField ?: 'password';
}
/**
@@ -40,14 +49,12 @@ class EloquentAuthHandler implements AuthHandlerInterface
*/
public function retrieveByCredentials(array $credentials)
{
- // First we will add each credential element to the query as a where clause.
- // Then we can execute the query and, if we found a user, return it in a
- // Eloquent User "model" that will be utilized by the Guard instances.
$query = $this->createModel()->newQuery();
- foreach ($credentials as $key => $value)
- {
- if ( ! str_contains($key, 'password')) $query->where($key, $value);
+ foreach ($credentials as $key => $value) {
+ if ($key !== $this->passwordField) {
+ $query->where($key, $value);
+ }
}
return $query->first();
@@ -62,7 +69,7 @@ class EloquentAuthHandler implements AuthHandlerInterface
*/
public function validateCredentials(UserInterface $user, array $credentials)
{
- $plain = $credentials['password'];
+ $plain = $credentials[$this->passwordField];
return $this->hasher->check($plain, $user->getAuthPassword());
}
|
Dont assume password and set a default if none is passed
|
tomahawkphp_framework
|
train
|
3e4a26136bf8f702825dd6686f1bd6b62b494e09
|
diff --git a/Tests/Fixtures/Connectors/Clients/FakeClientTrait.php b/Tests/Fixtures/Connectors/Clients/FakeClientTrait.php
index <HASH>..<HASH> 100644
--- a/Tests/Fixtures/Connectors/Clients/FakeClientTrait.php
+++ b/Tests/Fixtures/Connectors/Clients/FakeClientTrait.php
@@ -45,7 +45,8 @@ trait FakeClientTrait
protected function getResponseFromCache($resource, $suffix = null)
{
- $fixturePath = $this->fileLocator->locate($this->cacheDir . DIRECTORY_SEPARATOR . $resource . (($suffix)? '.' . $suffix : null));
+ $file = $this->cacheDir . DIRECTORY_SEPARATOR . $resource . (($suffix)? '.' . $suffix : null);
+ $fixturePath = $this->fileLocator->locate($file);
return file_get_contents($fixturePath);
}
diff --git a/Tests/Fixtures/Connectors/Clients/FakeRestClient.php b/Tests/Fixtures/Connectors/Clients/FakeRestClient.php
index <HASH>..<HASH> 100644
--- a/Tests/Fixtures/Connectors/Clients/FakeRestClient.php
+++ b/Tests/Fixtures/Connectors/Clients/FakeRestClient.php
@@ -79,12 +79,14 @@ class FakeRestClient extends Client
[
'status' => $response->getStatusCode(),
'headers' => $response->getHeaders(),
- 'body' => $response->getBody(),
+ 'body' => $response->getBody()->getContents(),
'version' => $response->getProtocolVersion(),
'reason' => $response->getReasonPhrase(),
]
);
+ $response->getBody()->rewind();
+
$this->trait_setResponseInCache($resource, $content, $suffix);
}
}
\ No newline at end of file
diff --git a/Tests/Fixtures/Connectors/Clients/FakeSoapClient.php b/Tests/Fixtures/Connectors/Clients/FakeSoapClient.php
index <HASH>..<HASH> 100644
--- a/Tests/Fixtures/Connectors/Clients/FakeSoapClient.php
+++ b/Tests/Fixtures/Connectors/Clients/FakeSoapClient.php
@@ -38,7 +38,7 @@ class FakeSoapClient extends \SoapClient
$actionName = md5($location) . '_' . $this->actionName;
try {
- $response = $this->getResponseFromCache($actionName . self::CACHE_SUFFIX);
+ $response = $this->getResponseFromCache($actionName, self::CACHE_SUFFIX);
} catch (\InvalidArgumentException $e) {
$response = parent::__doRequest($request, $location, $action, $version, $one_way);
|
Bug fixes and update of README file
|
smartboxgroup_integration-framework-bundle
|
train
|
e7592d543321e1db17d27bad4856247d6b5bf2ff
|
diff --git a/web/concrete/blocks/content/edit.php b/web/concrete/blocks/content/edit.php
index <HASH>..<HASH> 100644
--- a/web/concrete/blocks/content/edit.php
+++ b/web/concrete/blocks/content/edit.php
@@ -5,5 +5,5 @@ $bt->inc('editor_init.php');
?>
<div style="text-align: center" id="ccm-editor-pane">
-<textarea id="ccm-content-<?=$b->getBlockID()?>-<?=$a->getAreaID()?>" class="advancedEditor ccm-advanced-editor" name="content" style="width: 580px; height: 380px"><?=$controller->getContentEditMode()?></textarea>
+<textarea id="ccm-content-<?=$b->getBlockID()?>-<?=$a->getAreaID()?>" class="advancedEditor ccm-advanced-editor" name="content" style="width: 580px; height: 380px"><?=htmlspecialchars($controller->getContentEditMode())?></textarea>
</div>
\ No newline at end of file
|
Fixed editing content
The html code inside the textarea should be escaped (for example, if you have a textarea inside the html the editor gets broked, since the editor textarea is ended by the </textarea> of the content).
Former-commit-id: bcb<I>ce<I>e1a<I>b7b1fde<I>e7cbcb<I>c<I>
|
concrete5_concrete5
|
train
|
c522c994cd162bc42d987e2ebb08f3d0a2b6f644
|
diff --git a/lib/client.js b/lib/client.js
index <HASH>..<HASH> 100644
--- a/lib/client.js
+++ b/lib/client.js
@@ -14,6 +14,7 @@ const {
InvalidArgumentError,
RequestAbortedError,
ClientDestroyedError,
+ ClientClosedError,
HeadersTimeoutError,
SocketError,
InformationalError,
@@ -241,6 +242,14 @@ class Client extends EventEmitter {
}
[kEnqueue] (request) {
+ if (this[kDestroyed]) {
+ throw new ClientDestroyedError()
+ }
+
+ if (this[kClosed]) {
+ throw new ClientClosedError()
+ }
+
this[kQueue].push(request)
if (this[kResuming]) {
// Do nothing.
|
fix: add destroyed & closed check to enqueue
|
mcollina_undici
|
train
|
f310397f045d0c2b0b69506fd469ee65d83e6232
|
diff --git a/db/rdb/src/main/java/it/unibz/inf/ontop/model/term/functionsymbol/db/impl/PostgreSQLDBFunctionSymbolFactory.java b/db/rdb/src/main/java/it/unibz/inf/ontop/model/term/functionsymbol/db/impl/PostgreSQLDBFunctionSymbolFactory.java
index <HASH>..<HASH> 100644
--- a/db/rdb/src/main/java/it/unibz/inf/ontop/model/term/functionsymbol/db/impl/PostgreSQLDBFunctionSymbolFactory.java
+++ b/db/rdb/src/main/java/it/unibz/inf/ontop/model/term/functionsymbol/db/impl/PostgreSQLDBFunctionSymbolFactory.java
@@ -54,10 +54,6 @@ public class PostgreSQLDBFunctionSymbolFactory extends AbstractSQLDBFunctionSymb
ImmutableTable.Builder<DBTermType, RDFDatatype, DBTypeConversionFunctionSymbol> builder = ImmutableTable.builder();
builder.putAll(super.createNormalizationTable());
- // BOOL
- DBTermType boolType = dbTypeFactory.getDBTermType(BOOL_STR);
- builder.put(boolType, typeFactory.getXsdBooleanDatatype(), createBooleanNormFunctionSymbol(boolType));
-
//TIMESTAMP
DBTermType timeStamp = dbTypeFactory.getDBTermType(TIMESTAMP_STR);
RDFDatatype xsdDatetime = typeFactory.getXsdDatetimeDatatype();
@@ -148,7 +144,7 @@ public class PostgreSQLDBFunctionSymbolFactory extends AbstractSQLDBFunctionSymb
public DBFunctionSymbol getDBSubString3() {
return getRegularDBFunctionSymbol(SUBSTR_STR, 3);
}
-
+
@Override
public NonDeterministicDBFunctionSymbol getDBUUID(UUID uuid) {
return new DefaultNonDeterministicNullaryFunctionSymbol(UUID_STR, uuid, dbStringType,
|
bool and boolean unified to boolean
|
ontop_ontop
|
train
|
d53e3298c08fd37d0e0bd8e1bc6777b09471189e
|
diff --git a/backup/moodle2/restore_course_task.class.php b/backup/moodle2/restore_course_task.class.php
index <HASH>..<HASH> 100644
--- a/backup/moodle2/restore_course_task.class.php
+++ b/backup/moodle2/restore_course_task.class.php
@@ -133,6 +133,26 @@ class restore_course_task extends restore_task {
$startdate->set_ui(new backup_setting_ui_dateselector($startdate, get_string('setting_course_startdate', 'backup')));
$this->add_setting($startdate);
+ $purge_enrols = new restore_course_generic_setting('keep_roles_and_enrolments', base_setting::IS_BOOLEAN, false);
+ $purge_enrols->set_ui(new backup_setting_ui_select($purge_enrols, $purge_enrols->get_name(), array(1=>get_string('yes'), 0=>get_string('no'))));
+ $purge_enrols->get_ui()->set_label(get_string('setting_keep_roles_and_enrolments', 'backup'));
+ if ($this->get_target() != backup::TARGET_CURRENT_DELETING and $this->get_target() != backup::TARGET_EXISTING_DELETING) {
+ $purge_enrols->set_value(false);
+ $purge_enrols->set_status(backup_setting::LOCKED_BY_CONFIG);
+ $purge_enrols->set_visibility(backup_setting::HIDDEN);
+ }
+ $this->add_setting($purge_enrols);
+
+ $purge_groups = new restore_course_generic_setting('keep_groups_and_groupings', base_setting::IS_BOOLEAN, false);
+ $purge_groups->set_ui(new backup_setting_ui_select($purge_groups, $purge_groups->get_name(), array(1=>get_string('yes'), 0=>get_string('no'))));
+ $purge_groups->get_ui()->set_label(get_string('setting_keep_groups_and_groupings', 'backup'));
+ if ($this->get_target() != backup::TARGET_CURRENT_DELETING and $this->get_target() != backup::TARGET_EXISTING_DELETING) {
+ $purge_groups->set_value(false);
+ $purge_groups->set_status(backup_setting::LOCKED_BY_CONFIG);
+ $purge_groups->set_visibility(backup_setting::HIDDEN);
+ }
+ $this->add_setting($purge_groups);
+
// Define overwrite_conf to decide if course configuration will be restored over existing one
$overwrite = new restore_course_overwrite_conf_setting('overwrite_conf', base_setting::IS_BOOLEAN, false);
$overwrite->set_ui(new backup_setting_ui_select($overwrite, $overwrite->get_name(), array(1=>get_string('yes'), 0=>get_string('no'))));
diff --git a/backup/util/dbops/restore_dbops.class.php b/backup/util/dbops/restore_dbops.class.php
index <HASH>..<HASH> 100644
--- a/backup/util/dbops/restore_dbops.class.php
+++ b/backup/util/dbops/restore_dbops.class.php
@@ -1354,10 +1354,11 @@ abstract class restore_dbops {
/**
* Deletes all of the content associated with the given course (courseid)
* @param int $courseid
+ * @param array $options
* @return bool True for success
*/
- public static function delete_course_content($courseid) {
- return remove_course_contents($courseid, false);
+ public static function delete_course_content($courseid, array $options = null) {
+ return remove_course_contents($courseid, false, $options);
}
}
diff --git a/backup/util/ui/restore_ui.class.php b/backup/util/ui/restore_ui.class.php
index <HASH>..<HASH> 100644
--- a/backup/util/ui/restore_ui.class.php
+++ b/backup/util/ui/restore_ui.class.php
@@ -139,7 +139,10 @@ class restore_ui extends base_ui {
throw new restore_ui_exception('restoreuifinalisedbeforeexecute');
}
if ($this->controller->get_target() == backup::TARGET_CURRENT_DELETING || $this->controller->get_target() == backup::TARGET_EXISTING_DELETING) {
- restore_dbops::delete_course_content($this->controller->get_courseid());
+ $options = array();
+ $options['keep_roles_and_enrolments'] = $this->get_setting_value('keep_roles_and_enrolments');
+ $options['keep_groups_and_groupings'] = $this->get_setting_value('keep_groups_and_groupings');
+ restore_dbops::delete_course_content($this->controller->get_courseid(), $options);
}
$this->controller->execute_plan();
$this->progress = self::PROGRESS_EXECUTED;
diff --git a/lang/en/backup.php b/lang/en/backup.php
index <HASH>..<HASH> 100644
--- a/lang/en/backup.php
+++ b/lang/en/backup.php
@@ -220,5 +220,7 @@ $string['setting_overwriteconf'] = 'Overwrite course configuration';
$string['setting_course_fullname'] = 'Course name';
$string['setting_course_shortname'] = 'Course short name';
$string['setting_course_startdate'] = 'Course startdate';
+$string['setting_keep_roles_and_enrolments'] = 'Keep current roles and enrolments';
+$string['setting_keep_groups_and_groupings'] = 'Keep current groups and groupings';
$string['totalcategorysearchresults'] = 'Total categories: {$a}';
$string['totalcoursesearchresults'] = 'Total courses: {$a}';
|
MDL-<I> add new options to keep enrols and groups purging existing course in restore
|
moodle_moodle
|
train
|
74a30d804a45d6b83322738215470f375b05fd1c
|
diff --git a/lib/bitly/utils.rb b/lib/bitly/utils.rb
index <HASH>..<HASH> 100644
--- a/lib/bitly/utils.rb
+++ b/lib/bitly/utils.rb
@@ -16,8 +16,6 @@ module Bitly
def attr_define(k,v)
instance_variable_set("@#{k}", v)
- meta = class << self; self; end
- meta.class_eval { attr_reader k.to_sym }
end
def instance_variablise(obj,variables)
|
Fixes warnings for redefining methods.
Turns out the URL class used this, but declared it's attr_readers up front, so there's no need to redefine them here.
|
philnash_bitly
|
train
|
59a8be3875ffa9dc280e1f760d8415d97e06ec21
|
diff --git a/core/src/main/java/io/undertow/protocols/http2/HpackEncoder.java b/core/src/main/java/io/undertow/protocols/http2/HpackEncoder.java
index <HASH>..<HASH> 100644
--- a/core/src/main/java/io/undertow/protocols/http2/HpackEncoder.java
+++ b/core/src/main/java/io/undertow/protocols/http2/HpackEncoder.java
@@ -163,6 +163,10 @@ public class HpackEncoder {
skip = true;
}
}
+ if(values.getHeaderName().equals(Headers.TRANSFER_ENCODING)) {
+ //ignore transfer-encoding, it is forbidden by the spec
+ skip = true;
+ }
if (!skip) {
for (int i = 0; i < values.size(); ++i) {
diff --git a/core/src/main/java/io/undertow/protocols/http2/HpackException.java b/core/src/main/java/io/undertow/protocols/http2/HpackException.java
index <HASH>..<HASH> 100644
--- a/core/src/main/java/io/undertow/protocols/http2/HpackException.java
+++ b/core/src/main/java/io/undertow/protocols/http2/HpackException.java
@@ -36,6 +36,10 @@ public class HpackException extends Exception {
this.closeCode = closeCode;
}
+ public HpackException(int closeCode) {
+ this.closeCode = closeCode;
+ }
+
public int getCloseCode() {
return closeCode;
}
diff --git a/core/src/main/java/io/undertow/protocols/http2/Http2HeaderBlockParser.java b/core/src/main/java/io/undertow/protocols/http2/Http2HeaderBlockParser.java
index <HASH>..<HASH> 100644
--- a/core/src/main/java/io/undertow/protocols/http2/Http2HeaderBlockParser.java
+++ b/core/src/main/java/io/undertow/protocols/http2/Http2HeaderBlockParser.java
@@ -29,6 +29,7 @@ import io.undertow.UndertowLogger;
import io.undertow.UndertowMessages;
import io.undertow.util.HeaderMap;
+import io.undertow.util.Headers;
import io.undertow.util.HttpString;
/**
@@ -133,6 +134,9 @@ abstract class Http2HeaderBlockParser extends Http2PushBackParser implements Hpa
if(name.length() == 0) {
throw UndertowMessages.MESSAGES.invalidHeader();
}
+ if(name.equals(Headers.TRANSFER_ENCODING)) {
+ throw new HpackException(Http2Channel.ERROR_PROTOCOL_ERROR);
+ }
if(name.byteAt(0) == ':') {
if(client) {
if(!name.equals(Http2Channel.STATUS)) {
|
UNDERTOW-<I> Ignore transfer-encoding header if it is present in HTTP/2
|
undertow-io_undertow
|
train
|
5d8d7fd8ee5222d9f3fc5f5b606c8a1c94194b0b
|
diff --git a/lib/hanami/utils/basic_object.rb b/lib/hanami/utils/basic_object.rb
index <HASH>..<HASH> 100644
--- a/lib/hanami/utils/basic_object.rb
+++ b/lib/hanami/utils/basic_object.rb
@@ -4,6 +4,23 @@ module Hanami
#
# @since 0.3.5
class BasicObject < ::BasicObject
+ # Lookup constants at the top-level namespace, if they are missing in the
+ # current context.
+ #
+ # @param name [Symbol] the constant name
+ #
+ # @return [Object, Module] the constant
+ #
+ # @raises [NameError] if the constant cannot be found
+ #
+ # @since x.x.x
+ # @api private
+ #
+ # @see https://ruby-doc.org/core/Module.html#method-i-const_missing
+ def self.const_missing(name)
+ ::Object.const_get(name)
+ end
+
# Return the class for debugging purposes.
#
# @since 0.3.5
diff --git a/spec/unit/hanami/utils/basic_object_spec.rb b/spec/unit/hanami/utils/basic_object_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/unit/hanami/utils/basic_object_spec.rb
+++ b/spec/unit/hanami/utils/basic_object_spec.rb
@@ -1,10 +1,32 @@
require 'hanami/utils/basic_object'
require 'pp'
+class ExternalTestClass
+end
+
class TestClass < Hanami::Utils::BasicObject
+ class InternalTestClass
+ end
+
+ def internal
+ InternalTestClass
+ end
+
+ def external
+ ExternalTestClass
+ end
end
RSpec.describe Hanami::Utils::BasicObject do
+ describe '.const_missing' do
+ subject { TestClass.new }
+
+ it 'lookups constants at the top-level namespace' do
+ expect(subject.internal).to eq(TestClass::InternalTestClass)
+ expect(subject.external).to eq(ExternalTestClass)
+ end
+ end
+
describe '#respond_to_missing?' do
it 'raises an exception if respond_to? method is not implemented' do
expect { TestClass.new.respond_to?(:no_existing_method) }
|
Ensure `Utils::BasicObject` to lookup constants at the top-level namespace, if they are missing in the current context. (#<I>)
|
hanami_utils
|
train
|
1ddf5bfc5f44f98b60fe372b159eaeecc79ab62d
|
diff --git a/terraform/context.go b/terraform/context.go
index <HASH>..<HASH> 100644
--- a/terraform/context.go
+++ b/terraform/context.go
@@ -1415,7 +1415,9 @@ func (c *walkContext) computeVars(
case *config.CountVariable:
switch v.Type {
case config.CountValueIndex:
- vs[n] = strconv.FormatInt(int64(r.CountIndex), 10)
+ if r != nil {
+ vs[n] = strconv.FormatInt(int64(r.CountIndex), 10)
+ }
}
case *config.ModuleVariable:
value, err := c.computeModuleVariable(v)
|
terraform: guard against a nil resource
|
hashicorp_terraform
|
train
|
e6813f3f9d504681c390afaa6cf084670b1a5d5a
|
diff --git a/src/tagify.js b/src/tagify.js
index <HASH>..<HASH> 100644
--- a/src/tagify.js
+++ b/src/tagify.js
@@ -492,6 +492,7 @@ Tagify.prototype = {
var text = e.target ? e.target.textContent.trim() : '', // a string
_s = this.settings,
type = e.type,
+ eventData = {relatedTarget:e.relatedTarget},
shouldAddTags;
// goes into this scenario only on input "blur" and a tag was clicked
@@ -516,13 +517,19 @@ Tagify.prototype = {
this.setRangeAtStartEnd(false)
if( _s.mode == 'mix' ){
- if( e.type == "blur" )
- this.dropdown.hide.call(this)
+ if( type == "focus" ){
+ this.trigger("focus", eventData)
+ }
+ else if( e.type == "blur" ){
+ this.trigger("blur", eventData)
+ this.loading(false)
+ this.dropdown.hide.call(this)
+ }
return
}
if( type == "focus" ){
- this.trigger("focus", {relatedTarget:e.relatedTarget})
+ this.trigger("focus", eventData)
// e.target.classList.remove('placeholder');
if( _s.dropdown.enabled === 0 && _s.mode != "select" ){
this.dropdown.show.call(this)
@@ -531,7 +538,7 @@ Tagify.prototype = {
}
else if( type == "blur" ){
- this.trigger("blur", {relatedTarget:e.relatedTarget})
+ this.trigger("blur", eventData)
this.loading(false)
shouldAddTags = this.settings.mode == 'select'
|
fixes "focus" and "blur" events not triggered in mix-mode
|
yairEO_tagify
|
train
|
9f497f3a84f0fd6f17ec3cd7450dbe873dbe79fd
|
diff --git a/tests/test_parser.py b/tests/test_parser.py
index <HASH>..<HASH> 100644
--- a/tests/test_parser.py
+++ b/tests/test_parser.py
@@ -1563,8 +1563,8 @@ def foo(x: bytes <= 32) -> num:
success = False
print('Passed bytes_to_num tests')
-import rlp
def test_rlp_decoder_code():
+ import rlp
rlp_decoder_code = """
u: bytes <= 100
|
per @yograterol's suggestion
|
ethereum_vyper
|
train
|
d403936818b8785b65ff55ebab0d266b4a871ef6
|
diff --git a/daemon/execdriver/native/driver.go b/daemon/execdriver/native/driver.go
index <HASH>..<HASH> 100644
--- a/daemon/execdriver/native/driver.go
+++ b/daemon/execdriver/native/driver.go
@@ -178,7 +178,7 @@ func (d *driver) Terminate(p *execdriver.Command) error {
}
// TODO: Remove this part for version 1.2.0
// This is added only to ensure smooth upgrades from pre 1.1.0 to 1.1.0
- data, err := ioutil.ReadAll(filepath.Join(d.root, p.ID, "start"))
+ data, err := ioutil.ReadFile(filepath.Join(d.root, p.ID, "start"))
if err != nil {
// if we don't have the data on disk then we can assume the process is gone
// because this is only removed after we know the process has stopped
@@ -187,7 +187,7 @@ func (d *driver) Terminate(p *execdriver.Command) error {
}
return err
}
- state.InitStartTime = string(data)
+ state = &libcontainer.State{InitStartTime: string(data)}
}
currentStartTime, err := system.GetProcessStartTime(p.Process.Pid)
|
fix compilation and panic
Docker-DCO-<I>-
|
containers_storage
|
train
|
53195f701883b8e0309d3926cb5e1d2c26a4b3f5
|
diff --git a/neutronclient/v2_0/client.py b/neutronclient/v2_0/client.py
index <HASH>..<HASH> 100644
--- a/neutronclient/v2_0/client.py
+++ b/neutronclient/v2_0/client.py
@@ -451,27 +451,27 @@ class Client(ClientBase):
@APIParamsCall
def list_ext(self, collection, path, retrieve_all, **_params):
- """Client extension hook for lists."""
+ """Client extension hook for list."""
return self.list(collection, path, retrieve_all, **_params)
@APIParamsCall
def show_ext(self, path, id, **_params):
- """Client extension hook for shows."""
+ """Client extension hook for show."""
return self.get(path % id, params=_params)
@APIParamsCall
def create_ext(self, path, body=None):
- """Client extension hook for creates."""
+ """Client extension hook for create."""
return self.post(path, body=body)
@APIParamsCall
def update_ext(self, path, id, body=None):
- """Client extension hook for updates."""
+ """Client extension hook for update."""
return self.put(path % id, body=body)
@APIParamsCall
def delete_ext(self, path, id):
- """Client extension hook for deletes."""
+ """Client extension hook for delete."""
return self.delete(path % id)
@APIParamsCall
@@ -501,24 +501,24 @@ class Client(ClientBase):
@APIParamsCall
def list_extensions(self, **_params):
- """Fetch a list of all exts on server side."""
+ """Fetch a list of all extensions on server side."""
return self.get(self.extensions_path, params=_params)
@APIParamsCall
def show_extension(self, ext_alias, **_params):
- """Fetch a list of all exts on server side."""
+ """Fetches information of a certain extension."""
return self.get(self.extension_path % ext_alias, params=_params)
@APIParamsCall
def list_ports(self, retrieve_all=True, **_params):
- """Fetches a list of all networks for a tenant."""
+ """Fetches a list of all ports for a tenant."""
# Pass filters in "params" argument to do_request
return self.list('ports', self.ports_path, retrieve_all,
**_params)
@APIParamsCall
def show_port(self, port, **_params):
- """Fetches information of a certain network."""
+ """Fetches information of a certain port."""
return self.get(self.port_path % (port), params=_params)
@APIParamsCall
@@ -565,7 +565,7 @@ class Client(ClientBase):
@APIParamsCall
def list_subnets(self, retrieve_all=True, **_params):
- """Fetches a list of all networks for a tenant."""
+ """Fetches a list of all subnets for a tenant."""
return self.list('subnets', self.subnets_path, retrieve_all,
**_params)
@@ -1419,7 +1419,7 @@ class Client(ClientBase):
@APIParamsCall
def list_firewalls(self, retrieve_all=True, **_params):
- """Fetches a list of all firewals for a tenant."""
+ """Fetches a list of all firewalls for a tenant."""
# Pass filters in "params" argument to do_request
return self.list('firewalls', self.firewalls_path, retrieve_all,
|
Fix typos in the docstrings
Fixed some typos in the docstrings for methods and corrected the
docstring for a method.
Change-Id: I<I>de<I>e<I>ec<I>d<I>c9e<I>f7c<I>
|
rackerlabs_rackspace-python-neutronclient
|
train
|
f6c792717fe44c7966ad12924ba4b3863f156d05
|
diff --git a/tests/automatic_karma.conf.js b/tests/automatic_karma.conf.js
index <HASH>..<HASH> 100644
--- a/tests/automatic_karma.conf.js
+++ b/tests/automatic_karma.conf.js
@@ -11,7 +11,7 @@ module.exports = function(config) {
'lib/lodash.js',
'lib/MockFirebase.js',
'../angularfire.js',
- 'unit/orderbypriority.spec.js'
+ 'unit/**/*.spec.js'
],
autoWatch: true,
diff --git a/tests/lib/MockFirebase.js b/tests/lib/MockFirebase.js
index <HASH>..<HASH> 100644
--- a/tests/lib/MockFirebase.js
+++ b/tests/lib/MockFirebase.js
@@ -258,14 +258,16 @@
},
transaction: function(valueFn, finishedFn, applyLocally) {
- var self = this;
var valueSpy = sinon.spy(valueFn);
var finishedSpy = sinon.spy(finishedFn);
this._defer(function() {
var err = this._nextErr('transaction');
- var res = valueSpy(self.getData());
- var newData = _.isUndefined(res) || err? this.data : res;
- finishedSpy(err, err === null && !_.isUndefined(res), makeSnap(self, newData));
+ // unlike most defer methods, this will use the value as it exists at the time
+ // the transaction is actually invoked, which is the eventual consistent value
+ // it would have in reality
+ var res = valueSpy(this.getData());
+ var newData = _.isUndefined(res) || err? this.getData() : res;
+ finishedSpy(err, err === null && !_.isUndefined(res), makeSnap(this, newData));
this._dataChanged(newData);
});
return [valueSpy, finishedSpy, applyLocally];
|
auto...conf.js: Reset conf to run all tests.
MockFirebase.js: minor cleanup
|
firebase_angularfire
|
train
|
ced877b2d3f28cf9922fdb2516804546b34f9ae3
|
diff --git a/src/Sylius/Bundle/OrderBundle/Controller/OrderItemController.php b/src/Sylius/Bundle/OrderBundle/Controller/OrderItemController.php
index <HASH>..<HASH> 100644
--- a/src/Sylius/Bundle/OrderBundle/Controller/OrderItemController.php
+++ b/src/Sylius/Bundle/OrderBundle/Controller/OrderItemController.php
@@ -72,7 +72,7 @@ class OrderItemController extends ResourceController
if ($request->isMethod('POST') && $form->submit($request)->isValid()) {
$newResource = $form->getData();
- $event = $this->eventDispatcher->dispatchPreEvent('sylius.cart_item.pre_create', $configuration, $newResource);
+ $event = $this->eventDispatcher->dispatchPreEvent(ResourceActions::CREATE, $configuration, $newResource);
if ($event->isStopped() && !$configuration->isHtmlRequest()) {
throw new HttpException($event->getErrorCode(), $event->getMessage());
@@ -90,6 +90,8 @@ class OrderItemController extends ResourceController
$cartManager->persist($cart);
$cartManager->flush();
+ $this->eventDispatcher->dispatchPostEvent(ResourceActions::CREATE, $configuration, $newResource);
+
if (!$configuration->isHtmlRequest()) {
return $this->viewHandler->handle($configuration, View::create($newResource, Response::HTTP_CREATED));
}
|
[OrderBundle] Fix Add-to-cart Pre-event
Add post event too
|
Sylius_Sylius
|
train
|
2c7aa2c8c10be115b79cbbbfb3b46c28e48ee647
|
diff --git a/app/Config/Autoload.php b/app/Config/Autoload.php
index <HASH>..<HASH> 100644
--- a/app/Config/Autoload.php
+++ b/app/Config/Autoload.php
@@ -50,9 +50,9 @@ class Autoload extends \CodeIgniter\Config\AutoloadConfig
* `];
*/
$psr4 = [
- 'Config' => APPPATH . 'Config',
- APP_NAMESPACE => APPPATH, // For custom namespace
'App' => APPPATH, // To ensure filters, etc still found,
+ APP_NAMESPACE => APPPATH, // For custom namespace
+ 'Config' => APPPATH . 'Config',
];
/**
diff --git a/system/Autoloader/FileLocator.php b/system/Autoloader/FileLocator.php
index <HASH>..<HASH> 100644
--- a/system/Autoloader/FileLocator.php
+++ b/system/Autoloader/FileLocator.php
@@ -287,10 +287,23 @@ class FileLocator
{
$namespaces = [];
+ // Save system for last
+ $system = null;
+
foreach ($this->autoloader->getNamespace() as $prefix => $paths)
{
foreach ($paths as $path)
{
+ if ($prefix === 'CodeIgniter')
+ {
+ $system = [
+ 'prefix' => $prefix,
+ 'path' => rtrim($path, '\\/') . DIRECTORY_SEPARATOR,
+ ];
+
+ continue;
+ }
+
$namespaces[] = [
'prefix' => $prefix,
'path' => rtrim($path, '\\/') . DIRECTORY_SEPARATOR,
@@ -298,6 +311,8 @@ class FileLocator
}
}
+ $namespaces[] = $system;
+
return $namespaces;
}
diff --git a/tests/system/Autoloader/FileLocatorTest.php b/tests/system/Autoloader/FileLocatorTest.php
index <HASH>..<HASH> 100644
--- a/tests/system/Autoloader/FileLocatorTest.php
+++ b/tests/system/Autoloader/FileLocatorTest.php
@@ -22,8 +22,8 @@ class FileLocatorTest extends \CIUnitTestCase
'Tests/Support' => TESTPATH . '_support/',
'App' => APPPATH,
'CodeIgniter' => [
- SYSTEMPATH,
TESTPATH,
+ SYSTEMPATH,
],
'Errors' => APPPATH . 'Views/errors',
'System' => SUPPORTPATH . 'Autoloader/system',
@@ -170,7 +170,6 @@ class FileLocatorTest extends \CIUnitTestCase
$this->assertContains($expected, $foundFiles);
$expected = SYSTEMPATH . 'index.html';
-
$this->assertContains($expected, $foundFiles);
}
diff --git a/tests/system/Language/LanguageTest.php b/tests/system/Language/LanguageTest.php
index <HASH>..<HASH> 100644
--- a/tests/system/Language/LanguageTest.php
+++ b/tests/system/Language/LanguageTest.php
@@ -221,7 +221,7 @@ class LanguageTest extends \CIUnitTestCase
$language = Services::language('en', false);
// this should load the replacement bundle of messages
$message = lang('Core.missingExtension', [], 'en');
- $this->assertEquals('{0} extension could not be found.', $message);
+ $this->assertEquals('{0} extension is not loaded.', $message);
// and we should have our new message too
$this->assertEquals('billions and billions', lang('Core.bazillion', [], 'en'));
}
|
Update ordering of search locations for better prioritization. Fixes #<I>
|
codeigniter4_CodeIgniter4
|
train
|
4b3b03a7116c3d8f27a992c7fbbe1f665a4de3e3
|
diff --git a/dagster/core/__init__.py b/dagster/core/__init__.py
index <HASH>..<HASH> 100644
--- a/dagster/core/__init__.py
+++ b/dagster/core/__init__.py
@@ -4,7 +4,7 @@ from builtins import * # pylint: disable=W0622,W0401
from dagster import check
from dagster.core import types
-from .definitions import InputDefinition
+from .definitions import InputDefinition, create_dagster_single_file_input
from .graph import DagsterPipeline
@@ -32,4 +32,4 @@ def create_json_input(name):
# context.metric('rows', df.shape[0])
return json_obj
- return create_dagster_json_input(name, check_path)
\ No newline at end of file
+ return create_dagster_single_file_input(name, check_path)
\ No newline at end of file
diff --git a/dagster/pandas_kernel/__init__.py b/dagster/pandas_kernel/__init__.py
index <HASH>..<HASH> 100644
--- a/dagster/pandas_kernel/__init__.py
+++ b/dagster/pandas_kernel/__init__.py
@@ -14,6 +14,9 @@ from .definitions import (
create_dagster_pd_dependency_input,
create_dagster_pd_parquet_output,
)
+from dagster.core import (
+ create_json_input
+)
def solid(**kwargs):
@@ -95,10 +98,11 @@ def single_path_arg(input_name, path):
def csv_input(name, delimiter=',', **read_csv_kwargs):
return create_dagster_pd_csv_input(name, delimiter, **read_csv_kwargs)
-
def csv_output():
return create_dagster_pd_csv_output()
+def json_input(name):
+ return create_json_input(name)
def parquet_output():
return create_dagster_pd_parquet_output()
|
Get json_input working
|
dagster-io_dagster
|
train
|
7d86de08768b3d8e64592a80b64f506a8f6ea895
|
diff --git a/addon-test-support/index.js b/addon-test-support/index.js
index <HASH>..<HASH> 100644
--- a/addon-test-support/index.js
+++ b/addon-test-support/index.js
@@ -11,9 +11,10 @@ export function setup(hooks) {
});
}
-export async function fastboot(url) {
+export async function fastboot(url, { headers = {} }) {
let encodedURL = encodeURIComponent(url);
- let endpoint = `/__fastboot-testing?url=${encodedURL}`;
+ let customHeaders = JSON.stringify(headers)
+ let endpoint = `/__fastboot-testing?url=${encodedURL}&headers=${customHeaders}`;
let response = await fetch(endpoint);
let result = await response.json();
@@ -25,8 +26,8 @@ export async function fastboot(url) {
return result;
}
-export async function visit(url) {
- let result = await fastboot(url);
+export async function visit(url, options = {}) {
+ let result = await fastboot(url, { headers: options.headers || {} });
document.querySelector('#ember-testing').innerHTML = result.body;
diff --git a/index.js b/index.js
index <HASH>..<HASH> 100644
--- a/index.js
+++ b/index.js
@@ -21,11 +21,11 @@ module.exports = {
_fastbootRenderingMiddleware(app) {
app.use('/__fastboot-testing', (req, res) => {
let urlToVisit = decodeURIComponent(req.query.url);
+ let customHeaders = JSON.parse(req.query.headers);
let parsed = url.parse(urlToVisit, true);
- let headers = Object.assign(req.headers, {
- host: 'ember-cli-fastboot-testing.localhost'
- });
+ let headers = Object.assign(req.headers, customHeaders)
+ headers.host = 'ember-cli-fastboot-testing.localhost';
let options = {
request: {
diff --git a/tests/fastboot/request-object-test.js b/tests/fastboot/request-object-test.js
index <HASH>..<HASH> 100644
--- a/tests/fastboot/request-object-test.js
+++ b/tests/fastboot/request-object-test.js
@@ -36,6 +36,18 @@ module('FastBoot | request object test', function(hooks) {
.includesText('user-agent: ');
});
+ test('it can override header in visit request', async function (assert) {
+ await visit('/request-object', {
+ headers: {
+ 'user-agent': 'ember-cli-fastboot-testing'
+ }
+ });
+
+ assert
+ .dom('[data-test-id=headers] [data-header-name=user-agent')
+ .includesText('user-agent: ember-cli-fastboot-testing');
+ });
+
test('it includes cookies in request headers', async function (assert) {
await visit('/request-object');
|
Add ability to override headers from test
|
embermap_ember-cli-fastboot-testing
|
train
|
0778972438895aeb16400b1d9caf47a3245e5d5c
|
diff --git a/server/container_create_linux.go b/server/container_create_linux.go
index <HASH>..<HASH> 100644
--- a/server/container_create_linux.go
+++ b/server/container_create_linux.go
@@ -470,13 +470,13 @@ func (s *Server) createSandboxContainer(ctx context.Context, ctr ctrIface.Contai
Destination: "/sys",
Type: "sysfs",
Source: "sysfs",
- Options: []string{"nosuid", "noexec", "nodev", "rw"},
+ Options: []string{"nosuid", "noexec", "nodev", "rw", "rslave"},
})
ctr.SpecAddMount(rspec.Mount{
Destination: "/sys/fs/cgroup",
Type: "cgroup",
Source: "cgroup",
- Options: []string{"nosuid", "noexec", "nodev", "rw", "relatime"},
+ Options: []string{"nosuid", "noexec", "nodev", "rw", "relatime", "rslave"},
})
}
|
server: mount cgroup with rslave
even when running as privileged container, prevent cgroup mounts to be
propagated to the host as it could cause errors when running with
rshared and systemd inside of the container.
Closes: <URL>
|
cri-o_cri-o
|
train
|
baa5323089a654e555df27bc60c164c55ad6475c
|
diff --git a/web/src/main/java/uk/ac/ebi/atlas/model/baseline/BaselineExpression.java b/web/src/main/java/uk/ac/ebi/atlas/model/baseline/BaselineExpression.java
index <HASH>..<HASH> 100644
--- a/web/src/main/java/uk/ac/ebi/atlas/model/baseline/BaselineExpression.java
+++ b/web/src/main/java/uk/ac/ebi/atlas/model/baseline/BaselineExpression.java
@@ -29,7 +29,6 @@ import com.esotericsoftware.kryo.io.Output;
import com.google.common.base.Objects;
import org.apache.commons.lang.ArrayUtils;
import uk.ac.ebi.atlas.model.Expression;
-import uk.ac.ebi.atlas.model.baseline.impl.FactorSet;
import java.text.DecimalFormat;
import java.text.NumberFormat;
@@ -43,7 +42,8 @@ public class BaselineExpression implements Expression, KryoSerializable {
private double[] quartiles;
public static final NumberFormat FOUR_DP = new DecimalFormat("0.####");
- public BaselineExpression() {}
+ // No-arg constructor required by Kryo. Can be private because Kryo uses reflection.
+ private BaselineExpression() {}
public BaselineExpression(double level, FactorGroup factorGroup) {
this(level, factorGroup, new double[]{});
diff --git a/web/src/main/java/uk/ac/ebi/atlas/model/baseline/impl/FactorSet.java b/web/src/main/java/uk/ac/ebi/atlas/model/baseline/impl/FactorSet.java
index <HASH>..<HASH> 100644
--- a/web/src/main/java/uk/ac/ebi/atlas/model/baseline/impl/FactorSet.java
+++ b/web/src/main/java/uk/ac/ebi/atlas/model/baseline/impl/FactorSet.java
@@ -36,7 +36,8 @@ public class FactorSet implements FactorGroup {
private Map<String, Factor> factorsByType = new HashMap<>();
- public FactorSet() {}
+ // No-arg constructor required by Kryo. Can be private because Kryo uses reflection.
+ private FactorSet() {}
FactorSet(Map<String, Factor> factorsByType) {
this.factorsByType = factorsByType;
@@ -185,4 +186,5 @@ public class FactorSet implements FactorGroup {
public boolean containsOnlyOrganism() {
return size() == 1 && getFactorByType("ORGANISM") != null;
}
+
}
|
#<I> Read baseline expression data from binary files instead of TSV files - Make no-arg constructors private
|
ebi-gene-expression-group_atlas
|
train
|
963aa593166ba1f72da1a154923dedb5f447e495
|
diff --git a/mpd.py b/mpd.py
index <HASH>..<HASH> 100644
--- a/mpd.py
+++ b/mpd.py
@@ -532,9 +532,11 @@ class MPDClient(object):
def disconnect(self):
logger.info("Calling MPD disconnect()")
- if self._rfile is not None:
+ if (self._rfile is not None
+ and not isinstance(self._rfile, _NotConnected)):
self._rfile.close()
- if self._wfile is not None:
+ if (self._wfile is not None
+ and not isinstance(self._wfile, _NotConnected)):
self._wfile.close()
if self._sock is not None:
self._sock.close()
|
Allow to call the method disconnect, same when any connection is alive
|
Mic92_python-mpd2
|
train
|
9797d8a16680085bd80e23184547a7986647d2ea
|
diff --git a/ServerNode.js b/ServerNode.js
index <HASH>..<HASH> 100644
--- a/ServerNode.js
+++ b/ServerNode.js
@@ -39,8 +39,8 @@ ServerNode.prototype.createHTTPServer = function (options) {
filePath = './nodegame/nodegame-all-latest.js';
}
-
- var extname = path.extname(filePath);
+ // Added path.normalize here. TODO: Check if it works on windows.
+ var extname = path.extname(path.normalize(filePath));
console.log(filePath);
|
HTTP server should work on Windows as well now
|
nodeGame_nodegame-server
|
train
|
42acdad20cab59022992b2b3de5641ab0e6fa2ee
|
diff --git a/test/integration/datastore/sync_methods/inject.test.js b/test/integration/datastore/sync_methods/inject.test.js
index <HASH>..<HASH> 100644
--- a/test/integration/datastore/sync_methods/inject.test.js
+++ b/test/integration/datastore/sync_methods/inject.test.js
@@ -214,4 +214,58 @@ describe('DS.inject(resourceName, attrs[, options])', function () {
assert.equal(2, DS.get('user', 1).comments.length);
});
+ it('should inject cyclic dependencies', function () {
+ DS.defineResource({
+ name: 'foo',
+ relations: {
+ hasMany: {
+ foo: {
+ localField: 'children',
+ foreignKey: 'parentId'
+ }
+ }
+ }
+ });
+ var injected = DS.inject('foo', [{
+ id: 1,
+ children: [
+ {
+ id: 2,
+ parentId: 1,
+ children: [
+ {
+ id: 4,
+ parentId: 2
+ },
+ {
+ id: 5,
+ parentId: 2
+ }
+ ]
+ },
+ {
+ id: 3,
+ parentId: 1,
+ children: [
+ {
+ id: 6,
+ parentId: 3
+ },
+ {
+ id: 7,
+ parentId: 3
+ }
+ ]
+ }
+ ]
+ }]);
+
+ assert.equal(injected[0].id, 1);
+ assert.equal(injected[0].children[0].id, 2);
+ assert.equal(injected[0].children[1].id, 3);
+ assert.equal(injected[0].children[0].children[0].id, 4);
+ assert.equal(injected[0].children[0].children[1].id, 5);
+ assert.equal(injected[0].children[1].children[0].id, 6);
+ assert.equal(injected[0].children[1].children[1].id, 7);
+ });
});
|
Added test for cyclic dependencies
|
js-data_js-data-angular
|
train
|
57b21a330e22ed8a3fc2e34c9f80b8ac55d7e68f
|
diff --git a/parsl/app/bash.py b/parsl/app/bash.py
index <HASH>..<HASH> 100644
--- a/parsl/app/bash.py
+++ b/parsl/app/bash.py
@@ -1,13 +1,12 @@
import logging
-
+from functools import update_wrapper
from inspect import signature, Parameter
+
from parsl.app.errors import wrap_error
from parsl.app.futures import DataFuture
from parsl.app.app import AppBase
from parsl.dataflow.dflow import DataFlowKernelLoader
-from functools import update_wrapper
-
logger = logging.getLogger(__name__)
@@ -152,7 +151,6 @@ class BashApp(AppBase):
else:
dfk = self.data_flow_kernel
-
app_fut = dfk.submit(wrap_error(update_wrapper(remote_side_bash_executor, self.func)),
self.func, *args,
executors=self.executors,
|
Clean up imports, fix flake8
|
Parsl_parsl
|
train
|
bf38a924da439a966d8c13d7e38519d79a44fe53
|
diff --git a/README.md b/README.md
index <HASH>..<HASH> 100644
--- a/README.md
+++ b/README.md
@@ -19,6 +19,8 @@ For OAuth applications. The shop domain, API key, API secret, and an access toke
#### Quick run-down
```php
+use TylerKing\BasicShopifyAPI;
+
$api = new BasicShopifyAPI;
$api->setShop('example.myshopify.com');
$api->setApiKey('your key here');
@@ -43,7 +45,9 @@ $api->setApiKey($app['config']->shopify_api_key);
$code = $request->query->get('code');
if (! $code) {
# No code, send user to authorize screen
- header('Location: ' . $api->getAuthUrl());
+ # Pass your scopes as an array for the first argument
+ # Pass your redirect URI as the second argument
+ header('Location: ' . $api->getAuthUrl($app['config']->shopify_scopes, $app['config']->shopify_redirect_uri));
exit;
} else {
# We now have a code, lets grab the access token
diff --git a/src/TylerKing/BasicShopifyAPI.php b/src/TylerKing/BasicShopifyAPI.php
index <HASH>..<HASH> 100644
--- a/src/TylerKing/BasicShopifyAPI.php
+++ b/src/TylerKing/BasicShopifyAPI.php
@@ -62,16 +62,12 @@ class BasicShopifyAPI {
return $this;
}
- public function getInstallUrl() {
- return "{$this->getBaseUrl()}/admin/api/auth?api_key={$this->api_key}";
- }
-
public function getAuthUrl($scopes, $redirect_uri) {
if (is_array($scopes)) {
$scopes = implode(',', $scopes);
}
- return "{$this->getBaseUrl()}/admin/oauth/authorize?client_id={$this->api_key}&scopes={$scopes}&redirect_uri={$redirect_uri}";
+ return "{$this->getBaseUrl()}/admin/oauth/authorize?client_id={$this->api_key}&scope={$scopes}&redirect_uri={$redirect_uri}";
}
public function verifyRequest($params) {
diff --git a/test/test.php b/test/test.php
index <HASH>..<HASH> 100644
--- a/test/test.php
+++ b/test/test.php
@@ -132,19 +132,6 @@ class BasicShopifyAPITest extends \PHPUnit_Framework_TestCase
/**
* @test
- *
- * Should get auth URL containing shop and API key
- */
- function itShouldGetgetInstallUrl() {
- $api = new BasicShopifyAPI;
- $api->setShop('example.myshopify.com');
- $api->setApiKey('123');
-
- $this->assertEquals('https://example.myshopify.com/admin/api/auth?api_key=123', $api->getInstallUrl());
- }
-
- /**
- * @test
* @expectedException Exception
* @expectedExceptionMessage Shopify domain missing for API calls
*
@@ -152,7 +139,7 @@ class BasicShopifyAPITest extends \PHPUnit_Framework_TestCase
*/
function itShouldThrowExceptionForMissingShopifyDomain() {
$api = new BasicShopifyAPI;
- $api->getInstallUrl();
+ $api->getAuthUrl(['read_products', 'write_products'], 'https://localapp.local/');
}
/**
@@ -164,7 +151,7 @@ class BasicShopifyAPITest extends \PHPUnit_Framework_TestCase
*/
function itShouldThrowExceptionForMissingApiDetails() {
$api = new BasicShopifyAPI(true);
- $api->getInstallUrl();
+ $api->getAuthUrl(['read_products', 'write_products'], 'https://localapp.local/');
}
/**
@@ -231,7 +218,7 @@ class BasicShopifyAPITest extends \PHPUnit_Framework_TestCase
$api->setApiKey('123');
$this->assertEquals(
- 'https://example.myshopify.com/admin/oauth/authorize?client_id=123&scopes=read_products,write_products&redirect_uri=https://localapp.local/',
+ 'https://example.myshopify.com/admin/oauth/authorize?client_id=123&scope=read_products,write_products&redirect_uri=https://localapp.local/',
$api->getAuthUrl(['read_products', 'write_products'], 'https://localapp.local/')
);
}
|
Update to remove install URL as its not needed. Fix for scopes and updated tests
|
ohmybrew_Basic-Shopify-API
|
train
|
39705febc2c90ea8a2fc61ad3e47458eeffe0e75
|
diff --git a/azurerm/resource_arm_servicebus_namespace.go b/azurerm/resource_arm_servicebus_namespace.go
index <HASH>..<HASH> 100644
--- a/azurerm/resource_arm_servicebus_namespace.go
+++ b/azurerm/resource_arm_servicebus_namespace.go
@@ -195,12 +195,7 @@ func resourceArmServiceBusNamespaceDelete(d *schema.ResourceData, meta interface
resourceGroup := id.ResourceGroup
name := id.Path["namespaces"]
- deleteResp, err := client.Delete(ctx, resourceGroup, name)
- if err != nil {
- return err
- }
-
- err = deleteResp.WaitForCompletion(ctx, client.Client)
+ _, err = client.Delete(ctx, resourceGroup, name)
if err != nil {
return err
}
|
ServiceBus Namespaces apparently aren't actually long polling
|
terraform-providers_terraform-provider-azurerm
|
train
|
833f231dbb3c0b25298c22e58e1a9c40065a9e65
|
diff --git a/examples/ex3.rb b/examples/ex3.rb
index <HASH>..<HASH> 100644
--- a/examples/ex3.rb
+++ b/examples/ex3.rb
@@ -1,8 +1,7 @@
-(wav = WavOut.new("ex3.wav")) >> blackhole
-(s = SinOsc.new(440, 0.5)) >> wav
-(s2 = SinOsc.new(3)) >> blackhole
+wav = WavOut.new("ex3.wav")
+s2 = SinOsc.new(3)
+s = SinOsc.new(L{ s2.last * 220 + 660 }, L{ 0.5 + s2.last * 0.5 })
-s.gain = L{ 0.5 + s2.last * 0.5 }
-s.freq = L{ s2.last * 220 + 660 }
+[s2, s >> wav] >> blackhole
play 3.seconds
diff --git a/ugen/oscillators.rb b/ugen/oscillators.rb
index <HASH>..<HASH> 100644
--- a/ugen/oscillators.rb
+++ b/ugen/oscillators.rb
@@ -20,12 +20,13 @@ module Ruck
include Source
include Oscillator
+ linkable_attr :freq
linkable_attr :gain
def initialize(freq = 440.0, gain = 1.0)
@now = 0
- @freq = freq
- @gain = gain
+ self.freq = freq
+ self.gain = gain
@phase = 0.0
@last = 0.0
end
|
SinOsc uses linkable_attr setter so its constructor takes lambdas
|
alltom_ruck
|
train
|
cdd35cdc82105096d11062572faabf3c892059fc
|
diff --git a/types/ruby-2.x/kernel.rb b/types/ruby-2.x/kernel.rb
index <HASH>..<HASH> 100644
--- a/types/ruby-2.x/kernel.rb
+++ b/types/ruby-2.x/kernel.rb
@@ -20,7 +20,7 @@ module Kernel
type 'self.__dir__', '() -> String or nil'
type 'self.__method__', '() -> Symbol or nil'
type 'self.`', '(String) -> String'
- type 'self.abort', '(?String msg) -> %any'
+ type 'self.abort', '(?String msg) -> %bot'
type 'self.at_exit', '() { () -> %any} -> Proc' # TODO: Fix proc
type 'self.autoload', '(String or Symbol module, String filename) -> nil'
type 'self.autoload?', '(Symbol or String name) -> String or nil'
@@ -33,12 +33,12 @@ module Kernel
# type 'self.catch' # TODO
type 'self.eval', '(String, ?Binding, ?String filename, ?Fixnum lineno) -> %any'
# type 'self.exec' #TODO
- type 'self.exit', '(Fixnum or %bool status) -> %any'
- type 'self.exit!', '(Fixnum or %bool status) -> %any'
- type 'self.fail', '() -> %any'
- type 'self.fail', '(String) -> %any'
- type 'self.fail', '(Class, Array<String>) -> %any'
- type 'self.fail', '(Class, String, Array<String>) -> %any'
+ type 'self.exit', '(Fixnum or %bool status) -> %bot'
+ type 'self.exit!', '(Fixnum or %bool status) -> %bot'
+ type 'self.fail', '() -> %bot'
+ type 'self.fail', '(String) -> %bot'
+ type 'self.fail', '(Class, Array<String>) -> %bot'
+ type 'self.fail', '(Class, String, Array<String>) -> %bot'
# type 'self.fail', '(String or [exception : () -> String], ?String, ?Array<String>) -> %any'
# type 'self.fork' #TODO
type 'self.format', '(String format, *%any args) -> String'
@@ -58,7 +58,7 @@ module Kernel
type(:proc, "() {(*%any) -> %any} -> Proc") # TODO more precise
type 'self.putc', '(Fixnum) -> Fixnum'
type 'self.puts', '(*[to_s : () -> String]) -> nil'
- type 'self.raise', '() -> %any'
+ type 'self.raise', '() -> %bot'
# type 'self.raise', '(String or [exception : () -> String], ?String, ?Array<String>) -> %any'
# TODO: above same as fail?
type 'self.rand', '(Fixnum or Range max) -> Numeric'
@@ -82,9 +82,9 @@ module Kernel
# type 'self.untrace_var' # TODO
type 'self.warn', '(*String msg) -> nil'
type :clone, '() -> self'
- type :raise, '() -> nil'
- type :raise, '(String) -> nil'
- type :raise, '(Class, String, Array<String>) -> nil'
+ type :raise, '() -> %bot'
+ type :raise, '(String) -> %bot'
+ type :raise, '(Class, String, Array<String>) -> %bot'
type :send, '(String or Symbol, *%any) -> %any'
type :send, '(String or Symbol, *%any) { (*%any) -> %any } -> %any'
end
|
Annotate non-returning methods as returning %bot
|
plum-umd_rdl
|
train
|
94be0ea4532bac64d3ff4466618eb0d3b93f6b19
|
diff --git a/src/Awjudd/FeedReader/FeedReader.php b/src/Awjudd/FeedReader/FeedReader.php
index <HASH>..<HASH> 100644
--- a/src/Awjudd/FeedReader/FeedReader.php
+++ b/src/Awjudd/FeedReader/FeedReader.php
@@ -66,6 +66,13 @@ class FeedReader
// Grab the cache location
$cache_location = storage_path($this->read_config($configuration, 'cache.location', 'rss-feeds'));
+ // Is the last character a slash?
+ if(substr($cache_location, -1) != DIRECTORY_SEPARATOR)
+ {
+ // Add in the slash at the end
+ $cache_location .= DIRECTORY_SEPARATOR;
+ }
+
// Check if the folder is available
if(!file_exists($cache_location))
{
|
Fixing a minor bug where the feed reader wasn't dropping the .gitignore file into the storage folder
|
awjudd_l4-feed-reader
|
train
|
ed9b4bca2733beebf68fc10412fc19c9042c6cb5
|
diff --git a/webview/__init__.py b/webview/__init__.py
index <HASH>..<HASH> 100755
--- a/webview/__init__.py
+++ b/webview/__init__.py
@@ -26,8 +26,11 @@ from webview.util import base_uri, parse_file_type, escape_string, transform_url
from .js import css
from .localization import localization
-logger = logging.getLogger(__name__)
-logging.basicConfig(level=logging.INFO)
+
+logger = logging.getLogger('pywebview')
+logger.addHandler(logging.StreamHandler())
+logger.setLevel(logging.INFO)
+
OPEN_DIALOG = 10
FOLDER_DIALOG = 20
diff --git a/webview/cocoa.py b/webview/cocoa.py
index <HASH>..<HASH> 100755
--- a/webview/cocoa.py
+++ b/webview/cocoa.py
@@ -6,6 +6,7 @@ http://github.com/r0x0r/pywebview/
"""
import sys
import json
+import logging
import subprocess
import webbrowser
@@ -28,6 +29,10 @@ info = bundle.localizedInfoDictionary() or bundle.infoDictionary()
info['NSAppTransportSecurity'] = {'NSAllowsArbitraryLoads': Foundation.YES}
+
+logger = logging.getLogger('pywebview')
+logger.debug('Using Cocoa')
+
class BrowserView:
instances = {}
app = AppKit.NSApplication.sharedApplication()
diff --git a/webview/gtk.py b/webview/gtk.py
index <HASH>..<HASH> 100755
--- a/webview/gtk.py
+++ b/webview/gtk.py
@@ -21,7 +21,7 @@ from webview.util import parse_api_js
from webview.js.css import disable_text_select
-logger = logging.getLogger(__name__)
+logger = logging.getLogger('pywebview')
import gi
gi.require_version('Gtk', '3.0')
diff --git a/webview/qt.py b/webview/qt.py
index <HASH>..<HASH> 100755
--- a/webview/qt.py
+++ b/webview/qt.py
@@ -22,7 +22,7 @@ from webview import OPEN_DIALOG, FOLDER_DIALOG, SAVE_DIALOG
from webview.js.css import disable_text_select
-logger = logging.getLogger(__name__)
+logger = logging.getLogger('pywebview')
# Try importing Qt5 modules
diff --git a/webview/win32.py b/webview/win32.py
index <HASH>..<HASH> 100644
--- a/webview/win32.py
+++ b/webview/win32.py
@@ -27,7 +27,7 @@ from webview.win32_shared import set_ie_mode
from webview.localization import localization
from webview import OPEN_DIALOG, FOLDER_DIALOG, SAVE_DIALOG
-logger = logging.getLogger(__name__)
+logger = logging.getLogger('pywebview')
"""
diff --git a/webview/winforms.py b/webview/winforms.py
index <HASH>..<HASH> 100644
--- a/webview/winforms.py
+++ b/webview/winforms.py
@@ -37,7 +37,7 @@ from webview.win32_shared import set_ie_mode
clr.AddReference(interop_dll_path())
from WebBrowserInterop import IWebBrowserInterop, WebBrowserEx
-logger = logging.getLogger(__name__)
+logger = logging.getLogger('pywebview')
class BrowserView:
|
[All] Refactor logging to keep its configuration locally
|
r0x0r_pywebview
|
train
|
9be6cdc66b0bfd64dc7652a3bf0fb3a7372a07a6
|
diff --git a/tests/test_interpolation.py b/tests/test_interpolation.py
index <HASH>..<HASH> 100644
--- a/tests/test_interpolation.py
+++ b/tests/test_interpolation.py
@@ -1,7 +1,9 @@
+import pytest
+
import pandas as pd
import numpy as np
-from vivarium.interpolation import Interpolation
+from vivarium.interpolation import Interpolation, validate_parameters
def test_1d_interpolation():
@@ -97,3 +99,15 @@ def test_order_zero_1d():
assert f(index=[1])[0] == 1
assert f(index=[2])[0] == 1, 'should be constant extrapolation outside of input range'
assert f(index=[-1])[0] == 0
+
+
+def test_validate_parameters__empty_data():
+ with pytest.warns(UserWarning) as record:
+ out, data = validate_parameters(pd.DataFrame(columns=["age", "sex", "year", "value"]), ["age", "year"], 2)
+ assert len(record) == 2
+ message = record[0].message.args[0] + " " + record[1].message.args[0]
+ assert "age" in message and "year" in message
+
+ assert set(data.columns) == {"sex", "value"}
+
+
diff --git a/vivarium/framework/results_writer.py b/vivarium/framework/results_writer.py
index <HASH>..<HASH> 100644
--- a/vivarium/framework/results_writer.py
+++ b/vivarium/framework/results_writer.py
@@ -1,4 +1,5 @@
"""Provides a class for consistently managing and writing vivarium outputs and output paths."""
+import shutil
from collections import defaultdict
import os
from datetime import datetime
@@ -70,6 +71,19 @@ class ResultsWriter:
raise NotImplementedError(
f"Only 'yaml' and 'hdf' file types are supported. You requested {extension}")
+ def copy_file(self, src_path, file_name, key=None):
+ """Copies a file unmodified to a location inside the ouput directory.
+
+ Parameters
+ ----------
+ src_path: str
+ Path to the src file
+ file_name: str
+ name of the destination file
+ """
+ path = os.path.join(self._directories[key], file_name)
+ shutil.copyfile(src_path, path)
+
def get_results_writer(results_directory, model_specification_file):
launch_time = datetime.now().strftime("%Y_%m_%d_%H_%M_%S")
diff --git a/vivarium/interpolation.py b/vivarium/interpolation.py
index <HASH>..<HASH> 100644
--- a/vivarium/interpolation.py
+++ b/vivarium/interpolation.py
@@ -8,15 +8,16 @@ class Interpolation:
def __init__(self, data, categorical_parameters, continuous_parameters, order, func=None):
data = data
self.key_columns = categorical_parameters
+
+ if data.empty:
+ raise ValueError("Must supply some input data")
+
self.parameter_columns, self_data = validate_parameters(data, continuous_parameters, order)
self.func = func
if len(self.parameter_columns) not in [1, 2]:
raise ValueError("Only interpolation over 1 or 2 variables is supported")
- if data.empty:
- raise ValueError("Must supply some input data")
-
# These are the columns which the interpolation function will approximate
value_columns = sorted(data.columns.difference(set(self.key_columns)|set(self.parameter_columns)))
assert value_columns, (f"No non-parameter data. Avaliable columns: {data.columns}, "
@@ -106,9 +107,6 @@ class Interpolation:
def validate_parameters(data, continuous_parameters, order):
- if data.empty:
- return continuous_parameters
-
out = []
for p in continuous_parameters:
if len(data[p].unique()) > order:
|
Cleanup failure case around interpolations and test a little
|
ihmeuw_vivarium
|
train
|
ccb4334111c6a57898dcae4f50d3785e14517abd
|
diff --git a/holoviews/plotting/element.py b/holoviews/plotting/element.py
index <HASH>..<HASH> 100644
--- a/holoviews/plotting/element.py
+++ b/holoviews/plotting/element.py
@@ -270,7 +270,7 @@ class ElementPlot(Plot):
elif self.aspect == 'square':
axis.set_aspect((1./axis.get_data_ratio()))
elif self.aspect not in [None, 'square']:
- axis.set_aspect(self.aspect)
+ axis.set_aspect(((1./axis.get_data_ratio()))/self.aspect)
if self.logx:
axis.set_xscale('log')
|
Made numeric aspects control plot aspect rather than axes aspect
|
pyviz_holoviews
|
train
|
7c755e95bfd74fd028e72203c4a51c4f00283014
|
diff --git a/search_queries_multi_match.go b/search_queries_multi_match.go
index <HASH>..<HASH> 100644
--- a/search_queries_multi_match.go
+++ b/search_queries_multi_match.go
@@ -28,7 +28,7 @@ type MultiMatchQuery struct {
rewrite string
fuzzyRewrite string
useDisMax *bool
- tieBreaker *int
+ tieBreaker *float32
lenient *bool
}
@@ -113,7 +113,7 @@ func (q MultiMatchQuery) UseDisMax(useDisMax bool) MultiMatchQuery {
return q
}
-func (q MultiMatchQuery) TieBreaker(tieBreaker int) MultiMatchQuery {
+func (q MultiMatchQuery) TieBreaker(tieBreaker float32) MultiMatchQuery {
q.tieBreaker = &tieBreaker
return q
}
|
TieBreaker in MultiMatchQuery is float<I> (as in QueryStringQuery)
|
olivere_elastic
|
train
|
05bc96b444012d52134566c3d142dec713c2d4e5
|
diff --git a/sbe-tool/src/main/java/uk/co/real_logic/sbe/generation/java/JavaGenerator.java b/sbe-tool/src/main/java/uk/co/real_logic/sbe/generation/java/JavaGenerator.java
index <HASH>..<HASH> 100644
--- a/sbe-tool/src/main/java/uk/co/real_logic/sbe/generation/java/JavaGenerator.java
+++ b/sbe-tool/src/main/java/uk/co/real_logic/sbe/generation/java/JavaGenerator.java
@@ -1133,43 +1133,46 @@ public class JavaGenerator implements CodeGenerator
int index,
final Function<String, String> nameMapping) throws IOException
{
- final List<String> groupClassNames = new ArrayList<>();
- int level = 0;
-
- for (int size = tokens.size(); index < size; index++)
+ if (shouldGenerateGroupOrderAnnotation)
{
- if (tokens.get(index).signal() == Signal.BEGIN_GROUP)
+ final List<String> groupClassNames = new ArrayList<>();
+ int level = 0;
+
+ for (int size = tokens.size(); index < size; index++)
{
- if (++level == 1)
+ if (tokens.get(index).signal() == Signal.BEGIN_GROUP)
{
- final Token groupToken = tokens.get(index);
- final String groupName = groupToken.name();
- groupClassNames.add(formatClassName(nameMapping.apply(groupName)));
+ if (++level == 1)
+ {
+ final Token groupToken = tokens.get(index);
+ final String groupName = groupToken.name();
+ groupClassNames.add(formatClassName(nameMapping.apply(groupName)));
+ }
}
- }
- else if (tokens.get(index).signal() == Signal.END_GROUP)
- {
- if (--level < 0)
+ else if (tokens.get(index).signal() == Signal.END_GROUP)
{
- break;
+ if (--level < 0)
+ {
+ break;
+ }
}
}
- }
- if (!groupClassNames.isEmpty() && shouldGenerateGroupOrderAnnotation)
- {
- out.append(indent).append("@uk.co.real_logic.sbe.codec.java.GroupOrder({");
- index = 0;
- for (final String name : groupClassNames)
+ if (!groupClassNames.isEmpty())
{
- out.append(className).append('.').append(name).append(".class");
- if (++index < groupClassNames.size())
+ out.append(indent).append("@uk.co.real_logic.sbe.codec.java.GroupOrder({");
+ index = 0;
+ for (final String name : groupClassNames)
{
- out.append(", ");
+ out.append(className).append('.').append(name).append(".class");
+ if (++index < groupClassNames.size())
+ {
+ out.append(", ");
+ }
}
- }
- out.append("})\n");
+ out.append("})\n");
+ }
}
}
|
[Java] Bale out fast when not generating annotations.
|
real-logic_simple-binary-encoding
|
train
|
724b4eb9183d5f5c6debd426c2431a9f2e402002
|
diff --git a/scripts/update-example-deps.js b/scripts/update-example-deps.js
index <HASH>..<HASH> 100644
--- a/scripts/update-example-deps.js
+++ b/scripts/update-example-deps.js
@@ -88,7 +88,7 @@ async function main () {
}
console.info('Pushing updated dependencies')
- await execa('git', ['commit', '-m', '"chore: updated example dependencies"'])
+ await execa('git', ['commit', '-m', 'chore: updated example dependencies'])
await execa('git', ['push'])
}
|
chore: fix commit message for updating example deps (#<I>)
Removes extraneous quotation marks as they are not needed.
|
ipfs_js-ipfs
|
train
|
107268eae28bf2879026b0b1b103fc7047e891c7
|
diff --git a/moment.js b/moment.js
index <HASH>..<HASH> 100644
--- a/moment.js
+++ b/moment.js
@@ -599,6 +599,10 @@
return this;
},
+ unixValueOf : function () {
+ return parseInt(this.valueOf() / 1000, 10);
+ },
+
local : function () {
this._isUTC = false;
return this;
|
Add a unixValueOf that returns the unix timestamp in seconds.
|
moment_moment
|
train
|
8d15503d6cd9a1eae9de2fb581c8b5da968e7a43
|
diff --git a/src/Connection/Aggregate/SentinelReplication.php b/src/Connection/Aggregate/SentinelReplication.php
index <HASH>..<HASH> 100644
--- a/src/Connection/Aggregate/SentinelReplication.php
+++ b/src/Connection/Aggregate/SentinelReplication.php
@@ -11,6 +11,7 @@
namespace Predis\Connection\Aggregate;
+use Predis\Command\CommandInterface;
use Predis\Command\RawCommand;
use Predis\Connection\ConnectionException;
use Predis\Connection\Factory as ConnectionFactory;
@@ -55,6 +56,11 @@ class SentinelReplication extends MasterSlaveReplication
protected $sentinelTimeout = 0.100;
/**
+ * Flag for automatic retries of commands upon server failure.
+ */
+ protected $autoRetry = true;
+
+ /**
* @param array $sentinels Sentinel servers connection parameters.
* @param string $service Name of the service for autodiscovery.
* @param ConnectionFactoryInterface $connectionFactory Connection factory instance.
@@ -87,6 +93,16 @@ class SentinelReplication extends MasterSlaveReplication
}
/**
+ * Set automatic retries of commands upon server failure.
+ *
+ * @param bool $retry Retry value.
+ */
+ public function setAutomaticRetry($retry)
+ {
+ $this->autoRetry = (bool) $retry;
+ }
+
+ /**
* {@inheritdoc}
*/
protected function check()
@@ -245,4 +261,57 @@ class SentinelReplication extends MasterSlaveReplication
}
}
}
+
+ /**
+ * Retries the execution of a command upon server failure after asking a new
+ * configuration to one of the sentinels.
+ *
+ * @param string $method Actual method.
+ * @param CommandInterface $command Command instance.
+ *
+ * @return mixed
+ */
+ private function retryCommandOnFailure($method, $command)
+ {
+ SENTINEL_RETRY: {
+ try {
+ $response = parent::$method($command);
+ } catch (ConnectionException $exception) {
+ if (!$this->autoRetry) {
+ throw $exception;
+ }
+
+ $exception->getConnection()->disconnect();
+ $this->querySentinel();
+
+ goto SENTINEL_RETRY;
+ }
+ }
+
+ return $response;
+ }
+
+ /**
+ * {@inheritdoc}
+ */
+ public function writeRequest(CommandInterface $command)
+ {
+ $this->retryCommandOnFailure(__FUNCTION__, $command);
+ }
+
+ /**
+ * {@inheritdoc}
+ */
+ public function readResponse(CommandInterface $command)
+ {
+ return $this->retryCommandOnFailure(__FUNCTION__, $command);
+ }
+
+ /**
+ * {@inheritdoc}
+ */
+ public function executeCommand(CommandInterface $command)
+ {
+ return $this->retryCommandOnFailure(__FUNCTION__, $command);
+ }
}
|
Implement transparent auto-retry of commands upon server failure.
By default, when the current server dies while executing a command Predis asks
for a new configuration to one of the sentinels and re-issues the same command.
This behavior can be disabled calling SentinelReplication::setAutomaticRetry().
|
nrk_predis
|
train
|
ef3c95248f442be403d6c780ffaa348ab7d0add6
|
diff --git a/phonopy/__init__.py b/phonopy/__init__.py
index <HASH>..<HASH> 100644
--- a/phonopy/__init__.py
+++ b/phonopy/__init__.py
@@ -440,7 +440,6 @@ class Phonopy:
self._band_structure = BandStructure(
bands,
self._dynamical_matrix,
- self._primitive,
is_eigenvectors=is_eigenvectors,
is_band_connection=is_band_connection,
group_velocity=self._group_velocity,
@@ -469,7 +468,6 @@ class Phonopy:
is_gamma_center=False):
self._mesh = Mesh(self._dynamical_matrix,
- self._primitive,
mesh,
shift=shift,
is_time_reversal=is_time_reversal,
@@ -752,7 +750,6 @@ class Phonopy:
factor=VaspToTHz):
write_yaml_qpoints(q_points,
- self._primitive,
self._dynamical_matrix,
nac_q_direction=nac_q_direction,
is_eigenvectors=is_eigenvectors,
@@ -772,12 +769,10 @@ class Phonopy:
if q_point==None:
animation = Animation([0, 0, 0],
self._dynamical_matrix,
- self._primitive,
shift=shift)
else:
animation = Animation(q_point,
self._dynamical_matrix,
- self._primitive,
shift=shift)
if anime_type=='v_sim':
if amplitude:
@@ -855,7 +850,6 @@ class Phonopy:
derivative_order=None,
nac_q_direction=None):
self._modulation = Modulation(self._dynamical_matrix,
- self._primitive,
dimension=dimension,
phonon_modes=phonon_modes,
delta_q=delta_q,
@@ -976,13 +970,13 @@ class PhonopyGruneisen:
def set_mesh(self,
mesh,
- grid_shift=None,
+ shift=None,
is_gamma_center=False):
self._mesh = GruneisenMesh(self._phonon,
self._phonon_plus,
self._phonon_minus,
mesh,
- grid_shift=grid_shift,
+ shift=shift,
is_gamma_center=is_gamma_center)
def write_yaml_mesh(self):
|
Remove Atoms object input when calling Mesh, BandStructure, Modulation, Anime class objects and qpoints method because it can be obtained from DynamicalMatrix object by get_primitive().
|
atztogo_phonopy
|
train
|
1fbd83f2f1eea3fec478240b6bf4eb518e622868
|
diff --git a/src/AuthenticationService.php b/src/AuthenticationService.php
index <HASH>..<HASH> 100644
--- a/src/AuthenticationService.php
+++ b/src/AuthenticationService.php
@@ -186,7 +186,7 @@ class AuthenticationService implements AuthenticationServiceInterface
];
}
- if (!$result->isValid() && $authenticator instanceof StatelessInterface) {
+ if ($authenticator instanceof StatelessInterface) {
$authenticator->unauthorizedChallenge($request);
}
}
|
#<I> Removed unnecessary condition
|
cakephp_authentication
|
train
|
6916ac83037f3743132c583619c03b681ef3cbab
|
diff --git a/README.md b/README.md
index <HASH>..<HASH> 100644
--- a/README.md
+++ b/README.md
@@ -900,6 +900,10 @@ Bounded by a box
```ruby
Restaurant.search "sushi", where: {location: {top_left: {lat: 38, lon: -123}, bottom_right: {lat: 37, lon: -122}}}
```
+OR
+```ruby
+Restaurant.search "sushi", where: {location: {top_right: {lat: 38, lon: -122}, bottom_left: {lat: 37, lon: -123}}}
+```
Bounded by a polygon
diff --git a/lib/searchkick/query.rb b/lib/searchkick/query.rb
index <HASH>..<HASH> 100644
--- a/lib/searchkick/query.rb
+++ b/lib/searchkick/query.rb
@@ -770,7 +770,7 @@ module Searchkick
if value.is_a?(Hash)
value.each do |op, op_value|
case op
- when :within, :bottom_right
+ when :within, :bottom_right, :bottom_left
# do nothing
when :near
filters << {
@@ -805,6 +805,15 @@ module Searchkick
}
}
}
+ when :top_right
+ filters << {
+ geo_bounding_box: {
+ field => {
+ top_right: location_value(op_value),
+ bottom_left: location_value(value[:bottom_left])
+ }
+ }
+ }
when :regexp # support for regexp queries without using a regexp ruby object
filters << {regexp: {field => {value: op_value}}}
when :not # not equal
diff --git a/test/where_test.rb b/test/where_test.rb
index <HASH>..<HASH> 100644
--- a/test/where_test.rb
+++ b/test/where_test.rb
@@ -189,6 +189,22 @@ class WhereTest < Minitest::Test
assert_search "san", ["San Francisco"], where: {location: {top_left: {lat: 38, lon: -123}, bottom_right: {lat: 37, lon: -122}}}
end
+ def test_top_right_bottom_left
+ store [
+ {name: "San Francisco", latitude: 37.7833, longitude: -122.4167},
+ {name: "San Antonio", latitude: 29.4167, longitude: -98.5000}
+ ]
+ assert_search "san", ["San Francisco"], where: {location: {top_right: [38, -122], bottom_left: [37, -123]}}
+ end
+
+ def test_top_right_bottom_left_hash
+ store [
+ {name: "San Francisco", latitude: 37.7833, longitude: -122.4167},
+ {name: "San Antonio", latitude: 29.4167, longitude: -98.5000}
+ ]
+ assert_search "san", ["San Francisco"], where: {location: {top_right: {lat: 38, lon: -122}, bottom_left: {lat: 37, lon: -123}}}
+ end
+
def test_multiple_locations
store [
{name: "San Francisco", latitude: 37.7833, longitude: -122.4167},
|
Added in top_right and bottom_left for posterity (#<I>)
|
ankane_searchkick
|
train
|
2d893dbe925db4ca20d28bca0110f0e6aa9c8d1b
|
diff --git a/CHANGELOG.txt b/CHANGELOG.txt
index <HASH>..<HASH> 100644
--- a/CHANGELOG.txt
+++ b/CHANGELOG.txt
@@ -2,6 +2,7 @@
- Change: Removed all deprecations.
- Change: Removed the PHP 5.x fatal error handler.
- Change: Dropped PHP 5.x support.
+- Change: Remove all double Exception / Throwable catching
- Bugfix: The process other routing is never called.
- Bugfix: The cookie editor needs to be "initialized" prior usage.
diff --git a/src/Analyse/Callback/Analyse/Objects.php b/src/Analyse/Callback/Analyse/Objects.php
index <HASH>..<HASH> 100644
--- a/src/Analyse/Callback/Analyse/Objects.php
+++ b/src/Analyse/Callback/Analyse/Objects.php
@@ -47,7 +47,6 @@ use Brainworxx\Krexx\Analyse\Callback\Analyse\Objects\PublicProperties;
use Brainworxx\Krexx\Analyse\Callback\Analyse\Objects\Traversable;
use Brainworxx\Krexx\Service\Config\Fallback;
use Brainworxx\Krexx\Service\Reflection\ReflectionClass;
-use Exception;
use Throwable;
/**
@@ -91,9 +90,7 @@ class Objects extends AbstractCallback
$output .= $this->dumpStuff(Meta::class);
// Anaylsing error objects.
- if (is_a($this->parameters[static::PARAM_DATA], Throwable::class) ||
- is_a($this->parameters[static::PARAM_DATA], Exception::class)
- ) {
+ if (is_a($this->parameters[static::PARAM_DATA], Throwable::class)) {
$output .= $this->dumpStuff(ErrorObject::class);
}
diff --git a/src/Analyse/Callback/Analyse/Objects/DebugMethods.php b/src/Analyse/Callback/Analyse/Objects/DebugMethods.php
index <HASH>..<HASH> 100644
--- a/src/Analyse/Callback/Analyse/Objects/DebugMethods.php
+++ b/src/Analyse/Callback/Analyse/Objects/DebugMethods.php
@@ -39,7 +39,6 @@ use Brainworxx\Krexx\Analyse\Code\Connectors;
use Brainworxx\Krexx\Analyse\Model;
use Brainworxx\Krexx\Service\Config\Fallback;
use Brainworxx\Krexx\Service\Reflection\ReflectionClass;
-use Exception;
use ReflectionException;
use Throwable;
@@ -128,8 +127,6 @@ class DebugMethods extends AbstractObjectAnalysis
$result = $object->$methodName();
} catch (Throwable $e) {
// Do nothing.
- } catch (Exception $e) {
- // Do nothing.
}
// Reactivate whatever error handling we had previously.
diff --git a/src/Analyse/Callback/Analyse/Objects/Traversable.php b/src/Analyse/Callback/Analyse/Objects/Traversable.php
index <HASH>..<HASH> 100644
--- a/src/Analyse/Callback/Analyse/Objects/Traversable.php
+++ b/src/Analyse/Callback/Analyse/Objects/Traversable.php
@@ -39,7 +39,6 @@ use Brainworxx\Krexx\Analyse\Callback\Iterate\ThroughArray;
use Brainworxx\Krexx\Analyse\Callback\Iterate\ThroughLargeArray;
use Brainworxx\Krexx\Analyse\Model;
use Brainworxx\Krexx\Service\Config\Fallback;
-use Exception;
use SplObjectStorage;
use Throwable;
@@ -108,11 +107,6 @@ class Traversable extends AbstractObjectAnalysis
restore_error_handler();
$this->pool->emergencyHandler->downOneNestingLevel();
return '';
- } catch (Exception $e) {
- //Restore the previous error handler, and return an empty string.
- restore_error_handler();
- $this->pool->emergencyHandler->downOneNestingLevel();
- return '';
}
// Reactivate whatever error handling we had previously.
|
Remove all double Exception / Throwable catching
|
brainworxx_kreXX
|
train
|
0a03ea5f505eb4bf6e32ccc2414170783d084cc5
|
diff --git a/wandb/sdk/wandb_settings.py b/wandb/sdk/wandb_settings.py
index <HASH>..<HASH> 100644
--- a/wandb/sdk/wandb_settings.py
+++ b/wandb/sdk/wandb_settings.py
@@ -69,7 +69,9 @@ defaults = dict(
console="auto",
_console=Field(str, ("auto", "redirect", "off", "file", "iowrap",)),
git_remote="origin",
- _anonymous=Field(str, ("allow", "must", "never",)),
+ # anonymous might be set by a config file: "false" and "true"
+ # or from wandb.init(anonymous=) or environment: "allow", "must", "never"
+ _anonymous=Field(str, ("allow", "must", "never", "false", "true",)),
)
# env mapping?
diff --git a/wandb/sdk_py27/wandb_settings.py b/wandb/sdk_py27/wandb_settings.py
index <HASH>..<HASH> 100644
--- a/wandb/sdk_py27/wandb_settings.py
+++ b/wandb/sdk_py27/wandb_settings.py
@@ -69,7 +69,9 @@ defaults = dict(
console="auto",
_console=Field(str, ("auto", "redirect", "off", "file", "iowrap",)),
git_remote="origin",
- _anonymous=Field(str, ("allow", "must", "never",)),
+ # anonymous might be set by a config file: "false" and "true"
+ # or from wandb.init(anonymous=) or environment: "allow", "must", "never"
+ _anonymous=Field(str, ("allow", "must", "never", "false", "true",)),
)
# env mapping?
|
fix crash when user had cli-og anonymous setting (#<I>)
|
wandb_client
|
train
|
967ab6f10f5e111a5b20941ccec97ce97e4baf1b
|
diff --git a/raven/lib/raven/client.rb b/raven/lib/raven/client.rb
index <HASH>..<HASH> 100644
--- a/raven/lib/raven/client.rb
+++ b/raven/lib/raven/client.rb
@@ -69,7 +69,7 @@ module Raven
req.body = Yajl::Encoder.encode(event.to_hash)
req.headers[AUTH_HEADER_KEY] = self.generate_auth_header(req.body)
end
- raise Error.new("Error from Sentry server (#{response.status_code}): #{response.body}") unless response.status_code == 200
+ raise Error.new("Error from Sentry server (#{response.status}): #{response.body}") unless response.status == 200
response
end
|
Fix to use the correct faraday response attr.
|
getsentry_raven-ruby
|
train
|
13902c2a811ef6dac9ee8961cd2f873aeff1279d
|
diff --git a/vraptor-core/src/test/java/br/com/caelum/vraptor/VRaptorTest.java b/vraptor-core/src/test/java/br/com/caelum/vraptor/VRaptorTest.java
index <HASH>..<HASH> 100644
--- a/vraptor-core/src/test/java/br/com/caelum/vraptor/VRaptorTest.java
+++ b/vraptor-core/src/test/java/br/com/caelum/vraptor/VRaptorTest.java
@@ -16,27 +16,24 @@
*/
package br.com.caelum.vraptor;
-import static org.hamcrest.Matchers.is;
-import static org.junit.Assert.assertThat;
-import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.verify;
-import static org.mockito.Mockito.verifyNoMoreInteractions;
-import static org.mockito.Mockito.when;
-
-import javax.inject.Inject;
-import javax.servlet.FilterChain;
-import javax.servlet.ServletException;
-import javax.servlet.ServletRequest;
-import javax.servlet.ServletResponse;
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-
-import org.junit.Rule;
-import org.junit.Test;
+import org.jboss.arquillian.container.test.api.Deployment;
+import org.jboss.arquillian.junit.Arquillian;
+import org.jboss.shrinkwrap.api.ShrinkWrap;
+import org.jboss.shrinkwrap.api.spec.WebArchive;
+import org.junit.*;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith;
-@RunWith(WeldJunitRunner.class)
+import javax.inject.Inject;
+import javax.servlet.*;
+import javax.servlet.http.*;
+
+import static org.hamcrest.Matchers.is;
+import static org.jboss.shrinkwrap.api.asset.EmptyAsset.INSTANCE;
+import static org.junit.Assert.assertThat;
+import static org.mockito.Mockito.*;
+
+@RunWith(Arquillian.class)
public class VRaptorTest {
@Rule
@@ -44,9 +41,18 @@ public class VRaptorTest {
@Inject
private VRaptor vRaptor;
+
@Inject
private MockStaticContentHandler handler;
+ @Deployment
+ public static WebArchive createDeployment() {
+ return ShrinkWrap
+ .create(WebArchive.class)
+ .addPackages(true, "br.com.caelum.vraptor")
+ .addAsManifestResource(INSTANCE, "beans.xml");
+ }
+
@Test
public void shoudlComplainIfNotInAServletEnviroment() throws Exception {
exception.expect(ServletException.class);
diff --git a/vraptor-core/src/test/java/br/com/caelum/vraptor/ioc/cdi/CDIBasedContainerTest.java b/vraptor-core/src/test/java/br/com/caelum/vraptor/ioc/cdi/CDIBasedContainerTest.java
index <HASH>..<HASH> 100644
--- a/vraptor-core/src/test/java/br/com/caelum/vraptor/ioc/cdi/CDIBasedContainerTest.java
+++ b/vraptor-core/src/test/java/br/com/caelum/vraptor/ioc/cdi/CDIBasedContainerTest.java
@@ -27,7 +27,6 @@ import org.hamcrest.Matcher;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.shrinkwrap.api.ShrinkWrap;
-import org.jboss.shrinkwrap.api.asset.EmptyAsset;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.Test;
import org.junit.runner.RunWith;
|
migrating VRaptorTest to use arquillian
|
caelum_vraptor4
|
train
|
accb7fbc5127d0d95362408ab141f699ba1e7e9b
|
diff --git a/katcp/resource_client.py b/katcp/resource_client.py
index <HASH>..<HASH> 100644
--- a/katcp/resource_client.py
+++ b/katcp/resource_client.py
@@ -521,7 +521,7 @@ class KATCPClientResource(resource.KATCPResource):
if preset_listeners:
try:
for listener in preset_listeners:
- s_obj.register_listener(listener)
+ s_obj.register_listener(listener, reading=True)
except Exception:
self._logger.exception(
'Exception trying to pre-set sensor listeners for sensor {}'
|
Fix register_listener that uses a reading
|
ska-sa_katcp-python
|
train
|
c30e153171d026e12b777371a0ba48e6fdd4f7e7
|
diff --git a/src/Git/PickLastMinorVersionFromCollection.php b/src/Git/PickLastMinorVersionFromCollection.php
index <HASH>..<HASH> 100644
--- a/src/Git/PickLastMinorVersionFromCollection.php
+++ b/src/Git/PickLastMinorVersionFromCollection.php
@@ -4,12 +4,15 @@ declare(strict_types=1);
namespace Roave\BackwardCompatibility\Git;
+use Assert\Assert;
use Symfony\Component\Process\Exception\LogicException;
use Symfony\Component\Process\Exception\RuntimeException;
+use Version\Constraint\ComparisonConstraint;
+use Version\Constraint\CompositeConstraint;
use Version\Version;
use Version\VersionsCollection;
+use function array_values;
use function iterator_to_array;
-use function reset;
final class PickLastMinorVersionFromCollection implements PickVersionFromVersionCollection
{
@@ -20,23 +23,33 @@ final class PickLastMinorVersionFromCollection implements PickVersionFromVersion
*/
public function forVersions(VersionsCollection $versions) : Version
{
+ Assert
+ ::that($versions->count())
+ ->greaterThan(0, 'Cannot determine latest minor version from an empty collection');
+
$versions->sort(VersionsCollection::SORT_DESC);
/** @var Version[] $versionsAsArray */
- $versionsAsArray = iterator_to_array($versions->getIterator());
+ $versionsAsArray = array_values(iterator_to_array($versions));
+
/** @var Version $lastVersion */
- $lastVersion = reset($versionsAsArray);
- $previousVersionInIteration = $lastVersion;
+ $lastVersion = $versionsAsArray[0];
+
+ $matchingMinorVersions = $versions->matching(new CompositeConstraint(
+ CompositeConstraint::OPERATOR_AND,
+ new ComparisonConstraint(ComparisonConstraint::OPERATOR_LTE, $lastVersion),
+ new ComparisonConstraint(
+ ComparisonConstraint::OPERATOR_GTE,
+ Version::fromString($lastVersion->getMajor() . '.' . $lastVersion->getMinor() . '.0')
+ )
+ ));
- /** @var Version $version */
- foreach ($versions as $version) {
- if ($lastVersion->getMinor() !== $version->getMinor()) {
- return $previousVersionInIteration;
- }
+ $matchingMinorVersions->sort(VersionsCollection::SORT_ASC);
- $previousVersionInIteration = $version;
- }
+ /** @var Version[] $matchingMinorVersionsAsArray */
+ $matchingMinorVersionsAsArray = array_values(iterator_to_array($matchingMinorVersions));
- return $previousVersionInIteration;
+ // Note: since the collection is never empty, we can assume that the first element exists
+ return $matchingMinorVersionsAsArray[0];
}
}
diff --git a/test/unit/Git/PickLastMinorVersionFromCollectionTest.php b/test/unit/Git/PickLastMinorVersionFromCollectionTest.php
index <HASH>..<HASH> 100644
--- a/test/unit/Git/PickLastMinorVersionFromCollectionTest.php
+++ b/test/unit/Git/PickLastMinorVersionFromCollectionTest.php
@@ -4,6 +4,7 @@ declare(strict_types=1);
namespace RoaveTest\BackwardCompatibility\Git;
+use Assert\AssertionFailedException;
use PHPUnit\Framework\TestCase;
use Roave\BackwardCompatibility\Git\PickLastMinorVersionFromCollection;
use Version\Version;
@@ -21,6 +22,10 @@ final class PickLastMinorVersionFromCollectionTest extends TestCase
public function lastStableMinorVersionForCollectionProvider() : array
{
return [
+ ['2.2.0', ['1.1.0', '2.1.1', '2.2.0', '1.2.1']],
+ ['2.2.0', ['1.1.0', '2.2.1', '2.2.0', '1.2.1']],
+ ['2.2.0', ['1.2.0', '2.2.1', '2.2.0', '1.2.1']],
+ ['2.2.0', ['1.2.0', '2.2.0', '2.2.1', '1.2.1']],
['1.2.0', ['1.1.0', '1.1.1', '1.2.0', '1.2.1']],
['1.2.0', ['1.1.0', '1.1.1', '1.2.0']],
['1.2.0', ['1.2.0', '1.2.1']],
@@ -43,4 +48,13 @@ final class PickLastMinorVersionFromCollectionTest extends TestCase
)->getVersionString()
);
}
+
+ public function testWillRejectEmptyCollection() : void
+ {
+ $pick = new PickLastMinorVersionFromCollection();
+
+ $this->expectException(AssertionFailedException::class);
+
+ $pick->forVersions(new VersionsCollection());
+ }
}
|
#<I> #<I> #<I> ensure that the latest minor version for the current *MAJOR* is picked
Previously, only the *MINOR* version was being compared, leading to previous major
versions being considered in the lookup for the lowest available stable release.
|
Roave_BackwardCompatibilityCheck
|
train
|
2f08e8d260b0c7ec49ca0b6c1f270be7df589262
|
diff --git a/src/main/java/eu/hansolo/medusa/skins/TileKpiSkin.java b/src/main/java/eu/hansolo/medusa/skins/TileKpiSkin.java
index <HASH>..<HASH> 100644
--- a/src/main/java/eu/hansolo/medusa/skins/TileKpiSkin.java
+++ b/src/main/java/eu/hansolo/medusa/skins/TileKpiSkin.java
@@ -291,8 +291,8 @@ public class TileKpiSkin extends SkinBase<Gauge> implements Skin<Gauge> {
sectionArc.setStrokeWidth(barWidth);
sectionArc.setStrokeLineCap(StrokeLineCap.BUTT);
sectionArc.setFill(null);
- sectionArc.setVisible(highlightSections);
- sectionArc.setOpacity(highlightSections ? 0.25 : 1.0);
+ sectionArc.setVisible(!highlightSections);
+ sectionArc.setOpacity(highlightSections ? 1.0 : 0.25);
Tooltip sectionTooltip = new Tooltip(section.getText());
sectionTooltip.setTextAlignment(TextAlignment.CENTER);
Tooltip.install(sectionArc, sectionTooltip);
|
Minor fix related to toggle of highlightSections behavior
|
HanSolo_Medusa
|
train
|
63b7588681f32ac795df6c4eab016ab46b5a47d5
|
diff --git a/tests/test_transliterate.py b/tests/test_transliterate.py
index <HASH>..<HASH> 100644
--- a/tests/test_transliterate.py
+++ b/tests/test_transliterate.py
@@ -157,8 +157,8 @@ class TestTransliteratePackage(unittest.TestCase):
self.assertEqual(puan("แมว"), "แมว")
self.assertEqual(puan("นาริน"), "นิน-รา")
self.assertEqual(puan("นาริน", show_pronunciation=False), "นินรา")
- self.assertEqual(puan("แสงดีนะ"), "แสง-ดะ-นี")
- self.assertEqual(puan("แสงดีนะ", show_pronunciation=False), "แสงดะนี")
- self.assertEqual(
- puan("การทำความดี", show_pronunciation=False), "ดานทำความกี"
- )
+ # self.assertEqual(puan("แสงดีนะ"), "แสง-ดะ-นี")
+ # self.assertEqual(puan("แสงดีนะ", show_pronunciation=False), "แสงดะนี")
+ # self.assertEqual(
+ # puan("การทำความดี", show_pronunciation=False), "ดานทำความกี"
+ # )
|
Update test_transliterate.py
|
PyThaiNLP_pythainlp
|
train
|
580039208ae12b07bb94e1a924f201e5e923b19f
|
diff --git a/src/java/org/apache/cassandra/db/CompactionManager.java b/src/java/org/apache/cassandra/db/CompactionManager.java
index <HASH>..<HASH> 100644
--- a/src/java/org/apache/cassandra/db/CompactionManager.java
+++ b/src/java/org/apache/cassandra/db/CompactionManager.java
@@ -29,7 +29,6 @@ import javax.management.*;
import org.apache.log4j.Logger;
import org.apache.cassandra.concurrent.DebuggableThreadPoolExecutor;
-import org.apache.cassandra.concurrent.NamedThreadFactory;
import org.apache.cassandra.dht.Range;
import org.apache.cassandra.io.*;
import org.apache.cassandra.config.DatabaseDescriptor;
@@ -37,7 +36,6 @@ import org.apache.cassandra.service.StorageService;
import org.apache.cassandra.service.AntiEntropyService;
import org.apache.cassandra.io.util.FileUtils;
import org.apache.cassandra.utils.FBUtilities;
-import org.apache.cassandra.utils.WrappedRunnable;
import org.cliffc.high_scale_lib.NonBlockingHashMap;
import java.net.InetAddress;
@@ -53,6 +51,8 @@ public class CompactionManager implements CompactionManagerMBean
private static final Logger logger = Logger.getLogger(CompactionManager.class);
public static final CompactionManager instance;
+ private static volatile boolean gcRequested;
+
private int minimumCompactionThreshold = 4; // compact this many sstables min at a time
private int maximumCompactionThreshold = 32; // compact this many sstables max at a time
@@ -68,11 +68,40 @@ public class CompactionManager implements CompactionManagerMBean
{
throw new RuntimeException(e);
}
+
+ /**
+ * thread that requests GCs to clean out obsolete sstables, sleeping rpc timeout first so that most in-progress ops can complete
+ * (thus, no longer reference the sstables in question)
+ */
+ new Thread(new Runnable()
+ {
+ final long gcDelay = DatabaseDescriptor.getRpcTimeout();
+
+ public void run()
+ {
+ while (true)
+ {
+ try
+ {
+ Thread.sleep(gcDelay * 10);
+ if (gcRequested)
+ {
+ Thread.sleep(gcDelay);
+ System.gc();
+ gcRequested = false;
+ }
+ }
+ catch (InterruptedException e)
+ {
+ throw new AssertionError(e);
+ }
+ }
+ }
+ }, "COMPACTION-GC-INVOKER").start();
}
private CompactionExecutor executor = new CompactionExecutor();
private Map<ColumnFamilyStore, Integer> estimatedCompactions = new NonBlockingHashMap<ColumnFamilyStore, Integer>();
- private static final NamedThreadFactory gcThreadFactory = new NamedThreadFactory("GC-INVOKER");
/**
* Call this whenever a compaction might be needed on the given columnfamily.
@@ -308,7 +337,7 @@ public class CompactionManager implements CompactionManagerMBean
SSTableReader ssTable = writer.closeAndOpenReader(DatabaseDescriptor.getKeysCachedFraction(table.name, cfs.getColumnFamilyName()));
cfs.replaceCompactedSSTables(sstables, Arrays.asList(ssTable));
- gcAfterRpcTimeout();
+ gcRequested = true;
submitMinorIfNeeded(cfs);
String format = "Compacted to %s. %d/%d bytes for %d keys. Time: %dms.";
@@ -409,7 +438,7 @@ public class CompactionManager implements CompactionManagerMBean
{
cfs.replaceCompactedSSTables(originalSSTables, sstables);
}
- CompactionManager.gcAfterRpcTimeout();
+ gcRequested = true;
}
/**
@@ -441,22 +470,6 @@ public class CompactionManager implements CompactionManagerMBean
}
}
- /**
- * perform a GC to clean out obsolete sstables, sleeping rpc timeout first so that most in-progress ops can complete
- * (thus, no longer reference the sstables in question)
- */
- static void gcAfterRpcTimeout()
- {
- gcThreadFactory.newThread(new WrappedRunnable()
- {
- public void runMayThrow() throws InterruptedException
- {
- Thread.sleep(DatabaseDescriptor.getRpcTimeout());
- System.gc();
- }
- }).start();
- }
-
/*
* Group files of similar size into buckets.
*/
|
avoid creating a new thread for each requested GC. easier for telemetery (and better design anyway) to re-use the same thread. patch by jbellis
git-svn-id: <URL>
|
Stratio_stratio-cassandra
|
train
|
5af65a0674bdb4ce3b118802156d89b3d9433f0f
|
diff --git a/core/src/main/java/hudson/PluginWrapper.java b/core/src/main/java/hudson/PluginWrapper.java
index <HASH>..<HASH> 100644
--- a/core/src/main/java/hudson/PluginWrapper.java
+++ b/core/src/main/java/hudson/PluginWrapper.java
@@ -102,7 +102,13 @@ public final class PluginWrapper {
if(isLinked) {
// resolve the .hpl file to the location of the manifest file
- archive = resolve(archive,new BufferedReader(new FileReader(archive)).readLine());
+ String firstLine = new BufferedReader(new FileReader(archive)).readLine();
+ if(firstLine.startsWith("Manifest-Version:")) {
+ // this is the manifest already
+ } else {
+ // in direction
+ archive = resolve(archive, firstLine);
+ }
// then parse manifest
FileInputStream in = new FileInputStream(archive);
try {
@@ -201,6 +207,7 @@ public final class PluginWrapper {
private void parseClassPath(File archive, List<URL> paths, String attributeName, String separator) throws IOException {
String classPath = manifest.getMainAttributes().getValue(attributeName);
+ if(classPath==null) return; // attribute not found
for (String s : classPath.split(separator)) {
File file = resolve(archive, s);
if(file.getName().contains("*")) {
|
adjusting to work with new manifest file that the maven plugin creates.
git-svn-id: <URL>
|
jenkinsci_jenkins
|
train
|
9ac3e86fe03e5f63dbd765bf90cb50c086e1728d
|
diff --git a/src/java/com/threerings/presents/client/BasicDirector.java b/src/java/com/threerings/presents/client/BasicDirector.java
index <HASH>..<HASH> 100644
--- a/src/java/com/threerings/presents/client/BasicDirector.java
+++ b/src/java/com/threerings/presents/client/BasicDirector.java
@@ -149,5 +149,5 @@ public class BasicDirector
protected PresentsContext _ctx;
/** Whether or not this director is available in standalone mode. */
- protected boolean _availableInStandalone;
+ protected boolean _availableInStandalone = true;
}
|
Being available in standalone mode should be the default. This will of course
make life harder for Yohoho, but making life easier for Yohoho should not come
at the expense of baffling default behavior.
git-svn-id: svn+ssh://src.earth.threerings.net/narya/trunk@<I> <I>f4-<I>e9-<I>-aa3c-eee0fc<I>fb1
|
threerings_narya
|
train
|
135f529bfc131a9137672be3399e51eecea03f1f
|
diff --git a/worker/bridge.js b/worker/bridge.js
index <HASH>..<HASH> 100644
--- a/worker/bridge.js
+++ b/worker/bridge.js
@@ -1,10 +1,6 @@
import PromiseWorker from 'promise-worker';
-const uri = process.env.NODE_ENV === 'development' ?
- '/panels-worker.js' :
- 'https://cdn.uxtemple.com/panels-worker.js';
-
-const worker = new Worker(uri);
+const worker = new Worker('/panels-worker.js');
const promiseWorker = new PromiseWorker(worker);
export default promiseWorker;
|
fix: always load worker from /panels-worker.js
|
UXtemple_panels
|
train
|
59662fff7837fb051e5d5ad57689807b5d11de0a
|
diff --git a/baselines/trpo_mpi/trpo_mpi.py b/baselines/trpo_mpi/trpo_mpi.py
index <HASH>..<HASH> 100644
--- a/baselines/trpo_mpi/trpo_mpi.py
+++ b/baselines/trpo_mpi/trpo_mpi.py
@@ -92,7 +92,7 @@ def learn(*,
gamma=0.99,
lam=1.0, # advantage estimation
seed=None,
- entcoeff=0.0,
+ ent_coef=0.0,
cg_damping=1e-2,
vf_stepsize=3e-4,
vf_iters =3,
@@ -117,7 +117,7 @@ def learn(*,
max_kl max KL divergence between old policy and new policy ( KL(pi_old || pi) )
- entcoeff coefficient of policy entropy term in the optimization objective
+ ent_coef coefficient of policy entropy term in the optimization objective
cg_iters number of iterations of conjugate gradient algorithm
@@ -182,7 +182,7 @@ def learn(*,
ent = pi.pd.entropy()
meankl = tf.reduce_mean(kloldnew)
meanent = tf.reduce_mean(ent)
- entbonus = entcoeff * meanent
+ entbonus = ent_coef * meanent
vferr = tf.reduce_mean(tf.square(pi.vf - ret))
|
rename entcoeff to ent_coef in trpo_mpi for compatibility with other algos (#<I>)
|
openai_baselines
|
train
|
c06e8a550120d4c8f4e0b09eb6df18e6d6488199
|
diff --git a/image_test.go b/image_test.go
index <HASH>..<HASH> 100644
--- a/image_test.go
+++ b/image_test.go
@@ -33,6 +33,9 @@ import (
t "github.com/hajimehoshi/ebiten/v2/internal/testing"
)
+// maxImageSize is a maximum image size that should work in almost every environment.
+const maxImageSize = 4096 - 2
+
func init() {
rand.Seed(time.Now().UnixNano())
}
@@ -801,7 +804,7 @@ func TestImageStretch(t *testing.T) {
const w = 16
- dst := NewImage(w, 4096)
+ dst := NewImage(w, maxImageSize)
loop:
for h := 1; h <= 32; h++ {
src := NewImage(w+2, h+2)
@@ -2159,7 +2162,7 @@ func TestImageDrawImageTooSmallScale(t *testing.T) {
// Issue #1399
func TestImageDrawImageCannotAllocateImageForMipmap(t *testing.T) {
dst := NewImage(1, 1)
- src := NewImage(4096, 4096)
+ src := NewImage(maxImageSize, maxImageSize)
op := &DrawImageOptions{}
op.GeoM.Scale(64, 64)
|
ebiten: Fix tests for a very restricted environment (Steam Runtime)
Updates #<I>
|
hajimehoshi_ebiten
|
train
|
c3e793aead3cbc1ee5314c9c166e693eae62012d
|
diff --git a/mod/glossary/restorelib.php b/mod/glossary/restorelib.php
index <HASH>..<HASH> 100644
--- a/mod/glossary/restorelib.php
+++ b/mod/glossary/restorelib.php
@@ -673,7 +673,7 @@
$status = true;
//Convert glossary_comments->entrycomment
- if ($records = $DB->get_records_sql("SELECT c.id, c.entrycomment, c.format
+ if ($records = $DB->get_records_sql("SELECT c.id, c.entrycomment, c.entrycommentformat
FROM {glossary_comments} c,
{glossary_entries} e,
{glossary} g,
@@ -681,7 +681,7 @@
WHERE e.id = c.entryid AND
g.id = e.glossaryid AND
g.course = ? AND
- c.format = ".FORMAT_WIKI. " AND
+ c.entrycommentformat = ".FORMAT_WIKI. " AND
b.backup_code = ? AND
b.table_name = 'glossary_comments' AND
b.new_id = c.id", array($restore->course_id, $restore->backup_unique_code))) {
@@ -709,13 +709,13 @@
}
//Convert glossary_entries->definition
- if ($records = $DB->get_records_sql("SELECT e.id, e.definition, e.format
+ if ($records = $DB->get_records_sql("SELECT e.id, e.definition, e.definitionformat
FROM {glossary_entries} e,
{glossary} g,
{backup_ids} b
WHERE g.id = e.glossaryid AND
g.course = ? AND
- e.format = ".FORMAT_WIKI. " AND
+ e.definitionformat = ".FORMAT_WIKI. " AND
b.backup_code = ? AND
b.table_name = 'glossary_entries' AND
b.new_id = e.id", array($restore->course_id, $restore->backup_unique_code))) {
@@ -725,7 +725,7 @@
//Convert to Markdown
$wtm = new WikiToMarkdown();
$record->definition = $wtm->convert($record->definition, $restore->course_id);
- $record->entrycommentformat = FORMAT_MARKDOWN;
+ $record->definitionformat = FORMAT_MARKDOWN;
$status = $DB->update_record('glossary_entries', $record);
//Do some output
$i++;
|
MDL-<I> reimplemented trusstext support in glossary + standardising format column for text fields
|
moodle_moodle
|
train
|
f0113d49167bdbb8eeacbe2af2d1093da6127111
|
diff --git a/src/java/com/threerings/media/animation/AnimationManager.java b/src/java/com/threerings/media/animation/AnimationManager.java
index <HASH>..<HASH> 100644
--- a/src/java/com/threerings/media/animation/AnimationManager.java
+++ b/src/java/com/threerings/media/animation/AnimationManager.java
@@ -1,5 +1,5 @@
//
-// $Id: AnimationManager.java,v 1.10 2002/04/25 16:23:30 mdb Exp $
+// $Id: AnimationManager.java,v 1.11 2002/08/15 20:53:24 shaper Exp $
package com.threerings.media.animation;
@@ -136,8 +136,14 @@ public class AnimationManager
if (((layer == ALL) ||
(layer == FRONT && order >= 0) ||
(layer == BACK && order < 0)) &&
- clip.intersects(anim.getBounds())) {
- anim.paint(gfx);
+ try {
+ clip.intersects(anim.getBounds())) {
+ anim.paint(gfx);
+ } catch (Exception e) {
+ Log.warning("Failed to render animation " +
+ "[anim=" + anim + ", e=" + e + "].");
+ Log.logStackTrace(e);
+ }
}
}
}
|
Catch exceptions while rendering animations so that we can report the
animation at fault.
git-svn-id: svn+ssh://src.earth.threerings.net/narya/trunk@<I> <I>f4-<I>e9-<I>-aa3c-eee0fc<I>fb1
|
threerings_narya
|
train
|
e9c5fba06b65a3e0243ad04144fe33b95f485df4
|
diff --git a/test/test_apps/2.3/app/controllers/authors_controller.rb b/test/test_apps/2.3/app/controllers/authors_controller.rb
index <HASH>..<HASH> 100644
--- a/test/test_apps/2.3/app/controllers/authors_controller.rb
+++ b/test/test_apps/2.3/app/controllers/authors_controller.rb
@@ -2,7 +2,7 @@ class AuthorsController < ApplicationController
# GET /authors
# GET /authors.xml
def index
- @authors = Author.all
+ @authors = Author.all(:order => :last_name)
respond_to do |format|
format.html # index.html.erb
@@ -25,6 +25,8 @@ class AuthorsController < ApplicationController
# GET /authors/new.xml
def new
@author = Author.new
+ @author.books.build
+ @author.books.build
respond_to do |format|
format.html # new.html.erb
|
fix <I> authors controller to match the shared
|
appfolio_ae_page_objects
|
train
|
76b8b7e8928f514a4769db39bc27463e56f6ea4c
|
diff --git a/cxx-squid/src/main/java/org/sonar/cxx/preprocessor/CxxPreprocessor.java b/cxx-squid/src/main/java/org/sonar/cxx/preprocessor/CxxPreprocessor.java
index <HASH>..<HASH> 100644
--- a/cxx-squid/src/main/java/org/sonar/cxx/preprocessor/CxxPreprocessor.java
+++ b/cxx-squid/src/main/java/org/sonar/cxx/preprocessor/CxxPreprocessor.java
@@ -91,7 +91,7 @@ public class CxxPreprocessor extends Preprocessor {
public String toString() {
return name
- + (params == null ? "" : "(" + serialize(params, ", ") + ")")
+ + (params == null ? "" : "(" + serialize(params, ", ") + (isVariadic ? "..." : "") + ")")
+ " -> '" + serialize(body) + "'";
}
@@ -501,7 +501,6 @@ public class CxxPreprocessor extends Preprocessor {
if (macro != null) {
List<Token> replTokens = new LinkedList<Token>();
int tokensConsumed = 0;
- List<Token> arguments = new ArrayList<Token>();
if (macro.params == null) {
tokensConsumed = 1;
@@ -517,12 +516,25 @@ public class CxxPreprocessor extends Preprocessor {
}
if (tokensConsumed > 0) {
+
+ // Partial rescanning, to handle dangling function like macro expansion
+ if (replTokens.size() == 1 && replTokens.get(0).getType() == IDENTIFIER) {
+ macros.disable(macro.name);
+ PreprocessorAction action = handleIdentifiersAndKeywords(tokens.subList(tokensConsumed - 1, tokens.size()),
+ replTokens.get(0), filename);
+ if (action != PreprocessorAction.NO_OPERATION) {
+ tokensConsumed += action.getNumberOfConsumedTokens() - 1;
+ replTokens = action.getTokensToInject();
+ }
+ macros.enable(macro.name);
+ }
+
replTokens = reallocate(replTokens, curr);
LOG.trace("[{}:{}]: replacing '" + curr.getValue()
- + (arguments.isEmpty()
- ? ""
- : "(" + serialize(arguments, ", ") + ")") + "' -> '" + serialize(replTokens) + "'",
+ + (tokensConsumed == 1
+ ? ""
+ : serialize(tokens.subList(1, tokensConsumed))) + "' -> '" + serialize(replTokens) + "'",
filename, curr.getLine());
ppaction = new PreprocessorAction(
diff --git a/cxx-squid/src/test/java/org/sonar/cxx/parser/PreprocessorDirectivesTest.java b/cxx-squid/src/test/java/org/sonar/cxx/parser/PreprocessorDirectivesTest.java
index <HASH>..<HASH> 100644
--- a/cxx-squid/src/test/java/org/sonar/cxx/parser/PreprocessorDirectivesTest.java
+++ b/cxx-squid/src/test/java/org/sonar/cxx/parser/PreprocessorDirectivesTest.java
@@ -124,6 +124,27 @@ public class PreprocessorDirectivesTest extends ParserBaseTest {
}
@Test
+ public void complex_macro_rescanning() {
+ assert (serialize(p.parse(
+ "#define lang_init std_init\n"
+ + "#define std_init() c_init()\n"
+ + "lang_init();"))
+ .equals("c_init ( ) ; EOF"));
+
+ assert (serialize(p.parse(
+ "#define lang_init(x) std_init\n"
+ + "#define std_init() c_init()\n"
+ + "lang_init(0)();"))
+ .equals("c_init ( ) ; EOF"));
+
+ /*assert (serialize(p.parse(
+ "#define PAIR(x,y) x, y\n"
+ + "#define FOO(x, y) x + y\n"
+ + "FOO(PAIR(x, y));"))
+ .equals("x + y ; EOF"));*/
+ }
+
+ @Test
public void macro_arguments() {
assert (serialize(p.parse(
"#define min(X, Y) ((X) < (Y) ? (X) : (Y))\n"
|
Handle some macro rescanning cases.
This allows handling the case of objectLikeMacro expanding to the name of a functionLikeMacro, which is then followed by arguments:
#define FOO BAR
#define BAR(x) bar(x);
FOO(0);
|
SonarOpenCommunity_sonar-cxx
|
train
|
b4098399727924c99a5100e9c13e0cedafadc3ca
|
diff --git a/config/webpack.vars.js b/config/webpack.vars.js
index <HASH>..<HASH> 100644
--- a/config/webpack.vars.js
+++ b/config/webpack.vars.js
@@ -6,5 +6,5 @@ const production = process.env.NODE_ENV === 'production'
module.exports = {
production: production,
- extractor: new ExtractTextPlugin(`app${production ? '.[hash].min' : ''}.css`)
+ extractor: new ExtractTextPlugin(`[name]${production ? '.[hash].min' : ''}.css`)
}
diff --git a/webpack.config.js b/webpack.config.js
index <HASH>..<HASH> 100644
--- a/webpack.config.js
+++ b/webpack.config.js
@@ -4,7 +4,6 @@ const path = require('path')
const autoprefixer = require('autoprefixer')
-const ExtractTextPlugin = require('extract-text-webpack-plugin')
const CopyPlugin = require('copy-webpack-plugin')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const pkg = require(path.resolve(__dirname, 'package.json'))
@@ -85,7 +84,7 @@ let loaders = [
* http://localhost:3000, proxified to the server app port
*/
let plugins = [
- new ExtractTextPlugin(optimize ? 'app.[hash].css' : 'app.css'),
+ extractor,
new CopyPlugin([
{ from: 'vendor/assets', ignore: ['.gitkeep'] }
]),
|
fix: genetares two separate CSS for app and services :ambulance:
|
cozy_cozy-home
|
train
|
fbb0bc99aadf14bd43f4028bf94838a349131fa2
|
diff --git a/src/lib/worker/Main.js b/src/lib/worker/Main.js
index <HASH>..<HASH> 100644
--- a/src/lib/worker/Main.js
+++ b/src/lib/worker/Main.js
@@ -3,7 +3,6 @@
* This interface exposes web worker search capabilities to the UI thread.
* @flow
*/
-import SearchIndexWorker from 'worker?inline=true!./Worker'
import uuid from 'node-uuid'
/**
@@ -14,7 +13,13 @@ export default class SearchWorkerLoader {
/**
* Constructor.
*/
- constructor (WorkerClass = SearchIndexWorker) {
+ constructor (WorkerClass) {
+ // Defer worker import until construction to avoid testing error:
+ // Error: Cannot find module 'worker!./[workername]'
+ if (!WorkerClass) {
+ WorkerClass = require('worker?inline=true!./Worker')
+ }
+
// Maintain context if references are passed around
this.indexDocument = this.indexDocument.bind(this)
this.search = this.search.bind(this)
|
Changed worker import to fix test issue
|
bvaughn_redux-search
|
train
|
a19f1ac1a7f902e9183979fd414ef2ab3063ee96
|
diff --git a/src/Sylius/Bundle/ApiBundle/DependencyInjection/Compiler/CommandDataTransformerPass.php b/src/Sylius/Bundle/ApiBundle/DependencyInjection/Compiler/CommandDataTransformerPass.php
index <HASH>..<HASH> 100644
--- a/src/Sylius/Bundle/ApiBundle/DependencyInjection/Compiler/CommandDataTransformerPass.php
+++ b/src/Sylius/Bundle/ApiBundle/DependencyInjection/Compiler/CommandDataTransformerPass.php
@@ -33,7 +33,7 @@ final class CommandDataTransformerPass implements CompilerPassInterface
}
$container->setDefinition(
- 'sylius_api.command_data_transformers_chain',
+ 'sylius.api.command_data_transformers_chain',
$commandDataTransformersChainDefinition
);
}
diff --git a/src/Sylius/Bundle/ApiBundle/Resources/config/services.xml b/src/Sylius/Bundle/ApiBundle/Resources/config/services.xml
index <HASH>..<HASH> 100644
--- a/src/Sylius/Bundle/ApiBundle/Resources/config/services.xml
+++ b/src/Sylius/Bundle/ApiBundle/Resources/config/services.xml
@@ -96,16 +96,16 @@
<tag name="property_info.list_extractor" priority="-2000" />
</service>
- <service class="Sylius\Bundle\ApiBundle\DataTransformer\CommandAwareInputDataTransformer" id="sylius_bundle_api.data_transformer.add_item_to_cart_input_data_transformer">
- <argument type="service" id="sylius_api.command_data_transformers_chain" />
+ <service id="sylius.api.data_transformer.add_item_to_cart_input_data_transformer" class="Sylius\Bundle\ApiBundle\DataTransformer\CommandAwareInputDataTransformer">
+ <argument type="service" id="sylius.api.command_data_transformers_chain" />
<tag name="api_platform.data_transformer" />
</service>
- <service class="Sylius\Bundle\ApiBundle\DataTransformer\OrderTokenValueAwareInputCommandDataTransformer" id="sylius_bundle_api.data_transformer.order_token_value_aware_input_data_transformer">
+ <service id="sylius.api.data_transformer.order_token_value_aware_input_data_transformer" class="Sylius\Bundle\ApiBundle\DataTransformer\OrderTokenValueAwareInputCommandDataTransformer">
<tag name="sylius.api.command_data_transformer" />
</service>
- <service class="Sylius\Bundle\ApiBundle\DataTransformer\SubresourceIdAwareCommandDataTransformer" id="sylius_bundle_api.data_transformer.subresource_id_aware_data_transformer">
+ <service id="sylius.api.data_transformer.subresource_id_aware_data_transformer" class="Sylius\Bundle\ApiBundle\DataTransformer\SubresourceIdAwareCommandDataTransformer">
<argument type="service" id="request_stack" />
<tag name="sylius.api.command_data_transformer" />
</service>
diff --git a/src/Sylius/Bundle/ApiBundle/Tests/DependencyInjection/Compiler/CommandDataTransformerPassTest.php b/src/Sylius/Bundle/ApiBundle/Tests/DependencyInjection/Compiler/CommandDataTransformerPassTest.php
index <HASH>..<HASH> 100644
--- a/src/Sylius/Bundle/ApiBundle/Tests/DependencyInjection/Compiler/CommandDataTransformerPassTest.php
+++ b/src/Sylius/Bundle/ApiBundle/Tests/DependencyInjection/Compiler/CommandDataTransformerPassTest.php
@@ -55,7 +55,7 @@ final class CommandDataTransformerPassTest extends AbstractCompilerPassTestCase
{
$this->compile();
- $this->assertContainerBuilderHasService('sylius_api.command_data_transformers_chain');
+ $this->assertContainerBuilderHasService('sylius.api.command_data_transformers_chain');
}
protected function registerCompilerPass(ContainerBuilder $container): void
|
[API] Adjust services names to common convention
|
Sylius_Sylius
|
train
|
8e8b58bc3ac7f1292b5350b0b9ed69ed1e4e8292
|
diff --git a/go/vt/wrangler/traffic_switcher.go b/go/vt/wrangler/traffic_switcher.go
index <HASH>..<HASH> 100644
--- a/go/vt/wrangler/traffic_switcher.go
+++ b/go/vt/wrangler/traffic_switcher.go
@@ -211,7 +211,6 @@ func (wr *Wrangler) getWorkflowState(ctx context.Context, targetKeyspace, workfl
}
ws := workflow.NewServer(wr.ts, wr.tmc)
- _ = ws // make it compile
state := &workflow.State{
Workflow: workflowName,
SourceKeyspace: ts.SourceKeyspaceName(),
@@ -219,10 +218,8 @@ func (wr *Wrangler) getWorkflowState(ctx context.Context, targetKeyspace, workfl
}
var (
- reverse bool
- keyspace string
- cellsSwitched []string
- cellsNotSwitched []string
+ reverse bool
+ keyspace string
)
// we reverse writes by using the source_keyspace.workflowname_reverse workflow spec, so we need to use the
@@ -245,16 +242,15 @@ func (wr *Wrangler) getWorkflowState(ctx context.Context, targetKeyspace, workfl
}
table := ts.Tables()[0]
- cellsSwitched, cellsNotSwitched, err = wr.getCellsWithTableReadsSwitched(ctx, keyspace, table, "rdonly")
+ state.RdonlyCellsSwitched, state.RdonlyCellsNotSwitched, err = ws.GetCellsWithTableReadsSwitched(ctx, keyspace, table, topodatapb.TabletType_RDONLY)
if err != nil {
return nil, nil, err
}
- state.RdonlyCellsNotSwitched, state.RdonlyCellsSwitched = cellsNotSwitched, cellsSwitched
- cellsSwitched, cellsNotSwitched, err = wr.getCellsWithTableReadsSwitched(ctx, keyspace, table, "replica")
+
+ state.ReplicaCellsSwitched, state.ReplicaCellsNotSwitched, err = ws.GetCellsWithTableReadsSwitched(ctx, keyspace, table, topodatapb.TabletType_REPLICA)
if err != nil {
return nil, nil, err
}
- state.ReplicaCellsNotSwitched, state.ReplicaCellsSwitched = cellsNotSwitched, cellsSwitched
rules, err := topotools.GetRoutingRules(ctx, ts.TopoServer())
if err != nil {
return nil, nil, err
@@ -277,16 +273,16 @@ func (wr *Wrangler) getWorkflowState(ctx context.Context, targetKeyspace, workfl
shard = ts.SourceShards()[0]
}
- cellsSwitched, cellsNotSwitched, err = wr.getCellsWithShardReadsSwitched(ctx, keyspace, shard, "rdonly")
+ state.RdonlyCellsSwitched, state.RdonlyCellsNotSwitched, err = ws.GetCellsWithShardReadsSwitched(ctx, keyspace, shard, topodatapb.TabletType_RDONLY)
if err != nil {
return nil, nil, err
}
- state.RdonlyCellsNotSwitched, state.RdonlyCellsSwitched = cellsNotSwitched, cellsSwitched
- cellsSwitched, cellsNotSwitched, err = wr.getCellsWithShardReadsSwitched(ctx, keyspace, shard, "replica")
+
+ state.ReplicaCellsSwitched, state.ReplicaCellsNotSwitched, err = ws.GetCellsWithShardReadsSwitched(ctx, keyspace, shard, topodatapb.TabletType_REPLICA)
if err != nil {
return nil, nil, err
}
- state.ReplicaCellsNotSwitched, state.ReplicaCellsSwitched = cellsNotSwitched, cellsSwitched
+
if !shard.IsPrimaryServing {
state.WritesSwitched = true
}
|
Call workflow.Server methods directly instead of wrangler passthroughs
|
vitessio_vitess
|
train
|
7ebd072d4999870f39c4aa95240360d497379e54
|
diff --git a/actionsystemtest/lib/action_system_test/driver_adapters/web_server.rb b/actionsystemtest/lib/action_system_test/driver_adapters/web_server.rb
index <HASH>..<HASH> 100644
--- a/actionsystemtest/lib/action_system_test/driver_adapters/web_server.rb
+++ b/actionsystemtest/lib/action_system_test/driver_adapters/web_server.rb
@@ -30,7 +30,7 @@ module ActionSystemTest
end
def register_webrick(app, port)
- Rack::Handler::WEBrick.run(app, Port: port)
+ Rack::Handler::WEBrick.run(app, Port: port, AccessLog: [], Logger: WEBrick::Log::new(nil, 0))
end
def set_server
|
Set Webrick logger for system testing
If this is not set Webrick will log **everything** to STDOUT and
distract from the running tests. This will instead log to the log file.
This example was extracted from the Capybara source code.
|
rails_rails
|
train
|
22e7f8349c517fb3edeea3870e6189c02c3e43e1
|
diff --git a/src/mvc/redux-view.js b/src/mvc/redux-view.js
index <HASH>..<HASH> 100644
--- a/src/mvc/redux-view.js
+++ b/src/mvc/redux-view.js
@@ -19,8 +19,16 @@ const ReduxViewMixin = {
return this;
},
- onStoreUpdated() {
- this.render();
+ shouldViewRender(oldState, newState) {
+ return true;
+ },
+
+ onStoreUpdated(oldState, newState) {
+ this.state = newState;
+
+ if (this.shouldViewRender(oldState, newState)) {
+ this.render();
+ }
},
connectToStore() {
@@ -37,8 +45,7 @@ const ReduxViewMixin = {
this.actions = actions;
observeStore(provider.store, currentState, mapState, (newState, oldState) => {
- this.state = newState;
- if (typeof this.onStoreUpdated === 'function') this.onStoreUpdated(oldState);
+ this.onStoreUpdated(oldState, newState);
});
},
|
Add shouldViewRender and move state updating to onStateChanged so it can be conditional
|
BedeGaming_orchestra
|
train
|
05bedd0d5b88bcfc64a65234aeb35d1391eb0281
|
diff --git a/flow-typed/npm/immutable_vx.x.x.js b/flow-typed/npm/immutable_vx.x.x.js
index <HASH>..<HASH> 100644
--- a/flow-typed/npm/immutable_vx.x.x.js
+++ b/flow-typed/npm/immutable_vx.x.x.js
@@ -16,38 +16,3 @@
declare module 'immutable' {
declare module.exports: any;
}
-
-/**
- * We include stubs for each file inside this npm package in case you need to
- * require those files directly. Feel free to delete any files that aren't
- * needed.
- */
-declare module 'immutable/contrib/cursor/index' {
- declare module.exports: any;
-}
-
-declare module 'immutable/dist/immutable.es' {
- declare module.exports: any;
-}
-
-declare module 'immutable/dist/immutable' {
- declare module.exports: any;
-}
-
-declare module 'immutable/dist/immutable.min' {
- declare module.exports: any;
-}
-
-// Filename aliases
-declare module 'immutable/contrib/cursor/index.js' {
- declare module.exports: $Exports<'immutable/contrib/cursor/index'>;
-}
-declare module 'immutable/dist/immutable.es.js' {
- declare module.exports: $Exports<'immutable/dist/immutable.es'>;
-}
-declare module 'immutable/dist/immutable.js' {
- declare module.exports: $Exports<'immutable/dist/immutable'>;
-}
-declare module 'immutable/dist/immutable.min.js' {
- declare module.exports: $Exports<'immutable/dist/immutable.min'>;
-}
|
remove extra stuff from immutable's flow-typed def
|
openlattice_lattice-sagas
|
train
|
bf4d5316dda84425baf4258146eef0d407fd6572
|
diff --git a/nugridse.py b/nugridse.py
index <HASH>..<HASH> 100644
--- a/nugridse.py
+++ b/nugridse.py
@@ -202,6 +202,9 @@ class se(DataPlot, Utils):
code_source : string, optional
By default data based on MESA tracks is selected ('MES').
Data based on the GENEVA tracks is selected with 'GNV'.
+ exp_type :
+ If type is 'see_exp' or 'ppd_exp' runs of exp_type are selected. For example
+ 'delay' and 'rapid' would be choices for Set1.
verbose : boolean, optional
If True, print more output
@@ -220,7 +223,7 @@ class se(DataPlot, Utils):
se = [] # main data dictionary
pattern=''
- def __init__(self, sedir='.', pattern='.h5', rewrite=False, mass=None, Z=None, type='ppd_wind', output='out', code_source='MES',verbose=False):
+ def __init__(self, sedir='.', pattern='.h5', rewrite=False, mass=None, Z=None, type='ppd_wind', output='out', code_source='MES',exp_type='delay',verbose=False):
# seeker to find the data requested on VOspace:
if mass is not None and Z is not None:
@@ -264,11 +267,27 @@ class se(DataPlot, Utils):
if setmasses[i][-1]=='.': setmasses[i]=setmasses[i][:-1]
setmasses[i] = float(setmasses[i])
idx2=np.abs(np.array(setmasses)-mass).argmin()
- modname=mlist[idx2]
- realmass=setmasses[idx2]
+
+ realmass=setmasses[idx2]
print('closest mass is '+str(realmass))
+ if 'exp' in type:
+ #check if mass occurs twice, in case of ppd_exp runs
+ mlist_idx=[k for k in range(len(setmasses)) if realmass == setmasses[k]]
+ if (mlist_idx)>1:
+ #loop over different explosion prescriptions
+ found_exp_type=False
+ for k in range(len(mlist_idx)):
+ if exp_type in mlist[mlist_idx[k]]:
+ idx2 = mlist_idx[k]
+ found_exp_type=True
+ break
+ if not found_exp_type:
+ raise IOError("Sorry. There is no match for the exp_type ",exp_type," in ",mlist)
+
+ modname=mlist[idx2]
+
sedir+=modname
if 'ppd' in type:
sedir+='/H5_'+output
|
added feature to distinguish between different CCSN explosion types
|
NuGrid_NuGridPy
|
train
|
f89b733e1e9dac46a3cbc39180dad30d87aec19f
|
diff --git a/salt/modules/boto_vpc.py b/salt/modules/boto_vpc.py
index <HASH>..<HASH> 100644
--- a/salt/modules/boto_vpc.py
+++ b/salt/modules/boto_vpc.py
@@ -390,6 +390,18 @@ def associate_dhcp_options_to_vpc(dhcp_options_id, vpc_id, region=None, key=None
def associate_new_dhcp_options_to_vpc(vpc_id, domain_name=None, domain_name_servers=None, ntp_servers=None,
netbios_name_servers=None, netbios_node_type=None,
region=None, key=None, keyid=None, profile=None):
+ '''
+ Given valid DHCP options and a valid VPC id, create and associate the DHCP options record with the VPC.
+
+ Returns True if the DHCP options record were created and associated and returns False if the DHCP options record was not created and associated.
+
+ CLI example::
+
+ .. code-block:: bash
+
+ salt myminion boto_vpc.associate_new_dhcp_options_to_vpc 'vpc-6b1fe402' domain_name='example.com' domain_name_servers='[1.2.3.4]' ntp_servers='[5.6.7.8]' netbios_name_servers='[10.0.0.1]' netbios_node_type=1
+
+ '''
conn = _get_conn(region, key, keyid, profile)
if not conn:
return False
|
Added docstrings for the associate_new_dhcp_options_to_vpc method.
|
saltstack_salt
|
train
|
3d789a3015bdf248f77367862b4d6ebda7af31ae
|
diff --git a/index.js b/index.js
index <HASH>..<HASH> 100644
--- a/index.js
+++ b/index.js
@@ -1,7 +1,7 @@
/*!
* split-string <https://github.com/jonschlinkert/split-string>
*
- * Copyright (c) 2015, 2017, Jon Schlinkert.
+ * Copyright (c) 2015-2017, Jon Schlinkert.
* Released under the MIT License.
*/
@@ -164,5 +164,8 @@ function keepQuotes(ch, opts) {
}
function keepEscaping(opts, str, idx) {
+ if (typeof opts.keepEscaping === 'function') {
+ return opts.keepEscaping(str, idx);
+ }
return opts.keepEscaping === true || str[idx + 1] === '\\';
}
|
support `keepEscaping` as a function
|
jonschlinkert_split-string
|
train
|
c2406597c0ed9163fbb9ec90038598b8f918dd01
|
diff --git a/lib/multirepo/git/ref.rb b/lib/multirepo/git/ref.rb
index <HASH>..<HASH> 100644
--- a/lib/multirepo/git/ref.rb
+++ b/lib/multirepo/git/ref.rb
@@ -10,8 +10,8 @@ module MultiRepo
end
def exists?
- output = GitRunner.run_in_working_dir(@repo.path, "rev-parse --verify --quiet #{@name}", Runner::Verbosity::OUTPUT_NEVER)
- return output != nil
+ output = GitRunner.run_in_working_dir(@repo.path, "rev-parse --verify --quiet #{@name}", Runner::Verbosity::OUTPUT_NEVER).strip
+ return output != ""
end
def hash
|
Fixed Ref#exists? implementation.
|
fortinmike_git-multirepo
|
train
|
1d1239d32856b32b19c04edd17d0dd0d47611586
|
diff --git a/railties/lib/rails/application.rb b/railties/lib/rails/application.rb
index <HASH>..<HASH> 100644
--- a/railties/lib/rails/application.rb
+++ b/railties/lib/rails/application.rb
@@ -381,13 +381,8 @@ module Rails
# Fallback to config.secret_key_base if secrets.secret_key_base isn't set
secrets.secret_key_base ||= config.secret_key_base
- # Sync secrets.secret_token with config.secret_token, preferring secrets.secret_token
- # note that unset config's default to "", secrets default to nil
- if secrets.secret_token.blank? && config.secret_token.present?
- secrets.secret_token = config.secret_token
- elsif secrets.secret_token.present?
- config.secret_token = secrets.secret_token
- end
+ # Fallback to config.secret_token if secrets.secret_token isn't set
+ secrets.secret_token ||= config.secret_token
secrets
end
diff --git a/railties/test/application/configuration_test.rb b/railties/test/application/configuration_test.rb
index <HASH>..<HASH> 100644
--- a/railties/test/application/configuration_test.rb
+++ b/railties/test/application/configuration_test.rb
@@ -347,19 +347,17 @@ module ApplicationTests
end
end
- test "uses secrets.secret_token when secrets.secret_key_base and config.secret_token are blank" do
+ test "prefer secrets.secret_token over config.secret_token" do
app_file 'config/initializers/secret_token.rb', <<-RUBY
Rails.application.config.secret_token = ""
RUBY
app_file 'config/secrets.yml', <<-YAML
development:
- secret_key_base:
secret_token: 3b7cd727ee24e8444053437c36cc66c3
YAML
require "#{app_path}/config/environment"
assert_equal '3b7cd727ee24e8444053437c36cc66c3', app.secrets.secret_token
- assert_equal '3b7cd727ee24e8444053437c36cc66c3', app.config.secret_token
end
test "application verifier can build different verifiers" do
@@ -404,7 +402,7 @@ module ApplicationTests
test "config.secret_token over-writes a blank secrets.secret_token" do
app_file 'config/initializers/secret_token.rb', <<-RUBY
- Rails.application.config.secret_token = "b3c631c314c0bbca50c1b2843150fe33"
+ Rails.application.config.secret_token = "b3c631c314c0bbca50c1b2843150fe33"
RUBY
app_file 'config/secrets.yml', <<-YAML
development:
@@ -417,36 +415,6 @@ module ApplicationTests
assert_equal 'b3c631c314c0bbca50c1b2843150fe33', app.config.secret_token
end
- test "secret_token is copied from secrets to config when set" do
- app_file 'config/initializers/secret_token.rb', <<-RUBY
- Rails.application.config.secret_token = ""
- RUBY
- app_file 'config/secrets.yml', <<-YAML
- development:
- secret_key_base:
- secret_token: 3b7cd727ee24e8444053437c36cc66c3
- YAML
- require "#{app_path}/config/environment"
-
- assert_equal '3b7cd727ee24e8444053437c36cc66c3', app.secrets.secret_token
- assert_equal '3b7cd727ee24e8444053437c36cc66c3', app.config.secret_token
- end
-
- test "secret_token is copied from secrets to config when different" do
- app_file 'config/initializers/secret_token.rb', <<-RUBY
- Rails.application.config.secret_token = "b3c631c314c0bbca50c1b2843150fe33"
- RUBY
- app_file 'config/secrets.yml', <<-YAML
- development:
- secret_key_base:
- secret_token: 3b7cd727ee24e8444053437c36cc66c3
- YAML
- require "#{app_path}/config/environment"
-
- assert_equal '3b7cd727ee24e8444053437c36cc66c3', app.secrets.secret_token
- assert_equal '3b7cd727ee24e8444053437c36cc66c3', app.config.secret_token
- end
-
test "custom secrets saved in config/secrets.yml are loaded in app secrets" do
app_file 'config/secrets.yml', <<-YAML
development:
|
No need to sync config.secret_token and secrets.secret_token
Just prefer secrets over config
|
rails_rails
|
train
|
8d0ab8536444fc2deb2b3578716060fd34217ef5
|
diff --git a/views/js/uiForm.js b/views/js/uiForm.js
index <HASH>..<HASH> 100755
--- a/views/js/uiForm.js
+++ b/views/js/uiForm.js
@@ -496,10 +496,18 @@
}
}
+ function regularConfirmantion() {
+ return window.confirm(__('Please confirm property deletion!'));
+ }
+
async function getPropertyRemovalConfirmation($groupNode, uri) {
const dependencies = await checkForDependency(uri);
return new Promise((resolve, reject) => {
+ if (!dependencies.length) {
+ return regularConfirmantion() ? resolve() : reject();
+ }
+
const name = $groupNode.find('.property-heading-label')[0].innerText;
const dependantPropName = dependencies.reduce((prev, next, index) => {
const delimiter = index === dependencies.length - 1 ? '' : ', '
|
chore: Use regularConfirmation when no dependency
|
oat-sa_tao-core
|
train
|
ea5b9511ee2cfba58504c04e3791f5b991882328
|
diff --git a/satpy/readers/abi_l2_nc.py b/satpy/readers/abi_l2_nc.py
index <HASH>..<HASH> 100644
--- a/satpy/readers/abi_l2_nc.py
+++ b/satpy/readers/abi_l2_nc.py
@@ -46,7 +46,7 @@ class NC_ABI_L2(NC_ABI_BASE):
'units': _units,
'satellite_latitude': float(self.nc['nominal_satellite_subpoint_lat']),
'satellite_longitude': float(self.nc['nominal_satellite_subpoint_lon']),
- 'satellite_altitude': float(self.nc['nominal_satellite_height'])})
+ 'satellite_altitude': float(self.nc['nominal_satellite_height']) * 1000.})
variable.attrs.update(key.to_dict())
|
bugfix for satellite altitude in ABI L2 reader
The attribute data assumes the satellite altitude is stored
in meters, while the ABI L2 data stores thisvalue in km;
we simply need to insert factor of <I> to convert the units.
This matches what happens in the ABI L1b reader.
|
pytroll_satpy
|
train
|
d4d47734ad1e14e34291e336eb03b93057fa6ea1
|
diff --git a/packet.js b/packet.js
index <HASH>..<HASH> 100644
--- a/packet.js
+++ b/packet.js
@@ -5,7 +5,7 @@ function Packet (original, broker) {
this.brokerId = original.brokerId || (broker && broker.id)
this.brokerCounter = original.brokerCounter || (broker ? (++broker.counter) : 0)
this.topic = original.topic
- this.payload = original.payload || new Buffer(0)
+ this.payload = original.payload || Buffer.alloc(0)
this.qos = original.qos || 0
this.retain = original.retain || false
this.messageId = 0
diff --git a/test.js b/test.js
index <HASH>..<HASH> 100644
--- a/test.js
+++ b/test.js
@@ -9,7 +9,7 @@ test('Packet defaults', function (t) {
t.equal(instance.brokerId, undefined)
t.equal(instance.brokerCounter, 0)
t.equal(instance.topic, undefined)
- t.deepEqual(instance.payload, new Buffer(0))
+ t.deepEqual(instance.payload, Buffer.alloc(0))
t.equal(instance.qos, 0)
t.equal(instance.retain, false)
t.equal(instance.messageId, 0)
|
Not to use deprecated new Buffer(0)
|
mcollina_aedes-packet
|
train
|
1c8f26455e5ded6b8ec2ddf734beeaec1dc94315
|
diff --git a/rest-provider/src/main/java/org/jboss/pressgang/ccms/rest/RESTErrorInterceptor.java b/rest-provider/src/main/java/org/jboss/pressgang/ccms/rest/RESTErrorInterceptor.java
index <HASH>..<HASH> 100644
--- a/rest-provider/src/main/java/org/jboss/pressgang/ccms/rest/RESTErrorInterceptor.java
+++ b/rest-provider/src/main/java/org/jboss/pressgang/ccms/rest/RESTErrorInterceptor.java
@@ -19,9 +19,8 @@ public class RESTErrorInterceptor implements ClientErrorInterceptor {
final int status = response.getStatus();
String message = null;
try {
- message = (String) response.getEntity();
+ message = response.getEntity(String.class);
} catch (Exception e) {
-
} finally {
response.releaseConnection();
}
|
Fixed a bug where the Error Message in a response wasn't set.
|
pressgang-ccms_PressGangCCMSDatasourceProviders
|
train
|
33302fdd14d6e82293d1d8ea151af1197e7d74e2
|
diff --git a/activesupport/test/core_ext/range_ext_test.rb b/activesupport/test/core_ext/range_ext_test.rb
index <HASH>..<HASH> 100644
--- a/activesupport/test/core_ext/range_ext_test.rb
+++ b/activesupport/test/core_ext/range_ext_test.rb
@@ -115,11 +115,11 @@ class RangeTest < ActiveSupport::TestCase
def test_date_time_with_each
datetime = DateTime.now
- assert ((datetime - 1.hour)..datetime).each {}
+ assert(((datetime - 1.hour)..datetime).each {})
end
def test_date_time_with_step
datetime = DateTime.now
- assert ((datetime - 1.hour)..datetime).step(1) {}
+ assert(((datetime - 1.hour)..datetime).step(1) {})
end
end
|
Fix grouped expression warning - `warning: (...) interpreted as grouped expression`
|
rails_rails
|
train
|
b684a520af2c246940c5f95c927793e7ff92a195
|
diff --git a/spec/active_record/monetizable_spec.rb b/spec/active_record/monetizable_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/active_record/monetizable_spec.rb
+++ b/spec/active_record/monetizable_spec.rb
@@ -78,13 +78,25 @@ if defined? ActiveRecord
end
it "assigns the correct value from params" do
- params_clp = { amount: '20000', tax: '1000', currency: 'CLP' }
+ params_clp = { amount: '20000', tax: '1000', currency: 'CLP' }
product = Transaction.create(params_clp)
expect(product.valid?).to be_truthy
expect(product.amount.currency.subunit_to_unit).to eq(1)
expect(product.amount_cents).to eq(20000)
end
+ # TODO: This is a slightly controversial example, btu it reflects the current behaviour
+ it "re-assigns cents amount when subunit/unit ratio changes preserving amount in units" do
+ transaction = Transaction.create(amount: '20000', tax: '1000', currency: 'USD')
+
+ expect(transaction.amount).to eq(Money.new(20000_00, 'USD'))
+
+ transaction.currency = 'CLP'
+
+ expect(transaction.amount).to eq(Money.new(20000, 'CLP'))
+ expect(transaction.amount_cents).to eq(20000)
+ end
+
it "raises an error if trying to create two attributes with the same name" do
expect do
class Product
|
Add a missing example for a case currency changing use case
This illustrates that the amount is preserved in units when currency is
changed to a different subunit/unit ratio. The example is controversial
and confusing, this commit just ensures that is covered by specs.
|
RubyMoney_money-rails
|
train
|
f4a544081941e355ca5653e6dcb5eb682ef137c1
|
diff --git a/tasks/weinre.js b/tasks/weinre.js
index <HASH>..<HASH> 100644
--- a/tasks/weinre.js
+++ b/tasks/weinre.js
@@ -12,7 +12,7 @@ module.exports = function (grunt) {
var options = this.options();
var done = this.async();
- var args = [__dirname + '/../node_modules/weinre/weinre'];
+ var args = [require.resolve('weinre/weinre')];
[
'httpPort',
@@ -37,13 +37,7 @@ module.exports = function (grunt) {
},
function (error) {
if (error) {
- grunt.fail.fatal('weinre must be installed as a local dependency of grunt-weinre.\n\n' +
-
- 'Run the following command:\n' +
- 'rm -rf node_modules/weinre\n\n' +
-
- 'Then run:\n' +
- 'npm install grunt-weinre --save-dev');
+ grunt.fail.fatal(error);
}
done();
});
|
Use require.resolve to determine weinre path
|
ChrisWren_grunt-weinre
|
train
|
cc3e89aec833b7d628e98fb98057cd4ed7f9ad38
|
diff --git a/rest_collector.go b/rest_collector.go
index <HASH>..<HASH> 100644
--- a/rest_collector.go
+++ b/rest_collector.go
@@ -1,17 +1,16 @@
-/*
- *
+/*
+ *
*
* No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)
*
* OpenAPI spec version: 1.0.0
- *
+ *
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*/
package logicmonitor
type RestCollector struct {
-
ConfVersion string `json:"confVersion,omitempty"`
NumberOfServices int32 `json:"numberOfServices,omitempty"`
@@ -114,7 +113,7 @@ type RestCollector struct {
CreatedOnLocal string `json:"createdOnLocal,omitempty"`
- EnableFailBack bool `json:"enableFailBack,omitempty"`
+ EnableFailBack bool `json:"enableFailBack"`
ResendIval int32 `json:"resendIval,omitempty"`
|
don't omit empty for failback (#2)
|
logicmonitor_lm-sdk-go
|
train
|
6556f5c3ff3a5d32dfa3235a6df10c8bd2fda65c
|
diff --git a/src/resources/views/admin/_image-fieldset.blade.php b/src/resources/views/admin/_image-fieldset.blade.php
index <HASH>..<HASH> 100644
--- a/src/resources/views/admin/_image-fieldset.blade.php
+++ b/src/resources/views/admin/_image-fieldset.blade.php
@@ -1,7 +1,7 @@
<div ng-app="typicms">
<div class="filepicker" id="filepicker">
<div class="filepicker-content">
- @include('files::admin._filemanager', ['options' => ['dropzoneHidden', 'addFileButton']])
+ @include('files::admin._filemanager', ['options' => ['dropzoneHidden', 'single']])
</div>
</div>
<div class="form-group">
|
param 'addFileButton' is now 'single'
|
TypiCMS_Core
|
train
|
1d876a87c1fbe60b7c19a53bcc61bcb8af5b4f50
|
diff --git a/lib/utils.js b/lib/utils.js
index <HASH>..<HASH> 100644
--- a/lib/utils.js
+++ b/lib/utils.js
@@ -95,7 +95,7 @@ module.exports = function(self) {
if (options.single) {
s = s.replace(/\'/g, ''');
} else {
- s = s.replace(/\"/g, '&34;');
+ s = s.replace(/\"/g, '"');
}
if (options.pretty) {
s = s.replace(/\r?\n/g, "<br />");
|
fix nasty bug in jsonAttribute which only kicks in if you're not using the single:true option
|
apostrophecms_apostrophe
|
train
|
ef841478b77aa76276d859c2e60bd0f1c2a83d92
|
diff --git a/gwpy/timeseries/timeseries.py b/gwpy/timeseries/timeseries.py
index <HASH>..<HASH> 100644
--- a/gwpy/timeseries/timeseries.py
+++ b/gwpy/timeseries/timeseries.py
@@ -1323,19 +1323,19 @@ class TimeSeries(TimeSeriesBase):
--------
Demodulation is useful when trying to examine steady sinusoidal
signals we know to be contained within data. For instance,
- we can download some data from LOSC to look for fluctuations
- in the 60 Hz power line harmonic:
+ we can download some data from LOSC to look at trends of the
+ amplitude and phase of Livingston's calibration line at 331.3 Hz:
>>> from gwpy.timeseries import TimeSeries
>>> data = TimeSeries.fetch_open_data('L1', 1131350417, 1131357617)
- We can demodulate the `TimeSeries` at 60 Hz with a stride of once
+ We can demodulate the `TimeSeries` at 331.3 Hz with a stride of once
per minute:
- >>> amp, phase = data.demodulate(60, stride=60)
+ >>> amp, phase = data.demodulate(331.3, stride=60)
We can then plot these trends to visualize changes in the amplitude
- and phase of the 60 Hz line:
+ and phase of the calibration line:
>>> from gwpy.plotter import TimeSeriesPlot
>>> plot = TimeSeriesPlot(amp, phase, sep=True)
|
Changing the example use case to L1's cal line at <I> Hz -- it just works better.
|
gwpy_gwpy
|
train
|
a175a2307f8fd202357336e382e5845bc4bc5096
|
diff --git a/definitions/npm/pg_v7.x.x/flow_v0.28.x-/pg_v7.x.x.js b/definitions/npm/pg_v7.x.x/flow_v0.28.x-/pg_v7.x.x.js
index <HASH>..<HASH> 100644
--- a/definitions/npm/pg_v7.x.x/flow_v0.28.x-/pg_v7.x.x.js
+++ b/definitions/npm/pg_v7.x.x/flow_v0.28.x-/pg_v7.x.x.js
@@ -49,6 +49,8 @@ declare module pg {
log: Function,
// node-postgres Client ------
+ //database connection string to define some other config parameters
+ connectionString: string,
//database user's name
user: string,
//name of database to connect
|
fix missing connection string config property for pg (#<I>)
|
flow-typed_flow-typed
|
train
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.