hash
stringlengths 40
40
| diff
stringlengths 131
114k
| message
stringlengths 7
980
| project
stringlengths 5
67
| split
stringclasses 1
value |
---|---|---|---|---|
0259ee5ba2416f071e55297662c2a868a7c96ef7 | diff --git a/libkbfs/mdserver_remote.go b/libkbfs/mdserver_remote.go
index <HASH>..<HASH> 100644
--- a/libkbfs/mdserver_remote.go
+++ b/libkbfs/mdserver_remote.go
@@ -25,6 +25,9 @@ const (
// waits between runs. The timer gets reset to this period after
// every incoming FolderNeedsRekey RPC.
MdServerBackgroundRekeyPeriod = 1 * time.Hour
+ // MdServerDefaultPingIntervalSeconds is the default interval on which the
+ // client should contact the MD Server
+ MdServerDefaultPingIntervalSeconds = 10
)
// MDServerRemote is an implementation of the MDServer interface.
@@ -101,6 +104,7 @@ func (md *MDServerRemote) OnConnect(ctx context.Context,
if err != nil {
return err
} else if pingIntervalSeconds == -1 {
+ md.resetPingTicker(MdServerDefaultPingIntervalSeconds)
return nil
} | We now have a reasonable ping interval that will notice when you get disconnected, thus passing on the notification | keybase_client | train |
41058b1e4baec95d1f7a8071690cef4cab1da99a | diff --git a/commons-datastore/commons-datastore-mongodb/src/main/java/org/opencb/commons/datastore/mongodb/MongoDataStore.java b/commons-datastore/commons-datastore-mongodb/src/main/java/org/opencb/commons/datastore/mongodb/MongoDataStore.java
index <HASH>..<HASH> 100644
--- a/commons-datastore/commons-datastore-mongodb/src/main/java/org/opencb/commons/datastore/mongodb/MongoDataStore.java
+++ b/commons-datastore/commons-datastore-mongodb/src/main/java/org/opencb/commons/datastore/mongodb/MongoDataStore.java
@@ -20,6 +20,7 @@ import com.mongodb.MongoClient;
import com.mongodb.ReadPreference;
import com.mongodb.WriteConcern;
import com.mongodb.client.MongoDatabase;
+import org.bson.Document;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -74,6 +75,10 @@ public class MongoDataStore {
return mongoDBCollection;
}
+ public Document getServerStatus() {
+ return db.runCommand(new Document("serverStatus", 1));
+ }
+
public MongoDBCollection createCollection(String collectionName) {
if (!Arrays.asList(db.listCollectionNames()).contains(collectionName)) {
db.createCollection(collectionName); | datastore: Added new method to mongoDataStore to retrieve the server status info | opencb_java-common-libs | train |
8743e66acfd4b06a460db567d4f871f6861d987b | diff --git a/newsplease/__main__.py b/newsplease/__main__.py
index <HASH>..<HASH> 100644
--- a/newsplease/__main__.py
+++ b/newsplease/__main__.py
@@ -185,6 +185,7 @@ class NewsPlease(object):
thread_daemonized.start()
while not self.shutdown:
+ print("hi")
try:
time.sleep(10)
# if we are not in daemon mode and no crawler is running any longer, | add check to prevent self shutdown in daemon mode if no further sites are there | fhamborg_news-please | train |
c4530a4419d6d98a66482de5f6277a44f4f912dc | diff --git a/lib/generators/enju_leaf/quick_install/quick_install_generator.rb b/lib/generators/enju_leaf/quick_install/quick_install_generator.rb
index <HASH>..<HASH> 100644
--- a/lib/generators/enju_leaf/quick_install/quick_install_generator.rb
+++ b/lib/generators/enju_leaf/quick_install/quick_install_generator.rb
@@ -33,5 +33,6 @@ class EnjuLeaf::QuickInstallGenerator < Rails::Generators::Base
end
rake("enju_library:upgrade")
+ rake("enju_leaf:load_asset_files")
end
end | run load_asset_files task in install task | next-l_enju_leaf | train |
515bd01ace936f8b94a7b4e1bd39ff5ed2ba320c | diff --git a/asteval/asteval.py b/asteval/asteval.py
index <HASH>..<HASH> 100644
--- a/asteval/asteval.py
+++ b/asteval/asteval.py
@@ -129,8 +129,6 @@ class Interpreter(object):
usersyms = {}
symtable = make_symbol_table(use_numpy=use_numpy, **usersyms)
- symtable['print'] = self._printer
- self.no_print = no_print
self.symtable = symtable
self._interrupt = None
self.error = []
@@ -141,6 +139,9 @@ class Interpreter(object):
self.start_time = time.time()
self.use_numpy = HAS_NUMPY and use_numpy
+ symtable['print'] = self._printer
+ self.no_print = no_print or minimal
+
nodes = ALL_NODES[:]
if minimal or no_if:
@@ -161,8 +162,6 @@ class Interpreter(object):
nodes.remove('delete')
if minimal or no_raise:
nodes.remove('raise')
- if minimal or no_print:
- nodes.remove('print')
if minimal or no_listcomp:
nodes.remove('listcomp')
if minimal or no_augassign:
@@ -740,7 +739,8 @@ class Interpreter(object):
args = args + self.run(starargs)
keywords = {}
- keywords['file'] = self.writer
+ if func == print:
+ keywords['file'] = self.writer
for key in node.keywords:
if not isinstance(key, ast.keyword): | fixes for having removed print node/statement | newville_asteval | train |
7e1de98cbacbf058b8f81a77ba28237ff5a75804 | diff --git a/logbook-core/src/test/java/org/zalando/logbook/ObfuscatorTest.java b/logbook-core/src/test/java/org/zalando/logbook/ObfuscatorTest.java
index <HASH>..<HASH> 100644
--- a/logbook-core/src/test/java/org/zalando/logbook/ObfuscatorTest.java
+++ b/logbook-core/src/test/java/org/zalando/logbook/ObfuscatorTest.java
@@ -56,7 +56,17 @@ public final class ObfuscatorTest {
public void compoundShouldObfuscateMultipleTimes() {
final Obfuscator unit = Obfuscator.compound(
Obfuscator.obfuscate((key, value) -> "XXX".equals(value), "YYY"),
- Obfuscator.obfuscate((key, value) -> "password".equals(key), "<secret>"),
+ Obfuscator.obfuscate("Authorization"::equalsIgnoreCase, "XXX"));
+
+ assertThat(unit.obfuscate("Authorization", "Bearer c61a8f84-6834-11e5-a607-10ddb1ee7671"),
+ is(equalTo("YYY")));
+ }
+
+ @Test
+ public void compoundShouldObfuscateOnlyMatchingEntries() {
+ final Obfuscator unit = Obfuscator.compound(
+ Obfuscator.obfuscate((key, value) -> "XXX".equals(value), "YYY"),
+ Obfuscator.obfuscate((key, value) -> "password".equals(key), "<secret>"), // this won't be used
Obfuscator.obfuscate("Authorization"::equalsIgnoreCase, "XXX"));
assertThat(unit.obfuscate("Authorization", "Bearer c61a8f84-6834-11e5-a607-10ddb1ee7671"), | Changed compound obfuscation tests
This should make it clear we are testing two things now | zalando_logbook | train |
3adbd2c71325645c97a0bed2cd3325807f81ddbd | diff --git a/domain/host/host.go b/domain/host/host.go
index <HASH>..<HASH> 100644
--- a/domain/host/host.go
+++ b/domain/host/host.go
@@ -169,6 +169,9 @@ func (a *Host) Equals(b *Host) bool {
if !a.MonitoringProfile.Equals(&b.MonitoringProfile) {
return false
}
+ if a.NatIP != b.NatIP {
+ return false
+ }
return true
}
diff --git a/facade/host.go b/facade/host.go
index <HASH>..<HASH> 100644
--- a/facade/host.go
+++ b/facade/host.go
@@ -262,9 +262,10 @@ func (f *Facade) UpdateHost(ctx datastore.Context, entity *host.Host) error {
defer f.DFSLock(ctx).Unlock()
// validate the host exists
- if host, err := f.GetHost(ctx, entity.ID); err != nil {
+ foundhost, err := f.GetHost(ctx, entity.ID)
+ if err != nil {
return alog.Error(err)
- } else if host == nil {
+ } else if foundhost == nil {
return alog.Error(fmt.Errorf("host does not exist: %s", entity.ID))
}
@@ -275,7 +276,6 @@ func (f *Facade) UpdateHost(ctx datastore.Context, entity *host.Host) error {
return alog.Error(fmt.Errorf("pool does not exist: %s", entity.PoolID))
}
- var err error
ec := newEventCtx()
defer f.afterEvent(afterHostAdd, ec, entity, err)
@@ -283,6 +283,9 @@ func (f *Facade) UpdateHost(ctx datastore.Context, entity *host.Host) error {
return alog.Error(err)
}
+ // Preserve the NAT IP. Delegates won't know their own.
+ entity.NatIP = foundhost.NatIP
+
entity.UpdatedAt = time.Now()
if err = f.hostStore.Put(ctx, host.HostKey(entity.ID), entity); err != nil {
return alog.Error(err) | Preserve NatIP during updateHost | control-center_serviced | train |
1b4006393abedcefb614dd4e466f5dc63fb4b87f | diff --git a/lib/user_agent_parser/parser.rb b/lib/user_agent_parser/parser.rb
index <HASH>..<HASH> 100644
--- a/lib/user_agent_parser/parser.rb
+++ b/lib/user_agent_parser/parser.rb
@@ -6,8 +6,7 @@ module UserAgentParser
attr_reader :patterns_path
def initialize(patterns_path = UserAgentParser::DefaultPatternsPath)
- @patterns_path = patterns_path
- @patterns = {}
+ @ua_patterns, @os_patterns, @device_patterns = load_patterns(patterns_path)
end
def parse(user_agent)
@@ -18,20 +17,21 @@ module UserAgentParser
private
- def all_patterns
- @all_patterns ||= YAML.load_file(@patterns_path)
- end
+ def load_patterns(path)
+ yml = YAML.load_file(path)
- def patterns(type)
- @patterns[type] ||= begin
- all_patterns[type].each do |pattern|
+ # Parse all the regexs
+ yml.each_pair do |type, patterns|
+ patterns.each do |pattern|
pattern["regex"] = Regexp.new(pattern["regex"])
end
end
+
+ [ yml["user_agent_parsers"], yml["os_parsers"], yml["device_parsers"] ]
end
def parse_ua(user_agent, os = nil, device = nil)
- pattern, match = first_pattern_match(patterns("user_agent_parsers"), user_agent)
+ pattern, match = first_pattern_match(@ua_patterns, user_agent)
if match
user_agent_from_pattern_match(pattern, match, os, device)
@@ -41,7 +41,7 @@ module UserAgentParser
end
def parse_os(user_agent)
- pattern, match = first_pattern_match(patterns("os_parsers"), user_agent)
+ pattern, match = first_pattern_match(@os_patterns, user_agent)
if match
os_from_pattern_match(pattern, match)
@@ -51,7 +51,7 @@ module UserAgentParser
end
def parse_device(user_agent)
- pattern, match = first_pattern_match(patterns("device_parsers"), user_agent)
+ pattern, match = first_pattern_match(@device_patterns, user_agent)
if match
device_from_pattern_match(pattern, match)
@@ -66,7 +66,6 @@ module UserAgentParser
return [pattern, match]
end
end
-
nil
end | Remove the need for memoized methods by simply using instance vars | ua-parser_uap-ruby | train |
06e323596015f8a54edffcf64406715dbcf9f486 | diff --git a/PHPCI/Plugin/Deployer.php b/PHPCI/Plugin/Deployer.php
index <HASH>..<HASH> 100644
--- a/PHPCI/Plugin/Deployer.php
+++ b/PHPCI/Plugin/Deployer.php
@@ -59,6 +59,8 @@ class Deployer implements \PHPCI\Plugin
$response = $http->post($this->webhookUrl, array(
'reason' => $this->phpci->interpolate($this->reason),
+ 'source' => 'PHPCI',
+ 'url' => $this->phpci->interpolate('%BUILD_URI%'),
));
return $response['success']; | Add "source" and "url" parameters to Deployer plugin. | dancryer_PHPCI | train |
fa4affb0b2482650dc63a797388c83866d077e84 | diff --git a/spec/vkontakte_api/result_spec.rb b/spec/vkontakte_api/result_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/vkontakte_api/result_spec.rb
+++ b/spec/vkontakte_api/result_spec.rb
@@ -98,6 +98,17 @@ describe VkontakteApi::Result do
}.to raise_error(VkontakteApi::Error)
end
end
+
+ context 'with execute_errors in the response' do
+ let(:error) { Hashie::Mash.new(method: 'wall.get', error_code: 15, error_msg: 'Access denied') }
+ let(:result) { Hashie::Mash.new(execute_errors: [error]) }
+
+ it 'raises a VkontakteApi::ExecuteError' do
+ expect {
+ subject.send(:extract_result, result)
+ }.to raise_error(VkontakteApi::ExecuteError)
+ end
+ end
end
describe ".typecast" do | add execute_errors case to result_spec | 7even_vkontakte_api | train |
ade0072379dc579157afc1f71ce200c5cfa581d4 | diff --git a/lib/outputrenderers.php b/lib/outputrenderers.php
index <HASH>..<HASH> 100644
--- a/lib/outputrenderers.php
+++ b/lib/outputrenderers.php
@@ -3072,7 +3072,6 @@ EOD;
case 'divider':
// If the nav item is a divider, add one and skip link processing.
$am->add($divider);
- $idx++;
break;
case 'invalid':
@@ -3098,16 +3097,15 @@ EOD;
array('class' => 'icon')
);
$am->add($al);
-
- // Add dividers after the first item and before the
- // last item.
- if ($idx == 0 || $idx == $navitemcount - 2) {
- $am->add($divider);
- }
break;
}
$idx++;
+
+ // Add dividers after the first item and before the last item.
+ if ($idx == 1 || $idx == $navitemcount - 1) {
+ $am->add($divider);
+ }
}
} | MDL-<I> user_menu: Increment index for all menu items
The invalid type was not causing the idx to incremented, thus missing off
the final divider. | moodle_moodle | train |
c4358b6eb5562a16587e6adee4d09a16de7ec10c | diff --git a/src/sos/step_executor.py b/src/sos/step_executor.py
index <HASH>..<HASH> 100755
--- a/src/sos/step_executor.py
+++ b/src/sos/step_executor.py
@@ -1187,24 +1187,36 @@ class Base_Step_Executor:
rvars = self.step.options['shared']
if isinstance(rvars, str):
result['__changed_vars__'].add(rvars)
- result['__shared__'][rvars] = copy.deepcopy(
- env.sos_dict[rvars])
+ if rvars not in env.sos_dict:
+ env.logger.warning(f'Shared variable {rvars} does not exist.')
+ else:
+ result['__shared__'][rvars] = copy.deepcopy(
+ env.sos_dict[rvars])
elif isinstance(rvars, Mapping):
result['__changed_vars__'] |= rvars.keys()
for var in rvars.keys():
- result['__shared__'][var] = copy.deepcopy(
- env.sos_dict[var])
+ if var not in env.sos_dict:
+ env.logger.warning(f'Shared variable {var} does not exist.')
+ else:
+ result['__shared__'][var] = copy.deepcopy(
+ env.sos_dict[var])
elif isinstance(rvars, Sequence):
for item in rvars:
if isinstance(item, str):
result['__changed_vars__'].add(item)
- result['__shared__'][item] = copy.deepcopy(
- env.sos_dict[item])
+ if item not in env.sos_dict:
+ env.logger.warning(f'Shared variable {item} does not exist.')
+ else:
+ result['__shared__'][item] = copy.deepcopy(
+ env.sos_dict[item])
elif isinstance(item, Mapping):
result['__changed_vars__'] |= item.keys()
for var in item.keys():
- result['__shared__'][var] = copy.deepcopy(
- env.sos_dict[var])
+ if item not in env.sos_dict:
+ env.logger.warning(f'Shared variable {item} does not exist.')
+ else:
+ result['__shared__'][var] = copy.deepcopy(
+ env.sos_dict[var])
else:
raise ValueError(
f'Option shared should be a string, a mapping of expression, or a list of string or mappings. {rvars} provided') | Adjust a warning message regarding the use of %include after %run | vatlab_SoS | train |
09f69d6979b2748527b72838d619f2bb225fefb8 | diff --git a/lib/ronin/fuzzing/extensions/string.rb b/lib/ronin/fuzzing/extensions/string.rb
index <HASH>..<HASH> 100644
--- a/lib/ronin/fuzzing/extensions/string.rb
+++ b/lib/ronin/fuzzing/extensions/string.rb
@@ -131,6 +131,64 @@ class String
end
#
+ # Repeats the String.
+ #
+ # @param [Enumerable, Integer] n
+ # The number of times to repeat the String.
+ #
+ # @yield [repeated]
+ # The given block will be passed every repeated String.
+ #
+ # @yieldparam [String] repeated
+ # A repeated version of the String.
+ #
+ # @return [Enumerator]
+ # If no block is given, an Enumerator will be returned.
+ #
+ # @raise [TypeError]
+ # `n` must either be Enumerable or an Integer.
+ #
+ # @example
+ # 'A'.repeating(100)
+ # # => "AAAAAAAAAAAAA..."
+ #
+ # @example Generates 100 upto 700 `A`s, increasing by 100 at a time:
+ # 'A'.repeating((100..700).step(100)) do |str|
+ # # ...
+ # end
+ #
+ # @example Generates 128, 1024, 65536 `A`s:
+ # 'A'.repeating([128, 1024, 65536]) do |str|
+ # # ...
+ # end
+ #
+ # @api public
+ #
+ # @since 0.4.0
+ #
+ def repeating(n)
+ if n.kind_of?(Integer)
+ # if n is an Integer, simply multiply the String and return
+ repeated = (self * n)
+
+ yield repeated if block_given?
+ return repeated
+ end
+
+ return enum_for(:repeating,n) unless block_given?
+
+ unless n.kind_of?(Enumerable)
+ raise(TypeError,"argument must be Enumerable or an Integer")
+ end
+
+ n.each do |length|
+ yield (self * length)
+ end
+
+ return self
+ end
+
+ #
# Incrementally fuzzes the String.
#
# @param [Hash{Regexp,String => #each}] substitutions
diff --git a/spec/fuzzing/string_spec.rb b/spec/fuzzing/string_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/fuzzing/string_spec.rb
+++ b/spec/fuzzing/string_spec.rb
@@ -6,6 +6,10 @@ describe String do
described_class.should respond_to(:generate)
end
+ it "should provide String#repeating" do
+ subject.should respond_to(:repeating)
+ end
+
describe "generate" do
subject { described_class }
@@ -58,6 +62,28 @@ describe String do
end
end
+ describe "#repeating" do
+ subject { 'A' }
+
+ context "when n is an Integer" do
+ let(:n) { 100 }
+
+ it "should multiply the String by n" do
+ subject.repeating(n).should == (subject * n)
+ end
+ end
+
+ context "when n is Enumerable" do
+ let(:n) { [128, 512, 1024] }
+
+ it "should repeat the String by each length" do
+ strings = subject.repeating(n).to_a
+
+ strings.should == n.map { |length| subject * n }
+ end
+ end
+ end
+
describe "#fuzz" do
subject { 'GET /one/two/three' } | Added String#repeating. | ronin-ruby_ronin-support | train |
a61e677428aca0715c4b1f5513dcb56569a72732 | diff --git a/http.go b/http.go
index <HASH>..<HASH> 100644
--- a/http.go
+++ b/http.go
@@ -163,6 +163,9 @@ func (c *Client) magicRequestDecoder(method, path string, body io.Reader, v inte
debug("Request: %+v \n", req)
res, err := c.Do(req, v)
+ if res != nil {
+ defer res.Body.Close()
+ }
debug("Response: %+v \n", res)
if err != nil {
return err | Close resp.Body when done reading from it. | go-chef_chef | train |
d90814f95f61423865187530b4ef71c6ddcee1d3 | diff --git a/src/controller.js b/src/controller.js
index <HASH>..<HASH> 100644
--- a/src/controller.js
+++ b/src/controller.js
@@ -92,13 +92,10 @@ class Controller extends EventEmitter {
}
async sendCommand(command, subscriber = () => {}) {
- let _internalId = ++this._counter
-
let promise = new Promise((resolve, reject) => {
if (this.process == null) this.start()
let commandString = Command.toString(command)
-
if (commandString.trim() === '') {
let response = Response.fromString('')
@@ -108,10 +105,19 @@ class Controller extends EventEmitter {
return
}
+ let _internalId = ++this._counter
let eventName = `response-${_internalId}`
let content = ''
let firstLine = true
+ let handleExit = () => reject(new Error('GTP engine has stopped'))
+ let cleanUp = () => {
+ this._responseLineEmitter.removeAllListeners(eventName)
+ this.process.removeListener('exit', handleExit)
+ }
+
+ this.process.once('exit', handleExit)
+
this._responseLineEmitter.on(eventName, ({line, end}) => {
if (firstLine && (line.length === 0 || !'=?'.includes(line[0]))) {
// Ignore
@@ -127,8 +133,8 @@ class Controller extends EventEmitter {
if (!end) return
content = ''
- this._responseLineEmitter.removeAllListeners(eventName)
+ cleanUp()
resolve(response)
})
@@ -136,7 +142,7 @@ class Controller extends EventEmitter {
this.commands.push(Object.assign({_internalId}, command))
this.process.stdin.write(commandString + '\n')
} catch (err) {
- this._responseLineEmitter.removeAllListeners(eventName)
+ cleanUp()
reject(new Error('GTP engine connection error'))
}
}) | Ensure controller.sendCommand() rejects when engine stops | SabakiHQ_gtp | train |
ba2f7af3ddfbedda7d9897fbdf91443c69f95d04 | diff --git a/aws/resource_aws_apprunner_service.go b/aws/resource_aws_apprunner_service.go
index <HASH>..<HASH> 100644
--- a/aws/resource_aws_apprunner_service.go
+++ b/aws/resource_aws_apprunner_service.go
@@ -736,7 +736,7 @@ func expandAppRunnerServiceImageConfiguration(l []interface{}) *apprunner.ImageC
}
if v, ok := tfMap["runtime_environment_variables"].(map[string]interface{}); ok && len(v) > 0 {
- result.RuntimeEnvironmentVariables = expandStringMap(v)
+ result.RuntimeEnvironmentVariables = flex.ExpandStringMap(v)
}
if v, ok := tfMap["start_command"].(string); ok && v != "" {
@@ -852,7 +852,7 @@ func expandAppRunnerServiceCodeConfigurationValues(l []interface{}) *apprunner.C
}
if v, ok := tfMap["runtime_environment_variables"].(map[string]interface{}); ok && len(v) > 0 {
- result.RuntimeEnvironmentVariables = expandStringMap(v)
+ result.RuntimeEnvironmentVariables = flex.ExpandStringMap(v)
}
if v, ok := tfMap["start_command"].(string); ok && v != "" { | apprunner: Migrate to service, global flex | terraform-providers_terraform-provider-aws | train |
a7bc53b5ada2ab4cac081c9e7295e9a8665ef09a | diff --git a/javamelody-core/src/main/java/net/bull/javamelody/Stopwatch.java b/javamelody-core/src/main/java/net/bull/javamelody/Stopwatch.java
index <HASH>..<HASH> 100644
--- a/javamelody-core/src/main/java/net/bull/javamelody/Stopwatch.java
+++ b/javamelody-core/src/main/java/net/bull/javamelody/Stopwatch.java
@@ -1,5 +1,6 @@
package net.bull.javamelody;
+import net.bull.javamelody.internal.common.Parameters;
import net.bull.javamelody.internal.model.Counter;
/**
@@ -9,6 +10,8 @@ import net.bull.javamelody.internal.model.Counter;
*/
public class Stopwatch implements AutoCloseable {
private static final Counter SERVICES_COUNTER = MonitoringProxy.getServicesCounter();
+ private static final boolean COUNTER_HIDDEN = Parameters
+ .isCounterHidden(SERVICES_COUNTER.getName());
private final String name;
private final long startTime;
@@ -26,6 +29,8 @@ public class Stopwatch implements AutoCloseable {
*/
public Stopwatch(String stopwatchName) {
super();
+ SERVICES_COUNTER.setDisplayed(!COUNTER_HIDDEN);
+ SERVICES_COUNTER.setUsed(true);
SERVICES_COUNTER.bindContextIncludingCpu(stopwatchName);
this.startTime = System.currentTimeMillis();
this.name = stopwatchName; | fix #<I> StopWatch not displayed in statistics by default | javamelody_javamelody | train |
ebcb702d1b583f6b66fb6ccd2b15939d5402dc1e | diff --git a/lib/stellar-base.rb b/lib/stellar-base.rb
index <HASH>..<HASH> 100644
--- a/lib/stellar-base.rb
+++ b/lib/stellar-base.rb
@@ -30,3 +30,4 @@ require_relative './stellar/util/strkey'
require_relative './stellar/util/continued_fraction'
require_relative './stellar/convert'
require_relative './stellar/networks'
+require_relative './stellar/base/version' | fix for issuer#<I> missing VERSION | stellar_ruby-stellar-base | train |
6c35e5b36a918f50c7dd2cb581ae3bdbc117d16f | diff --git a/tests/Common.php b/tests/Common.php
index <HASH>..<HASH> 100644
--- a/tests/Common.php
+++ b/tests/Common.php
@@ -23,13 +23,13 @@ function prepare_config_sql($engine=null, $config_file=null) {
'POSTGRES_HOST' => 'localhost',
'POSTGRES_PORT' => 5432,
'POSTGRES_USER' => 'postgres',
- 'POSTGRES_PASS' => 'XxXxXxXxX',
+ 'POSTGRES_PASS' => '',
'POSTGRES_DB' => 'zapstore_test_db',
'MYSQL_HOST' => '127.0.0.1',
'MYSQL_PORT' => '3306',
'MYSQL_USER' => 'root',
- 'MYSQL_PASS' => 'XxXxXxXxX',
+ 'MYSQL_PASS' => '',
'MYSQL_DB' => 'zapstore_test_db',
];
foreach ($params as $key => $val) { | Remove db passwords from test config stub.
Setting passwords will fail on unpassworded databases such as in
Travis environment. | bfitech_zapstore | train |
beb94fdda0ccebff67393615581f870b381a2c29 | diff --git a/index.js b/index.js
index <HASH>..<HASH> 100644
--- a/index.js
+++ b/index.js
@@ -497,6 +497,7 @@ osmtogeojson = function( data, options ) {
has_interesting_tags(node.tags)) // this checks if the node has any tags other than "created_by"
poinids[node.id] = true;
}
+ // todo -> after deduplication of relations??
for (var i=0;i<rels.length;i++) {
if (_.isArray(rels[i].members)) {
for (var j=0;j<rels[i].members.length;j++) {
@@ -516,6 +517,7 @@ osmtogeojson = function( data, options ) {
wayids[way.id] = way;
if (_.isArray(way.nodes)) {
for (var j=0;j<way.nodes.length;j++) {
+ if (typeof way.nodes[j] === "object") continue; // ignore already replaced way node objects
waynids[way.nodes[j]] = true;
way.nodes[j] = nodeids[way.nodes[j]];
}
@@ -838,6 +840,11 @@ osmtogeojson = function( data, options ) {
}
// process lines and polygons
for (var i=0;i<ways.length;i++) {
+ // todo: refactor such that this loops over wayids instead of ways?
+ if (wayids[ways[i].id] !== ways[i]) {
+ // skip way because it's a deduplication artifact
+ continue;
+ }
if (!_.isArray(ways[i].nodes)) {
if (options.verbose) console.warn('Way',ways[i].type+'/'+ways[i].id,'ignored because it has no nodes');
continue; // ignore ways without nodes (e.g. returned by an ids_only query)
diff --git a/test/osm.test.js b/test/osm.test.js
index <HASH>..<HASH> 100644
--- a/test/osm.test.js
+++ b/test/osm.test.js
@@ -3623,6 +3623,63 @@ describe("duplicate elements", function () {
expect(geojson.features[0].geometry.coordinates).to.have.length(2);
});
+ it("way, different versions", function () {
+ var json, geojson;
+
+ // do not include full geometry nd's as node in output
+ json = {
+ elements: [
+ {
+ type: "way",
+ id: 1,
+ version: 1,
+ nodes: [1,2],
+ tags: {
+ "foo": "bar",
+ "dupe": "x"
+ }
+ },
+ {
+ type: "way",
+ id: 1,
+ version: 2,
+ nodes: [1,2,3],
+ tags: {
+ "asd": "fasd",
+ "dupe": "y"
+ }
+ },
+ {
+ type: "node",
+ id: 1,
+ lat: 1,
+ lon: 1
+ },
+ {
+ type: "node",
+ id: 2,
+ lat: 2,
+ lon: 2
+ },
+ {
+ type: "node",
+ id: 3,
+ lat: 3,
+ lon: 3
+ }
+ ]
+ };
+ geojson = osmtogeojson.toGeojson(json);
+
+ expect(geojson.features.length).to.eql(1);
+ expect(geojson.features[0].id).to.eql("way/1");
+ expect(geojson.features[0].properties.meta.version).to.eql(2);
+ expect(geojson.features[0].properties.tags.foo).to.be(undefined);
+ expect(geojson.features[0].properties.tags.dupe).to.eql("y");
+ expect(geojson.features[0].properties.tags.asd).to.eql("fasd");
+ expect(geojson.features[0].geometry.coordinates).to.have.length(3);
+ });
+
it("relation", function () {
var json, geojson;
@@ -3688,7 +3745,7 @@ describe("duplicate elements", function () {
expect(geojson.features[0].properties.tags.foo).to.eql("2");
});
- it("node, different version", function () {
+ it("custom deduplicator", function () {
var json, geojson;
// do not include full geometry nd's as node in output | fix and test deduplication of ways with different versions | tyrasd_osmtogeojson | train |
e9055e0fde8493e8ad98310b5f3c23c7d3324d24 | diff --git a/README.md b/README.md
index <HASH>..<HASH> 100644
--- a/README.md
+++ b/README.md
@@ -94,6 +94,9 @@ Each of them are discussed in the documentation below.
- [findFirst(options = {})](#findfirstoptions--)
- [findCount(options = {})](#findcountoptions--)
- [findList(options = {})](#findlistoptions--)
+ - [findBy(field, value, options = {})](#findbyfield-value-options--)
+ - [findById(value, options = {})](#findbyidvalue-options--)
+ - [findByKey(value, options = {})](#findbykeyvalue-options--)
- [save(model, options = {})](#savemodel-options--)
- [delete(model)](#deletemodel)
- [Models](#models)
@@ -553,6 +556,44 @@ Returns a promise with key/value pair of matched results.
Same as `collection.find('list', options)`.
+### findBy(field, value, options = {})
+
+Shortcut method for finding a single record.
+
+Same as:
+
+```js
+collection.find('first', {
+ conditions: {
+ field: value
+ }
+});
+```
+
+Returns a promise.
+
+### findById(value, options = {})
+
+Shortcut method for finding record by ID.
+
+Same as:
+
+```js
+collection.find('first', {
+ conditions: {
+ id: value // `id` key comes from `model.primaryKey
+ }
+});
+```
+
+Returns a promise.
+
+### findByKey(value, options = {})
+
+Alias for `collection.findById()`.
+
+Returns a promise.
+
### save(model, options = {})
Save the given model. This method is not usually called directly, but rather via `Model.save()`.
diff --git a/src/Collection.js b/src/Collection.js
index <HASH>..<HASH> 100644
--- a/src/Collection.js
+++ b/src/Collection.js
@@ -283,6 +283,60 @@ export default class Collection {
});
}
+// ### findBy(field, value, options = {})
+//
+// Shortcut method for finding a single record.
+//
+// Same as:
+//
+// ```js
+// collection.find('first', {
+// conditions: {
+// field: value
+// }
+// });
+// ```
+//
+// Returns a promise.
+//
+ findBy(field, value, options = {}) {
+ return this.find('first', _.merge({
+ conditions: {
+ [field]: value
+ }
+ }, options));
+ }
+
+// ### findById(value, options = {})
+//
+// Shortcut method for finding record by ID.
+//
+// Same as:
+//
+// ```js
+// collection.find('first', {
+// conditions: {
+// id: value // `id` key comes from `model.primaryKey
+// }
+// });
+// ```
+//
+// Returns a promise.
+//
+ findById(value, options = {}) {
+ return this.findBy(this.primaryKey, value, options);
+ }
+
+// ### findByKey(value, options = {})
+//
+// Alias for `collection.findById()`.
+//
+// Returns a promise.
+//
+ findByKey(value, options = {}) {
+ return this.findById(value, options);
+ }
+
// ### save(model, options = {})
//
// Save the given model. This method is not usually called directly, but rather via `Model.save()`.
diff --git a/src/test/cases/Collection.js b/src/test/cases/Collection.js
index <HASH>..<HASH> 100644
--- a/src/test/cases/Collection.js
+++ b/src/test/cases/Collection.js
@@ -93,4 +93,26 @@ describe('Collection', function () {
throw error;
});
});
+
+ it('should find single result by primaryKey', function (done) {
+ var posts = new this.Posts();
+ var promise = posts.findById(1);
+
+ promise.then(function (post) {
+ post.get('title').should.equal('Hello World');
+ done();
+ }).catch(function (error) {
+ throw error;
+ });
+ });
+
+ it('should find single result by field', function (done) {
+ var posts = new this.Posts();
+ posts.findBy('title', 'Hello World').then(function (post) {
+ post.get('title').should.equal('Hello World');
+ done();
+ }).catch(function (error) {
+ throw error;
+ });
+ });
}); | collections: shortcut methods for finding single methods with conditions. Closes #<I> | fahad19_firenze | train |
6eca6e9bd2673e930b93062f5b0bb94b0486541f | diff --git a/ArgusWeb/app/js/directives/charts/lineChart.js b/ArgusWeb/app/js/directives/charts/lineChart.js
index <HASH>..<HASH> 100644
--- a/ArgusWeb/app/js/directives/charts/lineChart.js
+++ b/ArgusWeb/app/js/directives/charts/lineChart.js
@@ -15,31 +15,28 @@ angular.module('argus.directives.charts.lineChart', [])
templateUrl: 'js/templates/charts/topToolbar.html',
controller: ['$scope', function($scope) {
$scope.toggleSource = function(source) {
- toggleGraphOnOff(source.name);
+ debugger;
+ toggleGraphOnOff(source);
};
// show ONLY this 1 source, hide all others
$scope.hideOtherSources = function(sourceToShow, sources) {
for (var i = 0; i < sources.length; i++) {
if (sourceToShow.name !== sources[i].name) {
- toggleGraphOnOff(sources[i].name);
+ toggleGraphOnOff(sources[i]);
}
}
};
$scope.labelTextColor = function(source) {
- var graphID = "path[id='" + source.name.replace(/\s+/g, '') +"']";
- if (d3.select(graphID).style("opacity") === "1") {
- return 'blue';
- } else {
- return 'grey';
- }
+ return source.displaying? 'blue': 'gray';
};
- function toggleGraphOnOff(sourceName) {
+ function toggleGraphOnOff(source) {
// d3 select with dot in ID name: http://stackoverflow.com/questions/33502614/d3-how-to-select-element-by-id-when-there-is-a-dot-in-id
- var graphID = "path[id='" + sourceName.replace(/\s+/g, '') +"']";
- var newOpacity = 1 - d3.select(graphID).style("opacity"); // not type strict. . .
+ var graphID = "path[id='" + source.name.replace(/\s+/g, '') +"']";
+ var newOpacity = source.displaying? 0 : 1;
+ source.displaying = !source.displaying;
d3.select(graphID)
.transition().duration(100)
.style("opacity", newOpacity);
@@ -349,9 +346,12 @@ angular.module('argus.directives.charts.lineChart', [])
return function(group, datapoints) {
var tmpSources = [];
for (var i = 0; i < datapoints.length; i++) {
+ var tempColor = colors[i] === null? z(names[i]): colors[i];
tmpSources.push({
name: names[i],
- value: datapoints[i][1]
+ value: datapoints[i][1],
+ displaying: true,
+ color: tempColor
});
}
diff --git a/ArgusWeb/app/js/services/charts/dataProcessing.js b/ArgusWeb/app/js/services/charts/dataProcessing.js
index <HASH>..<HASH> 100644
--- a/ArgusWeb/app/js/services/charts/dataProcessing.js
+++ b/ArgusWeb/app/js/services/charts/dataProcessing.js
@@ -1,3 +1,5 @@
+'use strict';
+
angular.module('argus.services.charts.dataProcessing', [])
.service('ChartDataProcessingService', ['ChartOptionService', 'Annotations', function(ChartOptionService, Annotations) {
'use strict';
@@ -21,14 +23,14 @@ angular.module('argus.services.charts.dataProcessing', [])
result.push({name: 'result', data: []});
}
return result;
- };
+ }
function createSeriesName(metric) {
var scope = metric.scope;
var name = metric.metric;
var tags = createTagString(metric.tags);
return scope + ':' + name + tags;
- };
+ }
function createTagString(tags) {
var result = '';
@@ -44,7 +46,7 @@ angular.module('argus.services.charts.dataProcessing', [])
}
}
return result;
- };
+ }
function copyFlagSeries(data) {
var result;
@@ -59,7 +61,7 @@ angular.module('argus.services.charts.dataProcessing', [])
result = null;
}
return result;
- };
+ }
function formatFlagText(fields) {
var result = '';
@@ -71,7 +73,7 @@ angular.module('argus.services.charts.dataProcessing', [])
}
}
return result;
- };
+ }
// Public Service methods
var service = { | resolve some lagging/performance issue | salesforce_Argus | train |
13a893429fbc99cc798adfd9994104250c16ec54 | diff --git a/addons/info/src/index.test.js b/addons/info/src/index.test.js
index <HASH>..<HASH> 100644
--- a/addons/info/src/index.test.js
+++ b/addons/info/src/index.test.js
@@ -20,7 +20,8 @@ const TestComponent = ({ func, obj, array, number, string, bool, empty }) => (
<li>1</li>
<li>2</li>
</ul>
- </div>);
+ </div>
+);
/* eslint-enable */
const reactClassPath = 'some/path/TestComponent.jsx';
@@ -31,7 +32,7 @@ const storybookReactClassMock = {
description: `
# Awesome test component description
## with markdown support
-**bold** *cursive*
+**bold** *cursive*
`,
name: 'TestComponent',
},
@@ -45,9 +46,9 @@ containing **bold**, *cursive* text, \`code\` and [a link](https://github.com)`;
describe('addon Info', () => {
// eslint-disable-next-line react/prop-types
- const storyFn = ({ story }) => (
+ const storyFn = ({ name }) => (
<div>
- It's a {story} story:
+ It's a {name} story:
<TestComponent
func={x => x + 1}
obj={{ a: 'a', b: 'b' }}
@@ -85,7 +86,7 @@ describe('addon Info', () => {
const Info = () =>
withInfo({ inline: true, propTables: false })(storyFn, {
kind: 'TestComponent',
- story: 'Basic test',
+ name: 'Basic test',
});
expect(mount(<Info />)).toMatchSnapshot();
@@ -100,7 +101,7 @@ describe('addon Info', () => {
const Info = () =>
withInfo({ inline: true, propTables: false })(storyFn, {
kind: 'Test Components',
- story: 'TestComponent',
+ name: 'TestComponent',
});
expect(mount(<Info />)).toMatchSnapshot(); | Update test to reflect context prop name change | storybooks_storybook | train |
af1dffda642068713b57d377bdb23a87432b702d | diff --git a/Swat/SwatHtmlHeadEntrySetDisplayer.php b/Swat/SwatHtmlHeadEntrySetDisplayer.php
index <HASH>..<HASH> 100644
--- a/Swat/SwatHtmlHeadEntrySetDisplayer.php
+++ b/Swat/SwatHtmlHeadEntrySetDisplayer.php
@@ -178,6 +178,8 @@ class SwatHtmlHeadEntrySetDisplayer extends SwatObject
foreach ($info['combines'] as $combine) {
if (substr($combine, -4) === '.css') {
$class_name = 'SwatStyleSheetHtmlHeadEntry';
+ } elseif (substr($combine, -5) === '.less') {
+ $class_name = 'SwatLessStyleSheetHtmlHeadEntry';
} else {
$class_name = 'SwatJavaScriptHtmlHeadEntry';
} | Support displaying combined LESS files.
svn commit r<I> | silverorange_swat | train |
313b74029f3ff2fb4d89667a362c82a03c72e3d6 | diff --git a/pysnow.py b/pysnow.py
index <HASH>..<HASH> 100644
--- a/pysnow.py
+++ b/pysnow.py
@@ -129,10 +129,20 @@ class Query(object):
def greater_than(self, value):
"""Query records with the given field greater than the value specified"""
- return self._add_condition('>', value, types=[int])
+ if hasattr(value, 'strftime'):
+ value = value.strftime('%Y-%m-%d %H:%M:%S')
+ elif isinstance(value, str):
+ raise QueryTypeError('Expected value of type `int` or instance of `datetime`, not %s' % type(value))
+
+ return self._add_condition('>', value, types=[int, str])
def less_than(self, value):
"""Query records with the given field less than the value specified"""
+ if hasattr(value, 'strftime'):
+ value = value.strftime('%Y-%m-%d %H:%M:%S')
+ elif isinstance(value, str):
+ raise QueryTypeError('Expected value of type `int` or instance of `datetime`, not %s' % type(value))
+
return self._add_condition('<', value, types=[int])
def between(self, start, end): | Added support for passing datetime objects to greater_than() and less_than | rbw_pysnow | train |
f0876daebc7c0b0496874366ca941fa09c9f9264 | diff --git a/bids/variables/io.py b/bids/variables/io.py
index <HASH>..<HASH> 100644
--- a/bids/variables/io.py
+++ b/bids/variables/io.py
@@ -303,8 +303,8 @@ def _load_time_variables(layout, dataset=None, columns=None, scan_length=None,
if regressors:
sub_ents = {k: v for k, v in entities.items()
if k in BASE_ENTITIES}
- confound_files = layout.get(suffix='regressors', scope=scope,
- **sub_ents)
+ confound_files = layout.get(suffix=['regressors', 'timeseries'],
+ scope=scope, **sub_ents)
for cf in confound_files:
_data = pd.read_csv(cf.path, sep='\t', na_values='n/a')
if columns is not None: | ENH: Accept variables from timeseries as well as regressors (#<I>)
* ENH: Accept variables from timeseries as well as regressors
* FIX: Maybe most of these should remain... | bids-standard_pybids | train |
a3909df89c81143e63eb80b14e0f215f5f81f3ec | diff --git a/core/phantomas.js b/core/phantomas.js
index <HASH>..<HASH> 100644
--- a/core/phantomas.js
+++ b/core/phantomas.js
@@ -82,6 +82,9 @@ var phantomas = function(params) {
// --user-agent=custom-agent
this.userAgent = params['user-agent'] || getDefaultUserAgent();
+ // disable JavaScript on the page that will be loaded
+ this.disableJs = params['disable-js'] === true;
+
// cookie handling via command line and config.json
phantom.cookiesEnabled = true;
@@ -361,6 +364,12 @@ phantomas.prototype = {
this.page.settings.userAgent = this.userAgent;
}
+ // disable JavaScript on the page that will be loaded
+ if (this.disableJs) {
+ this.page.settings.javascriptEnabled = false;
+ this.log('JavaScript execution disabled by --disable-js!');
+ }
+
// print out debug messages
this.log('Opening <' + this.url + '>...');
this.log('Using ' + this.page.settings.userAgent + ' as user agent'); | Make it possible to disable JavaScript on the page | macbre_phantomas | train |
1c6d95e0645edce3843c51700f251a15ca22c1bd | diff --git a/packages/vaex-core/vaex/asyncio.py b/packages/vaex-core/vaex/asyncio.py
index <HASH>..<HASH> 100644
--- a/packages/vaex-core/vaex/asyncio.py
+++ b/packages/vaex-core/vaex/asyncio.py
@@ -5,7 +5,7 @@ import sys
def check_ipython():
IPython = sys.modules.get('IPython')
if IPython:
- IPython_version = tuple(map(int, IPython.__version__.split('.')))
+ IPython_version = tuple(map(int, IPython.__version__.split('.')[:3]))
if IPython_version < (7, 0, 0):
raise RuntimeError(f'You are using IPython {IPython.__version__} while we require 7.0.0, please update IPython') | Fix version compare when running development IPython which has versions
like <I>.dev. #<I> | vaexio_vaex | train |
46c60a881f950b627c5f49ed0a7bb274ac002dea | diff --git a/mill/__init__.py b/mill/__init__.py
index <HASH>..<HASH> 100644
--- a/mill/__init__.py
+++ b/mill/__init__.py
@@ -454,7 +454,6 @@ class Mill:
return
heater.day_consumption = float(cons.get("valueTotal"))
- heater.last_consumption_update = dt.datetime.now()
cons = await self.request_stats(
"statisticDeviceForAndroid", | Fix last_consumption_update (#<I>) | Danielhiversen_pymill | train |
e391c47ed8e6b4e68ec6e97b2ea3195a198e218f | diff --git a/testing/logging/test_reporting.py b/testing/logging/test_reporting.py
index <HASH>..<HASH> 100644
--- a/testing/logging/test_reporting.py
+++ b/testing/logging/test_reporting.py
@@ -889,6 +889,12 @@ def test_live_logging_suspends_capture(has_capture_manager, request):
def resume_global_capture(self):
self.calls.append("resume_global_capture")
+ def activate_fixture(self, item=None):
+ self.calls.append("activate_fixture")
+
+ def deactivate_fixture(self, item=None):
+ self.calls.append("deactivate_fixture")
+
# sanity check
assert CaptureManager.suspend_capture_item
assert CaptureManager.resume_global_capture
@@ -909,8 +915,10 @@ def test_live_logging_suspends_capture(has_capture_manager, request):
logger.critical("some message")
if has_capture_manager:
assert MockCaptureManager.calls == [
+ "deactivate_fixture",
"suspend_global_capture",
"resume_global_capture",
+ "activate_fixture",
]
else:
assert MockCaptureManager.calls == [] | Update capture suspend test for logging. | pytest-dev_pytest | train |
866ad91f763b2312e8a5b9905be017bc98eb609d | diff --git a/lib/hrr_rb_ssh/transport/kex_algorithm/diffie_hellman.rb b/lib/hrr_rb_ssh/transport/kex_algorithm/diffie_hellman.rb
index <HASH>..<HASH> 100644
--- a/lib/hrr_rb_ssh/transport/kex_algorithm/diffie_hellman.rb
+++ b/lib/hrr_rb_ssh/transport/kex_algorithm/diffie_hellman.rb
@@ -23,7 +23,12 @@ module HrrRbSsh
@logger = HrrRbSsh::Logger.new self.class.name
@dh = OpenSSL::PKey::DH.new
- @dh.set_pqg OpenSSL::BN.new(self.class::P, 16), nil, OpenSSL::BN.new(self.class::G)
+ if @dh.respond_to?(:set_pqg)
+ @dh.set_pqg OpenSSL::BN.new(self.class::P, 16), nil, OpenSSL::BN.new(self.class::G)
+ else
+ @dh.p = OpenSSL::BN.new(self.class::P, 16)
+ @dh.g = OpenSSL::BN.new(self.class::G)
+ end
@dh.generate_key!
end
diff --git a/spec/hrr_rb_ssh/transport/kex_algorithm/diffie_hellman_group14_sha1_spec.rb b/spec/hrr_rb_ssh/transport/kex_algorithm/diffie_hellman_group14_sha1_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/hrr_rb_ssh/transport/kex_algorithm/diffie_hellman_group14_sha1_spec.rb
+++ b/spec/hrr_rb_ssh/transport/kex_algorithm/diffie_hellman_group14_sha1_spec.rb
@@ -26,7 +26,12 @@ RSpec.describe HrrRbSsh::Transport::KexAlgorithm::DiffieHellmanGroup14Sha1 do
}
let(:remote_dh){
dh = OpenSSL::PKey::DH.new
- dh.set_pqg OpenSSL::BN.new(dh_group14_p, 16), nil, OpenSSL::BN.new(dh_group14_g)
+ if dh.respond_to?(:set_pqg)
+ dh.set_pqg OpenSSL::BN.new(dh_group14_p, 16), nil, OpenSSL::BN.new(dh_group14_g)
+ else
+ dh.p = OpenSSL::BN.new(dh_group14_p, 16)
+ dh.g = OpenSSL::BN.new(dh_group14_g)
+ end
dh.generate_key!
dh
}
diff --git a/spec/hrr_rb_ssh/transport/kex_algorithm/diffie_hellman_group1_sha1_spec.rb b/spec/hrr_rb_ssh/transport/kex_algorithm/diffie_hellman_group1_sha1_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/hrr_rb_ssh/transport/kex_algorithm/diffie_hellman_group1_sha1_spec.rb
+++ b/spec/hrr_rb_ssh/transport/kex_algorithm/diffie_hellman_group1_sha1_spec.rb
@@ -18,7 +18,12 @@ RSpec.describe HrrRbSsh::Transport::KexAlgorithm::DiffieHellmanGroup1Sha1 do
}
let(:remote_dh){
dh = OpenSSL::PKey::DH.new
- dh.set_pqg OpenSSL::BN.new(dh_group1_p, 16), nil, OpenSSL::BN.new(dh_group1_g)
+ if dh.respond_to?(:set_pqg)
+ dh.set_pqg OpenSSL::BN.new(dh_group1_p, 16), nil, OpenSSL::BN.new(dh_group1_g)
+ else
+ dh.p = OpenSSL::BN.new(dh_group1_p, 16)
+ dh.g = OpenSSL::BN.new(dh_group1_g)
+ end
dh.generate_key!
dh
}
diff --git a/spec/hrr_rb_ssh/transport_spec.rb b/spec/hrr_rb_ssh/transport_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/hrr_rb_ssh/transport_spec.rb
+++ b/spec/hrr_rb_ssh/transport_spec.rb
@@ -331,7 +331,12 @@ RSpec.describe HrrRbSsh::Transport do
}
let(:remote_dh){
dh = OpenSSL::PKey::DH.new
- dh.set_pqg OpenSSL::BN.new(dh_group14_p, 16), nil, OpenSSL::BN.new(dh_group14_g)
+ if dh.respond_to?(:set_pqg)
+ dh.set_pqg OpenSSL::BN.new(dh_group14_p, 16), nil, OpenSSL::BN.new(dh_group14_g)
+ else
+ dh.p = OpenSSL::BN.new(dh_group14_p, 16)
+ dh.g = OpenSSL::BN.new(dh_group14_g)
+ end
dh.generate_key!
dh
} | update transport/kex_algorithm/diffie_hellman codes and their specs to support older version of OpenSSL library that does not support set_pqg method | hirura_hrr_rb_ssh | train |
1f516c2dd01e9795e3db6400696f144dff755c9f | diff --git a/openhtf/exe/__init__.py b/openhtf/exe/__init__.py
index <HASH>..<HASH> 100644
--- a/openhtf/exe/__init__.py
+++ b/openhtf/exe/__init__.py
@@ -38,6 +38,10 @@ conf.Declare('teardown_timeout_s', default_value=3, description=
'Timeout (in seconds) for test teardown functions.')
+class TestExecutionError(Exception):
+ """Raised when there's an internal error during test execution."""
+
+
class TestStopError(Exception):
"""Test is being stopped."""
diff --git a/openhtf/exe/phase_executor.py b/openhtf/exe/phase_executor.py
index <HASH>..<HASH> 100644
--- a/openhtf/exe/phase_executor.py
+++ b/openhtf/exe/phase_executor.py
@@ -182,10 +182,6 @@ class PhaseExecutor(object):
self._execute_one_phase(teardown_func, output_record=False)
yield outcome
- # We shouldn't keep executing if the outcome was terminal.
- if outcome.is_terminal:
- raise IndexError('Kept executing phases after terminal outcome.')
-
# If we're done with this phase, skip to the next one.
if outcome.phase_result is openhtf.PhaseResult.CONTINUE:
break
diff --git a/openhtf/exe/test_state.py b/openhtf/exe/test_state.py
index <HASH>..<HASH> 100644
--- a/openhtf/exe/test_state.py
+++ b/openhtf/exe/test_state.py
@@ -216,6 +216,10 @@ class TestState(object):
# TODO(madsci): Decouple flow control from pass/fail.
self.finalize(test_record.Outcome.ABORTED)
+ if self.is_finalized != phase_outcome.is_terminal:
+ raise exe.TestExecutionError(
+ 'Unexpected finalized state (%s) after PhaseOutcome %s.',
+ self.is_finalized, phase_outcome)
return self.is_finalized
def TestStarted(self, dut_id): | move is_finalized check to a more obvious place | google_openhtf | train |
f819d85428947c416b0f1f7c95dfa9471fc4e638 | diff --git a/utils/src/main/java/jetbrains/exodus/core/execution/Job.java b/utils/src/main/java/jetbrains/exodus/core/execution/Job.java
index <HASH>..<HASH> 100644
--- a/utils/src/main/java/jetbrains/exodus/core/execution/Job.java
+++ b/utils/src/main/java/jetbrains/exodus/core/execution/Job.java
@@ -19,6 +19,8 @@ import jetbrains.exodus.core.dataStructures.Priority;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
+import java.util.Date;
+
public abstract class Job {
private JobProcessor processor;
@@ -28,12 +30,15 @@ public abstract class Job {
@Nullable
private JobHandler[] jobFinishedHandlers;
private Thread executingThread;
+ private long startedAt;
protected Job() {
processor = null;
wasQueued = false;
jobStartingHandlers = null;
jobFinishedHandlers = null;
+ executingThread = null;
+ startedAt = 0L;
}
protected Job(@NotNull final JobProcessor processor) {
@@ -74,15 +79,25 @@ public abstract class Job {
@Override
public String toString() {
- return getGroup() + ": " + getName();
+ final StringBuilder result = new StringBuilder(100);
+ result.append(getGroup());
+ result.append(": ");
+ result.append(getName());
+ if (startedAt > 0L) {
+ result.append(", started at: ");
+ result.append(new Date(startedAt).toString()
+ .substring(4) // skip day of the week
+ );
+ }
+ return result.toString();
}
public Thread getExecutingThread() {
return executingThread;
}
- void setExecutingThread(Thread executingThread) {
- this.executingThread = executingThread;
+ public long getStartedAt() {
+ return startedAt;
}
/**
@@ -106,7 +121,10 @@ public abstract class Job {
jobFinishedHandlers = JobHandler.append(jobFinishedHandlers, handler);
}
- final void run(@Nullable final JobProcessorExceptionHandler handler) {
+ final void run(@Nullable final JobProcessorExceptionHandler handler,
+ @NotNull final Thread executingThread) {
+ this.executingThread = executingThread;
+ startedAt = System.currentTimeMillis();
Throwable exception = null;
JobHandler.invokeHandlers(jobStartingHandlers, this);
try {
diff --git a/utils/src/main/java/jetbrains/exodus/core/execution/JobProcessorAdapter.java b/utils/src/main/java/jetbrains/exodus/core/execution/JobProcessorAdapter.java
index <HASH>..<HASH> 100644
--- a/utils/src/main/java/jetbrains/exodus/core/execution/JobProcessorAdapter.java
+++ b/utils/src/main/java/jetbrains/exodus/core/execution/JobProcessorAdapter.java
@@ -214,7 +214,7 @@ public abstract class JobProcessorAdapter implements JobProcessor {
processor.beforeProcessingJob(job);
JobHandler.invokeHandlers(jobStartingHandlers, job);
try {
- job.run(exceptionHandler);
+ job.run(exceptionHandler, Thread.currentThread());
} finally {
JobHandler.invokeHandlers(jobFinishedHandlers, job);
}
diff --git a/utils/src/main/java/jetbrains/exodus/core/execution/ThreadJobProcessor.java b/utils/src/main/java/jetbrains/exodus/core/execution/ThreadJobProcessor.java
index <HASH>..<HASH> 100644
--- a/utils/src/main/java/jetbrains/exodus/core/execution/ThreadJobProcessor.java
+++ b/utils/src/main/java/jetbrains/exodus/core/execution/ThreadJobProcessor.java
@@ -96,15 +96,6 @@ public class ThreadJobProcessor extends JobProcessorQueueAdapter {
return thread.toString();
}
- @Override
- protected boolean push(Job job, Priority priority) {
- final boolean result = super.push(job, priority);
- if (result) {
- job.setExecutingThread(thread);
- }
- return result;
- }
-
public long getId() {
return thread.getId();
}
@@ -139,7 +130,7 @@ public class ThreadJobProcessor extends JobProcessorQueueAdapter {
JobHandler.invokeHandlers(jobStartingHandlers, job);
try {
thread.setContextClassLoader(job.getClass().getClassLoader());
- job.run(exceptionHandler);
+ job.run(exceptionHandler, thread);
} finally {
thread.setContextClassLoader(classLoader);
JobHandler.invokeHandlers(jobFinishedHandlers, job); | Job sets executing thread and start time by itself | JetBrains_xodus | train |
33d004fb9a50eb57774b71b4721f16ed0fd80f7a | diff --git a/lib/express/spec/mocks.js b/lib/express/spec/mocks.js
index <HASH>..<HASH> 100644
--- a/lib/express/spec/mocks.js
+++ b/lib/express/spec/mocks.js
@@ -108,7 +108,7 @@ var MockResponse = new Class({
* Flag response as finished.
*/
- close: function() {
+ end: function() {
this.finished = true
}
}) | Fixed MockResponse to match node API | expressjs_express | train |
f58fc796488b490ec23f49e62dd672e8a4e1dd04 | diff --git a/core/test/karma.conf.js b/core/test/karma.conf.js
index <HASH>..<HASH> 100644
--- a/core/test/karma.conf.js
+++ b/core/test/karma.conf.js
@@ -25,7 +25,8 @@ module.exports = function(config) {
'../../core/lib/popover-animator.es6',
'../../core/lib/*.{es6,js}',
'../../core/*.{es6,js}',
- '../../core/elements/*.{es6,js}'
+ '../../core/elements/*.{es6,js}',
+ '../../build/css/onsenui.css'
],
// list of files to exclude | fix(test): Include onsenui.css in karma tests. | OnsenUI_OnsenUI | train |
5c4318d68c579a4106965ca1ed7e0ed18075555c | diff --git a/salesforce/testrunner/example/templates/search-accounts.html b/salesforce/testrunner/example/templates/search-accounts.html
index <HASH>..<HASH> 100644
--- a/salesforce/testrunner/example/templates/search-accounts.html
+++ b/salesforce/testrunner/example/templates/search-accounts.html
@@ -17,16 +17,19 @@
{{ form.as_p }}
<input type="submit" value="search">
</form>
- {% if account %}
+ {% if accounts %}
<div class="content">
<div id="content-wrapper">
- <div class="account">
- {{ account.FirstName }} {{ account.LastName }}
- </div>
+ <div>{{ accounts.count }} results:</div>
+ {% for account in accounts %}
+ <div class="account">
+ {{ account.Name }}
+ </div>
+ {% endfor %}
</div>
</div>
{% else %}
- <strong>Enter an email to search for</strong>
+ <strong>Enter a name to search for</strong>
{% endif %}
</div>
</div>
diff --git a/salesforce/testrunner/example/views.py b/salesforce/testrunner/example/views.py
index <HASH>..<HASH> 100644
--- a/salesforce/testrunner/example/views.py
+++ b/salesforce/testrunner/example/views.py
@@ -23,16 +23,16 @@ def list_accounts(request):
), context_instance=template.RequestContext(request))
def search_accounts(request):
- account = None
+ accounts = []
if(request.method == 'POST'):
form = forms.SearchForm(request.POST)
if(form.is_valid()):
- account = models.Account.objects.get(PersonEmail=form.cleaned_data['query'])
+ accounts = models.Account.objects.filter(Name__icontains=form.cleaned_data['query'])
else:
form = forms.SearchForm()
return shortcuts.render_to_response('search-accounts.html', dict(
title = "Search Accounts by Email",
- account = account,
+ accounts = accounts,
form = form,
), context_instance=template.RequestContext(request))
diff --git a/salesforce/tests/test_browser.py b/salesforce/tests/test_browser.py
index <HASH>..<HASH> 100644
--- a/salesforce/tests/test_browser.py
+++ b/salesforce/tests/test_browser.py
@@ -1,5 +1,6 @@
from django.test import TestCase
import django.contrib.auth
+from salesforce.testrunner.example.models import Account
class WebTest(TestCase):
@@ -13,12 +14,18 @@ class WebTest(TestCase):
user.save()
self.client.login(username='fredsu', password='passwd')
+ account = Account(Name = 'sf_test account')
+ account.save()
+
response = self.client.get('/')
response = self.client.get('/search/')
- response = self.client.get('/search/')
+ response = self.client.post('/search/', {'query': 'test account'})
+ self.assertIn(b'sf_test account', response.content)
response = self.client.post('/admin/example/account/')
response = self.client.post('/admin/example/contact/')
response = self.client.post('/admin/example/lead/')
response = self.client.post('/admin/example/pricebook/')
response = self.client.post('/admin/')
self.assertIn('PricebookEntries', response.rendered_content)
+ account.delete()
+ user.delete() | Fixed the demo homepage to work also with a normal Account.
It should also never raise exception for any user input. | django-salesforce_django-salesforce | train |
45e35ac14a7f6461973dc550cdb5be7fa382c20f | diff --git a/Worker.php b/Worker.php
index <HASH>..<HASH> 100644
--- a/Worker.php
+++ b/Worker.php
@@ -15,10 +15,10 @@ interface Worker
public function canWork($task);
/**
- * Work on data.
+ * Work on $task.
*
* @param mixed $task The task to be worked
- * @return mixed true or a value on success, false on failure.
+ * @return mixed true or a positive value on success, false on failure.
*/
public function work($task);
}
diff --git a/Worker/WorksAnything.php b/Worker/WorksAnything.php
index <HASH>..<HASH> 100644
--- a/Worker/WorksAnything.php
+++ b/Worker/WorksAnything.php
@@ -15,5 +15,5 @@ abstract class CatchAll implements
/**
*/
- public abstract function process($data);
+ public abstract function process($task);
}
diff --git a/Worker/WorksAnythingTrait.php b/Worker/WorksAnythingTrait.php
index <HASH>..<HASH> 100644
--- a/Worker/WorksAnythingTrait.php
+++ b/Worker/WorksAnythingTrait.php
@@ -11,7 +11,7 @@ trait WorksAnythingTrait
{
/**
*/
- public function canWork($data)
+ public function canWork($task)
{
return true;
} | Workers work on a "task" | dankempster_axstrad-workforce | train |
e517b3225f6074fca82d61e449c98a1ade38a627 | diff --git a/src/main/java/org/mapdb/StoreDirect.java b/src/main/java/org/mapdb/StoreDirect.java
index <HASH>..<HASH> 100644
--- a/src/main/java/org/mapdb/StoreDirect.java
+++ b/src/main/java/org/mapdb/StoreDirect.java
@@ -681,14 +681,14 @@ public class StoreDirect extends Store{
try{
if(!readOnly){
+ if(serializerPojo!=null && serializerPojo.hasUnsavedChanges()){
+ serializerPojo.save(this);
+ }
+
index.putLong(IO_PHYS_SIZE,physSize);
index.putLong(IO_INDEX_SIZE,indexSize);
index.putLong(IO_FREE_SIZE,freeSize);
- if(serializerPojo!=null && serializerPojo.hasUnsavedChanges()){
- serializerPojo.save(this);
- }
-
index.putLong(IO_INDEX_SUM,indexHeaderChecksum());
}
@@ -719,14 +719,15 @@ public class StoreDirect extends Store{
@Override
public void commit() {
if(!readOnly){
- index.putLong(IO_PHYS_SIZE,physSize);
- index.putLong(IO_INDEX_SIZE,indexSize);
- index.putLong(IO_FREE_SIZE,freeSize);
if(serializerPojo!=null && serializerPojo.hasUnsavedChanges()){
serializerPojo.save(this);
}
-
+
+ index.putLong(IO_PHYS_SIZE,physSize);
+ index.putLong(IO_INDEX_SIZE,indexSize);
+ index.putLong(IO_FREE_SIZE,freeSize);
+
index.putLong(IO_INDEX_SUM, indexHeaderChecksum());
}
if(!syncOnCommitDisabled){ | StoreDirect: SerializerPojo could get corrupted on close. See #<I> | jankotek_mapdb | train |
7cc66269e6ad3cbae850daf8ee9036565a3b0f5b | diff --git a/core/cas-server-core-configuration/src/main/java/org/apereo/cas/configuration/model/support/jpa/AbstractJpaProperties.java b/core/cas-server-core-configuration/src/main/java/org/apereo/cas/configuration/model/support/jpa/AbstractJpaProperties.java
index <HASH>..<HASH> 100644
--- a/core/cas-server-core-configuration/src/main/java/org/apereo/cas/configuration/model/support/jpa/AbstractJpaProperties.java
+++ b/core/cas-server-core-configuration/src/main/java/org/apereo/cas/configuration/model/support/jpa/AbstractJpaProperties.java
@@ -28,7 +28,7 @@ public abstract class AbstractJpaProperties implements Serializable {
private String healthQuery = StringUtils.EMPTY;
private String idleTimeout = "PT10M";
private String dataSourceName;
- private Map<String, String> properties = new HashMap<String, String>();
+ private Map<String, String> properties = new HashMap<>();
private ConnectionPoolingProperties pool = new ConnectionPoolingProperties(); | (refactor) some opportunities to use diamond operator (#<I>) | apereo_cas | train |
a28ba734152007e0e9ec68873852d39eebe57f3b | diff --git a/src/shouldInstrument.js b/src/shouldInstrument.js
index <HASH>..<HASH> 100644
--- a/src/shouldInstrument.js
+++ b/src/shouldInstrument.js
@@ -1,4 +1,4 @@
-// copy-paste from https://github.com/nx-js/observer-util/blob/master/src/builtIns/index.js
+// Based on https://github.com/nx-js/observer-util/blob/master/src/builtIns/index.js
// built-in object can not be wrapped by Proxies, or, to be clear - unfreezed
// their methods expect the object instance as the 'this' instead of the Proxy wrapper
@@ -15,37 +15,34 @@ const collectionHandlers = {
[Symbol.iterator]: true
};
-const handlers = new Map([
- [Map, collectionHandlers],
- [Set, collectionHandlers],
- [WeakMap, collectionHandlers],
- [WeakSet, collectionHandlers],
- [Object, false],
- [Array, false],
- [Int8Array, false],
- [Uint8Array, false],
- [Uint8ClampedArray, false],
- [Int16Array, false],
- [Uint16Array, false],
- [Int32Array, false],
- [Uint32Array, false],
- [Float32Array, false],
- [Float64Array, false]
-]);
-
+const handlers = {
+ Map: collectionHandlers,
+ Set: collectionHandlers,
+ WeakMap: collectionHandlers,
+ WeakSet: collectionHandlers,
+ Object: false,
+ Array: false,
+ Int8Array: false,
+ Uint8Array: false,
+ Uint8ClampedArray: false,
+ Int16Array: false,
+ Uint16Array: false,
+ Int32Array: false,
+ Uint32Array: false,
+ Float32Array: false,
+ Float64Array: false
+};
-// eslint-disable-next-line
const globalObj = typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : typeof window !== 'undefined' ? window : {};
export function shouldInstrument({constructor}) {
+ const name = constructor.name;
const isBuiltIn = (
typeof constructor === 'function' &&
- constructor.name in globalObj &&
- globalObj[constructor.name] === constructor
+ name in globalObj &&
+ globalObj[name] === constructor
);
- return !isBuiltIn || handlers.has(constructor);
+ return !isBuiltIn || handlers.hasOwnProperty(name);
}
-export const getCollectionHandlers = ({constructor}) => (
- handlers.get(constructor)
-)
\ No newline at end of file
+export const getCollectionHandlers = ({constructor}) => handlers[constructor.name]; | Avoid shouldInstrument ReferenceError on ES6 types
To check for builtin types, the shouldInstrument file creates a map
with various constructors as the keys. However, as WeakSet is not
used, there's no guarantee it's been polyfilled in for browsers that
lack support like IE<I>, which leads to a runtime ReferenceError when
proxyequal is imported.
Instead key on the constructor name, which gracefully handles cases
where the browser does not have one of the types that need special
handling. | theKashey_proxyequal | train |
9ead6f51f428e6ea74850eb68ea57cb8e2493b6d | diff --git a/tests/test_potential.py b/tests/test_potential.py
index <HASH>..<HASH> 100644
--- a/tests/test_potential.py
+++ b/tests/test_potential.py
@@ -1995,9 +1995,6 @@ def test_rtide_noMError():
def test_ttensor():
pmass= potential.KeplerPotential(normalize=1.)
tij=pmass.ttensor(1.0,0.0,0.0)
- #For a points mass galaxy assert that maximum eigenvalue is 3.
- max_eigenvalue=tij[0][0]-tij[2][2]
- assert abs(1.0-max_eigenvalue/3.0) < 10.**-12., "Calculation of tidal tensor in point-mass potential fails"
# Full tidal tensor here should be diag(2,-1,-1)
assert numpy.all(numpy.fabs(tij-numpy.diag([2,-1,-1])) < 1e-10), "Calculation of tidal tensor in point-mass potential fails"
# Also test eigenvalues | Remove test of ttensor that tests against eivenvalue of effective tidal tensor for point-mass galaxy, because hard to explain | jobovy_galpy | train |
f8768cab3404ea80a8a9baba1b7d86792d5af264 | diff --git a/DependencyInjection/FOSRestExtension.php b/DependencyInjection/FOSRestExtension.php
index <HASH>..<HASH> 100644
--- a/DependencyInjection/FOSRestExtension.php
+++ b/DependencyInjection/FOSRestExtension.php
@@ -19,6 +19,8 @@ use Symfony\Component\Config\Definition\Processor,
Symfony\Component\DependencyInjection\ContainerBuilder,
Symfony\Component\DependencyInjection\Loader\XmlFileLoader;
+use FOS\RestBundle\Response\Codes;
+
class FOSRestExtension extends Extension
{
/**
@@ -85,6 +87,11 @@ class FOSRestExtension extends Extension
$serializer->replaceArgument(1, $encoders);
}
+ foreach ($config['force_redirects'] as $format => $code) {
+ if (true === $code) {
+ $config['force_redirects'][$format] = Codes::HTTP_CREATED;
+ }
+ }
$container->setParameter($this->getAlias().'.force_redirects', $config['force_redirects']);
foreach ($config['exception']['codes'] as $exception => $code) {
diff --git a/View/View.php b/View/View.php
index <HASH>..<HASH> 100644
--- a/View/View.php
+++ b/View/View.php
@@ -505,7 +505,7 @@ class View implements ContainerAwareInterface
$location = $this->getLocation();
if ($location) {
if (!empty($this->forceRedirects[$format]) && !$response->isRedirect()) {
- $response->setStatusCode(Codes::HTTP_FOUND);
+ $response->setStatusCode($this->forceRedirects[$format]);
}
if ('html' === $format && $response->isRedirect()) { | make it possible to customize the status code to force redirect to | FriendsOfSymfony_FOSRestBundle | train |
19b8adfdae9cb57d5904157f6825ec40944978d2 | diff --git a/comments/comments.js b/comments/comments.js
index <HASH>..<HASH> 100644
--- a/comments/comments.js
+++ b/comments/comments.js
@@ -147,15 +147,16 @@ Comments.prototype = {
* @param {Number} comment.user_id ID of logged-in user.
* @param {String} comment.content The text of comment.
* @param {String} comment.content_html Formatted text of comment.
- * @param {String} comment.type Type name of target.
- * @param {String} comment.cls Class name of target.
- * @param {String} comment.member Member name of target.
+ * @param {Object} comment.target The target:
+ * @param {String} comment.target.type Type name of target.
+ * @param {String} comment.target.cls Class name of target.
+ * @param {String} comment.target.member Member name of target.
* @param {Function} callback
* @param {Error} callback.err The error object.
* @param {Function} callback.id The ID of newly inserted comment.
*/
add: function(comment, callback) {
- this.targets.ensure(comment, function(err, target_id) {
+ this.targets.ensure(comment.target, function(err, target_id) {
if (err) {
callback(err);
return;
diff --git a/comments/comments.spec.js b/comments/comments.spec.js
index <HASH>..<HASH> 100644
--- a/comments/comments.spec.js
+++ b/comments/comments.spec.js
@@ -124,9 +124,11 @@ describe("Comments", function() {
content: "Blah.",
content_html: "<p>Blah.</p>",
- type: "class",
- cls: "Ext",
- member: "method-getBody"
+ target: {
+ type: "class",
+ cls: "Ext",
+ member: "method-getBody"
+ }
};
comments.add(com, function(err, id) {
comments.getById(id, function(err, newCom) {
@@ -143,9 +145,11 @@ describe("Comments", function() {
content: "Blah.",
content_html: "<p>Blah.</p>",
- type: "class",
- cls: "Blah",
- member: "method-foo"
+ target: {
+ type: "class",
+ cls: "Blah",
+ member: "method-foo"
+ }
};
comments.add(com, function(err, id) {
comments.getById(id, function(err, newCom) { | Make Comments#add take target as separate object.
Instead of listing all target properties inside the comment object
separately, there's now a target property that should contain object
with type,cls,member fields. | senchalabs_jsduck | train |
4b5b86f4038b0fc3700084a8d9418e7825420de9 | diff --git a/src/list/reduce.js b/src/list/reduce.js
index <HASH>..<HASH> 100644
--- a/src/list/reduce.js
+++ b/src/list/reduce.js
@@ -1,3 +1,4 @@
+/* eslint-disable no-param-reassign */
import curry3 from '../_internal/curry3';
/**
@@ -11,13 +12,12 @@ import curry3 from '../_internal/curry3';
* Applies a function to an accumulator and each value of a given list to reduce
* it to a single value.
*
- * At each iteration, the supplied function receives the current accumulator
- * (initialValue on the first iteration), the current value and the current index
- * as arguments.
+ * At each iteration, the supplied function receives the current accumlated value
+ * and the list's current value and index as arguments.
*
* @function
* @param {function} fn - The reducer function
- * @param {*} initialValue - The initial accumulator
+ * @param {*} accum - The initial value for the operation
* @param {List} list - The list to reduce
* @return {*} The reduced value
* @example
@@ -28,9 +28,8 @@ import curry3 from '../_internal/curry3';
* reduce(sum, 10, [1, 2, 3]) //=> 16
* reduce(ids, [], [1, 2]) //=> [{ id: 1 }, { id: 2 }]
*/
-export default curry3((fn, initialValue, list) => {
- let result = initialValue;
+export default curry3((fn, accum, list) => {
for (let i = 0; i < list.length; i++)
- result = fn(result, list[i], i);
- return result;
+ accum = fn(accum, list[i], i);
+ return accum;
});
diff --git a/src/list/reduce_test.js b/src/list/reduce_test.js
index <HASH>..<HASH> 100644
--- a/src/list/reduce_test.js
+++ b/src/list/reduce_test.js
@@ -3,11 +3,11 @@ import A from 'assert';
import reduce from './reduce';
import util from '../../build/util';
-describe('reduce(fn, initialValue, list)', () => {
+describe('reduce(fn, accum, list)', () => {
const array = ['b', 'c', 'd'];
const arrayLike = util.arrayLike('b', 'c', 'd');
- it('uses "fn" to reduce "initialValue" and the value in "list" to a single value', () => {
+ it('uses "fn" to reduce "accum" and the values in "list" to a single value', () => {
A.equal(reduce(util.concat, 'a', array), 'abcd');
A.equal(reduce(util.concat, 'a', []), 'a');
}); | (- re list) Removes the alias for the initial value in `reduce`
The initial value in a reduce operation is meant to be mutated. Aliasing it inside the body of the function has no real benefit. | valtermro_tolb | train |
5ee8289a8e39cd2b5bf78e4a458b43d63c0a2359 | diff --git a/src/Buffer.php b/src/Buffer.php
index <HASH>..<HASH> 100644
--- a/src/Buffer.php
+++ b/src/Buffer.php
@@ -131,11 +131,11 @@ class Buffer extends EventEmitter implements WritableStreamInterface
}
private function lastErrorFlush() {
- $this->lastError = [
+ $this->lastError = array(
'number' => 0,
'message' => '',
'file' => '',
'line' => 0,
- ];
+ );
}
} | change array definition (for php <I> compatibility) | reactphp_stream | train |
b96d4f3db25e7ac91b76238fd53fb2b1b1f0e903 | diff --git a/test/intervals.py b/test/intervals.py
index <HASH>..<HASH> 100644
--- a/test/intervals.py
+++ b/test/intervals.py
@@ -66,12 +66,12 @@ def nogaps_rand(size=100, labels=False):
:rtype: list of Intervals
"""
cur = -50
- ivs = []
+ result = []
for i in xrange(size):
length = randint(1, 10)
- ivs.append(make_iv(cur, cur + length, labels))
+ result.append(make_iv(cur, cur + length, labels))
cur += length
- return ivs
+ return result
def gaps_rand(size=100, labels=False):
@@ -82,22 +82,22 @@ def gaps_rand(size=100, labels=False):
:rtype: list of Intervals
"""
cur = -50
- ivs = []
+ result = []
for i in xrange(size):
length = randint(1, 10)
if choice([True, False]):
cur += length
length = randint(1, 10)
- ivs.append(make_iv(cur, cur + length, labels))
+ result.append(make_iv(cur, cur + length, labels))
cur += length
- return ivs
+ return result
def overlaps_nogaps_rand(size=100, labels=False):
l1 = nogaps_rand(size, labels)
l2 = nogaps_rand(size, labels)
- ivs = set(l1) + set(l2)
- return list(ivs)
+ result = set(l1) | set(l2)
+ return list(result)
def write_ivs_data(name, ivs, docstring='', imports=None): | fix: shadowed identifier ivs in test/intervals.py | chaimleib_intervaltree | train |
1cf7df697f88223cd755f301de2baa720c352f6b | diff --git a/common/src/main/java/tachyon/conf/TachyonConf.java b/common/src/main/java/tachyon/conf/TachyonConf.java
index <HASH>..<HASH> 100644
--- a/common/src/main/java/tachyon/conf/TachyonConf.java
+++ b/common/src/main/java/tachyon/conf/TachyonConf.java
@@ -265,16 +265,17 @@ public class TachyonConf {
return defaultValue;
}
- private double getDouble(String key, final double defaultValue) {
+ public double getDouble(String key) {
if (mProperties.containsKey(key)) {
String rawValue = mProperties.getProperty(key);
try {
return Double.parseDouble(lookup(rawValue));
} catch (NumberFormatException e) {
- LOG.warn("Configuration cannot evaluate key " + key + " as double.");
+ throw new RuntimeException("Configuration cannot evaluate key " + key + " as double.");
}
}
- return defaultValue;
+ // if key is not found among the default properties
+ throw new RuntimeException("Invalid configuration key " + key + ".");
}
private float getFloat(String key, final float defaultValue) {
@@ -316,15 +317,6 @@ public class TachyonConf {
return defaultValue;
}
- private long getBytes(String key, long defaultValue) {
- String rawValue = get(key, "");
- try {
- return FormatUtils.parseSpaceSize(rawValue);
- } catch (Exception ex) {
- return defaultValue;
- }
- }
-
public long getBytes(String key) {
if (mProperties.containsKey(key)) {
String rawValue = get(key);
diff --git a/servers/src/main/java/tachyon/worker/block/evictor/LRFUEvictor.java b/servers/src/main/java/tachyon/worker/block/evictor/LRFUEvictor.java
index <HASH>..<HASH> 100644
--- a/servers/src/main/java/tachyon/worker/block/evictor/LRFUEvictor.java
+++ b/servers/src/main/java/tachyon/worker/block/evictor/LRFUEvictor.java
@@ -76,10 +76,9 @@ public class LRFUEvictor extends BlockStoreEventListenerBase implements Evictor
mManagerView = view;
mTachyonConf = new TachyonConf();
mStepFactor = mTachyonConf
- .getDouble(Constants.WORKER_EVICT_STRATEGY_LRFU_STEP_FACTOR, DEFAULT_STEP_FACTOR);
+ .getDouble(Constants.WORKER_EVICT_STRATEGY_LRFU_STEP_FACTOR);
mAttenuationFactor = mTachyonConf
- .getDouble(Constants.WORKER_EVICT_STRATEGY_LRFU_ATTENUATION_FACTOR,
- DEFAULT_ATTENUATION_FACTOR);
+ .getDouble(Constants.WORKER_EVICT_STRATEGY_LRFU_ATTENUATION_FACTOR);
Preconditions.checkArgument(mStepFactor >= 0.0 && mStepFactor <= 1.0,
"Step factor should be in the range of [0.0, 1.0]");
Preconditions.checkArgument(mAttenuationFactor >= 2.0,
diff --git a/servers/src/test/java/tachyon/worker/block/evictor/LRFUEvictorTest.java b/servers/src/test/java/tachyon/worker/block/evictor/LRFUEvictorTest.java
index <HASH>..<HASH> 100644
--- a/servers/src/test/java/tachyon/worker/block/evictor/LRFUEvictorTest.java
+++ b/servers/src/test/java/tachyon/worker/block/evictor/LRFUEvictorTest.java
@@ -66,9 +66,9 @@ public class LRFUEvictorTest {
Collections.<Long>emptySet());
TachyonConf conf = new TachyonConf();
conf.set(Constants.WORKER_EVICT_STRATEGY_CLASS, LRFUEvictor.class.getName());
- mStepFactor = conf.getDouble(Constants.WORKER_EVICT_STRATEGY_LRFU_STEP_FACTOR, 0.25);
+ mStepFactor = conf.getDouble(Constants.WORKER_EVICT_STRATEGY_LRFU_STEP_FACTOR);
mAttenuationFactor =
- conf.getDouble(Constants.WORKER_EVICT_STRATEGY_LRFU_ATTENUATION_FACTOR, 2.0);
+ conf.getDouble(Constants.WORKER_EVICT_STRATEGY_LRFU_ATTENUATION_FACTOR);
mEvictor = Evictor.Factory.createEvictor(conf, mManagerView);
} | [TACHYON-<I>] Resolve merge conflicts | Alluxio_alluxio | train |
53fef0ab6fcdf3f8018c231f8f445384d1f58c87 | diff --git a/lib/fugue.js b/lib/fugue.js
index <HASH>..<HASH> 100644
--- a/lib/fugue.js
+++ b/lib/fugue.js
@@ -34,12 +34,12 @@ exports.start = function(server, port, host, worker_count, options) {
if (!path.existsSync(options.working_path)) {
throw "Working path "+options.working_path + " does not exist. Please create it";
}
-
+
// setup log function
- var log = function(what) {
- if (options.verbose) console.log(what);
- }
+ var log = options.verbose ?
+ function(what) { console.log(what); } :
+ function() {};
// Master or worker?
var worker_id = process.env._FUGUE_WORKER; | Move verbose test out of log function and into configuration. If there's need to change logging at run time, then this code can be easily moved into a (new) function. | pgte_fugue | train |
314ef35475fcb8eceb2c18fc8fd6ffab26d45cd9 | diff --git a/lib/IDS/Converter.php b/lib/IDS/Converter.php
index <HASH>..<HASH> 100644
--- a/lib/IDS/Converter.php
+++ b/lib/IDS/Converter.php
@@ -561,6 +561,9 @@ class IDS_Converter
$value
);
+ // normalize separation char repetion
+ $value = preg_replace('/([.+~=\-])\1{2,}/m', '$1', $value);
+
//remove parenthesis inside sentences
$value = preg_replace('/(\w\s)\(([&\w]+)\)(\s\w|$)/', '$1$2$3', $value); | added code to deal with abnormal repetiton of separation chars
git-svn-id: <URL> | ZendExperts_phpids | train |
4b407cace19798644a9f928c0b8b8f2f6a887517 | diff --git a/oauth2.go b/oauth2.go
index <HASH>..<HASH> 100644
--- a/oauth2.go
+++ b/oauth2.go
@@ -25,6 +25,7 @@ type tokenRespBody struct {
TokenType string `json:"token_type"`
RefreshToken string `json:"refresh_token"`
ExpiresIn int64 `json:"expires_in"` // in seconds
+ Expires int64 `json:"expires"` // in seconds. Facebook returns expires_in as expires.
IdToken string `json:"id_token"`
}
@@ -223,6 +224,7 @@ func (c *Config) retrieveToken(v url.Values) (*Token, error) {
resp.TokenType = vals.Get("token_type")
resp.RefreshToken = vals.Get("refresh_token")
resp.ExpiresIn, _ = strconv.ParseInt(vals.Get("expires_in"), 10, 64)
+ resp.Expires, _ = strconv.ParseInt(vals.Get("expires"), 10, 64)
resp.IdToken = vals.Get("id_token")
default:
if err = json.Unmarshal(body, &resp); err != nil {
@@ -239,11 +241,18 @@ func (c *Config) retrieveToken(v url.Values) (*Token, error) {
if resp.RefreshToken == "" {
token.RefreshToken = v.Get("refresh_token")
}
- if resp.ExpiresIn == 0 {
+ if resp.ExpiresIn == 0 || resp.Expires == 0 {
token.Expiry = time.Time{}
- } else {
+ }
+ if resp.ExpiresIn > 0 {
token.Expiry = time.Now().Add(time.Duration(resp.ExpiresIn) * time.Second)
}
+ if resp.Expires > 0 {
+ // TODO(jbd): Facebook's OAuth2 implementation is broken and
+ // returns expires_in field in expires. Remove the fallback to expires,
+ // when Facebook fixes their implementation.
+ token.Expiry = time.Now().Add(time.Duration(resp.Expires) * time.Second)
+ }
if resp.IdToken != "" {
if token.Extra == nil {
token.Extra = make(map[string]string) | Support token expiration for Facebook OAuth <I>.
Facebook's OAuth <I> implementation seems to be broken and
returns expires_in value in expires. Fallback to expires field to
handle the expiration time for Facebook. | golang_oauth2 | train |
52987e328d4633ca8ddfd8c426f8ac505f702bf3 | diff --git a/src/Google/Service/YouTube.php b/src/Google/Service/YouTube.php
index <HASH>..<HASH> 100644
--- a/src/Google/Service/YouTube.php
+++ b/src/Google/Service/YouTube.php
@@ -4310,6 +4310,8 @@ class Google_Service_YouTube_Channel extends Google_Model
protected $invideoPromotionType = 'Google_Service_YouTube_InvideoPromotion';
protected $invideoPromotionDataType = '';
public $kind;
+ protected $localizationsType = 'Google_Service_YouTube_ChannelLocalization';
+ protected $localizationsDataType = 'map';
protected $snippetType = 'Google_Service_YouTube_ChannelSnippet';
protected $snippetDataType = '';
protected $statisticsType = 'Google_Service_YouTube_ChannelStatistics';
@@ -4392,6 +4394,14 @@ class Google_Service_YouTube_Channel extends Google_Model
{
return $this->kind;
}
+ public function setLocalizations($localizations)
+ {
+ $this->localizations = $localizations;
+ }
+ public function getLocalizations()
+ {
+ return $this->localizations;
+ }
public function setSnippet(Google_Service_YouTube_ChannelSnippet $snippet)
{
$this->snippet = $snippet;
@@ -4798,6 +4808,36 @@ class Google_Service_YouTube_ChannelListResponse extends Google_Collection
}
}
+class Google_Service_YouTube_ChannelLocalization extends Google_Model
+{
+ protected $internal_gapi_mappings = array(
+ );
+ public $description;
+ public $title;
+
+
+ public function setDescription($description)
+ {
+ $this->description = $description;
+ }
+ public function getDescription()
+ {
+ return $this->description;
+ }
+ public function setTitle($title)
+ {
+ $this->title = $title;
+ }
+ public function getTitle()
+ {
+ return $this->title;
+ }
+}
+
+class Google_Service_YouTube_ChannelLocalizations extends Google_Model
+{
+}
+
class Google_Service_YouTube_ChannelSection extends Google_Model
{
protected $internal_gapi_mappings = array(
@@ -4993,6 +5033,7 @@ class Google_Service_YouTube_ChannelSettings extends Google_Collection
protected $collection_key = 'featuredChannelsUrls';
protected $internal_gapi_mappings = array(
);
+ public $defaultLanguage;
public $defaultTab;
public $description;
public $featuredChannelsTitle;
@@ -5007,6 +5048,14 @@ class Google_Service_YouTube_ChannelSettings extends Google_Collection
public $unsubscribedTrailer;
+ public function setDefaultLanguage($defaultLanguage)
+ {
+ $this->defaultLanguage = $defaultLanguage;
+ }
+ public function getDefaultLanguage()
+ {
+ return $this->defaultLanguage;
+ }
public function setDefaultTab($defaultTab)
{
$this->defaultTab = $defaultTab;
@@ -5109,13 +5158,24 @@ class Google_Service_YouTube_ChannelSnippet extends Google_Model
{
protected $internal_gapi_mappings = array(
);
+ public $defaultLanguage;
public $description;
+ protected $localizedType = 'Google_Service_YouTube_ChannelLocalization';
+ protected $localizedDataType = '';
public $publishedAt;
protected $thumbnailsType = 'Google_Service_YouTube_ThumbnailDetails';
protected $thumbnailsDataType = '';
public $title;
+ public function setDefaultLanguage($defaultLanguage)
+ {
+ $this->defaultLanguage = $defaultLanguage;
+ }
+ public function getDefaultLanguage()
+ {
+ return $this->defaultLanguage;
+ }
public function setDescription($description)
{
$this->description = $description;
@@ -5124,6 +5184,14 @@ class Google_Service_YouTube_ChannelSnippet extends Google_Model
{
return $this->description;
}
+ public function setLocalized(Google_Service_YouTube_ChannelLocalization $localized)
+ {
+ $this->localized = $localized;
+ }
+ public function getLocalized()
+ {
+ return $this->localized;
+ }
public function setPublishedAt($publishedAt)
{
$this->publishedAt = $publishedAt;
@@ -6702,6 +6770,23 @@ class Google_Service_YouTube_InvideoTiming extends Google_Model
}
}
+class Google_Service_YouTube_LanguageTag extends Google_Model
+{
+ protected $internal_gapi_mappings = array(
+ );
+ public $value;
+
+
+ public function setValue($value)
+ {
+ $this->value = $value;
+ }
+ public function getValue()
+ {
+ return $this->value;
+ }
+}
+
class Google_Service_YouTube_LiveBroadcast extends Google_Model
{
protected $internal_gapi_mappings = array(
@@ -7336,6 +7421,8 @@ class Google_Service_YouTube_LocalizedProperty extends Google_Collection
protected $internal_gapi_mappings = array(
);
public $default;
+ protected $defaultLanguageType = 'Google_Service_YouTube_LanguageTag';
+ protected $defaultLanguageDataType = '';
protected $localizedType = 'Google_Service_YouTube_LocalizedString';
protected $localizedDataType = 'array';
@@ -7348,6 +7435,14 @@ class Google_Service_YouTube_LocalizedProperty extends Google_Collection
{
return $this->default;
}
+ public function setDefaultLanguage(Google_Service_YouTube_LanguageTag $defaultLanguage)
+ {
+ $this->defaultLanguage = $defaultLanguage;
+ }
+ public function getDefaultLanguage()
+ {
+ return $this->defaultLanguage;
+ }
public function setLocalized($localized)
{
$this->localized = $localized; | Updated YouTube.php
This change has been generated by a script that has detected changes in the
discovery doc of the API.
Check <URL> | googleapis_google-api-php-client | train |
0344b23cf7f1315a9017160fa9296daf432f4d4c | diff --git a/setup.py b/setup.py
index <HASH>..<HASH> 100644
--- a/setup.py
+++ b/setup.py
@@ -13,7 +13,7 @@ Link to full documentation: http://tabs.readthedocs.io/en/latest/index.html
from setuptools import setup
setup(name='tabs',
- version='0.6.4',
+ version='0.6.5',
url='https://github.com/ohenrik/tabs',
description="""Tabs - Import tables in a consistent, maintainable, and readable way""",
long_description=__doc__,
@@ -21,7 +21,7 @@ setup(name='tabs',
author_email='[email protected]',
packages=['tabs'],
install_requires=[
- 'pandas>=0.20'
+ 'pandas>=0.20',
'dill>=0.2'
],
classifiers=[
diff --git a/tabs/tables.py b/tabs/tables.py
index <HASH>..<HASH> 100644
--- a/tabs/tables.py
+++ b/tabs/tables.py
@@ -62,6 +62,7 @@ class BaseTableABC(metaclass=ABCMeta):
@classmethod
def describe_processors(cls):
"""List all postprocessors and their description"""
+ # TODO: Add dependencies to this dictionary
for processor in cls.post_processors(cls):
yield {'name': processor.__name__,
'description': processor.__doc__,
@@ -124,6 +125,7 @@ class BaseTableABC(metaclass=ABCMeta):
NB! The dictionaries have to be sorted or hash id will change
arbitrarely.
"""
+ # TODO: Add md5 hash from dependencies and add them to this md5 hash, to ensure that this table is regenerated.
settings = settings_list or self.get_settings_list()
settings_str = pickle.dumps(settings)
cache_id = hashlib.md5(settings_str).hexdigest()
@@ -210,7 +212,7 @@ class Table(BaseTableABC, metaclass=ABCMeta):
self.to_cache(table)
return table
- # TODO: Check upstream if a table needs to be rerun.
+ # TODO: Check upstream if a table needs to be rerun (will be fixed based on hash included in settings for dependent variables)
def fetch(self, rebuild=False, cache=True):
"""Fetches the table and applies all post processors. | Corrected missing comma in setup script | ohenrik_tabs | train |
9f4979fdcdfb4dbf8efa583396b831b4df6b040a | diff --git a/slim/Route.php b/slim/Route.php
index <HASH>..<HASH> 100644
--- a/slim/Route.php
+++ b/slim/Route.php
@@ -227,8 +227,9 @@ class Route {
if ( preg_match($patternAsRegex, $resourceUri, $paramValues) ) {
array_shift($paramValues);
foreach ( $paramNames as $index => $value ) {
- if ( isset($paramValues[substr($value, 1)]) ) {
- $this->params[substr($value, 1)] = urldecode($paramValues[substr($value, 1)]);
+ $val = substr($value, 1);
+ if ( isset($paramValues[$val]) ) {
+ $this->params[$val] = urldecode($paramValues[$val]);
}
}
return true; | Route::matches now uses a single substr call | slimphp_Slim | train |
7234ddc263f3b3a687fce3f18ce838e8dc0738c9 | diff --git a/cherrypy/_cphttpserver.py b/cherrypy/_cphttpserver.py
index <HASH>..<HASH> 100644
--- a/cherrypy/_cphttpserver.py
+++ b/cherrypy/_cphttpserver.py
@@ -62,7 +62,7 @@ def run_server(HandlerClass, ServerClass, server_address, socketFile):
if cpg.configOption.socketFile:
try: os.chmod(socketFile, 0777) # So everyone can access the socket
except: pass
-
+ global _cpLogMessage
_cpLogMessage = _cputil.getSpecialFunction('_cpLogMessage')
servingWhat = "HTTP" | resolves logmessage error at control-c: ticket #<I> | cherrypy_cheroot | train |
e2d1876096ceee3cbe248c9f5b3e94f651105337 | diff --git a/presto-main/src/main/java/com/facebook/presto/server/HttpRemoteTask.java b/presto-main/src/main/java/com/facebook/presto/server/HttpRemoteTask.java
index <HASH>..<HASH> 100644
--- a/presto-main/src/main/java/com/facebook/presto/server/HttpRemoteTask.java
+++ b/presto-main/src/main/java/com/facebook/presto/server/HttpRemoteTask.java
@@ -697,6 +697,13 @@ public class HttpRemoteTask
return;
}
+ // if throttled due to error, asynchronously wait for timeout and try again
+ ListenableFuture<?> errorRateLimit = getErrorTracker.acquireRequestPermit();
+ if (!errorRateLimit.isDone()) {
+ errorRateLimit.addListener(this::scheduleNextRequest, executor);
+ return;
+ }
+
Request request = prepareGet()
.setUri(uriBuilderFrom(taskInfo.getSelf()).addParameter("summarize").build())
.setHeader(HttpHeaders.CONTENT_TYPE, MediaType.JSON_UTF_8.toString())
@@ -704,6 +711,8 @@ public class HttpRemoteTask
.setHeader(PrestoHeaders.PRESTO_MAX_WAIT, refreshMaxWait.toString())
.build();
+ getErrorTracker.startRequest();
+
future = httpClient.executeAsync(request, createFullJsonResponseHandler(taskInfoCodec));
Futures.addCallback(future, new SimpleHttpResponseHandler<>(this, request.getUri()), executor);
} | Throttle continuous task info fetcher on errors | prestodb_presto | train |
379f1e0a861022c7eca51cf27a0c54dfedadc40f | diff --git a/lib/schema/schema/compare/difference/attributes.rb b/lib/schema/schema/compare/difference/attributes.rb
index <HASH>..<HASH> 100644
--- a/lib/schema/schema/compare/difference/attributes.rb
+++ b/lib/schema/schema/compare/difference/attributes.rb
@@ -13,7 +13,31 @@ module Schema
end
def self.compare(attr_names, control_attributes, compare_attributes)
- # ...
+ instance = new
+
+ attr_names.each do |attr_name|
+ entry = compare_attribute(attr_name, control_attributes, compare_attributes)
+ instance.entries << entry if not entry.nil?
+ end
+
+ instance
+ end
+
+ def self.compare_attribute(attr_name, control_attributes, compare_attributes)
+ control_value = control_attributes[attr_name]
+ compare_value = compare_attributes[attr_name]
+
+ if control_value == compare_value
+ return nil
+ end
+
+ entry = Entry.new(
+ attr_name,
+ control_value,
+ compare_value
+ )
+
+ entry
end
def self.build(*args) | An entry is recorded for every attribute that is different | eventide-project_schema | train |
9262f308fccad725303979c7504949b9f8fa380c | diff --git a/src/main/java/me/tomassetti/symbolsolver/model/declarations/ClassDeclaration.java b/src/main/java/me/tomassetti/symbolsolver/model/declarations/ClassDeclaration.java
index <HASH>..<HASH> 100644
--- a/src/main/java/me/tomassetti/symbolsolver/model/declarations/ClassDeclaration.java
+++ b/src/main/java/me/tomassetti/symbolsolver/model/declarations/ClassDeclaration.java
@@ -50,7 +50,7 @@ public interface ClassDeclaration extends TypeDeclaration, TypeParametrized {
ancestors.add(new TypeUsageOfTypeDeclaration(getSuperClass(typeSolver)));
ancestors.addAll(getSuperClass(typeSolver).getAllAncestors(typeSolver));
}
- ancestors.addAll(getAllInterfaces(typeSolver).stream().map((i)->new TypeUsageOfTypeDeclaration(i)).collect(Collectors.toList()));
+ ancestors.addAll(getAllInterfaces(typeSolver).stream().map((i)->new TypeUsageOfTypeDeclaration(i)).collect(Collectors.<TypeUsageOfTypeDeclaration>toList()));
return ancestors;
} | walkmod: workaround to permit walkmod to process the project | javaparser_javasymbolsolver | train |
c80e6a6e822ba6ea33f95fdc2fc068a2d9d74451 | diff --git a/resources/src/main/java/org/robolectric/res/ResBundle.java b/resources/src/main/java/org/robolectric/res/ResBundle.java
index <HASH>..<HASH> 100644
--- a/resources/src/main/java/org/robolectric/res/ResBundle.java
+++ b/resources/src/main/java/org/robolectric/res/ResBundle.java
@@ -1,7 +1,8 @@
package org.robolectric.res;
-import java.util.Collection;
+import java.util.ArrayList;
import java.util.HashMap;
+import java.util.List;
import java.util.Map;
import org.robolectric.res.android.ConfigDescription;
import org.robolectric.res.android.ResTable_config;
@@ -18,25 +19,23 @@ public class ResBundle {
}
public void receive(ResourceTable.Visitor visitor) {
- for (final Map.Entry<ResName, Map<String, TypedResource>> entry : valuesMap.map.entrySet()) {
- visitor.visit(entry.getKey(), entry.getValue().values());
+ for (final Map.Entry<ResName, List<TypedResource>> entry : valuesMap.map.entrySet()) {
+ visitor.visit(entry.getKey(), entry.getValue());
}
}
static class ResMap {
- private final Map<ResName, Map<String, TypedResource>> map = new HashMap<>();
+ private final Map<ResName, List<TypedResource>> map = new HashMap<>();
public TypedResource pick(ResName resName, String qualifiersStr) {
- Map<String, TypedResource> values = map.get(resName);
+ List<TypedResource> values = map.get(resName);
if (values == null || values.size() == 0) return null;
- Collection<TypedResource> typedResources = values.values();
-
ResTable_config toMatch = new ResTable_config();
new ConfigDescription().parse(qualifiersStr == null ? "" : qualifiersStr, toMatch);
TypedResource bestMatchSoFar = null;
- for (TypedResource candidate : typedResources) {
+ for (TypedResource candidate : values) {
ResTable_config candidateConfig = candidate.getConfig();
if (candidateConfig.match(toMatch)) {
if (bestMatchSoFar == null || candidateConfig.isBetterThan(bestMatchSoFar.getConfig(), toMatch)) {
@@ -49,11 +48,9 @@ public class ResBundle {
}
public void put(ResName resName, TypedResource value) {
- Map<String, TypedResource> values = map.get(resName);
- if (values == null) map.put(resName, values = new HashMap<>());
- if (!values.containsKey(value.getXmlContext().getQualifiers())) {
- values.put(value.getXmlContext().getQualifiers(), value);
- }
+ List<TypedResource> values = map.get(resName);
+ if (values == null) map.put(resName, values = new ArrayList<>());
+ values.add(value);
}
public int size() { | Simplify ResBundle. | robolectric_robolectric | train |
6c1defcd58bc61127b5b75341c986d92ba00f00a | diff --git a/core/src/main/java/com/orientechnologies/orient/core/storage/index/sbtree/local/OPrefixBTree.java b/core/src/main/java/com/orientechnologies/orient/core/storage/index/sbtree/local/OPrefixBTree.java
index <HASH>..<HASH> 100755
--- a/core/src/main/java/com/orientechnologies/orient/core/storage/index/sbtree/local/OPrefixBTree.java
+++ b/core/src/main/java/com/orientechnologies/orient/core/storage/index/sbtree/local/OPrefixBTree.java
@@ -2052,8 +2052,9 @@ public class OPrefixBTree<V> extends ODurableComponent {
itemIndex = bucket.size() - 1;
break;
} else {
- currentPath.add(new ORawPair<>(cacheEntry.getPageIndex(), 1));
- final long childIndex = bucket.getRight(0);
+ final int lastIndex = bucket.size() - 1;
+ currentPath.add(new ORawPair<>(cacheEntry.getPageIndex(), lastIndex + 1));
+ final long childIndex = bucket.getRight(lastIndex);
releasePageFromRead(atomicOperation, cacheEntry); | Correct iteration in backward cursor was restored | orientechnologies_orientdb | train |
1aa40329ce0d21bb1def7b945c42e8b4cbbfa83c | diff --git a/lib/write_xlsx/chart.rb b/lib/write_xlsx/chart.rb
index <HASH>..<HASH> 100644
--- a/lib/write_xlsx/chart.rb
+++ b/lib/write_xlsx/chart.rb
@@ -1390,20 +1390,22 @@ module Writexlsx
def get_labels_properties(labels) # :nodoc:
return nil unless labels
- # Map user defined label positions to Excel positions.
- if position = labels[:position]
-
+ position = labels[:position]
+ if position.nil? || position.empty?
+ labels.delete(:position)
+ else
+ # Map user defined label positions to Excel positions.
positions = {
- :center => 'ctr',
- :right => 'r',
- :left => 'l',
- :top => 't',
- :above => 't',
- :bottom => 'b',
- :below => 'b',
- :inside_end => 'inEnd',
- :outside_end => 'outEnd',
- :best_fit => 'bestFit'
+ :center => 'ctr',
+ :right => 'r',
+ :left => 'l',
+ :top => 't',
+ :above => 't',
+ :bottom => 'b',
+ :below => 'b',
+ :inside_end => 'inEnd',
+ :outside_end => 'outEnd',
+ :best_fit => 'bestFit'
}
if positions[position.to_sym]
@@ -1413,7 +1415,7 @@ module Writexlsx
end
end
- return labels
+ labels
end
# | Chart#get_labels_properties : remove key and retuen when :position is empty string. | cxn03651_write_xlsx | train |
fc880e7a46663ccb92f492bffc076ff6c664dec4 | diff --git a/lib/gitlab/client/search.rb b/lib/gitlab/client/search.rb
index <HASH>..<HASH> 100644
--- a/lib/gitlab/client/search.rb
+++ b/lib/gitlab/client/search.rb
@@ -56,7 +56,7 @@ class Gitlab::Client
# @return [Array<Gitlab::ObjectifiedHash>] Returns a list of responses depending on the requested scope.
def search_in_project(project, scope, search, ref = nil)
options = { scope: scope, search: search }
-
+
# Add ref filter if provided - backward compatible with main project
options[:ref] = ref unless ref.nil? | [FIX] Fixed the single rubocop offence from existing commits | NARKOZ_gitlab | train |
b8b63b4d00c7a374c98a8321f560e0397d180a3f | diff --git a/lib/init.js b/lib/init.js
index <HASH>..<HASH> 100644
--- a/lib/init.js
+++ b/lib/init.js
@@ -131,6 +131,7 @@ module.exports = function(req, res, next) {
if (req.socket.isHttps || headers[config.HTTPS_FIELD] || headers[config.HTTPS_PROTO_HEADER] === 'https') {
req.isHttps = true;
delete headers[config.HTTPS_FIELD];
+ delete headers[config.HTTPS_PROTO_HEADER];
}
if (headers['proxy-connection']) {
headers.connection = headers['proxy-connection'];
diff --git a/lib/plugins/index.js b/lib/plugins/index.js
index <HASH>..<HASH> 100644
--- a/lib/plugins/index.js
+++ b/lib/plugins/index.js
@@ -35,6 +35,7 @@ var REQ_ID_HEADER = 'x-whistle-req-id';
var PIPE_VALUE_HEADER = 'x-whistle-pipe-value';
var CUSTOM_PARSER_HEADER = 'x-whistle-frame-parser';
var STATUS_CODE_HEADER = 'x-whistle-status-code';
+var PLUGIN_REQUEST_HEADER = 'x-whistle-plugin-request';
var LOCAL_HOST_HEADER = 'x-whistle-local-host';
var PROXY_VALUE_HEADER = 'x-whistle-proxy-value';
var PAC_VALUE_HEADER = 'x-whistle-pac-value';
@@ -365,6 +366,7 @@ function loadPlugin(plugin, callback) {
PIPE_VALUE_HEADER: PIPE_VALUE_HEADER,
CUSTOM_PARSER_HEADER: CUSTOM_PARSER_HEADER,
STATUS_CODE_HEADER: STATUS_CODE_HEADER,
+ PLUGIN_REQUEST_HEADER: PLUGIN_REQUEST_HEADER,
LOCAL_HOST_HEADER: LOCAL_HOST_HEADER,
HOST_VALUE_HEADER: LOCAL_HOST_HEADER,
PROXY_VALUE_HEADER: PROXY_VALUE_HEADER,
@@ -644,6 +646,10 @@ function getOptions(req, res, type) {
}
}
+ if (req.isPluginReq) {
+ headers[PLUGIN_REQUEST_HEADER] = 1;
+ }
+
options.protocol = 'http:';
options.host = LOCALHOST;
options.hostname = null;
diff --git a/lib/upgrade.js b/lib/upgrade.js
index <HASH>..<HASH> 100644
--- a/lib/upgrade.js
+++ b/lib/upgrade.js
@@ -131,6 +131,7 @@ function upgradeHandler(req, socket) {
}
// 不能放到上面,否则转发后的协议将丢失
delete headers[config.HTTPS_FIELD];
+ delete headers[config.HTTPS_PROTO_HEADER];
socket.rawHeaderNames = getRawHeaderNames(req.rawHeaders);
socket.headers = headers;
socket.url = req.url;
diff --git a/lib/util/index.js b/lib/util/index.js
index <HASH>..<HASH> 100644
--- a/lib/util/index.js
+++ b/lib/util/index.js
@@ -477,14 +477,24 @@ exports.toRegExp = function toRegExp(regExp, ignoreCase) {
};
function getFullUrl(req) {
- var host = req.headers.host;
+ var headers = req.headers;
+ var host = headers['x-whistle-real-host'] || headers['x-forwarded-host'];
+ if (host) {
+ delete headers['x-whistle-real-host'];
+ delete headers['x-forwarded-host'];
+ }
+ if (!host || typeof host !== 'string') {
+ host = headers.host;
+ } else {
+ headers.host = host;
+ }
var hostRule;
if (hasProtocol(req.url)) {
var options = url.parse(req.url);
req.url = options.path;
if (options.host) {
- if (!host) {
- host = req.headers.host = options.host;
+ if (!host || typeof host !== 'string') {
+ host = headers.host = options.host;
} else if (host != options.host) {
hostRule = options.host;
}
@@ -495,7 +505,7 @@ function getFullUrl(req) {
req.url = '/' + req.url;
}
if (typeof host !== 'string') {
- host = req.headers.host = '';
+ host = headers.host = '';
}
}
if (host) {
@@ -503,7 +513,7 @@ function getFullUrl(req) {
}
var fullUrl = _getProtocol(req.isHttps) + host + req.url;
if (hostRule) {
- req.headers['x-whistle-rule-host'] = fullUrl + ' host://' + hostRule;
+ headers['x-whistle-rule-host'] = fullUrl + ' host://' + hostRule;
}
return fullUrl;
} | feat: support x-forwarded-host || x-whistle-real-host | avwo_whistle | train |
a18e102cfe027c00bb37d38862369679881b3d37 | diff --git a/lib/puppet/application/ssl.rb b/lib/puppet/application/ssl.rb
index <HASH>..<HASH> 100644
--- a/lib/puppet/application/ssl.rb
+++ b/lib/puppet/application/ssl.rb
@@ -84,6 +84,14 @@ HELP
option('--verbose', '-v')
option('--debug', '-d')
+ def initialize(command_line = Puppet::Util::CommandLine.new)
+ super(command_line)
+
+ @cert_provider = Puppet::X509::CertProvider.new
+ @ssl_provider = Puppet::SSL::SSLProvider.new
+ @machine = Puppet::SSL::StateMachine.new
+ end
+
def setup_logs
set_log_level(options)
Puppet::Util::Log.newdestination(:console)
@@ -108,8 +116,7 @@ HELP
action = command_line.args.first
case action
when 'submit_request'
- machine = Puppet::SSL::StateMachine.new
- ssl_context = machine.ensure_ca_certificates
+ ssl_context = @machine.ensure_ca_certificates
if submit_request(ssl_context)
cert = download_cert(ssl_context)
unless cert
@@ -117,8 +124,7 @@ HELP
end
end
when 'download_cert'
- machine = Puppet::SSL::StateMachine.new
- ssl_context = machine.ensure_ca_certificates
+ ssl_context = @machine.ensure_ca_certificates
cert = download_cert(ssl_context)
unless cert
raise Puppet::Error, _("The certificate for '%{name}' has not yet been signed") % { name: certname }
@@ -131,8 +137,7 @@ HELP
if !Puppet::Util::Log.sendlevel?(:info)
Puppet::Util::Log.level = :info
end
- sm = Puppet::SSL::StateMachine.new
- sm.ensure_client_certificate
+ @machine.ensure_client_certificate
Puppet.notice(_("Completed SSL initialization"))
else
raise Puppet::Error, _("Unknown action '%{action}'") % { action: action }
@@ -140,17 +145,16 @@ HELP
end
def submit_request(ssl_context)
- cert_provider = Puppet::X509::CertProvider.new
- key = cert_provider.load_private_key(Puppet[:certname])
+ key = @cert_provider.load_private_key(Puppet[:certname])
unless key
Puppet.info _("Creating a new SSL key for %{name}") % { name: Puppet[:certname] }
key = OpenSSL::PKey::RSA.new(Puppet[:keylength].to_i)
- cert_provider.save_private_key(Puppet[:certname], key)
+ @cert_provider.save_private_key(Puppet[:certname], key)
end
- csr = cert_provider.create_request(Puppet[:certname], key)
+ csr = @cert_provider.create_request(Puppet[:certname], key)
Puppet::Rest::Routes.put_certificate_request(csr.to_pem, Puppet[:certname], ssl_context)
- cert_provider.save_request(Puppet[:certname], csr)
+ @cert_provider.save_request(Puppet[:certname], csr)
Puppet.notice _("Submitted certificate request for '%{name}' to https://%{server}:%{port}") % {
name: Puppet[:certname], server: Puppet[:ca_server], port: Puppet[:ca_port]
}
@@ -165,9 +169,7 @@ HELP
end
def download_cert(ssl_context)
- ssl_provider = Puppet::SSL::SSLProvider.new
- cert_provider = Puppet::X509::CertProvider.new
- key = cert_provider.load_private_key(Puppet[:certname])
+ key = @cert_provider.load_private_key(Puppet[:certname])
Puppet.info _("Downloading certificate '%{name}' from https://%{server}:%{port}") % {
name: Puppet[:certname], server: Puppet[:ca_server], port: Puppet[:ca_port]
@@ -178,11 +180,11 @@ HELP
cert = OpenSSL::X509::Certificate.new(x509)
Puppet.notice _("Downloaded certificate '%{name}' with fingerprint %{fingerprint}") % { name: Puppet[:certname], fingerprint: fingerprint(cert) }
# verify client cert before saving
- ssl_provider.create_context(
+ @ssl_provider.create_context(
cacerts: ssl_context.cacerts, crls: ssl_context.crls, private_key: key, client_cert: cert
)
- cert_provider.save_client_cert(Puppet[:certname], cert)
- cert_provider.delete_request(Puppet[:certname])
+ @cert_provider.save_client_cert(Puppet[:certname], cert)
+ @cert_provider.delete_request(Puppet[:certname])
Puppet.notice _("Downloaded certificate '%{name}' with fingerprint %{fingerprint}") % {
name: Puppet[:certname], fingerprint: fingerprint(cert)
@@ -199,8 +201,7 @@ HELP
end
def verify(certname)
- ssl = Puppet::SSL::SSLProvider.new
- ssl_context = ssl.load_context(certname: certname)
+ ssl_context = @ssl_provider.load_context(certname: certname)
# print from root to client
ssl_context.client_chain.reverse.each_with_index do |cert, i|
@@ -219,8 +220,7 @@ HELP
cert = nil
begin
- machine = Puppet::SSL::StateMachine.new(onetime: true)
- ssl_context = machine.ensure_ca_certificates
+ ssl_context = @machine.ensure_ca_certificates
cert = Puppet::Rest::Routes.get_certificate(certname, ssl_context)
rescue Puppet::Rest::ResponseError => e
if e.response.code.to_i != 404 | (PUP-<I>) Remove some duplication
Create ssl and cert providers and state machine as instance variables for the
ssl application, and reference them where needed. | puppetlabs_puppet | train |
dcdfeee96c82bb465c2aeb4ecc4d08396818a2ff | diff --git a/blog/models/blog_post_model.php b/blog/models/blog_post_model.php
index <HASH>..<HASH> 100644
--- a/blog/models/blog_post_model.php
+++ b/blog/models/blog_post_model.php
@@ -1275,7 +1275,7 @@ class NAILS_Blog_post_model extends NAILS_Model
$hitData['created'] = $oDate->format('Y-m-d H:i:s');
$hitData['referrer'] = empty($data['referrer']) ? null : prep_url(trim($data['referrer']));
- if ($hitData['user_id'] && $this->user_model->isAdmin($hitData['user_id'])) {
+ if ($hitData['user_id'] && isAdmin($hitData['user_id'])) {
$this->setError('Administrators cannot affect the post\'s popularity.');
return false; | Calling helper function instead of method for brevity | nails_module-blog | train |
f551ec9549cdc5f1a63461d6ce93e523f51e1c88 | diff --git a/lib/lwm2m.js b/lib/lwm2m.js
index <HASH>..<HASH> 100644
--- a/lib/lwm2m.js
+++ b/lib/lwm2m.js
@@ -186,6 +186,8 @@ export default function(RED) {
self.warn(`stored objects JSON must be Object rather than Array`);
json = {};
}
+ self.definitions = lwm2m.objectDefinitions || {};
+ debug(`[init] definitions => ${JSON.stringify(self.definitions)}`);
let initialObjects = {};
try {
initialObjects = JSON.parse(self.objects); | Allow lwm2m settings to set object definitions rather than object instances | CANDY-LINE_node-red-contrib-lwm2m | train |
3753fbb59dac44e59923c6d80596bc2c669301bd | diff --git a/sepa/definitions/statement.py b/sepa/definitions/statement.py
index <HASH>..<HASH> 100644
--- a/sepa/definitions/statement.py
+++ b/sepa/definitions/statement.py
@@ -313,7 +313,7 @@ def entry(tag):
'remittance_information': {
'_self': 'RmtInf',
'_sorting': ['Ustrd', 'Strd'],
- 'unstructed': ['Unstrd'],
+ 'unstructed': ['Ustrd'],
'structured': [{
'_self': 'Strd',
'_sorting': []
diff --git a/setup.py b/setup.py
index <HASH>..<HASH> 100644
--- a/setup.py
+++ b/setup.py
@@ -8,7 +8,7 @@ with open('LICENSE.md') as f:
setup(
name='sepa',
- version='0.4.4',
+ version='0.4.5',
description='Python library for parsing and building SEPA Direct Debit and SEPA eMandate schemas.',
long_description=readme,
license=license, | Release <I> to fix another typo | VerenigingCampusKabel_python-sepa | train |
ec391a4a791d8a30d40225bc8a35b36f266ad588 | diff --git a/config/config.go b/config/config.go
index <HASH>..<HASH> 100644
--- a/config/config.go
+++ b/config/config.go
@@ -12,6 +12,7 @@ type Homebrew struct {
Folder string
Caveats string
Dependencies []string
+ Conflicts []string
}
// Hooks define actions to run before and/or after something
@@ -47,6 +48,7 @@ type Release struct {
type FPM struct {
Formats []string
Dependencies []string
+ Conflicts []string
}
// Project includes all project configuration
diff --git a/pipeline/brew/brew.go b/pipeline/brew/brew.go
index <HASH>..<HASH> 100644
--- a/pipeline/brew/brew.go
+++ b/pipeline/brew/brew.go
@@ -31,6 +31,12 @@ const formula = `class {{ .Name }} < Formula
{{- end }}
{{- end }}
+ {{- if .Conflicts }}
+ {{ range $index, $element := .Conflicts }}
+ conflicts_with "{{ . }}"
+ {{- end }}
+ {{- end }}
+
def install
bin.install "{{ .BinaryName }}"
end
@@ -57,6 +63,7 @@ type templateData struct {
Format string
SHA256 string
Dependencies []string
+ Conflicts []string
}
// Pipe for brew deployment
@@ -164,6 +171,7 @@ func dataFor(ctx *context.Context, client *github.Client) (result templateData,
Format: ctx.Config.Archive.Format,
SHA256: sum,
Dependencies: ctx.Config.Brew.Dependencies,
+ Conflicts: ctx.Config.Brew.Conflicts,
}, err
}
diff --git a/pipeline/brew/brew_test.go b/pipeline/brew/brew_test.go
index <HASH>..<HASH> 100644
--- a/pipeline/brew/brew_test.go
+++ b/pipeline/brew/brew_test.go
@@ -46,6 +46,7 @@ func TestFullFormulae(t *testing.T) {
data := defaultTemplateData
data.Caveats = "Here are some caveats"
data.Dependencies = []string{"gtk", "git"}
+ data.Conflicts = []string{"conflicting_dep"}
out, err := doBuildFormula(data)
assert.NoError(err)
formulae := out.String()
@@ -54,9 +55,10 @@ func TestFullFormulae(t *testing.T) {
assert.Contains(formulae, "Here are some caveats")
assert.Contains(formulae, "depends_on \"gtk\"")
assert.Contains(formulae, "depends_on \"git\"")
+ assert.Contains(formulae, "conflicts_with \"conflicting_dep\"")
}
-func TestFormulaeNoCaveats(t *testing.T) {
+func TestFormulaeSimple(t *testing.T) {
assert := assert.New(t)
out, err := doBuildFormula(defaultTemplateData)
assert.NoError(err)
diff --git a/pipeline/fpm/fpm.go b/pipeline/fpm/fpm.go
index <HASH>..<HASH> 100644
--- a/pipeline/fpm/fpm.go
+++ b/pipeline/fpm/fpm.go
@@ -60,24 +60,27 @@ func create(ctx *context.Context, format, archive, arch string) error {
log.Println("Creating", file)
var options = []string{
- "-s", "dir",
- "-t", format,
- "-n", name,
- "-v", ctx.Version,
- "-a", arch,
- "-C", path,
- "-p", file,
+ "--input-type", "dir",
+ "--output-type", format,
+ "--name", name,
+ "--version", ctx.Version,
+ "--architecture", arch,
+ "--chdir", path,
+ "--package", file,
"--force",
}
for _, dep := range ctx.Config.FPM.Dependencies {
- options = append(options, "-d", dep)
+ options = append(options, "--depends", dep)
}
+ for _, conflict := range ctx.Config.FPM.Conflicts {
+ options = append(options, "--conflicts", conflict)
+ }
+
// This basically tells fpm to put the binary in the /usr/local/bin
// binary=/usr/local/bin/binary
options = append(options, name+"="+filepath.Join("/usr/local/bin", name))
- cmd := exec.Command("fpm", options...)
- if out, err := cmd.CombinedOutput(); err != nil {
+ if out, err := exec.Command("fpm", options...).CombinedOutput(); err != nil {
return errors.New(string(out))
}
return nil | adds conflicts_with for fpm and brew | goreleaser_goreleaser | train |
7013e99eb576dca0764eabe8ee62d2a9ccb26ac8 | diff --git a/agent/tcs/client/client.go b/agent/tcs/client/client.go
index <HASH>..<HASH> 100644
--- a/agent/tcs/client/client.go
+++ b/agent/tcs/client/client.go
@@ -145,7 +145,7 @@ func (cs *clientServer) publishMetrics() {
}
if *metadata.Idle {
- log.Debug("Idle instance, sending message")
+ // Idle instance, send message and return.
cs.MakeRequest(ecstcs.NewPublishMetricsRequest(metadata, taskMetrics))
return
}
@@ -154,14 +154,14 @@ func (cs *clientServer) publishMetrics() {
for i := range taskMetrics {
messageTaskMetrics = append(messageTaskMetrics, taskMetrics[i])
if (i+1)%tasksInMessage == 0 {
- log.Debug("Sending payload, aggregated tasks", "numtasks", i)
+ // Construct payload with tasksInMessage number of task metrics and send to backend.
cs.MakeRequest(ecstcs.NewPublishMetricsRequest(metadata, messageTaskMetrics))
messageTaskMetrics = messageTaskMetrics[:0]
}
}
if len(messageTaskMetrics) > 0 {
- log.Debug("Sending payload, residual tasks", "numtasks", len(messageTaskMetrics))
+ // Send remaining task metrics to backend.
cs.MakeRequest(ecstcs.NewPublishMetricsRequest(metadata, messageTaskMetrics))
}
} | Add comments around sending chunked payloads | aws_amazon-ecs-agent | train |
e10030d864575dc6619442213720e9760fca5f40 | diff --git a/src/cells.js b/src/cells.js
index <HASH>..<HASH> 100644
--- a/src/cells.js
+++ b/src/cells.js
@@ -1,5 +1,4 @@
import { appendFromTemplate, selectionChanged, rebind, forward } from '@zambezi/d3-utils'
-import { dataset } from './dataset'
import { dispatch as createDispatch } from 'd3-dispatch'
import { property, batch } from '@zambezi/fun'
import { select } from 'd3-selection'
@@ -12,6 +11,7 @@ const appendDefaultCell = appendFromTemplate(
, appendRow = appendFromTemplate('<li class="zambezi-grid-row"></li>')
, changed = selectionChanged()
, firstLastChanged = selectionChanged().key(firstAndLast)
+ , indexChanged = selectionChanged().key(d => d.index).debug(true)
, id = property('id')
, isFirst = property('isFirst')
, isLast = property('isLast')
@@ -92,8 +92,7 @@ export function createCells() {
, rowChanged = rows
.merge(rowsEnter)
.each(forward(dispatcher, 'row-update'))
- .each(updateRow)
- .call(dataset, 'gridRowIndex', d => d.index)
+ .call(updateRow)
.select(
changed.key(
orderAndKey(rowChangedKey, visibleCellsHash)
@@ -153,11 +152,12 @@ export function createCells() {
}
}
- function updateRow(d) {
- const index = d.index
- , selector = `#${ gridId } [data-grid-row-index="${index}"]`
+ function updateRow(s) {
+ s.select(indexChanged).each(updateTop)
+ }
- sheet(selector, { top: top(d) })
+ function updateTop(d) {
+ select(this).style('top', top)
}
} | Use inline styles for rows
The grid was proliferating rules by adding a rule per row -- in Chrome that was fine, but in IE it wasn't | zambezi_grid | train |
f74a7f5684e9c053a6370e7561eafed85d31be8b | diff --git a/src/XR.js b/src/XR.js
index <HASH>..<HASH> 100644
--- a/src/XR.js
+++ b/src/XR.js
@@ -141,6 +141,17 @@ class XRSession extends EventTarget {
this.depthFar = depthFar;
}
if (renderWidth !== undefined && renderHeight !== undefined) {
+ if (this.baseLayer) {
+ const {context} = this.baseLayer;
+
+ if (context.drawingBufferWidth !== renderWidth * 2) {
+ context.canvas.width = renderWidth * 2;
+ }
+ if (context.drawingBufferHeight !== renderHeight) {
+ context.canvas.height = renderHeight;
+ }
+ }
+
for (let i = 0; i < this._frame.views.length; i++) {
this._frame.views[i]._viewport.set(i * renderWidth, 0, renderWidth, renderHeight);
} | Make XRWebGLLayer resize context to match renderWidth | exokitxr_exokit | train |
e485a6ee2a1f05f2333e22b0fbdbafb12badaf3f | diff --git a/kafka/client_async.py b/kafka/client_async.py
index <HASH>..<HASH> 100644
--- a/kafka/client_async.py
+++ b/kafka/client_async.py
@@ -201,10 +201,15 @@ class KafkaClient(object):
if key in configs:
self.config[key] = configs[key]
+ # these properties need to be set on top of the initialization pipeline
+ # because they are used when __del__ method is called
+ self._closed = False
+ self._wake_r, self._wake_w = socket.socketpair()
+ self._selector = self.config['selector']()
+
self.cluster = ClusterMetadata(**self.config)
self._topics = set() # empty set will fetch all topic metadata
self._metadata_refresh_in_progress = False
- self._selector = self.config['selector']()
self._conns = Dict() # object to support weakrefs
self._api_versions = None
self._connecting = set()
@@ -212,7 +217,6 @@ class KafkaClient(object):
self._refresh_on_disconnects = True
self._last_bootstrap = 0
self._bootstrap_fails = 0
- self._wake_r, self._wake_w = socket.socketpair()
self._wake_r.setblocking(False)
self._wake_w.settimeout(self.config['wakeup_timeout_ms'] / 1000.0)
self._wake_lock = threading.Lock()
@@ -226,7 +230,6 @@ class KafkaClient(object):
self._selector.register(self._wake_r, selectors.EVENT_READ)
self._idle_expiry_manager = IdleConnectionManager(self.config['connections_max_idle_ms'])
- self._closed = False
self._sensors = None
if self.config['metrics']:
self._sensors = KafkaClientMetrics(self.config['metrics'], | Fix initialization order in KafkaClient (#<I>)
Fix initialization order in KafkaClient | dpkp_kafka-python | train |
b8bcdaa95339911ba3c19b540577d478567ae1e6 | diff --git a/api/handler.go b/api/handler.go
index <HASH>..<HASH> 100644
--- a/api/handler.go
+++ b/api/handler.go
@@ -24,14 +24,14 @@ import (
"strings"
)
-var maxMemory int
+var maxMemory uint
-func maxMemoryValue() int {
+func maxMemoryValue() uint {
if maxMemory > 0 {
return maxMemory
}
var err error
- maxMemory, err = config.GetInt("api:request:maxMemory")
+ maxMemory, err = config.GetUint("api:request:maxMemory")
if err != nil {
panic("You should configure a api:request:maxMemory for gandalf.")
}
diff --git a/api/handler_test.go b/api/handler_test.go
index <HASH>..<HASH> 100644
--- a/api/handler_test.go
+++ b/api/handler_test.go
@@ -67,14 +67,22 @@ func (s *S) authKeysContent(c *gocheck.C) string {
func (s *S) TestMaxMemoryValueShouldComeFromGandalfConf(c *gocheck.C) {
config.Set("api:request:maxMemory", 1024)
+ oldMaxMemory := maxMemory
maxMemory = 0
- c.Assert(maxMemoryValue(), gocheck.Equals, 1024)
+ defer func() {
+ maxMemory = oldMaxMemory
+ }()
+ c.Assert(maxMemoryValue(), gocheck.Equals, uint(1024))
}
func (s *S) TestMaxMemoryValueDontResetMaxMemory(c *gocheck.C) {
config.Set("api:request:maxMemory", 1024)
+ oldMaxMemory := maxMemory
maxMemory = 359
- c.Assert(maxMemoryValue(), gocheck.Equals, 359)
+ defer func() {
+ maxMemory = oldMaxMemory
+ }()
+ c.Assert(maxMemoryValue(), gocheck.Equals, uint(359))
}
func (s *S) TestNewUser(c *gocheck.C) { | Declare maxMemory as uint | tsuru_gandalf | train |
a7686e82f003284f167a064eacd7e3194d52a3c3 | diff --git a/src/Composer/Command/InitCommand.php b/src/Composer/Command/InitCommand.php
index <HASH>..<HASH> 100644
--- a/src/Composer/Command/InitCommand.php
+++ b/src/Composer/Command/InitCommand.php
@@ -869,10 +869,10 @@ EOT
return array($name, $requiredVersion ?: '*');
}
- // Check whether the PHP version was the problem
+ // Check whether the package requirements were the problem
if (true !== $ignorePlatformReqs && ($candidate = $versionSelector->findBestCandidate($name, $requiredVersion, $preferredStability, true))) {
throw new \InvalidArgumentException(sprintf(
- 'Package %s%s has a PHP requirement incompatible with your PHP version, PHP extensions and Composer version' . $this->getPlatformExceptionDetails($candidate, $platformRepo),
+ 'Package %s%s has requirements incompatible with your PHP version, PHP extensions and Composer version' . $this->getPlatformExceptionDetails($candidate, $platformRepo),
$name,
$requiredVersion ? ' at version '.$requiredVersion : ''
));
diff --git a/src/Composer/Package/Version/VersionSelector.php b/src/Composer/Package/Version/VersionSelector.php
index <HASH>..<HASH> 100644
--- a/src/Composer/Package/Version/VersionSelector.php
+++ b/src/Composer/Package/Version/VersionSelector.php
@@ -82,14 +82,20 @@ class VersionSelector
$reqs = $pkg->getRequires();
foreach ($reqs as $name => $link) {
- if (!in_array($name, $ignorePlatformReqs, true) && isset($platformConstraints[$name])) {
- foreach ($platformConstraints[$name] as $constraint) {
- if ($link->getConstraint()->matches($constraint)) {
- continue 2;
+ if (!in_array($name, $ignorePlatformReqs, true)) {
+ if (isset($platformConstraints[$name])) {
+ foreach ($platformConstraints[$name] as $constraint) {
+ if ($link->getConstraint()->matches($constraint)) {
+ continue 2;
+ }
}
- }
- return false;
+ return false;
+ } elseif (PlatformRepository::isPlatformPackage($name)) {
+ // Package requires a platform package that is unknown on current platform.
+ // It means that current platform cannot validate this constraint and so package is not installable.
+ return false;
+ }
}
}
diff --git a/tests/Composer/Test/Package/Version/VersionSelectorTest.php b/tests/Composer/Test/Package/Version/VersionSelectorTest.php
index <HASH>..<HASH> 100644
--- a/tests/Composer/Test/Package/Version/VersionSelectorTest.php
+++ b/tests/Composer/Test/Package/Version/VersionSelectorTest.php
@@ -100,6 +100,31 @@ class VersionSelectorTest extends TestCase
$this->assertSame($package2, $best, 'Latest version should be returned when ignoring platform reqs (2.0.0)');
}
+ public function testLatestVersionIsReturnedThatMatchesPlatformExt()
+ {
+ $packageName = 'foobar';
+
+ $platform = new PlatformRepository();
+ $repositorySet = $this->createMockRepositorySet();
+ $versionSelector = new VersionSelector($repositorySet, $platform);
+
+ $parser = new VersionParser;
+ $package1 = $this->createPackage('1.0.0');
+ $package2 = $this->createPackage('2.0.0');
+ $package2->setRequires(array('ext-barfoo' => new Link($packageName, 'ext-barfoo', $parser->parseConstraints('*'), Link::TYPE_REQUIRE, '*')));
+ $packages = array($package1, $package2);
+
+ $repositorySet->expects($this->any())
+ ->method('findPackages')
+ ->with($packageName, null)
+ ->will($this->returnValue($packages));
+
+ $best = $versionSelector->findBestCandidate($packageName);
+ $this->assertSame($package1, $best, 'Latest version not requiring ext-barfoo should be returned (1.0.0)');
+ $best = $versionSelector->findBestCandidate($packageName, null, 'stable', true);
+ $this->assertSame($package2, $best, 'Latest version should be returned when ignoring platform reqs (2.0.0)');
+ }
+
public function testLatestVersionIsReturnedThatMatchesComposerRequirements()
{
$packageName = 'foobar'; | Filter candidates requiring an unknown platform package; fixes #<I> (#<I>) | composer_composer | train |
d54c5577ca03f42ade4e4f04f5fe516451d973d9 | diff --git a/spyderlib/widgets/browser.py b/spyderlib/widgets/browser.py
index <HASH>..<HASH> 100644
--- a/spyderlib/widgets/browser.py
+++ b/spyderlib/widgets/browser.py
@@ -116,13 +116,12 @@ class WebBrowser(QWidget):
hlayout = QHBoxLayout()
for widget in (previous_button, next_button, home_button, find_button,
label, self.url_combo, zoom_out_button, zoom_in_button,
- refresh_button, stop_button):
+ refresh_button, progressbar, stop_button):
hlayout.addWidget(widget)
layout = QVBoxLayout()
layout.addLayout(hlayout)
layout.addWidget(self.webview)
- layout.addWidget(progressbar)
layout.addWidget(self.find_widget)
self.setLayout(layout) | Web browser widget: moved progress bar from bottom to top right | spyder-ide_spyder | train |
ce82167559953e15fb2814a7ac742005450b1b58 | diff --git a/lib/credentials-io.js b/lib/credentials-io.js
index <HASH>..<HASH> 100644
--- a/lib/credentials-io.js
+++ b/lib/credentials-io.js
@@ -205,16 +205,10 @@ api.verify = function(identity, options, callback) {
});
}, callback);
}],
- getEphemeralPublicKey: ['verifyCredentials', function(callback, results) {
- var signature = result.identity.signature || {};
- var creator = signature.creator || '';
- if(creator.indexOf('http') === 0 || creator.indexOf('did') === 0) {
- // known schemes; no special retrieval of public key
- return callback(null, null);
- }
- getEphemeralPublicKey(result, callback);
+ getIdpSignedPublicKey: ['verifyCredentials', function(callback) {
+ getIdpSignedPublicKey(result, callback);
}],
- verifyIdentity: ['getEphemeralPublicKey', function(callback, results) {
+ verifyIdentity: ['getIdpSignedPublicKey', function(callback, results) {
var opts = _.assign({
id: result.identity.id,
checkTimestamp: true
@@ -222,9 +216,9 @@ api.verify = function(identity, options, callback) {
checkDomain: checkDomain(result),
checkKeyOwner: checkKeyOwner(result)
});
- if(results.getEphemeralPublicKey) {
- opts.publicKeyOwner = results.getEphemeralPublicKey.publicKeyOwner;
- opts.publicKey = results.getEphemeralPublicKey.publicKey;
+ if(results.getIdpSignedPublicKey) {
+ opts.publicKeyOwner = results.getIdpSignedPublicKey.publicKeyOwner;
+ opts.publicKey = results.getIdpSignedPublicKey.publicKey;
}
jsigs.verify(result.identity, opts, function(err, verified) {
result.verified = !err && verified;
@@ -276,7 +270,7 @@ function checkKeyOwner(result) {
};
}
-function getEphemeralPublicKey(result, callback) {
+function getIdpSignedPublicKey(result, callback) {
var jsonld = api.use('jsonld');
var identity = result.identity;
async.auto({
@@ -306,9 +300,6 @@ function getEphemeralPublicKey(result, callback) {
continue;
}
var publicKey = credential.claim.publicKey;
- if(!jsonld.hasValue(publicKey, 'type', 'EphemeralCryptographicKey')) {
- continue;
- }
// match found if public key ID matches creator of signature on
// identity, credential is verified, and key owner ID is identity's IdP
var res = result.credentials[credential.id];
@@ -321,10 +312,10 @@ function getEphemeralPublicKey(result, callback) {
callback(null, null);
}]
}, function(err, results) {
- callback(err, {
+ callback(err, results.getMatch ? {
publicKeyOwner: results.getIdentity,
publicKey: results.getMatch
- });
+ } : null);
});
} | Change ephemeral key verification to idp-signed.
- Check is non-specific to ephemeral keys; it applies to any
public key asserted by the user's IdP.
- Needs a security audit. Trusting an IdP's view of a particular
key is only valid for very specific use cases. | digitalbazaar_credentials-io | train |
12264767908e495af28be5c07cde905489d78a70 | diff --git a/beep_darwin.go b/beep_darwin.go
index <HASH>..<HASH> 100644
--- a/beep_darwin.go
+++ b/beep_darwin.go
@@ -23,6 +23,6 @@ func Beep(freq float64, duration int) error {
return err
}
- cmd := exec.Command(osa, "-e", `tell application "System Events" to beep`)
+ cmd := exec.Command(osa, "-e", `beep`)
return cmd.Run()
} | beep_darwin: beep without requiring special system events permissions | gen2brain_beeep | train |
fb7e012cd59cee48d581338b0c7d256df2a65e73 | diff --git a/src/main/java/de/digitalcollections/iiif/model/image/ImageApiProfile.java b/src/main/java/de/digitalcollections/iiif/model/image/ImageApiProfile.java
index <HASH>..<HASH> 100644
--- a/src/main/java/de/digitalcollections/iiif/model/image/ImageApiProfile.java
+++ b/src/main/java/de/digitalcollections/iiif/model/image/ImageApiProfile.java
@@ -339,8 +339,11 @@ public class ImageApiProfile extends Profile {
/** Merge multiple profiles into one.
Useful for image servers that want to consolidate the limits given in a info.json. */
- public static ImageApiProfile merge(List<ImageApiProfile> profiles) {
- return profiles.stream().reduce(new ImageApiProfile(), ImageApiProfile::merge);
+ public static ImageApiProfile merge(List<Profile> profiles) {
+ return profiles.stream()
+ .filter(ImageApiProfile.class::isInstance)
+ .map(ImageApiProfile.class::cast)
+ .reduce(new ImageApiProfile(), ImageApiProfile::merge);
}
/** Merge two profiles. */
diff --git a/src/test/java/de/digitalcollections/iiif/model/image/ProfileTest.java b/src/test/java/de/digitalcollections/iiif/model/image/ProfileTest.java
index <HASH>..<HASH> 100644
--- a/src/test/java/de/digitalcollections/iiif/model/image/ProfileTest.java
+++ b/src/test/java/de/digitalcollections/iiif/model/image/ProfileTest.java
@@ -1,5 +1,6 @@
package de.digitalcollections.iiif.model.image;
+import de.digitalcollections.iiif.model.Profile;
import java.util.ArrayList;
import java.util.List;
import org.junit.Test;
@@ -9,7 +10,7 @@ import static org.assertj.core.api.Assertions.assertThat;
public class ProfileTest {
@Test
public void testMerge() {
- List<ImageApiProfile> profiles = new ArrayList<>();
+ List<Profile> profiles = new ArrayList<>();
profiles.add(ImageApiProfile.LEVEL_ONE);
ImageApiProfile extraProfile = new ImageApiProfile();
extraProfile.addFeature(ImageApiProfile.Feature.REGION_BY_PCT, | Relax type requirements for ImageApiProfile.class::merge | dbmdz_iiif-apis | train |
9e06add44f57dfcb3668546ad6ae0c4060b22a87 | diff --git a/autofit/graphical/declarative.py b/autofit/graphical/declarative.py
index <HASH>..<HASH> 100644
--- a/autofit/graphical/declarative.py
+++ b/autofit/graphical/declarative.py
@@ -130,6 +130,8 @@ class AbstractModelFactor(Analysis, ABC):
-------
A collection of prior models
"""
+ self.freeze()
+
opt = self._make_ep_optimiser(
optimiser
)
diff --git a/test_autofit/graphical/gaussian/test_declarative.py b/test_autofit/graphical/gaussian/test_declarative.py
index <HASH>..<HASH> 100644
--- a/test_autofit/graphical/gaussian/test_declarative.py
+++ b/test_autofit/graphical/gaussian/test_declarative.py
@@ -156,8 +156,6 @@ def test_factor_model_attributes(
def test_optimise_factor_model(
factor_model
):
- factor_model.freeze()
-
"""
We optimise the model
""" | freeze whenever optimising a declarative graphical model | rhayes777_PyAutoFit | train |
24463b7c1832af22eeb7e52051fc8798ecfbbe65 | diff --git a/pyqode/python/panels/quick_doc.py b/pyqode/python/panels/quick_doc.py
index <HASH>..<HASH> 100644
--- a/pyqode/python/panels/quick_doc.py
+++ b/pyqode/python/panels/quick_doc.py
@@ -4,8 +4,8 @@ Contains the quick documentation panel
"""
from docutils.core import publish_parts
from pyqode.core import icons
-from pyqode.qt import QtCore, QtGui, QtWidgets
-from pyqode.core.api import Panel, TextHelper, CodeEdit
+from pyqode.qt import QtCore, QtWidgets
+from pyqode.core.api import Panel, TextHelper
from pyqode.python.backend.workers import quick_doc
@@ -15,14 +15,6 @@ class QuickDocPanel(Panel):
This panel quickly shows the documentation of the symbol under
cursor.
"""
- STYLESHEET = '''
- QTextEdit
- {
- background-color: %s;
- color: %s;
- }
- '''
-
_KEYS = ['panelBackground', 'background', 'panelForeground',
'panelHighlight']
@@ -60,15 +52,8 @@ class QuickDocPanel(Panel):
self.action_quick_doc.triggered.connect(
self._on_action_quick_doc_triggered)
- def _reset_stylesheet(self):
- p = self.text_edit.palette()
- p.setColor(p.Base, self.editor.palette().toolTipBase().color())
- p.setColor(p.Text, self.editor.palette().toolTipText().color())
- self.text_edit.setPalette(p)
-
def on_install(self, editor):
super(QuickDocPanel, self).on_install(editor)
- self._reset_stylesheet()
self.setVisible(False)
def on_state_changed(self, state):
@@ -78,9 +63,6 @@ class QuickDocPanel(Panel):
else:
self.editor.remove_action(self.action_quick_doc)
- def refresh_style(self):
- self._reset_stylesheet()
-
def _on_action_quick_doc_triggered(self):
tc = TextHelper(self.editor).word_under_cursor(select_whole_word=True)
request_data = {
@@ -94,7 +76,6 @@ class QuickDocPanel(Panel):
quick_doc, request_data, on_receive=self._on_results_available)
def _on_results_available(self, results):
- self._reset_stylesheet()
self.setVisible(True)
if len(results) and results[0] != '':
string = '\n\n'.join(results) | Fix quick dock panel colors (remove stylesheet) | pyQode_pyqode.python | train |
59e4eda9ebbeda2d87e4fe78523e3386be52c280 | diff --git a/dark/graphics.py b/dark/graphics.py
index <HASH>..<HASH> 100644
--- a/dark/graphics.py
+++ b/dark/graphics.py
@@ -575,9 +575,11 @@ def alignmentPanel(titlesAlignments, sortOn='maxScore', interactive=True,
readCount = titleAlignments.readCount()
hspCount = titleAlignments.hspCount()
- try:
+ # Make a short title for the small panel blue plot, ignoring any
+ # leading NCBI gi / accession numbers.
+ if title.startswith('gi|') and title.find(' ') > -1:
shortTitle = title.split(' ', 1)[1][:40]
- except IndexError:
+ else:
shortTitle = title[:40]
plotTitle = ('%d: %s\nLength %d, %d read%s, %d HSP%s.' % ( | Improved short title processing in graphics.py alignment panel. | acorg_dark-matter | train |
ceb3b3744d2d195d54d5e6d36e41d51965e30b1c | diff --git a/bayes_opt/helpers.py b/bayes_opt/helpers.py
index <HASH>..<HASH> 100644
--- a/bayes_opt/helpers.py
+++ b/bayes_opt/helpers.py
@@ -30,7 +30,7 @@ class UtilityFunction(object):
if self.kind == 'ei':
return self._ei(x, gp, y_max)
if self.kind == 'poi':
- return self._ucb(x, gp, y_max)
+ return self._poi(x, gp, y_max)
@staticmethod
def _ucb(x, gp, kappa): | bugfix: selecting the "poi" acquisition function actually selected the "ucb" acquisition function :/ | fmfn_BayesianOptimization | train |
05c455b85396d7457fe8fd20e733f05d635e6553 | diff --git a/plugins/org.eclipse.xtext.xbase/src/org/eclipse/xtext/xbase/compiler/TypeConvertingCompiler.java b/plugins/org.eclipse.xtext.xbase/src/org/eclipse/xtext/xbase/compiler/TypeConvertingCompiler.java
index <HASH>..<HASH> 100644
--- a/plugins/org.eclipse.xtext.xbase/src/org/eclipse/xtext/xbase/compiler/TypeConvertingCompiler.java
+++ b/plugins/org.eclipse.xtext.xbase/src/org/eclipse/xtext/xbase/compiler/TypeConvertingCompiler.java
@@ -353,6 +353,11 @@ public class TypeConvertingCompiler extends AbstractXbaseCompiler {
final ITreeAppendable appendable,
final Later expression) {
appendable.append("(");
+ if (mustInsertTypeCast(context, wrapper)) {
+ appendable.append("(");
+ serialize(wrapper, context, appendable);
+ appendable.append(") ");
+ }
expression.exec(appendable);
appendable.append(")");
appendable.append("."); | [bug <I>]: fixed converting of wrapped type to primitive type with
type cast
Change-Id: Ia<I>f<I>ef<I>ff<I>c<I>f7e<I>e<I>a2f | eclipse_xtext-extras | train |
5b5c2c5d8789e1177a7e25cdbd8286e6a79eb647 | diff --git a/assess_network_health.py b/assess_network_health.py
index <HASH>..<HASH> 100755
--- a/assess_network_health.py
+++ b/assess_network_health.py
@@ -56,7 +56,7 @@ class AssessNetworkHealth:
"""
self.setup_testing_environment(client, bundle, target_model, series)
log.info('Starting network tests.')
- results_pre = self.testing_iterations(client, series)
+ results_pre = self.testing_iterations(client, series, target_model)
error_string = ['Initial test failures:']
if not reboot:
if results_pre:
@@ -66,7 +66,7 @@ class AssessNetworkHealth:
return
log.info('Units completed pre-reboot tests, rebooting machines.')
self.reboot_machines(client)
- results_post = self.testing_iterations(client, series,
+ results_post = self.testing_iterations(client, series, target_model,
reboot_msg='Post-reboot ')
if results_pre or results_post:
error_string.extend(results_pre or 'No pre-reboot failures.')
@@ -76,7 +76,7 @@ class AssessNetworkHealth:
log.info('SUCESS')
return
- def testing_iterations(self, client, series, reboot_msg=''):
+ def testing_iterations(self, client, series, target_model, reboot_msg=''):
"""Runs through each test given for a given client and series
:param client: Client
@@ -97,13 +97,15 @@ class AssessNetworkHealth:
json.dumps(vis_result,
indent=4,
sort_keys=True)))
- exp_result = self.ensure_exposed(client, series)
- log.info('{0}Exposure '
- 'result:\n {1}'.format(reboot_msg,
- json.dumps(exp_result,
- indent=4,
- sort_keys=True)) or
- NO_EXPOSED_UNITS)
+ exp_result = None
+ if not target_model:
+ exp_result = self.ensure_exposed(client, series)
+ log.info('{0}Exposure '
+ 'result:\n {1}'.format(reboot_msg,
+ json.dumps(exp_result,
+ indent=4,
+ sort_keys=True)) or
+ NO_EXPOSED_UNITS)
log.info('Tests complete.')
return self.parse_final_results(con_result, vis_result, int_result,
exp_result)
@@ -338,7 +340,7 @@ class AssessNetworkHealth:
return result
def parse_final_results(self, controller, visibility, internet,
- exposed=None):
+ exposed):
"""Parses test results and raises an error if any failed.
:param controller: Controller test result | removed expose test if given a target model | juju_juju | train |
311ca1cc729d9d18bf2e4a3411a2b3d9ab1e49ee | diff --git a/fetch.go b/fetch.go
index <HASH>..<HASH> 100644
--- a/fetch.go
+++ b/fetch.go
@@ -32,6 +32,10 @@ var (
)
const (
+ // DefaultCrawlPoliteness states that the crawling process is polite by default,
+ // meaning that robots.txt policies are respected if present.
+ DefaultCrawlPoliteness = true
+
// DefaultCrawlDelay represents the delay to use if there is no robots.txt
// specified delay.
DefaultCrawlDelay = 5 * time.Second
@@ -57,6 +61,10 @@ type Fetcher struct {
// produce a Handler call.
Handler Handler
+ // CrawlPoliteness makes the fetcher respect the robots.txt policies of hosts by
+ // requesting and parsing it before any other request to the same host.
+ CrawlPoliteness bool
+
// Default delay to use between requests to a same host if there is no robots.txt
// crawl delay.
CrawlDelay time.Duration
@@ -99,12 +107,13 @@ type DebugInfo struct {
// New returns an initialized Fetcher.
func New(h Handler) *Fetcher {
return &Fetcher{
- Handler: h,
- CrawlDelay: DefaultCrawlDelay,
- HttpClient: http.DefaultClient,
- UserAgent: DefaultUserAgent,
- WorkerIdleTTL: DefaultWorkerIdleTTL,
- dbg: make(chan *DebugInfo, 1),
+ Handler: h,
+ CrawlPoliteness: DefaultCrawlPoliteness,
+ CrawlDelay: DefaultCrawlDelay,
+ HttpClient: http.DefaultClient,
+ UserAgent: DefaultUserAgent,
+ WorkerIdleTTL: DefaultWorkerIdleTTL,
+ dbg: make(chan *DebugInfo, 1),
}
}
@@ -253,7 +262,7 @@ loop:
// Must send the robots.txt request.
rob, err := u.Parse("/robots.txt")
- if err != nil {
+ if err != nil && f.CrawlPoliteness {
f.mu.Unlock()
// Handle on a separate goroutine, the Queue goroutine must not block.
go f.Handler.Handle(&Context{Cmd: v, Q: f.q}, nil, err)
@@ -271,8 +280,11 @@ loop:
go sliceIQ(in, out)
// Start the working goroutine for this host
go f.processChan(out, u.Host)
- // Enqueue the robots.txt request first.
- in <- robotCommand{&Cmd{U: rob, M: "GET"}}
+
+ if f.CrawlPoliteness {
+ // Enqueue the robots.txt request first.
+ in <- robotCommand{&Cmd{U: rob, M: "GET"}}
+ }
} else {
f.mu.Unlock()
} | Now robots.txt policy checks can be disabled
However they are active by default. | PuerkitoBio_fetchbot | train |
fae77f5d998d5743eb6f084b6a10c6a11bb9cb1f | diff --git a/lib/voice/players/FFmpegEncoder.js b/lib/voice/players/FFmpegEncoder.js
index <HASH>..<HASH> 100644
--- a/lib/voice/players/FFmpegEncoder.js
+++ b/lib/voice/players/FFmpegEncoder.js
@@ -226,9 +226,9 @@ class FFmpegEncoder extends ExternalEncoderBase {
this._stream.unpipe(dest);
}
destroy() {
- if (this._handle) {
+ if (this._handle && this._handle.exitCode === null) {
const handle = this._handle;
- // send an extra SIGTERM to interrupt trasncoding
+ // send an extra SIGTERM to interrupt transcoding
handle.kill();
// kill with SIGKILL if it still hasn't exited
setTimeout(() => handle.kill("SIGKILL"), 5000); | Schedule a FFmpeg SIGKILL only if it hasn't exited | qeled_discordie | train |
bf404d4fbce589d6396c3b793f729a76f710a65f | diff --git a/lib/media/media_source_engine.js b/lib/media/media_source_engine.js
index <HASH>..<HASH> 100644
--- a/lib/media/media_source_engine.js
+++ b/lib/media/media_source_engine.js
@@ -113,7 +113,7 @@ shaka.media.MediaSourceEngine.isTypeSupported = function(mimeType) {
* @return {boolean}
*/
shaka.media.MediaSourceEngine.isBrowserSupported = function() {
- return !!window.MediaSource;
+ return !!window.MediaSource && !!window.MediaSource.isTypeSupported;
}; | Check for MediaSource.isTypeSupported
On at least one TV platform, isBrowserSupported returned true in spite
of a lack of MediaSource.isTypeSupported. (See #<I>) This adds a
check for that required method.
Change-Id: I4e<I>b<I>c1b3eafc9a<I>f7d<I>ecbb<I> | google_shaka-player | train |
3f75740b43b806df56b1bdb59763138b5fdd922f | diff --git a/src/main/java/org/andidev/webdriverextension/junitrunner/WebDriverRunner.java b/src/main/java/org/andidev/webdriverextension/junitrunner/WebDriverRunner.java
index <HASH>..<HASH> 100644
--- a/src/main/java/org/andidev/webdriverextension/junitrunner/WebDriverRunner.java
+++ b/src/main/java/org/andidev/webdriverextension/junitrunner/WebDriverRunner.java
@@ -142,7 +142,8 @@ public class WebDriverRunner extends BlockJUnit4ClassRunner {
if (method.getAnnotation(Ignore.class) != null
|| browserConfigurations.isBrowserIgnored(browserConfiguration)
|| (BrowserType.IE.equals(browserConfiguration.getBrowserName()) && !OsUtils.isWindows())
- || (BrowserType.IEXPLORE.equals(browserConfiguration.getBrowserName()) && !OsUtils.isWindows())) {
+ || (BrowserType.IEXPLORE.equals(browserConfiguration.getBrowserName()) && !OsUtils.isWindows())
+ || (BrowserType.SAFARI.equals(browserConfiguration.getBrowserName()) && (!OsUtils.isWindows() && !OsUtils.isMac()))) {
notifier.fireTestIgnored(description);
} else {
long threadId = Thread.currentThread().getId(); | Ignoring Safari tests on platforms not equal to Windows or Mac | webdriverextensions_webdriverextensions | train |
103d27d380d30f4d0c622e66f92b8402ae89df37 | diff --git a/test/test.js b/test/test.js
index <HASH>..<HASH> 100644
--- a/test/test.js
+++ b/test/test.js
@@ -450,25 +450,25 @@ describe('vend-nodejs-sdk', function () {
describe('with products API', function() {
this.timeout(300000);
- xit('BROKEN: can create a product', function () {
- // TODO: implement it - doesn't work right now
+ it('can create a product', function () {
var args = vendSdk.args.products.create();
+ var cost = faker.fake('{{commerce.price}}'); // faker.commerce.price
+ var sku = faker.fake('{{random.number}}'); // faker.random.number,
var randomProduct = {
- 'handle': faker.lorem.word(1),
- 'has_variants': false,
- //'active':true,
- 'name': faker.commerce.productName(),
- 'description': faker.lorem.sentence(),
- 'sku': faker.fake('{{random.number}}'), // faker.random.number,
- 'supply_price': faker.fake('{{commerce.price}}') // faker.commerce.price
+ 'name': faker.commerce.productName(), // REQUIRED
+ 'sku': sku, // REQUIRED
+ 'handle': faker.lorem.word(1), // REQUIRED
+ 'retail_price': cost + 5.00, // REQUIRED
+ 'supply_price': cost,
+ 'description': faker.lorem.sentence()
};
randomProduct.price = String(Number(randomProduct['supply_price']) + 10.00);
args.body.value = randomProduct;
return vendSdk.products.create(args, getConnectionInfo())
.then(function (response) {
- log.debug('response', response);
+ log.debug('response:', response);
});
}); | fixed test - create a product | ShoppinPal_vend-nodejs-sdk | train |
76f938b86b52e0be7399e6934a7cc7d757d45ef7 | diff --git a/src/FelixOnline/Core/Theme.php b/src/FelixOnline/Core/Theme.php
index <HASH>..<HASH> 100644
--- a/src/FelixOnline/Core/Theme.php
+++ b/src/FelixOnline/Core/Theme.php
@@ -20,8 +20,8 @@ class Theme {
function __construct($name) {
global $currentuser, $db;
$this->name = $name;
- $this->directory = BASE_DIRECTORY.'/themes/'.$this->name;
- $this->url = STANDARD_URL.'themes/'.$this->name;
+ $this->directory = BASE_DIRECTORY.'/themes/'.$this->name.'/';
+ $this->url = STANDARD_URL.'themes/'.$this->name.'/';
/*
* Check if there is theme specific theme class and load in if there is | Fix missing slash in theme resource urls | FelixOnline_BaseApp | train |
ed2f434593e27a9a72feb4eeadd96e20ba895287 | diff --git a/python/ray/serve/master.py b/python/ray/serve/master.py
index <HASH>..<HASH> 100644
--- a/python/ray/serve/master.py
+++ b/python/ray/serve/master.py
@@ -323,6 +323,23 @@ class ServeMaster:
await worker_handle.ready.remote()
return worker_handle
+ async def _start_replica(self, backend_tag, replica_tag):
+ # NOTE(edoakes): the replicas may already be created if we
+ # failed after creating them but before writing a
+ # checkpoint.
+ try:
+ worker_handle = ray.util.get_actor(replica_tag)
+ except ValueError:
+ worker_handle = await self._start_backend_worker(
+ backend_tag, replica_tag)
+
+ self.replicas[backend_tag].append(replica_tag)
+ self.workers[backend_tag][replica_tag] = worker_handle
+
+ # Register the worker with the router.
+ await self.router.add_new_worker.remote(backend_tag, replica_tag,
+ worker_handle)
+
async def _start_pending_replicas(self):
"""Starts the pending backend replicas in self.replicas_to_start.
@@ -332,22 +349,14 @@ class ServeMaster:
Clears self.replicas_to_start.
"""
+ replica_started_futures = []
for backend_tag, replicas_to_create in self.replicas_to_start.items():
for replica_tag in replicas_to_create:
- # NOTE(edoakes): the replicas may already be created if we
- # failed after creating them but before writing a checkpoint.
- try:
- worker_handle = ray.util.get_actor(replica_tag)
- except ValueError:
- worker_handle = await self._start_backend_worker(
- backend_tag, replica_tag)
+ replica_started_futures.append(
+ self._start_replica(backend_tag, replica_tag))
- self.replicas[backend_tag].append(replica_tag)
- self.workers[backend_tag][replica_tag] = worker_handle
-
- # Register the worker with the router.
- await self.router.add_new_worker.remote(
- backend_tag, replica_tag, worker_handle)
+ # Wait on all creation task futures together.
+ await asyncio.gather(*replica_started_futures)
self.replicas_to_start.clear()
diff --git a/python/ray/serve/tests/test_api.py b/python/ray/serve/tests/test_api.py
index <HASH>..<HASH> 100644
--- a/python/ray/serve/tests/test_api.py
+++ b/python/ray/serve/tests/test_api.py
@@ -1,4 +1,6 @@
import time
+import asyncio
+
import pytest
import requests
@@ -386,3 +388,41 @@ def test_cluster_name():
serve.init(cluster_name="cluster1")
serve.delete_endpoint(endpoint)
serve.delete_backend(backend)
+
+
+def test_parallel_start(serve_instance):
+ # Test the ability to start multiple replicas in parallel.
+ # In the past, when Serve scale up a backend, it does so one by one and
+ # wait for each replica to initialize. This test avoid this by preventing
+ # the first replica to finish initialization unless the second replica is
+ # also started.
+ @ray.remote
+ class Barrier:
+ def __init__(self, release_on):
+ self.release_on = release_on
+ self.current_waiters = 0
+ self.event = asyncio.Event()
+
+ async def wait(self):
+ self.current_waiters += 1
+ if self.current_waiters == self.release_on:
+ self.event.set()
+ else:
+ await self.event.wait()
+
+ barrier = Barrier.remote(release_on=2)
+
+ class LongStartingServable:
+ def __init__(self):
+ ray.get(barrier.wait.remote(), timeout=10)
+
+ def __call__(self, _):
+ return "Ready"
+
+ serve.create_endpoint("test-parallel")
+ serve.create_backend(
+ "p:v0", LongStartingServable, config={"num_replicas": 2})
+ serve.set_traffic("test-parallel", {"p:v0": 1})
+ handle = serve.get_handle("test-parallel")
+
+ ray.get(handle.remote(), timeout=10) | [Serve] Start Replicas in Parallel (#<I>) | ray-project_ray | train |
130290a8f28e85eeb7ac07eb579d139602505aba | diff --git a/forms/TreeDropdownField.php b/forms/TreeDropdownField.php
index <HASH>..<HASH> 100755
--- a/forms/TreeDropdownField.php
+++ b/forms/TreeDropdownField.php
@@ -113,7 +113,7 @@ class TreeDropdownField extends FormField {
array (
'id' => "TreeDropdownField_{$this->id()}",
'class' => 'TreeDropdownField single' . ($this->extraClass() ? " {$this->extraClass()}" : ''),
- 'href' => $this->Link(),
+ 'href' => $this->form ? $this->Link() : "",
),
$this->createTag (
'input',
diff --git a/javascript/TreeSelectorField.js b/javascript/TreeSelectorField.js
index <HASH>..<HASH> 100755
--- a/javascript/TreeSelectorField.js
+++ b/javascript/TreeSelectorField.js
@@ -60,6 +60,7 @@ TreeDropdownField.prototype = {
// Build a URL from the field's base URL and the given sub URL
buildURL: function(subURL) {
var baseURL = jQuery(this).attr('href');
+ if (!baseURL) baseURL = this.ownerForm().action + '/field/' + this.getName() + '/';
var subHasQuerystring = subURL.match(/\?/);
if(baseURL.match(/^(.*)\?(.*)$/)) { | BUGFIX: fallback for changes in r<I>, required if TreeDropdownField is used in a widgetarea, and does not know its field
git-svn-id: svn://svn.silverstripe.com/silverstripe/open/modules/sapphire/branches/<I>@<I> <I>b<I>ca-7a2a-<I>-9d3b-<I>d<I>a<I>a9 | silverstripe_silverstripe-framework | train |
93f5a16f0e3aef4facb645cabf5f8932b256c2f3 | diff --git a/pmagpy/ipmag.py b/pmagpy/ipmag.py
index <HASH>..<HASH> 100755
--- a/pmagpy/ipmag.py
+++ b/pmagpy/ipmag.py
@@ -812,6 +812,9 @@ def inc_from_lat(lat):
return inc
+
+
+
def plot_net(fignum):
"""
Draws circle and tick marks for equal area projection.
@@ -866,7 +869,10 @@ def plot_net(fignum):
plt.axis((-1.05,1.05,-1.05,1.05))
-def plot_di(dec=None, inc=None, di_block=None, color='k', marker='o', markersize=20, legend='no', label=''):
+def plot_XY(X=None, Y=None,sym='ro'):
+ plt.plot(X,Y,sym)
+
+def plot_di(dec=None, inc=None, di_block=None, color='k', marker='o', markersize=20, legend='no', label='',title=''):
"""
Plot declination, inclination data on an equal area plot.
@@ -931,6 +937,8 @@ def plot_di(dec=None, inc=None, di_block=None, color='k', marker='o', markersize
if legend=='yes':
plt.legend(loc=2)
plt.tight_layout()
+ if title!="":
+ plt.title(title)
def plot_di_mean(dec,inc,a95,color='k',marker='o',markersize=20,label='',legend='no'): | modified: ipmag.py => added plot_XY to ipmag and title to plot_di function | PmagPy_PmagPy | train |
22f6c4611ec34d9b2781b1d7e761a91ec598acb3 | diff --git a/src/GenomeTrack.js b/src/GenomeTrack.js
index <HASH>..<HASH> 100644
--- a/src/GenomeTrack.js
+++ b/src/GenomeTrack.js
@@ -41,6 +41,12 @@ var NonEmptyGenomeTrack = React.createClass({
basePairs: React.PropTypes.object.isRequired,
onRangeChange: React.PropTypes.func.isRequired
},
+ getInitialState: function() {
+ return {
+ width: 0,
+ height: 0
+ };
+ },
render: function(): any {
return <div className="reference"></div>;
},
@@ -49,6 +55,11 @@ var NonEmptyGenomeTrack = React.createClass({
svg = d3.select(div)
.append('svg');
+ this.setState({
+ width: div.offsetWidth,
+ height: div.offsetHeight
+ });
+
var originalRange, originalScale, dx=0;
var dragstarted = () => {
d3.event.sourceEvent.stopPropagation();
@@ -109,17 +120,21 @@ var NonEmptyGenomeTrack = React.createClass({
// For now, just basePairs and range.
var newProps = this.props;
if (!_.isEqual(newProps.basePairs, prevProps.basePairs) ||
- !_.isEqual(newProps.range, prevProps.range)) {
+ !_.isEqual(newProps.range, prevProps.range) ||
+ this.state != prevState) {
this.updateVisualization();
}
},
updateVisualization: function() {
var div = this.getDOMNode(),
range = this.props.range,
- width = div.offsetWidth,
- height = div.offsetHeight,
+ width = this.state.width,
+ height = this.state.height,
svg = d3.select(div).select('svg');
+ // Hold off until height & width are known.
+ if (width === 0) return;
+
var scale = this.getScale();
var pxPerLetter = scale(1) - scale(0); | cache width/height in GenomeTrack | hammerlab_pileup.js | train |
f07dc13e80b54762453e5cb58175bf07078a950b | diff --git a/jbpm-services/jbpm-kie-services/src/main/java/org/jbpm/kie/services/impl/store/DeploymentSynchronizer.java b/jbpm-services/jbpm-kie-services/src/main/java/org/jbpm/kie/services/impl/store/DeploymentSynchronizer.java
index <HASH>..<HASH> 100644
--- a/jbpm-services/jbpm-kie-services/src/main/java/org/jbpm/kie/services/impl/store/DeploymentSynchronizer.java
+++ b/jbpm-services/jbpm-kie-services/src/main/java/org/jbpm/kie/services/impl/store/DeploymentSynchronizer.java
@@ -33,21 +33,21 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class DeploymentSynchronizer implements DeploymentEventListener {
-
+
private static final Logger logger = LoggerFactory.getLogger(DeploymentSynchronizer.class);
-
+
public static final String DEPLOY_SYNC_INTERVAL = System.getProperty("org.jbpm.deploy.sync.int", "3");
public static final boolean DEPLOY_SYNC_ENABLED = Boolean.parseBoolean(System.getProperty("org.jbpm.deploy.sync.enabled", "true"));
-
+
private final Map<String, DeploymentUnit> entries = new ConcurrentHashMap<String, DeploymentUnit>();
-
+
private DeploymentStore deploymentStore;
private DeploymentService deploymentService;
-
+
private Date lastSync = null;
-
+
protected Class<?> targetExceptionClass;
-
+
public DeploymentSynchronizer() {
String clazz = System.getProperty("org.kie.constviol.exclass", "org.hibernate.exception.ConstraintViolationException");
try {
@@ -56,11 +56,11 @@ public class DeploymentSynchronizer implements DeploymentEventListener {
logger.error("Optimistic locking exception class not found {}", clazz, e);
}
}
-
+
public boolean isActive() {
return true;
}
-
+
public void setDeploymentStore(DeploymentStore deploymentStore) {
this.deploymentStore = deploymentStore;
@@ -84,7 +84,7 @@ public class DeploymentSynchronizer implements DeploymentEventListener {
} else {
deploymentStore.getDeploymentUnitsByDate(lastSync, enabledSet, disabledSet, activatedSet, deactivatedSet);
}
-
+
logger.debug("About to synchronize deployment units, found new enabled {}, found new disabled {}", enabledSet, disabledSet);
if (enabledSet != null) {
for (DeploymentUnit unit : enabledSet) {
@@ -95,12 +95,12 @@ public class DeploymentSynchronizer implements DeploymentEventListener {
deploymentService.deploy(unit);
} catch (Exception e) {
entries.remove(unit.getIdentifier());
- logger.warn("Deployment unit {} failed to deploy: {}", unit.getIdentifier(), e.getMessage());
+ logger.warn("Deployment unit {} failed to deploy: {}", unit.getIdentifier(), e.getMessage());
}
}
}
}
-
+
if (disabledSet != null) {
for (DeploymentUnit unit : disabledSet) {
if (entries.containsKey(unit.getIdentifier()) && deploymentService.getDeployedUnit(unit.getIdentifier()) != null) {
@@ -116,7 +116,7 @@ public class DeploymentSynchronizer implements DeploymentEventListener {
}
}
}
-
+
logger.debug("About to synchronize deployment units, found new activated {}, found new deactivated {}", activatedSet, deactivatedSet);
if (activatedSet != null) {
for (DeploymentUnit unit : activatedSet) {
@@ -126,7 +126,7 @@ public class DeploymentSynchronizer implements DeploymentEventListener {
}
}
}
-
+
if (deactivatedSet != null) {
for (DeploymentUnit unit : deactivatedSet) {
DeployedUnit deployed = deploymentService.getDeployedUnit(unit.getIdentifier());
@@ -141,7 +141,7 @@ public class DeploymentSynchronizer implements DeploymentEventListener {
// update last sync date
this.lastSync = new Date();
}
-
+
@Override
public void onDeploy(DeploymentEvent event) {
if (event == null || event.getDeployedUnit() == null) {
@@ -149,7 +149,7 @@ public class DeploymentSynchronizer implements DeploymentEventListener {
}
DeploymentUnit unit = event.getDeployedUnit().getDeploymentUnit();
if (!entries.containsKey(unit.getIdentifier())) {
-
+
try {
deploymentStore.enableDeploymentUnit(unit);
// when successfully stored add it to local store
@@ -159,11 +159,11 @@ public class DeploymentSynchronizer implements DeploymentEventListener {
if (isCausedByConstraintViolation(e)) {
logger.info("Deployment {} already stored in deployment store", unit);
} else {
- logger.error("Unable to store deployment {} in deployment store due to {}", e.getMessage());
+ logger.error("Unable to store deployment {} in deployment store due to {}", unit, e.getMessage());
}
}
}
-
+
}
@Override
@@ -184,7 +184,7 @@ public class DeploymentSynchronizer implements DeploymentEventListener {
deploymentStore.activateDeploymentUnit(unit);
logger.info("Deployment unit {} activated successfully", unit.getIdentifier());
}
-
+
}
@@ -195,9 +195,9 @@ public class DeploymentSynchronizer implements DeploymentEventListener {
deploymentStore.deactivateDeploymentUnit(unit);
logger.info("Deployment unit {} deactivated successfully", unit.getIdentifier());
}
-
+
}
-
+
protected boolean isCausedByConstraintViolation(Throwable throwable) {
if (targetExceptionClass == null) {
return false;
@@ -214,5 +214,5 @@ public class DeploymentSynchronizer implements DeploymentEventListener {
return false;
}
-
+
} | BZ-<I> - BPM cluster fails to create deployment of asset-mgmt project - fixed log statement | kiegroup_jbpm | train |
66fb9938a23d0742ad082aa7752057b804b72d5e | diff --git a/libraries/joomla/database/driver/mysql.php b/libraries/joomla/database/driver/mysql.php
index <HASH>..<HASH> 100644
--- a/libraries/joomla/database/driver/mysql.php
+++ b/libraries/joomla/database/driver/mysql.php
@@ -251,11 +251,13 @@ class JDatabaseDriverMysql extends JDatabaseDriverMysqli
$sql .= ' LIMIT ' . $this->offset . ', ' . $this->limit;
}
+ // Increment the query counter.
+ $this->count++;
+
// If debugging is enabled then let's log the query.
if ($this->debug)
{
- // Increment the query counter and add the query to the object queue.
- $this->count++;
+ // Add the query to the object queue.
$this->log[] = $sql;
JLog::add($sql, JLog::DEBUG, 'databasequery');
diff --git a/libraries/joomla/database/driver/mysqli.php b/libraries/joomla/database/driver/mysqli.php
index <HASH>..<HASH> 100644
--- a/libraries/joomla/database/driver/mysqli.php
+++ b/libraries/joomla/database/driver/mysqli.php
@@ -482,11 +482,13 @@ class JDatabaseDriverMysqli extends JDatabaseDriver
$sql .= ' LIMIT ' . $this->offset . ', ' . $this->limit;
}
+ // Increment the query counter.
+ $this->count++;
+
// If debugging is enabled then let's log the query.
if ($this->debug)
{
- // Increment the query counter and add the query to the object queue.
- $this->count++;
+ // Add the query to the object queue.
$this->log[] = $sql;
JLog::add($sql, JLog::DEBUG, 'databasequery');
diff --git a/libraries/joomla/database/driver/pdo.php b/libraries/joomla/database/driver/pdo.php
index <HASH>..<HASH> 100644
--- a/libraries/joomla/database/driver/pdo.php
+++ b/libraries/joomla/database/driver/pdo.php
@@ -373,11 +373,13 @@ abstract class JDatabaseDriverPdo extends JDatabaseDriver
$sql .= ' LIMIT ' . $this->offset . ', ' . $this->limit;
}
+ // Increment the query counter.
+ $this->count++;
+
// If debugging is enabled then let's log the query.
if ($this->debug)
{
- // Increment the query counter and add the query to the object queue.
- $this->count++;
+ // Add the query to the object queue.
$this->log[] = $sql;
JLog::add($sql, JLog::DEBUG, 'databasequery');
diff --git a/libraries/joomla/database/driver/postgresql.php b/libraries/joomla/database/driver/postgresql.php
index <HASH>..<HASH> 100644
--- a/libraries/joomla/database/driver/postgresql.php
+++ b/libraries/joomla/database/driver/postgresql.php
@@ -621,11 +621,13 @@ class JDatabaseDriverPostgresql extends JDatabaseDriver
$sql .= ' LIMIT ' . $this->limit . ' OFFSET ' . $this->offset;
}
+ // Increment the query counter.
+ $this->count++;
+
// If debugging is enabled then let's log the query.
if ($this->debug)
{
- // Increment the query counter and add the query to the object queue.
- $this->count++;
+ // Add the query to the object queue.
$this->log[] = $sql;
JLog::add($sql, JLog::DEBUG, 'databasequery');
@@ -790,7 +792,7 @@ class JDatabaseDriverPostgresql extends JDatabaseDriver
* @param array $columns Array of table's column returned by ::getTableColumns.
* @param string $field_name The table field's name.
* @param string $field_value The variable value to quote and return.
- *
+ *
* @return string The quoted string.
*
* @since 11.3
diff --git a/libraries/joomla/database/driver/sqlsrv.php b/libraries/joomla/database/driver/sqlsrv.php
index <HASH>..<HASH> 100644
--- a/libraries/joomla/database/driver/sqlsrv.php
+++ b/libraries/joomla/database/driver/sqlsrv.php
@@ -566,12 +566,13 @@ class JDatabaseDriverSqlsrv extends JDatabaseDriver
$sql = $this->limit($sql, $this->limit, $this->offset);
}
+ // Increment the query counter.
+ $this->count++;
+
// If debugging is enabled then let's log the query.
if ($this->debug)
{
-
- // Increment the query counter and add the query to the object queue.
- $this->count++;
+ // Add the query to the object queue.
$this->log[] = $sql;
JLog::add($sql, JLog::DEBUG, 'databasequery'); | Move db query count out of debugging conditional. | joomla_joomla-framework | train |
74f9a9ec5208caae9f84c6b1b3339f1cb4a03fa9 | diff --git a/src/errors.js b/src/errors.js
index <HASH>..<HASH> 100644
--- a/src/errors.js
+++ b/src/errors.js
@@ -8,10 +8,12 @@ const BusinessError = MostlyError.subclass('BusinessError');
const FeathersError = MostlyError.subclass('FeathersError');
const FatalError = MostlyError.subclass('FatalError');
const PatternNotFound = MostlyError.subclass('PatternNotFound');
-const PayloadValidationError = SuperError.subclass('PayloadValidationError');
+const MaxRecursionError = MostlyError.subclass('MaxRecursionError');
+const PayloadValidationError = MostlyError.subclass('PayloadValidationError');
module.exports = {
MostlyError,
+ MaxRecursionError,
ParseError,
TimeoutError,
ImplementationError,
diff --git a/src/extensions.js b/src/extensions.js
index <HASH>..<HASH> 100644
--- a/src/extensions.js
+++ b/src/extensions.js
@@ -1,5 +1,6 @@
import Constants from './constants';
import Util from './util';
+const Errors = require('./errors');
module.exports.onClientPreRequest = [function onClientPreRequest (next) {
let ctx = this;
@@ -26,6 +27,23 @@ module.exports.onClientPreRequest = [function onClientPreRequest (next) {
ctx.trace$.timestamp = currentTime;
ctx.trace$.service = pattern.topic;
ctx.trace$.method = Util.pattern(pattern);
+
+ // detect recursion
+ if (this._config.maxRecursion > 1) {
+ const callSignature = `${ctx.trace$.traceId}:${ctx.trace$.method}`;
+ if (ctx.meta$ && ctx.meta$.referrers) {
+ let count = ctx.meta$.referrers[callSignature];
+ count += 1;
+ ctx.meta$.referrers[callSignature] = count;
+ if (count > this._config.maxRecursion) {
+ ctx.meta$.referrers[callSignature] = 0;
+ return next(new Errors.MaxRecursionError({ count: --count }));
+ }
+ } else {
+ ctx.meta$.referrers = {};
+ ctx.meta$.referrers[callSignature] = 1;
+ }
+ }
// request
let request = {
diff --git a/src/index.js b/src/index.js
index <HASH>..<HASH> 100644
--- a/src/index.js
+++ b/src/index.js
@@ -34,6 +34,7 @@ const defaultConfig = {
name: 'mostly-' + Util.randomId(),
crashOnFatal: true,
logLevel: 'silent',
+ maxRecursion: 0,
bloomrun: {
indexing: 'inserting',
lookupBeforeAdd: true
@@ -552,7 +553,8 @@ export default class MostlyCore extends EventEmitter {
if (err) {
debug('actionHandler:error', err);
const errorDetails = {
- pattern: self._actMeta.pattern,
+ service: self.trace$.service,
+ method: self._actMeta.method,
app: self._config.name,
ts: Util.nowHrTime()
}; | detect recursion and abort | MostlyJS_mostly-node | train |
54a85fa96a35dc099b469aeb0cead58b4c61cd21 | diff --git a/registry/registry.go b/registry/registry.go
index <HASH>..<HASH> 100644
--- a/registry/registry.go
+++ b/registry/registry.go
@@ -61,11 +61,15 @@ func NewCache() *Cache {
}
func typeFromConfig(config map[string]interface{}) (string, error) {
- typ, ok := config["type"].(string)
- if ok {
- return typ, nil
+ prop, ok := config["type"]
+ if !ok {
+ return "", fmt.Errorf("'type' property is not defined")
}
- return "", fmt.Errorf("unable to determine type")
+ typ, ok := prop.(string)
+ if !ok {
+ return "", fmt.Errorf("'type' property must be a string, not %T", prop)
+ }
+ return typ, nil
}
func (c *Cache) CharFilterNamed(name string) (analysis.CharFilter, error) {
@@ -87,7 +91,7 @@ func (c *Cache) TokenizerNamed(name string) (analysis.Tokenizer, error) {
func (c *Cache) DefineTokenizer(name string, config map[string]interface{}) (analysis.Tokenizer, error) {
typ, err := typeFromConfig(config)
if err != nil {
- return nil, err
+ return nil, fmt.Errorf("cannot resolve '%s' tokenizer type: %s", name, err)
}
return c.Tokenizers.DefineTokenizer(name, typ, config, c)
} | registry: improve error message upon forgotten "type" property
Registering a custom tokenizer while forgetting its "type" used to
return:
error: unable to determine type
It now says:
error: cannot resolve 'foo' tokenizer type: 'type' property is not defined | blevesearch_bleve | train |
027e81c534e10b08e3d460f012b14c212841326c | diff --git a/issuing_authorization.go b/issuing_authorization.go
index <HASH>..<HASH> 100644
--- a/issuing_authorization.go
+++ b/issuing_authorization.go
@@ -51,6 +51,16 @@ const (
IssuingAuthorizationVerificationDataCheckNotProvided IssuingAuthorizationVerificationDataCheck = "not_provided"
)
+// IssuingAuthorizationWalletProviderType is the list of possible values for the authorization's wallet provider.
+type IssuingAuthorizationWalletProviderType string
+
+// List of values that IssuingAuthorizationWalletProviderType can take.
+const (
+ IssuingAuthorizationWalletProviderTypeApplePay IssuingAuthorizationWalletProviderType = "apple_pay"
+ IssuingAuthorizationWalletProviderTypeGooglePay IssuingAuthorizationWalletProviderType = "google_pay"
+ IssuingAuthorizationWalletProviderTypeSamsungPay IssuingAuthorizationWalletProviderType = "samsung_pay"
+)
+
// IssuingAuthorizationParams is the set of parameters that can be used when updating an issuing authorization.
type IssuingAuthorizationParams struct {
Params `form:"*"`
@@ -117,6 +127,7 @@ type IssuingAuthorization struct {
Status IssuingAuthorizationStatus `json:"status"`
Transactions []*IssuingTransaction `json:"transactions"`
VerificationData *IssuingAuthorizationVerificationData `json:"verification_data"`
+ WalletProvider IssuingAuthorizationWalletProviderType `json:"wallet_provider"`
}
// IssuingMerchantData is the resource representing merchant data on Issuing APIs. | Add support for `wallet_provider` on the Issuing Authorization | stripe_stripe-go | train |
f1d873a0102a6a8596db534197a96a196857fab7 | diff --git a/django_payzen/views.py b/django_payzen/views.py
index <HASH>..<HASH> 100644
--- a/django_payzen/views.py
+++ b/django_payzen/views.py
@@ -47,6 +47,7 @@ class ResponseView(generic.View):
.format(response.vads_trans_id))
else:
signals.response_error.send(sender=self.__class__)
- logger.error("Django-Payzen : Response could not be saved - {}"
- .format(form.errors), extra={"stack": True})
+ logger.error("Django-Payzen : Response could not be saved - {} {}"
+ .format(form.errors, request.POST),
+ extra={"stack": True})
return http.HttpResponse() | views | added more info in logs in case of failure. | bsvetchine_django-payzen | train |
6e4fd09490efd625760bfb4c2be1dc8710951c52 | diff --git a/sentry/client/base.py b/sentry/client/base.py
index <HASH>..<HASH> 100644
--- a/sentry/client/base.py
+++ b/sentry/client/base.py
@@ -37,9 +37,15 @@ class SentryClient(object):
if request:
if not kwargs.get('data'):
kwargs['data'] = {}
+
+ if not request.POST and request.raw_post_data:
+ post_data = request.raw_post_data
+ else:
+ post_data = request.POST
+
kwargs['data'].update(dict(
META=request.META,
- POST=request.POST,
+ POST=post_data,
GET=request.GET,
COOKIES=request.COOKIES,
))
diff --git a/sentry/reporter.py b/sentry/reporter.py
index <HASH>..<HASH> 100644
--- a/sentry/reporter.py
+++ b/sentry/reporter.py
@@ -83,6 +83,7 @@ class FakeRequest(object):
META = {}
COOKIES = {}
FILES = {}
+ raw_post_data = ''
url = ''
def __repr__(self):
diff --git a/sentry/tests/tests.py b/sentry/tests/tests.py
index <HASH>..<HASH> 100644
--- a/sentry/tests/tests.py
+++ b/sentry/tests/tests.py
@@ -14,7 +14,7 @@ import threading
from django.conf import settings
from django.contrib.auth.models import User
from django.core import mail
-from django.core.handlers.wsgi import WSGIRequest, WSGIHandler
+from django.core.handlers.wsgi import WSGIHandler
from django.core.management import call_command
from django.core.urlresolvers import reverse
from django.core.signals import got_request_exception
@@ -705,6 +705,31 @@ class SentryTestCase(TestCase):
self.assertTrue('baz' in last.data)
self.assertEquals(last.data['baz'], 'bar')
+ def testRawPostData(self):
+ from sentry.reporter import FakeRequest
+
+ request = FakeRequest()
+ request.raw_post_data = '{"json": "string"}'
+
+ logger = logging.getLogger()
+
+ self.setUpHandler()
+
+ logger.error('This is a test %s', 'error', extra={
+ 'request': request,
+ 'data': {
+ 'baz': 'bar',
+ }
+ })
+ self.assertEquals(Message.objects.count(), 1)
+ self.assertEquals(GroupedMessage.objects.count(), 1)
+ last = Message.objects.get()
+ self.assertEquals(last.logger, 'root')
+ self.assertEquals(last.level, logging.ERROR)
+ self.assertEquals(last.message, 'This is a test error')
+ self.assertTrue('POST' in last.data)
+ self.assertEquals(request.raw_post_data, last.data['POST'])
+
class SentryViewsTest(TestCase):
urls = 'sentry.tests.urls'
fixtures = ['sentry/tests/fixtures/views.json'] | Support raw_post_data when request.POST is empty | elastic_apm-agent-python | train |
Subsets and Splits