hash
stringlengths 40
40
| diff
stringlengths 131
114k
| message
stringlengths 7
980
| project
stringlengths 5
67
| split
stringclasses 1
value |
|---|---|---|---|---|
969ac53448f0c968ba200dabca2dcbbc565f1b32
|
diff --git a/lib/vcr/http_stubbing_adapters/webmock.rb b/lib/vcr/http_stubbing_adapters/webmock.rb
index <HASH>..<HASH> 100644
--- a/lib/vcr/http_stubbing_adapters/webmock.rb
+++ b/lib/vcr/http_stubbing_adapters/webmock.rb
@@ -86,8 +86,3 @@ if defined?(WebMock::NetConnectNotAllowedError)
end
end
end
-
-# TODO: remove this once a new version of WebMock has been released with this fixed.
-if defined?(HTTPClient) && !defined?(HTTPClient::NetConnectNotAllowedError)
- HTTPClient::NetConnectNotAllowedError = WebMock::NetConnectNotAllowedError
-end
|
Removed webmock work around that is no longer necessary.
|
vcr_vcr
|
train
|
44dca82943cb7649c061a0bd255456e9c184e7a0
|
diff --git a/lib/cantango/configuration.rb b/lib/cantango/configuration.rb
index <HASH>..<HASH> 100644
--- a/lib/cantango/configuration.rb
+++ b/lib/cantango/configuration.rb
@@ -17,26 +17,8 @@ module CanTango
attr_accessor :user_key_field
attr_accessor :user_accounts, :users
- attr_reader :guest_user_procedure, :guest_account_procedure
-
- def guest_user procedure
- raise ArgumentError, "Argument must be a Proc or lambda" if !procedure.respond_to? :call
- @guest_user_procedure = procedure
- end
-
- def guest_account procedure
- raise ArgumentError, "Argument must be a Proc or lambda" if !procedure.respond_to? :call
- @guest_account_procedure = procedure
- end
-
- def config_path
- @config_path ||= File.join(::Rails.root.to_s, 'config') if rails?
- @config_path or raise "Define path to config files dir!\n"
- end
-
- def config_path= path
- raise "Must be a valid path to permission yaml file, was: #{path}" if !dir?(path)
- @config_path = path
+ def guest
+ Guest.instance
end
def engines
@@ -47,8 +29,8 @@ module CanTango
Autoload.instance
end
- def default_store_type
- @default_store_type || :redis
+ def user
+ User.instance
end
def default_cache_type
diff --git a/lib/cantango/configuration/engines/cache.rb b/lib/cantango/configuration/engines/cache.rb
index <HASH>..<HASH> 100644
--- a/lib/cantango/configuration/engines/cache.rb
+++ b/lib/cantango/configuration/engines/cache.rb
@@ -11,6 +11,8 @@ module CanTango
end
class Store
+ attr_writer :default_type
+
def default_type
@default_type || :memory
end
diff --git a/lib/cantango/configuration/engines/permission.rb b/lib/cantango/configuration/engines/permission.rb
index <HASH>..<HASH> 100644
--- a/lib/cantango/configuration/engines/permission.rb
+++ b/lib/cantango/configuration/engines/permission.rb
@@ -15,9 +15,18 @@ module CanTango
end
def config_path
+ @config_path ||= File.join(::Rails.root.to_s, 'config') if rails?
+ @config_path or raise "Define path to config files dir!\n"
+ end
+
+ def config_path= path
+ raise "Must be a valid path to permission yaml file, was: #{path}" if !dir?(path)
+ @config_path = path
end
class Store
+ attr_writer :default_type
+
def default_type
@default_type || :memory
end
diff --git a/lib/cantango/configuration/guest.rb b/lib/cantango/configuration/guest.rb
index <HASH>..<HASH> 100644
--- a/lib/cantango/configuration/guest.rb
+++ b/lib/cantango/configuration/guest.rb
@@ -2,6 +2,18 @@ module CanTango
class Configuration
class Guest
include Singleton
+
+ attr_reader :user_procedure, :account_procedure
+
+ def user procedure
+ raise ArgumentError, "Argument must be a Proc or lambda" if !procedure.respond_to? :call
+ @user_procedure = procedure
+ end
+
+ def account procedure
+ raise ArgumentError, "Argument must be a Proc or lambda" if !procedure.respond_to? :call
+ @account_procedure = procedure
+ end
end
end
end
|
more refactoring of config - no guest and user
|
kristianmandrup_cantango
|
train
|
add89926de6d2df623ec3e0f918797ca2e7d222d
|
diff --git a/upload/system/library/cart/tax.php b/upload/system/library/cart/tax.php
index <HASH>..<HASH> 100644
--- a/upload/system/library/cart/tax.php
+++ b/upload/system/library/cart/tax.php
@@ -8,7 +8,7 @@ class Tax {
$this->db = $registry->get('db');
}
- public function setShippingAddress(int $country_id, int $zone_id) {
+ public function setShippingAddress(int $country_id, int $zone_id): void {
$tax_query = $this->db->query("SELECT tr1.`tax_class_id`, tr2.`tax_rate_id`, tr2.`name`, tr2.`rate`, tr2.`type`, tr1.`priority` FROM `" . DB_PREFIX . "tax_rule` tr1 LEFT JOIN `" . DB_PREFIX . "tax_rate` tr2 ON (tr1.`tax_rate_id` = tr2.`tax_rate_id`) INNER JOIN `" . DB_PREFIX . "tax_rate_to_customer_group` tr2cg ON (tr2.`tax_rate_id` = tr2cg.`tax_rate_id`) LEFT JOIN `" . DB_PREFIX . "zone_to_geo_zone` z2gz ON (tr2.`geo_zone_id` = z2gz.`geo_zone_id`) LEFT JOIN `" . DB_PREFIX . "geo_zone` gz ON (tr2.`geo_zone_id` = gz.`geo_zone_id`) WHERE tr1.`based` = 'shipping' AND tr2cg.`customer_group_id` = '" . (int)$this->config->get('config_customer_group_id') . "' AND z2gz.`country_id` = '" . (int)$country_id . "' AND (z2gz.`zone_id` = '0' OR z2gz.`zone_id` = '" . (int)$zone_id . "') ORDER BY tr1.`priority` ASC");
foreach ($tax_query->rows as $result) {
|
[Master] Added void on setShippingAddress() method
|
opencart_opencart
|
train
|
38332618868f34e7628a0b8c668c7ce06406d99b
|
diff --git a/etc/reset.py b/etc/reset.py
index <HASH>..<HASH> 100755
--- a/etc/reset.py
+++ b/etc/reset.py
@@ -115,27 +115,30 @@ def parse_log_level(s):
except KeyError:
raise Exception("Unknown log level: {}".format(s))
-def redirect_to_logger(stdout, stderr):
- for io in select.select([stdout.pipe, stderr.pipe], [], [], 5000)[0]:
- line = io.readline().decode().rstrip()
-
- if line == "":
- continue
-
- dest = stdout if io == stdout.pipe else stderr
- log.log(LOG_LEVELS[dest.level], "{}{}\x1b[0m".format(LOG_COLORS.get(dest.level, ""), line))
- dest.lines.append(line)
-
def run(cmd, *args, raise_on_error=True, shell=False, stdout_log_level="info", stderr_log_level="error"):
log.debug("Running `%s %s`", cmd, " ".join(args))
proc = subprocess.Popen([cmd, *args], shell=shell, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdout = Output(proc.stdout, stdout_log_level)
stderr = Output(proc.stderr, stderr_log_level)
+ timed_out_last = False
+
+ while True:
+ if (proc.poll() is not None and timed_out_last) or (stdout.pipe.closed and stderr.pipe.closed):
+ break
- while proc.poll() is None:
- redirect_to_logger(stdout, stderr)
- redirect_to_logger(stdout, stderr)
+ for io in select.select([stdout.pipe, stderr.pipe], [], [], 100)[0]:
+ timed_out_last = False
+ line = io.readline().decode().rstrip()
+
+ if line == "":
+ continue
+
+ dest = stdout if io == stdout.pipe else stderr
+ log.log(LOG_LEVELS[dest.level], "{}{}\x1b[0m".format(LOG_COLORS.get(dest.level, ""), line))
+ dest.lines.append(line)
+ else:
+ timed_out_last = True
rc = proc.wait()
|
More resilient dumping of stdout/stderr
|
pachyderm_pachyderm
|
train
|
1e884c33a2ba07646f1ec553755fb22c542a9ff9
|
diff --git a/psdash/run.py b/psdash/run.py
index <HASH>..<HASH> 100644
--- a/psdash/run.py
+++ b/psdash/run.py
@@ -271,6 +271,7 @@ class PsDashRunner(object):
'certfile': self.app.config.get('PSDASH_HTTPS_CERTFILE')
}
+ self.app.config['SERVER_NAME'] = '%s:%s' % (self.app.config['PSDASH_BIND_HOST'], self.app.config['PSDASH_PORT'])
self.server = WSGIServer(
(self.app.config['PSDASH_BIND_HOST'], self.app.config['PSDASH_PORT']),
application=self.app,
|
Trying to fix failing tests in Travis CI.
|
Jahaja_psdash
|
train
|
014ef2c0327b72c3a76b5a77d8db2ec4d39a6d13
|
diff --git a/index.js b/index.js
index <HASH>..<HASH> 100644
--- a/index.js
+++ b/index.js
@@ -37,7 +37,7 @@ var modulesLoadedBeforeTrace = [];
for (var i = 0; i < filesLoadedBeforeTrace.length; i++) {
var moduleName = traceUtil.packageNameFromPath(filesLoadedBeforeTrace[i]);
- if (moduleName && moduleName !== 'vxx' &&
+ if (moduleName && moduleName !== '@pm2/legacy-tracing' &&
modulesLoadedBeforeTrace.indexOf(moduleName) === -1) {
modulesLoadedBeforeTrace.push(moduleName);
}
diff --git a/src/trace-plugin-loader.js b/src/trace-plugin-loader.js
index <HASH>..<HASH> 100644
--- a/src/trace-plugin-loader.js
+++ b/src/trace-plugin-loader.js
@@ -48,7 +48,7 @@ function checkLoadedModules() {
}
if (process._preload_modules && process._preload_modules.length > 0) {
var first = process._preload_modules[0];
- if (first !== 'vxx') {
+ if (first !== '@pm2/legacy-tracing') {
logger.error('Tracing might not work as ' + first +
' was loaded with --require before the trace agent was initialized.');
}
|
chore: do not log when this module is required before itself
|
keymetrics_trassingue
|
train
|
b581490f478eae18a60e2ff11f9e85ee9bfbe59f
|
diff --git a/graw.go b/graw.go
index <HASH>..<HASH> 100644
--- a/graw.go
+++ b/graw.go
@@ -1,6 +1,8 @@
package graw
import (
+ "log"
+ "os"
"time"
"github.com/turnage/graw/internal/client"
@@ -63,6 +65,7 @@ func Run(c Config, bot interface{}) error {
engine.Config{
Dispatchers: dispatchers,
Rate: rateLimit(c.Rate, loggedIn),
+ Logger: log.New(os.Stderr, "", log.LstdFlags),
},
).Run()
}
diff --git a/internal/engine/engine.go b/internal/engine/engine.go
index <HASH>..<HASH> 100644
--- a/internal/engine/engine.go
+++ b/internal/engine/engine.go
@@ -2,8 +2,10 @@
package engine
import (
+ "log"
"time"
+ "github.com/turnage/graw/internal/client"
"github.com/turnage/graw/internal/dispatcher"
)
@@ -13,6 +15,8 @@ type Config struct {
Dispatchers []dispatcher.Dispatcher
// Rate limits the rate at which dispatchers run.
Rate <-chan time.Time
+ // Logger logs events and errors.
+ Logger *log.Logger
}
// Engine controls disptachers.
@@ -26,17 +30,19 @@ type Engine interface {
}
type engine struct {
- ds []dispatcher.Dispatcher
- rate <-chan time.Time
- stop chan bool
+ logger *log.Logger
+ ds []dispatcher.Dispatcher
+ rate <-chan time.Time
+ stop chan bool
}
// New returns an Engine implementation.
func New(c Config) Engine {
return &engine{
- ds: c.Dispatchers,
- rate: c.Rate,
- stop: make(chan bool, 100),
+ logger: c.Logger,
+ ds: c.Dispatchers,
+ rate: c.Rate,
+ stop: make(chan bool, 100),
}
}
@@ -55,7 +61,14 @@ func (e *engine) Run() error {
if len(e.ds) == 0 {
break
}
- if err := e.ds[i()].Dispatch(); err != nil {
+ err := e.ds[i()].Dispatch()
+ switch err {
+ case client.BusyErr:
+ e.logger.Printf("503: Busy from Reddit; ignoring")
+ case client.GatewayErr:
+ e.logger.Printf("502: Bad Gateway from Reddit; ignoring")
+ case nil:
+ default:
return err
}
case <-e.stop:
|
Hook engine up with a logger and log errors.
Former-commit-id: b<I>f<I>bd<I>f<I>a<I>b<I>b<I>f7ef7b4
|
turnage_graw
|
train
|
8224beef57010d659b17f10ce7f7b00898b9edae
|
diff --git a/raft.go b/raft.go
index <HASH>..<HASH> 100644
--- a/raft.go
+++ b/raft.go
@@ -1576,7 +1576,7 @@ func (r *Raft) setCurrentTerm(t uint64) {
// transition causes the known leader to be cleared. This means
// that leader should be set only after updating the state.
func (r *Raft) setState(state RaftState) {
- r.setLeader(nil)
+ r.setLeader("")
r.raftState.setState(state)
}
diff --git a/raft_test.go b/raft_test.go
index <HASH>..<HASH> 100644
--- a/raft_test.go
+++ b/raft_test.go
@@ -1280,10 +1280,10 @@ func TestRaft_LeaderLeaseExpire(t *testing.T) {
}
// Ensure both have cleared their leader
- if l := leader.Leader(); l != nil {
+ if l := leader.Leader(); l != "" {
t.Fatalf("bad: %v", l)
}
- if l := follower.Leader(); l != nil {
+ if l := follower.Leader(); l != "" {
t.Fatalf("bad: %v", l)
}
}
@@ -1383,7 +1383,7 @@ func TestRaft_VerifyLeader_Fail(t *testing.T) {
}
// Ensure the known leader is cleared
- if l := leader.Leader(); l != nil {
+ if l := leader.Leader(); l != "" {
t.Fatalf("bad: %v", l)
}
}
|
Fixing type issues with peer to string conversion
|
hashicorp_raft
|
train
|
7a355c8a62d52bef63c7c1fd64c32f81fc275f2a
|
diff --git a/falafel/console/__init__.py b/falafel/console/__init__.py
index <HASH>..<HASH> 100644
--- a/falafel/console/__init__.py
+++ b/falafel/console/__init__.py
@@ -118,15 +118,21 @@ def main():
logging.error("At least one plugin module must be specified.")
sys.exit(1)
+ import_failure = False
for module in args.plugin_modules:
logging.info("Loading %s", module)
try:
plugins.load(module)
except ImportError as e:
+ import_failure = True
logging.error("Invalid module: %s", module)
if "Import by filename" in e.message:
logging.error('Perhaps try adding "--" to the end of --plugin-modules arguments, e.g. "--plugin.modules my.plugins --"')
+ # Wait to exit until all module imports have been attempted
+ if import_failure:
+ sys.exit(1)
+
if args.reports:
for report in args.reports:
Formatter(args).format_results(*runner.handle_sosreport(report, args.spec_map))
|
Exit CLI after import failure and trying all imports
|
RedHatInsights_insights-core
|
train
|
6b3611586bf2577c394395e7177d5aaf121babbb
|
diff --git a/lib/import.js b/lib/import.js
index <HASH>..<HASH> 100644
--- a/lib/import.js
+++ b/lib/import.js
@@ -1,7 +1,7 @@
const fs = require('fs');
const path = require('path');
const bunyan = require('bunyan');
-const {Specifications} = require('shr-models');
+const {Specifications, MODELS_INFO} = require('shr-models');
const {Preprocessor, VERSION, GRAMMAR_VERSION} = require('./preprocessor');
const {DataElementImporter} = require('./dataElementListener');
const {ValueSetImporter} = require('./valueSetListener');
@@ -121,4 +121,4 @@ class FilesByType {
}
}
-module.exports = {importFromFilePath, importConfigFromFilePath, VERSION, GRAMMAR_VERSION, setLogger};
\ No newline at end of file
+module.exports = {importFromFilePath, importConfigFromFilePath, VERSION, GRAMMAR_VERSION, setLogger, MODELS_INFO};
|
Added support for sanity checking shr-models.
|
standardhealth_shr-text-import
|
train
|
76424f11f88d3270b751612802fea005339d55e3
|
diff --git a/scenarios/kubernetes_e2e.py b/scenarios/kubernetes_e2e.py
index <HASH>..<HASH> 100755
--- a/scenarios/kubernetes_e2e.py
+++ b/scenarios/kubernetes_e2e.py
@@ -261,9 +261,10 @@ def cluster_name(cluster, build):
"""Return or select a cluster name."""
if cluster:
return cluster
- if len(build) < 20:
- return 'e2e-%s' % build
- return 'e2e-%s' % hashlib.md5(build).hexdigest()[:10]
+ # Create a suffix based on the build number. Append a random string to it for
+ # avoiding potential conflicts across different jobs' runs (see issue #7592).
+ suffix = build if len(build) < 10 else hashlib.md5(build).hexdigest()[:10]
+ return 'e2e-%s-%s' % (suffix, os.urandom(3).encode('hex'))
# TODO(krzyzacy): Move this into kubetest
|
Append random string to cluster name to avoid conflicts b/w presubmits
|
kubernetes_test-infra
|
train
|
f62a7267c551d216297bec9f0496738b8e27dcae
|
diff --git a/History.txt b/History.txt
index <HASH>..<HASH> 100644
--- a/History.txt
+++ b/History.txt
@@ -11,6 +11,11 @@
* Nodes::Node#not factory method added for creating Nodes::Not nodes
* Added an As node
+* Deprecations
+
+ * Support for Subclasses of core classes will be removed in ARel version
+ 2.2.0
+
== 2.0.4
* Bug fixes
diff --git a/lib/arel/visitors/visitor.rb b/lib/arel/visitors/visitor.rb
index <HASH>..<HASH> 100644
--- a/lib/arel/visitors/visitor.rb
+++ b/lib/arel/visitors/visitor.rb
@@ -13,6 +13,13 @@ module Arel
def visit object
send DISPATCH[object.class], object
+ rescue NoMethodError
+ warn "visiting #{object.class} via superclass, this will be removed in arel 2.2.0" if $VERBOSE
+ superklass = object.class.ancestors.find { |klass|
+ respond_to?(DISPATCH[klass], true)
+ }
+ DISPATCH[object.class] = DISPATCH[superklass]
+ retry
end
end
end
diff --git a/test/visitors/test_to_sql.rb b/test/visitors/test_to_sql.rb
index <HASH>..<HASH> 100644
--- a/test/visitors/test_to_sql.rb
+++ b/test/visitors/test_to_sql.rb
@@ -21,6 +21,11 @@ module Arel
end
end
+ it "should visit string subclass" do
+ @visitor.accept(Class.new(String).new(":'("))
+ @visitor.accept(Class.new(Class.new(String)).new(":'("))
+ end
+
it "should visit_Class" do
@visitor.accept(DateTime).must_equal "'DateTime'"
end
|
adding deprecated support for walking ancestor trees
|
rails_rails
|
train
|
ad78f9c71a0aece1351e49f844efe54263d38a0b
|
diff --git a/git/clone.go b/git/clone.go
index <HASH>..<HASH> 100644
--- a/git/clone.go
+++ b/git/clone.go
@@ -34,7 +34,11 @@ func CloneRepos(destDir string, repos map[string]string) error {
continue
}
- cmd := exec.Command("git", "clone", "--bare", "--verbose", "--progress", "--recursive", cloneURL, repoDest)
+ cmd := exec.Command(
+ "git", "clone", "--bare", "--verbose", "--progress",
+ // Only fetch branch heads, and ignore note branches.
+ "--config", "remote.origin.fetch=+refs/heads/*:refs/heads/*",
+ cloneURL, repoDest)
// Prevent prompting
cmd.Stdin = &bytes.Buffer{}
log.Println("running:", cmd.Args)
|
Set a fetch spec for cloned repositories.
Otherwise, the repos are never updated beyond their first clone.
Change-Id: Ia<I>b<I>c<I>fe8c7f7b7accdd<I>ac<I>d<I>bb4
|
google_zoekt
|
train
|
77d3e61b09f22de181284df30111344caf79a416
|
diff --git a/src/YurunHttp/Http/Psr7/Consts/StatusCode.php b/src/YurunHttp/Http/Psr7/Consts/StatusCode.php
index <HASH>..<HASH> 100644
--- a/src/YurunHttp/Http/Psr7/Consts/StatusCode.php
+++ b/src/YurunHttp/Http/Psr7/Consts/StatusCode.php
@@ -110,7 +110,7 @@ abstract class StatusCode
self::UNSUPPORTED_MEDIA_TYPE => 'Unsupported Media Type',
self::REQUESTED_RANGE_NOT_SATISFIABLE => 'Requested range not satisfiable',
self::EXPECTATION_FAILED => 'Expectation Failed',
- self::MISDIRECTED_REQUEST => 'Unprocessable Entity',
+ self::MISDIRECTED_REQUEST => 'Misdirected Request',
self::UNPROCESSABLE_ENTITY => 'Unprocessable Entity',
self::LOCKED => 'Locked',
self::FAILED_DEPENDENCY => 'Failed Dependency',
|
Fix typo (#<I>)
|
Yurunsoft_YurunHttp
|
train
|
4c47dde9240c046e3e47512932c66d85fa9f104d
|
diff --git a/src/Core/CommandCollector.php b/src/Core/CommandCollector.php
index <HASH>..<HASH> 100644
--- a/src/Core/CommandCollector.php
+++ b/src/Core/CommandCollector.php
@@ -104,7 +104,7 @@ class CommandCollector
$consoleCommands = isset($oxideshop['console-commands']) && is_array($oxideshop['console-commands']) ?
$oxideshop['console-commands'] : [];
foreach ($consoleCommands as $commandClass) {
- print "$commandClass is defined in composer.json of module this is depricated\n";
+ print "$commandClass is defined in composer.json of module this is deprecated\n";
$commandsClasses[] = new $commandClass();
}
//end of deprecated code
@@ -197,7 +197,7 @@ class CommandCollector
$fullModulePaths = array_map(function ($modulePath) use ($modulesRootPath) {
return $modulesRootPath . $modulePath;
}, array_values($modulePaths));
-
+
return array_filter($fullModulePaths, function ($fullModulePath) {
if (! is_dir($fullModulePath)) {
return false;
|
fixed typo introduced in #<I>
|
OXIDprojects_oxid-console
|
train
|
568963fc3fe833d2c494572f704b98335c80be76
|
diff --git a/src/Responder/Redirect.php b/src/Responder/Redirect.php
index <HASH>..<HASH> 100644
--- a/src/Responder/Redirect.php
+++ b/src/Responder/Redirect.php
@@ -44,11 +44,15 @@ class Redirect extends AbstractWithViewData
* uses current hosts and scheme.
*
* @param string $path
+ * @param string $query
* @return ResponseInterface
*/
- public function toPath($path)
+ public function toPath($path, $query = '')
{
$uri = $this->request->getUri()->withPath($path);
+ if (!is_null($query)) {
+ $uri = $uri->withQuery($query);
+ }
return $this->toAbsoluteUri($uri);
}
@@ -65,7 +69,7 @@ class Redirect extends AbstractWithViewData
$path = rtrim($base, '/') . $path;
$path = rtrim($path, '/');
$uri = $this->request->getUri()->withPath($path);
- if ($query) {
+ if (!is_null($query)) {
$uri = $uri->withQuery($query);
}
|
fix bug: to clear query from the existing URI.
set $query as default, unless the $query is NULL.
|
TuumPHP_Respond
|
train
|
71a06a455ed675243e02b8666615955dcaa7e025
|
diff --git a/pythonwhat/check_funcs.py b/pythonwhat/check_funcs.py
index <HASH>..<HASH> 100644
--- a/pythonwhat/check_funcs.py
+++ b/pythonwhat/check_funcs.py
@@ -165,7 +165,7 @@ def multi(*args, state=None):
if any(args):
rep = Reporter.active_reporter
# when input is a single list of subtests
- args = args[0] if len(args) == 1 and hasattr(args[0], '__iter__') else args
+ args = args[0] if len(args) == 1 and isinstance(args[0], (list, tuple)) else args
for test in args:
# assume test is function needing a state argument
diff --git a/pythonwhat/check_wrappers.py b/pythonwhat/check_wrappers.py
index <HASH>..<HASH> 100644
--- a/pythonwhat/check_wrappers.py
+++ b/pythonwhat/check_wrappers.py
@@ -59,7 +59,7 @@ def multi_dec(f):
@wraps(f)
def wrapper(*args, **kwargs):
- args = args[0] if len(args) == 1 and hasattr(args[0], '__iter__') else args
+ args = args[0] if len(args) == 1 and isinstance(args[0], (list, tuple)) else args
for arg in args:
if isinstance(arg, Node) and arg.parent.name is 'root':
arg.parent.remove_child(arg)
@@ -83,4 +83,5 @@ for k in ['set_context', 'has_equal_value', 'extend']:
scts[k] = state_dec(getattr(check_funcs, k))
-scts['multi'] = multi_dec(state_dec((check_funcs.multi)))
+scts['multi'] = multi_dec(state_dec(check_funcs.multi))
+scts['with_context'] = multi_dec(state_dec(check_funcs.with_context))
diff --git a/tests/test_test_for_loop.py b/tests/test_test_for_loop.py
index <HASH>..<HASH> 100644
--- a/tests/test_test_for_loop.py
+++ b/tests/test_test_for_loop.py
@@ -161,9 +161,7 @@ Ex().check_for_call(0)\
.check_for_call(0)\
.check_body()\
.set_context(jj=2)\
- .multi(test_expression_result(incorrect_msg="wronginnerfor"))
-
-success_msg("Well done!")
+ .multi(test_function('sum', incorrect_msg="wronginnerfor"))
'''
}
@@ -172,6 +170,15 @@ success_msg("Well done!")
sct_payload = helper.run(self.data)
self.assertTrue(sct_payload['correct'])
+ def test_Fail(self):
+ self.data["DC_CODE"] = '''
+for ii in range(1, 2):
+ for jj in list(range(ii)):
+ x = sum([ii+1,jj])
+ '''
+ sct_payload = helper.run(self.data)
+ self.assertFalse(sct_payload['correct'])
+ self.assertIn('wronginnerfor', sct_payload['message'])
if __name__ == "__main__":
unittest.main()
diff --git a/tests/test_test_with.py b/tests/test_test_with.py
index <HASH>..<HASH> 100644
--- a/tests/test_test_with.py
+++ b/tests/test_test_with.py
@@ -91,6 +91,15 @@ success_msg("Nice work!")
sct_payload = helper.run(self.data)
self.assertTrue(sct_payload['correct'])
+ def test_Pass1_spec2(self):
+ self.data["DC_SCT"] = '''
+for_test = test_for_loop(1, body = test_if_else(1, body = test_function('print')))
+Ex().check_with(1).check_body().with_context(for_test)
+ '''
+ sct_payload = helper.run(self.data)
+ self.assertTrue(sct_payload['correct'])
+
+
class TestExercise2(unittest.TestCase):
def setUp(self):
|
unit tests for with_context, fix nested for loop test
|
datacamp_pythonwhat
|
train
|
e0748ccc755c0b9219929d58c33a7f4aed50e557
|
diff --git a/mongo/mongo.go b/mongo/mongo.go
index <HASH>..<HASH> 100644
--- a/mongo/mongo.go
+++ b/mongo/mongo.go
@@ -85,7 +85,7 @@ const (
Upgrading StorageEngine = "Upgrading"
// SnapTrack is the track to get the juju-db snap from
- SnapTrack = "latest"
+ SnapTrack = "4.0"
// SnapRisk is which juju-db snap to use i.e. stable or edge.
SnapRisk = "stable"
|
Follow <I> channel in juju-db snap
|
juju_juju
|
train
|
0fbe68a2de80297e03bfc6b156e95be01ec1227e
|
diff --git a/duallog/duallog.py b/duallog/duallog.py
index <HASH>..<HASH> 100644
--- a/duallog/duallog.py
+++ b/duallog/duallog.py
@@ -45,7 +45,11 @@ def setup(logdir='log'):
# Validate the given directory.
logdir = os.path.normpath(logdir)
-
+
+ # if output directory is an existing file
+ if os.path.isfile(logdir):
+ logger.critical("Output directory is an existing file")
+ raise FileExistsError
# Create a folder for the logfiles.
if not os.path.exists(logdir):
os.makedirs(logdir)
|
[bugfix] When the output folder is a file
This solves the bug which happens when the output folder specified by user is a file which already exists.
|
acschaefer_duallog
|
train
|
fdd3671fa7addfb434094c62df9baa46fc9179fc
|
diff --git a/lib/pusher.js b/lib/pusher.js
index <HASH>..<HASH> 100644
--- a/lib/pusher.js
+++ b/lib/pusher.js
@@ -87,9 +87,9 @@ var Pusher = function(application_key, channel){
}
conn.onopen = function(){dispatch('open',null)}
- var dispatch = function(event_name, message){
- Pusher.log("DISPATCHING: " + event_name);
- Pusher.log(message);
+ var dispatch = function(event_name, raw_message){
+ var message = Pusher.parser(raw_message);
+ Pusher.log("Pusher : event received : " + event_name + " : " + message);
var chain = callbacks[event_name];
if(typeof chain == 'undefined'){
Pusher.log('No callbacks for '+event_name);
@@ -118,5 +118,13 @@ var Pusher = function(application_key, channel){
// Defaults ::::::::::::
Pusher.host = "ws.pusherapp.com:80";
-Pusher.log = function(msg){};
+Pusher.log = function(msg){}; // e.g. function(m){console.log(m)}
Pusher.allow_reconnect = true;
+Pusher.parser = function(data) {
+ try {
+ return JSON.parse(data);
+ } catch(e) {
+ Pusher.log("Pusher : data attribute not valid JSON - you may wish to implement your own Pusher.parser");
+ return data;
+ }
+};
|
Added backward compatible parser
A new release of pusher will send the unparsed JSON data supplied to the API as the value of the data attribute
|
pusher_pusher-js
|
train
|
fec08b4e81a81995afa560ee31a4a7255e5357b9
|
diff --git a/github/apps_manifest_test.go b/github/apps_manifest_test.go
index <HASH>..<HASH> 100644
--- a/github/apps_manifest_test.go
+++ b/github/apps_manifest_test.go
@@ -51,4 +51,18 @@ func TestGetConfig(t *testing.T) {
if !reflect.DeepEqual(cfg, want) {
t.Errorf("GetConfig returned %+v, want %+v", cfg, want)
}
+
+ const methodName = "CompleteAppManifest"
+ testBadOptions(t, methodName, func() (err error) {
+ _, _, err = client.Apps.CompleteAppManifest(ctx, "\n")
+ return err
+ })
+
+ testNewRequestAndDoFailure(t, methodName, client, func() (*Response, error) {
+ got, resp, err := client.Apps.CompleteAppManifest(ctx, "code")
+ if got != nil {
+ t.Errorf("testNewRequestAndDoFailure %v = %#v, want nil", methodName, got)
+ }
+ return resp, err
+ })
}
|
Improve apps_manifest.go coverage (#<I>)
|
google_go-github
|
train
|
d43a13836d8c40c350f109c4d5c431aee6a6f8ea
|
diff --git a/app/readers/mzidplus.py b/app/readers/mzidplus.py
index <HASH>..<HASH> 100644
--- a/app/readers/mzidplus.py
+++ b/app/readers/mzidplus.py
@@ -77,4 +77,10 @@ def get_specidentitem_percolator_data(item, namespace):
continue
else:
percodata[percoscore] = child.attrib['value']
+ outkeys = [y for x in percomap.values() for y in x.values()]
+ for key in outkeys():
+ try:
+ percodata[key]
+ except KeyError:
+ percodata[key] = 'NA'
return percodata
|
Do not crash when we dont have percolator values on certain spectra
|
glormph_msstitch
|
train
|
2d058424ee685429ca43bfadd21e8a41b40c8440
|
diff --git a/lib/api/analytics.js b/lib/api/analytics.js
index <HASH>..<HASH> 100644
--- a/lib/api/analytics.js
+++ b/lib/api/analytics.js
@@ -62,6 +62,34 @@ Report.prototype.describe = function(callback) {
};
/**
+ * Synonym of Analytics~Report#destroy()
+ *
+ * @method Analytics~Report#delete
+ * @param {Callback.<Analytics~ReportResult>} [callback] - Callback function
+ * @returns {Promise.<Analytics~ReportResult>}
+ */
+/**
+ * Synonym of Analytics~Report#destroy()
+ *
+ * @method Analytics~Report#del
+ * @param {Callback.<Analytics~ReportResult>} [callback] - Callback function
+ * @returns {Promise.<Analytics~ReportResult>}
+ */
+/**
+ * Destroy a report
+ *
+ * @method Analytics~Report#destroy
+ * @param {Callback.<Analytics~ReportResult>} [callback] - Callback function
+ * @returns {Promise.<Analytics~ReportResult>}
+ */
+Report.prototype["delete"] =
+Report.prototype.del =
+Report.prototype.destroy = function(callback) {
+ var url = [ this._conn._baseUrl(), "analytics", "reports", this.id ].join('/');
+ return this._conn.request({method: 'DELETE', url: url}).thenCall(callback);
+};
+
+/**
* Explain plan for executing report
*
* @method Analytics~Report#explain
|
Adding the ability to destroy reports via the analytics API
|
jsforce_jsforce
|
train
|
644edcda175716ce7c18d4ebcca51447347432c7
|
diff --git a/src/Client/Duty.php b/src/Client/Duty.php
index <HASH>..<HASH> 100644
--- a/src/Client/Duty.php
+++ b/src/Client/Duty.php
@@ -49,7 +49,7 @@ class Duty extends Client
* @param int $id
* @return \Unirest\Response
*/
- public function get($id = 0)
+ public function get($id)
{
return parent::get($id);
}
@@ -62,7 +62,7 @@ class Duty extends Client
* @param string $code
* @return \Unirest\Response
*/
- public function getFromCode($code = '')
+ public function getFromCode($code)
{
return parent::getFromCode($code);
}
@@ -75,7 +75,7 @@ class Duty extends Client
* @param int $id
* @return \Unirest\Response
*/
- public function getForAccount($id = 0)
+ public function getForAccount($id)
{
$slug = implode('/', ['account', $id]);
return $this->_get($slug);
@@ -89,7 +89,7 @@ class Duty extends Client
* @param string $identifier
* @return \Unirest\Response
*/
- public function getForIdentifier($identifier = '')
+ public function getForIdentifier($identifier)
{
$slug = implode('/', ['identifier', $identifier]);
return $this->_get($slug);
@@ -103,7 +103,7 @@ class Duty extends Client
* @param string $username
* @return \Unirest\Response
*/
- public function getForUsername($username = '')
+ public function getForUsername($username)
{
$slug = implode('/', ['username', $username]);
return $this->_get($slug);
|
removed uneeded default values from Duty client
|
OpenResourceManager_client-php
|
train
|
31fc7bf0c39285be52ba585e5dab720a30608045
|
diff --git a/python/bigdl/dllib/models/inception/inception.py b/python/bigdl/dllib/models/inception/inception.py
index <HASH>..<HASH> 100644
--- a/python/bigdl/dllib/models/inception/inception.py
+++ b/python/bigdl/dllib/models/inception/inception.py
@@ -269,7 +269,7 @@ if __name__ == "__main__":
train_transformer = Pipeline([PixelBytesToMat(),
Resize(256, 256),
RandomCropper(image_size, image_size, True, "Random", 3),
- ChannelNormalize(123, 117, 104),
+ ChannelNormalize(123.0, 117.0, 104.0),
MatToTensor(to_rgb=False),
ImageFrameToSample(input_keys=["imageTensor"], target_keys=["label"])
])
@@ -279,7 +279,7 @@ if __name__ == "__main__":
val_transformer = Pipeline([PixelBytesToMat(),
Resize(256, 256),
RandomCropper(image_size, image_size, False, "Center", 3),
- ChannelNormalize(123, 117, 104),
+ ChannelNormalize(123.0, 117.0, 104.0),
MatToTensor(to_rgb=False),
ImageFrameToSample(input_keys=["imageTensor"], target_keys=["label"])
])
|
fix channel normalize value to float (#<I>)
|
intel-analytics_BigDL
|
train
|
f4b6f151e1295245115becde380358d7625e2f49
|
diff --git a/src/js/form-builder.js b/src/js/form-builder.js
index <HASH>..<HASH> 100644
--- a/src/js/form-builder.js
+++ b/src/js/form-builder.js
@@ -1134,11 +1134,16 @@
_helpers.disabledTT($(this));
});
- // Attach a callback to add new options
- $sortableFields.delegate('.add_opt', 'click', function(e) {
+ // Attach a callback to add new options
+ $sortableFields.delegate('.add_opt', 'click', function (e) {
e.preventDefault();
- var isMultiple = $(this).parents('.fields').first().find('input[name="multiple"]')[0].checked,
- name = $(this).parents('.fields').find('.select-option:eq(0)').attr('name');
+ var multiple = $(this).parents('.fields').first().find('input[name="multiple"]')[0];
+ if(multiple != undefined){
+ var isMultiple = $multiple.checked;
+ }else{
+ var isMultiple = false;
+ }
+ var name = $(this).parents('.fields').find('.select-option:eq(0)').attr('name');
$(this).parents('.fields').first().find('.sortable-options').append(selectFieldOptions(false, name, false, isMultiple));
_helpers.updateMultipleSelect();
});
|
Solved bug of checking checked property of null
Modified the lines that attaches callbacks to add new options. It was throwing error "trying to get checked property of undefined" due to which it was not possilbe to add new options to radio group.
|
kevinchappell_formBuilder
|
train
|
2a3affe9915bcac14b4f6c3c216a790ad183c039
|
diff --git a/lib/weblib.php b/lib/weblib.php
index <HASH>..<HASH> 100644
--- a/lib/weblib.php
+++ b/lib/weblib.php
@@ -1065,6 +1065,17 @@ function format_string ($string, $striplinks = false, $courseid=NULL ) {
global $CFG, $course;
+ //We'll use a in-memory cache here to speed up repeated strings
+ static $strcache;
+
+ //Calculate md5
+ $md5 = md5($string.$striplinks);
+
+ //Fetch from cache if possible
+ if(isset($strcache[$md5])) {
+ return $strcache[$md5];
+ }
+
if (empty($courseid)) {
if (!empty($course->id)) { // An ugly hack for better compatibility
$courseid = $course->id; // (copied from format_text)
@@ -1079,6 +1090,9 @@ function format_string ($string, $striplinks = false, $courseid=NULL ) {
$string = preg_replace('/(<a[^>]+?>)(.+?)(<\/a>)/is','$2',$string);
}
+ //Store to cache
+ $strcache[$md5] = $string;
+
return $string;
}
|
Now format_string() uses an in-memory cache per request to make
things faster. Really noticeable in logs page!
|
moodle_moodle
|
train
|
e9fe738f038ea3d4de16643e460e369d3c81eeb2
|
diff --git a/merb-gen/app_generators/merb/templates/autotest/merb_rspec.rb b/merb-gen/app_generators/merb/templates/autotest/merb_rspec.rb
index <HASH>..<HASH> 100644
--- a/merb-gen/app_generators/merb/templates/autotest/merb_rspec.rb
+++ b/merb-gen/app_generators/merb/templates/autotest/merb_rspec.rb
@@ -3,13 +3,18 @@ require 'autotest'
class RspecCommandError < StandardError; end
+# This class maps your application's structure so Autotest can understand what
+# specs to run when files change.
+#
+# Fixtures are _not_ covered by this class. If you change a fixture file, you
+# will have to run your spec suite manually, or, better yet, provide your own
+# Autotest map explaining how your fixtures are set up.
class Autotest::MerbRspec < Autotest
# +model_tests_dir+:: the directory to find model-centric tests
# +controller_tests_dir+:: the directory to find controller-centric tests
# +view_tests_dir+:: the directory to find view-centric tests
- # +fixtures_dir+:: the directory to find fixtures in
- attr_accessor :model_tests_dir, :controller_tests_dir, :view_tests_dir, :fixtures_dir
+ attr_accessor :model_tests_dir, :controller_tests_dir, :view_tests_dir
def initialize # :nodoc:
super
@@ -35,16 +40,6 @@ class Autotest::MerbRspec < Autotest
all_specs
end
- # Any changes to a fixture will run corresponding view, controller and
- # model tests
- add_mapping %r%^#{fixtures_dir}/(.*)s.yml% do |_, m|
- [
- model_test_for(m[1]),
- controller_test_for(m[1]),
- view_test_for(m[1])
- ]
- end
-
# Any change to a test or spec will cause it to be run
add_mapping %r%^spec/(unit|models|integration|controllers|views|functional)/.*rb$% do |filename, _|
filename
@@ -174,13 +169,11 @@ private
files_matching %r%^spec/.*_spec\.rb$%
end
- # Determines the paths we can expect tests or specs to reside, as well as
- # corresponding fixtures.
+ # Determines the paths we can expect tests or specs to reside
def initialize_test_layout
self.model_tests_dir = "spec/models"
self.controller_tests_dir = "spec/controllers"
self.view_tests_dir = "spec/views"
- self.fixtures_dir = "spec/fixtures"
end
# Given a filename and the test type, this method will return the
|
Remove baked-in support for fixtures. This is between you and your ORM
|
wycats_merb
|
train
|
61c9755d4c793f02bb4880d1a55a3b4932bf4a32
|
diff --git a/rst2rst/tests/test_fixtures.py b/rst2rst/tests/test_fixtures.py
index <HASH>..<HASH> 100644
--- a/rst2rst/tests/test_fixtures.py
+++ b/rst2rst/tests/test_fixtures.py
@@ -76,8 +76,8 @@ class WriterTestCase(TestCase):
real_output_lines = real_output.splitlines(True)
theoric_output_lines = theoric_output.splitlines(True)
- diff = ''.join(unified_diff(real_output_lines,
- theoric_output_lines))
+ diff = ''.join(unified_diff(theoric_output_lines,
+ real_output_lines))
msg = "Content generated from %s differs from content at %s" \
"\nDiff:\n%s" % (
input_filename,
|
Revert expected and observed results in diffing
this way, removals and additions show the *errors* in the current output
|
benoitbryon_rst2rst
|
train
|
9252468e8f4d60eeca7e8380d2fdbe3edf2bf75a
|
diff --git a/cli/src/main/java/hudson/cli/CLI.java b/cli/src/main/java/hudson/cli/CLI.java
index <HASH>..<HASH> 100644
--- a/cli/src/main/java/hudson/cli/CLI.java
+++ b/cli/src/main/java/hudson/cli/CLI.java
@@ -440,7 +440,13 @@ public class CLI {
if (candidateKeys.isEmpty())
addDefaultPrivateKeyLocations(candidateKeys);
- CLI cli = new CLIConnectionFactory().url(url).httpsProxyTunnel(httpProxy).connect();
+ CLIConnectionFactory factory = new CLIConnectionFactory().url(url).httpsProxyTunnel(httpProxy);
+ String userInfo = new URL(url).getUserInfo();
+ if (userInfo != null) {
+ factory = factory.basicAuth(userInfo);
+ }
+
+ CLI cli = factory.connect();
try {
if (!candidateKeys.isEmpty()) {
try {
diff --git a/cli/src/main/java/hudson/cli/CLIConnectionFactory.java b/cli/src/main/java/hudson/cli/CLIConnectionFactory.java
index <HASH>..<HASH> 100644
--- a/cli/src/main/java/hudson/cli/CLIConnectionFactory.java
+++ b/cli/src/main/java/hudson/cli/CLIConnectionFactory.java
@@ -61,7 +61,11 @@ public class CLIConnectionFactory {
* Convenience method to call {@link #authorization} with the HTTP basic authentication.
*/
public CLIConnectionFactory basicAuth(String username, String password) {
- return authorization("Basic " + new String(Base64.encodeBase64((username+':'+password).getBytes())));
+ return basicAuth(username+':'+password);
+ }
+
+ public CLIConnectionFactory basicAuth(String userInfo) {
+ return authorization("Basic " + new String(Base64.encodeBase64((userInfo).getBytes())));
}
public CLI connect() throws IOException, InterruptedException {
diff --git a/cli/src/main/java/hudson/cli/FullDuplexHttpStream.java b/cli/src/main/java/hudson/cli/FullDuplexHttpStream.java
index <HASH>..<HASH> 100644
--- a/cli/src/main/java/hudson/cli/FullDuplexHttpStream.java
+++ b/cli/src/main/java/hudson/cli/FullDuplexHttpStream.java
@@ -37,6 +37,7 @@ public class FullDuplexHttpStream {
return output;
}
+ @Deprecated
public FullDuplexHttpStream(URL target) throws IOException {
this(target,basicAuth(target.getUserInfo()));
}
|
CLIConnectionFactory.basicAuth was defined but never used.
Fixed to pass basic auth to HTTP connections when included in user info portion of URL (e.g. as API token).
|
jenkinsci_jenkins
|
train
|
9070f5390668e762b7e5ec7e079435ae3ae7c0f8
|
diff --git a/graylog2-web-interface/src/views/logic/SearchResult.js b/graylog2-web-interface/src/views/logic/SearchResult.js
index <HASH>..<HASH> 100644
--- a/graylog2-web-interface/src/views/logic/SearchResult.js
+++ b/graylog2-web-interface/src/views/logic/SearchResult.js
@@ -46,7 +46,7 @@ class SearchResult {
const relatedQuery = this._getQueryBySearchTypeId(searchTypeId);
return SearchResult._getSearchTypeFromQuery(relatedQuery, searchTypeId);
});
- return compact(searchTypes);
+ return SearchResult._filterFailedSearchTypes(searchTypes);
}
_getQueryBySearchTypeId(searchTypeId) {
@@ -56,6 +56,10 @@ class SearchResult {
static _getSearchTypeFromQuery(query, searchTypeId) {
return (query && query.search_types) ? query.search_types[searchTypeId] : undefined;
}
+
+ static _filterFailedSearchTypes(searchTypes) {
+ return compact(searchTypes);
+ }
}
export default SearchResult;
|
Create extra function to filter failed search types inside SearchResult class
|
Graylog2_graylog2-server
|
train
|
8f7dd18685a6eee3adba7a80cfba906cccffed87
|
diff --git a/src/Modal.js b/src/Modal.js
index <HASH>..<HASH> 100644
--- a/src/Modal.js
+++ b/src/Modal.js
@@ -9,7 +9,7 @@
/**
* @todo
*
- * @version 0.1
+ * @version 0.2
* @uses Titon
* @uses Core
* @uses More/Drag
@@ -53,13 +53,13 @@ Titon.Modal = new Class({
* Default options.
*
* draggable - (bool) Will enable dragging on the outer element
- * closeable - (bool) Will create a closeable element and set esc binds
* blackout - (bool) Will show a blackout when a modal is opened, and hide it when it is closed
* fade - (bool) Will fade the modals in and out
* fadeDuration - (int) Fade duration in milliseconds
* className - (string) Class name to append to a tooltip when it is shown
* showLoading - (bool) Will display the loading text while waiting for AJAX calls
* contentQuery - (string) Attribute to read the content from
+ * closeQuery - (string) CSS query to bind hide() events to inner content
* delay - (int) The delay in milliseconds before the modal shows
* context - (element) The element the tooltips will display in (defaults body)
* onHide - (function) Callback to trigger when a modal is hidden
@@ -68,13 +68,13 @@ Titon.Modal = new Class({
*/
options: {
draggable: false,
- closeable: false,
blackout: false,
fade: false,
fadeDuration: 250,
className: '',
showLoading: true,
contentQuery: 'data-modal',
+ closeQuery: '.modal-close-button',
delay: 0,
context: document.body,
onHide: null,
@@ -114,14 +114,7 @@ Titon.Modal = new Class({
}
// Assign elements and events
- outer.grab(inner);
-
- if (this.options.closeable) {
- outer.grab(close);
- close.addEvent('click', this.hide.bind(this));
- }
-
- outer.inject(document.body);
+ outer.grab(inner).grab(close).inject(document.body);
this.element = outer;
this.elementBody = inner;
@@ -129,6 +122,14 @@ Titon.Modal = new Class({
$(this.options.context)
.removeEvent('click:relay(' + query + ')', listenCallback)
.addEvent('click:relay(' + query + ')', listenCallback);
+
+ close.addEvent('click', this.hide.bind(this));
+
+ window.addEvent('keydown', function(e) {
+ if (e.key === 'esc') {
+ this.hide();
+ }
+ }.bind(this));
},
/**
@@ -181,7 +182,9 @@ Titon.Modal = new Class({
* @param {string|Element} content
*/
position: function(content) {
- this.elementBody.set('html', content);
+ this.elementBody
+ .set('html', content)
+ .getElements(this.options.closeQuery).addEvent('click', this.hide().bind(this));
this.element.position({
relativeTo: document.body,
|
Removed closeable option from Modal
Added closeQuery option to Modal
|
titon_toolkit
|
train
|
7ce0010205d7c09d2bda9387223114801a1fb8cf
|
diff --git a/nephele/nephele-common/src/main/java/eu/stratosphere/nephele/io/AbstractID.java b/nephele/nephele-common/src/main/java/eu/stratosphere/nephele/io/AbstractID.java
index <HASH>..<HASH> 100644
--- a/nephele/nephele-common/src/main/java/eu/stratosphere/nephele/io/AbstractID.java
+++ b/nephele/nephele-common/src/main/java/eu/stratosphere/nephele/io/AbstractID.java
@@ -48,6 +48,19 @@ public abstract class AbstractID {
private final long lowerPart;
/**
+ * Constructs a new ID with a specific bytes value.
+ */
+ public AbstractID(final byte[] bytes) {
+
+ if (bytes.length != SIZE) {
+ throw new IllegalArgumentException("Argument bytes must by an array of " + SIZE + " bytes");
+ }
+
+ this.lowerPart = byteArrayToLong(bytes, 0);
+ this.upperPart = byteArrayToLong(bytes, SIZE_OF_LONG);
+ }
+
+ /**
* Constructs a new abstract ID.
*
* @param lowerPart
@@ -112,6 +125,26 @@ public abstract class AbstractID {
}
/**
+ * Converts the given byte array to a long.
+ *
+ * @param ba
+ * the byte array to be converted
+ * @param offset
+ * the offset indicating at which byte inside the array the conversion shall begin
+ * @return the long variable
+ */
+ private static long byteArrayToLong(final byte[] ba, final int offset) {
+
+ long l = 0;
+
+ for (int i = 0; i < SIZE_OF_LONG; ++i) {
+ l |= (ba[offset + SIZE_OF_LONG - 1 - i] & 0xffL) << (i << 3);
+ }
+
+ return l;
+ }
+
+ /**
* {@inheritDoc}
*/
@Override
diff --git a/nephele/nephele-common/src/main/java/eu/stratosphere/nephele/jobgraph/JobID.java b/nephele/nephele-common/src/main/java/eu/stratosphere/nephele/jobgraph/JobID.java
index <HASH>..<HASH> 100644
--- a/nephele/nephele-common/src/main/java/eu/stratosphere/nephele/jobgraph/JobID.java
+++ b/nephele/nephele-common/src/main/java/eu/stratosphere/nephele/jobgraph/JobID.java
@@ -45,6 +45,16 @@ public final class JobID extends AbstractID {
}
/**
+ * Constructs a new job ID from the given bytes.
+ *
+ * @param bytes
+ * the bytes to initialize the job ID with
+ */
+ private JobID(final byte[] bytes) {
+ super(bytes);
+ }
+
+ /**
* Generates a new statistically unique job ID.
*
* @return a new statistically unique job ID
@@ -56,4 +66,16 @@ public final class JobID extends AbstractID {
return new JobID(lowerPart, upperPart);
}
+
+ /**
+ * Constructs a new job ID and initializes it with the given bytes.
+ *
+ * @param bytes
+ * the bytes to initialize the new job ID with
+ * @return the new job ID
+ */
+ public static JobID fromByteArray(final byte[] bytes) {
+
+ return new JobID(bytes);
+ }
}
diff --git a/pact/pact-clients/src/main/java/eu/stratosphere/pact/client/CliFrontend.java b/pact/pact-clients/src/main/java/eu/stratosphere/pact/client/CliFrontend.java
index <HASH>..<HASH> 100644
--- a/pact/pact-clients/src/main/java/eu/stratosphere/pact/client/CliFrontend.java
+++ b/pact/pact-clients/src/main/java/eu/stratosphere/pact/client/CliFrontend.java
@@ -541,7 +541,7 @@ public class CliFrontend {
try {
ExtendedManagementProtocol jmConn = getJMConnection(rpcService);
- jmConn.cancelJob(new JobID(StringUtils.hexStringToByte(jobId)));
+ jmConn.cancelJob(JobID.fromByteArray(StringUtils.hexStringToByte(jobId)));
} catch (Throwable t) {
handleError(t);
} finally {
|
Added method to construct job ID from byte array
|
stratosphere_stratosphere
|
train
|
c57b730ecd38908a5e4db6de514442158945e0ee
|
diff --git a/empymod/__init__.py b/empymod/__init__.py
index <HASH>..<HASH> 100644
--- a/empymod/__init__.py
+++ b/empymod/__init__.py
@@ -124,12 +124,9 @@ Frequency- and time-domain examples can be found in the
`empymod/example-notebooks
<https://github.com/empymod/example-notebooks>`_-repository.
-More information and more examples can be found in the following articles:
+A good starting point is [Werthmuller_2017b]_, and more information can be
+found in [Werthmuller_2017]_.
- - `empymod/article-geo2017 <https://github.com/empymod/article-geo2017>`_
- (doi: `10.1190/geo2016-0626.1 <http://doi.org/10.1190/geo2016-0626.1>`_)
- - `empymod/article-tle2017 <https://github.com/empymod/article-tle2017>`_
- (doi: `10.1190/tle36040352.1 <http://doi.org/10.1190/tle36040352.1>`_)
Structure
'''''''''
|
Add references to usage [ci skip]
|
empymod_empymod
|
train
|
7afcacc9a19bf4e52714cde7e52562f67c76b8c0
|
diff --git a/discord/flags.py b/discord/flags.py
index <HASH>..<HASH> 100644
--- a/discord/flags.py
+++ b/discord/flags.py
@@ -876,17 +876,6 @@ class MemberCacheFlags(BaseFlags):
return self.value == self.DEFAULT_VALUE
@flag_value
- def online(self):
- """:class:`bool`: Whether to cache members with a status.
-
- For example, members that are part of the initial ``GUILD_CREATE``
- or become online at a later point. This requires :attr:`Intents.presences`.
-
- Members that go offline are no longer cached.
- """
- return 1
-
- @flag_value
def voice(self):
""":class:`bool`: Whether to cache members that are in voice.
@@ -894,7 +883,7 @@ class MemberCacheFlags(BaseFlags):
Members that leave voice are no longer cached.
"""
- return 2
+ return 1
@flag_value
def joined(self):
@@ -905,7 +894,7 @@ class MemberCacheFlags(BaseFlags):
Members that leave the guild are no longer cached.
"""
- return 4
+ return 2
@classmethod
def from_intents(cls: Type[MemberCacheFlags], intents: Intents) -> MemberCacheFlags:
@@ -926,35 +915,18 @@ class MemberCacheFlags(BaseFlags):
self = cls.none()
if intents.members:
self.joined = True
- if intents.presences:
- self.online = True
if intents.voice_states:
self.voice = True
- if not self.joined and self.online and self.voice:
- self.voice = False
-
return self
def _verify_intents(self, intents: Intents):
- if self.online and not intents.presences:
- raise ValueError('MemberCacheFlags.online requires Intents.presences enabled')
-
if self.voice and not intents.voice_states:
raise ValueError('MemberCacheFlags.voice requires Intents.voice_states')
if self.joined and not intents.members:
raise ValueError('MemberCacheFlags.joined requires Intents.members')
- if not self.joined and self.voice and self.online:
- msg = 'Setting both MemberCacheFlags.voice and MemberCacheFlags.online requires MemberCacheFlags.joined ' \
- 'to properly evict members from the cache.'
- raise ValueError(msg)
-
@property
def _voice_only(self):
- return self.value == 2
-
- @property
- def _online_only(self):
return self.value == 1
|
Remove MemberCacheFlags.online
v8 no longer gives enough data for this to be possible
|
Rapptz_discord.py
|
train
|
ef16478f8e40b5ebaf1252f26433faebad91fec6
|
diff --git a/master/buildbot/master.py b/master/buildbot/master.py
index <HASH>..<HASH> 100644
--- a/master/buildbot/master.py
+++ b/master/buildbot/master.py
@@ -333,30 +333,34 @@ class BotMaster(service.MultiService):
# point, if there are two slave proceses out there with the same name,
# so instead of booting the old (which may be in the middle of a build),
# we reject the new connection and ping the old slave.
- log.msg("duplicate slave %s; rejecting new slave and pinging old" % sl.slavename)
-
- # just in case we've got two identically-configured slaves,
- # report the IP addresses of both so someone can resolve the
- # squabble
old_tport = sl.slave.broker.transport
new_tport = mind.broker.transport
- log.msg("old slave was connected from", old_tport.getPeer())
- log.msg("new slave is from", new_tport.getPeer())
+ log.msg("duplicate slave %s; rejecting new slave (%s) and pinging old (%s)" %
+ (sl.slavename, new_tport.getPeer(), old_tport.getPeer()))
# ping the old slave. If this kills it, then the new slave will connect
# again and everyone will be happy.
- sl.slave.callRemote("print", "master got a duplicate connection; keeping this one")
-
- # now return a dummy avatar and kill the new connection in 5
- # seconds, thereby giving the ping a bit of time to kill the old
- # connection, if necessary
- def kill():
- log.msg("killing new slave on", new_tport.getPeer())
- new_tport.loseConnection()
- reactor.callLater(5, kill)
+ d = sl.slave.callRemote("print",
+ "master got a duplicate connection from %s; keeping this one" %
+ new_tport.getPeer())
+ def old_gone(f):
+ f.trap(pb.PBConnectionLost)
+ log.msg("connection lost while pinging old slave '%s' - new slave will reconnect" % slavename)
+ d.addErrback(old_gone)
+
+ # kill the new connection before it has attached. TODO: find a way
+ # to hold onto the new slave connection until the ping of the old
+ # is complete -- for better (old slave still there) or for worse
+ # (gone). Bug #1702
+ d = mind.callRemote("print",
+ "master already has a connection named '%s'; killing connection" % slavename)
+ d.addErrback(lambda f : None) # ignore errors
+ d.addCallback(lambda _ : new_tport.loseConnection())
+
+ # now return a dummy avatar to hold the slave over for the moment
class DummyAvatar(pb.Avatar):
- def attached(self, *args):
- pass
+ def attached(self, bot):
+ return defer.Deferred() # block the slave in attached()
def detached(self, *args):
pass
return DummyAvatar()
|
Better logging for duplicate slaves
Log appropriately on the master, and on both the new and old slaves,
what is going on. Fixes #<I>
|
buildbot_buildbot
|
train
|
b5196badcd6ab59de84d402b3238dc05ed87f3ed
|
diff --git a/mod/assign/locallib.php b/mod/assign/locallib.php
index <HASH>..<HASH> 100644
--- a/mod/assign/locallib.php
+++ b/mod/assign/locallib.php
@@ -4066,7 +4066,9 @@ class assign {
* @return bool
*/
protected function gradebook_item_update($submission=null, $grade=null) {
+ global $CFG;
+ require_once($CFG->dirroot.'/mod/assign/lib.php');
// Do not push grade to gradebook if blind marking is active as
// the gradebook would reveal the students.
if ($this->is_blind_marking()) {
|
MDL-<I> assign: Add missing include
There was a report of mod_assign_save_grade webservice failing because of this.
I couldn't reproduce it, but grepping the code found one place where this include
should be added.
|
moodle_moodle
|
train
|
635b3341473dd9806451de2aa46e3cbc22f9ed92
|
diff --git a/pydatastream/pydatastream.py b/pydatastream/pydatastream.py
index <HASH>..<HASH> 100644
--- a/pydatastream/pydatastream.py
+++ b/pydatastream/pydatastream.py
@@ -568,15 +568,12 @@ class Datastream(object):
return data
#################################################################################
- def get_constituents(self, index_ticker, date=None, return_raw=False,
- only_list=False):
+ def get_constituents(self, index_ticker, date=None, only_list=False):
""" Get a list of all constituents of a given index.
index_ticker - Datastream ticker for index
date - date for which list should be retrieved (if None then
list of present constituents is retrieved)
- return_raw - method does not parse the response to pd.DataFrame format
- and returns the raw dict (for debugging purposes)
only_list - request only list of symbols. By default the method
retrieves many extra fields with information (various
mnemonics and codes). This might pose some problems
@@ -594,8 +591,5 @@ class Datastream(object):
query = 'L' + index_ticker + str_date + fields
raw = self.request(query)
- if return_raw:
- return self.extract_data(raw)
-
res, metadata = self.parse_record_static(raw)
return res
|
return_raw argument is not needed any more in the get_constituents
|
vfilimonov_pydatastream
|
train
|
fd534b6196fb52a1c431faeb936934f4cd89eacc
|
diff --git a/lib/parser.js b/lib/parser.js
index <HASH>..<HASH> 100644
--- a/lib/parser.js
+++ b/lib/parser.js
@@ -504,10 +504,13 @@ Parser.prototype = {
var mode = block.mode;
var name = block.val.trim();
+ var line = block.line;
+
block = 'indent' == this.peek().type
? this.block()
: new nodes.Block(new nodes.Literal(''));
block.name = name;
+ block.line = line;
var prev = this.blocks[name] || {prepended: [], appended: []}
if (prev.mode === 'replace') return this.blocks[name] = prev;
|
Fix line number for un-used blocks warning
|
pugjs_then-pug
|
train
|
b4ae9b36e49d1a70e6ce67e3dd05b413700335ec
|
diff --git a/spec/models/comment_spec.rb b/spec/models/comment_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/models/comment_spec.rb
+++ b/spec/models/comment_spec.rb
@@ -1,7 +1,6 @@
require 'spec_helper'
describe Comment do
-
def valid_comment(options={})
Comment.new({:author => 'Bob',
:article_id => Factory(:article).id,
@@ -41,7 +40,7 @@ describe Comment do
end
describe '#save' do
- before(:each) { Factory(:blog) }
+ before(:each) { Factory(:blog, :sp_article_auto_close => 300) }
it 'should save good comment' do
assert feedback(:comment2).save
assert_equal "http://www.google.com", feedback(:comment2).url
|
Fix comment model specs after change to blog factory.
|
publify_publify
|
train
|
39e595844f1eaa711ed58ca68cda435b27dc715f
|
diff --git a/src/core.js b/src/core.js
index <HASH>..<HASH> 100644
--- a/src/core.js
+++ b/src/core.js
@@ -56,7 +56,6 @@ $.fn.powerTip = function(opts) {
$this.removeData([
'originalTitle',
- 'powertiptarget',
'displayController'
]);
});
|
Removed powertiptarget from destroy.
|
stevenbenner_jquery-powertip
|
train
|
7d4154d95c3220efbd37d83cb161285b2e65dca7
|
diff --git a/hydpy/docs/apidoc.py b/hydpy/docs/apidoc.py
index <HASH>..<HASH> 100644
--- a/hydpy/docs/apidoc.py
+++ b/hydpy/docs/apidoc.py
@@ -1,11 +1,12 @@
import os
-import shutil
import webbrowser
+os.system(r'make clean')
os.system(r'make html')
-paths = [os.path.join('_build', 'html', fn) for fn in os.listdir(os.path.join('_build', 'html'))
+paths = [os.path.join('_build', 'html', fn)
+ for fn in os.listdir(os.path.join('_build', 'html'))
if fn.endswith('.html')]
for path in paths:
lines = []
@@ -14,8 +15,9 @@ for path in paths:
line = line.split('span')[1]
line = line.split('>')[1]
line = line.split('<')[0]
- lines[-1] = lines[-1].replace('TYPE</code>',
- 'TYPE</code><em class="property"> = %s</em>' % line)
+ lines[-1] = lines[-1].replace(
+ 'TYPE</code>',
+ 'TYPE</code><em class="property"> = %s</em>' % line)
else:
lines.append(line)
open(path, 'w').write(''.join(lines))
@@ -23,5 +25,5 @@ for path in paths:
os.chdir(r'C:\Program Files (x86)\Mozilla Firefox')
webbrowser.register('firefox', None, webbrowser.GenericBrowser('firefox'), 1)
-webbrowser.get('firefox').open_new_tab(r'C:\HydPy\hydpy\docs\_build\html\index.html')
-
+webbrowser.get('firefox').open_new_tab(
+ r'C:\HydPy\hydpy\docs\_build\html\index.html')
|
Some small improvements in module `apidoc` (local creation of the documentation).
|
hydpy-dev_hydpy
|
train
|
cf24860121eda69df0c5dc6374cc62201a671af0
|
diff --git a/bundles/flex4/lib/sprout/flex4/version.rb b/bundles/flex4/lib/sprout/flex4/version.rb
index <HASH>..<HASH> 100644
--- a/bundles/flex4/lib/sprout/flex4/version.rb
+++ b/bundles/flex4/lib/sprout/flex4/version.rb
@@ -3,7 +3,7 @@ module Sprout # :nodoc:
module VERSION #:nodoc:
MAJOR = 0
MINOR = 1
- TINY = 2
+ TINY = 3
STRING = [MAJOR, MINOR, TINY].join('.')
MAJOR_MINOR = [MAJOR, MINOR].join('.')
diff --git a/bundles/flex4/test/test_helper.rb b/bundles/flex4/test/test_helper.rb
index <HASH>..<HASH> 100644
--- a/bundles/flex4/test/test_helper.rb
+++ b/bundles/flex4/test/test_helper.rb
@@ -13,7 +13,7 @@ $:.push(File.dirname(__FILE__) + '/../lib')
$:.push(File.dirname(__FILE__))
require 'generator_test_helper'
-require 'sprout/mxml'
+require 'sprout/flex4'
Sprout::Log.debug = true
|
Updated flex4 bundle version and fixed unit tests
|
lukebayes_project-sprouts
|
train
|
9753d08f19209e633918c8367d64c6ca5fdaa5fd
|
diff --git a/Core/Search/Solr/Query/Common/CriterionVisitor/Tags.php b/Core/Search/Solr/Query/Common/CriterionVisitor/Tags.php
index <HASH>..<HASH> 100644
--- a/Core/Search/Solr/Query/Common/CriterionVisitor/Tags.php
+++ b/Core/Search/Solr/Query/Common/CriterionVisitor/Tags.php
@@ -6,7 +6,7 @@ use eZ\Publish\API\Repository\Values\Content\Query\Criterion;
use eZ\Publish\Core\Search\Common\FieldNameResolver;
use eZ\Publish\Core\Search\Common\FieldValueMapper;
use eZ\Publish\SPI\Persistence\Content\Type\Handler;
-use EzSystems\EzPlatformSolrSearchEngine\Query\Content\CriterionVisitor\Field;
+use EzSystems\EzPlatformSolrSearchEngine\Query\Common\CriterionVisitor\Field;
abstract class Tags extends Field
{
|
Remove usage of deprecated base field visitor
|
netgen_TagsBundle
|
train
|
1c1fab7fa33bacf12bfdf63a0dc3427b9b92fff3
|
diff --git a/tests/TestInstallation.py b/tests/TestInstallation.py
index <HASH>..<HASH> 100644
--- a/tests/TestInstallation.py
+++ b/tests/TestInstallation.py
@@ -28,7 +28,7 @@ class VMHelper(object):
def wait_for_vm_up(self):
if not self.__vm_is_up:
print("Waiting for {} to come up.".format(self.vm_name))
- while self.__send_command("echo", hide_output=False, print_command=False) != 0:
+ while self.__send_command("echo", hide_output=True, print_command=False) != 0:
time.sleep(1)
self.__vm_is_up = True
@@ -37,21 +37,21 @@ class VMHelper(object):
return self.__send_command(command)
def __send_command(self, command: str, hide_output=False, print_command=True) -> int:
- cmd = list(self.shell.split(" "))
- cmd.extend(command.split(" "))
-
if self.use_ssh:
- fullcmd = ["ssh", "-p", str(self.ssh_port), "{0}@127.0.0.1".format(self.ssh_username),
- '"{0}"'.format(" ".join(cmd))]
+ fullcmd = ["ssh", "-p", str(self.ssh_port), "{0}@127.0.0.1".format(self.ssh_username), "'{0}'".format(command)]
else:
- fullcmd = ["VBoxManage", "guestcontrol", self.vm_name, "run"] + cmd
-
- if print_command:
- print("Running", " ".join(fullcmd))
+ fullcmd = ["VBoxManage", "guestcontrol", '"{0}"'.format(self.vm_name), "run"] \
+ + self.shell.split(" ") \
+ + ["'{0}'".format(command)]
kwargs = {"stdout": DEVNULL, "stderr": DEVNULL} if hide_output else {}
- return call(" ".join(fullcmd), **kwargs, shell=True)
+ fullcmd = " ".join(fullcmd)
+
+ if print_command:
+ print("'\033[1m'" + str(fullcmd) + "'\033[0m'")
+
+ return call(fullcmd, shell=True, **kwargs)
class TestInstallation(unittest.TestCase):
@@ -102,8 +102,8 @@ class TestInstallation(unittest.TestCase):
rc = vm_helper.send_command(r"python C:\urh\src\urh\cythonext\build.py")
self.assertEqual(rc, 0)
- #rc = vm_helper.send_command(r"set PYTHONPATH={0}\src && py.test C:\urh\tests".format(target_dir))
- #self.assertEqual(rc, 0)
+ rc = vm_helper.send_command(r"set PYTHONPATH={0}\src && py.test C:\urh\tests".format(target_dir))
+ self.assertEqual(rc, 0)
vm_helper.send_command("pip install urh")
rc = vm_helper.send_command("urh autoclose")
@@ -125,11 +125,14 @@ class TestInstallation(unittest.TestCase):
target_dir = "/tmp/urh"
vm_helper.send_command("rm -rf {0}".format(target_dir))
vm_helper.send_command("git clone https://github.com/jopohl/urh " + target_dir)
+
+ # Build extensions
rc = vm_helper.send_command("{0}python3 {1}/src/urh/cythonext/build.py".format(python_bin_dir, target_dir))
self.assertEqual(rc, 0)
- #rc = vm_helper.send_command("export PYTHONPATH='{0}/urh/src && py.test {0}/urh/tests'".format(target_dir))
- #self.assertEqual(rc, 0)
+ # Run Unit tests
+ rc = vm_helper.send_command("export PYTHONPATH='{0}/src' && {1}py.test {0}/tests".format(target_dir, python_bin_dir))
+ self.assertEqual(rc, 0)
vm_helper.send_command("{0}pip3 --no-cache-dir install urh".format(python_bin_dir))
rc = vm_helper.send_command("{0}urh autoclose".format(python_bin_dir))
diff --git a/tests/test_project_manager.py b/tests/test_project_manager.py
index <HASH>..<HASH> 100644
--- a/tests/test_project_manager.py
+++ b/tests/test_project_manager.py
@@ -13,7 +13,7 @@ app = tests.utils_testing.app
class TestProjectManager(unittest.TestCase):
def setUp(self):
self.form = MainController()
- self.form.project_manager.set_project_folder(get_path_for_data_file(""))
+ self.form.project_manager.set_project_folder(get_path_for_data_file(""), ask_for_new_project=False)
self.cframe = self.form.compare_frame_controller
self.gframe = self.form.generator_tab_controller
|
streamline windows + osx tests + do not ask for new project file in test
|
jopohl_urh
|
train
|
b2edf6fec1f7157c7dc5ac0d9f80a3f5ff670cbf
|
diff --git a/generators/generator-base.js b/generators/generator-base.js
index <HASH>..<HASH> 100644
--- a/generators/generator-base.js
+++ b/generators/generator-base.js
@@ -19,6 +19,7 @@
const path = require('path');
const _ = require('lodash');
+const { kebabCase } = require('lodash');
const chalk = require('chalk');
const fs = require('fs');
const shelljs = require('shelljs');
@@ -2994,19 +2995,18 @@ templates: ${JSON.stringify(existingTemplates, null, 2)}`;
*/
jhipsterOptions(options = {}) {
Object.entries(options).forEach(([optionName, optionDesc]) => {
- this.option(optionName, optionDesc);
+ this.option(kebabCase(optionName), optionDesc);
if (!optionDesc.scope) return;
- const camelCaseName = _.camelCase(optionName);
- const optionValue = this.options[camelCaseName];
+ const optionValue = this.options[optionName];
if (optionValue !== undefined) {
if (optionDesc.scope === 'storage') {
- this.config.set(camelCaseName, optionValue);
+ this.config.set(optionName, optionValue);
} else if (optionDesc.scope === 'runtime') {
- this.configOptions[camelCaseName] = optionValue;
+ this.configOptions[optionName] = optionValue;
} else {
throw new Error(`Scope ${optionDesc.scope} not supported`);
}
- delete this.options[camelCaseName];
+ delete this.options[optionName];
}
});
}
|
Use camelCase option name to register jhipsterOptions.
|
jhipster_generator-jhipster
|
train
|
1b7287e8bfe632d11f7f1197c2ab9679cd24c690
|
diff --git a/src/gremlin.js b/src/gremlin.js
index <HASH>..<HASH> 100644
--- a/src/gremlin.js
+++ b/src/gremlin.js
@@ -29,7 +29,7 @@ module.exports = (function() {
*/
Gremlin.prototype._ = function() {
var gremlin = new Gremlin(this.gRex);
- gremlin.queryMain('_', arguments);
+ gremlin.append('_' + gremlin.argumentHandler.build(arguments, true));
return new Pipeline(gremlin);
};
@@ -61,28 +61,21 @@ module.exports = (function() {
Gremlin.prototype.queryMain = function(methodName, args) {
var appendArg = '';
- //cater for select array parameters
- if (methodName == 'select') {
- this.append('.' + methodName + this.argumentHandler.build(args, true));
- } else if (methodName == '_') {
- this.append(methodName + this.argumentHandler.build(args, true));
- } else {
- args = _.isArray(args[0]) ? args[0] : args;
-
- //cater for idx param 2
- if (methodName == 'idx' && args.length > 1) {
- _.each(args[1], function(v, k) {
- appendArg = k + ":";
- appendArg += this.argumentHandler.parse(args[1][k]);
- }, this);
+ args = _.isArray(args[0]) ? args[0] : args;
- appendArg = "[["+ appendArg + "]]";
- args.length = 1;
- }
+ //cater for idx param 2
+ if (methodName == 'idx' && args.length > 1) {
+ _.each(args[1], function(v, k) {
+ appendArg = k + ":";
+ appendArg += this.argumentHandler.parse(args[1][k]);
+ }, this);
- this.append('.' + methodName + this.argumentHandler.build(args));
+ appendArg = "[["+ appendArg + "]]";
+ args.length = 1;
}
+ this.append('.' + methodName + this.argumentHandler.build(args));
+
this.append(appendArg);
};
diff --git a/src/pipeline.js b/src/pipeline.js
index <HASH>..<HASH> 100644
--- a/src/pipeline.js
+++ b/src/pipeline.js
@@ -100,7 +100,9 @@ module.exports = (function () {
};
Pipeline.prototype.select = function() {
- return this.add('select', 'Main', arguments);
+ this.gremlin.append('.select' + this.gremlin.argumentHandler.build(arguments, true));
+
+ return this;
};
Pipeline.prototype.transform = function() {
|
Remove logic for select() and _() methods from Gremlin.queryMain()
|
jbmusso_grex
|
train
|
11efdc688cec499515599f3224b3a526b73c291b
|
diff --git a/src/com/google/javascript/jscomp/newtypes/ClojurePersistentHashMap.java b/src/com/google/javascript/jscomp/newtypes/ClojurePersistentHashMap.java
index <HASH>..<HASH> 100644
--- a/src/com/google/javascript/jscomp/newtypes/ClojurePersistentHashMap.java
+++ b/src/com/google/javascript/jscomp/newtypes/ClojurePersistentHashMap.java
@@ -60,11 +60,13 @@ public class ClojurePersistentHashMap<K, V> extends PersistentMap<K, V> {
}
@Override
+ @SuppressWarnings("unchecked")
public V get(Object key) {
return (V) this.map.get(key);
}
@Override
+ @SuppressWarnings("unchecked")
public Set<K> keySet() {
return this.map.keySet();
}
@@ -75,6 +77,7 @@ public class ClojurePersistentHashMap<K, V> extends PersistentMap<K, V> {
}
@Override
+ @SuppressWarnings("unchecked")
public Set<Map.Entry<K, V>> entrySet() {
return this.map.entrySet();
}
diff --git a/src/com/google/javascript/jscomp/newtypes/ClojurePersistentHashSet.java b/src/com/google/javascript/jscomp/newtypes/ClojurePersistentHashSet.java
index <HASH>..<HASH> 100644
--- a/src/com/google/javascript/jscomp/newtypes/ClojurePersistentHashSet.java
+++ b/src/com/google/javascript/jscomp/newtypes/ClojurePersistentHashSet.java
@@ -75,6 +75,7 @@ public class ClojurePersistentHashSet<K> extends PersistentSet<K> {
}
@Override
+ @SuppressWarnings("unchecked")
public Iterator<K> iterator() {
return this.set.iterator();
}
|
Suppress unchecked conversions in clojure data structures
-------------
Created by MOE: <URL>
|
google_closure-compiler
|
train
|
f9bb4656f61264cf188677fa1b33b997a919a67b
|
diff --git a/includes/class-freemius.php b/includes/class-freemius.php
index <HASH>..<HASH> 100755
--- a/includes/class-freemius.php
+++ b/includes/class-freemius.php
@@ -6044,6 +6044,8 @@
fs_redirect( $this->get_after_activation_url( 'after_delegation_url' ) );
}
+ $this->_add_upgrade_action_link();
+
if ( ! $this->is_addon() &&
(
// Not registered nor anonymous.
@@ -6120,8 +6122,6 @@
$this->_show_theme_activation_optin_dialog();
}
}
-
- $this->_add_upgrade_action_link();
}
/**
@@ -18737,7 +18737,6 @@
function _add_upgrade_action_link() {
$this->_logger->entrance();
- if ( $this->is_registered() ) {
if ( ! $this->is_paying() && $this->has_paid_plan() ) {
$this->add_plugin_action_link(
$this->get_text_inline( 'Upgrade', 'upgrade' ),
@@ -18758,7 +18757,6 @@
);
}
}
- }
/**
* Adds "Activate License" or "Change License" link to the main Plugins page link actions collection.
|
[action-links] [upgrade] [fix] Make sure that the upgrade and add-ons action links are visible in all cases.
|
Freemius_wordpress-sdk
|
train
|
8cc3c4a6b765fc37f72dc557c453a219346befb9
|
diff --git a/configuration/configuration.go b/configuration/configuration.go
index <HASH>..<HASH> 100644
--- a/configuration/configuration.go
+++ b/configuration/configuration.go
@@ -207,6 +207,11 @@ func (gc *GlobalConfiguration) SetEffectiveConfiguration(configFile string) {
entryPoint.WhitelistSourceRange = nil
}
}
+
+ if entryPoint.TLS != nil && entryPoint.TLS.DefaultCertificate == nil && len(entryPoint.TLS.Certificates) > 0 {
+ log.Infof("No tls.defaultCertificate given for %s: using the first item in tls.certificates as a fallback.", entryPointName)
+ entryPoint.TLS.DefaultCertificate = &entryPoint.TLS.Certificates[0]
+ }
}
// Make sure LifeCycle isn't nil to spare nil checks elsewhere.
diff --git a/integration/etcd_test.go b/integration/etcd_test.go
index <HASH>..<HASH> 100644
--- a/integration/etcd_test.go
+++ b/integration/etcd_test.go
@@ -315,13 +315,13 @@ func (s *EtcdSuite) TestCertificatesContentWithSNIConfigHandshake(c *check.C) {
snitestOrgKey, err := ioutil.ReadFile("fixtures/https/snitest.org.key")
c.Assert(err, checker.IsNil)
- globalConfig := map[string]string{
- "/traefik/entrypoints/https/address": ":4443",
- "/traefik/entrypoints/https/tls/certificates/0/certfile": string(snitestComCert),
- "/traefik/entrypoints/https/tls/certificates/0/keyfile": string(snitestComKey),
- "/traefik/entrypoints/https/tls/certificates/1/certfile": string(snitestOrgCert),
- "/traefik/entrypoints/https/tls/certificates/1/keyfile": string(snitestOrgKey),
- "/traefik/defaultentrypoints/0": "https",
+ globalConfig := map[string][]byte{
+ "/traefik/entrypoints/https/address": []byte(":4443"),
+ "/traefik/entrypoints/https/tls/certificates/0/certfile": snitestComCert,
+ "/traefik/entrypoints/https/tls/certificates/0/keyfile": snitestComKey,
+ "/traefik/entrypoints/https/tls/certificates/1/certfile": snitestOrgCert,
+ "/traefik/entrypoints/https/tls/certificates/1/keyfile": snitestOrgKey,
+ "/traefik/defaultentrypoints/0": []byte("https"),
}
backend1 := map[string]string{
@@ -351,7 +351,7 @@ func (s *EtcdSuite) TestCertificatesContentWithSNIConfigHandshake(c *check.C) {
"/traefik/frontends/frontend2/routes/test_2/rule": "Host:snitest.org",
}
for key, value := range globalConfig {
- err := s.kv.Put(key, []byte(value), nil)
+ err := s.kv.Put(key, value, nil)
c.Assert(err, checker.IsNil)
}
for key, value := range backend1 {
diff --git a/server/server_configuration.go b/server/server_configuration.go
index <HASH>..<HASH> 100644
--- a/server/server_configuration.go
+++ b/server/server_configuration.go
@@ -590,13 +590,17 @@ func (s *Server) buildServerEntryPoints() map[string]*serverEntryPoint {
serverEntryPoints[entryPointName].certs.SniStrict = entryPoint.Configuration.TLS.SniStrict
if entryPoint.Configuration.TLS.DefaultCertificate != nil {
- cert, err := tls.LoadX509KeyPair(entryPoint.Configuration.TLS.DefaultCertificate.CertFile.String(), entryPoint.Configuration.TLS.DefaultCertificate.KeyFile.String())
+ cert, err := buildDefaultCertificate(entryPoint.Configuration.TLS.DefaultCertificate)
if err != nil {
+ log.Error(err)
+ continue
}
- serverEntryPoints[entryPointName].certs.DefaultCertificate = &cert
+ serverEntryPoints[entryPointName].certs.DefaultCertificate = cert
} else {
cert, err := generate.DefaultCertificate()
if err != nil {
+ log.Errorf("failed to generate default certificate: %v", err)
+ continue
}
serverEntryPoints[entryPointName].certs.DefaultCertificate = cert
}
@@ -611,6 +615,24 @@ func (s *Server) buildServerEntryPoints() map[string]*serverEntryPoint {
return serverEntryPoints
}
+func buildDefaultCertificate(defaultCertificate *traefiktls.Certificate) (*tls.Certificate, error) {
+ certFile, err := defaultCertificate.CertFile.Read()
+ if err != nil {
+ return nil, fmt.Errorf("failed to get cert file content: %v", err)
+ }
+
+ keyFile, err := defaultCertificate.KeyFile.Read()
+ if err != nil {
+ return nil, fmt.Errorf("failed to get key file content: %v", err)
+ }
+
+ cert, err := tls.X509KeyPair(certFile, keyFile)
+ if err != nil {
+ return nil, fmt.Errorf("failed to load X509 key pair: %v", err)
+ }
+ return &cert, nil
+}
+
func (s *Server) buildDefaultHTTPRouter() *mux.Router {
rt := mux.NewRouter()
rt.NotFoundHandler = s.wrapHTTPHandlerWithAccessLog(http.HandlerFunc(http.NotFound), "backend not found")
|
Use the first static certificate as a fallback when no default is given
|
containous_traefik
|
train
|
541db3495d3d9b68edc16bde51066adedf174069
|
diff --git a/master/buildbot/steps/source.py b/master/buildbot/steps/source.py
index <HASH>..<HASH> 100644
--- a/master/buildbot/steps/source.py
+++ b/master/buildbot/steps/source.py
@@ -842,6 +842,23 @@ class Git(Source):
self.args['repourl'] = self.computeRepositoryURL(self.repourl)
self.args['revision'] = revision
self.args['patch'] = patch
+
+ # check if there is any patchset we should fetch from Gerrit
+ try:
+ # GerritChangeSource
+ self.args['gerrit_branch'] = self.build.getProperty("event.patchSet.ref")
+ self.setProperty("gerrit_branch", self.args['gerrit_branch'])
+ except KeyError:
+ try:
+ # forced build
+ change = self.build.getProperty("gerrit_change").split('/')
+ if len(change) == 2:
+ self.args['gerrit_branch'] = "refs/changes/%2.2d/%d/%d" \
+ % (int(change[0]) % 100, int(change[0]), int(change[1]))
+ self.setProperty("gerrit_branch", self.args['gerrit_branch'])
+ except:
+ pass
+
slavever = self.slaveVersion("git")
if not slavever:
raise BuildSlaveTooOldError("slave is too old, does not know "
diff --git a/slave/buildslave/commands/git.py b/slave/buildslave/commands/git.py
index <HASH>..<HASH> 100644
--- a/slave/buildslave/commands/git.py
+++ b/slave/buildslave/commands/git.py
@@ -52,6 +52,7 @@ class Git(SourceBaseCommand):
self.submodules = args.get('submodules')
self.ignore_ignores = args.get('ignore_ignores', True)
self.reference = args.get('reference', None)
+ self.gerrit_branch = args.get('gerrit_branch', None)
def _fullSrcdir(self):
return os.path.join(self.builder.basedir, self.srcdir)
@@ -146,10 +147,10 @@ class Git(SourceBaseCommand):
return self._dovccmd(command, self._didClean)
return self._didClean(None)
- def _doFetch(self, dummy):
+ def _doFetch(self, dummy, branch):
# The plus will make sure the repo is moved to the branch's
# head even if it is not a simple "fast-forward"
- command = ['fetch', '-t', self.repourl, '+%s' % self.branch]
+ command = ['fetch', '-t', self.repourl, '+%s' % branch]
# If the 'progress' option is set, tell git fetch to output
# progress information to the log. This can solve issues with
# long fetches killed due to lack of output, but only works
@@ -157,10 +158,12 @@ class Git(SourceBaseCommand):
if self.args.get('progress'):
command.append('--progress')
self.sendStatus({"header": "fetching branch %s from %s\n"
- % (self.branch, self.repourl)})
+ % (branch, self.repourl)})
return self._dovccmd(command, self._didFetch, keepStderr=True)
def _didClean(self, dummy):
+ branch = self.gerrit_branch or self.branch
+
# After a clean, try to use the given revision if we have one.
if self.revision:
# We know what revision we want. See if we have it.
@@ -168,11 +171,11 @@ class Git(SourceBaseCommand):
self._initSubmodules)
# If we are unable to reset to the specified version, we
# must do a fetch first and retry.
- d.addErrback(self._doFetch)
+ d.addErrback(self._doFetch, branch)
return d
else:
# No known revision, go grab the latest.
- return self._doFetch(None)
+ return self._doFetch(None, branch)
def _didInit(self, res):
# If we have a reference repository specified, we need to also set that
|
Add support for fetching from "virtual branch" (take two).
This is much cleaner version of previous patch, that also adds
support for forced builds with "gerrit_change" property.
|
buildbot_buildbot
|
train
|
8bdd959d5b77e84481656622b648c525069335f6
|
diff --git a/hotModuleReplacement.js b/hotModuleReplacement.js
index <HASH>..<HASH> 100644
--- a/hotModuleReplacement.js
+++ b/hotModuleReplacement.js
@@ -40,16 +40,26 @@ function updateCss(el, url) {
if (!url) {
url = el.href.split('?')[0];
}
-
+ if (el.isLoaded === false && url == el.href.split('?')[0]) {
+ // We seem to be about to replace a css link that hasn't loaded yet.
+ // We're probably changing the same file more than once.
+ return;
+ }
if (!url || !(url.indexOf('.css') > -1)) return;
+ el.visited = true;
var newEl = el.cloneNode();
+
+ newEl.isLoaded = false;
newEl.addEventListener('load', function () {
+ newEl.isLoaded = true;
el.remove();
});
newEl.addEventListener('error', function () {
+ newEl.isLoaded = true;
el.remove();
});
+
newEl.href = url + '?' + Date.now();
el.parentNode.appendChild(newEl);
}
@@ -59,6 +69,8 @@ function reloadStyle(src) {
var loaded = false;
forEach.call(elements, function(el) {
+ if (el.visited === true) return;
+
var url = getReloadUrl(el.href, src);
if (url) {
updateCss(el, url);
@@ -83,6 +95,7 @@ function getReloadUrl(href, src) {
function reloadAll() {
var elements = document.querySelectorAll('link');
forEach.call(elements, function(el) {
+ if (el.visited === true) return;
updateCss(el);
});
}
|
Fix issue causing multiple instances of link tags to be inserted.
If you have a large css code base which import from eachother, webpack will
send a single HMR update with an entry for each of the underlying source files.
Without this patch, if you are compiling all the css into a single bundle,
css-hot-reloader will insert a new copy of the bundle for each underlying module
in the change tree that maps to said bundle. Result: memory usage goes through the
roof and possible browser crash.
|
shepherdwind_css-hot-loader
|
train
|
ffe19c936847928a292ecd4bbadf96f304e66cfb
|
diff --git a/parsedatetime/__init__.py b/parsedatetime/__init__.py
index <HASH>..<HASH> 100644
--- a/parsedatetime/__init__.py
+++ b/parsedatetime/__init__.py
@@ -910,6 +910,12 @@ class Calendar(object):
sourceTime = sTime
ctx.updateAccuracy(ctx.ACU_HALFDAY)
else:
+ # unless one of these modifiers is being applied to the
+ # day-of-week, we want to start with target as the day
+ # in the current week.
+ if not modifier in ['next', 'last', 'prior', 'previous']:
+ offset = 0
+
wkdy = self.ptc.WeekdayOffsets[wkdy]
diff = self._CalculateDOWDelta(
wd, wkdy, offset, self.ptc.DOWParseStyle,
diff --git a/tests/TestSimpleOffsets.py b/tests/TestSimpleOffsets.py
index <HASH>..<HASH> 100644
--- a/tests/TestSimpleOffsets.py
+++ b/tests/TestSimpleOffsets.py
@@ -46,6 +46,23 @@ class test(unittest.TestCase):
self.assertExpectedResult(self.cal.parse('now', start), (target, 2))
+ def testWeeksFromDayOfWeek(self):
+ self.cal.ptc.StartTimeFromSourceTime = True
+
+ s = datetime.datetime(2016, 2, 16) # a Tuesday
+ t = datetime.datetime(2016, 2, 18) # Thursday of the same week
+ tPlusOffset = t + datetime.timedelta(hours=1)
+
+ start = s.timetuple()
+ target = t.timetuple()
+ targetPlusOffset = tPlusOffset.timetuple()
+
+ self.assertExpectedResult(
+ self.cal.parse('Thursday', start), (target, 1))
+
+ self.assertExpectedResult(
+ self.cal.parse('one hour from Thursday', start), (targetPlusOffset, 3))
+
def testMinutesFromNow(self):
s = datetime.datetime.now()
t = s + datetime.timedelta(minutes=5)
|
fix offsetting of weekdays with "from"
|
bear_parsedatetime
|
train
|
e4e13ba45fa891f443f075467a91fb14a0956a67
|
diff --git a/nomenclate/core/configurator.py b/nomenclate/core/configurator.py
index <HASH>..<HASH> 100644
--- a/nomenclate/core/configurator.py
+++ b/nomenclate/core/configurator.py
@@ -14,8 +14,9 @@ from future.utils import iteritems
import yaml
import os
from collections import OrderedDict
-import nomenclate.core.exceptions as exceptions
+from six import add_metaclass
from pprint import pformat
+import nomenclate.core.exceptions as exceptions
from nomenclate.core.tools import (
gen_dict_key_matches,
get_keys_containing
@@ -97,7 +98,7 @@ class ConfigParse(object):
try:
config_entry = function_type_lookup[type(query_path)](query_path)
- self.LOG.debug('Retrieved and config entry:\n%s' % pformat(config_entry, depth=1))
+ self.LOG.debug('Retrieved config entry:\n%s' % pformat(config_entry, depth=1))
query_result = self.config_entry_handler.format_query_result(config_entry,
query_path,
return_type=return_type,
@@ -105,14 +106,17 @@ class ConfigParse(object):
self.LOG.debug('Converted config entry:\n%s' % pformat(query_result, depth=1))
return query_result
except IndexError:
+ self.LOG.debug('Not sure why but IndexError was found...defaulting to return: %s = %r' %
+ (return_type, return_type()))
return return_type()
- def _get_path_entry_from_string(self, qstr, first_found=True, full_path=False):
- iter_matches = gen_dict_key_matches(qstr, self.config_file_contents, full_path=full_path)
+ def _get_path_entry_from_string(self, query_string, first_found=True, full_path=False):
+ iter_matches = gen_dict_key_matches(query_string, self.config_file_contents, full_path=full_path)
try:
return next(iter_matches) if first_found else iter_matches
except (StopIteration, TypeError):
- raise exceptions.ResourceNotFoundError('Could not find search string %s in the config file contents %s' % (qstr, self.config_file_contents))
+ raise exceptions.ResourceNotFoundError('Could not find search string %s in the config file contents %s' %
+ (query_string, self.config_file_contents))
def _get_path_entry_from_list(self, query_path):
cur_data = self.config_file_contents
@@ -170,8 +174,8 @@ class FormatterRegistry(type):
return mcs.CONVERSION_TABLE[input_type][return_type]
+@add_metaclass(FormatterRegistry)
class BaseFormatter(object):
- __metaclass__ = FormatterRegistry
converts = {'accepted_input_type': None,
'accepted_return_type': None}
@@ -260,6 +264,15 @@ class ListToStringEntryFormatter(BaseFormatter):
return ' '.join(input)
+class IntToListEntryFormatter(BaseFormatter):
+ converts = {'accepted_input_type': int,
+ 'accepted_return_type': list}
+
+ @staticmethod
+ def format_result(input):
+ return [input]
+
+
class ConfigEntryFormatter(object):
def format_query_result(self, query_result, query_path, return_type=list, preceding_depth=None):
"""
diff --git a/tests/test_configurator.py b/tests/test_configurator.py
index <HASH>..<HASH> 100644
--- a/tests/test_configurator.py
+++ b/tests/test_configurator.py
@@ -3,7 +3,6 @@ from __future__ import print_function
from imp import reload
from future.utils import iteritems
import six
-
import nomenclate.core.exceptions as exceptions
import unittest
import mock
@@ -123,11 +122,11 @@ class TestConfigurator(unittest.TestCase):
return len(L1) == len(L2) and sorted(L1) == sorted(L2)
def assertDictEqual(self, d1, d2, msg=None): # assertEqual uses for dicts
- for k, v1 in d1.iteritems():
+ for k, v1 in iteritems(d1):
self.assertIn(k, d2, msg)
v2 = d2[k]
if (isinstance(v1, collections.Iterable) and
- not isinstance(v1, basestring)):
+ not isinstance(v1, six.string_types)):
self.checkEqual(v1, v2)
else:
self.assertEqual(v1, v2, msg)
diff --git a/tests/test_nameparser.py b/tests/test_nameparser.py
index <HASH>..<HASH> 100644
--- a/tests/test_nameparser.py
+++ b/tests/test_nameparser.py
@@ -126,6 +126,7 @@ class TestNameparser(unittest.TestCase):
self.assertIsNone(side_results)
else:
for element in [side, permutation]:
+ print(element, side_results)
self.assertIn(element, side_results)
def test_get_date_specific(self):
diff --git a/tox.ini b/tox.ini
index <HASH>..<HASH> 100644
--- a/tox.ini
+++ b/tox.ini
@@ -1,5 +1,5 @@
[tox]
-envlist=py35
+envlist=py27, py35
skip_missing_interpreters=True
[testenv]
@@ -8,5 +8,6 @@ nose==1.3.7
commands=nosetests -c tests/nose.cfg
-[testenv:py35]
-basepython=C:\Users\andre\Anaconda3\python.exe
\ No newline at end of file
+# For local testing in windows
+#[testenv:py35]
+#basepython=C:\Users\andre\Anaconda3\python.exe
\ No newline at end of file
|
Added int -> list formatter for versions etc. Converted to python 2/3 friendly metaclassing. Fixed some test cases to by python2/3 compatible with iteritems etc.
|
AndresMWeber_Nomenclate
|
train
|
052229853799460a1e1ee6396f6633249522f77c
|
diff --git a/bundles/org.eclipse.orion.client.ui/web/plugins/site/selfHostingRules.js b/bundles/org.eclipse.orion.client.ui/web/plugins/site/selfHostingRules.js
index <HASH>..<HASH> 100644
--- a/bundles/org.eclipse.orion.client.ui/web/plugins/site/selfHostingRules.js
+++ b/bundles/org.eclipse.orion.client.ui/web/plugins/site/selfHostingRules.js
@@ -47,6 +47,7 @@ define([], function() {
{ type: API, source: "/mixlogin/manageopenids", targetPattern: "${0}mixlogin/manageopenids" },
{ type: API, source: "/openids", targetPattern: "${0}openids" },
{ type: API, source: "/task", targetPattern: "${0}task" },
+ { type: API, source: "/cfapi", targetPattern: "${0}cfapi" },
// { type: API, source: "/help", targetPattern: "${0}help" },
{ type: API, source: "/docker", targetPattern: "${0}docker" }
];
|
[nobug] Add /cfapi to self hosting
|
eclipse_orion.client
|
train
|
df2041fcd0e8fda2376c8fe69760cc7d7bfe6a41
|
diff --git a/addons/storysource/src/loader/index.js b/addons/storysource/src/loader/index.js
index <HASH>..<HASH> 100644
--- a/addons/storysource/src/loader/index.js
+++ b/addons/storysource/src/loader/index.js
@@ -1,13 +1,16 @@
import { getOptions } from 'loader-utils';
import injectDecorator from './inject-decorator';
-const ADD_DECORATOR_STATEMENT = '.addDecorator(withStorySource(__STORY__, __ADDS_MAP__))';
+let ADD_DECORATOR_STATEMENT = '.addDecorator(withStorySource(__STORY__, __ADDS_MAP__))';
function transform(source) {
const options = getOptions(this) || {};
+
+ if (options.noStoriesOf) ADD_DECORATOR_STATEMENT = '';
+
const result = injectDecorator(source, ADD_DECORATOR_STATEMENT, this.resourcePath, options);
- if (!result.changed) {
+ if (!options.noStoriesOf && !result.changed) {
return source;
}
@@ -17,13 +20,22 @@ function transform(source) {
const addsMap = JSON.stringify(result.addsMap);
- return `
+ if (!options.noStoriesOf) {
+ return `
var withStorySource = require('@storybook/addon-storysource').withStorySource;
var __STORY__ = ${sourceJson};
var __ADDS_MAP__ = ${addsMap};
${result.source}
`;
+ } else {
+ return `
+ export var __STORY__ = ${sourceJson};
+ export var __ADDS_MAP__ = ${addsMap};
+
+ ${result.source}
+ `;
+ }
}
export default transform;
diff --git a/addons/storysource/src/loader/inject-decorator.js b/addons/storysource/src/loader/inject-decorator.js
index <HASH>..<HASH> 100644
--- a/addons/storysource/src/loader/inject-decorator.js
+++ b/addons/storysource/src/loader/inject-decorator.js
@@ -23,7 +23,7 @@ function inject(source, decorator, filepath, options = {}) {
options.parser
);
- if (!changed) {
+ if (!options.noStoriesOf && !changed) {
return {
source: newSource,
addsMap: {},
|
add: noStoriesOf loader option support for custome story
|
storybooks_storybook
|
train
|
f3768cc288f3ac638b3f301ff11e7275ac293e37
|
diff --git a/test/Stagehand/TestRunner/Runner/PHPUnitRunnerTest.php b/test/Stagehand/TestRunner/Runner/PHPUnitRunnerTest.php
index <HASH>..<HASH> 100644
--- a/test/Stagehand/TestRunner/Runner/PHPUnitRunnerTest.php
+++ b/test/Stagehand/TestRunner/Runner/PHPUnitRunnerTest.php
@@ -477,7 +477,7 @@ class Stagehand_TestRunner_Runner_PHPUnitRunnerTest extends Stagehand_TestRunner
$this->assertTestCaseCount(1);
$this->assertTestCaseExists('isFailure', $testClass);
$this->assertTestCaseAssertionCount(1, 'isFailure', $testClass);
- $this->assertTestCaseHasFailure('isFailure', $testClass);
+ $this->assertTestCaseFailed('isFailure', $testClass);
$this->assertTestCaseFailureMessageEquals('/The First Failure/', 'isFailure', $testClass);
}
diff --git a/test/Stagehand/TestRunner/Runner/SimpleTestRunnerTest.php b/test/Stagehand/TestRunner/Runner/SimpleTestRunnerTest.php
index <HASH>..<HASH> 100644
--- a/test/Stagehand/TestRunner/Runner/SimpleTestRunnerTest.php
+++ b/test/Stagehand/TestRunner/Runner/SimpleTestRunnerTest.php
@@ -4,7 +4,7 @@
/**
* PHP version 5
*
- * Copyright (c) 2009-2010 KUBO Atsuhiro <kubo@iteman.jp>,
+ * Copyright (c) 2009-2011 KUBO Atsuhiro <kubo@iteman.jp>,
* 2010 KUMAKURA Yousuke <kumatch@gmail.com>,
* All rights reserved.
*
@@ -30,7 +30,7 @@
* POSSIBILITY OF SUCH DAMAGE.
*
* @package Stagehand_TestRunner
- * @copyright 2009-2010 KUBO Atsuhiro <kubo@iteman.jp>
+ * @copyright 2009-2011 KUBO Atsuhiro <kubo@iteman.jp>
* @copyright 2010 KUMAKURA Yousuke <kumatch@gmail.com>
* @license http://www.opensource.org/licenses/bsd-license.php New BSD License
* @version Release: @package_version@
@@ -39,7 +39,7 @@
/**
* @package Stagehand_TestRunner
- * @copyright 2009-2010 KUBO Atsuhiro <kubo@iteman.jp>
+ * @copyright 2009-2011 KUBO Atsuhiro <kubo@iteman.jp>
* @copyright 2010 KUMAKURA Yousuke <kumatch@gmail.com>
* @license http://www.opensource.org/licenses/bsd-license.php New BSD License
* @version Release: @package_version@
@@ -298,7 +298,7 @@ class Stagehand_TestRunner_Runner_SimpleTestRunnerTest extends Stagehand_TestRun
$this->assertTestCaseCount(1);
$this->assertTestCaseExists('testIsFailure', $testClass);
$this->assertTestCaseAssertionCount(1, 'testIsFailure', $testClass);
- $this->assertTestCaseHasFailure('testIsFailure', $testClass);
+ $this->assertTestCaseFailed('testIsFailure', $testClass);
$this->assertTestCaseFailureMessageEquals('/^The First Failure/', 'testIsFailure', $testClass);
}
diff --git a/test/Stagehand/TestRunner/TestCase.php b/test/Stagehand/TestRunner/TestCase.php
index <HASH>..<HASH> 100644
--- a/test/Stagehand/TestRunner/TestCase.php
+++ b/test/Stagehand/TestRunner/TestCase.php
@@ -173,7 +173,7 @@ abstract class Stagehand_TestRunner_TestCase extends PHPUnit_Framework_TestCase
* @param string $class
* @since Method available since Release 2.14.0
*/
- protected function assertTestCaseHasFailure($method, $class)
+ protected function assertTestCaseFailed($method, $class)
{
$failures = $this->createXPath()
->query("//testcase[@name='$method'][@class='$class']/failure");
|
Renamed the method from assertTestCaseHasFailure() to assertTestCaseFailed().
|
piece_stagehand-testrunner
|
train
|
f48a0d9da5471143d45940c8a9e63c38f3f21e87
|
diff --git a/doc/conf.py b/doc/conf.py
index <HASH>..<HASH> 100644
--- a/doc/conf.py
+++ b/doc/conf.py
@@ -59,6 +59,7 @@ MOCK_MODULES = [
'psutil',
'pycassa',
'pymongo',
+ 'rabbitmq_server',
'redis',
'rpm',
'rpmUtils',
|
Mocked rabbitmq_server
|
saltstack_salt
|
train
|
2c246a0aa7d84dfaaecf4d629e216075f3f1acce
|
diff --git a/discord/client.py b/discord/client.py
index <HASH>..<HASH> 100644
--- a/discord/client.py
+++ b/discord/client.py
@@ -105,15 +105,15 @@ class Client:
self.token = None
self.gateway = None
self.voice = None
+ self.session_id = None
+ self.sequence = 0
self.loop = asyncio.get_event_loop() if loop is None else loop
self._listeners = []
self.cache_auth = options.get('cache_auth', True)
- max_messages = options.get('max_messages')
- if max_messages is None or max_messages < 100:
- max_messages = 5000
-
- self.connection = ConnectionState(self.dispatch, max_messages)
+ self.max_messages = options.get('max_messages')
+ if self.max_messages is None or self.max_messages < 100:
+ self.max_messages = 5000
# Blame React for this
user_agent = 'DiscordBot (https://github.com/Rapptz/discord.py {0}) Python/{1[0]}.{1[1]} aiohttp/{2}'
@@ -180,7 +180,6 @@ class Client:
log.info('a problem occurred while updating the login cache')
pass
-
def handle_message(self, message):
removed = []
for i, (condition, future) in enumerate(self._listeners):
@@ -311,6 +310,7 @@ class Client:
print('Ignoring exception in {}'.format(event_method), file=sys.stderr)
traceback.print_exc()
+ @asyncio.coroutine
def received_message(self, msg):
log.debug('WebSocket Event: {}'.format(msg))
self.dispatch('socket_response', msg)
@@ -318,6 +318,15 @@ class Client:
op = msg.get('op')
data = msg.get('d')
+ if 's' in msg:
+ self.sequence = msg['s']
+
+ if op == 7:
+ # redirect op code
+ yield from self.ws.close()
+ yield from self.redirect_websocket(data.get('url'))
+ return
+
if op != 0:
log.info('Unhandled op {}'.format(op))
return
@@ -325,6 +334,10 @@ class Client:
event = msg.get('t')
if event == 'READY':
+ self.connection = ConnectionState(self.dispatch, self.max_messages)
+ self.session_id = data['session_id']
+
+ if event == 'READY' or event == 'RESUMED':
interval = data['heartbeat_interval'] / 1000.0
self.keep_alive = utils.create_task(self.keep_alive_handler(interval), loop=self.loop)
@@ -352,30 +365,60 @@ class Client:
log.info("Unhandled event {}".format(event))
@asyncio.coroutine
- def _make_websocket(self):
+ def _make_websocket(self, initial=True):
if not self.is_logged_in:
raise ClientException('You must be logged in to connect')
self.ws = yield from websockets.connect(self.gateway, loop=self.loop)
self.ws.max_size = None
log.info('Created websocket connected to {0.gateway}'.format(self))
+
+ if initial:
+ payload = {
+ 'op': 2,
+ 'd': {
+ 'token': self.token,
+ 'properties': {
+ '$os': sys.platform,
+ '$browser': 'discord.py',
+ '$device': 'discord.py',
+ '$referrer': '',
+ '$referring_domain': ''
+ },
+ 'v': 3
+ }
+ }
+
+ yield from self.ws.send(utils.to_json(payload))
+ log.info('sent the initial payload to create the websocket')
+
+ @asyncio.coroutine
+ def redirect_websocket(self, url):
+ # if we get redirected then we need to recreate the websocket
+ # when this recreation happens we have to try to do a reconnection
+ log.info('redirecting websocket from {} to {}'.format(self.gateway, url))
+ self.keep_alive_handler.cancel()
+
+ self.gateway = url
+ yield from self._make_websocket(initial=False)
+ yield from self._reconnect_ws()
+
+ if self.is_voice_connected():
+ # update the websocket reference pointed to by voice
+ self.voice.main_ws = self.ws
+
+ @asyncio.coroutine
+ def _reconnect_ws(self):
payload = {
- 'op': 2,
+ 'op': 6,
'd': {
- 'token': self.token,
- 'properties': {
- '$os': sys.platform,
- '$browser': 'discord.py',
- '$device': 'discord.py',
- '$referrer': '',
- '$referring_domain': ''
- },
- 'v': 3
+ 'session_id': self.session_id,
+ 'seq': self.sequence
}
}
+ log.info('sending reconnection frame to websocket {}'.format(payload))
yield from self.ws.send(utils.to_json(payload))
- log.info('sent the initial payload to create the websocket')
# properties
@@ -636,10 +679,14 @@ class Client:
while not self._closed:
msg = yield from self.ws.recv()
if msg is None:
- yield from self.close()
- break
+ if self.ws.close_code == 1012:
+ yield from self.redirect_websocket(self.gateway)
+ continue
+ else:
+ yield from self.close()
+ break
- self.received_message(json.loads(msg))
+ yield from self.received_message(json.loads(msg))
@asyncio.coroutine
def close(self):
@@ -654,11 +701,12 @@ class Client:
yield from self.voice.disconnect()
self.voice = None
- yield from self.ws.close()
+ if self.ws.open:
+ yield from self.ws.close()
+
self.keep_alive.cancel()
self._closed = True
-
@asyncio.coroutine
def start(self, email, password):
"""|coro|
|
Add first support for gateway redirects and reconnects.
|
Rapptz_discord.py
|
train
|
92e290c2172e2a570adc830a37ad1af88bf8a174
|
diff --git a/wakatime/stats.py b/wakatime/stats.py
index <HASH>..<HASH> 100644
--- a/wakatime/stats.py
+++ b/wakatime/stats.py
@@ -23,7 +23,17 @@ from pygments.lexers import guess_lexer_for_filename
log = logging.getLogger(__name__)
+# force file name extensions to be recognized as a certain language
+EXTENSIONS = {
+ 'md': 'Markdown',
+}
+
+
def guess_language(file_name):
+ if file_name:
+ language = guess_language_from_extension(file_name.rsplit('.', 1)[-1])
+ if language:
+ return language
lexer = None
try:
with open(file_name) as f:
@@ -36,6 +46,15 @@ def guess_language(file_name):
return None
+def guess_language_from_extension(extension):
+ if extension:
+ if extension in EXTENSIONS:
+ return EXTENSIONS[extension]
+ if extension.lower() in EXTENSIONS:
+ return mapping[EXTENSIONS.lower()]
+ return None
+
+
def number_lines_in_file(file_name):
lines = 0
try:
|
force some file extensions to be recognizes as certain languages
|
wakatime_wakatime
|
train
|
f208354d2dc1a931ac2763f8bb4c9cc106998f26
|
diff --git a/flink-python/pyflink/fn_execution/coder_impl.py b/flink-python/pyflink/fn_execution/coder_impl.py
index <HASH>..<HASH> 100644
--- a/flink-python/pyflink/fn_execution/coder_impl.py
+++ b/flink-python/pyflink/fn_execution/coder_impl.py
@@ -149,10 +149,10 @@ class BigIntCoderImpl(StreamCoderImpl):
class TinyIntCoderImpl(StreamCoderImpl):
def encode_to_stream(self, value, out_stream, nested):
- out_stream.write_byte(value)
+ out_stream.write(struct.pack('b', value))
def decode_from_stream(self, in_stream, nested):
- return int(in_stream.read_byte())
+ return struct.unpack('b', in_stream.read(1))[0]
class SmallIntImpl(StreamCoderImpl):
@@ -237,8 +237,9 @@ class BinaryCoderImpl(StreamCoderImpl):
class CharCoderImpl(StreamCoderImpl):
def encode_to_stream(self, value, out_stream, nested):
- out_stream.write_bigendian_int32(len(value))
- out_stream.write(value.encode("utf-8"), False)
+ bytes_value = value.encode("utf-8")
+ out_stream.write_bigendian_int32(len(bytes_value))
+ out_stream.write(bytes_value, False)
def decode_from_stream(self, in_stream, nested):
size = in_stream.read_bigendian_int32()
diff --git a/flink-python/pyflink/fn_execution/tests/coders_test_common.py b/flink-python/pyflink/fn_execution/tests/coders_test_common.py
index <HASH>..<HASH> 100644
--- a/flink-python/pyflink/fn_execution/tests/coders_test_common.py
+++ b/flink-python/pyflink/fn_execution/tests/coders_test_common.py
@@ -46,7 +46,7 @@ class CodersTest(unittest.TestCase):
def test_tinyint_coder(self):
coder = TinyIntCoder()
- self.check_coder(coder, 1, 10, 127)
+ self.check_coder(coder, 1, 10, 127, -128)
def test_boolean_coder(self):
coder = BooleanCoder()
@@ -74,7 +74,7 @@ class CodersTest(unittest.TestCase):
def test_char_coder(self):
coder = CharCoder()
- self.check_coder(coder, 'flink')
+ self.check_coder(coder, 'flink', '🐿')
def test_date_coder(self):
import datetime
|
[FLINK-<I>][python] Fix impletation bug of TinyIntCoder and CharCoder
This closes #<I>.
|
apache_flink
|
train
|
a4dc7ba2d89539c40fed639166a399858d2271e4
|
diff --git a/src/sqla_filters/parser/parser.py b/src/sqla_filters/parser/parser.py
index <HASH>..<HASH> 100644
--- a/src/sqla_filters/parser/parser.py
+++ b/src/sqla_filters/parser/parser.py
@@ -26,8 +26,9 @@ def validate_element(e_type, e_value) -> bool:
class JSONFiltersParser(object):
- def __init__(self, json_str: str) -> None:
+ def __init__(self, json_str: str, attr_sep: str = '.') -> None:
self._raw_data = json_str
+ self._attr_sep = attr_sep # Global attr_sep
self._filters_tree = self._generate_filters_tree()
@property
@@ -35,6 +36,20 @@ class JSONFiltersParser(object):
return self._raw_data
@property
+ def attr_sep(self) -> str:
+ """Return the current attriute separator."""
+ return self._attr_sep
+
+ @attr_sep.setter
+ def attr_sep(self, new_sep: str) -> None:
+ """Set the new value for the attribute separator.
+
+ When the new value is assigned a new tree is generated.
+ """
+ self._attr_sep = new_sep
+ self._filters_tree = self._generate_filters_tree()
+
+ @property
def tree(self) -> SqlaFilterTree:
return self._filters_tree
@@ -44,9 +59,11 @@ class JSONFiltersParser(object):
return LOGICAL_NODES[key]()
elif key == 'operator':
operator = data.get('operator')
+ attr_sep = data.get('attr_sep', None) # Per node attr_sep
return OPERATOR_NODES[operator](
data.get('attribute', ''),
data.get('value', None),
+ attr_sep=attr_sep if attr_sep else self._attr_sep
)
else:
raise FiltersParserTypeError('Unknown key.')
|
Add support for multiple separator.
Before relation field was to be of the following form:
- <rel_attr>.<attr>
You can now modify the separator '.' and choose you want.
You can set this separator globally in the parser or per node.
|
MarcAureleCoste_sqla-filters
|
train
|
14e965d58ec32c482fcc4721f54980c0ce850eb8
|
diff --git a/packages_es6/ember-handlebars/lib/helpers/collection.js b/packages_es6/ember-handlebars/lib/helpers/collection.js
index <HASH>..<HASH> 100644
--- a/packages_es6/ember-handlebars/lib/helpers/collection.js
+++ b/packages_es6/ember-handlebars/lib/helpers/collection.js
@@ -236,7 +236,9 @@ function collectionHelper(path, options) {
}
if (emptyViewClass) { hash.emptyView = emptyViewClass; }
- if (!hash.keyword) {
+ if (hash.keyword) {
+ itemHash._context = this;
+ } else {
itemHash._context = alias('content');
}
diff --git a/packages_es6/ember-handlebars/tests/helpers/each_test.js b/packages_es6/ember-handlebars/tests/helpers/each_test.js
index <HASH>..<HASH> 100644
--- a/packages_es6/ember-handlebars/tests/helpers/each_test.js
+++ b/packages_es6/ember-handlebars/tests/helpers/each_test.js
@@ -669,3 +669,81 @@ test("it doesn't assert when the morph tags have the same parent", function() {
ok(true, "No assertion from valid template");
});
+
+test("itemController specified in template with name binding does not change context", function() {
+ var Controller = EmberController.extend({
+ controllerName: computed(function() {
+ return "controller:"+this.get('content.name');
+ })
+ });
+
+ var container = new Container();
+
+ people = A([{ name: "Steve Holt" }, { name: "Annabelle" }]);
+
+ var parentController = {
+ container: container,
+ people: people,
+ controllerName: 'controller:parentController'
+ };
+
+ container.register('controller:array', ArrayController.extend());
+
+ view = EmberView.create({
+ container: container,
+ template: templateFor('{{#each person in people itemController="person"}}{{controllerName}} - {{person.controllerName}} - {{/each}}'),
+ controller: parentController
+ });
+
+ container.register('controller:person', Controller);
+
+ append(view);
+
+ equal(view.$().text(), "controller:parentController - controller:Steve Holt - controller:parentController - controller:Annabelle - ");
+
+ run(function() {
+ people.pushObject({ name: "Yehuda Katz" });
+ });
+
+ assertText(view, "controller:parentController - controller:Steve Holt - controller:parentController - controller:Annabelle - controller:parentController - controller:Yehuda Katz - ");
+
+ run(function() {
+ set(parentController, 'people', A([{ name: "Trek Glowacki" }, { name: "Geoffrey Grosenbach" }]));
+ });
+
+ assertText(view, "controller:parentController - controller:Trek Glowacki - controller:parentController - controller:Geoffrey Grosenbach - ");
+
+ var controller = view.get('_childViews')[0].get('controller');
+ strictEqual(view.get('_childViews')[0].get('_arrayController.target'), parentController, "the target property of the child controllers are set correctly");
+});
+
+test("itemController specified in ArrayController with name binding does not change context", function() {
+ people = A([{ name: "Steve Holt" }, { name: "Annabelle" }]);
+
+ var PersonController = ObjectController.extend({
+ controllerName: computed(function() {
+ return "controller:" + get(this, 'content.name') + ' of ' + get(this, 'parentController.company');
+ })
+ }),
+ PeopleController = ArrayController.extend({
+ content: people,
+ itemController: 'person',
+ company: 'Yapp',
+ controllerName: 'controller:people'
+ }),
+ container = new Container();
+
+ container.register('controller:people', PeopleController);
+ container.register('controller:person', PersonController);
+
+ view = EmberView.create({
+ container: container,
+ template: templateFor('{{#each person in this}}{{controllerName}} - {{person.controllerName}} - {{/each}}'),
+ controller: container.lookup('controller:people')
+ });
+
+
+ append(view);
+
+ equal(view.$().text(), "controller:people - controller:Steve Holt of Yapp - controller:people - controller:Annabelle of Yapp - ");
+});
diff --git a/packages_es6/ember-handlebars/tests/helpers/with_test.js b/packages_es6/ember-handlebars/tests/helpers/with_test.js
index <HASH>..<HASH> 100644
--- a/packages_es6/ember-handlebars/tests/helpers/with_test.js
+++ b/packages_es6/ember-handlebars/tests/helpers/with_test.js
@@ -311,13 +311,13 @@ test("it should still have access to original parentController within an {{#each
var parentController = EmberObject.create({
container: container,
- name: 'Bob Loblaw'
+ name: 'Bob Loblaw',
+ people: people
});
view = EmberView.create({
container: container,
template: EmberHandlebars.compile('{{#each person in people}}{{#with person controller="person"}}{{controllerName}}{{/with}}{{/each}}'),
- context: { people: people },
controller: parentController
});
|
[BUGFIX beta] Ensure context is unchanged when using keywords with itemController.
Prior to this change the following code would bind `this` in the
template block to the itemController's content (even though the keyword
form of `{{each}}` is used).
This change sets the child view's `_context` property to the current context when using
the keyword form of `{{each}}`, and a couple of confirming tests to
demonstrate using `itemController` specified in either the
`ArrayController` or the template directly.
|
emberjs_ember.js
|
train
|
62e8ebff8f56b3b4fea683000802d24a02d011ff
|
diff --git a/pkg/model/components/etcd.go b/pkg/model/components/etcd.go
index <HASH>..<HASH> 100644
--- a/pkg/model/components/etcd.go
+++ b/pkg/model/components/etcd.go
@@ -24,7 +24,7 @@ import (
"k8s.io/kops/upup/pkg/fi/loader"
)
-const DefaultBackupImage = "kopeio/etcd-backup:3.0.20190516"
+const DefaultBackupImage = "kopeio/etcd-backup:3.0.20190801"
// EtcdOptionsBuilder adds options for etcd to the model
type EtcdOptionsBuilder struct {
diff --git a/pkg/model/components/etcdmanager/model.go b/pkg/model/components/etcdmanager/model.go
index <HASH>..<HASH> 100644
--- a/pkg/model/components/etcdmanager/model.go
+++ b/pkg/model/components/etcdmanager/model.go
@@ -189,7 +189,7 @@ metadata:
namespace: kube-system
spec:
containers:
- - image: kopeio/etcd-manager:3.0.20190516
+ - image: kopeio/etcd-manager:3.0.20190801
name: etcd-manager
resources:
requests:
diff --git a/pkg/model/components/etcdmanager/tests/minimal/tasks.yaml b/pkg/model/components/etcdmanager/tests/minimal/tasks.yaml
index <HASH>..<HASH> 100644
--- a/pkg/model/components/etcdmanager/tests/minimal/tasks.yaml
+++ b/pkg/model/components/etcdmanager/tests/minimal/tasks.yaml
@@ -89,7 +89,7 @@ Contents:
--v=6 --volume-name-tag=k8s.io/etcd/events --volume-provider=aws --volume-tag=k8s.io/etcd/events
--volume-tag=k8s.io/role/master=1 --volume-tag=kubernetes.io/cluster/minimal.example.com=owned
> /tmp/pipe 2>&1
- image: kopeio/etcd-manager:3.0.20190516
+ image: kopeio/etcd-manager:3.0.20190801
name: etcd-manager
resources:
requests:
@@ -160,7 +160,7 @@ Contents:
--v=6 --volume-name-tag=k8s.io/etcd/main --volume-provider=aws --volume-tag=k8s.io/etcd/main
--volume-tag=k8s.io/role/master=1 --volume-tag=kubernetes.io/cluster/minimal.example.com=owned
> /tmp/pipe 2>&1
- image: kopeio/etcd-manager:3.0.20190516
+ image: kopeio/etcd-manager:3.0.20190801
name: etcd-manager
resources:
requests:
|
Bump etcd-manager to <I>
Relnotes are at <URL>, to better import backups or support migration
* listen-metrics-urls can now be specified and will be passed through to etcd
* improved docs around internals
|
kubernetes_kops
|
train
|
31bd6e1c2d79b5a634dc8ba9dba7f7874e78d7da
|
diff --git a/kitty/fuzzers/base.py b/kitty/fuzzers/base.py
index <HASH>..<HASH> 100644
--- a/kitty/fuzzers/base.py
+++ b/kitty/fuzzers/base.py
@@ -293,9 +293,9 @@ class BaseFuzzer(KittyObject):
self.dataman.set('template_info', template_info)
def _pre_test(self):
+ self._update_test_info()
self.session_info.current_index = self.model.current_index()
self.target.pre_test(self.model.current_index())
- self._update_test_info()
def _post_test(self):
'''
|
update test info *before* calling target pre_test
Before this fix, if the target's pre_test was not returning immediately (which
may happen if it is waiting for the victim to be alive, for example) then an
exception would be raised each time the web interface would query for the
not-yet-existing test_info.
|
cisco-sas_kitty
|
train
|
c97f77e938faac22887eeec01f7fe2d426204120
|
diff --git a/pinky/scripts/pinky_broker.py b/pinky/scripts/pinky_broker.py
index <HASH>..<HASH> 100644
--- a/pinky/scripts/pinky_broker.py
+++ b/pinky/scripts/pinky_broker.py
@@ -16,6 +16,8 @@ class StartOptions(BaseStartOptions):
"""
optParameters = [
['port', 'p', 43435, 'The port number to listen on.'],
+ ['pidfile', None, '/var/run/{}.pid'.format(SERVICE),
+ 'File for the process Id.'],
['activate-ssh-server', None, False,
'Activate an SSH server on the broker for live debuging.'],
['ssh-user', None, None, 'SSH username.'],
@@ -57,16 +59,15 @@ def _handle_manhole(user, password, port, arguments):
def handle_start_command(options):
- arguments = ['twistd']
+ arguments = [
+ 'twistd', '--pidfile={}'.format(options.subOptions.opts['pidfile'])
+ ]
nodaemon = options.subOptions.opts['nodaemon']
if nodaemon:
arguments.append('--nodaemon')
- arguments.append('--pidfile=pinky_broker.pid')
else:
arguments.append('--syslog')
- # arguments.append('--pidfile=/var/run/{}.pid'.format(service))
- arguments.append('--pidfile=pinky_broker.pid')
arguments.append('--prefix=pinky-broker')
arguments.append(SERVICE)
diff --git a/pinky/scripts/pinky_node.py b/pinky/scripts/pinky_node.py
index <HASH>..<HASH> 100644
--- a/pinky/scripts/pinky_node.py
+++ b/pinky/scripts/pinky_node.py
@@ -16,6 +16,8 @@ class StartOptions(BaseStartOptions):
"""
optParameters = [
['port', 'p', None, 'The port number to listen on.'],
+ ['pidfile', None, '/var/run/{}.pid'.format(SERVICE),
+ 'File for the process Id.'],
['broker_host', 'h', None, 'The broker host to connect to.'],
['broker_port', 'p', 43435, 'The broker port to connect to.']
]
@@ -39,7 +41,9 @@ class Options(usage.Options):
def handle_start_command(options):
- arguments = ['twistd']
+ arguments = [
+ 'twistd', '--pidfile={}'.format(options.subOptions.opts['pidfile'])
+ ]
port = options.subOptions.opts['port']
broker_host = options.subOptions.opts['broker_host']
@@ -54,11 +58,8 @@ def handle_start_command(options):
nodaemon = options.subOptions.opts['nodaemon']
if nodaemon:
arguments.append('--nodaemon')
- arguments.append('--pidfile=pinky_node.pid')
else:
arguments.append('--syslog')
- # arguments.append('--pidfile=/var/run/pinky_node.pid')
- arguments.append('--pidfile=pinky_node.pid')
arguments.append('--prefix=pinky-node')
arguments.append(SERVICE)
|
Added pid key valaue to node and broker command line tool
|
dr4ke616_pinky
|
train
|
f0c8b0f90a8d5395748968662dfbed31893c870a
|
diff --git a/src/index.js b/src/index.js
index <HASH>..<HASH> 100644
--- a/src/index.js
+++ b/src/index.js
@@ -17,8 +17,9 @@ module.exports = {
buildFileResult : callback => pageFiles.map(file => {
file.content = processContent(file.content, file.path, options.jsonInput || {});
- // correct any unknown tags that were modified
- file.content = file.content.replace(/<!--!#/g, '<!--#');
+ // When an unknown tag is found it is changed to <!--!unknwn-tag# so that it doesn't
+ // continually get found. This will undo those changes
+ file.content = file.content.replace(/<!--!unknwn-tag#/g, '<!--#');
file.processed = true;
if(callback)
diff --git a/src/tags/index.js b/src/tags/index.js
index <HASH>..<HASH> 100644
--- a/src/tags/index.js
+++ b/src/tags/index.js
@@ -149,7 +149,7 @@ function processSplitArray(splitArr, path, jsonContext) {
}
else {
console.error('An unidentified tag is being used: ' + fragment);
- splitArr[i] = fragment.replace('<!--#', '<!--!#');
+ splitArr[i] = fragment.replace('<!--#', '<!--!unknwn-tag#');
}
pathStack = path;
|
changing how unknown tags are renamed in order to prevent accidental tampering with tags users have put in that are close to includer's tagging
|
internetErik_gulp-htmlincluder
|
train
|
11ab088315d169259a0b1b3b3023a9a2ac4d1b16
|
diff --git a/director/lib/director.rb b/director/lib/director.rb
index <HASH>..<HASH> 100644
--- a/director/lib/director.rb
+++ b/director/lib/director.rb
@@ -15,6 +15,7 @@ require "yaml"
require "bcrypt"
require "blobstore_client"
+require "duration"
require "eventmachine"
require "netaddr"
require "resque"
diff --git a/director/lib/director/jobs/base_job.rb b/director/lib/director/jobs/base_job.rb
index <HASH>..<HASH> 100644
--- a/director/lib/director/jobs/base_job.rb
+++ b/director/lib/director/jobs/base_job.rb
@@ -19,6 +19,7 @@ module Bosh::Director
Config.cloud_options = cloud_options
end
+ started = Time.now
with_thread_name("task:#{task_id}") do
begin
logger.info("Creating job")
@@ -43,6 +44,8 @@ module Bosh::Director
task.save
end
end
+ ended = Time.now
+ logger.info("Task took #{Duration.new(ended - started)} to process.")
end
end
|
added task duration to the task logs
|
cloudfoundry_bosh
|
train
|
124e42976f60addd1596f45489eb8073dbac2651
|
diff --git a/audiomate/corpus/io/mozilla_deepspeech.py b/audiomate/corpus/io/mozilla_deepspeech.py
index <HASH>..<HASH> 100644
--- a/audiomate/corpus/io/mozilla_deepspeech.py
+++ b/audiomate/corpus/io/mozilla_deepspeech.py
@@ -56,7 +56,7 @@ class MozillaDeepSpeechWriter(base.CorpusWriter):
records = []
- subset_utterance_ids = {idx: list(subset.utterances.keys()) for idx, subset in corpus.subviews.items()}
+ subset_utterance_ids = {idx: set(subset.utterances.keys()) for idx, subset in corpus.subviews.items()}
subset_records = collections.defaultdict(list)
for utterance_idx in sorted(corpus.utterances.keys()):
|
DeepSpeech Writer: Use set instead of list to improve performance
|
ynop_audiomate
|
train
|
54148cf38eeff49fda4b4eb440ff4fa11426a4c4
|
diff --git a/tests/test_compare_algorithms.py b/tests/test_compare_algorithms.py
index <HASH>..<HASH> 100644
--- a/tests/test_compare_algorithms.py
+++ b/tests/test_compare_algorithms.py
@@ -614,6 +614,9 @@ class TestCompareAlgorithms(unittest.TestCase):
['Anne'],
['Elizabeth'],
['Sarah'],
+ ['University of Waterloo'],
+ ['tyler'],
+ ['Betty']
],
columns=['str_1'])
self.E.index.name = 'index_df5'
@@ -629,6 +632,9 @@ class TestCompareAlgorithms(unittest.TestCase):
['Jill'],
['Elisabeth'],
['Sarrrrah'],
+ ['University Waterloo'],
+ ['Betty'],
+ ['tyler']
],
columns=['str_2'])
self.F.index.name = 'index_df6'
@@ -646,13 +652,13 @@ class TestCompareAlgorithms(unittest.TestCase):
comp.string('str_1', 'str_2', method='smith_waterman', norm='max', gap_continue=-5, name='max_2')
comp.string('str_1', 'str_2', method='smith_waterman', norm='mean', gap_continue=-5, name='mean_2')
- expected_min_1 = pandas.Series([0, 0, 0, 0, 0, 0, 1, 0, 7/9, 3.6/5])
- expected_max_1 = pandas.Series([0, 0, 0, 0, 0, 0, 1, 0, 7/9, 3.6/8])
- expected_mean_1 = pandas.Series([0, 0, 0, 0, 0, 0, 1, 0, 7/9, 3.6/6.5])
+ expected_min_1 = pandas.Series([0, 0, 0, 0, 0, 0, 1, 0, 7/9, 3.6/5, 17.6/19, 2/5, 2/5])
+ expected_max_1 = pandas.Series([0, 0, 0, 0, 0, 0, 1, 0, 7/9, 3.6/8, 17.6/22, 2/5, 2/5])
+ expected_mean_1 = pandas.Series([0, 0, 0, 0, 0, 0, 1, 0, 7/9, 3.6/6.5, 17.6/20.5, 2/5, 2/5])
- expected_min_2 = pandas.Series([0, 0, 0, 0, 0, 0, 1, 0, 7/9, 3/5])
- expected_max_2 = pandas.Series([0, 0, 0, 0, 0, 0, 1, 0, 7/9, 3/8])
- expected_mean_2 = pandas.Series([0, 0, 0, 0, 0, 0, 1, 0, 7/9, 3/6.5])
+ expected_min_2 = pandas.Series([0, 0, 0, 0, 0, 0, 1, 0, 7/9, 3/5, 16/19, 2/5, 2/5])
+ expected_max_2 = pandas.Series([0, 0, 0, 0, 0, 0, 1, 0, 7/9, 3/8, 16/22, 2/5, 2/5])
+ expected_mean_2 = pandas.Series([0, 0, 0, 0, 0, 0, 1, 0, 7/9, 3/6.5, 16/20.5, 2/5, 2/5])
SW_TEST_CASES = [
(comp.vectors['min_1'], expected_min_1, 'min_1'),
|
Added a few more correctness tests for smithwaterman()
|
J535D165_recordlinkage
|
train
|
99b6d3fef91200d7296c2e92aff539d0b1039279
|
diff --git a/lib/autokey/model/phrase.py b/lib/autokey/model/phrase.py
index <HASH>..<HASH> 100644
--- a/lib/autokey/model/phrase.py
+++ b/lib/autokey/model/phrase.py
@@ -47,7 +47,7 @@ class Phrase(AbstractAbbreviation, AbstractHotkey, AbstractWindowFilter):
self.matchCase = False
self.parent = None
self.show_in_tray_menu = False
- self.sendMode = SendMode.KEYBOARD
+ self.sendMode = SendMode.CB_CTRL_V
self.path = path
def build_path(self, base_name=None):
|
Change the default sendmode for phrases
Changes the default send mode for phrases from the keyboard to ctrl-V method. Per Joe's suggestion in #<I>
|
autokey_autokey
|
train
|
061d51fc2aaa91a7332306c67a0480a806b7457b
|
diff --git a/bfg9000/file_types.py b/bfg9000/file_types.py
index <HASH>..<HASH> 100644
--- a/bfg9000/file_types.py
+++ b/bfg9000/file_types.py
@@ -52,5 +52,5 @@ class SharedLibrary(Library):
yield self
# Used for Windows DLL files, which aren't linked to directly.
-class DllLibrary(Library):
+class DllLibrary(Binary):
pass
|
Treat DLLs as non-libraries (so they get installed into bin/)
|
jimporter_bfg9000
|
train
|
e5ff3084dc7e788c430344004cf8e59670892781
|
diff --git a/packages/cozy-client/src/CozyClient.js b/packages/cozy-client/src/CozyClient.js
index <HASH>..<HASH> 100644
--- a/packages/cozy-client/src/CozyClient.js
+++ b/packages/cozy-client/src/CozyClient.js
@@ -10,6 +10,7 @@
import StackLink from './StackLink'
import {
create as createAssociation,
+ getClass as getAssociationClass,
dehydrateDoc,
associationsFromModel,
responseToRelationship
@@ -379,19 +380,10 @@ export default class CozyClient {
}
}
- queryDocumentAssociation(document, association) {
- const { type, doctype, query } = association
- switch (type) {
- case 'has-many':
- if (query) {
- return query(this, association)(document)
- } else {
- const queryAll = this.find(doctype)
- return queryAll.referencedBy(document)
- }
- default:
- throw new Error(`Can't handle '${type}' associations`)
- }
+ queryDocumentAssociation(document, schemaAssociation) {
+ const { type, doctype } = schemaAssociation
+ const associationCls = getAssociationClass(doctype, type)
+ return associationCls.query(document, this, schemaAssociation)
}
async requestMutation(definition) {
diff --git a/packages/cozy-client/src/associations/Association.js b/packages/cozy-client/src/associations/Association.js
index <HASH>..<HASH> 100644
--- a/packages/cozy-client/src/associations/Association.js
+++ b/packages/cozy-client/src/associations/Association.js
@@ -1,3 +1,7 @@
export default class Association {
constructor() {}
+
+ static query() {
+ throw new Error('A custom relationship must define its query() function')
+ }
}
diff --git a/packages/cozy-client/src/associations/HasManyAssociation.js b/packages/cozy-client/src/associations/HasManyAssociation.js
index <HASH>..<HASH> 100644
--- a/packages/cozy-client/src/associations/HasManyAssociation.js
+++ b/packages/cozy-client/src/associations/HasManyAssociation.js
@@ -1,4 +1,5 @@
import Association from './Association'
+import { QueryDefinition } from '../dsl'
const empty = () => ({
data: [],
@@ -83,4 +84,9 @@ export default class HasManyAssociation extends Association {
}
}
}
+
+ static query(document, client, assoc) {
+ const ids = document[assoc.name]
+ return new QueryDefinition({ doctype: assoc.doctype, ids })
+ }
}
diff --git a/packages/cozy-client/src/associations/HasManyFilesAssociation.js b/packages/cozy-client/src/associations/HasManyFilesAssociation.js
index <HASH>..<HASH> 100644
--- a/packages/cozy-client/src/associations/HasManyFilesAssociation.js
+++ b/packages/cozy-client/src/associations/HasManyFilesAssociation.js
@@ -61,4 +61,9 @@ export default class HasManyFilesAssociation extends HasManyAssociation {
removeDocuments(referencedDocs) {
return Mutations.removeReferencesTo(this.target, referencedDocs)
}
+
+ static query(document, client, assoc) {
+ const queryAll = client.find(assoc.doctype)
+ return queryAll.referencedBy(document)
+ }
}
|
feat: Association is in charge of defining query
|
cozy_cozy-client
|
train
|
572423c9d8590d719e1bd0c67837087ff9785dd3
|
diff --git a/lib/how_is/sources/github/issue_fetcher.rb b/lib/how_is/sources/github/issue_fetcher.rb
index <HASH>..<HASH> 100644
--- a/lib/how_is/sources/github/issue_fetcher.rb
+++ b/lib/how_is/sources/github/issue_fetcher.rb
@@ -52,6 +52,7 @@ module HowIs
@user, @repo = @repository.split("/", 2)
@start_date = issues_source.start_date
@end_date = issues_source.end_date
+ @type = issues_source.type
end
def data
@@ -62,9 +63,8 @@ module HowIs
HowIs::Text.print "Fetching #{@repository} #{@issues_source.pretty_type} data."
- @data = @cache.cached(type) do
+ @data = @cache.cached("fetch-#{type}") do
data = []
- after = nil
after, data = fetch_issues(after, data) until after == END_LOOP
data.select(&method(:issue_is_relevant?))
end
|
Fix issue with type missing from the constructor
|
duckinator_inq
|
train
|
10cc045fa8b8b7d1701ed165f323f6d06ac6aa44
|
diff --git a/transit/writer.py b/transit/writer.py
index <HASH>..<HASH> 100644
--- a/transit/writer.py
+++ b/transit/writer.py
@@ -110,9 +110,9 @@ class Marshaler(object):
def emit_boolean(self, b, as_map_key, cache):
return self.emit_string(ESC, "?", b, True, cache) if as_map_key else self.emit_object(b)
- def emit_int(self, i, as_map_key, cache):
+ def emit_int(self, tag, i, as_map_key, cache):
if as_map_key or i > self.opts["max_int"] or i < self.opts["min_int"]:
- return self.emit_string(ESC, "i", str(i), as_map_key, cache)
+ return self.emit_string(ESC, tag, str(i), as_map_key, cache)
else:
return self.emit_object(i, as_map_key)
@@ -223,7 +223,8 @@ class Marshaler(object):
marshal_dispatch = {"_": Marshaler.emit_nil,
"?": Marshaler.emit_boolean,
"s": lambda self, rep, as_map_key, cache: Marshaler.emit_string(self, "", "", rep, as_map_key, cache),
- "i": Marshaler.emit_int,
+ "i": lambda self, rep, as_map_key, cache: Marshaler.emit_int(self, "i", rep, as_map_key, cache),
+ "n": lambda self, rep, as_map_key, cache: Marshaler.emit_int(self, "n", rep, as_map_key, cache),
"d": Marshaler.emit_double,
"'": lambda self, rep, _, cache: Marshaler.emit_tagged(self, "'", rep, cache),
"array": Marshaler.emit_array,
|
Direct BigInt/Py:long through emit_int
|
cognitect_transit-python
|
train
|
ae086ed40eba9bab9b8300140a005e9b8b1aedfe
|
diff --git a/packages/cq/src/index.js b/packages/cq/src/index.js
index <HASH>..<HASH> 100644
--- a/packages/cq/src/index.js
+++ b/packages/cq/src/index.js
@@ -23,6 +23,10 @@ export const NodeTypes = {
CALL_EXPRESSION: 'CALL_EXPRESSION'
};
+const QueryResultTypes = {
+ SELECTION_EXPRESSION: 'SELECTION_EXPRESSION'
+};
+
const whitespace = new Set([' ', '\n', '\t', '\r']);
function nextNewlinePos(code, start) {
@@ -367,14 +371,20 @@ function lineNumberOfCharacterIndex(code, idx) {
function resolveListOfQueries(ast, root, code, query, engine, opts) {
return query.reduce((acc, q) => {
let resolved = resolveIndividualQuery(ast, root, code, q, engine, opts);
+
// thought: maybe do something clever here like put in a comment ellipsis if
// the queries aren't contiguous
+ // if((acc.nodes.length > 0) &&
+ // (resolved.queryType === QueryResultTypes.SELECTION_EXPRESSION)) {
+ // }
acc.code = acc.code + resolved.code;
- acc.nodes = [...acc.nodes, resolved.node];
+
+ acc.nodes = [...acc.nodes, ...(resolved.nodes || [])];
acc.start = Math.min(acc.start, resolved.start);
acc.end = Math.max(acc.end, resolved.end);
acc.start_line = Math.min(acc.start_line, lineNumberOfCharacterIndex(code, resolved.start));
acc.end_line = Math.max(acc.end_line, lineNumberOfCharacterIndex(code, resolved.end));
+
return acc;
}, {
code: '',
diff --git a/packages/cq/src/query-parser.js b/packages/cq/src/query-parser.js
index <HASH>..<HASH> 100644
--- a/packages/cq/src/query-parser.js
+++ b/packages/cq/src/query-parser.js
@@ -37,6 +37,8 @@ module.exports = (function() {
peg$startRuleFunction = peg$parsestart,
peg$c0 = function(head, tail) {
+ // TODO: potentially use this for identifying the discontinuous queries
+ // head.queryType = QueryResultTypes.SELECTION_EXPRESSION;
return buildList(head, tail, 3);
},
peg$c1 = function(head, tail) {
@@ -1108,7 +1110,7 @@ module.exports = (function() {
}
- // ideally we would load this from the other cq code, but this is less hassle for now
+ // ideally we would load this from the other cq code, but module importing here is a bit buggy
const NodeTypes = {
IDENTIFIER: 'IDENTIFIER',
RANGE: 'RANGE',
@@ -1117,6 +1119,10 @@ module.exports = (function() {
STRING: 'STRING'
};
+ const QueryResultTypes = {
+ SELECTION_EXPRESSION: 'SELECTION_EXPRESSION'
+ };
+
function extractOptional(optional, index) {
return optional ? optional[index] : null;
}
@@ -1141,6 +1147,7 @@ module.exports = (function() {
+
peg$result = peg$startRuleFunction();
if (peg$result !== peg$FAILED && peg$currPos === input.length) {
diff --git a/packages/cq/src/query.pegjs b/packages/cq/src/query.pegjs
index <HASH>..<HASH> 100644
--- a/packages/cq/src/query.pegjs
+++ b/packages/cq/src/query.pegjs
@@ -18,7 +18,7 @@
*/
{
- // ideally we would load this from the other cq code, but this is less hassle for now
+ // ideally we would load this from the other cq code, but module importing here is a bit buggy
const NodeTypes = {
IDENTIFIER: 'IDENTIFIER',
RANGE: 'RANGE',
@@ -27,6 +27,10 @@
STRING: 'STRING'
};
+ const QueryResultTypes = {
+ SELECTION_EXPRESSION: 'SELECTION_EXPRESSION'
+ };
+
function extractOptional(optional, index) {
return optional ? optional[index] : null;
}
@@ -49,6 +53,7 @@
return [head].concat(extractList(tail, index));
}
+
}
start
@@ -56,6 +61,8 @@ start
SelectionExpressions
= head:SelectionExpression tail:(ws comma ws SelectionExpression)* {
+ // TODO: potentially use this for identifying the discontinuous queries
+ // head.queryType = QueryResultTypes.SELECTION_EXPRESSION;
return buildList(head, tail, 3);
}
diff --git a/packages/cq/test/babylon.test.js b/packages/cq/test/babylon.test.js
index <HASH>..<HASH> 100644
--- a/packages/cq/test/babylon.test.js
+++ b/packages/cq/test/babylon.test.js
@@ -589,6 +589,22 @@ bootstrap(DemoApp, [
}
}
);
+
+ it.pending(
+ "should have comment separators for discontiguous queries",
+ async () => {
+ {
+ let { code } = await cq(src, ".bootstrap, .routes");
+ // console.log('code, wanted', code);
+ // const wanted = lines(src, 8, 13);
+ // assert.equal(code, wanted);
+
+ // test - normal sep case
+ // test - contig case
+ // test - getting class, then render w/ gap
+ }
+ }
+ );
});
describe("disambiguation", async () => {
|
started code for detecting discontinuous queries
|
fullstackio_cq
|
train
|
139a1582397a402bc274165415edc6d7ac09d35a
|
diff --git a/xchart/src/main/java/org/knowm/xchart/internal/chartpart/AxisTickLabels.java b/xchart/src/main/java/org/knowm/xchart/internal/chartpart/AxisTickLabels.java
index <HASH>..<HASH> 100644
--- a/xchart/src/main/java/org/knowm/xchart/internal/chartpart/AxisTickLabels.java
+++ b/xchart/src/main/java/org/knowm/xchart/internal/chartpart/AxisTickLabels.java
@@ -189,7 +189,7 @@ public class AxisTickLabels<ST extends AxesChartStyler, S extends Series> implem
int tickLabelY = tickLabelBounds.getBounds().height;
int yAlignmentOffset;
- switch (styler.getxAxisLabelAlignmentVertical()) {
+ switch (styler.getXAxisLabelAlignmentVertical()) {
case Right:
yAlignmentOffset = maxTickLabelY - tickLabelY;
break;
diff --git a/xchart/src/main/java/org/knowm/xchart/style/AxesChartStyler.java b/xchart/src/main/java/org/knowm/xchart/style/AxesChartStyler.java
index <HASH>..<HASH> 100644
--- a/xchart/src/main/java/org/knowm/xchart/style/AxesChartStyler.java
+++ b/xchart/src/main/java/org/knowm/xchart/style/AxesChartStyler.java
@@ -771,11 +771,11 @@ public abstract class AxesChartStyler extends Styler {
return this;
}
- public TextAlignment getxAxisLabelAlignmentVertical() {
+ public TextAlignment getXAxisLabelAlignmentVertical() {
return xAxisLabelAlignmentVertical;
}
- public void setxAxisLabelAlignmentVertical(TextAlignment xAxisLabelAlignmentVertical) {
+ public void setXAxisLabelAlignmentVertical(TextAlignment xAxisLabelAlignmentVertical) {
this.xAxisLabelAlignmentVertical = xAxisLabelAlignmentVertical;
}
}
|
Capitalization correction get/setxAxisAlignmentVertical -> get/setXAxisAlignmentVertical
|
knowm_XChart
|
train
|
cd897445f578beb0fbcb49d24714ef6491a5d56f
|
diff --git a/phonopy/phonon/animation.py b/phonopy/phonon/animation.py
index <HASH>..<HASH> 100644
--- a/phonopy/phonon/animation.py
+++ b/phonopy/phonon/animation.py
@@ -43,13 +43,12 @@ class Animation:
def __init__(self,
qpoint,
dynamical_matrix,
- primitive,
shift=None):
-
dynamical_matrix.set_dynamical_matrix(qpoint)
self._eigenvalues, self._eigenvectors = \
np.linalg.eigh(dynamical_matrix.get_dynamical_matrix())
self._qpoint = qpoint
+ primitive = dynamical_matrix.get_primitive()
self._positions = primitive.get_scaled_positions()
self._symbols = primitive.get_chemical_symbols()
self._masses = primitive.get_masses()
diff --git a/phonopy/phonon/band_structure.py b/phonopy/phonon/band_structure.py
index <HASH>..<HASH> 100644
--- a/phonopy/phonon/band_structure.py
+++ b/phonopy/phonon/band_structure.py
@@ -60,14 +60,13 @@ class BandStructure:
def __init__(self,
paths,
dynamical_matrix,
- cell,
is_eigenvectors=False,
is_band_connection=False,
group_velocity=None,
factor=VaspToTHz,
verbose=False):
self._dynamical_matrix = dynamical_matrix
- self._cell = cell
+ self._cell = dynamical_matrix.get_primitive()
self._factor = factor
self._is_eigenvectors = is_eigenvectors
self._is_band_connection = is_band_connection
diff --git a/phonopy/phonon/modulation.py b/phonopy/phonon/modulation.py
index <HASH>..<HASH> 100644
--- a/phonopy/phonon/modulation.py
+++ b/phonopy/phonon/modulation.py
@@ -43,7 +43,6 @@ from phonopy.harmonic.derivative_dynmat import DerivativeOfDynamicalMatrix
class Modulation:
def __init__(self,
dynamical_matrix,
- cell,
dimension,
phonon_modes,
delta_q=None,
@@ -57,7 +56,7 @@ class Modulation:
"""
self._dm = dynamical_matrix
- self._cell = cell
+ self._cell = dynamical_matrix.get_primitive()
self._phonon_modes = phonon_modes
self._dimension = dimension
self._delta_q = delta_q # 1st/2nd order perturbation direction
diff --git a/phonopy/phonon/qpoints_mode.py b/phonopy/phonon/qpoints_mode.py
index <HASH>..<HASH> 100644
--- a/phonopy/phonon/qpoints_mode.py
+++ b/phonopy/phonon/qpoints_mode.py
@@ -37,13 +37,13 @@ import cmath
from phonopy.units import VaspToTHz
def write_yaml(qpoints,
- cell,
dynamical_matrix,
nac_q_direction=None,
is_eigenvectors=False,
group_velocity=None,
write_dynamical_matrices=False,
factor=VaspToTHz):
+ cell = dynamical_matrix.get_primitive()
num_atom = cell.get_number_of_atoms()
m = cell.get_masses()
names = cell.get_chemical_symbols()
|
Remove Atoms object input because it can be obtained from DynamicalMatrix object by get_primitive().
|
atztogo_phonopy
|
train
|
0c160720a9498d1a7491d0cf77792563b375fcfd
|
diff --git a/extension/framework/library/extension.php b/extension/framework/library/extension.php
index <HASH>..<HASH> 100644
--- a/extension/framework/library/extension.php
+++ b/extension/framework/library/extension.php
@@ -120,12 +120,6 @@ class Extension extends Library {
$this->_directory = $directory;
$this->_manifest = new Storage\File( $this->_directory . 'manifest' );
-
- // TODO add custom configuration and localization object support through manifest
-
- // create and configure configuration object
- $this->_configuration = new Extension\Configuration( $this );
- $this->_localization = new Extension\Localization( $this );
}
}
}
@@ -141,11 +135,32 @@ class Extension extends Library {
if( !property_exists( $this, $iindex ) ) return parent::__get( $index );
else {
- // lazy create the logger
- if( $index == 'log' && !$this->_log ) {
- $this->_log = Log::instance( $this->_id );
- }
+ // lazy create some variable
+ switch( $index ) {
+ case 'log':
+
+ if( !$this->_log ) {
+ $this->_log = Log::instance( $this->_id );
+ }
+
+ break;
+ // TODO add custom configuration and localization object support through manifest
+ case 'configuration':
+
+ if( !$this->_configuration ) {
+ $this->_configuration = new Extension\Configuration( $this );
+ }
+
+ break;
+ case 'localization':
+
+ if( !$this->_localization ) {
+ $this->_localization = new Extension\Localization( $this );
+ }
+
+ break;
+ }
return $this->{$iindex};
}
}
@@ -162,8 +177,8 @@ class Extension extends Library {
*/
public function __clone() {
- $this->_configuration = clone $this->_configuration;
- $this->_localization = clone $this->_localization;
+ if( $this->_configuration ) $this->_configuration = clone $this->_configuration;
+ if( $this->_localization ) $this->_localization = clone $this->_localization;
}
/**
@@ -176,7 +191,7 @@ class Extension extends Library {
* @return string
*/
public function text( $index, $insertion = null, $default = '' ) {
- return $this->_localization->getPattern( $index, $insertion, $default );
+ return $this->localization->getPattern( $index, $insertion, $default );
}
/**
* Get configuration variable from extension configuration object. It's a proxy for Configuration::get() method
@@ -187,7 +202,7 @@ class Extension extends Library {
* @return mixed
*/
public function option( $index, $default = null ) {
- return $this->_configuration->get( $index, $default );
+ return $this->configuration->get( $index, $default );
}
/**
diff --git a/extension/framework/library/extension/helper.php b/extension/framework/library/extension/helper.php
index <HASH>..<HASH> 100644
--- a/extension/framework/library/extension/helper.php
+++ b/extension/framework/library/extension/helper.php
@@ -93,28 +93,10 @@ abstract class Helper {
*
* @param string[] $input
*
+ * @deprecated Use the \Framework::search() instead
* @return bool|string
*/
public static function search( array &$input ) {
-
- $name = '';
- $length = 0;
- for( $i = 0, $count = count( $input ), $tmp = ''; $i < \Framework::EXTENSION_DEPTH && $i < $count; ++$i ) {
-
- // check if this path is an extension: check existance of the extension directory
- $tmp .= ( $i > 0 ? \Framework::EXTENSION_SEPARATOR : '' ) . mb_strtolower( $input[ $i ] );
- if( self::exist( $tmp, true ) ) {
-
- $length = $i + 1;
- $name = $tmp;
- }
- }
-
- if( !$length ) return '';
- else {
-
- $input = array_slice( $input, $length );
- return $name;
- }
+ return \Framework::search( $input );
}
}
diff --git a/framework.php b/framework.php
index <HASH>..<HASH> 100644
--- a/framework.php
+++ b/framework.php
@@ -237,6 +237,28 @@ class Framework {
return $name;
}
}
+ /**
+ * Get a class fully qualified name
+ *
+ * @param string $definition A fully qualified classname or an extension library with 'extension:library' syntax where the library is in dot notated format
+ * @param bool|true $validate Only return the class if it's really exists
+ *
+ * @return string|null The class fully qualified name or null if not exist and validate is true
+ */
+ public static function library( $definition, $validate = true ) {
+
+ if( !strpos( $definition, ':' ) ) $class = '\\' . trim( $definition, '\\' );
+ else {
+
+ list( $extension, $library ) = explode( ':', $definition, 2 );
+ $class = str_replace( self::EXTENSION_SEPARATOR, ' ', $extension ) . ' ' . str_replace( '.', ' ', $library );
+ if( ctype_lower( str_replace( ' ', '', $class ) ) ) $class = ucwords( $class );
+
+ $class = '\\' . str_replace( ' ', '\\', $class );
+ }
+
+ return !$validate || self::import( $class ) ? $class : null;
+ }
/**
* Add custom namespace root directory for the importer
|
other: Depricate the `Extension\Helper::search()` because it exist now in the `\Framework`
update: The `Extension`'s configuration and localization property is now lazy created
new: Create a helper named `\Framework::library()` that helps to link extension classes easier
|
spoom-php_core
|
train
|
4a90ac4774a575a8082636b6c22a4be29410f3ff
|
diff --git a/cloudfoundry-util/src/main/java/org/cloudfoundry/util/ExceptionUtils.java b/cloudfoundry-util/src/main/java/org/cloudfoundry/util/ExceptionUtils.java
index <HASH>..<HASH> 100644
--- a/cloudfoundry-util/src/main/java/org/cloudfoundry/util/ExceptionUtils.java
+++ b/cloudfoundry-util/src/main/java/org/cloudfoundry/util/ExceptionUtils.java
@@ -19,10 +19,8 @@ package org.cloudfoundry.util;
import org.cloudfoundry.client.v2.CloudFoundryException;
import reactor.core.publisher.Mono;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.List;
import java.util.function.Predicate;
+import java.util.stream.Stream;
/**
* Utilities for dealing with {@link Exception}s
@@ -69,9 +67,8 @@ public final class ExceptionUtils {
* @return {@code true} if the exception is a {@link CloudFoundryException} and its code matches
*/
public static Predicate<? super Throwable> statusCode(Integer... codes) {
- List<Integer> codesList = new ArrayList<>(Arrays.asList(codes));
-
- return t -> t instanceof CloudFoundryException && codesList.contains(((CloudFoundryException) t).getCode());
+ return t -> t instanceof CloudFoundryException &&
+ Stream.of(codes).anyMatch(candidate -> ((CloudFoundryException) t).getCode().equals(candidate));
}
}
|
Java 8 Idiom
This change updates some code to be a bit more Java 8 idiomatic.
|
cloudfoundry_cf-java-client
|
train
|
64f6d3c2cddf8d006a5d00e4842fd16e30ac8b04
|
diff --git a/mongoctl/objects/replicaset_cluster.py b/mongoctl/objects/replicaset_cluster.py
index <HASH>..<HASH> 100644
--- a/mongoctl/objects/replicaset_cluster.py
+++ b/mongoctl/objects/replicaset_cluster.py
@@ -728,7 +728,9 @@ class ReplicaSetCluster(Cluster):
}
if self.repl_set_config_settings:
- cmd["settings"] = self.repl_set_config_settings
+ settings = (current_rs_conf and current_rs_conf.get("settings")) or {}
+ settings.update(self.repl_set_config_settings)
+ cmd["settings"] = settings
return cmd
|
rs-conf: merge configured settings with existing settings instead of override
|
mongolab_mongoctl
|
train
|
eaa4ba7cb60c081d51ac28e41032757cc7545fb8
|
diff --git a/providers/github.js b/providers/github.js
index <HASH>..<HASH> 100644
--- a/providers/github.js
+++ b/providers/github.js
@@ -56,14 +56,11 @@ provider.authorization_done = function(opt, url, window, cb)
// If there is a code, proceed to get token from github
if(code)
{
- //Destroy the window
- window.destroy();
-
//Initialize the form object
var form = { client_id: opt.client_id, client_secret : opt.client_secret, state: opt.state, code: code };
//Get the token
- return request.post({ url: provider._token_url, form: form, json: true }, function(e, res, body)
+ return request({ url: provider._token_url, method: 'POST', form: form, json: true }, function(e, res, body)
{
//Check for error
if(e){ return cb(e, null); }
|
providers/github.js: removed window.destroy call
|
jmjuanes_electron-auth
|
train
|
4b4d0fe9f20e13232d75ba03fb7854392835999d
|
diff --git a/lib/grom/base.rb b/lib/grom/base.rb
index <HASH>..<HASH> 100644
--- a/lib/grom/base.rb
+++ b/lib/grom/base.rb
@@ -10,8 +10,7 @@ module Grom
def initialize(attributes)
unless attributes == {}
ttl_graph = self.class.convert_to_ttl(attributes[:graph]).gsub("'", "\\\\'")
- # self.instance_eval("def graph; self.class.create_graph_from_ttl('#{ttl_graph}') ; end")
- self.instance_eval("def graph; '#{ttl_graph}' ; end")
+ self.instance_eval("def graph; self.class.create_graph_from_ttl('#{ttl_graph}') ; end")
end
attributes.each do |k, v|
translated_key = self.class.property_translator[k]
@@ -60,21 +59,6 @@ module Grom
self.object_single_maker(graph_data)
end
- # def self.has_many_through_query(owner_object, through_class, optional=nil)
- # endpoint_url = associations_url_builder(owner_object, self.name, {optional: optional })
- # graph_data = get_graph_data(endpoint_url)
- # separated_graphs = split_by_subject(graph_data, self.name)
- # associated_objects_array = self.object_array_maker(separated_graphs[:associated_class_graph])
- # through_property_plural = create_plural_property_name(through_class)
- # self.through_getter_setter(through_property_plural)
- # associated_objects_array.each do |associated_object|
- # through_class_array = get_through_graphs(separated_graphs[:through_graph], associated_object.id).map do |graph|
- # ActiveSupport::Inflector.constantize(through_class).object_single_maker(graph)
- # end
- # associated_object.send((through_property_plural + '=').to_sym, through_class_array)
- # end
- # end
-
def self.through_getter_setter(through_property_plural)
self.class_eval("def #{through_property_plural}=(array); @#{through_property_plural} = array; end")
self.class_eval("def #{through_property_plural}; @#{through_property_plural}; end")
@@ -106,11 +90,6 @@ module Grom
hash
end
- # def self.apples(association, through_association)
- # self.has_many(through_association[:via])
- # self.class_eval("def #{association}(optional=nil); #{create_class_name(association)}.bananas(self, #{create_class_name(through_association[:via])}.new({}).class.name, optional); end")
- # end
-
def self.has_many_through_query(owner_object, through_class, optional=nil)
through_property_plural = create_plural_property_name(through_class)
endpoint_url = associations_url_builder(owner_object, self.name, {optional: optional })
|
refactored #statements_mnapper
|
ukparliament_grom
|
train
|
ca0b2694256716707d02b8592c1e2f7647b64f85
|
diff --git a/gremlin-server/src/main/java/org/apache/tinkerpop/gremlin/server/Settings.java b/gremlin-server/src/main/java/org/apache/tinkerpop/gremlin/server/Settings.java
index <HASH>..<HASH> 100644
--- a/gremlin-server/src/main/java/org/apache/tinkerpop/gremlin/server/Settings.java
+++ b/gremlin-server/src/main/java/org/apache/tinkerpop/gremlin/server/Settings.java
@@ -18,8 +18,13 @@
*/
package org.apache.tinkerpop.gremlin.server;
+import org.apache.tinkerpop.gremlin.driver.MessageSerializer;
+import org.apache.tinkerpop.gremlin.process.traversal.TraversalSource;
+import org.apache.tinkerpop.gremlin.process.traversal.TraversalStrategy;
import org.apache.tinkerpop.gremlin.server.channel.WebSocketChannelizer;
import info.ganglia.gmetric4j.gmetric.GMetric;
+import org.apache.tinkerpop.gremlin.server.util.LifeCycleHook;
+import org.apache.tinkerpop.gremlin.structure.Graph;
import org.yaml.snakeyaml.TypeDescription;
import org.yaml.snakeyaml.Yaml;
import org.yaml.snakeyaml.constructor.Constructor;
@@ -32,6 +37,7 @@ import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
+import java.util.ServiceLoader;
import java.util.UUID;
/**
@@ -170,7 +176,8 @@ public class Settings {
public List<String> plugins = new ArrayList<>();
/**
- * Custom settings for {@link org.apache.tinkerpop.gremlin.server.OpProcessor} implementations.
+ * Custom settings for {@link OpProcessor} implementations. Implementations are loaded via
+ * {@link ServiceLoader} but custom configurations can be supplied through this configuration.
*/
public List<ProcessorSettings> processors = new ArrayList<>();
@@ -250,8 +257,20 @@ public class Settings {
return yaml.loadAs(stream, Settings.class);
}
+ /**
+ * Custom configurations for any {@link OpProcessor} implementations. These settings will not be relevant
+ * unless the referenced {@link OpProcessor} is actually loaded via {@link ServiceLoader}.
+ */
public static class ProcessorSettings {
+ /**
+ * The fully qualified class name of an {@link OpProcessor} implementation.
+ */
public String className;
+
+ /**
+ * A set of configurations as expected by the {@link OpProcessor}. Consult the documentation of the
+ * {@link OpProcessor} for information on what these configurations should be.
+ */
public Map<String, Object> config;
}
@@ -259,14 +278,46 @@ public class Settings {
* Settings for the {@code ScriptEngine}.
*/
public static class ScriptEngineSettings {
+ /**
+ * A comma separated list of classes/packages to make available to the {@code ScriptEngine}.
+ */
public List<String> imports = new ArrayList<>();
+
+ /**
+ * A comma separated list of "static" imports to make available to the {@code ScriptEngine}.
+ */
public List<String> staticImports = new ArrayList<>();
+
+ /**
+ * A comma separated list of script files to execute on {@code ScriptEngine} initialization. {@link Graph} and
+ * {@link TraversalSource} instance references produced from scripts will be stored globally in Gremlin
+ * Server, therefore it is possible to use initialization scripts to add {@link TraversalStrategy} instances
+ * or create entirely new {@link Graph} instances all together. Instantiating a {@link LifeCycleHook} in a
+ * script provides a way to execute scripts when Gremlin Server starts and stops.
+ */
public List<String> scripts = new ArrayList<>();
+
+ /**
+ * A Map of configuration settings for the {@code ScriptEngine}. These settings are dependent on the
+ * {@code ScriptEngine} implementation being used.
+ */
public Map<String, Object> config = null;
}
+ /**
+ * Settings for the {@link MessageSerializer} implementations.
+ */
public static class SerializerSettings {
+ /**
+ * The fully qualified class name of the {@link MessageSerializer} implementation. This class name will be
+ * used to load the implementation from the classpath.
+ */
public String className;
+
+ /**
+ * A {@link Map} containing {@link MessageSerializer} specific configurations. Consult the
+ * {@link MessageSerializer} implementation for specifics on what configurations are expected.
+ */
public Map<String, Object> config = null;
}
|
Improve javadocs for server Settings.
|
apache_tinkerpop
|
train
|
ca60d9f2e09e97d7e46897611499dec41c6703cd
|
diff --git a/kairos/redis_backend.py b/kairos/redis_backend.py
index <HASH>..<HASH> 100644
--- a/kairos/redis_backend.py
+++ b/kairos/redis_backend.py
@@ -109,11 +109,15 @@ class RedisBackend(Timeseries):
kwargs['pipeline'] = pipe
own_pipe = True
+ ttl_batch = set()
for timestamp,names in inserts.iteritems():
for name,values in names.iteritems():
for value in values:
# TODO: support config param to flush the pipe every X inserts
- self._insert( name, value, timestamp, intervals, **kwargs )
+ self._insert( name, value, timestamp, intervals, ttl_batch=ttl_batch, **kwargs )
+
+ for ttl_args in ttl_batch:
+ pipe.expire(*ttl_args)
if own_pipe:
kwargs['pipeline'].execute()
@@ -130,12 +134,13 @@ class RedisBackend(Timeseries):
for interval,config in self._intervals.iteritems():
timestamps = self._normalize_timestamps(timestamp, intervals, config)
for tstamp in timestamps:
- self._insert_data(name, value, tstamp, interval, config, pipe)
+ self._insert_data(name, value, tstamp, interval, config, pipe,
+ ttl_batch=kwargs.get('ttl_batch'))
if 'pipeline' not in kwargs:
pipe.execute()
- def _insert_data(self, name, value, timestamp, interval, config, pipe):
+ def _insert_data(self, name, value, timestamp, interval, config, pipe, ttl_batch=None):
'''Helper to insert data into redis'''
# Calculate the TTL and abort if inserting into the past
expire, ttl = config['expire'], config['ttl'](timestamp)
@@ -155,9 +160,17 @@ class RedisBackend(Timeseries):
self._type_insert(pipe, r_key, value)
if expire:
- pipe.expire(i_key, ttl)
+ ttl_args = (i_key, ttl)
+ if ttl_batch is not None:
+ ttl_batch.add(ttl_args)
+ else:
+ pipe.expire(*ttl_args)
if not config['coarse']:
- pipe.expire(r_key, ttl)
+ ttl_args = (r_key, ttl)
+ if ttl_batch is not None:
+ ttl_batch.add(ttl_args)
+ else:
+ pipe.expire(*ttl_args)
def delete(self, name):
'''
|
Bulk inserts into Redis batch TTL calls
|
agoragames_kairos
|
train
|
4961f70e5fb08dbc407865a09732b0d223566371
|
diff --git a/src/lib/core/config.js b/src/lib/core/config.js
index <HASH>..<HASH> 100644
--- a/src/lib/core/config.js
+++ b/src/lib/core/config.js
@@ -294,7 +294,7 @@ Config.prototype.loadContractsConfigFile = function() {
}
if (newContractsConfig.deployment && 'accounts' in newContractsConfig.deployment) {
newContractsConfig.deployment.accounts.forEach((account) => {
- if (account.balance.match(unitRegex)) {
+ if (account.balance && account.balance.match(unitRegex)) {
account.balance = utils.getWeiBalanceFromString(account.balance, web3);
}
});
|
fix(@embark/core): don't expect `balance` on `accounts`
In <URL>
|
embark-framework_embark
|
train
|
d67941c8d976a4528316024597e78ee4b29160de
|
diff --git a/src/main/java/org/codehaus/plexus/components/cipher/DefaultPlexusCipher.java b/src/main/java/org/codehaus/plexus/components/cipher/DefaultPlexusCipher.java
index <HASH>..<HASH> 100644
--- a/src/main/java/org/codehaus/plexus/components/cipher/DefaultPlexusCipher.java
+++ b/src/main/java/org/codehaus/plexus/components/cipher/DefaultPlexusCipher.java
@@ -16,16 +16,13 @@ package org.codehaus.plexus.components.cipher;
* limitations under the License.
*/
-import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.Provider;
import java.security.SecureRandom;
import java.security.Security;
-import java.security.spec.AlgorithmParameterSpec;
import java.security.spec.KeySpec;
-import java.util.Date;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
@@ -35,14 +32,12 @@ import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.PBEParameterSpec;
-import javax.swing.plaf.SliderUI;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.util.encoders.Base64Encoder;
import org.codehaus.plexus.logging.AbstractLogEnabled;
import org.codehaus.plexus.personality.plexus.lifecycle.phase.Initializable;
import org.codehaus.plexus.personality.plexus.lifecycle.phase.InitializationException;
-import org.codehaus.plexus.util.StringOutputStream;
import org.codehaus.plexus.util.StringUtils;
/**
@@ -57,6 +52,7 @@ public class DefaultPlexusCipher
{
private static final String SECURITY_PROVIDER = "BC";
private static final int SALT_SIZE = 8;
+ private static final String STRING_ENCODING = "UTF8";
/**
* Encryption algorithm to use by this instance. Needs protected scope for
@@ -142,7 +138,7 @@ public class DefaultPlexusCipher
Cipher cipher = init( passPhrase, salt, true );
// Encode the string into bytes using utf-8
- byte[] utf8 = str.getBytes( "UTF8" );
+ byte[] utf8 = str.getBytes( STRING_ENCODING );
// Encrypt it
byte[] enc = cipher.doFinal( utf8 );
@@ -156,10 +152,10 @@ public class DefaultPlexusCipher
System.arraycopy( salt, 0, res, 1, saltLen );
System.arraycopy( enc, 0, res, saltLen + 1, encLen );
- StringOutputStream sout = new StringOutputStream();
- b64.encode( res, 0, res.length, sout );
+ ByteArrayOutputStream bout = new ByteArrayOutputStream( res.length*2 );
+ b64.encode( res, 0, res.length, bout );
- return sout.toString();
+ return bout.toString( STRING_ENCODING );
}
catch( Exception e )
|
thanks to bentmann: replaced locale-sensitive StringOutputStream with byte [] and utf-8 encoded String
|
sonatype_plexus-cipher
|
train
|
8994e8c841bd7777cb2a8edf694a551eb0458e35
|
diff --git a/smuggler/utils.py b/smuggler/utils.py
index <HASH>..<HASH> 100644
--- a/smuggler/utils.py
+++ b/smuggler/utils.py
@@ -39,39 +39,28 @@ def save_uploaded_file_on_disk(uploaded_file, destination_path):
def serialize_to_response(app_labels=[], exclude=[], response=None,
format=SMUGGLER_FORMAT, indent=SMUGGLER_INDENT):
- response = response or HttpResponse(mimetype='text/plain')
- # There's some funky output redirecting going on as Django >= 1.5 writes
- # to a wrapped output stream, instead of just returning the dumped output.
- stream = StringIO() # this is going to be our stdout
- # We need to fake an OutputWrapper as it's only introduced in Django 1.5
- out = lambda: None
- out.write = lambda s: stream.write(s) # this seems to be sufficient.
+ response = response or HttpResponse(content_type='text/plain')
+ stream = StringIO()
+ error_stream = StringIO()
try:
- # Now make sys.stdout our wrapped StringIO instance and start the dump.
- sys.stdout = out
dumpdata = DumpData()
- dumpdata.stdout = sys.stdout
- dumpdata.stderr = sys.stderr
- output = dumpdata.handle(*app_labels, **{
+ dumpdata.style = no_style()
+ dumpdata.execute(*app_labels, **{
'exclude': exclude,
'format': format,
'indent': indent,
'show_traceback': True,
- 'use_natural_keys': True
+ 'use_natural_keys': True,
+ 'stdout': stream,
+ 'stderr': error_stream
})
- except CommandError:
- # We expect and re-raise CommandErrors, these contain "user friendly"
- # error messages.
- raise
- else:
- if output:
- response.write(output)
- else:
- response.write(stream.getvalue())
- return response
- finally:
- # Be nice and cleanup!
- sys.stdout = sys.__stdout__
+ except SystemExit:
+ # Django 1.4's implementation of execute catches CommandErrors and
+ # then calls sys.exit(1), we circumvent this here.
+ errors = error_stream.getvalue()
+ raise CommandError(errors)
+ response.write(stream.getvalue())
+ return response
def load_requested_data(data):
diff --git a/tests/test_app/tests.py b/tests/test_app/tests.py
index <HASH>..<HASH> 100644
--- a/tests/test_app/tests.py
+++ b/tests/test_app/tests.py
@@ -50,4 +50,4 @@ class BasicDumpTestCase(TestCase):
self.assertEqual(out, self.SITE_DUMP)
def test_serialize_unknown_app_fail(self):
- self.assertRaises(CommandError, utils.serialize_to_response, 'auth')
+ self.assertRaises(CommandError, utils.serialize_to_response, ['auth'])
|
Get rid of convuluted output redirection and just pass stdout/stderr to the command.execute.
|
semente_django-smuggler
|
train
|
f13a3114e97e3822bd33f50d0991e9a8299cd2a4
|
diff --git a/hack/e2e.go b/hack/e2e.go
index <HASH>..<HASH> 100644
--- a/hack/e2e.go
+++ b/hack/e2e.go
@@ -40,6 +40,9 @@ var (
tests = flag.String("tests", "", "Run only tests in hack/e2e-suite matching this glob. Ignored if -test is set.")
root = flag.String("root", absOrDie(filepath.Clean(filepath.Join(path.Base(os.Args[0]), ".."))), "Root directory of kubernetes repository.")
verbose = flag.Bool("v", false, "If true, print all command output.")
+
+ cfgCmd = flag.String("cfg", "", "If nonempty, pass this as an argument, and call kubecfg. Implies -v.")
+ ctlCmd = flag.String("ctl", "", "If nonempty, pass this as an argument, and call kubectl. Implies -v. (-test, -cfg, -ctl are mutually exclusive)")
)
var signals = make(chan os.Signal, 100)
@@ -87,18 +90,24 @@ func main() {
}
}
- failed, passed := []string{}, []string{}
- if *tests != "" {
- failed, passed = Test()
+ failure := false
+ switch {
+ case *cfgCmd != "":
+ failure = !runBash("'kubecfg "+*cfgCmd+"'", "$KUBECFG "+*cfgCmd)
+ case *ctlCmd != "":
+ failure = !runBash("'kubectl "+*ctlCmd+"'", "$KUBECFG "+*ctlCmd)
+ case *tests != "":
+ failed, passed := Test()
+ log.Printf("Passed tests: %v", passed)
+ log.Printf("Failed tests: %v", failed)
+ failure = len(failed) > 0
}
if *down {
TearDown()
}
- log.Printf("Passed tests: %v", passed)
- log.Printf("Failed tests: %v", failed)
- if len(failed) > 0 {
+ if failure {
os.Exit(1)
}
}
|
Add handy -cfg and -ctl options to make it easy to run a kubecfg or kubectl command against your e2e cluster.
|
kubernetes_test-infra
|
train
|
f6b1f824a342602950aee0522f85d68bb7ae4810
|
diff --git a/src/Koldy/Session/Adapter/Db.php b/src/Koldy/Session/Adapter/Db.php
index <HASH>..<HASH> 100644
--- a/src/Koldy/Session/Adapter/Db.php
+++ b/src/Koldy/Session/Adapter/Db.php
@@ -151,7 +151,7 @@ class Db implements SessionHandlerInterface
* @throws \Koldy\Config\Exception
* @throws \Koldy\Exception
*/
- public function read(string $sessionid): string
+ public function read($sessionid)
{
$sess = $this->getDbData($sessionid);
@@ -176,7 +176,7 @@ class Db implements SessionHandlerInterface
* @throws \Koldy\Exception
* @throws \Koldy\Json\Exception
*/
- public function write($sessionid, $sessiondata): bool
+ public function write($sessionid, $sessiondata)
{
$adapter = $this->getAdapter();
@@ -289,11 +289,11 @@ class Db implements SessionHandlerInterface
/**
* @param int $maxlifetime
*
- * @return int
+ * @return bool
* @throws \Koldy\Config\Exception
* @throws \Koldy\Exception
*/
- public function gc(int $maxlifetime): int
+ public function gc($maxlifetime)
{
$timestamp = time() - $maxlifetime;
@@ -302,8 +302,7 @@ class Db implements SessionHandlerInterface
}
try {
- $stmt = $this->getAdapter()->delete($this->getTableName())->where('time', '<', $timestamp)->exec();
- $counter = $stmt->rowCount();
+ $this->getAdapter()->delete($this->getTableName())->where('time', '<', $timestamp)->exec();
if ($this->disableLog) {
Log::restoreTemporaryDisablement();
@@ -316,11 +315,11 @@ class Db implements SessionHandlerInterface
Log::restoreTemporaryDisablement();
}
- $counter = 0;
+ return false;
}
- return $counter;
+ return true;
}
}
diff --git a/src/Koldy/Session/Adapter/File.php b/src/Koldy/Session/Adapter/File.php
index <HASH>..<HASH> 100644
--- a/src/Koldy/Session/Adapter/File.php
+++ b/src/Koldy/Session/Adapter/File.php
@@ -46,7 +46,7 @@ class File implements SessionHandlerInterface
*
* @return bool
*/
- public function open($save_path, $sessionid): bool
+ public function open($save_path, $sessionid)
{
// we'll ignore $save_path because we have our own path from config
@@ -66,7 +66,7 @@ class File implements SessionHandlerInterface
/**
* @return bool
*/
- public function close(): bool
+ public function close()
{
return true;
}
@@ -76,7 +76,7 @@ class File implements SessionHandlerInterface
*
* @return string
*/
- public function read(string $sessionid): string
+ public function read($sessionid)
{
return (string)@file_get_contents("{$this->savePath}{$sessionid}.txt");
}
@@ -90,7 +90,7 @@ class File implements SessionHandlerInterface
* @throws \Koldy\Exception
* @throws \Koldy\Filesystem\Exception
*/
- public function write($sessionid, $sessiondata): bool
+ public function write($sessionid, $sessiondata)
{
$wasWritten = !(file_put_contents("{$this->savePath}{$sessionid}.txt", $sessiondata) === false);
@@ -111,7 +111,7 @@ class File implements SessionHandlerInterface
*
* @return bool
*/
- public function destroy($sessionid): bool
+ public function destroy($sessionid)
{
$file = "{$this->savePath}{$sessionid}.txt";
if (file_exists($file)) {
@@ -124,19 +124,17 @@ class File implements SessionHandlerInterface
/**
* @param int $maxlifetime
*
- * @return int
+ * @return bool
*/
- public function gc(int $maxlifetime): int
+ public function gc($maxlifetime)
{
- $counter = 0;
-
foreach (glob("{$this->savePath}*") as $file) {
- if (filemtime($file) + $maxlifetime < time() && file_exists($file) && unlink($file)) {
- $counter++;
+ if (filemtime($file) + $maxlifetime < time() && file_exists($file)) {
+ unlink($file);
}
}
- return $counter;
+ return true;
}
}
|
Reverted session adapters for PHP 7+ compatibility. For PHP 8 compatibility, use branch v3
|
koldy_framework
|
train
|
851a82f09ff27cb93e3620e62c6b2e1bb69be8de
|
diff --git a/src/Deployer/Recipe/Magento2Recipe.php b/src/Deployer/Recipe/Magento2Recipe.php
index <HASH>..<HASH> 100644
--- a/src/Deployer/Recipe/Magento2Recipe.php
+++ b/src/Deployer/Recipe/Magento2Recipe.php
@@ -21,6 +21,10 @@ class Magento2Recipe
{
public static function configuration()
{
+ $appDir = '';
+
+ \Deployer\set('app_dir', $appDir);
+
$sharedFiles = [
'app/etc/env.php',
];
|
[TASK] set app_dir to empty in Magento2Recipe
|
netz98_n98-deployer
|
train
|
b7a6a04caa2c6d54f205fa75d33ccf198cdc8577
|
diff --git a/mr/awsome/common.py b/mr/awsome/common.py
index <HASH>..<HASH> 100644
--- a/mr/awsome/common.py
+++ b/mr/awsome/common.py
@@ -79,10 +79,6 @@ def yesno(question, default=None, all=False):
class StartupScriptMixin(object):
- def get_config(self, overrides=None):
- return self.master.main_config.get_section_with_overrides(
- self.sectiongroupname, self.id, overrides)
-
def startup_script(self, overrides=None, debug=False):
from mr.awsome import template # avoid circular import
@@ -201,6 +197,10 @@ class BaseInstance(object):
self._conn = ssh_info['client']
return self._conn
+ def get_config(self, overrides=None):
+ return self.master.main_config.get_section_with_overrides(
+ self.sectiongroupname, self.id, overrides)
+
class Hooks(object):
def __init__(self):
diff --git a/mr/awsome/tests/test_common.py b/mr/awsome/tests/test_common.py
index <HASH>..<HASH> 100644
--- a/mr/awsome/tests/test_common.py
+++ b/mr/awsome/tests/test_common.py
@@ -1,6 +1,6 @@
from StringIO import StringIO
from mock import patch
-from mr.awsome.common import InstanceHooks, StartupScriptMixin
+from mr.awsome.common import InstanceHooks, BaseInstance, StartupScriptMixin
from mr.awsome.config import Config, StartupScriptMassager
from unittest2 import TestCase
import os
@@ -19,7 +19,7 @@ class MockMaster(object):
self.main_config = main_config
-class MockInstance(StartupScriptMixin):
+class MockInstance(BaseInstance, StartupScriptMixin):
sectiongroupname = "instance"
def __init__(self):
|
Move get_config to BaseInstance.
|
ployground_ploy
|
train
|
0eb3d1abb80d3d7524f3996d18e967bc2f91a1fe
|
diff --git a/hazelcast/src/main/java/com/hazelcast/jet/impl/pipeline/Planner.java b/hazelcast/src/main/java/com/hazelcast/jet/impl/pipeline/Planner.java
index <HASH>..<HASH> 100644
--- a/hazelcast/src/main/java/com/hazelcast/jet/impl/pipeline/Planner.java
+++ b/hazelcast/src/main/java/com/hazelcast/jet/impl/pipeline/Planner.java
@@ -203,14 +203,23 @@ public class Planner {
FunctionEx trailingMapFn = mergeMapFunctions(chain.subList(lastFlatMap, chain.size()));
String name = chain.stream().map(Transform::name).collect(Collectors.joining(", ", "fused(", ")"));
+ Transform fused;
if (flatMapFn == null) {
- return new MapTransform(name, chain.get(0).upstream().get(0), trailingMapFn);
+ fused = new MapTransform(name, chain.get(0).upstream().get(0), trailingMapFn);
} else {
if (trailingMapFn != null) {
flatMapFn = flatMapFn.andThen(t -> t.map(trailingMapFn));
}
- return new FlatMapTransform(name, chain.get(0).upstream().get(0), flatMapFn);
+ fused = new FlatMapTransform(name, chain.get(0).upstream().get(0), flatMapFn);
}
+ // if the first stage of the chain is rebalanced, then we set
+ // the rebalance flag of the created fused stage. Only consider
+ // the case when first element of the chain is rebalanced
+ // because there isn't any other case. If any stage in the
+ // middle includes rebalance, then those stages are not fused
+ // by findFusableChain().
+ fused.setRebalanceInput(0, chain.get(0).shouldRebalanceInput(0));
+ return fused;
}
@SuppressWarnings("rawtypes")
diff --git a/hazelcast/src/test/java/com/hazelcast/jet/pipeline/RebalanceBatchStageTest.java b/hazelcast/src/test/java/com/hazelcast/jet/pipeline/RebalanceBatchStageTest.java
index <HASH>..<HASH> 100644
--- a/hazelcast/src/test/java/com/hazelcast/jet/pipeline/RebalanceBatchStageTest.java
+++ b/hazelcast/src/test/java/com/hazelcast/jet/pipeline/RebalanceBatchStageTest.java
@@ -16,6 +16,7 @@
package com.hazelcast.jet.pipeline;
+import com.hazelcast.collection.IList;
import com.hazelcast.function.FunctionEx;
import com.hazelcast.jet.JetException;
import com.hazelcast.jet.Util;
@@ -30,6 +31,7 @@ import com.hazelcast.jet.datamodel.ItemsByTag;
import com.hazelcast.jet.datamodel.Tag;
import com.hazelcast.jet.datamodel.Tuple2;
import com.hazelcast.jet.datamodel.Tuple3;
+import com.hazelcast.jet.pipeline.test.TestSources;
import com.hazelcast.test.annotation.ParallelJVMTest;
import com.hazelcast.test.annotation.QuickTest;
import org.junit.Test;
@@ -64,6 +66,7 @@ import static java.util.stream.Collectors.groupingBy;
import static java.util.stream.Collectors.summingLong;
import static java.util.stream.Collectors.toList;
import static java.util.stream.StreamSupport.stream;
+import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
@@ -630,6 +633,28 @@ public class RebalanceBatchStageTest extends PipelineTestSupport {
);
}
+ @Test
+ public void twoConsecutiveRebalance() {
+ Pipeline p = Pipeline.create();
+ p.readFrom(TestSources.items(1, 2, 3, 4, 5, 6, 7, 8))
+ .rebalance()
+ .filter(simpleEvent -> true)
+ .setName("filter trues 1")
+ .filter(simpleEvent -> true)
+ .setName("filter trues 2")
+ .writeTo(SinkBuilder.sinkBuilder("sink", context -> context.jetInstance().getList("result" + context.globalProcessorIndex()))
+ .receiveFn((list, o) -> list.add(o)).build());
+
+ member.newJob(p).join();
+
+ IList<Object> result0 = member.getList("result0");
+ IList<Object> result1 = member.getList("result1");
+
+ assertThat(result0).hasSize(4);
+ assertThat(result1).hasSize(4);
+
+ }
+
@Nonnull
private static Stream<Integer> streamFromIterator(Iterator<Integer> iter) {
return stream(spliteratorUnknownSize(iter, 0), false);
|
Fix rebalance() nonfunctional before fused stages (#<I>)
* Add reproducer for rebalance in stage which is later fused
* Set the rebalance flag of fused stage
|
hazelcast_hazelcast
|
train
|
704a7e655dfbb2b3fb1678a5cd72f84de8fb57fd
|
diff --git a/matplotlib_scalebar/scalebar.py b/matplotlib_scalebar/scalebar.py
index <HASH>..<HASH> 100644
--- a/matplotlib_scalebar/scalebar.py
+++ b/matplotlib_scalebar/scalebar.py
@@ -261,7 +261,11 @@ class ScaleBar(Artist):
factor = value / newvalue
index = bisect.bisect_left(self._PREFERRED_VALUES, newvalue)
- newvalue = self._PREFERRED_VALUES[index - 1]
+ if index > 0:
+ # When we get the lowest index of the list, removing -1 will
+ # return the last index.
+ index -= 1
+ newvalue = self._PREFERRED_VALUES[index]
length_px = newvalue * factor / dx
|
Fix issue with getting the wrong preferred values for the scale bar.
|
ppinard_matplotlib-scalebar
|
train
|
d6273fdded1867aa5d525795eb20f1cd9e9b2396
|
diff --git a/acceptance/tests/direct_puppet/static_catalog_env_control.rb b/acceptance/tests/direct_puppet/static_catalog_env_control.rb
index <HASH>..<HASH> 100644
--- a/acceptance/tests/direct_puppet/static_catalog_env_control.rb
+++ b/acceptance/tests/direct_puppet/static_catalog_env_control.rb
@@ -14,7 +14,7 @@ require 'json'
@agent_manifests = {}
@catalog_files = {}
agents.each do |agent|
- hn = agent.hostname
+ hn = agent.node_name
resdir = agent.tmpdir('results')
@production_files[hn] = "#{resdir}/prod_hello_from_puppet_uri"
@canary_files[hn] = "#{resdir}/can_hello_from_puppet_uri"
@@ -179,7 +179,7 @@ modify_tk_config(master, puppetserver_config, versioned_code_settings)
step 'start puppet server'
with_puppet_running_on master, @master_opts, @coderoot do
agents.each do |agent|
- hn = agent.hostname
+ hn = agent.node_name
apply_manifest_on(master, @agent_manifests[hn], :catch_failures => true)
@@ -190,7 +190,7 @@ with_puppet_running_on master, @master_opts, @coderoot do
'agent',
'-t',
'--environment', 'production',
- '--server', master.hostname
+ '--server', master.node_name
),
:acceptable_exit_codes => [0, 2]
)
@@ -217,7 +217,7 @@ with_puppet_running_on master, @master_opts, @coderoot do
'agent',
'-t',
'--environment', 'canary',
- '--server', master.hostname
+ '--server', master.node_name
),
:acceptable_exit_codes => [0, 2]
)
@@ -265,7 +265,7 @@ step 'disable global static catalog setting'
step 'bounce server for static catalog disable setting to take effect.'
with_puppet_running_on master, @master_opts, @coderoot do
agents.each do |agent|
- hn = agent.hostname
+ hn = agent.node_name
apply_manifest_on(master, @agent_manifests[hn], :catch_failures => true)
@@ -276,7 +276,7 @@ with_puppet_running_on master, @master_opts, @coderoot do
'agent',
'-t',
'--environment', 'production',
- '--server', master.hostname
+ '--server', master.node_name
),
:acceptable_exit_codes => [0, 2]
)
@@ -303,7 +303,7 @@ with_puppet_running_on master, @master_opts, @coderoot do
'agent',
'-t',
'--environment', 'canary',
- '--server', master.hostname
+ '--server', master.node_name
),
:acceptable_exit_codes => [0, 2]
)
|
(PUP-<I>) Use beaker node_name in static cat test
This commit updates the acceptance
`direct_puppet/static_catalog_env_control` test to use the beaker
`node_name` value when referencing value for puppet catalog
validation.
Prior to this change, the test would fail if the `hostname` was
not the same as the `node_name`.
|
puppetlabs_puppet
|
train
|
badfba64015454ecc97cd002bd84859212cda96a
|
diff --git a/src/unpoly/link.js b/src/unpoly/link.js
index <HASH>..<HASH> 100644
--- a/src/unpoly/link.js
+++ b/src/unpoly/link.js
@@ -313,7 +313,7 @@ up.link = (function() {
Setting this to `false` will disable most defaults, causing
Unpoly to render a fragment without side-effects like updating history
- or scroll positions.
+ or scrolling.
@return {Promise<up.RenderResult>}
A promise that will be fulfilled when the link destination
@@ -834,7 +834,7 @@ up.link = (function() {
Setting this to `false` will disable most defaults documented below,
causing Unpoly to render a fragment without side-effects like updating history
- or scroll positions.
+ or scrolling.
@param [href]
The URL to fetch from the server.
|
Shorter wording for [up-navigate] docs
|
unpoly_unpoly
|
train
|
1e9e33b02d9256f32ecd4d3e3c12b7aa246a2a4e
|
diff --git a/lib/API.php b/lib/API.php
index <HASH>..<HASH> 100644
--- a/lib/API.php
+++ b/lib/API.php
@@ -68,12 +68,16 @@ class API {
// Optional inline attachment
if (isset($payload['inline'])) {
- $inline_attachment_path = $payload['inline'];
- $payload["inline"] = array(
- "id" => basename($inline_attachment_path),
- "data" => $this->encode_attachment($inline_attachment_path)
- );
+ if (is_string($payload['inline'])) {
+
+ $inline_attachment_path = $payload['inline'];
+
+ $payload["inline"] = array(
+ "id" => basename($inline_attachment_path),
+ "data" => $this->encode_attachment($inline_attachment_path)
+ );
+ }
}
// Optional file attachment
diff --git a/test/APITest.php b/test/APITest.php
index <HASH>..<HASH> 100644
--- a/test/APITest.php
+++ b/test/APITest.php
@@ -292,6 +292,24 @@ class APITestCase extends PHPUnit_Framework_TestCase
print 'Simple send with inline';
}
+ public function testSendWithInlineEncoded() {
+ $r = $this->api->send(
+ $this->EMAIL_ID,
+ $this->recipient,
+ array(
+ "data" => $this->data,
+ "inline" => array(
+ 'id' => basename($this->files[0]),
+ 'data' => base64_encode(file_get_contents($this->files[0]))
+ )
+ )
+ );
+
+ $this->assertSuccess($r);
+ $this->assertNotNull($r->receipt_id);
+ print 'Simple send with inline';
+ }
+
public function testSendWithFiles() {
$r = $this->api->send(
$this->EMAIL_ID,
@@ -305,7 +323,34 @@ class APITestCase extends PHPUnit_Framework_TestCase
$this->assertSuccess($r);
$this->assertNotNull($r->receipt_id);
print 'Simple send with file attachments';
- }
+ }
+
+ public function testSendWithFilesEncoded() {
+
+ $files = array(
+ array(
+ 'id' => basename($this->files[0]),
+ 'data' => base64_encode(file_get_contents($this->files[0]))
+ ),
+ array(
+ 'id' => basename($this->files[1]),
+ 'data' => base64_encode(file_get_contents($this->files[1]))
+ )
+ );
+
+ $r = $this->api->send(
+ $this->EMAIL_ID,
+ $this->recipient,
+ array(
+ "data" => $this->data,
+ "files" => $files
+ )
+ );
+
+ $this->assertSuccess($r);
+ $this->assertNotNull($r->receipt_id);
+ print 'Simple send with file attachments';
+ }
public function testSendWithTags() {
$r = $this->api->send(
|
Added possibility to provide inline encoded file to the API
Added test cases
|
sendwithus_sendwithus_php
|
train
|
240986f37d770315b8fe8a0965efa099c396439a
|
diff --git a/lib/searchkick/query.rb b/lib/searchkick/query.rb
index <HASH>..<HASH> 100644
--- a/lib/searchkick/query.rb
+++ b/lib/searchkick/query.rb
@@ -132,21 +132,23 @@ module Searchkick
pp options
puts
- puts "Model Search Data"
- begin
- pp klass.first(3).map { |r| {index: searchkick_index.record_data(r).merge(data: searchkick_index.send(:search_data, r))}}
- rescue => e
- puts "#{e.class.name}: #{e.message}"
- end
- puts
+ if searchkick_index
+ puts "Model Search Data"
+ begin
+ pp klass.first(3).map { |r| {index: searchkick_index.record_data(r).merge(data: searchkick_index.send(:search_data, r))}}
+ rescue => e
+ puts "#{e.class.name}: #{e.message}"
+ end
+ puts
- puts "Elasticsearch Mapping"
- puts JSON.pretty_generate(searchkick_index.mapping)
- puts
+ puts "Elasticsearch Mapping"
+ puts JSON.pretty_generate(searchkick_index.mapping)
+ puts
- puts "Elasticsearch Settings"
- puts JSON.pretty_generate(searchkick_index.settings)
- puts
+ puts "Elasticsearch Settings"
+ puts JSON.pretty_generate(searchkick_index.settings)
+ puts
+ end
puts "Elasticsearch Query"
puts to_curl
|
Fixed debug option with multiple models - #<I> [skip ci]
|
ankane_searchkick
|
train
|
93d078610b2739c611a729e9811b4c4fcd005f03
|
diff --git a/api/service/handler.go b/api/service/handler.go
index <HASH>..<HASH> 100644
--- a/api/service/handler.go
+++ b/api/service/handler.go
@@ -90,6 +90,11 @@ func CreateInstanceHandler(w http.ResponseWriter, r *http.Request, u *auth.User)
}
instance := ""
if s.Bootstrap["when"] == OnNewInstance {
+ _, err := ec2.Conn()
+ if err != nil {
+ log.Print("Got error while connecting with ec2:")
+ log.Print(err.Error())
+ }
instance, err = ec2.RunInstance(s.Bootstrap["ami"], "") //missing user data
if err != nil {
msg := fmt.Sprintf("Instance for service could not be created. \nError: %s", err.Error())
diff --git a/api/service/suite_test.go b/api/service/suite_test.go
index <HASH>..<HASH> 100644
--- a/api/service/suite_test.go
+++ b/api/service/suite_test.go
@@ -108,4 +108,6 @@ func (s *S) reconfEc2Srv(c *C) {
region := aws.Region{EC2Endpoint: s.ec2Srv.URL()}
auth := aws.Auth{AccessKey: "blaa", SecretKey: "blee"}
tsuruEC2.EC2 = ec2.New(auth, region)
+ tsuruEC2.Auth = &auth
+ tsuruEC2.Region = ®ion
}
|
Refactoring service api to fit changes in ec2 package
|
tsuru_tsuru
|
train
|
4a6ad53502757cc578cde3569cb9d72e73d50a7c
|
diff --git a/lib/smartcoin/util.rb b/lib/smartcoin/util.rb
index <HASH>..<HASH> 100644
--- a/lib/smartcoin/util.rb
+++ b/lib/smartcoin/util.rb
@@ -8,7 +8,9 @@ module SmartCoin
}
def self.get_object_type(type)
- OBJECT_TYPES[type]
+ object_type = SmartCoin::SmartCoinObject
+ object_type = OBJECT_TYPES[type] if OBJECT_TYPES[type]
+ object_type
end
end
end
diff --git a/test/smartcoin/charge_spec.rb b/test/smartcoin/charge_spec.rb
index <HASH>..<HASH> 100644
--- a/test/smartcoin/charge_spec.rb
+++ b/test/smartcoin/charge_spec.rb
@@ -24,6 +24,8 @@ describe SmartCoin::Charge do
expect(charge.captured).to be_true
expect(charge.card.id).to match(/card_(.*)/)
expect(charge.card.type).to eq('Visa')
+ expect(charge.fees).to have_at_least(2).items
+ expect(charge.fees.first.type).to eq('SmartCoin fee: flat')
end
it 'should retrieve a charge that has already created' do
|
BugFix: Allow to create SmartCoin Object when receive a object that is not specified in Util#get_object_type
|
smartcoinpayments_smartcoin-ruby
|
train
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.