hash
stringlengths 40
40
| diff
stringlengths 131
114k
| message
stringlengths 7
980
| project
stringlengths 5
67
| split
stringclasses 1
value |
|---|---|---|---|---|
4fdb02f33c7d38535984c1dad7a58346b0a08c5b
|
diff --git a/views/js/uiForm.js b/views/js/uiForm.js
index <HASH>..<HASH> 100644
--- a/views/js/uiForm.js
+++ b/views/js/uiForm.js
@@ -34,7 +34,7 @@ define([
var self = this;
this.counter = 0;
this.initFormPattern = new RegExp(['search', 'authoring', 'Import', 'Export', 'IO', 'preview'].join('|'));
- this.initGenerisFormPattern = new RegExp(['add', 'edit', 'mode'].join('|'), 'i');
+ this.initGenerisFormPattern = new RegExp(['add', 'edit', 'mode', 'PropertiesAuthoring'].join('|'), 'i');
this.initTranslationFormPattern = /translate/;
this.initNav();
@@ -325,7 +325,6 @@ define([
return $wantedPanel;
}());
-
$.ajax({
type: "GET",
url: tabUrl,
@@ -369,7 +368,7 @@ define([
e.preventDefault();
property.add($("#id").val(), helpers._url('addClassProperty', 'PropertiesAuthoring', 'tao'));
});
-
+
$(".property-mode").off('click').on('click', function () {
var $btn = $(this),
mode = 'simple';
|
Ensure uiForm js is included on PropertiesAuthoring
|
oat-sa_tao-core
|
train
|
7281ac8d98710638dced51ee7c10817267eb30d7
|
diff --git a/metal/mmtl/aws/mmtl_aws.py b/metal/mmtl/aws/mmtl_aws.py
index <HASH>..<HASH> 100644
--- a/metal/mmtl/aws/mmtl_aws.py
+++ b/metal/mmtl/aws/mmtl_aws.py
@@ -54,7 +54,7 @@ parser.add_argument("--aws_access_key_id", required=True)
parser.add_argument("--aws_secret_access_key", required=True)
parser.add_argument("--region", default="us-east-1")
parser.add_argument("--n_machines", default=2, type=int)
-parser.add_argument("--n_trials", default=2, type=int)
+parser.add_argument("--n_trials", default=None, type=int)
parser.add_argument("--keypath", required=True)
parser.add_argument("--outputpath", default="output")
parser.add_argument("--instance_type", default="t2.medium")
|
Default n_trials to None in MMTL-AWS so it goes through all possible discrete combs
|
HazyResearch_metal
|
train
|
72eb316d21e62bd4019c37a6df672a11e37e0646
|
diff --git a/lib/Doctrine/Common/Annotations/DocParser.php b/lib/Doctrine/Common/Annotations/DocParser.php
index <HASH>..<HASH> 100644
--- a/lib/Doctrine/Common/Annotations/DocParser.php
+++ b/lib/Doctrine/Common/Annotations/DocParser.php
@@ -684,6 +684,13 @@ final class DocParser
// check if we have an annotation
$name = $this->Identifier();
+ if ($this->lexer->isNextToken(DocLexer::T_MINUS)
+ && $this->lexer->nextTokenIsAdjacent()
+ ) {
+ // Annotations with dashes, such as "@foo-" or "@foo-bar", are to be discarded
+ return false;
+ }
+
// only process names which are not fully qualified, yet
// fully qualified names must start with a \
$originalName = $name;
diff --git a/tests/Doctrine/Tests/Common/Annotations/DocParserTest.php b/tests/Doctrine/Tests/Common/Annotations/DocParserTest.php
index <HASH>..<HASH> 100644
--- a/tests/Doctrine/Tests/Common/Annotations/DocParserTest.php
+++ b/tests/Doctrine/Tests/Common/Annotations/DocParserTest.php
@@ -852,7 +852,7 @@ DOCBLOCK;
'@Doctrine\Tests\Common\Annotations\Fixtures\AnnotationWithConstants(Doctrine\Tests\Common\Annotations\Fixtures\AnnotationWithConstants::class)',
AnnotationWithConstants::class
];
- return $provider;
+ return array_combine(array_column($provider, 0), $provider);
}
/**
@@ -1381,6 +1381,23 @@ DOCBLOCK;
self::assertCount(1, $result);
}
+
+ public function testWillNotParseAnnotationSucceededByAnImmediateDash()
+ {
+ $parser = $this->createTestParser();
+
+ self::assertEmpty($parser->parse('@SomeAnnotationClassNameWithoutConstructorAndProperties-'));
+ }
+
+ public function testWillParseAnnotationSucceededByANonImmediateDash()
+ {
+ $result = $this
+ ->createTestParser()
+ ->parse('@SomeAnnotationClassNameWithoutConstructorAndProperties -');
+
+ self::assertCount(1, $result);
+ self::assertInstanceOf(SomeAnnotationClassNameWithoutConstructorAndProperties::class, $result[0]);
+ }
}
/** @Annotation */
|
Skip parsing of annotations immediately followed by `T_MINUS` ("-")
|
doctrine_annotations
|
train
|
7ea9d0f75bbd60f3bcae50d9cf7648d46979e0ba
|
diff --git a/gulpfile.js b/gulpfile.js
index <HASH>..<HASH> 100644
--- a/gulpfile.js
+++ b/gulpfile.js
@@ -28,6 +28,7 @@ const gutil = require('gulp-util');
const header = require('gulp-header');
const jsdoc = require('gulp-jsdoc3');
const through = require('through2');
+const merge = require('merge-stream');
// Rollup
const { rollup } = require('rollup');
@@ -329,8 +330,10 @@ gulp.task('sass:compiled', () => {
.pipe(browserSync.stream({ match: '**/*.css' }));
}
- buildStyles(); // Expanded CSS
- buildStyles(true); // Minified CSS
+ return merge(
+ buildStyles(), // Expanded CSS
+ buildStyles(true) // Minified CSS
+ );
});
gulp.task('sass:dev', () =>
|
chore(build): wait for finishing Sass build (#<I>)
Before its Gulp task finishes.
|
carbon-design-system_carbon-components
|
train
|
152b411b53126aa66a256346110ad97621968ece
|
diff --git a/src/Gateway.php b/src/Gateway.php
index <HASH>..<HASH> 100644
--- a/src/Gateway.php
+++ b/src/Gateway.php
@@ -558,9 +558,15 @@ class Gateway extends Worker
$this->_clientConnections[$data['connection_id']]->send($data['body']);
}
return;
- // 关闭客户端连接,Gateway::closeClient($client_id);
+ // 踢出用户,Gateway::closeClient($client_id, $message);
case GatewayProtocol::CMD_KICK:
if (isset($this->_clientConnections[$data['connection_id']])) {
+ $this->_clientConnections[$data['connection_id']]->close($data['body']);
+ }
+ return;
+ // 立即销毁用户连接, Gateway::destroyClient($client_id);
+ case GatewayProtocol::CMD_DESTROY:
+ if (isset($this->_clientConnections[$data['connection_id']])) {
$this->_clientConnections[$data['connection_id']]->destroy();
}
return;
diff --git a/src/Lib/Gateway.php b/src/Lib/Gateway.php
index <HASH>..<HASH> 100644
--- a/src/Lib/Gateway.php
+++ b/src/Lib/Gateway.php
@@ -407,15 +407,16 @@ class Gateway
}
/**
- * 关闭某个客户端
+ * 踢掉某个客户端,并以$message通知被踢掉客户端
*
* @param int $client_id
+ * @param string $message
* @return bool
*/
- public static function closeClient($client_id)
+ public static function closeClient($client_id, $message = null)
{
if ($client_id === Context::$client_id) {
- return self::closeCurrentClient();
+ return self::closeCurrentClient($message);
} // 不是发给当前用户则使用存储中的地址
else {
$address_data = Context::clientIdToAddress($client_id);
@@ -423,22 +424,60 @@ class Gateway
return false;
}
$address = long2ip($address_data['local_ip']) . ":{$address_data['local_port']}";
- return self::kickAddress($address, $address_data['connection_id']);
+ return self::kickAddress($address, $address_data['connection_id'], $message);
}
}
/**
- * 踢掉当前客户端
+ * 踢掉当前客户端,并以$message通知被踢掉客户端
*
+ * @param string $message
* @return bool
* @throws Exception
*/
- public static function closeCurrentClient()
+ public static function closeCurrentClient($message = null)
{
if (!Context::$connection_id) {
throw new Exception('closeCurrentClient can not be called in async context');
}
- return self::kickAddress(long2ip(Context::$local_ip) . ':' . Context::$local_port, Context::$connection_id);
+ $address = long2ip(Context::$local_ip) . ':' . Context::$local_port;
+ return self::kickAddress($address, Context::$connection_id, $message);
+ }
+
+ /**
+ * 踢掉某个客户端并直接立即销毁相关连接
+ *
+ * @param int $client_id
+ * @return bool
+ */
+ public static function destoryClient($client_id)
+ {
+ if ($client_id === Context::$client_id) {
+ return self::destoryCurrentClient();
+ } // 不是发给当前用户则使用存储中的地址
+ else {
+ $address_data = Context::clientIdToAddress($client_id);
+ if (!$address_data) {
+ return false;
+ }
+ $address = long2ip($address_data['local_ip']) . ":{$address_data['local_port']}";
+ return self::destroyAddress($address, $address_data['connection_id']);
+ }
+ }
+
+ /**
+ * 踢掉当前客户端并直接立即销毁相关连接
+ *
+ * @return bool
+ * @throws Exception
+ */
+ public static function destoryCurrentClient()
+ {
+ if (!Context::$connection_id) {
+ throw new Exception('destoryCurrentClient can not be called in async context');
+ }
+ $address = long2ip(Context::$local_ip) . ':' . Context::$local_port;
+ return self::destroyAddress($address, Context::$connection_id);
}
/**
@@ -791,11 +830,27 @@ class Gateway
* @param int $connection_id
* @return bool
*/
- protected static function kickAddress($address, $connection_id)
+ protected static function kickAddress($address, $connection_id, $message)
{
$gateway_data = GatewayProtocol::$empty;
$gateway_data['cmd'] = GatewayProtocol::CMD_KICK;
$gateway_data['connection_id'] = $connection_id;
+ $gateway_data['body'] = $message;
+ return self::sendToGateway($address, $gateway_data);
+ }
+
+ /**
+ * 销毁某个网关的 socket
+ *
+ * @param string $address
+ * @param int $connection_id
+ * @return bool
+ */
+ protected static function destroyAddress($address, $connection_id)
+ {
+ $gateway_data = GatewayProtocol::$empty;
+ $gateway_data['cmd'] = GatewayProtocol::CMD_DESTROY;
+ $gateway_data['connection_id'] = $connection_id;
return self::sendToGateway($address, $gateway_data);
}
diff --git a/src/Protocols/GatewayProtocol.php b/src/Protocols/GatewayProtocol.php
index <HASH>..<HASH> 100644
--- a/src/Protocols/GatewayProtocol.php
+++ b/src/Protocols/GatewayProtocol.php
@@ -51,8 +51,13 @@ class GatewayProtocol
const CMD_SEND_TO_ALL = 6;
// 发给gateway的踢出用户
+ // 1、如果有待发消息,将在发送完后立即销毁用户连接
+ // 2、如果无待发消息,将立即销毁用户连接
const CMD_KICK = 7;
+ // 发给gateway的立即销毁用户连接
+ const CMD_DESTROY = 8;
+
// 发给gateway,通知用户session更新
const CMD_UPDATE_SESSION = 9;
|
support close client with a message;
add destory client method;
|
walkor_GatewayWorker
|
train
|
eed10e89771516a546017417d207ca5ebb3e1411
|
diff --git a/lib/travis/event/config.rb b/lib/travis/event/config.rb
index <HASH>..<HASH> 100644
--- a/lib/travis/event/config.rb
+++ b/lib/travis/event/config.rb
@@ -26,7 +26,7 @@ module Travis
send(:"send_on_#{event}_for?", type)
end
- def send_on_start_for?(type)
+ def send_on_started_for?(type)
config = with_fallbacks(type, :on_start, DEFAULTS[:start][type])
config == true || config == :always
end
diff --git a/spec/travis/addons/campfire/event_handler_spec.rb b/spec/travis/addons/campfire/event_handler_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/travis/addons/campfire/event_handler_spec.rb
+++ b/spec/travis/addons/campfire/event_handler_spec.rb
@@ -69,7 +69,7 @@ describe Travis::Addons::Campfire::EventHandler do
end
it 'does not trigger task if specified by the config' do
- Travis::Event::Config.any_instance.stubs(:send_on_finish?).with(:campfire).returns(true)
+ Travis::Event::Config.any_instance.stubs(:send_on_finished_for?).with(:campfire).returns(true)
task.expects(:run).with(:campfire, payload, targets: ['room'])
notify
end
diff --git a/spec/travis/addons/flowdock/event_handler_spec.rb b/spec/travis/addons/flowdock/event_handler_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/travis/addons/flowdock/event_handler_spec.rb
+++ b/spec/travis/addons/flowdock/event_handler_spec.rb
@@ -69,7 +69,7 @@ describe Travis::Addons::Flowdock::EventHandler do
end
it 'does not trigger task if specified by the config' do
- Travis::Event::Config.any_instance.stubs(:send_on_finish?).with(:flowdock).returns(true)
+ Travis::Event::Config.any_instance.stubs(:send_on_finished_for?).with(:flowdock).returns(true)
task.expects(:run).with(:flowdock, payload, targets: ['room'])
notify
end
diff --git a/spec/travis/addons/hipchat/event_handler_spec.rb b/spec/travis/addons/hipchat/event_handler_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/travis/addons/hipchat/event_handler_spec.rb
+++ b/spec/travis/addons/hipchat/event_handler_spec.rb
@@ -69,7 +69,7 @@ describe Travis::Addons::Hipchat::EventHandler do
end
it 'does not trigger task if specified by the config' do
- Travis::Event::Config.any_instance.stubs(:send_on_finish?).with(:hipchat).returns(true)
+ Travis::Event::Config.any_instance.stubs(:send_on_finished_for?).with(:hipchat).returns(true)
task.expects(:run).with(:hipchat, payload, targets: ['room'])
notify
end
diff --git a/spec/travis/addons/irc/event_handler_spec.rb b/spec/travis/addons/irc/event_handler_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/travis/addons/irc/event_handler_spec.rb
+++ b/spec/travis/addons/irc/event_handler_spec.rb
@@ -69,7 +69,7 @@ describe Travis::Addons::Irc::EventHandler do
end
it 'does not trigger task if specified by the config' do
- Travis::Event::Config.any_instance.stubs(:send_on_finish?).with(:irc).returns(true)
+ Travis::Event::Config.any_instance.stubs(:send_on_finished_for?).with(:irc).returns(true)
task.expects(:run).with(:irc, payload, channels: ['irc.freenode.net#travis'])
notify
end
diff --git a/spec/travis/addons/webhook/event_handler_spec.rb b/spec/travis/addons/webhook/event_handler_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/travis/addons/webhook/event_handler_spec.rb
+++ b/spec/travis/addons/webhook/event_handler_spec.rb
@@ -69,7 +69,7 @@ describe Travis::Addons::Webhook::EventHandler do
end
it 'does not trigger task if specified by the config' do
- Travis::Event::Config.any_instance.stubs(:send_on_finish?).with(:webhooks).returns(true)
+ Travis::Event::Config.any_instance.stubs(:send_on_finished_for?).with(:webhooks).returns(true)
task.expects(:run).with(:webhook, payload, targets: ['http://webhook.com'], token: 'token')
notify
end
diff --git a/spec/travis/event/config_spec.rb b/spec/travis/event/config_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/travis/event/config_spec.rb
+++ b/spec/travis/event/config_spec.rb
@@ -6,7 +6,7 @@ describe Travis::Event::Config do
let(:payload) { Travis::Api.data(build, for: 'event', version: 'v0') }
let(:config) { Travis::Event::Config.new(payload) }
- describe :send_on_finish? do
+ describe :send_on_finished_for? do
before :each do
build.stubs(:config => { :notifications => { :webhooks => 'http://example.com' } })
end
|
fix event/config to have send_on_started_for?
|
travis-ci_travis-core
|
train
|
639caa7eb5031c3fc275d5b3bf1f44fe3c3f2623
|
diff --git a/v2/i18n/localizer.go b/v2/i18n/localizer.go
index <HASH>..<HASH> 100644
--- a/v2/i18n/localizer.go
+++ b/v2/i18n/localizer.go
@@ -9,6 +9,15 @@ import (
)
// Localizer provides Localize and MustLocalize methods that return localized messages.
+// Localize and MustLocalize methods use a language.Tag matching algorithm based
+// on the best possible value. This algorithm may cause an unexpected language.Tag returned
+// value depending on the order of the tags stored in memory. For example, if the bundle
+// used to create a Localizer instance ingested locales following this order
+// ["en-US", "en-GB", "en-IE", "en"] and the locale "en" is asked, the underlying matching
+// algorithm will return "en-US" thinking it is the best match possible. More information
+// about the algorithm in this Github issue: https://github.com/golang/go/issues/49176.
+// There is additionnal informations inside the Go code base:
+// https://github.com/golang/text/blob/master/language/match.go#L142
type Localizer struct {
// bundle contains the messages that can be returned by the Localizer.
bundle *Bundle
|
doc(localizer): add specification about language tag detection (#<I>)
|
nicksnyder_go-i18n
|
train
|
ae13d0b2a30549220f35cf0a5abb1d6fae230ce3
|
diff --git a/.gitignore b/.gitignore
index <HASH>..<HASH> 100644
--- a/.gitignore
+++ b/.gitignore
@@ -36,6 +36,7 @@ var/
.idea/
# Visual Studio
.vs/
+.vscode/
# Local virtual environments
.virtualenv/
diff --git a/bolt/tasks/bolt_nose.py b/bolt/tasks/bolt_nose.py
index <HASH>..<HASH> 100644
--- a/bolt/tasks/bolt_nose.py
+++ b/bolt/tasks/bolt_nose.py
@@ -2,6 +2,7 @@
"""
import logging
import os.path
+import subprocess as sp
import bolt.utils as utilities
@@ -17,7 +18,7 @@ class _NoseArgumentGenerator(utilities.ArgumentsGenerator):
def _convert_config_to_arguments(self):
- self.args.append('dummy')
+ self.args.append('nosetests')
super(_NoseArgumentGenerator, self)._convert_config_to_arguments()
directory = self.config.get('directory') or DEFAULT_DIR
directory = os.path.abspath(directory)
@@ -29,16 +30,20 @@ class _NoseArgumentGenerator(utilities.ArgumentsGenerator):
def execute_nose(**kwargs):
logging.info('Executing nose')
- import nose.core
config = kwargs.get('config')
generator = _NoseArgumentGenerator()
args = generator.generate_from(config)
logging.debug('Arguments: ' + repr(args))
- try:
- nose.core.main(argv=args)
- except SystemExit as ex:
- # Nose tries to sys.exit(), so we have to intercept it.
- pass
+ result = sp.call(args)
+ # try:
+ # test_program = nose.core.TestProgram(argv=args, exit=False)
+ # result = test_program.success
+ # del(test_program)
+
+ # # nose.core.run(argv=args)
+ # except SystemExit as ex:
+ # # Nose tries to sys.exit(), so we have to intercept it.
+ # pass
diff --git a/test/test_btrunner.py b/test/test_btrunner.py
index <HASH>..<HASH> 100644
--- a/test/test_btrunner.py
+++ b/test/test_btrunner.py
@@ -71,6 +71,11 @@ class TestTaskRunner(unittest.TestCase):
self.subject.build('inexistent')
+ # def test_exits_if_task_does_not_return_zero(self):
+ # with self.assertRaises(SystemExit):
+ # self.given('failing_task')
+
+
def given(self, task_name):
self.subject.build(task_name)
self.subject.run()
diff --git a/test/test_tasks/test_bolt_nose.py b/test/test_tasks/test_bolt_nose.py
index <HASH>..<HASH> 100644
--- a/test/test_tasks/test_bolt_nose.py
+++ b/test/test_tasks/test_bolt_nose.py
@@ -73,9 +73,7 @@ class TestNoseArgumentGenerator(unittest.TestCase):
self.generated_args = self.subject.generate_from(config)
- def expect(self, expected):
- if expected:
- expected.insert(0, 'dummy')
+ def expect(self, expected):
commonitems = set(self.generated_args).intersection(expected)
self.assertEqual(len(commonitems), len(expected))
|
Fixes running nose under conttest
|
abantos_bolt
|
train
|
735771961bc04f8f7de9372297921826a814fd12
|
diff --git a/tests/common.py b/tests/common.py
index <HASH>..<HASH> 100644
--- a/tests/common.py
+++ b/tests/common.py
@@ -175,7 +175,7 @@ if hypothesis:
default_settings = hypothesis.settings(deadline=10000)
hypothesis.settings.register_profile('default', default_settings)
- ci_settings = hypothesis.settings(deadline=10000, max_examples=2500)
+ ci_settings = hypothesis.settings(deadline=20000, max_examples=1000)
hypothesis.settings.register_profile('ci', ci_settings)
expensive_settings = hypothesis.settings(deadline=None, max_examples=10000)
|
tests: tweak hypothesis CI settings
This should make things a bit faster.
|
indygreg_python-zstandard
|
train
|
531ad5c2426b1f017019a82cb39062006f8308ff
|
diff --git a/lib/puppet_library/forge/git_repository.rb b/lib/puppet_library/forge/git_repository.rb
index <HASH>..<HASH> 100644
--- a/lib/puppet_library/forge/git_repository.rb
+++ b/lib/puppet_library/forge/git_repository.rb
@@ -20,24 +20,33 @@ require 'open3'
require 'rubygems/package'
require 'puppet_library/forge/abstract'
require 'puppet_library/util/git'
+require 'puppet_library/util/temp_dir'
module PuppetLibrary::Forge
class GitRepository < PuppetLibrary::Forge::Abstract
- def initialize(git_path, version_tag_regex)
+ def initialize(url, version_tag_regex)
super(self)
- @path = File.expand_path(git_path)
+ @url = url
+ @path = PuppetLibrary::Util::TempDir.create("git-repo-cache")
@version_tag_regex = version_tag_regex
@git = PuppetLibrary::Util::Git.new(@path)
+ @mutex = Mutex.new
+ end
+
+ def destroy!
+ FileUtils.rm_rf @path
end
def get_module(author, name, version)
+ update_cache
+
return nil unless tags.include? tag_for(version)
metadata = modulefile_for(version).to_metadata
return nil unless metadata["name"] == "#{author}-#{name}"
on_tag_for(version) do
- PuppetLibrary::Archive::Archiver.archive_dir(@path, "#{metadata["name"]}-#{version}") do |archive|
+ PuppetLibrary::Archive::Archiver.archive_dir('.', "#{metadata["name"]}-#{version}") do |archive|
archive.add_file("metadata.json", 0644) do |entry|
entry.write metadata.to_json
end
@@ -46,6 +55,7 @@ module PuppetLibrary::Forge
end
def get_all_metadata
+ update_cache
tags.map do |tag|
modulefile_for_tag(tag).to_metadata
end
@@ -60,6 +70,19 @@ module PuppetLibrary::Forge
end
private
+ def update_cache
+ puts "Updating git repo cache"
+ @mutex.synchronize do
+ if File.directory? "#{@path}/.git"
+ puts " Cache already exists: fetching updates from #{@url}"
+ @git.git "fetch --tags"
+ else
+ puts " No cache yet: creating one in #{@path}"
+ @git.git "clone --bare #{@url} #{@path}/.git"
+ end
+ end
+ end
+
def tags
@git.tags.select {|tag| tag =~ @version_tag_regex }
end
diff --git a/lib/puppet_library/util/git.rb b/lib/puppet_library/util/git.rb
index <HASH>..<HASH> 100644
--- a/lib/puppet_library/util/git.rb
+++ b/lib/puppet_library/util/git.rb
@@ -41,7 +41,6 @@ module PuppetLibrary::Util
end
end
- private
def git(command, work_tree = nil)
work_tree = @path unless work_tree
Open3.popen3("git --git-dir=#{@path}/.git --work-tree=#{work_tree} #{command}") do |stdin, stdout, stderr, thread|
diff --git a/spec/forge/git_repository_spec.rb b/spec/forge/git_repository_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/forge/git_repository_spec.rb
+++ b/spec/forge/git_repository_spec.rb
@@ -53,6 +53,9 @@ module PuppetLibrary::Forge
end
let(:forge) { GitRepository.new(@@repo_path, /[0-9.]+/) }
+ after do
+ forge.destroy!
+ end
describe "#get_module" do
context "when the requested author is different from the configured author" do
|
Basic support for remote git repositories
Suboptimal caching, so it's slow
|
drrb_puppet-library
|
train
|
36c40d1a0ea8dd6997ac3c89f7977b5b746d552f
|
diff --git a/nipap/nipap/nipap.py b/nipap/nipap/nipap.py
index <HASH>..<HASH> 100644
--- a/nipap/nipap/nipap.py
+++ b/nipap/nipap/nipap.py
@@ -1842,6 +1842,10 @@ class Nipap:
if args is None:
args = {}
+ # attr must be a dict!
+ if type(attr) != dict:
+ raise NipapInputError("'attr' must be a dict")
+
# Handle Pool - find correct one and remove bad pool keys
if 'pool_id' in attr or 'pool_name' in attr:
if 'pool_id' in attr:
|
Make sure attr is a dict
Fixes #<I>
|
SpriteLink_NIPAP
|
train
|
5f10edcaae4459bb76084eeda4b1a552c650eb0b
|
diff --git a/aws/resource_aws_ram_resource_share_accepter_test.go b/aws/resource_aws_ram_resource_share_accepter_test.go
index <HASH>..<HASH> 100644
--- a/aws/resource_aws_ram_resource_share_accepter_test.go
+++ b/aws/resource_aws_ram_resource_share_accepter_test.go
@@ -255,14 +255,14 @@ resource "aws_iam_role_policy" "test" {
role = aws_iam_role.test.name
policy = jsonencode({
- Version = "2012-10-17"
+ Version = "2012-10-17"
Statement = [{
Effect = "Allow"
Resource = ["*"]
Action = [
- "logs:CreateLogGroup",
- "logs:CreateLogStream",
- "logs:PutLogEvents"
+ "logs:CreateLogGroup",
+ "logs:CreateLogStream",
+ "logs:PutLogEvents"
]
}]
})
|
tests/r/ram_resource_share_accepter: Appease linter overlord
|
terraform-providers_terraform-provider-aws
|
train
|
9d630718653bf3ca73537e447213b60199f0c1fc
|
diff --git a/addon/mode/simple.js b/addon/mode/simple.js
index <HASH>..<HASH> 100644
--- a/addon/mode/simple.js
+++ b/addon/mode/simple.js
@@ -135,7 +135,7 @@
if (rule.data.dedent)
state.indent.pop();
var token = rule.token
- if (token.apply) token = token(matches)
+ if (token && token.apply) token = token(matches)
if (matches.length > 2) {
state.pending = [];
for (var j = 2; j < matches.length; j++)
|
[mode/simple addon] Fix crash bug
Issue #<I>
|
codemirror_CodeMirror
|
train
|
c15307d8178c1e907d4a160c29c48cbca86f3506
|
diff --git a/Integration/AgeFromBirthdateIntegration.php b/Integration/AgeFromBirthdateIntegration.php
index <HASH>..<HASH> 100644
--- a/Integration/AgeFromBirthdateIntegration.php
+++ b/Integration/AgeFromBirthdateIntegration.php
@@ -97,31 +97,40 @@ class AgeFromBirthdateIntegration extends AbstractEnhancerIntegration
$month = $monthOrig = $lead->getFieldValue('dob_month');
$year = $yearOrig = $lead->getFieldValue('dob_year');
$age = $ageOrig = $lead->getFieldValue('afb_age');
+ $today = new \DateTime();
try {
- if ('' !== $dobStr && '0000-00-00' !== $dobStr) {
+ if ($dobOrig instanceof \DateTime) {
+ // For BC.
+ $dobStr = $dobOrig = $dobOrig->format('Y-m-d');
+ }
+ if (
+ $dobStr
+ && '0000-00-00' !== $dobStr
+ && $today->format('Y-m-d') != $dobStr
+ ) {
// DOB field to date/month/day fields.
$dob = new \DateTime($dobStr);
$day = (int) $dob->format('d');
$month = (int) $dob->format('m');
$year = (int) $dob->format('Y');
- } elseif ('' !== $yearOrig) {
+ } elseif ($yearOrig) {
// Date/month/day fields to DOB field with normalization.
- $day = max(1, min(31, (int) $dayOrig));
- $month = max(1, min(12, (int) $monthOrig));
$year = (int) $yearOrig;
if ($year) {
+ $day = max(1, min(31, (int) $dayOrig));
+ $month = max(1, min(12, (int) $monthOrig));
$dob = new \DateTime(sprintf('%04d-%02d-%02d 00:00:00', $year, $month, $day));
}
+ } elseif ($ageOrig) {
+ // @todo - Support age back to DOB estimation.
}
- // @todo - Support age back to DOB estimation.
} catch (\Exception $e) {
// Allow DateTime to fail gracefully.
}
// Generate age if DOB was found valid.
if (isset($dob) && $dob) {
- $today = new \DateTime();
$yearDiff = (int) $today->diff($dob)->y;
if ($yearDiff > -1 && $yearDiff < 120) {
$age = $yearDiff;
@@ -130,23 +139,23 @@ class AgeFromBirthdateIntegration extends AbstractEnhancerIntegration
}
// See if any field values changed (intentionally not type checking).
- if ($dobOrig != $dobStr) {
+ if ($dobStr && $dobOrig != $dobStr) {
$lead->addUpdatedField('dob', $dobStr, $dobOrig);
$save = true;
}
- if ($dayOrig != $day) {
+ if ($day && $dayOrig != $day) {
$lead->addUpdatedField('dob_day', $day, $dayOrig);
$save = true;
}
- if ($monthOrig != $month) {
+ if ($month && $monthOrig != $month) {
$lead->addUpdatedField('dob_month', $month, $monthOrig);
$save = true;
}
- if ($yearOrig != $year) {
+ if ($year && $yearOrig != $year) {
$lead->addUpdatedField('dob_year', $year, $yearOrig);
$save = true;
}
- if ($ageOrig != $age) {
+ if ($age && $ageOrig != $age) {
$lead->addUpdatedField('afb_age', $age, $ageOrig);
$save = true;
}
|
Do not permit current date for birthdate/age calculation.
|
TheDMSGroup_mautic-enhancer
|
train
|
b8e4d4b7913990e7a198e1bdb9667b31fe12fbef
|
diff --git a/lib/dm-sweatshop.rb b/lib/dm-sweatshop.rb
index <HASH>..<HASH> 100644
--- a/lib/dm-sweatshop.rb
+++ b/lib/dm-sweatshop.rb
@@ -1,6 +1,6 @@
require 'rubygems'
-gem 'dm-core', '=0.9.4'
+gem 'dm-core', '=0.9.5'
require 'dm-core'
require 'randexp'
diff --git a/lib/dm-sweatshop/version.rb b/lib/dm-sweatshop/version.rb
index <HASH>..<HASH> 100644
--- a/lib/dm-sweatshop/version.rb
+++ b/lib/dm-sweatshop/version.rb
@@ -1,5 +1,5 @@
module DataMapper
class Sweatshop
- VERSION = "0.9.4"
+ VERSION = "0.9.5"
end
end
|
Version Bump for <I>.
|
datamapper_dm-sweatshop
|
train
|
39db1b10dc4b160cfa14b742dadf813ef0431e92
|
diff --git a/src/Support/helpers.php b/src/Support/helpers.php
index <HASH>..<HASH> 100644
--- a/src/Support/helpers.php
+++ b/src/Support/helpers.php
@@ -34,12 +34,12 @@ if (! function_exists('intend')) {
/**
* Return redirect response.
*
- * @param array $arguments
- * @param int $status
+ * @param array $arguments
+ * @param int|null $status
*
* @return \Illuminate\Http\JsonResponse|\Illuminate\Http\RedirectResponse
*/
- function intend(array $arguments, int $status = 302)
+ function intend(array $arguments, int $status = null)
{
if (request()->expectsJson()) {
$messages = collect($arguments['with'] ?? []);
|
Set default status code to null, we'll handle it!
|
rinvex_laravel-support
|
train
|
999b548cecc28035b12e7144ed21c80f8c70d373
|
diff --git a/wildmatch_linux.go b/wildmatch_linux.go
index <HASH>..<HASH> 100644
--- a/wildmatch_linux.go
+++ b/wildmatch_linux.go
@@ -3,5 +3,5 @@
package wildmatch
func init() {
- SystemCase = CaseFold
+ SystemCase = func(w *Wildmatch) {}
}
diff --git a/wildmatch_notlinux.go b/wildmatch_notlinux.go
index <HASH>..<HASH> 100644
--- a/wildmatch_notlinux.go
+++ b/wildmatch_notlinux.go
@@ -3,5 +3,5 @@
package wildmatch
func init() {
- SystemCase = func(w *Wildmatch) {}
+ SystemCase = CaseFold
}
|
Fix swapped case-sensitivity defaults
We have two implementations of the init function, which sets the system
case sensitivity: one for Linux, and one for non-Linux. However, the
implementations are swapped: the Linux one is case insensitive, and the
non-Linux is case sensitive. Correct this by swapping the functions
around so that Linux is case sensitive and Windows and Mac are case
insensitive.
|
git-lfs_wildmatch
|
train
|
d1d9190b5f4209b5837816b21b452f19600ce9ba
|
diff --git a/javaee/impl/src/main/java/org/jboss/forge/addon/javaee/jpa/ui/NewFieldWizard.java b/javaee/impl/src/main/java/org/jboss/forge/addon/javaee/jpa/ui/NewFieldWizard.java
index <HASH>..<HASH> 100644
--- a/javaee/impl/src/main/java/org/jboss/forge/addon/javaee/jpa/ui/NewFieldWizard.java
+++ b/javaee/impl/src/main/java/org/jboss/forge/addon/javaee/jpa/ui/NewFieldWizard.java
@@ -9,6 +9,8 @@ package org.jboss.forge.addon.javaee.jpa.ui;
import java.io.FileNotFoundException;
import java.util.ArrayList;
+import java.util.Calendar;
+import java.util.Date;
import java.util.List;
import java.util.concurrent.Callable;
@@ -16,6 +18,8 @@ import javax.inject.Inject;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Lob;
+import javax.persistence.Temporal;
+import javax.persistence.TemporalType;
import org.jboss.forge.addon.convert.Converter;
import org.jboss.forge.addon.javaee.jpa.FieldOperations;
@@ -74,12 +78,17 @@ public class NewFieldWizard extends AbstractJavaEECommand implements UIWizard
private UIInput<Integer> length;
@Inject
+ @WithAttributes(label = "Temporal Type", defaultValue = "DATE", description = "Adds @Temporal only if field is java.util.Date or java.util.Calendar", type = InputType.RADIO, enabled = false)
+ private UISelectOne<TemporalType> temporalType;
+
+ @Inject
private FieldOperations fieldOperations;
@Override
public Metadata getMetadata(UIContext context)
{
- return Metadata.from(super.getMetadata(context), getClass()).name("JPA: New Field").description("Create a new field")
+ return Metadata.from(super.getMetadata(context), getClass()).name("JPA: New Field")
+ .description("Create a new field")
.category(Categories.create(super.getMetadata(context).getCategory().getName(), "JPA"));
}
@@ -120,7 +129,17 @@ public class NewFieldWizard extends AbstractJavaEECommand implements UIWizard
return !lob.getValue();
}
});
- builder.add(entity).add(fieldName).add(typeName).add(length).add(relationshipType).add(lob).add(primitive);
+ temporalType.setEnabled(new Callable<Boolean>()
+ {
+ @Override
+ public Boolean call() throws Exception
+ {
+ String typeValue = typeName.getValue();
+ return Date.class.getName().equals(typeValue) || Calendar.class.getName().equals(typeValue);
+ }
+ });
+ builder.add(entity).add(fieldName).add(typeName).add(temporalType).add(length).add(relationshipType).add(lob)
+ .add(primitive);
}
private void setupEntities(UIContext context)
@@ -211,6 +230,10 @@ public class NewFieldWizard extends AbstractJavaEECommand implements UIWizard
{
field.getAnnotation(Column.class).setLiteralValue("length", String.valueOf(length.getValue()));
}
+ if (temporalType.isEnabled())
+ {
+ field.addAnnotation(Temporal.class).setEnumValue(temporalType.getValue());
+ }
Project selectedProject = getSelectedProject(context);
if (selectedProject != null)
{
|
Added @Temporal support for java.util.Date and java.util.Calendar
|
forge_core
|
train
|
1553130eece93c7d8ccd1405596964cae2618302
|
diff --git a/src/Product/PriceSnippetRenderer.php b/src/Product/PriceSnippetRenderer.php
index <HASH>..<HASH> 100644
--- a/src/Product/PriceSnippetRenderer.php
+++ b/src/Product/PriceSnippetRenderer.php
@@ -101,7 +101,7 @@ class PriceSnippetRenderer implements SnippetRenderer
private function createPriceSnippetForEachCountry(Product $product)
{
return @array_map(function ($country) use ($product) {
- return $this->createPriceSnipperForCountry($product, $country);
+ return $this->createPriceSnippetForCountry($product, $country);
}, $this->taxableCountries->getCountries());
}
@@ -110,7 +110,7 @@ class PriceSnippetRenderer implements SnippetRenderer
* @param string $country
* @return Snippet
*/
- private function createPriceSnipperForCountry(Product $product, $country)
+ private function createPriceSnippetForCountry(Product $product, $country)
{
$key = $this->getSnippetKeyForCountry($product, $country);
$price = $this->getPriceIncludingTax($product, $country);
|
Issue #<I>: Fix typo in method name
|
lizards-and-pumpkins_catalog
|
train
|
e70a199d69cbbdd53f46ff6014b5368a6c7e4472
|
diff --git a/i3pystatus/updates/yaourt.py b/i3pystatus/updates/yaourt.py
index <HASH>..<HASH> 100644
--- a/i3pystatus/updates/yaourt.py
+++ b/i3pystatus/updates/yaourt.py
@@ -9,15 +9,13 @@ class Yaourt(Backend):
By default it will only count aur packages. Thus it can be used with the pacman backend like this:
from i3pystatus.updates import pacman, yaourt
- status.register("updates",
- backends = [pacman.Pacman(), yaourt.Yaourt()])
+ status.register("updates", backends = [pacman.Pacman(), yaourt.Yaourt()])
If you want to count both pacman and aur packages with this module you can set the variable
count_only_aur = False like this:
from i3pystatus.updates import yaourt
- status.register("updates",
- backends = [yaourt.Yaourt(False)])
+ status.register("updates", backends = [yaourt.Yaourt(False)])
"""
def __init__(self, aur_only=True):
|
Removed indentation in docstring.
|
enkore_i3pystatus
|
train
|
023df6c59b6bb8cb4f267a8b6d456a8c4da6844e
|
diff --git a/tooling/vis/main.js b/tooling/vis/main.js
index <HASH>..<HASH> 100644
--- a/tooling/vis/main.js
+++ b/tooling/vis/main.js
@@ -4,6 +4,11 @@
var $removeTransitNodesCheckbox = $("#transit-node-removal-pass");
var $rewriteConstantConditionalEdgesCheckbox = $("#constant-conditional-edge-rewriting-pass");
+ var sessionStorageKeys = {
+ code: "code",
+ options: "options"
+ };
+
var previousCode;
var debouncedUpdate = _.debounce(update, 200);
@@ -27,8 +32,8 @@
previousCode = code;
- sessionStorage.setItem("code", code);
- sessionStorage.setItem("options", JSON.stringify(options));
+ sessionStorage.setItem(sessionStorageKeys.code, code);
+ sessionStorage.setItem(sessionStorageKeys.options, JSON.stringify(options));
window.cfgVisualization.renderControlFlowGraph(container, code, options);
}
@@ -54,9 +59,9 @@
}
function initializeFormFromSessionStorage() {
- $input.val(sessionStorage.getItem("code"));
+ $input.val(sessionStorage.getItem(sessionStorageKeys.code));
- var optionsString = sessionStorage.getItem("options") || "";
+ var optionsString = sessionStorage.getItem(sessionStorageKeys.options) || "";
var options = JSON.parse(optionsString);
$removeTransitNodesCheckbox.prop("checked", !!options.passes.removeTransitNodes);
|
Less stringly-typed code
|
mariusschulz_styx
|
train
|
e21d79d18b13078ec3d22893e65c8596e9ce745d
|
diff --git a/src/main/java/org/skysql/jdbc/MySQLStatement.java b/src/main/java/org/skysql/jdbc/MySQLStatement.java
index <HASH>..<HASH> 100644
--- a/src/main/java/org/skysql/jdbc/MySQLStatement.java
+++ b/src/main/java/org/skysql/jdbc/MySQLStatement.java
@@ -627,7 +627,7 @@ public class MySQLStatement implements Statement {
* @since 1.4
*/
public int executeUpdate(final String sql, final int[] columnIndexes) throws SQLException {
- throw SQLExceptionMapper.getFeatureNotSupportedException("Not supported");
+ return executeUpdate(sql);
}
/**
@@ -652,7 +652,7 @@ public class MySQLStatement implements Statement {
* @since 1.4
*/
public int executeUpdate(final String sql, final String[] columnNames) throws SQLException {
- throw SQLExceptionMapper.getFeatureNotSupportedException("Not supported");
+ return executeUpdate(sql);
}
/**
@@ -722,7 +722,7 @@ public class MySQLStatement implements Statement {
* @since 1.4
*/
public boolean execute(final String sql, final int[] columnIndexes) throws SQLException {
- throw SQLExceptionMapper.getFeatureNotSupportedException("Not supported");
+ return execute(sql);
}
/**
@@ -757,7 +757,7 @@ public class MySQLStatement implements Statement {
* @since 1.4
*/
public boolean execute(final String sql, final String[] columnNames) throws SQLException {
- throw SQLExceptionMapper.getFeatureNotSupportedException("Not supported");
+ return execute(sql);
}
/**
|
allow different update() methods with multiple generated values. Rven if it does not work wth MySQL server at all, we cannot stop people complaining we do not support the API. Perhaps they want just to use single generated value, we do not know
|
MariaDB_mariadb-connector-j
|
train
|
45537f70fa580ad2ebbaa586b376d2e44cec925b
|
diff --git a/packages/tooling/__tests__/operation.test.js b/packages/tooling/__tests__/operation.test.js
index <HASH>..<HASH> 100644
--- a/packages/tooling/__tests__/operation.test.js
+++ b/packages/tooling/__tests__/operation.test.js
@@ -107,6 +107,30 @@ describe('#getContentType', () => {
});
});
+describe('#isFormUrlEncoded', () => {
+ it('should identify `application/x-www-form-urlencoded` as json', () => {
+ const op = new Operation(petstore, '/json', 'get', {
+ requestBody: {
+ content: {
+ 'application/x-www-form-urlencoded': {
+ schema: {
+ type: 'array',
+ items: {
+ type: 'string',
+ },
+ },
+ },
+ },
+ },
+ });
+
+ expect(op.getContentType()).toBe('application/x-www-form-urlencoded');
+ expect(op.isFormUrlEncoded()).toBe(true);
+ expect(op.isJson()).toBe(false);
+ expect(op.isMultipart()).toBe(false);
+ });
+});
+
describe('#isMultipart', () => {
it.each([['multipart/mixed'], ['multipart/related'], ['multipart/form-data'], ['multipart/alternative']])(
'should identify `%s` as multipart',
@@ -130,8 +154,9 @@ describe('#isMultipart', () => {
});
expect(op.getContentType()).toBe(contentType);
- expect(op.isMultipart()).toBe(true);
+ expect(op.isFormUrlEncoded()).toBe(false);
expect(op.isJson()).toBe(false);
+ expect(op.isMultipart()).toBe(true);
}
);
});
@@ -160,6 +185,7 @@ describe('#isJson', () => {
});
expect(op.getContentType()).toBe(contentType);
+ expect(op.isFormUrlEncoded()).toBe(false);
expect(op.isJson()).toBe(true);
expect(op.isMultipart()).toBe(false);
});
diff --git a/packages/tooling/src/operation.js b/packages/tooling/src/operation.js
index <HASH>..<HASH> 100644
--- a/packages/tooling/src/operation.js
+++ b/packages/tooling/src/operation.js
@@ -46,6 +46,10 @@ class Operation {
return this.contentType;
}
+ isFormUrlEncoded() {
+ return matchesMimeType(['application/x-www-form-urlencoded'], this.getContentType());
+ }
+
isMultipart() {
return matchesMimeType(
['multipart/mixed', 'multipart/related', 'multipart/form-data', 'multipart/alternative'],
|
feat: adding a new isFormUrlEncoded method on the operation class
|
readmeio_oas
|
train
|
d7d45322dca1ba97de64ede2e7f7aca2fe7b67a0
|
diff --git a/src/PermissionAuthServiceProvider.php b/src/PermissionAuthServiceProvider.php
index <HASH>..<HASH> 100644
--- a/src/PermissionAuthServiceProvider.php
+++ b/src/PermissionAuthServiceProvider.php
@@ -9,7 +9,7 @@ class PermissionAuthServiceProvider extends ServiceProvider
public function boot()
{
\Gate::define('access-route', function ($user, $route) {
- return $user->hasAccessTo($route);
+ return !is_null($user->role->permissions()->whereName($route)->first());
});
}
}
diff --git a/src/app/Http/Middleware/VerifyRouteAccess.php b/src/app/Http/Middleware/VerifyRouteAccess.php
index <HASH>..<HASH> 100644
--- a/src/app/Http/Middleware/VerifyRouteAccess.php
+++ b/src/app/Http/Middleware/VerifyRouteAccess.php
@@ -8,7 +8,7 @@ class VerifyRouteAccess
{
public function handle($request, Closure $next)
{
- if (!$request->user()->hasAccessTo($request->route()->getName())) {
+ if (!$request->user()->can('access-route', $request->route()->getName())) {
\Log::warning('The user having id [ '.$request->user()->id.' ] is not allowed on route [ '.$request->route()->getName().' ] ');
throw new \EnsoException(__('You are not authorized here'), 'error', [], 403);
diff --git a/src/app/Models/Permission.php b/src/app/Models/Permission.php
index <HASH>..<HASH> 100644
--- a/src/app/Models/Permission.php
+++ b/src/app/Models/Permission.php
@@ -3,11 +3,11 @@
namespace LaravelEnso\PermissionManager\app\Models;
use Illuminate\Database\Eloquent\Model;
-use LaravelEnso\Helpers\Traits\DMYTimestamps;
+use LaravelEnso\Helpers\Traits\FormattedTimestamps;
class Permission extends Model
{
- use DMYTimestamps;
+ use FormattedTimestamps;
protected $fillable = ['permission_group_id', 'name', 'description', 'type', 'default'];
protected $attributes = ['default' => 0];
diff --git a/src/app/Models/PermissionGroup.php b/src/app/Models/PermissionGroup.php
index <HASH>..<HASH> 100644
--- a/src/app/Models/PermissionGroup.php
+++ b/src/app/Models/PermissionGroup.php
@@ -3,11 +3,11 @@
namespace LaravelEnso\PermissionManager\app\Models;
use Illuminate\Database\Eloquent\Model;
-use LaravelEnso\Helpers\Traits\DMYTimestamps;
+use LaravelEnso\Helpers\Traits\FormattedTimestamps;
class PermissionGroup extends Model
{
- use DMYTimestamps;
+ use FormattedTimestamps;
protected $fillable = ['name', 'description'];
|
updated can(access-route) gate
|
laravel-enso_PermissionManager
|
train
|
b41e8a6cc7b7c56c634b950255d71f6d6c166859
|
diff --git a/ui/admin/pods_shortcode_form.php b/ui/admin/pods_shortcode_form.php
index <HASH>..<HASH> 100644
--- a/ui/admin/pods_shortcode_form.php
+++ b/ui/admin/pods_shortcode_form.php
@@ -8,8 +8,34 @@ h3.popup-header {
div.section {
padding: 15px 15px 0 15px;
}
+
+div.section.hide {
+ display: none;
+}
</style>
+<script type="text/javascript">
+jQuery(function($) {
+ var $useCaseSelector = $('#use-case-selector');
+
+ $useCaseSelector.change(function(evt) {
+ var val = $(this).val();
+
+ switch (val) {
+ case 'single':
+
+ break;
+ case 'list':
+
+ break;
+ case 'column':
+
+ break;
+ }
+ });
+});
+</script>
+
<div id="pods_shortcode_form" style="display: none;">
<div class="wrap">
@@ -19,7 +45,15 @@ div.section {
</div>
<form id="pods_shortcode_form">
- <div class="section">
+ <div class="select">
+ <label for="use-case-selector">What would you like to do?</label>
+ <select id="use-case-selector">
+ <option value="single">Display a single Pod item</option>
+ <option value="list">List multiple Pod items</option>
+ <option value="column">Display a column from a single Pod item</option>
+ </select>
+ </div>
+ <div class="section hide">
<?php
$api = new PodsAPI();
$all_pods = $api->load_pods(array(
@@ -35,15 +69,15 @@ div.section {
<?php } ?>
</select>
</div>
- <div class="section">
+ <div class="section hide">
<label for="pod_slug">Slug</label>
<input type="text" id="pod_slug" name="pod_slug" />
</div>
- <div class="section">
+ <div class="section hide">
<label for="pod_orderby">Order By</label>
<input type="text" id="pod_orderby" name="pod_orderby" />
</div>
- <div class="section">
+ <div class="section hide">
<label for="pod_sort_direction">Direction</label>
<select id="pod_sort_direction" name="pod_sort_direction">
<option value=""></option>
@@ -55,7 +89,7 @@ div.section {
</option>
</select>
</div>
- <div class="section">
+ <div class="section hide">
<?php
$templates = $api->load_templates(array(
'orderby' => 'name ASC',
@@ -71,15 +105,15 @@ div.section {
<?php } ?>
</select>
</div>
- <div class="section">
+ <div class="section hide">
<label for="pod_limit">Limit</label>
<input type="text" id="pod_limit" name="pod_limit" />
</div>
- <div class="section">
+ <div class="section hide">
<label for="pod_column">Column</label>
<input type="text" id="pod_column" name="pod_column" />
</div>
- <div class="section">
+ <div class="section hide">
<?php
$helpers = $api->load_helpers(array(
"orderby" => "name ASC",
@@ -95,7 +129,7 @@ div.section {
<?php } ?>
</select>
</div>
- <div class="section">
+ <div class="section hide">
<a class="button" id="pods_insert_shortcode" href="#">Insert</a>
</div>
</form>
|
Added use case selector and JS skeleton
|
pods-framework_pods
|
train
|
221dd79e24aca7d956b94442669a827d9b5e76b6
|
diff --git a/src/osrm.js b/src/osrm.js
index <HASH>..<HASH> 100644
--- a/src/osrm.js
+++ b/src/osrm.js
@@ -93,15 +93,13 @@ OSRM.prototype = {
var url = (typeof arg === 'string') && (this._url + arg) ||
this._encodeUrl(arg.service, arg.version, arg.query, arg.format, arg.options);
- var timeout = setTimeout(function() { callback(new Error("Request timed out")); }, this._timeout);
-
- this._get(url, function (response) {
+ var timedout;
+ var request = this._get(url, function (response) {
var body = '';
response.on('data', function(data) {
body += data;
});
response.on('end', function() {
- clearTimeout(timeout);
if (response.headers['content-type'] === undefined)
{
return callback(new Error("Response does not have a content-type set."));
@@ -119,7 +117,12 @@ OSRM.prototype = {
}
});
}).on('error', function(err) {
+ if (timedout) return;
callback(err);
+ }).setTimeout(this._timeout, function() {
+ request.abort();
+ timedout = true;
+ callback(new Error("Request timed out"));
});
},
|
fix callback duplicate in case of timeout
reimplement timeout with http.ClientRequest.setTimeout and abort.
|
Project-OSRM_osrm.js
|
train
|
9f3f52a7f38971b6a05983bf5d4af2d21a0e27cf
|
diff --git a/xwiki-rendering-wikimodel/src/test/java/org/xwiki/rendering/wikimodel/ReferenceHandlerTest.java b/xwiki-rendering-wikimodel/src/test/java/org/xwiki/rendering/wikimodel/ReferenceHandlerTest.java
index <HASH>..<HASH> 100644
--- a/xwiki-rendering-wikimodel/src/test/java/org/xwiki/rendering/wikimodel/ReferenceHandlerTest.java
+++ b/xwiki-rendering-wikimodel/src/test/java/org/xwiki/rendering/wikimodel/ReferenceHandlerTest.java
@@ -30,18 +30,18 @@ import static org.junit.jupiter.api.Assertions.assertEquals;
* @version $Id$
* @since 4.0M1
*/
-public class ReferenceHandlerTest
+class ReferenceHandlerTest
{
private TestReferenceHandler clazz;
@BeforeEach
- private void setUp()
+ void setUp()
{
this.clazz = new TestReferenceHandler(true, true);
}
@Test
- public void handleImageUppercase()
+ void handleImageUppercase()
{
WikiReference ref = new WikiReference("Image:foo.png", "bar");
clazz.handle(ref);
@@ -50,7 +50,7 @@ public class ReferenceHandlerTest
}
@Test
- public void handleImageLowercase()
+ void handleImageLowercase()
{
WikiReference ref = new WikiReference("image:bar.png", "foo");
clazz.handle(ref);
diff --git a/xwiki-rendering-wikimodel/src/test/java/org/xwiki/rendering/wikimodel/WikiParametersTest.java b/xwiki-rendering-wikimodel/src/test/java/org/xwiki/rendering/wikimodel/WikiParametersTest.java
index <HASH>..<HASH> 100644
--- a/xwiki-rendering-wikimodel/src/test/java/org/xwiki/rendering/wikimodel/WikiParametersTest.java
+++ b/xwiki-rendering-wikimodel/src/test/java/org/xwiki/rendering/wikimodel/WikiParametersTest.java
@@ -28,10 +28,10 @@ import static org.junit.jupiter.api.Assertions.assertEquals;
*
* @version $Id$
*/
-public class WikiParametersTest
+class WikiParametersTest
{
@Test
- public void testParametersValuewithoutEndingDoubleQuote()
+ void testParametersValuewithoutEndingDoubleQuote()
{
WikiParameters wikiParameters = WikiParameters.newWikiParameters("key=\"value");
|
[Misc] Apply JUnit5 best practice and fix failing test with JUnit <I>
|
xwiki_xwiki-rendering
|
train
|
1c2b07519c79f0a9c895958104212b3261af63b9
|
diff --git a/src/sap.ui.documentation/src/sap/ui/documentation/sdk/controller/App.controller.js b/src/sap.ui.documentation/src/sap/ui/documentation/sdk/controller/App.controller.js
index <HASH>..<HASH> 100644
--- a/src/sap.ui.documentation/src/sap/ui/documentation/sdk/controller/App.controller.js
+++ b/src/sap.ui.documentation/src/sap/ui/documentation/sdk/controller/App.controller.js
@@ -78,8 +78,11 @@ sap.ui.define([
// shortcut for sap.m.URLHelper
var URLHelper = mobileLibrary.URLHelper,
+ bUseUnifiedResourceOrigin = new URLSearchParams(window.location.search).get('sap-ui-xx-unifiedResources') != null,
sNeoAppJsonPath = ResourcesUtil.getResourceOriginPath("/neo-app.json"), /* Load neo-app.json always from root URL */
- sVersionOverviewJsonPath = ResourcesUtil.getResourceOriginPath("/versionoverview.json"), /* Load versionoverview.json always from root URL */
+ sVersionOverviewJsonPath = bUseUnifiedResourceOrigin && !self['sap-ui-documentation-config'] ?
+ window.origin + "/versionoverview.json" :
+ ResourcesUtil.getResourceOriginPath("/versionoverview.json"), /* Load versionoverview.json always from root URL */
ABOUT_TEXT = "about",
FEEDBACK_TEXT = "feedback",
FEEDBACK_URL = "https://demokit-feedback-proxy.cfapps.eu12.hana.ondemand.com/issue",
@@ -1030,8 +1033,8 @@ sap.ui.define([
onVersionItemPress: function (oEvent) {
var oSelectedItem = oEvent.getParameter("listItem"),
- oCustomData = oSelectedItem.getCustomData()[0],
- bUseUnifiedResourceOrigin = new URLSearchParams(window.location.search).get('sap-ui-xx-unifiedResources') != null;
+ oCustomData = oSelectedItem.getCustomData()[0];
+
if (oCustomData && oCustomData.getKey() === "path") {
|
[INTERNAL] Demo Kit: Show Change Version button on every version
We used to look for versionOverview.json in every version directory, but it is
missing on some of them. Now we only look for it in the root folder.
Jira: BGSOFUIPIRIN-<I>
Change-Id: Ib<I>c<I>a<I>e<I>a2b1ed9cecbe3cb<I>ac<I>cd
|
SAP_openui5
|
train
|
32bf0c4950d8d2dae2d16f33b1f3bfcbefb6004d
|
diff --git a/executor/infoschema_reader.go b/executor/infoschema_reader.go
index <HASH>..<HASH> 100644
--- a/executor/infoschema_reader.go
+++ b/executor/infoschema_reader.go
@@ -1919,6 +1919,9 @@ func (e *memtableRetriever) dataForTableTiFlashReplica(ctx sessionctx.Context, s
}
func (e *memtableRetriever) setDataForStatementsSummaryEvicted(ctx sessionctx.Context) error {
+ if !hasPriv(ctx, mysql.ProcessPriv) {
+ return plannercore.ErrSpecificAccessDenied.GenWithStackByArgs("PROCESS")
+ }
e.rows = stmtsummary.StmtSummaryByDigestMap.ToEvictedCountDatum()
switch e.table.Name.O {
case infoschema.ClusterTableStatementsSummaryEvicted:
diff --git a/infoschema/tables_test.go b/infoschema/tables_test.go
index <HASH>..<HASH> 100644
--- a/infoschema/tables_test.go
+++ b/infoschema/tables_test.go
@@ -1436,6 +1436,29 @@ func (s *testClusterTableSuite) TestStmtSummaryEvictedCountTable(c *C) {
Check(testkit.Rows("2"))
// TODO: Add more tests.
+ tk.MustExec("create user 'testuser'@'localhost'")
+ tk.MustExec("create user 'testuser2'@'localhost'")
+ tk.MustExec("grant process on *.* to 'testuser2'@'localhost'")
+ tk1 := s.newTestKitWithRoot(c)
+ defer tk1.MustExec("drop user 'testuser'@'localhost'")
+ defer tk1.MustExec("drop user 'testuser2'@'localhost'")
+
+ c.Assert(tk.Se.Auth(&auth.UserIdentity{
+ Username: "testuser",
+ Hostname: "localhost",
+ }, nil, nil), Equals, true)
+
+ err := tk.QueryToErr("select * from information_schema.CLUSTER_STATEMENTS_SUMMARY_EVICTED")
+ c.Assert(err, NotNil)
+ // This error is come from cop(TiDB) fetch from rpc server.
+ c.Assert(err.Error(), Equals, "other error: [planner:1227]Access denied; you need (at least one of) the PROCESS privilege(s) for this operation")
+
+ c.Assert(tk.Se.Auth(&auth.UserIdentity{
+ Username: "testuser2",
+ Hostname: "localhost",
+ }, nil, nil), Equals, true)
+ err = tk.QueryToErr("select * from information_schema.CLUSTER_STATEMENTS_SUMMARY_EVICTED")
+ c.Assert(err, IsNil)
}
func (s *testTableSuite) TestStmtSummaryTableOther(c *C) {
|
executor: fix user without process privilege can access cluster_statements_summary_evicted table (#<I>)
|
pingcap_tidb
|
train
|
709dd4583d8ecf255e1fe5ff9658e56ab6d23308
|
diff --git a/openquake/commonlib/logictree.py b/openquake/commonlib/logictree.py
index <HASH>..<HASH> 100644
--- a/openquake/commonlib/logictree.py
+++ b/openquake/commonlib/logictree.py
@@ -994,6 +994,15 @@ class GsimLogicTree(object):
'Could not find branches with attribute %r in %s' %
(self.branchset_filter, set(filter_keys)))
+ def filter(self, trts):
+ """
+ Build a reduced GsimLogicTree.
+
+ :param trts: a subset of tectonic region types
+ """
+ assert set(trts) <= set(self.filter_keys), (trts, self.filter_keys)
+ return self.__class__(self.fname, self.branchset_filter, trts)
+
def get_num_branches(self):
"""
Return the number of branches for branchset id, as a dictionary.
diff --git a/openquake/commonlib/source.py b/openquake/commonlib/source.py
index <HASH>..<HASH> 100644
--- a/openquake/commonlib/source.py
+++ b/openquake/commonlib/source.py
@@ -759,8 +759,11 @@ class CompositeSourceModel(object):
@property
def trt_models(self):
+ trt_id = 0
for sm in self.source_models:
for trt_model in sm.trt_models:
+ if not trt_model.id: # set only the first time
+ trt_model.id = trt_id
yield trt_model
@property
@@ -770,17 +773,41 @@ class CompositeSourceModel(object):
"""
for trt_model in self.trt_models:
for src in trt_model:
+ src.trt_model_id = trt_model.id
yield src
def __getitem__(self, path):
return self.smdict[path]
+ def __setitem__(self, path, sm):
+ self.smdict[path] = sm
+
def __iter__(self):
return iter(self.source_models)
def __len__(self):
return len(self.source_models)
+ def reduce_trt_models(self):
+ """
+ Remove the tectonic regions without ruptures and reduce the
+ GSIM logic tree.
+ """
+ for sm in self:
+ trts = set(trt_model.trt for trt_model in sm.trt_models
+ if trt_model.num_ruptures > 0)
+ if trts == set(sm.gsim_lt.filter_keys):
+ # nothing to remove
+ continue
+ gsim_lt = sm.gsim_lt.filter(trts)
+ models = []
+ for trt_model in sm.trt_models:
+ if trt_model.trt in trts:
+ trt_model.gsims = gsim_lt.values[trt_model.trt]
+ models.append(trt_model)
+ self[sm.path] = SourceModel(
+ sm.name, sm.weight, sm.path, models, gsim_lt, sm.ordinal)
+
def get_realizations(self, num_samples, random_seed):
"""
This function works either in random sampling mode (when lt_realization
|
Introduced method reduce_trt_models
|
gem_oq-engine
|
train
|
196c0f5e41cfddd60122bddc063f0b61a4063e55
|
diff --git a/closure/goog/db/indexeddb.js b/closure/goog/db/indexeddb.js
index <HASH>..<HASH> 100644
--- a/closure/goog/db/indexeddb.js
+++ b/closure/goog/db/indexeddb.js
@@ -95,7 +95,7 @@ goog.db.IndexedDb.prototype.getVersion = function() {
/**
- * @return {Array} List of object stores in this database.
+ * @return {DOMStringList} List of object stores in this database.
*/
goog.db.IndexedDb.prototype.getObjectStoreNames = function() {
return this.db_.objectStoreNames;
|
Correct a type annotation in w3c_indexeddb.js
R=nicksantos
Revision created by MOE tool push_codebase.
R=johnlenz
DELTA=2 (0 added, 0 deleted, 2 changed)
Revision created by MOE tool push_codebase.
MOE_MIGRATION=<I>
git-svn-id: <URL>
|
google_closure-library
|
train
|
910287e2a5bc829da8c72f7b9af73a7d98452a61
|
diff --git a/runewidth_test.go b/runewidth_test.go
index <HASH>..<HASH> 100644
--- a/runewidth_test.go
+++ b/runewidth_test.go
@@ -457,15 +457,15 @@ func TestZeroWidthJoiner(t *testing.T) {
want int
}{
{"👩", 2},
- {"👩", 2},
- {"👩🍳", 2},
- {"🍳", 2},
- {"👨👨", 2},
- {"👨👨👧", 2},
- {"🏳️🌈", 1},
- {"あ👩🍳い", 6},
- {"あ🍳い", 6},
- {"あい", 4},
+ {"👩\u200d", 2},
+ {"👩\u200d🍳", 2},
+ {"\u200d🍳", 2},
+ {"👨\u200d👨", 2},
+ {"👨\u200d👨\u200d👧", 2},
+ {"🏳️\u200d🌈", 1},
+ {"あ👩\u200d🍳い", 6},
+ {"あ\u200d🍳い", 6},
+ {"あ\u200dい", 4},
}
for _, tt := range tests {
|
Use unicode escape sequence in zero width joiner tests
|
mattn_go-runewidth
|
train
|
cd2941e4fa7d61c39436d4fcbada73de7835fd07
|
diff --git a/generators/generator-constants.js b/generators/generator-constants.js
index <HASH>..<HASH> 100644
--- a/generators/generator-constants.js
+++ b/generators/generator-constants.js
@@ -41,7 +41,7 @@ const DOCKER_JHIPSTER_ELASTICSEARCH = 'jhipster/jhipster-elasticsearch:v3.0.1';
const DOCKER_JHIPSTER_LOGSTASH = 'jhipster/jhipster-logstash:v3.0.1';
const DOCKER_JHIPSTER_IMPORT_DASHBOARDS = 'jhipster/jhipster-import-dashboards:v3.0.1';
const DOCKER_JHIPSTER_ZIPKIN = 'jhipster/jhipster-zipkin:v3.0.1';
-const DOCKER_TRAEFIK = 'traefik:1.7.0';
+const DOCKER_TRAEFIK = 'traefik:1.7.1';
const DOCKER_CONSUL = 'consul:1.2.3';
const DOCKER_CONSUL_CONFIG_LOADER = 'jhipster/consul-config-loader:v0.3.0';
const DOCKER_PROMETHEUS = 'prom/prometheus:v1.6.3';
|
Update traefik version to <I>
|
jhipster_generator-jhipster
|
train
|
fd2d7b3742a24ca3bfe2e8baf702c0f9661906d4
|
diff --git a/lib/monban/services/password_reset.rb b/lib/monban/services/password_reset.rb
index <HASH>..<HASH> 100644
--- a/lib/monban/services/password_reset.rb
+++ b/lib/monban/services/password_reset.rb
@@ -8,7 +8,7 @@ module Monban
def perform
field = Monban.config.user_token_store_field
encrypted_password = Monban.encrypt_token(@password)
- @user.write_attribute(field, encrypted_password)
+ @user[field] = encrypted_password
end
end
end
diff --git a/spec/monban/services/password_reset_spec.rb b/spec/monban/services/password_reset_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/monban/services/password_reset_spec.rb
+++ b/spec/monban/services/password_reset_spec.rb
@@ -11,7 +11,7 @@ describe Monban::PasswordReset do
password_digest = Monban.encrypt_token('password')
user = double()
field = Monban.config.user_token_store_field
- user.should_receive(:write_attribute).with(field, 'passwordsecret')
+ user.should_receive(:[]=).with(field, 'passwordsecret')
password_reset = Monban::PasswordReset.new(user, 'password')
password_reset.perform
|
write_attribute is now private.
|
halogenandtoast_oath
|
train
|
c83d794afa6c97fa11540590efcfbc8ed7c21b07
|
diff --git a/spec/em_spec.rb b/spec/em_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/em_spec.rb
+++ b/spec/em_spec.rb
@@ -28,40 +28,6 @@ describe 'ZookeeperEM' do
end
end
- describe 'selectable_io' do
- it %[should return an IO object] do
- setup_zk do
- @zk.selectable_io.should be_instance_of(IO)
- teardown_and_done
- end
- end
-
- it %[should not be closed] do
- setup_zk do
- @zk.selectable_io.should_not be_closed
- teardown_and_done
- end
- end
-
- before do
- @data_cb = ZookeeperCallbacks::DataCallback.new do
- logger.debug { "cb called: #{@data_cb.inspect}" }
- end
- end
-
- it %[should be read-ready if there's an event waiting] do
- setup_zk do
- @zk.get(:path => "/", :callback => @data_cb)
-
- r, *_ = IO.select([@zk.selectable_io], [], [], 2)
-
- r.should be_kind_of(Array)
-
- teardown_and_done
- end
- end
- end
-
describe 'callbacks' do
it %[should be called on the reactor thread] do
cb = lambda do |h|
|
get rid of em_spec's selectable_io calls, no need
|
zk-ruby_zookeeper
|
train
|
958dfb5e3bb5ecf40143e3a6259bb81792fb45ec
|
diff --git a/LiSE/LiSE/proxy.py b/LiSE/LiSE/proxy.py
index <HASH>..<HASH> 100644
--- a/LiSE/LiSE/proxy.py
+++ b/LiSE/LiSE/proxy.py
@@ -1804,3 +1804,5 @@ class EngineProcessManager(object):
def shutdown(self):
self.engine_proxy.close()
self._handle_out_pipe_send.send('shutdown')
+ self._p.join()
+ del self.engine_proxy
|
Make EngineProcessManager.shutdown() a bit more thorough
|
LogicalDash_LiSE
|
train
|
3fb22e35be1ad64acffac36992322e2ffdf3faf8
|
diff --git a/spring-cloud-sleuth-core/src/test/java/org/springframework/cloud/sleuth/instrument/web/client/feign/issues/issue362/Issue362Tests.java b/spring-cloud-sleuth-core/src/test/java/org/springframework/cloud/sleuth/instrument/web/client/feign/issues/issue362/Issue362Tests.java
index <HASH>..<HASH> 100644
--- a/spring-cloud-sleuth-core/src/test/java/org/springframework/cloud/sleuth/instrument/web/client/feign/issues/issue362/Issue362Tests.java
+++ b/spring-cloud-sleuth-core/src/test/java/org/springframework/cloud/sleuth/instrument/web/client/feign/issues/issue362/Issue362Tests.java
@@ -209,7 +209,7 @@ class CustomConfig {
this.feignComponentAsserter.executedComponents.put(ErrorDecoder.class, true);
if (response.status() == 409) {
return new RetryableException(response.status(), "Article not Ready",
- Request.HttpMethod.GET, new Date(), response.request());
+ Request.HttpMethod.GET, new Date());
}
else {
return super.decode(methodKey, response);
|
Came back to previous test impl
|
spring-cloud_spring-cloud-sleuth
|
train
|
f58d1a2eac71f79ddf56f5372fdd6dae81b6d628
|
diff --git a/edisgo/tools/plots.py b/edisgo/tools/plots.py
index <HASH>..<HASH> 100644
--- a/edisgo/tools/plots.py
+++ b/edisgo/tools/plots.py
@@ -15,7 +15,7 @@ from dash import dcc, html
from dash.dependencies import Input, Output
from jupyter_dash import JupyterDash
from matplotlib import pyplot as plt
-from pyproj import Proj, Transformer
+from pyproj import Transformer
from pypsa import Network as PyPSANetwork
from edisgo.tools import session_scope, tools
diff --git a/setup.py b/setup.py
index <HASH>..<HASH> 100644
--- a/setup.py
+++ b/setup.py
@@ -5,8 +5,6 @@ import sys
from setuptools import find_packages, setup
from setuptools.command.install import install
-BASEPATH = ".eDisGo"
-
if sys.version_info[:2] < (3, 7):
error = (
"eDisGo requires Python 3.7 or later (%d.%d detected)." % sys.version_info[:2]
@@ -33,29 +31,6 @@ def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
-class InstallSetup(install):
- """
- Run setup installation.
- """
-
- def run(self):
- self.create_edisgo_path()
- install.run(self)
-
- @staticmethod
- def create_edisgo_path():
- """
- Create edisgo path if missing.
- """
- edisgo_path = os.path.join(os.path.expanduser("~"), BASEPATH)
- data_path = os.path.join(edisgo_path, "data")
-
- if not os.path.isdir(edisgo_path):
- os.mkdir(edisgo_path)
- if not os.path.isdir(data_path):
- os.mkdir(data_path)
-
-
requirements = [
"demandlib",
"networkx >= 2.5.0",
@@ -113,7 +88,7 @@ setup(
packages=find_packages(),
url="https://github.com/openego/eDisGo",
license="GNU Affero General Public License v3.0",
- author="birgits, AnyaHe, gplssm, nesnoj, jaappedersen, Elias, boltbeard",
+ author="birgits, AnyaHe, khelfen, gplssm, nesnoj, jaappedersen, Elias, boltbeard",
author_email="anya.heider@rl-institut.de",
description="A python package for distribution network analysis and optimization",
long_description=read("README.md"),
@@ -122,13 +97,8 @@ setup(
extras_require=extras,
package_data={
"edisgo": [
- os.path.join("config", "config_system"),
os.path.join("config", "*.cfg"),
os.path.join("equipment", "*.csv"),
]
},
- cmdclass={"install": InstallSetup},
- entry_points={
- "console_scripts": ["edisgo_run = edisgo.tools.edisgo_run:edisgo_run"]
- },
)
|
removed obsolete legacy code in setup.py
|
openego_eDisGo
|
train
|
cb84936b6cff2879472bfd02c11e4e4a59c0ac3b
|
diff --git a/cas_server/models.py b/cas_server/models.py
index <HASH>..<HASH> 100644
--- a/cas_server/models.py
+++ b/cas_server/models.py
@@ -102,16 +102,18 @@ class User(models.Model):
url = utils.update_url(service, {'ticket':ticket.value})
return url
-class BadUsername(Exception):
+class ServicePatternException(Exception):
+ pass
+class BadUsername(ServicePatternException):
"""Exception raised then an non allowed username
try to get a ticket for a service"""
pass
-class BadFilter(Exception):
+class BadFilter(ServicePatternException):
""""Exception raised then a user try
to get a ticket for a service and do not reach a condition"""
pass
-class UserFieldNotDefined(Exception):
+class UserFieldNotDefined(ServicePatternException):
"""Exception raised then a user try to get a ticket for a service
using as username an attribut not present on this user"""
pass
diff --git a/cas_server/urls.py b/cas_server/urls.py
index <HASH>..<HASH> 100644
--- a/cas_server/urls.py
+++ b/cas_server/urls.py
@@ -27,5 +27,6 @@ urlpatterns = patterns(
url('^p3/serviceValidate$', views.ValidateService.as_view(allow_proxy_ticket=False), name='p3_serviceValidate'),
url('^p3/proxyValidate$', views.ValidateService.as_view(allow_proxy_ticket=True), name='p3_proxyValidate'),
url('^samlValidate$', views.SamlValidate.as_view(), name='samlValidate'),
+ url('^auth$', views.Auth.as_view(), name='auth'),
)
diff --git a/cas_server/views.py b/cas_server/views.py
index <HASH>..<HASH> 100644
--- a/cas_server/views.py
+++ b/cas_server/views.py
@@ -281,6 +281,47 @@ class LoginView(View, LogoutMixin):
else:
return self.not_authenticated()
+class Auth(View):
+ """A simple view to validate username/password/service tuple"""
+ @method_decorator(csrf_exempt)
+ def dispatch(self, request, *args, **kwargs):
+ """dispatch requests based on method GET, POST, ..."""
+ return super(Auth, self).dispatch(request, *args, **kwargs)
+
+ @staticmethod
+ def post(request):
+ """methode called on GET request on this view"""
+ username = request.POST.get('username')
+ password = request.POST.get('password')
+ service = request.POST.get('service')
+
+ if not username or not password or not service:
+ print "not username or service or password"
+ return HttpResponse("no\n", content_type="text/plain")
+ form = forms.UserCredential(
+ request.POST,
+ initial={
+ 'service':service,
+ 'method':'POST',
+ 'warn':False
+ }
+ )
+ if form.is_valid():
+ try:
+ user = models.User.objects.get(username=form.cleaned_data['username'])
+ # is the service allowed
+ service_pattern = models.ServicePattern.validate(service)
+ # is the current user allowed on this service
+ service_pattern.check_user(user)
+ # if the user has asked to be warned before any login to a service
+ return HttpResponse("yes\n", content_type="text/plain")
+ except (models.ServicePattern.DoesNotExist, models.ServicePatternException) as error:
+ print "error: %r" % error
+ return HttpResponse("no\n", content_type="text/plain")
+ else:
+ print "bad password"
+ return HttpResponse("no\n", content_type="text/plain")
+
class Validate(View):
"""service ticket validation"""
@staticmethod
|
an auth view to validate (username, password, service) by remote service
|
nitmir_django-cas-server
|
train
|
e83e9b5b378205410eb53c16602398aa467a7a73
|
diff --git a/cdm/src/main/java/ucar/nc2/NetcdfFileWriteable.java b/cdm/src/main/java/ucar/nc2/NetcdfFileWriteable.java
index <HASH>..<HASH> 100644
--- a/cdm/src/main/java/ucar/nc2/NetcdfFileWriteable.java
+++ b/cdm/src/main/java/ucar/nc2/NetcdfFileWriteable.java
@@ -61,18 +61,6 @@ public class NetcdfFileWriteable extends NetcdfFile {
static private Set<DataType> valid = EnumSet.of(DataType.BYTE, DataType.CHAR, DataType.SHORT, DataType.INT,
DataType.DOUBLE, DataType.FLOAT);
- private IOServiceProviderWriter spiw;
-
- // modes
- private boolean defineMode;
-
- // state
- private boolean isNewFile;
- private boolean isLargeFile;
- private boolean fill;
- private int extraHeader;
- private long preallocateSize;
-
/**
* Open an existing Netcdf file for writing data. Fill mode is true.
* Cannot add new objects, you can only read/write data to existing Variables.
@@ -126,6 +114,20 @@ public class NetcdfFileWriteable extends NetcdfFile {
return new NetcdfFileWriteable(location, fill, false);
}
+ ////////////////////////////////////////////////////////////////////////////////
+ private IOServiceProviderWriter spiw;
+ private IOServiceProviderWriter cached_spiw = null; // Hold the IOSP for deferred use in create()
+
+ // modes
+ private boolean defineMode;
+
+ // state
+ private boolean isNewFile;
+ private boolean isLargeFile;
+ private boolean fill;
+ private int extraHeader;
+ private long preallocateSize;
+
/**
* Open or create a new Netcdf file, put it into define mode to allow writing.
*
@@ -135,18 +137,40 @@ public class NetcdfFileWriteable extends NetcdfFile {
* @throws IOException on I/O error
*/
private NetcdfFileWriteable(String location, boolean fill, boolean isExisting) throws IOException {
+ this(null, null, location, fill, isExisting);
+ }
+
+ /**
+ * Open or create a new Netcdf file, put it into define mode to allow
+ * writing, using the provided IOSP and RAF.
+ *
+ * @param iospw IO service provider to use, if null use standard
+ * @param raf Random access file to use, may be null if iospw is
+ * @param location open a new file at this location
+ * @param fill set fill mode
+ * @param isExisting true if file already exists
+ * @throws IOException on I/O error
+ */
+ protected NetcdfFileWriteable(IOServiceProviderWriter iospw, ucar.unidata.io.RandomAccessFile raf,
+ String location, boolean fill, boolean isExisting) throws IOException {
super();
this.location = location;
this.fill = fill;
if (isExisting) {
- ucar.unidata.io.RandomAccessFile raf = new ucar.unidata.io.RandomAccessFile(location, "rw");
- spi = SPFactory.getServiceProvider();
- spiw = (IOServiceProviderWriter) spi;
+ if (iospw == null) {
+ raf = new ucar.unidata.io.RandomAccessFile(location, "rw");
+ spi = SPFactory.getServiceProvider();
+ spiw = (IOServiceProviderWriter) spi;
+ } else {
+ spiw = iospw;
+ spi = spiw;
+ }
spiw.open(raf, this, null);
spiw.setFill( fill);
} else {
+ cached_spiw = iospw; // save for use later in create()
defineMode = true;
isNewFile = true;
}
@@ -178,7 +202,6 @@ public class NetcdfFileWriteable extends NetcdfFile {
this.preallocateSize = size;
}
-
/**
* Set if this should be a "large file" (64-bit offset) format.
* Must be in define mode
@@ -599,8 +622,13 @@ public class NetcdfFileWriteable extends NetcdfFile {
if (!defineMode)
throw new UnsupportedOperationException("not in define mode");
- spi = SPFactory.getServiceProvider();
- spiw = (IOServiceProviderWriter) spi;
+ if (cached_spiw == null) {
+ spi = SPFactory.getServiceProvider();
+ spiw = (IOServiceProviderWriter) spi;
+ } else {
+ spiw = cached_spiw;
+ spi = spiw;
+ }
spiw.setFill( fill);
spiw.create(location, this, extraHeader, preallocateSize, isLargeFile);
@@ -684,7 +712,7 @@ public class NetcdfFileWriteable extends NetcdfFile {
if (oldVar != null)
oldList.add(oldVar);
}
- FileWriter.copyVarData(this, oldList, recordVar, 0);
+ FileWriter.copyVarData(this, oldList, recordVar, null);
flush();
// delete old
|
incorporate kyle's patch to allow custom iosp writer. (<URL>)
|
Unidata_thredds
|
train
|
5499090ead17d4d75c5ca09274ef45c563576ccd
|
diff --git a/views/js/qtiCreator/editor/ckEditor/htmlEditor.js b/views/js/qtiCreator/editor/ckEditor/htmlEditor.js
index <HASH>..<HASH> 100755
--- a/views/js/qtiCreator/editor/ckEditor/htmlEditor.js
+++ b/views/js/qtiCreator/editor/ckEditor/htmlEditor.js
@@ -44,7 +44,7 @@ define([
*/
function _buildEditor($editable, $editableContainer, options){
- var $trigger;
+ var toolbarType, $trigger;
options = _.defaults(options, _defaults);
@@ -242,7 +242,14 @@ define([
},
configLoaded : function(e){
- e.editor.config = ckConfigurator.getConfig(e.editor, ckConfig);
+ //@todo : do we really have to wait here to initialize the config?
+ var toolbarType = '';
+ if(options.toolbar && _.isArray(options.toolbar)){
+ ckConfig.toolbar = options.toolbar;
+ }else{
+ toolbarType = getTooltypeFromContainer($editableContainer);
+ }
+ e.editor.config = ckConfigurator.getConfig(e.editor, toolbarType, ckConfig);
},
afterPaste : function(e){
//@todo : we may add some processing on the editor after paste
@@ -250,11 +257,6 @@ define([
}
};
- if(options.toolbar && _.isArray(options.toolbar)){
- ckConfig.toolbar = options.toolbar;
- }else{
- ckConfig.toolbarType = getTooltypeFromContainer($editableContainer);
- }
return CKEditor.inline($editable[0], ckConfig);
}
|
moved toolbar definition in configLoaded()
|
oat-sa_extension-tao-itemqti
|
train
|
db3a1eb8fdff7668b975209eb0a7d103e969dc46
|
diff --git a/lib/ddl/simpletest/testddl.php b/lib/ddl/simpletest/testddl.php
index <HASH>..<HASH> 100755
--- a/lib/ddl/simpletest/testddl.php
+++ b/lib/ddl/simpletest/testddl.php
@@ -13,6 +13,8 @@ require_once($CFG->libdir . '/adminlib.php');
class ddl_test extends UnitTestCase {
private $tables = array();
private $tdb;
+ public static $includecoverage = array('lib/ddl');
+ public static $excludecoverage = array('lib/ddl/simpletest');
public function setUp() {
global $CFG, $DB, $UNITTEST;
diff --git a/lib/simpletest/testmoodlelib.php b/lib/simpletest/testmoodlelib.php
index <HASH>..<HASH> 100644
--- a/lib/simpletest/testmoodlelib.php
+++ b/lib/simpletest/testmoodlelib.php
@@ -43,6 +43,8 @@ require_once($CFG->libdir . '/moodlelib.php');
class moodlelib_test extends UnitTestCase {
+ public static $includecoverage = array('lib/moodlelib.php');
+
var $user_agents = array(
'MSIE' => array(
'5.5' => array('Windows 2000' => 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT 5.0)'),
|
MDL-<I> code coverage - prepare ddl & moodlelib tests to support code coverage
|
moodle_moodle
|
train
|
70194102a3518308f260281b74c76cc0ca0a5006
|
diff --git a/src/index.js b/src/index.js
index <HASH>..<HASH> 100644
--- a/src/index.js
+++ b/src/index.js
@@ -451,7 +451,7 @@ export default class Critters {
const asset = style.$$asset;
if (asset) {
const percent = sheetInverse.length / before.length * 100;
- afterText = `, reducing non-inlined size ${percent | 0}% to ${prettyBytes(before.length)}`;
+ afterText = `, reducing non-inlined size ${percent | 0}% to ${prettyBytes(sheetInverse.length)}`;
style.$$assets[style.$$assetName] = new sources.LineToLineMappedSource(sheetInverse, style.$$assetName, before);
} else {
console.warn('pruneSource is enabaled, but a style (' + name + ') has no corresponding Webpack asset.');
|
Fix pruneSource reporting incorrect remaining size.
|
GoogleChromeLabs_critters
|
train
|
9f76531c3a7a6ff32515d2238cf26dbd772467d7
|
diff --git a/activerecord/lib/active_record/attribute_methods.rb b/activerecord/lib/active_record/attribute_methods.rb
index <HASH>..<HASH> 100644
--- a/activerecord/lib/active_record/attribute_methods.rb
+++ b/activerecord/lib/active_record/attribute_methods.rb
@@ -26,7 +26,15 @@ module ActiveRecord
end
def initialize_generated_modules # :nodoc:
- @generated_attribute_methods = Module.new { extend Mutex_m }
+ @generated_attribute_methods = Module.new {
+ extend Mutex_m
+
+ const_set :AttrNames, Module.new {
+ def self.const_missing(name)
+ const_set(name, [name.to_s.sub(/ATTR_/, '')].pack('h*').freeze)
+ end
+ }
+ }
@attribute_methods_generated = false
include @generated_attribute_methods
end
diff --git a/activerecord/lib/active_record/core.rb b/activerecord/lib/active_record/core.rb
index <HASH>..<HASH> 100644
--- a/activerecord/lib/active_record/core.rb
+++ b/activerecord/lib/active_record/core.rb
@@ -90,12 +90,6 @@ module ActiveRecord
module ClassMethods
def initialize_generated_modules
super
- # force attribute methods to be higher in inheritance hierarchy than other generated methods
- generated_attribute_methods.const_set(:AttrNames, Module.new {
- def self.const_missing(name)
- const_set(name, [name.to_s.sub(/ATTR_/, '')].pack('h*').freeze)
- end
- })
generated_feature_methods
end
|
push attribute constant cache in to the attribute methods module
|
rails_rails
|
train
|
d0b33636c884660bc06bda5b8dd30e11645a8b84
|
diff --git a/core/block_svg.js b/core/block_svg.js
index <HASH>..<HASH> 100644
--- a/core/block_svg.js
+++ b/core/block_svg.js
@@ -1400,8 +1400,8 @@ Blockly.BlockSvg.prototype.scheduleSnapAndBump = function() {
*/
Blockly.BlockSvg.prototype.isRecyclable = function() {
- // The procedures_call type is always dynamic as it can be mutated at runtime.
- if (this.type === 'procedures_call') {
+ // If the block needs to parse mutations, it's probably safest to never recycle.
+ if (this.mutationToDom && this.domToMutation) {
return false;
}
diff --git a/core/procedures.js b/core/procedures.js
index <HASH>..<HASH> 100644
--- a/core/procedures.js
+++ b/core/procedures.js
@@ -237,7 +237,6 @@ Blockly.Procedures.flyoutCategory = function(workspace) {
// <mutation ...></mutation>
// </block>
var block = goog.dom.createDom('block');
- block.setAttribute('id', 'proccode:' + mutation.proccode );
block.setAttribute('type', 'procedures_call');
block.setAttribute('gap', 16);
block.appendChild(mutation);
|
More general approach to procedures_call reasoning for being dynamic
|
LLK_scratch-blocks
|
train
|
9da64b780fc2888011e2d6acf9cb55798aa1e296
|
diff --git a/_uniout.py b/_uniout.py
index <HASH>..<HASH> 100644
--- a/_uniout.py
+++ b/_uniout.py
@@ -6,21 +6,46 @@ __all__ = ['unescape', 'make_unistream', 'runs_in_ipython']
import sys
import re
-escape_x_re = re.compile(r'(?:\\x[0-9a-f]{2})+')
-escape_u_re = re.compile(r'(?:\\u[0-9a-f]{4}|\\U[0-9a-f]{8})+')
-encoding = sys.getfilesystemencoding()
+try:
+ import chardet
+except ImportError:
+ chardet = None
-def unescape(s):
- r'''decode the \x, \u and \U in a escaped string -> encoded string'''
+string_literal_re = re.compile('(?![uU])(?P<q>[\'"]).+(?P=q)')
+unicode_literal_re = re.compile('[uU](?P<q>[\'"]).+(?P=q)')
- s = escape_x_re.sub(lambda m: m.group().decode('string-escape'), s)
- s = escape_u_re.sub(lambda m: m.group().decode('unicode-escape').encode(encoding), s)
+def unescape_bytes(b, target_encoding):
- # for Python < 2.7
- if isinstance(s, unicode):
- s = s.encode(encoding)
+ b = b.decode('string-escape')
- return s
+ if chardet:
+
+ r = chardet.detect(b)
+ confidence, b_encoding = r['confidence'], r['encoding']
+
+ if confidence >= 0.5 and b_encoding != target_encoding:
+ try:
+ b = b.decode(b_encoding)
+ except (UnicodeDecodeError, LookupError):
+ pass
+ else:
+ b = b.encode(target_encoding)
+
+ return b
+
+def unescape_unicodes(b, target_encoding):
+ return b.decode('unicode-escape').encode(target_encoding)
+
+def unescape(b, target_encoding=None):
+
+ if target_encoding is None:
+ target_encoding = sys.stdout.encoding
+
+ b = string_literal_re.sub(lambda m: unescape_bytes(m.group(), target_encoding), b)
+
+ b = unicode_literal_re.sub(lambda m: unescape_unicodes(m.group(), target_encoding), b)
+
+ return b
def make_unistream(stream):
@@ -32,7 +57,7 @@ def make_unistream(stream):
setattr(unistream, attr_name, getattr(stream, attr_name))
# modify the write method to de-escape
- unistream.write = lambda bytes: stream.write(unescape(bytes))
+ unistream.write = lambda bytes: stream.write(unescape(bytes, unistream.encoding))
return unistream
|
make the functions much better :D
|
moskytw_uniout
|
train
|
8ac2b4e4bcd6db0aab5fc396eee5818aea3f3f19
|
diff --git a/bt/core.py b/bt/core.py
index <HASH>..<HASH> 100644
--- a/bt/core.py
+++ b/bt/core.py
@@ -515,11 +515,10 @@ class StrategyBase(Node):
self._value = val
self._values.values[inow] = val
- try:
- with np.errstate(divide='raise', invalid='raise'):
- ret = self._value / (self._last_value
- + self._net_flows) - 1
- except (ZeroDivisionError, FloatingPointError):
+ bottom = self._last_value + self._net_flows
+ if bottom != 0:
+ ret = self._value / (self._last_value + self._net_flows) - 1
+ else:
if self._value == 0:
ret = 0
else:
@@ -542,10 +541,10 @@ class StrategyBase(Node):
# avoid useless update call
if c._issec and not c._needupdate:
continue
- try:
- with np.errstate(divide='raise', invalid='raise'):
- c._weight = c.value / val
- except (ZeroDivisionError, FloatingPointError):
+
+ if val != 0:
+ c._weight = c.value / val
+ else:
c._weight = 0.0
# if we have strategy children, we will need to update them in universe
@@ -974,8 +973,7 @@ class SecurityBase(Node):
if amount == -self._value:
q = -self._position
else:
- with np.errstate(divide='raise', invalid='raise'):
- q = amount / (self._price * self.multiplier)
+ q = amount / (self._price * self.multiplier)
if self.integer_positions:
if (self._position > 0) or ((self._position == 0) and (amount > 0)):
# if we're going long or changing long position
|
addresses performance issue brought up by @francol, introduced by issue #<I>
|
pmorissette_bt
|
train
|
d3d84f3124ca16ba32d33dac39bafaaf68e0713a
|
diff --git a/js/views/new_conversation_view.js b/js/views/new_conversation_view.js
index <HASH>..<HASH> 100644
--- a/js/views/new_conversation_view.js
+++ b/js/views/new_conversation_view.js
@@ -19,7 +19,7 @@ var Whisper = Whisper || {};
'use strict';
var typeahead = Backbone.TypeaheadCollection.extend({
- typeaheadAttributes: ['name'],
+ typeaheadAttributes: ['name', 'members'],
database: Whisper.Database,
storeName: 'conversations',
model: Whisper.Conversation,
|
Let typeahead surface groups with matching members
|
ForstaLabs_librelay-node
|
train
|
88da43534bfcfce6c9ac8786672958112a3d511b
|
diff --git a/src/finishing.js b/src/finishing.js
index <HASH>..<HASH> 100644
--- a/src/finishing.js
+++ b/src/finishing.js
@@ -48,17 +48,8 @@ export function tryToSetFocus(result) {
focusedViews.forEach((focusedView, idx) => {
focusedView.removeAttribute("data-jsua-focus");
if (idx !== 0) return;
-
- let addTabIndex = !focusedView.hasAttribute("tabindex");
- if (addTabIndex) focusedView.setAttribute("tabindex", -1);
-
- if (focusedView.setActive) {
- focusedView.setActive();
- } else {
- focusedView.focus();
- }
-
- if (addTabIndex) focusedView.removeAttribute("tabindex");
+ focusedView.scrollIntoView();
+ focusedView.focus();
});
}
diff --git a/src/index.js b/src/index.js
index <HASH>..<HASH> 100644
--- a/src/index.js
+++ b/src/index.js
@@ -12,7 +12,7 @@ function fetch(url, options) {
var sameDocumentReferenceView = findSameDocumentReferenceView(appView, urlObj, options);
if (sameDocumentReferenceView) {
if (sameDocumentReferenceView === appView) {
- window.scroll(0, 0);
+ scrollAppViewToTop(appView);
} else {
sameDocumentReferenceView.setAttribute("data-jsua-focus", true);
finishing.tryToSetFocus({ view: sameDocumentReferenceView });
@@ -56,6 +56,15 @@ function findSameDocumentReferenceView(appView, urlObj, options) {
return appView.querySelector("[data-jsua-view-uri='" + urlObj.href + "']");
}
+function scrollAppViewToTop(appView) {
+ var firstScrollableView = Array.from(appView.querySelectorAll("*"))
+ .find(el => el.style.overflowY === "scroll");
+
+ if (firstScrollableView) {
+ firstScrollableView.scrollTop = 0;
+ }
+}
+
function findAppViewFor(view) {
if (!view) return;
|
Simplify Scroll/Focus Strategy
|
lynx-json_jsua
|
train
|
59077566cfb0e002377ad3d2c959f02161ccc7e2
|
diff --git a/src/Kunstmaan/GeneratorBundle/Resources/SensioGeneratorBundle/skeleton/defaultsite/DataFixtures/ORM/DefaultSiteGenerator/SitemapFixtures.php b/src/Kunstmaan/GeneratorBundle/Resources/SensioGeneratorBundle/skeleton/defaultsite/DataFixtures/ORM/DefaultSiteGenerator/SitemapFixtures.php
index <HASH>..<HASH> 100644
--- a/src/Kunstmaan/GeneratorBundle/Resources/SensioGeneratorBundle/skeleton/defaultsite/DataFixtures/ORM/DefaultSiteGenerator/SitemapFixtures.php
+++ b/src/Kunstmaan/GeneratorBundle/Resources/SensioGeneratorBundle/skeleton/defaultsite/DataFixtures/ORM/DefaultSiteGenerator/SitemapFixtures.php
@@ -56,7 +56,7 @@ class SitemapFixtures extends AbstractFixture implements OrderedFixtureInterface
'page_internal_name' => 'sitemap',
'set_online' => true,
'hidden_from_nav' => true,
- 'creator' => 'Admin'
+ 'creator' => 'admin'
);
$pageCreator->createPage($sitemapPage, $translations, $options);
|
Username is not capitialized
|
Kunstmaan_KunstmaanBundlesCMS
|
train
|
79292582cf27eca2a4e66ecd325417c34f46e300
|
diff --git a/tests/test_parser.py b/tests/test_parser.py
index <HASH>..<HASH> 100644
--- a/tests/test_parser.py
+++ b/tests/test_parser.py
@@ -277,6 +277,12 @@ class TestRDDLyacc(unittest.TestCase):
i1 = KronDelta(p + Bernoulli( (p + q + r)/3.0 ) + r); // Just set i1 to a count of true state variables
+ picTaken'(?p) = picTaken(?p) == true | ~notPicTaken(?p) &
+ [~snapPicture ~= false ^ (time <= MAX_TIME)
+ & (PICT_ERROR_ALLOW(?p) > abs[xPos - PICT_XPOS(?p)])
+ ^ ~(abs[yPos - PICT_YPOS(?p)] == PICT_ERROR_ALLOW(?p))];
+
+
};
}
@@ -528,6 +534,38 @@ class TestRDDLyacc(unittest.TestCase):
'-',
('i1', None),
0.2
+ ],
+ "picTaken'": [
+ '|',
+ '==',
+ ('picTaken', ['?p']),
+ True,
+ '&',
+ '~',
+ ('notPicTaken', ['?p']),
+ '^',
+ '&',
+ '^',
+ '~=',
+ '~',
+ ('snapPicture', None),
+ False,
+ '<=',
+ ('time', None),
+ ('MAX_TIME', None),
+ '>',
+ ('PICT_ERROR_ALLOW', ['?p']),
+ 'abs',
+ '-',
+ ('xPos', None),
+ ('PICT_XPOS', ['?p']),
+ '~',
+ '==',
+ 'abs',
+ '-',
+ ('yPos', None),
+ ('PICT_YPOS', ['?p']),
+ ('PICT_ERROR_ALLOW', ['?p'])
]
}
@@ -549,6 +587,8 @@ class TestRDDLyacc(unittest.TestCase):
self.assertEqual(expr[1], expected[i])
else:
self.assertAlmostEqual(expr[1], expected[i])
+ elif expr[0] == 'boolean':
+ self.assertEqual(expr[1], expected[i])
elif expr[0] == 'func':
self.assertEqual(expr[1][0], expected[i])
for subexpr in expr[1][1][::-1]:
diff --git a/tfrddlsim/parser.py b/tfrddlsim/parser.py
index <HASH>..<HASH> 100644
--- a/tfrddlsim/parser.py
+++ b/tfrddlsim/parser.py
@@ -211,6 +211,13 @@ class RDDLParser(object):
self.tokens = self.lexer.tokens
self.precedence = (
+ ('left', 'ASSIGN_EQUAL'),
+ ('left', 'EQUIV'),
+ ('left', 'IMPLY'),
+ ('left', 'OR'),
+ ('left', 'AND', 'AMPERSAND'),
+ ('left', 'NOT'),
+ ('left', 'COMP_EQUAL', 'NEQ', 'LESS', 'LESSEQ', 'GREATER', 'GREATEREQ'),
('left', 'PLUS', 'MINUS'),
('left', 'TIMES', 'DIV'),
('right', 'UMINUS')
@@ -387,6 +394,8 @@ class RDDLParser(object):
'''expr : pvar_expr
| group_expr
| function_expr
+ | relational_expr
+ | boolean_expr
| numerical_expr
| randomvar_expr'''
p[0] = p[1]
@@ -408,6 +417,30 @@ class RDDLParser(object):
'''function_expr : IDENT LBRACK expr_list RBRACK'''
p[0] = ('func', (p[1], p[3]))
+ def p_relational_expr(self, p):
+ '''relational_expr : expr COMP_EQUAL expr
+ | expr NEQ expr
+ | expr GREATER expr
+ | expr GREATEREQ expr
+ | expr LESS expr
+ | expr LESSEQ expr'''
+ p[0] = (p[2], (p[1], p[3]))
+
+ def p_boolean_expr(self, p):
+ '''boolean_expr : expr AND expr
+ | expr AMPERSAND expr
+ | expr OR expr
+ | expr IMPLY expr
+ | expr EQUIV expr
+ | NOT expr %prec UMINUS
+ | bool_type'''
+ if len(p) == 4:
+ p[0] = (p[2], (p[1], p[3]))
+ elif len(p) == 3:
+ p[0] = (p[1], (p[2],))
+ elif len(p) == 2:
+ p[0] = ('boolean', p[1])
+
def p_numerical_expr(self, p):
'''numerical_expr : expr PLUS expr
| expr MINUS expr
@@ -489,7 +522,7 @@ class RDDLParser(object):
def p_bool_type(self, p):
'''bool_type : TRUE
| FALSE'''
- p[0] = True if p[1] == 'TRUE' else False
+ p[0] = True if p[1] == 'true' else False
def p_double_type(self, p):
'''double_type : DOUBLE
|
Parse relational and boolean expressions in cpfs
|
thiagopbueno_tf-rddlsim
|
train
|
4b428cbdeb6c09cbf7746665c6aef056792fe1b8
|
diff --git a/spec/datagrid/helper_spec.rb b/spec/datagrid/helper_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/datagrid/helper_spec.rb
+++ b/spec/datagrid/helper_spec.rb
@@ -7,13 +7,14 @@ require 'datagrid/renderer'
describe Datagrid::Helper do
subject do
template = ActionView::Base.new
+ template.stub(:protect_against_forgery?).and_return(false)
template.view_paths << File.expand_path("../../../app/views", __FILE__)
template.view_paths << File.expand_path("../../support/test_partials", __FILE__)
template
end
before(:each) do
- subject.stub!(:params).and_return({})
+ subject.stub(:params).and_return({})
subject.stub(:url_for) do |options|
options.to_param
end
|
Make tests for helper_spec to work
* get rid of deprecations for stub!
* fix exception in the test about protect_against_forgery? is not
* defined
|
bogdan_datagrid
|
train
|
2fc77fd3bc2b6e8f01663a3c915fc1caf869a4b8
|
diff --git a/lib/ohai/plugins/dmi.rb b/lib/ohai/plugins/dmi.rb
index <HASH>..<HASH> 100644
--- a/lib/ohai/plugins/dmi.rb
+++ b/lib/ohai/plugins/dmi.rb
@@ -90,9 +90,8 @@ table_location_line = /^Table at (0x[0-9A-E]+)\./
dmi_record = nil
field = nil
-popen4("dmidecode") do |pid, stdin, stdout, stderr|
- stdin.close
-
+status, stdout, stderr = run_command(:no_status_check => true, :command => "dmidecode")
+if status == 0
# ==== EXAMPLE RECORD: ====
#Handle 0x0000, DMI type 0, 24 bytes
#BIOS Information
|
[OHAI-<I>] use run_command instead of popen4 (for windows support)
|
chef_ohai
|
train
|
fd93daceebf20de3e75f0ac5551fe601dd20f0f5
|
diff --git a/pythainlp/transliterate/royin.py b/pythainlp/transliterate/royin.py
index <HASH>..<HASH> 100644
--- a/pythainlp/transliterate/royin.py
+++ b/pythainlp/transliterate/royin.py
@@ -166,12 +166,16 @@ def _replace_consonants(word: str, consonants: str) -> str:
consonants[0], _CONSONANTS[consonants[0]][0]
)
i += 1
- elif consonants[i] == _RO_RUA and word[i] == _RO_RUA:
- if i + 1 == len(word):
+ elif consonants[i] == _RO_RUA and i>=len(word) and word[i-1]== _RO_RUA:
+ word = word.replace(
+ consonants[i], _CONSONANTS[consonants[i]][1]
+ )
+ elif consonants[i] == _RO_RUA and i < len(word):
+ if i + 1 == len(word) and word[i] == _RO_RUA:
word = word.replace(
consonants[i], _CONSONANTS[consonants[i]][1]
)
- elif word[i + 1] == _RO_RUA:
+ elif word[i + 1] == _RO_RUA and word[i] == _RO_RUA:
word = list(word)
del word[i + 1]
if i + 2 == len_cons:
@@ -180,11 +184,14 @@ def _replace_consonants(word: str, consonants: str) -> str:
word[i] = "a"
word = "".join(word)
i += 1
- else:
+ elif word[i] == _RO_RUA:
word = word.replace(
consonants[i], _CONSONANTS[consonants[i]][1]
)
i += 1
+ else:
+ word = word.replace(consonants[i], _CONSONANTS[consonants[i]][1])
+ i += 1
else:
word = word.replace(consonants[i], _CONSONANTS[consonants[i]][1])
i += 1
|
Fixed #<I>
Fixed Romanize failed in some examples #<I>
|
PyThaiNLP_pythainlp
|
train
|
ce30074aad7db038966ae7a995f0697981acd947
|
diff --git a/src/cloudant/database.py b/src/cloudant/database.py
index <HASH>..<HASH> 100644
--- a/src/cloudant/database.py
+++ b/src/cloudant/database.py
@@ -386,14 +386,30 @@ class CouchDatabase(dict):
resp.raise_for_status()
return resp.json()
- def db_updates(self):
+ def db_updates(self, since=None, continuous=True, include_docs=False):
"""
- GET /_db_updates Returns information about databases that have been
- updated
+ _db_updates_
+
+ Implement streaming from _db_updates feed. Yields information about
+ databases that have been updated
+
+ :param str since: Start from this sequence
+ :param boolean continuous: Stream results?
+ :param boolean include_docs: Include/exclude document bodies in the
+ results
"""
+ db_updates_feed = Feed(
+ self._r_session,
+ posixpath.join(self._database_host, '_db_updates'),
+ since=since,
+ continuous=continuous,
+ include_docs=include_docs
+ )
- pass
+ for update in db_updates_feed:
+ if update:
+ yield update
class CloudantDatabase(CouchDatabase):
|
add support for _db_updates feed
|
cloudant_python-cloudant
|
train
|
011a712c0d36dee886e0337e9367adee50b9a2dc
|
diff --git a/src/Web/Routing/LocaleControllerCollection.php b/src/Web/Routing/LocaleControllerCollection.php
index <HASH>..<HASH> 100644
--- a/src/Web/Routing/LocaleControllerCollection.php
+++ b/src/Web/Routing/LocaleControllerCollection.php
@@ -13,8 +13,7 @@ use Silex\Route;
class LocaleControllerCollection extends PrefixedVariableControllerCollection {
public function __construct(Route $defaultRoute, $supportedLocales = array()) {
- parent::__construct($defaultRoute);
- $this->variableRequirement = implode('|', $supportedLocales);
+ parent::__construct($defaultRoute, implode('|', $supportedLocales));
}
/**
diff --git a/src/Web/Routing/PrefixedVariableControllerCollection.php b/src/Web/Routing/PrefixedVariableControllerCollection.php
index <HASH>..<HASH> 100644
--- a/src/Web/Routing/PrefixedVariableControllerCollection.php
+++ b/src/Web/Routing/PrefixedVariableControllerCollection.php
@@ -3,6 +3,7 @@ namespace GMO\Common\Web\Routing;
use Silex;
use Silex\Controller;
+use Silex\Route;
use Symfony\Component\Routing\RouteCollection;
/**
@@ -19,6 +20,11 @@ abstract class PrefixedVariableControllerCollection extends ControllerCollection
/** @var string|null The requirement for the variable */
protected $variableRequirement = null;
+ public function __construct(Route $defaultRoute, $variableRequirement = null) {
+ parent::__construct($defaultRoute);
+ $this->variableRequirement = $variableRequirement;
+ }
+
/**
* Returns the variable name
*
@@ -26,13 +32,18 @@ abstract class PrefixedVariableControllerCollection extends ControllerCollection
*/
abstract protected function getVariableName();
+ protected function getVariableRequirement() {
+ return $this->variableRequirement;
+ }
+
protected function getVariablePrefix($prefix) {
return sprintf('/{%s}%s', $this->getVariableName(), $prefix);
}
protected function flushController($prefix, Controller $controller, RouteCollection $routes) {
- if ($this->variableRequirement) {
- $controller->assert($this->getVariableName(), $this->variableRequirement);
+ $requirement = $this->getVariableRequirement();
+ if ($requirement) {
+ $controller->assert($this->getVariableName(), $requirement);
}
// Clone current controller for unprefixed route
|
[ControllerCollection] Passing variable requirement through constructor. Added getter so it can be overridden later.
|
gmo_common
|
train
|
44e0e9436c7abd7e4f62b944193a331c74d4f93c
|
diff --git a/src/test/java/net/joelinn/quartz/BaseTest.java b/src/test/java/net/joelinn/quartz/BaseTest.java
index <HASH>..<HASH> 100644
--- a/src/test/java/net/joelinn/quartz/BaseTest.java
+++ b/src/test/java/net/joelinn/quartz/BaseTest.java
@@ -52,7 +52,6 @@ public abstract class BaseTest {
logger.debug("Attempting to start embedded Redis server on port " + port);
redisServer = RedisServer.builder()
.port(port)
- .setting("maxheap 1000000000")
.build();
redisServer.start();
final short database = 1;
|
Remove Redis maxheap setting in BaseTest
|
jlinn_quartz-redis-jobstore
|
train
|
d768adda211509547242bf8a12ecb30b171901df
|
diff --git a/src/main/java/io/github/bonigarcia/wdm/ResolutionCache.java b/src/main/java/io/github/bonigarcia/wdm/ResolutionCache.java
index <HASH>..<HASH> 100644
--- a/src/main/java/io/github/bonigarcia/wdm/ResolutionCache.java
+++ b/src/main/java/io/github/bonigarcia/wdm/ResolutionCache.java
@@ -23,7 +23,6 @@ import static org.slf4j.LoggerFactory.getLogger;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
-import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.ParseException;
@@ -73,8 +72,7 @@ public class ResolutionCache {
this.resolutionCacheFile = new File(config.getTargetPath(),
config.getResolutionCache());
- InputStream fis = null;
- try {
+ try (InputStream fis = new FileInputStream(resolutionCacheFile)) {
if (!resolutionCacheFile.exists()) {
boolean createNewFile = resolutionCacheFile.createNewFile();
if (createNewFile) {
@@ -82,22 +80,11 @@ public class ResolutionCache {
resolutionCacheFile);
}
}
- fis = new FileInputStream(resolutionCacheFile);
props.load(fis);
} catch (Exception e) {
throw new WebDriverManagerException(
"Exception reading resolution cache as a properties file",
e);
- } finally {
- if (fis != null) {
- try {
- fis.close();
- } catch (IOException e) {
- log.warn(
- "Exception closing resolution cache as a properties file {}",
- e.getMessage());
- }
- }
}
}
@@ -135,24 +122,12 @@ public class ResolutionCache {
}
private synchronized void storeProperties() {
- OutputStream fos = null;
- try {
- fos = new FileOutputStream(resolutionCacheFile);
+ try (OutputStream fos = new FileOutputStream(resolutionCacheFile)) {
props.store(fos, RESOLUTION_CACHE_INFO);
} catch (Exception e) {
log.warn(
"Exception writing resolution cache as a properties file {}",
e.getClass().getName());
- } finally {
- if (fos != null) {
- try {
- fos.close();
- } catch (IOException e) {
- log.warn(
- "Exception closing resolution cache as a properties file {}",
- e.getMessage());
- }
- }
}
}
@@ -170,7 +145,8 @@ public class ResolutionCache {
private boolean checkValidity(String key, String value,
Date expirationDate) {
long now = new Date().getTime();
- long expirationTime = expirationDate.getTime();
+ long expirationTime = expirationDate != null ? expirationDate.getTime()
+ : 0;
boolean isValid = value != null && expirationTime != 0
&& expirationTime > now;
if (!isValid) {
@@ -198,8 +174,9 @@ public class ResolutionCache {
valueInResolutionCache &= checkValidity(key,
valueFromResolutionCache, expirationDate);
if (valueInResolutionCache) {
+ String strDate = formatDate(expirationDate);
log.debug("Resolution {}={} in cache (valid until {})", key,
- valueFromResolutionCache, formatDate(expirationDate));
+ valueFromResolutionCache, strDate);
}
}
return valueInResolutionCache;
|
More smell-fixes in resolution cache logic
|
bonigarcia_webdrivermanager
|
train
|
853f4932a6ce817c7dd9b371963bad18642e125f
|
diff --git a/datascience/tables.py b/datascience/tables.py
index <HASH>..<HASH> 100644
--- a/datascience/tables.py
+++ b/datascience/tables.py
@@ -1891,7 +1891,39 @@ class Table(collections.abc.MutableMapping):
return binned
def move_column(self, label, index):
- """Returns a new table with specified column moved to the specified column index."""
+ """Returns a new table with specified column moved to the specified column index.
+
+ Args:
+ ``label`` (str) A single label of column to be moved.
+
+ ``index`` (int) A single index of column to move to.
+
+ >>> titanic = Table().with_columns('age', make_array(21, 44, 56, 89, 95
+ ... , 40, 80, 45), 'survival', make_array(0,0,0,1, 1, 1, 0, 1),
+ ... 'gender', make_array('M', 'M', 'M', 'M', 'F', 'F', 'F', 'F'),
+ ... 'prediction', make_array(0, 0, 1, 1, 0, 1, 0, 1))
+ >>> titanic
+ age | survival | gender | prediction
+ 21 | 0 | M | 0
+ 44 | 0 | M | 0
+ 56 | 0 | M | 1
+ 89 | 1 | M | 1
+ 95 | 1 | F | 0
+ 40 | 1 | F | 1
+ 80 | 0 | F | 0
+ 45 | 1 | F | 1
+ >>> titanic.move_column('survival', 3)
+ age | gender | prediction | survival
+ 21 | M | 0 | 0
+ 44 | M | 0 | 0
+ 56 | M | 1 | 0
+ 89 | M | 1 | 1
+ 95 | F | 0 | 1
+ 40 | F | 1 | 1
+ 80 | F | 0 | 0
+ 45 | F | 1 | 1
+ """
+
table = type(self)()
col_order = list(self._columns)
label_idx = col_order.index(self._as_label(label))
|
tables.py: edited doc string
added more details in the docstring
including example of how the docstring can be used
Completed one item in todo list of <URL>
|
data-8_datascience
|
train
|
721755df5fb7fa0e9db43025d642c12785f5d606
|
diff --git a/src/util/path.js b/src/util/path.js
index <HASH>..<HASH> 100644
--- a/src/util/path.js
+++ b/src/util/path.js
@@ -5,11 +5,12 @@ export function resolvePath (
base: string,
append?: boolean
): string {
- if (relative.charAt(0) === '/') {
+ const firstChar = relative.charAt(0)
+ if (firstChar === '/') {
return relative
}
- if (relative.charAt(0) === '?' || relative.charAt(0) === '#') {
+ if (firstChar === '?' || firstChar === '#') {
return base + relative
}
@@ -26,11 +27,9 @@ export function resolvePath (
const segments = relative.replace(/^\//, '').split('/')
for (let i = 0; i < segments.length; i++) {
const segment = segments[i]
- if (segment === '.') {
- continue
- } else if (segment === '..') {
+ if (segment === '..') {
stack.pop()
- } else {
+ } else if (segment !== '.') {
stack.push(segment)
}
}
|
small tweaks on resolvePath function (#<I>)
|
vuejs_vue-router
|
train
|
f00870ed3180931b28e3ab6b6785f9191b433d9a
|
diff --git a/crispy_forms/tests/test_layout_objects.py b/crispy_forms/tests/test_layout_objects.py
index <HASH>..<HASH> 100644
--- a/crispy_forms/tests/test_layout_objects.py
+++ b/crispy_forms/tests/test_layout_objects.py
@@ -133,6 +133,17 @@ def test_i18n():
assert "Introduzca un valor correcto" in html
deactivate()
+def test_remove_labels():
+ form = SampleForm()
+ #remove boolean field as label is still printed in boostrap
+ del form.fields['is_company']
+
+ for fields in form:
+ fields.label = False
+
+ html = render_crispy_form(form)
+
+ assert '<label' not in html
@only_bootstrap
class TestBootstrapLayoutObjects(object):
@@ -150,7 +161,7 @@ class TestBootstrapLayoutObjects(object):
form.helper = FormHelper()
form.helper.layout = Layout('inline_radios')
- html = render_crispy_form(form)
+ html = render_crispy_form(form)
if settings.CRISPY_TEMPLATE_PACK == 'bootstrap4':
assert 'class="custom-control-input"' in html
else:
|
Test that labels do not print when label = False (#<I>)
|
django-crispy-forms_django-crispy-forms
|
train
|
6979b115a11ba6a02126708afb59b621940261ca
|
diff --git a/src/Illuminate/Notifications/Channels/MailChannel.php b/src/Illuminate/Notifications/Channels/MailChannel.php
index <HASH>..<HASH> 100644
--- a/src/Illuminate/Notifications/Channels/MailChannel.php
+++ b/src/Illuminate/Notifications/Channels/MailChannel.php
@@ -112,6 +112,7 @@ class MailChannel
protected function additionalMessageData($notification)
{
return [
+ '__laravel_notification_id' => $notification->id,
'__laravel_notification' => get_class($notification),
'__laravel_notification_queued' => in_array(
ShouldQueue::class, class_implements($notification)
diff --git a/tests/Integration/Notifications/SendingMailNotificationsTest.php b/tests/Integration/Notifications/SendingMailNotificationsTest.php
index <HASH>..<HASH> 100644
--- a/tests/Integration/Notifications/SendingMailNotificationsTest.php
+++ b/tests/Integration/Notifications/SendingMailNotificationsTest.php
@@ -13,6 +13,7 @@ use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Notifications\Notifiable;
use Illuminate\Notifications\Notification;
use Illuminate\Support\Facades\Schema;
+use Illuminate\Support\Str;
use Mockery as m;
use Orchestra\Testbench\TestCase;
@@ -69,6 +70,7 @@ class SendingMailNotificationsTest extends TestCase
public function testMailIsSent()
{
$notification = new TestMailNotification;
+ $notification->id = Str::uuid()->toString();
$user = NotifiableUser::forceCreate([
'email' => 'taylor@laravel.com',
@@ -80,6 +82,7 @@ class SendingMailNotificationsTest extends TestCase
$this->mailer->shouldReceive('send')->once()->with(
['html' => 'htmlContent', 'text' => 'textContent'],
array_merge($notification->toMail($user)->toArray(), [
+ '__laravel_notification_id' => $notification->id,
'__laravel_notification' => get_class($notification),
'__laravel_notification_queued' => false,
]),
@@ -112,6 +115,7 @@ class SendingMailNotificationsTest extends TestCase
public function testMailIsSentToNamedAddress()
{
$notification = new TestMailNotification;
+ $notification->id = Str::uuid()->toString();
$user = NotifiableUserWithNamedAddress::forceCreate([
'email' => 'taylor@laravel.com',
@@ -124,6 +128,7 @@ class SendingMailNotificationsTest extends TestCase
$this->mailer->shouldReceive('send')->once()->with(
['html' => 'htmlContent', 'text' => 'textContent'],
array_merge($notification->toMail($user)->toArray(), [
+ '__laravel_notification_id' => $notification->id,
'__laravel_notification' => get_class($notification),
'__laravel_notification_queued' => false,
]),
@@ -156,6 +161,7 @@ class SendingMailNotificationsTest extends TestCase
public function testMailIsSentWithSubject()
{
$notification = new TestMailNotificationWithSubject;
+ $notification->id = Str::uuid()->toString();
$user = NotifiableUser::forceCreate([
'email' => 'taylor@laravel.com',
@@ -167,6 +173,7 @@ class SendingMailNotificationsTest extends TestCase
$this->mailer->shouldReceive('send')->once()->with(
['html' => 'htmlContent', 'text' => 'textContent'],
array_merge($notification->toMail($user)->toArray(), [
+ '__laravel_notification_id' => $notification->id,
'__laravel_notification' => get_class($notification),
'__laravel_notification_queued' => false,
]),
@@ -189,6 +196,7 @@ class SendingMailNotificationsTest extends TestCase
public function testMailIsSentToMultipleAdresses()
{
$notification = new TestMailNotificationWithSubject;
+ $notification->id = Str::uuid()->toString();
$user = NotifiableUserWithMultipleAddreses::forceCreate([
'email' => 'taylor@laravel.com',
@@ -200,6 +208,7 @@ class SendingMailNotificationsTest extends TestCase
$this->mailer->shouldReceive('send')->once()->with(
['html' => 'htmlContent', 'text' => 'textContent'],
array_merge($notification->toMail($user)->toArray(), [
+ '__laravel_notification_id' => $notification->id,
'__laravel_notification' => get_class($notification),
'__laravel_notification_queued' => false,
]),
|
[6.x] Expose Notification Id within Message Data (#<I>)
* Expose Laravel Notification Id within Message Data
* Updating tests
* Fixing tests
* Fixing the test for <I>
|
laravel_framework
|
train
|
f1344692162d1314c83997ba17cdbf2ca9835957
|
diff --git a/go/test/endtoend/onlineddl_vrepl_stress/onlineddl_vrepl_mini_stress_test.go b/go/test/endtoend/onlineddl_vrepl_stress/onlineddl_vrepl_mini_stress_test.go
index <HASH>..<HASH> 100644
--- a/go/test/endtoend/onlineddl_vrepl_stress/onlineddl_vrepl_mini_stress_test.go
+++ b/go/test/endtoend/onlineddl_vrepl_stress/onlineddl_vrepl_mini_stress_test.go
@@ -106,7 +106,7 @@ var (
ALTER TABLE stress_test modify hint_col varchar(64) not null default '%s'
`
insertRowStatement = `
- INSERT IGNORE INTO stress_test (id, rand_val) VALUES (%d, left(md5(rand()), 8))
+ INSERT INTO stress_test (id, rand_val) VALUES (%d, left(md5(rand()), 8))
`
updateRowStatement = `
UPDATE stress_test SET updates=updates+1 WHERE id=%d
@@ -213,9 +213,27 @@ func TestSchemaChange(t *testing.T) {
testWithInitialSchema(t)
})
for i := 0; i < countIterations; i++ {
+ testName := fmt.Sprintf("init table %d/%d", (i + 1), countIterations)
+ t.Run(testName, func(t *testing.T) {
+ initTable(t)
+ testSelectTableMetrics(t)
+ })
+ }
+ for i := 0; i < countIterations; i++ {
testName := fmt.Sprintf("workload without ALTER TABLE %d/%d", (i + 1), countIterations)
t.Run(testName, func(t *testing.T) {
+ ctx := context.Background()
initTable(t)
+ done := make(chan bool)
+ var wg sync.WaitGroup
+ wg.Add(1)
+ go func() {
+ defer wg.Done()
+ runMultipleConnections(ctx, t, done)
+ }()
+ time.Sleep(5 * time.Second)
+ done <- true
+ wg.Wait()
testSelectTableMetrics(t)
})
}
@@ -227,17 +245,23 @@ func TestSchemaChange(t *testing.T) {
testSelectTableMetrics(t)
})
- ctx := context.Background()
for i := 0; i < countIterations; i++ {
testName := fmt.Sprintf("ALTER TABLE with workload %d/%d", (i + 1), countIterations)
t.Run(testName, func(t *testing.T) {
+ ctx := context.Background()
initTable(t)
done := make(chan bool)
- go runMultipleConnections(ctx, t, done)
+ var wg sync.WaitGroup
+ wg.Add(1)
+ go func() {
+ defer wg.Done()
+ runMultipleConnections(ctx, t, done)
+ }()
hint := fmt.Sprintf("hint-alter-with-workload-%d", i)
uuid := testOnlineDDLStatement(t, fmt.Sprintf(alterHintStatement, hint), "online", "vtgate", hint)
checkRecentMigrations(t, uuid, schema.OnlineDDLStatusComplete)
done <- true
+ wg.Wait()
testSelectTableMetrics(t)
})
}
@@ -447,6 +471,8 @@ func runSingleConnection(ctx context.Context, t *testing.T, done chan bool, wg *
if err != nil {
if strings.Contains(err.Error(), "disallowed due to rule: enforce blacklisted tables") {
err = nil
+ } else if strings.Contains(err.Error(), "AlreadyExists") {
+ err = nil
}
}
assert.Nil(t, err)
|
wait for runMultipleConnections() to complete
|
vitessio_vitess
|
train
|
23432fc069c74397c40397fe62cdbfefb7e4ed90
|
diff --git a/ca/django_ca/admin.py b/ca/django_ca/admin.py
index <HASH>..<HASH> 100644
--- a/ca/django_ca/admin.py
+++ b/ca/django_ca/admin.py
@@ -512,7 +512,10 @@ class CertificateAdmin(DjangoObjectActions, CertificateMixin, admin.ModelAdmin):
return urls
def resign(self, request, obj):
- # TODO: if there is no CSR, redirect back to change form with error message
+ if not obj.csr:
+ self.message_user(request, _('Certificate has no CSR (most likely because it was imported.'),
+ messages.ERROR)
+ return HttpResponseRedirect(obj.admin_change_url)
request._resign_obj = obj
extra_context = {
|
catch corner case if cert has no CSR
|
mathiasertl_django-ca
|
train
|
73e9f605dacb07ca5d3afae1adf7002e7ceaa93a
|
diff --git a/molecule/core.py b/molecule/core.py
index <HASH>..<HASH> 100644
--- a/molecule/core.py
+++ b/molecule/core.py
@@ -44,7 +44,6 @@ class Molecule(object):
self.config = config
self.args = args
self._verifier = self._get_verifier()
- self._verifier_options = self._get_verifier_options()
self._dependencies = self._get_dependencies()
self._disabled = self._get_disabled()
@@ -97,14 +96,6 @@ class Molecule(object):
self._verifier = val
@property
- def verifier_options(self):
- return self._verifier_options
-
- @verifier_options.setter
- def verifier_options(self, val):
- self._verifier_options = val
-
- @property
def dependencies(self):
return self._dependencies
@@ -378,12 +369,6 @@ class Molecule(object):
return 'testinfra'
return self.config.config['verifier']['name']
- def _get_verifier_options(self):
- # Preserve backward compatibility with old testinfra override
- # syntax.
- return self.config.config.get(
- 'testinfra', self.config.config['verifier'].get('options', {}))
-
def _get_dependencies(self):
if self.config.config.get('dependencies'):
return 'galaxy'
diff --git a/molecule/verifier/testinfra.py b/molecule/verifier/testinfra.py
index <HASH>..<HASH> 100644
--- a/molecule/verifier/testinfra.py
+++ b/molecule/verifier/testinfra.py
@@ -53,7 +53,7 @@ class Testinfra(base.Base):
testinfra_options = config.merge_dicts(
self._molecule.driver.testinfra_args,
- self._molecule.verifier_options)
+ self._molecule.config.config['verifier']['options'])
testinfra_options['ansible_env'] = ansible.env
if self._molecule.args.get('debug'):
diff --git a/test/unit/core/test_core.py b/test/unit/core/test_core.py
index <HASH>..<HASH> 100644
--- a/test/unit/core/test_core.py
+++ b/test/unit/core/test_core.py
@@ -71,24 +71,6 @@ def test_verifier_backward_compatible(molecule_instance):
assert 'testinfra' == m.verifier
-def test_verifier_options_setter(molecule_instance):
- molecule_instance.verifier_options = 'foo'
-
- assert 'foo' == molecule_instance.verifier_options
-
-
-def test_verifier_options(molecule_instance):
- assert {} == molecule_instance.verifier_options
-
-
-def test_verifier_options_backward_compatible(molecule_instance):
- m = molecule_instance
- m.config.config['testinfra'] = {'foo': 'bar'}
- m.verifier_options = m._get_verifier_options()
-
- assert {'foo': 'bar'} == m.verifier_options
-
-
def test_verifier_disabled_setter(molecule_instance):
molecule_instance.disabled = 'foo'
|
Removed testinfra config backward compatibility (#<I>)
Breaking Change: The testinfra override options have been moved to the
`verifier` section of molecule's config. No longer supporting the old
syntax.
|
ansible_molecule
|
train
|
c324e57dfe9aff8f396431e53d8ecdff6debdb02
|
diff --git a/src/Cache.php b/src/Cache.php
index <HASH>..<HASH> 100644
--- a/src/Cache.php
+++ b/src/Cache.php
@@ -351,7 +351,9 @@ class Cache extends \yii\caching\Cache
do {
list($cursor, $keys) = $this->redis->scan($cursor, 'MATCH', $this->keyPrefix . '*');
$cursor = (int) $cursor;
- $this->redis->executeCommand('DEL', $keys);
+ if (!empty($keys)) {
+ $this->redis->executeCommand('DEL', $keys);
+ }
} while ($cursor !== 0);
return true;
|
Fix 'DEL' command in `Cache::flushValues()` when `$shareDatabase` is enabled. (#<I>, #<I>)
|
yiisoft_yii2-redis
|
train
|
2697418f805ded3d981f79195109607da49ec401
|
diff --git a/spec/spec_helper.rb b/spec/spec_helper.rb
index <HASH>..<HASH> 100644
--- a/spec/spec_helper.rb
+++ b/spec/spec_helper.rb
@@ -1,15 +1,16 @@
require 'simplecov'
require 'codeclimate-test-reporter'
-require 'pilot-gnuplot'
require 'digest'
require 'chunky_png'
require 'digest/md5'
-
SimpleCov.add_filter 'vendor'
SimpleCov.add_filter 'samples'
SimpleCov.formatter = CodeClimate::TestReporter::Formatter
SimpleCov.start CodeClimate::TestReporter.configuration.profile
+require 'pilot-gnuplot'
+
+
include ChunkyPNG::Color
def same_images?(*imgs)
|
spec fix: require gem after codeclimate reporter
|
dilcom_gnuplotrb
|
train
|
28caa2bfbd8ce1b0a4a3bff11ee4ce146f037b32
|
diff --git a/salt/cloud/clouds/ec2.py b/salt/cloud/clouds/ec2.py
index <HASH>..<HASH> 100644
--- a/salt/cloud/clouds/ec2.py
+++ b/salt/cloud/clouds/ec2.py
@@ -2064,9 +2064,10 @@ def query_instance(vm_=None, call=None):
log.debug('Returned query data: {0}'.format(data))
- if 'ipAddress' in data[0]['instancesSet']['item']:
+ if ssh_interface(vm_) == 'public_ips' and 'ipAddress' in data[0]['instancesSet']['item']:
log.error(
- 'Public IP not detected. If private IP is meant for bootstrap you must specify "ssh_interface: private_ips" in your profile.'
+ 'Public IP not detected. If private IP is meant for bootstrap you must specify '
+ '"ssh_interface: private_ips" in your profile.'
)
return data
if ssh_interface(vm_) == 'private_ips' and \
|
Gate the Public IP ssh_interfaces warning a little better
Fixes #<I>
This error warning would still show up in the logs, even if
ssh_interface was set to private_ips.
|
saltstack_salt
|
train
|
85aca11cf86caca7e501749fd394dfb61d13c376
|
diff --git a/config.js b/config.js
index <HASH>..<HASH> 100644
--- a/config.js
+++ b/config.js
@@ -116,10 +116,10 @@ config.auditLogScope = [];
* Specifiies the TTL (time to live/lifetime/expiration) of Audit Log entries. Accepts values in seconds unless specified
* (Ex: 60 = 60 seconds, '1w' = 1 week, or '1d' = 1 day)
* See: http://nicoll.io/mongottl/
- * default: 0 (does not expire)
+ * default: null (does not expire)
* @type {string}
*/
-config.auditLogTTL = 0;
+config.auditLogTTL = null;
/**
* Enables policies via mrhorse (https://github.com/mark-bradshaw/mrhorse).
diff --git a/models/audit-log.model.js b/models/audit-log.model.js
index <HASH>..<HASH> 100644
--- a/models/audit-log.model.js
+++ b/models/audit-log.model.js
@@ -10,7 +10,8 @@ module.exports = function (mongoose) {
date: {
type: Types.Date,
default: Date.now(),
- required: true
+ required: true,
+ expires: Config.auditLogTTL
},
method: {
type: Types.String,
|
Added expiration to auditLog.
|
JKHeadley_rest-hapi
|
train
|
1c87d0b582532f39612265784a4e0a781519b42e
|
diff --git a/lib/paper_house/library_task.rb b/lib/paper_house/library_task.rb
index <HASH>..<HASH> 100644
--- a/lib/paper_house/library_task.rb
+++ b/lib/paper_house/library_task.rb
@@ -24,7 +24,7 @@ module PaperHouse
# Name of library.
def library_name
- @library_name ||= @name
+ (@library_name ||= @name).to_s
end
# Name of library.
diff --git a/spec/paper_house/ruby_extension_task_spec.rb b/spec/paper_house/ruby_extension_task_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/paper_house/ruby_extension_task_spec.rb
+++ b/spec/paper_house/ruby_extension_task_spec.rb
@@ -3,100 +3,58 @@
require 'paper_house/ruby_extension_task'
describe Rake::Task do
- before { Rake::Task.clear }
+ context 'when RubyExtensionTask (name = :test) is defined' do
+ Given { Rake::Task.clear }
+ Given { PaperHouse::RubyExtensionTask.new :test }
- describe '.[]' do
- subject { Rake::Task[task] }
+ describe '.[]' do
+ context 'with :test' do
+ Given(:name) { :test }
- context 'with :test' do
- let(:task) { :test }
-
- context 'when RubyExtensionTask named :test is defined' do
- before { PaperHouse::RubyExtensionTask.new :test }
+ When(:task) { Rake::Task[name] }
+ Then { task.is_a? Rake::Task }
describe '#invoke' do
- it do
- expect do
- subject.invoke
- end.to raise_error('Cannot find sources (*.c).')
+ When(:result) { task.invoke }
+ Then do
+ result ==
+ Failure(RuntimeError, 'Cannot find sources (*.c).')
end
end
end
-
- context 'when RubyExtensionTask named :test is not defined' do
- it { expect { subject }.to raise_error }
- end
end
end
end
-describe PaperHouse::RubyExtensionTask do
- before { Rake::Task.clear }
-
- describe '.find_by_name' do
- subject { PaperHouse::RubyExtensionTask.find_by_name name }
-
- context 'with :test' do
- let(:name) { :test }
-
- context 'when RubyExtensionTask named :test is defined' do
- before { PaperHouse::RubyExtensionTask.new :test }
-
- it { expect(subject).to be_a PaperHouse::RubyExtensionTask }
- end
-
- context 'when RubyExtensionTask named :test is not defined' do
- it { expect(subject).to be_nil }
- end
- end
-
- context %(with 'test') do
- let(:name) { 'test' }
-
- context %(when RubyExtensionTask named 'test' is defined) do
- before { PaperHouse::RubyExtensionTask.new :test }
+describe PaperHouse::RubyExtensionTask, '.new' do
+ context 'with :test' do
+ When(:task) { PaperHouse::RubyExtensionTask.new(:test) }
+ Then { task.name == 'test' }
+ Then { task.library_name == 'test' }
+ Then { task.sources == '*.c' }
+ Then { task.target_directory == '.' }
+ Then { task.cc == 'gcc' }
+ Then { task.library_dependencies == ['ruby'] }
+ Then { task.cflags.empty? }
+ Then { task.includes.empty? }
+ Then { task.ldflags.empty? }
+ end
- it { expect(subject).to be_a PaperHouse::RubyExtensionTask }
+ context "with :test and a block setting :library_name = 'libtest'" do
+ When(:task) do
+ PaperHouse::RubyExtensionTask.new(:test) do |task|
+ task.library_name = 'libtest'
end
end
-
- context 'with :no_such_task' do
- let(:name) { :no_such_task }
-
- it { expect(subject).to be_nil }
- end
+ Then { task.library_name == 'libtest' }
end
- describe '.new' do
- context 'with :test' do
- subject { PaperHouse::RubyExtensionTask.new :test }
-
- its(:cc) { should eq 'gcc' }
- its(:cflags) { should be_empty }
- its(:includes) { should be_empty }
- its(:name) { should eq 'test' }
- its(:sources) { should eq '*.c' }
- its(:target_directory) { should eq '.' }
- end
-
- context 'with :test and block' do
- subject do
- PaperHouse::RubyExtensionTask.new(:test) do | task |
- task.library_name = library_name
- end
- end
-
- context %(with #library_name = 'new_name') do
- let(:library_name) { 'new_name' }
-
- its(:library_name) { should eq 'new_name' }
- end
-
- context 'with #library_name = :new_name' do
- let(:library_name) { :new_name }
-
- its(:library_name) { should eq :new_name }
+ context 'with :test and a block setting :library_name = :libtest' do
+ When(:task) do
+ PaperHouse::RubyExtensionTask.new(:test) do |task|
+ task.library_name = :libtest
end
end
+ Then { task.library_name == 'libtest' }
end
end
|
Refactor so that the output of RSpec reads fluently.
|
trema_paper-house
|
train
|
2a09b70ef47febfe6441e25500e42a2b6164414e
|
diff --git a/lib/punchblock/protocol/ozone/transfer.rb b/lib/punchblock/protocol/ozone/transfer.rb
index <HASH>..<HASH> 100644
--- a/lib/punchblock/protocol/ozone/transfer.rb
+++ b/lib/punchblock/protocol/ozone/transfer.rb
@@ -22,10 +22,7 @@ module Punchblock
def self.new(transfer_to = '', options = {})
super().tap do |new_node|
new_node.to = transfer_to
- new_node.from = options[:from]
- new_node.terminator = options[:terminator]
- new_node.timeout = options[:timeout]
- new_node.answer_on_media = options[:answer_on_media]
+ options.each_pair { |k,v| new_node.send :"#{k}=", v }
end
end
|
Cleaner transfer options in initializer. Fixes #<I>
|
adhearsion_punchblock
|
train
|
6abbf02de73c2f6616033c111ab81f8c8f16d1b2
|
diff --git a/mod/chat/report.php b/mod/chat/report.php
index <HASH>..<HASH> 100644
--- a/mod/chat/report.php
+++ b/mod/chat/report.php
@@ -38,8 +38,9 @@
}
$context = get_context_instance(CONTEXT_MODULE, $cm->id);
+ $PAGE->set_context($context);
+
require_login($course->id, false, $cm);
- require_capability('mod/chat:readlog', $context);
if (empty($chat->studentlogs) && !has_capability('mod/chat:readlog', $context)) {
notice(get_string('nopermissiontoseethechatlog', 'chat'));
@@ -273,5 +274,3 @@
/// Finish the page
echo $OUTPUT->footer();
-
-
|
"CHAT MDL-<I>, removed require_capability"
|
moodle_moodle
|
train
|
70ba1f81f055d17c378be2c9af3c15df3fea20ef
|
diff --git a/IPython/html/widgets/widget.py b/IPython/html/widgets/widget.py
index <HASH>..<HASH> 100644
--- a/IPython/html/widgets/widget.py
+++ b/IPython/html/widgets/widget.py
@@ -360,7 +360,7 @@ class Widget(LoggingConfigurable):
elif isinstance(x, string_types) and x.startswith('IPY_MODEL_') and x[10:] in Widget.widgets:
# we want to support having child widgets at any level in a hierarchy
# trusting that a widget UUID will not appear out in the wild
- return Widget.widgets[x]
+ return Widget.widgets[x[10:]]
else:
return x
|
Strip the IPY_MODEL_ prefix from widget IDs before referencing them.
|
jupyter-widgets_ipywidgets
|
train
|
70aab26e2d55797b6f1a31df37dafb114f3c0fed
|
diff --git a/contrib/ovirt/test_scenarios/bootstrap.py b/contrib/ovirt/test_scenarios/bootstrap.py
index <HASH>..<HASH> 100644
--- a/contrib/ovirt/test_scenarios/bootstrap.py
+++ b/contrib/ovirt/test_scenarios/bootstrap.py
@@ -27,8 +27,8 @@ from ovirtlago import testlib
# DC/Cluster
DC_NAME = 'test-dc'
-DC_VER_MAJ = '3'
-DC_VER_MIN = '5'
+DC_VER_MAJ = 3
+DC_VER_MIN = 6
CLUSTER_NAME = 'test-cluster'
CLUSTER_CPU_FAMILY = 'Intel Conroe Family'
@@ -69,8 +69,8 @@ def add_dc(api):
def add_cluster(api):
p = params.Cluster(
name=CLUSTER_NAME,
- cpu=params.CPU(
- id=CLUSTER_CPU_FAMILY,
+ cpu=params.Cpu(
+ type_=CLUSTER_CPU_FAMILY,
),
version=params.Version(
major=DC_VER_MAJ,
|
Adjusting the bootstrap for master
Using correct DC version
changing the cpu.id to cpu.type
<URL>
|
lago-project_lago
|
train
|
8713ae2827a3c24cb88e1718ac8c1ea19d228f75
|
diff --git a/fabfile.py b/fabfile.py
index <HASH>..<HASH> 100644
--- a/fabfile.py
+++ b/fabfile.py
@@ -848,14 +848,25 @@ def docker(subtask=False):
execute(run_script, docker_configuration['rootFolder'], parsed_commands, host=host_str)
+
+
@task
def run_script(rootFolder=False, commands=False):
if not rootFolder:
return;
-
- with cd(rootFolder), warn_only():
- for line in commands:
- run(line)
+ warnOnly = True
+ for line in commands:
+ with cd(rootFolder):
+ if line.lower() == 'fail_on_error(1)':
+ warnOnly = False
+ elif line.lower() == 'fail_on_error(0)':
+ warnOnly = True
+ else:
+ if warnOnly:
+ with warn_only():
+ run(line)
+ else:
+ run(line)
def get_backups_list():
|
Allow docker-scripts to fail instead of warn_only. use 'fail_on_error(1)' or 'fail_on_error(0)' as command
|
factorial-io_fabalicious
|
train
|
7f16f95e81fef2a95f8759f5a34b5dd92a425b30
|
diff --git a/triflow/plugins/displays.py b/triflow/plugins/displays.py
index <HASH>..<HASH> 100644
--- a/triflow/plugins/displays.py
+++ b/triflow/plugins/displays.py
@@ -28,12 +28,15 @@ class bokeh_fields_update():
dictionnary with vars as key and a dictionnary of keywords arguments passed to the figs plots
init_notebook: True, optional
if True, initialize the javascript component needed for bokeh.
+ stack: False, optional
+ if True, all the plots are displayed in the same figure. fig kwargs is directly passed to this fig.
""" # noqa
def __init__(self, simul, keys=None,
line_kwargs={},
fig_kwargs={},
- notebook=True):
+ notebook=True,
+ stack=False):
from bokeh.io import push_notebook, output_notebook
from bokeh.plotting import figure, show, ColumnDataSource
from bokeh.layouts import Column
@@ -57,18 +60,28 @@ class bokeh_fields_update():
key)
for (key, func)
in self._datafunc.items()})
- figs = {}
- for key, func in self._datafunc.items():
- figs[key] = figure(**fig_kwargs.get(key, {}), title=key)
- figs[key].line('x', key, source=self._datasource,
- **line_kwargs.get(key, {}))
-
- self._handler = show(Column(*[figs[key]
- for key
- in self._datafunc.keys()
- if key != 'x']),
- notebook_handle=True)
- self._keys = keys
+ self._keys = self._datafunc.keys()
+ self._keys.remove("x")
+
+ if stack:
+ fig = figure(**fig_kwargs)
+ for key in self._keys:
+ fig.line('x', key, source=self._datasource,
+ **line_kwargs.get(key, {}))
+ self._handler = show(fig, notebook_handle=True)
+ return
+ else:
+ figs = {}
+ for key in self._keys:
+ figs[key] = figure(**fig_kwargs.get(key, {}), title=key)
+ figs[key].line('x', key, source=self._datasource,
+ **line_kwargs.get(key, {}))
+
+ self._handler = show(Column(*[figs[key]
+ for key
+ in self._datafunc.keys()
+ if key != 'x']),
+ notebook_handle=True)
def __call__(self, t, fields):
for key, func in self._datafunc.items():
|
Update bokeh fields display, allow displaying post-processed data
|
celliern_triflow
|
train
|
c38e264cb8b92e7ed6bcf9f84224ca083e191a48
|
diff --git a/galpy/actionAngle_src/actionAngleIsochroneApprox.py b/galpy/actionAngle_src/actionAngleIsochroneApprox.py
index <HASH>..<HASH> 100644
--- a/galpy/actionAngle_src/actionAngleIsochroneApprox.py
+++ b/galpy/actionAngle_src/actionAngleIsochroneApprox.py
@@ -17,7 +17,7 @@ import warnings
import numpy as nu
import numpy.linalg as linalg
from scipy import optimize
-from galpy.potential import dvcircdR, vcirc
+from galpy.potential import dvcircdR, vcirc, _isNonAxi
from galpy.actionAngle_src.actionAngleIsochrone import actionAngleIsochrone
from galpy.actionAngle_src.actionAngle import actionAngle
from galpy.potential import IsochronePotential, MWPotential
@@ -127,8 +127,6 @@ class actionAngleIsochroneApprox(actionAngle):
3) numpy.ndarray: [N,M] phase-space values for N objects at M
times
b) Orbit instance or list thereof; can be integrated already
- nonaxi= set to True to also calculate Lz using the isochrone
- approximation for non-axisymmetric potentials
cumul= if True, return the cumulative average actions (to look
at convergence)
OUTPUT:
@@ -165,7 +163,7 @@ class actionAngleIsochroneApprox(actionAngle):
sumFunc= nu.sum
jr= sumFunc(jrI*danglerI,axis=1)/sumFunc(danglerI,axis=1)
jz= sumFunc(jzI*danglezI,axis=1)/sumFunc(danglezI,axis=1)
- if kwargs.get('nonaxi',False):
+ if _isNonAxi(self._pot):
lzI= nu.reshape(acfs[1],R.shape)[:,:-1]
anglephiI= nu.reshape(acfs[7],R.shape)
danglephiI= ((nu.roll(anglephiI,-1,axis=1)-anglephiI) % _TWOPI)[:,:-1]
@@ -191,8 +189,6 @@ class actionAngleIsochroneApprox(actionAngle):
3) numpy.ndarray: [N,M] phase-space values for N objects at M
times
b) Orbit instance or list thereof; can be integrated already
- nonaxi= set to True to also calculate Lz using the isochrone
- approximation for non-axisymmetric potentials
OUTPUT:
(jr,lz,jz,Omegar,Omegaphi,Omegaz)
HISTORY:
@@ -217,8 +213,6 @@ class actionAngleIsochroneApprox(actionAngle):
times
b) Orbit instance or list thereof; can be integrated already
maxn= (default: 3) Use a grid in vec(n) up to this n (zero-based)
- nonaxi= set to True to also calculate Lz using the isochrone
- approximation for non-axisymmetric potentials
ts= if set, the phase-space points correspond to these times (IF NOT SET, WE ASSUME THAT ts IS THAT THAT IS ASSOCIATED WITH THIS OBJECT)
_firstFlip= (False) if True and Orbits are given, the backward part of the orbit is integrated first and stored in the Orbit object
OUTPUT:
@@ -227,7 +221,7 @@ class actionAngleIsochroneApprox(actionAngle):
2013-09-10 - Written - Bovy (IAS)
"""
from galpy.orbit import Orbit
- if kwargs.get('nonaxi',False):
+ if _isNonAxi(self._pot):
raise NotImplementedError('angles for non-axisymmetric potentials not implemented yet') #once this is implemented, remove the pragma further down
_firstFlip= kwargs.get('_firstFlip',False)
#If the orbit was already integrated, set ts to the integration times
@@ -275,7 +269,7 @@ class actionAngleIsochroneApprox(actionAngle):
danglezI= ((nu.roll(anglezI,-1,axis=1)-anglezI) % _TWOPI)[:,:-1]
jr= nu.sum(jrI*danglerI,axis=1)/nu.sum(danglerI,axis=1)
jz= nu.sum(jzI*danglezI,axis=1)/nu.sum(danglezI,axis=1)
- if kwargs.get('nonaxi',False): #pragma: no cover
+ if _isNonAxi(self._pot): #pragma: no cover
lzI= nu.reshape(acfs[1],R.shape)[:,:-1]
anglephiI= nu.reshape(acfs[7],R.shape)
if nu.any((nu.fabs(nu.amax(anglephiI,axis=1)-_TWOPI) > _ANGLETOL)\
@@ -467,7 +461,7 @@ class actionAngleIsochroneApprox(actionAngle):
colorbar=True,
**kwargs)
else:
- if kwargs.get('nonaxi',False):
+ if _isNonAxi(self._pot):
raise NotImplementedError('angles for non-axisymmetric potentials not implemented yet')
if deperiod:
if 'ar' in type:
diff --git a/nose/test_actionAngle.py b/nose/test_actionAngle.py
index <HASH>..<HASH> 100644
--- a/nose/test_actionAngle.py
+++ b/nose/test_actionAngle.py
@@ -1514,7 +1514,7 @@ def test_actionAngleIsochroneApprox_bovy14():
times= numpy.linspace(0.,100.,51)
obs.integrate(times,lp,method='dopr54_c')
js= aAI(obs.R(times),obs.vR(times),obs.vT(times),obs.z(times),
- obs.vz(times),obs.phi(times),nonaxi=True) #nonaxi to test that part of the code
+ obs.vz(times),obs.phi(times))
maxdj= numpy.amax(numpy.fabs((js-numpy.tile(numpy.mean(js,axis=1),(len(times),1)).T)),axis=1)/numpy.mean(js,axis=1)
assert maxdj[0] < 3.*10.**-2., 'Jr conservation for the GD-1 like orbit of Bovy (2014) fails at %f%%' % (100.*maxdj[0])
assert maxdj[1] < 10.**-2., 'Lz conservation for the GD-1 like orbit of Bovy (2014) fails at %f%%' % (100.*maxdj[1])
|
rm nonaxi= keyword from aAIA and determine it directly from the potential
|
jobovy_galpy
|
train
|
28f41b4f4974b5994ea2cec64e0f706e024b9589
|
diff --git a/tests/test_train_dictionary.py b/tests/test_train_dictionary.py
index <HASH>..<HASH> 100644
--- a/tests/test_train_dictionary.py
+++ b/tests/test_train_dictionary.py
@@ -14,14 +14,21 @@ else:
def generate_samples():
+ inputs = [
+ b'foo',
+ b'bar',
+ b'abcdef',
+ b'sometext',
+ b'baz',
+ ]
+
samples = []
+
for i in range(128):
- samples.append(b'foo' * 64)
- samples.append(b'bar' * 64)
- samples.append(b'foobar' * 64)
- samples.append(b'baz' * 64)
- samples.append(b'foobaz' * 64)
- samples.append(b'bazfoo' * 64)
+ samples.append(inputs[i % 5])
+ samples.append(inputs[i % 5] * (i + 3))
+ samples.append(inputs[-(i % 5)] * (i + 2))
+
return samples
@@ -39,25 +46,14 @@ class TestTrainDictionary(unittest.TestCase):
zstd.train_dictionary(8192, [u'foo'])
def test_no_params(self):
- samples = []
- for i in range(128):
- samples.append(b'foobarbaz' * 16)
- samples.append(b'blehbleh' * 16)
- samples.append(b'randomtext' * 16)
-
- d = zstd.train_dictionary(8192, samples)
+ d = zstd.train_dictionary(8192, generate_samples())
self.assertIsInstance(d.dict_id(), int_type)
data = d.as_bytes()
- self.assertEqual(data[0:8], b'\x37\xa4\x30\xec\xe3\x9f\x99\x7a')
+ self.assertEqual(data[0:8], b'\x37\xa4\x30\xec\x44\x05\x69\x35')
def test_basic(self):
- samples = []
- for i in range(128):
- samples.append(b'foo' * 64)
- samples.append(b'foobar' * 64)
-
- d = zstd.train_dictionary(8192, samples, k=64, d=16)
+ d = zstd.train_dictionary(8192, generate_samples(), k=64, d=16)
self.assertIsInstance(d.dict_id(), int_type)
data = d.as_bytes()
@@ -67,21 +63,13 @@ class TestTrainDictionary(unittest.TestCase):
self.assertEqual(d.d, 16)
def test_set_dict_id(self):
- samples = []
- for i in range(128):
- samples.append(b'foo' * 64)
- samples.append(b'foobar' * 64)
-
- d = zstd.train_dictionary(8192, samples, k=64, d=16, dict_id=42)
+ d = zstd.train_dictionary(8192, generate_samples(), k=64, d=16,
+ dict_id=42)
self.assertEqual(d.dict_id(), 42)
def test_optimize(self):
- samples = []
- for i in range(128):
- samples.append(b'foo' * 64)
- samples.append(b'foobar' * 64)
-
- d = zstd.train_dictionary(8192, samples, threads=-1, steps=1, d=16)
+ d = zstd.train_dictionary(8192, generate_samples(), threads=-1, steps=1,
+ d=16)
- self.assertEqual(d.k, 50)
+ self.assertIn(d.k, (50, 2000))
self.assertEqual(d.d, 16)
|
tests: change samples used for dictionary generation
zstandard <I> doesn't like the old inputs. In preparation for
upgrading, change the samples used in testing.
|
indygreg_python-zstandard
|
train
|
2ccd124637ccc073bf175ca58cd9c6687e21ccd1
|
diff --git a/pysat/instruments/pysat_testing.py b/pysat/instruments/pysat_testing.py
index <HASH>..<HASH> 100644
--- a/pysat/instruments/pysat_testing.py
+++ b/pysat/instruments/pysat_testing.py
@@ -100,7 +100,7 @@ def load(fnames, tag=None, sat_id=None, sim_multi_file_right=False,
day = int(parts[2][0:2])
# Specify the date tag locally and determine the desired date range
- date_tag = '' if tag not in tags
+ date_tag = '' if tag not in tags else tag
date = pysat.datetime(yr, month, day)
if sim_multi_file_right:
@@ -177,7 +177,7 @@ def list_files(tag=None, sat_id=None, data_path=None, format_str=None):
"""Produce a fake list of files spanning a year"""
# Determine the appropriate date range for the fake files
- date_tag = '' if tag not in tags
+ date_tag = '' if tag not in tags else tag
start = test_dates[date_tag][sat_id] - pds.DateOffset(years=1)
stop = test_dates[date_tag][sat_id] + pds.DateOffset(days=364)
index = pds.date_range(start, stop)
|
Update pysat_testing.py
Fixed bug in incomplete if/else statement
|
rstoneback_pysat
|
train
|
8264517a9b7314747bfc0893b251e807b41288f5
|
diff --git a/app/helpers/effective_moneris_checkout_helper.rb b/app/helpers/effective_moneris_checkout_helper.rb
index <HASH>..<HASH> 100644
--- a/app/helpers/effective_moneris_checkout_helper.rb
+++ b/app/helpers/effective_moneris_checkout_helper.rb
@@ -1,4 +1,5 @@
module EffectiveMonerisCheckoutHelper
+ SCRUB = /[^\w\d#,\s]/
def moneris_checkout_preload_request(order)
# Make the Preload Request
@@ -19,8 +20,8 @@ module EffectiveMonerisCheckoutHelper
language: 'en',
contact_details: {
- first_name: order.billing_first_name,
- last_name: order.billing_last_name,
+ first_name: moneris_checkout_scrub(order.billing_first_name),
+ last_name: moneris_checkout_scrub(order.billing_last_name),
email: order.email,
}
}
@@ -28,9 +29,9 @@ module EffectiveMonerisCheckoutHelper
if (address = order.billing_address).present?
params.merge!(
billing_details: {
- address_1: address.address1,
- address_2: address.address2,
- city: address.city,
+ address_1: moneris_checkout_scrub(address.address1),
+ address_2: moneris_checkout_scrub(address.address2),
+ city: moneris_checkout_scrub(address.city),
province: address.state_code,
country: address.country_code,
postal_code: address.postal_code
@@ -41,8 +42,8 @@ module EffectiveMonerisCheckoutHelper
if (address = order.shipping_address).present?
params.merge!(
shipping_details: {
- address_1: address.address1,
- address_2: address.address2,
+ address_1: moneris_checkout_scrub(address.address1),
+ address_2: moneris_checkout_scrub(address.address2),
city: address.city,
province: address.state_code,
country: address.country_code,
@@ -62,4 +63,9 @@ module EffectiveMonerisCheckoutHelper
}
end
+ def moneris_checkout_scrub(value)
+ return value unless value.kind_of?(String)
+ value.gsub(SCRUB, '')
+ end
+
end
|
Scrub bad characters from moneris preload request
|
code-and-effect_effective_orders
|
train
|
cc9e256b3634bf44c80af8dcdca3c7c7efd2847d
|
diff --git a/test/utils/db-utils.js b/test/utils/db-utils.js
index <HASH>..<HASH> 100644
--- a/test/utils/db-utils.js
+++ b/test/utils/db-utils.js
@@ -77,6 +77,9 @@ module.exports.teardown = () => {
}
throw err;
+ })
+ .finally(() => {
+ debug('Database teardown end');
});
}
diff --git a/test/utils/index.js b/test/utils/index.js
index <HASH>..<HASH> 100644
--- a/test/utils/index.js
+++ b/test/utils/index.js
@@ -2,6 +2,8 @@ require('../../core/server/overrides');
// Utility Packages
const {sequence} = require('@tryghost/promise');
+const debug = require('@tryghost/debug')('test:utils');
+
const _ = require('lodash');
// Ghost Internals
@@ -47,8 +49,13 @@ const setup = function setup() {
const args = arguments;
return function innerSetup() {
+ debug('setup start');
models.init();
- return initFixtures.apply(self, args);
+ return initFixtures
+ .apply(self, args)
+ .finally(() => {
+ debug('setup end');
+ });
};
};
|
Added extra debug to test utilities
- Looking for places we can SAVE TIME running tests
|
TryGhost_Ghost
|
train
|
2e609c1778d81d7b579bbaa65416099d5bb1318b
|
diff --git a/database/migrations/2016_05_15_133347_create_rinvex_fort_users_table.php b/database/migrations/2016_05_15_133347_create_rinvex_fort_users_table.php
index <HASH>..<HASH> 100644
--- a/database/migrations/2016_05_15_133347_create_rinvex_fort_users_table.php
+++ b/database/migrations/2016_05_15_133347_create_rinvex_fort_users_table.php
@@ -42,7 +42,7 @@ class CreateRinvexFortUsersTable extends Migration
$table->string('first_name')->nullable();
$table->string('middle_name')->nullable();
$table->string('last_name')->nullable();
- $table->string('sufix')->nullable();
+ $table->string('suffix')->nullable();
$table->string('job_title')->nullable();
$table->string('country', 2)->nullable();
$table->text('two_factor')->nullable();
|
Typo in field sufix
In the database the field is/was defined as `sufix` but in the views it's defined as `suffix`.
|
rinvex_laravel-auth
|
train
|
79dbde0f7e1fd9748d03908ede2f035868beb09a
|
diff --git a/.gitignore b/.gitignore
index <HASH>..<HASH> 100644
--- a/.gitignore
+++ b/.gitignore
@@ -4,6 +4,3 @@
# This is a backup
*-backup
.first-commit-backup
-
-# These are not yet finished
-mrvolume.py
diff --git a/neuropythy/cortex.py b/neuropythy/cortex.py
index <HASH>..<HASH> 100644
--- a/neuropythy/cortex.py
+++ b/neuropythy/cortex.py
@@ -11,7 +11,7 @@ import itertools
import collections
from pysistence import make_dict
import pysistence
-import mrvolume
+#import mrvolume
class CorticalMesh:
'''CorticalMesh is a class that handles properties of the cortical surface mesh.
diff --git a/neuropythy/registration.py b/neuropythy/registration.py
index <HASH>..<HASH> 100644
--- a/neuropythy/registration.py
+++ b/neuropythy/registration.py
@@ -100,7 +100,7 @@ class HarmonicEdgePotential:
D0 = self.D0
# calculate the total potential
D = np.sqrt(np.sum((X0[:, E[0]] - X0[:, E[1]]) ** 2, 0))
- return np.sum(0.5 * self.coefficient * (D - D0) ** 2)
+ return 0.5 * self.coefficient * np.sum((D - D0) ** 2)
def grad(self, X):
E = self.mesh.edges
X0 = self.mesh.coordinates
@@ -133,12 +133,69 @@ class HarmonicAnglePotential:
F = mesh.faces
d = X0.shape[0]
n = X0.shape[1]
- m = F.shape[1] * 3
+ m0 = F.shape[1]
+ m = m0 * F.shape[0]
# some relevant values we want to keep track of...
self.mesh = mesh
self.coefficient = self.constant / m
self.X0 = X0
- self.T0 = 0 #here
+ self.T0 = CorticalMesh.calculate_face_angles(F, X0)
+ # we need a summation matrix...
+ self.sumMatrix = sp.sparse.dok_matrix((n, m), dtype=np.float32)
+ for i in range(m0):
+ for j in range(F.shape[0]):
+ self.sum_matrix[F[j,i], j*m0 + i]
+ # and a constant hessian matrix...
+ def __call__(self, X):
+ T = CorticalMesh.calculate_face_angles(self.mesh.faces, X)
+ return 0.5 * self.coefficient * np.sum((T - self.T0) ** 2)
+ def grad(self, X):
+ F = self.mesh.faces
+ X0 = self.mesh.coordinates
+ T0 = self.T0
+ T = CorticalMesh.calculate_face_angles(F, X)
+ sinT = np.sin(T)
+ cosT = np.cos(T)
+ Xf = np.array([X[:,F[0]], X[:,F[1]], X[:,F[2]]])
+ sides = [Xf[1] - Xf[0], Xf[2] - Xf[1], Xf[0] - Xf[2]]
+ side_norms = map(
+ lambda side: np.sqrt((side**2).sum(0)),
+ sides)
+ normed_sides = map(
+ lambda side, norms: side / np.repeat([norms], X.shape[0], 0),
+ sides,
+ side_norms)
+ dT = T - T0
+ # below, g<m>[<n>] is the gradient for the angle centered at m for the vertex n
+ g0 = 2.0 * self.coefficient * [
+ 0,
+ dT[0]/(side_norms[0] * sinT[0]) * (normed_sides[2] - normed_sides[0]*cosT[0]),
+ dT[0]/(side_norms[2] * sinT[0]) * (normed_sides[0] - normed_sides[2]*cosT[0])]
+ g0[0] = g0[1] + g0[2]
+ g0 = np.array(map(lambda el: el.flatten(), g0))
+
+ g1 = 2.0 * self.coefficient * [
+ dT[1]/(side_norms[0] * sinT[1]) * (normed_sides[1] - normed_sides[0]*cosT[1]),
+ 0,
+ dT[1]/(side_norms[1] * sinT[1]) * (normed_sides[0] - normed_sides[1]*cosT[1])]
+ g1[1] = g1[0] + g1[2]
+ g1 = np.array(map(lambda el: el.flatten(), g1))
+
+ g2 = 2.0 * self.coefficient * [
+ dT[2]/(side_norms[2] * sinT[2]) * (normed_sides[1] - normed_sides[2]*cosT[2]),
+ dT[2]/(side_norms[1] * sinT[2]) * (normed_sides[2] - normed_sides[1]*cosT[2]),
+ 0]
+ g2[2] = g2[0] + g2[1]
+ g2 = np.array(map(lambda el: el.flatten(), g2))
+
+ # multiply these by the sum_matrix
+ g0 = map(lambda x: np.dot(self.sum_matrix, x), g0)
+ g1 = map(lambda x: np.dot(self.sum_matrix, x), g1)
+ g2 = map(lambda x: np.dot(self.sum_matrix, x), g2)
+ return g0 + g1 + g2
+
+
+
|
Minor bug fixes and added beginnings of HarmonicAnglePotential class.
|
noahbenson_neuropythy
|
train
|
1260858e7f80db60288cf46164222165d21ca616
|
diff --git a/tests/cacheTest.js b/tests/cacheTest.js
index <HASH>..<HASH> 100644
--- a/tests/cacheTest.js
+++ b/tests/cacheTest.js
@@ -10,7 +10,7 @@ tape('test the cache api', function (t) {
t.test('should have the correct value in the cache ', function (st) {
var account1 = {
address: Buffer.from('cd2a3d9f938e13cd947ec05abc7fe734df8dd826', 'hex'),
- key: ethUtil.sha3('cow')
+ key: ethUtil.keccak256('cow')
}
/*
diff --git a/tests/util.js b/tests/util.js
index <HASH>..<HASH> 100644
--- a/tests/util.js
+++ b/tests/util.js
@@ -118,7 +118,7 @@ exports.verifyPostConditions = function (state, testData, t, cb) {
var keyMap = {}
for (var key in testData) {
- var hash = utils.sha3(Buffer.from(utils.stripHexPrefix(key), 'hex')).toString('hex')
+ var hash = utils.keccak256(Buffer.from(utils.stripHexPrefix(key), 'hex')).toString('hex')
hashedAccounts[hash] = testData[key]
keyMap[hash] = key
}
@@ -182,7 +182,7 @@ exports.verifyAccountPostConditions = function (state, address, account, acctDat
var hashedStorage = {}
for (var key in acctData.storage) {
- hashedStorage[utils.sha3(utils.setLength(Buffer.from(key.slice(2), 'hex'), 32)).toString('hex')] = acctData.storage[key]
+ hashedStorage[utils.keccak256(utils.setLength(Buffer.from(key.slice(2), 'hex'), 32)).toString('hex')] = acctData.storage[key]
}
if (storageKeys.length > 0) {
@@ -286,12 +286,12 @@ exports.fromAddress = function (hexString) {
}
/**
- * toCodeHash - applies sha3 to hexCode
+ * toCodeHash - applies keccak256 to hexCode
* @param {String} hexCode string from tests repo
* @returns {Buffer}
*/
exports.toCodeHash = function (hexCode) {
- return utils.sha3(Buffer.from(hexCode.slice(2), 'hex'))
+ return utils.keccak256(Buffer.from(hexCode.slice(2), 'hex'))
}
exports.makeBlockHeader = function (data) {
|
Replace usages of sha3 with keccak<I>
|
ethereumjs_ethereumjs-vm
|
train
|
ace251d27f7f8899927244de62f7bf5761c8247f
|
diff --git a/tools/licenses/licenses/README.md b/tools/licenses/licenses/README.md
index <HASH>..<HASH> 100644
--- a/tools/licenses/licenses/README.md
+++ b/tools/licenses/licenses/README.md
@@ -116,6 +116,8 @@ Options:
* License results are printed to `stdout` as newline-delimited JSON.
+<!-- </notes> -->
+
<!-- <examples> -->
diff --git a/tools/licenses/licenses/lib/licenses.js b/tools/licenses/licenses/lib/licenses.js
index <HASH>..<HASH> 100644
--- a/tools/licenses/licenses/lib/licenses.js
+++ b/tools/licenses/licenses/lib/licenses.js
@@ -84,7 +84,7 @@ function licenses() {
readInstalled( opts.dir, options, onRead );
/**
- * Callback invoked after reading installed modules.
+ * Callback invoked after reading installed packages.
*
* @private
* @param {(Error|null)} error - error object
diff --git a/tools/licenses/licenses/lib/recurse.js b/tools/licenses/licenses/lib/recurse.js
index <HASH>..<HASH> 100644
--- a/tools/licenses/licenses/lib/recurse.js
+++ b/tools/licenses/licenses/lib/recurse.js
@@ -3,12 +3,12 @@
// MODULES //
var debug = require( 'debug' )( 'licenses:recurse' );
+var prefix = require( './stdlib.js' );
var join = require( 'path' ).join;
var getKeys = require( 'object-keys' ).shim();
-var prefix = require( './stdlib.js' );
+var indexOf = require( prefix+'@stdlib/utils/index-of' );
var getRepo = require( './pkg_repo.js' );
var getLicense = require( './pkg_license.js' );
-var indexOf = require( prefix+'@stdlib/utils/index-of' );
// RECURSE //
|
Fix missing closing comment, update fcn desc, and reorder require statements
|
stdlib-js_stdlib
|
train
|
246851db1a95e44f16736b130ee04c2b47715895
|
diff --git a/modules/uadetector-core/src/main/java/net/sf/uadetector/datastore/CachingXmlDataStore.java b/modules/uadetector-core/src/main/java/net/sf/uadetector/datastore/CachingXmlDataStore.java
index <HASH>..<HASH> 100644
--- a/modules/uadetector-core/src/main/java/net/sf/uadetector/datastore/CachingXmlDataStore.java
+++ b/modules/uadetector-core/src/main/java/net/sf/uadetector/datastore/CachingXmlDataStore.java
@@ -80,7 +80,7 @@ public final class CachingXmlDataStore extends AbstractDataStore implements Refr
* The suffix string to be used in generating the cache file's name; may be {@code null}, in which case the suffix "
* {@code .tmp}" will be used
*/
- private static final String SUFFIX = "";
+ private static final String SUFFIX = ".xml";
/**
* Constructs a new instance of {@code CachingXmlDataStore} with the given arguments. The given {@code cacheFile}
|
Added file extension ".xml" to default cache file (belongs to issue #<I>)
|
before_uadetector
|
train
|
6a44ce5c599c2762d3fcfb66d4b53b396df85f8f
|
diff --git a/pdef/src/main/java/io/pdef/json/JsonObjectFormat.java b/pdef/src/main/java/io/pdef/json/JsonObjectFormat.java
index <HASH>..<HASH> 100644
--- a/pdef/src/main/java/io/pdef/json/JsonObjectFormat.java
+++ b/pdef/src/main/java/io/pdef/json/JsonObjectFormat.java
@@ -225,6 +225,8 @@ class JsonObjectFormat {
private Boolean readBoolean(final Object input) {
if (input instanceof Boolean) {
return (Boolean) input;
+ } else if (input instanceof Number) {
+ return ((Number) input).intValue() == 1;
}
return Boolean.parseBoolean((String) input);
}
diff --git a/pdef/src/test/java/io/pdef/json/JsonObjectFormatTest.java b/pdef/src/test/java/io/pdef/json/JsonObjectFormatTest.java
index <HASH>..<HASH> 100644
--- a/pdef/src/test/java/io/pdef/json/JsonObjectFormatTest.java
+++ b/pdef/src/test/java/io/pdef/json/JsonObjectFormatTest.java
@@ -25,8 +25,7 @@ import io.pdef.test.inheritance.PdefBase;
import io.pdef.test.inheritance.PdefMultiLevelSubtype;
import io.pdef.test.messages.PdefTestEnum;
import io.pdef.test.messages.PdefTestMessage;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNull;
+import static org.junit.Assert.*;
import org.junit.Test;
import java.util.Date;
@@ -51,6 +50,8 @@ public class JsonObjectFormatTest {
public void testBool() throws Exception {
testPrimitive(Descriptors.bool, true, "TRUE");
testPrimitive(Descriptors.bool, false, "False");
+ assertTrue(format.read(1, Descriptors.bool));
+ assertFalse(format.read(0, Descriptors.bool));
}
@Test
|
Fixed parsing booleans from 0/1, fixed #<I>.
|
pdef_pdef-java
|
train
|
5c816089ee5f058cb6a93d2940026f761d60f238
|
diff --git a/content/template/bookingTemplate/single-person-booking.php b/content/template/bookingTemplate/single-person-booking.php
index <HASH>..<HASH> 100644
--- a/content/template/bookingTemplate/single-person-booking.php
+++ b/content/template/bookingTemplate/single-person-booking.php
@@ -134,7 +134,7 @@ if ( ! $no_invoice_free_events || ( $no_invoice_free_events && $first_price['Pri
<input type="text" name="invoiceReference" placeholder="<?php esc_attr_e( 'Invoice reference', 'eduadmin-booking' ); ?>" value="<?php echo ! empty( $billing_customer->SellerReference ) ? esc_attr( $billing_customer->SellerReference ) : ''; ?>" />
</div>
</label>
- <label style="<?php echo $force_show_invoice_information ? 'display: none;' : '' ?>" class="edu-book-singleParticipant-customerInvoiceOtherInfo>
+ <label style="<?php echo $force_show_invoice_information ? 'display: none;' : '' ?>" class="edu-book-singleParticipant-customerInvoiceOtherInfo">
<div class="inputHolder alsoInvoiceCustomer">
<input type="checkbox" id="alsoInvoiceCustomer" name="alsoInvoiceCustomer" value="true" onchange="eduBookingView.UpdateInvoiceCustomer(this);"
<?php echo $force_show_invoice_information ? 'checked' : '' ?>/>
@@ -196,14 +196,14 @@ if ( ! $no_invoice_free_events || ( $no_invoice_free_events && $first_price['Pri
</div>
</div>
<?php if ( get_option( 'eduadmin-useLogin', false ) && get_option( 'eduadmin-allowCustomerUpdate', false ) && isset( $customer->CustomerId ) && 0 !== $customer->CustomerId ) { ?>
- <label class="edu-book-singleParticipant-customerOverwriteData">
+ <div class="edu-book-singleParticipant-customerOverwriteData">
<div class="inputHolder">
<label class="inline-checkbox" for="overwriteCustomerData">
<input type="checkbox" id="overwriteCustomerData" name="overwriteCustomerData" value="true" />
<?php esc_html_e( 'Also update my customer information for future use', 'eduadmin-booking' ); ?>
</label>
</div>
- </label>
+ </div>
<?php } ?>
<?php } ?>
<div class="attributeView">
diff --git a/eduadmin.php b/eduadmin.php
index <HASH>..<HASH> 100644
--- a/eduadmin.php
+++ b/eduadmin.php
@@ -9,7 +9,7 @@ defined( 'WP_SESSION_COOKIE' ) || define( 'WP_SESSION_COOKIE', 'eduadmin-cookie'
* Plugin URI: https://www.eduadmin.se
* Description: EduAdmin plugin to allow visitors to book courses at your website
* Tags: booking, participants, courses, events, eduadmin, lega online
- * Version: 2.0.46
+ * Version: 2.0.47
* GitHub Plugin URI: multinetinteractive/eduadmin-wordpress
* GitHub Plugin URI: https://github.com/multinetinteractive/eduadmin-wordpress
* Requires at least: 4.7
diff --git a/readme.md b/readme.md
index <HASH>..<HASH> 100644
--- a/readme.md
+++ b/readme.md
@@ -43,6 +43,9 @@ If you notice that your API key doesn't work any more, you have to contact us.
== Changelog ==
+### 2.0.47
+- fix: Missing `"` on one class-attribute
+
### 2.0.46
- add: Added invoice organisation number to invoice-section
|
fix: Missing `"` in a class attribute.
chg: Switching to `div` from `label`
|
MultinetInteractive_EduAdmin-WordPress
|
train
|
436c12aaaadf641d9770632f6d1b651f888d9809
|
diff --git a/requestor/core/requestor-api/src/main/java/io/reinert/requestor/core/uri/UriCodec.java b/requestor/core/requestor-api/src/main/java/io/reinert/requestor/core/uri/UriCodec.java
index <HASH>..<HASH> 100644
--- a/requestor/core/requestor-api/src/main/java/io/reinert/requestor/core/uri/UriCodec.java
+++ b/requestor/core/requestor-api/src/main/java/io/reinert/requestor/core/uri/UriCodec.java
@@ -22,7 +22,7 @@ package io.reinert.requestor.core.uri;
*/
public abstract class UriCodec {
- public static UriCodec INSTANCE = null;
+ private static UriCodec INSTANCE = null;
public static UriCodec getInstance() {
if (INSTANCE == null) {
@@ -31,6 +31,10 @@ public abstract class UriCodec {
return INSTANCE;
}
+ public static synchronized void setInstance(UriCodec uriCodec) {
+ INSTANCE = uriCodec;
+ }
+
/**
* Returns a string where all URL escape sequences have been converted back to
* their original character representations.
|
#<I> [api] Add a static method to set UriCodec singleton
|
reinert_requestor
|
train
|
cd7aef2139e715c7a0a91983fc9203fc9471957a
|
diff --git a/docs/dgeni-package/services/tsParser/createCompilerHost.spec.js b/docs/dgeni-package/services/tsParser/createCompilerHost.spec.js
index <HASH>..<HASH> 100644
--- a/docs/dgeni-package/services/tsParser/createCompilerHost.spec.js
+++ b/docs/dgeni-package/services/tsParser/createCompilerHost.spec.js
@@ -1,6 +1,7 @@
var mockPackage = require('../../mocks/mockPackage');
var Dgeni = require('dgeni');
var path = require('canonical-path');
+var ts = require('typescript');
describe('createCompilerHost', function() {
var dgeni, injector, options, host, baseDir, extensions;
@@ -57,15 +58,16 @@ describe('createCompilerHost', function() {
describe('useCaseSensitiveFileNames', function() {
- it('should return false', function() {
- expect(host.useCaseSensitiveFileNames()).toBe(false);
+ it('should return true if the OS is case sensitive', function() {
+ expect(host.useCaseSensitiveFileNames()).toBe(ts.sys.useCaseSensitiveFileNames);
});
});
describe('getCanonicalFileName', function() {
it('should lower case the filename', function() {
- expect(host.getCanonicalFileName('SomeFile.ts')).toEqual('somefile.ts');
+ var expectedFilePath = host.useCaseSensitiveFileNames() ? 'SomeFile.ts' : 'somefile.ts';
+ expect(host.getCanonicalFileName('SomeFile.ts')).toEqual(expectedFilePath);
});
});
|
chore(doc-gen): fix up tests to work on linux
|
angular_angular
|
train
|
ccc6bc5ad1cd3f9e2462af2b1a9b03d376ffd43c
|
diff --git a/src/Commands/MakeRepositoryCommand.php b/src/Commands/MakeRepositoryCommand.php
index <HASH>..<HASH> 100644
--- a/src/Commands/MakeRepositoryCommand.php
+++ b/src/Commands/MakeRepositoryCommand.php
@@ -61,7 +61,9 @@ class MakeRepositoryCommand extends RepoistCommand
*/
public function handle()
{
- $this->checkModel();
+ if (!$this->isLumen()) {
+ $this->checkModel();
+ }
list($contract, $contractName) = $this->createContract();
@@ -177,4 +179,9 @@ class MakeRepositoryCommand extends RepoistCommand
$this->modelName = array_pop($modelParts);
}
+
+ protected function isLumen()
+ {
+ return str_contains($this->app->version(), 'Lumen');
+ }
}
|
Cant create models with the normal command in Lumen, disabled the check.
|
OzanKurt_Repoist
|
train
|
cec56eb09025a6f35f85d0578ec6a1db993f820a
|
diff --git a/bin/test-publisher.php b/bin/test-publisher.php
index <HASH>..<HASH> 100644
--- a/bin/test-publisher.php
+++ b/bin/test-publisher.php
@@ -6,4 +6,9 @@ require_once __DIR__ . '/../vendor/autoload.php';
use Hodor\JobQueueFacade as Q;
Q::setConfigFile(__DIR__ . '/../config/config.php');
-Q::push('default', 'some_job_name', ['some', 'cool', 'values', date('Y-m-d h:i:s')]);
+Q::push(
+ 'default',
+ 'some_job_name',
+ ['some', 'cool', 'values', date('Y-m-d h:i:s')],
+ ['queue_name' => 'default']
+);
|
chore(dev): add queue_name job option to test-publisher
|
lightster_hodor
|
train
|
38861ab8293259a3eb080151446caba93e8945a6
|
diff --git a/prow/tide/tide.go b/prow/tide/tide.go
index <HASH>..<HASH> 100644
--- a/prow/tide/tide.go
+++ b/prow/tide/tide.go
@@ -365,23 +365,40 @@ func (c *Controller) Sync() error {
c.config().BranchProtectionWarnings(c.logger, c.config().PresubmitsStatic)
c.logger.Debug("Building tide pool.")
+ lock := sync.Mutex{}
+ wg := sync.WaitGroup{}
prs := make(map[string]PullRequest)
+ var errs []error
for _, query := range c.config().Tide.Queries {
q := query.Query()
- results, err := search(c.ghc.Query, c.logger, q, time.Time{}, time.Now())
- if err != nil && len(results) == 0 {
- return fmt.Errorf("query %q, err: %v", q, err)
- }
- if err != nil {
- c.logger.WithError(err).WithField("query", q).Warning("found partial results")
- }
- for _, pr := range results {
- prs[prKey(&pr)] = pr
- }
+ wg.Add(1)
+ go func() {
+ defer wg.Done()
+ results, err := search(c.ghc.Query, c.logger, q, time.Time{}, time.Now())
+ lock.Lock()
+ defer lock.Unlock()
+
+ if err != nil && len(results) == 0 {
+ errs = append(errs, fmt.Errorf("query %q, err: %v", q, err))
+ return
+ }
+ if err != nil {
+ c.logger.WithError(err).WithField("query", q).Warning("found partial results")
+ }
+
+ for _, pr := range results {
+ prs[prKey(&pr)] = pr
+ }
+ }()
+ }
+ wg.Wait()
+ if err := utilerrors.NewAggregate(errs); err != nil {
+ return err
}
- c.logger.WithField(
- "duration", time.Since(start).String(),
- ).Debugf("Found %d (unfiltered) pool PRs.", len(prs))
+ c.logger.WithFields(logrus.Fields{
+ "duration": time.Since(start).String(),
+ "found_pr_count": len(prs),
+ }).Debug("Found (unfiltered) pool PRs.")
var blocks blockers.Blockers
var err error
|
Tide: Parallelize querying to reduce sync duration
We are seeing a very low Tide performance (between 5 and 8 minutes for
syncing) and that most of the time is spent querying GitHub. This
change is an attempt to improve that by parallelizing the querying.
|
kubernetes_test-infra
|
train
|
8c5887d05d38bdc40d1af8f3c8a76abee1d2faa9
|
diff --git a/lib/Doctrine/ORM/Mapping/Driver/AnnotationDriver.php b/lib/Doctrine/ORM/Mapping/Driver/AnnotationDriver.php
index <HASH>..<HASH> 100644
--- a/lib/Doctrine/ORM/Mapping/Driver/AnnotationDriver.php
+++ b/lib/Doctrine/ORM/Mapping/Driver/AnnotationDriver.php
@@ -169,10 +169,8 @@ class AnnotationDriver implements Driver
$mapping['type'] = $columnAnnot->type;
$mapping['length'] = $columnAnnot->length;
- $mapping['fixed'] = $columnAnnot->fixed;
$mapping['precision'] = $columnAnnot->precision;
$mapping['scale'] = $columnAnnot->scale;
- $mapping['unsigned'] = $columnAnnot->unsigned;
$mapping['nullable'] = $columnAnnot->nullable;
$mapping['options'] = $columnAnnot->options;
$mapping['unique'] = $columnAnnot->unique;
diff --git a/lib/Doctrine/ORM/Mapping/Driver/DoctrineAnnotations.php b/lib/Doctrine/ORM/Mapping/Driver/DoctrineAnnotations.php
index <HASH>..<HASH> 100644
--- a/lib/Doctrine/ORM/Mapping/Driver/DoctrineAnnotations.php
+++ b/lib/Doctrine/ORM/Mapping/Driver/DoctrineAnnotations.php
@@ -56,13 +56,11 @@ final class JoinColumns extends Annotation {}
final class Column extends Annotation {
public $type;
public $length;
- public $fixed = false;
public $precision = 0; // The precision for a decimal (exact numeric) column (Applies only for decimal column)
public $scale = 0; // The scale for a decimal (exact numeric) column (Applies only for decimal column)
- public $unsigned = false;
public $unique = false;
public $nullable = false;
- public $default;
+ public $default; //TODO: remove?
public $name;
public $options = array();
}
diff --git a/lib/Doctrine/ORM/Mapping/Driver/XmlDriver.php b/lib/Doctrine/ORM/Mapping/Driver/XmlDriver.php
index <HASH>..<HASH> 100644
--- a/lib/Doctrine/ORM/Mapping/Driver/XmlDriver.php
+++ b/lib/Doctrine/ORM/Mapping/Driver/XmlDriver.php
@@ -125,10 +125,6 @@ class XmlDriver extends AbstractFileDriver
$mapping['length'] = (int)$fieldMapping['length'];
}
- if (isset($fieldMapping['fixed'])) {
- $mapping['fixed'] = (bool)$fieldMapping['fixed'];
- }
-
if (isset($fieldMapping['precision'])) {
$mapping['precision'] = (int)$fieldMapping['precision'];
}
@@ -137,10 +133,6 @@ class XmlDriver extends AbstractFileDriver
$mapping['scale'] = (int)$fieldMapping['scale'];
}
- if (isset($fieldMapping['unsigned'])) {
- $mapping['unsigned'] = (bool)$fieldMapping['unsigned'];
- }
-
if (isset($fieldMapping['unique'])) {
$mapping['unique'] = (bool)$fieldMapping['unique'];
}
diff --git a/lib/Doctrine/ORM/Mapping/Driver/YamlDriver.php b/lib/Doctrine/ORM/Mapping/Driver/YamlDriver.php
index <HASH>..<HASH> 100644
--- a/lib/Doctrine/ORM/Mapping/Driver/YamlDriver.php
+++ b/lib/Doctrine/ORM/Mapping/Driver/YamlDriver.php
@@ -128,10 +128,6 @@ class YamlDriver extends AbstractFileDriver
$mapping['length'] = $fieldMapping['length'];
}
- if (isset($fieldMapping['fixed'])) {
- $mapping['fixed'] = (bool)$fieldMapping['fixed'];
- }
-
if (isset($fieldMapping['precision'])) {
$mapping['precision'] = $fieldMapping['precision'];
}
@@ -140,10 +136,6 @@ class YamlDriver extends AbstractFileDriver
$mapping['scale'] = $fieldMapping['scale'];
}
- if (isset($fieldMapping['unsigned'])) {
- $mapping['unsigned'] = (bool)$fieldMapping['unsigned'];
- }
-
if (isset($fieldMapping['unique'])) {
$mapping['unique'] = (bool)$fieldMapping['unique'];
}
diff --git a/lib/Doctrine/ORM/Tools/SchemaTool.php b/lib/Doctrine/ORM/Tools/SchemaTool.php
index <HASH>..<HASH> 100644
--- a/lib/Doctrine/ORM/Tools/SchemaTool.php
+++ b/lib/Doctrine/ORM/Tools/SchemaTool.php
@@ -569,24 +569,12 @@ class SchemaTool
$columnInfo['fixed'] = $fieldMapping['fixed'];
$columnChanged = true;
}
-
- // 7. check for unsigned change
- $fieldMapping['unsigned'] = ( ! isset($fieldMapping['unsigned']))
- ? false : $fieldMapping['unsigned'];
-
- if ($columnInfo['unsigned'] != $fieldMapping['unsigned']) {
- $columnInfo['unsigned'] = $fieldMapping['unsigned'];
- $columnChanged = true;
- }
// Only add to column changed list if it was actually changed
if ($columnChanged) {
$updateFields[] = $columnInfo;
}
- //var_dump($columnInfo);
- echo PHP_EOL . PHP_EOL;
-
unset($currentColumns[$index]);
$exists = true;
break;
|
[<I>][DDC-5] Fixed.
|
doctrine_orm
|
train
|
8f87dd5b29831c7abf9c11acc7f2f13403f7c8d2
|
diff --git a/src/Sylius/Bundle/AddressingBundle/Form/Type/CountryType.php b/src/Sylius/Bundle/AddressingBundle/Form/Type/CountryType.php
index <HASH>..<HASH> 100644
--- a/src/Sylius/Bundle/AddressingBundle/Form/Type/CountryType.php
+++ b/src/Sylius/Bundle/AddressingBundle/Form/Type/CountryType.php
@@ -34,7 +34,7 @@ class CountryType extends AbstractResourceType
'allow_add' => true,
'allow_delete' => true,
'by_reference' => false,
- 'button_add_label' => 'sylius.country.add_province',
+ 'button_add_label' => 'sylius.form.country.add_province',
))
;
}
diff --git a/src/Sylius/Bundle/AddressingBundle/Form/Type/ZoneType.php b/src/Sylius/Bundle/AddressingBundle/Form/Type/ZoneType.php
index <HASH>..<HASH> 100644
--- a/src/Sylius/Bundle/AddressingBundle/Form/Type/ZoneType.php
+++ b/src/Sylius/Bundle/AddressingBundle/Form/Type/ZoneType.php
@@ -58,7 +58,7 @@ class ZoneType extends AbstractResourceType
))
->add('members', 'collection', array(
'type' => 'sylius_zone_member',
- 'button_add_label' => 'sylius.zone.add_member',
+ 'button_add_label' => 'sylius.form.zone.add_member',
'allow_add' => true,
'allow_delete' => true,
'by_reference' => false,
diff --git a/src/Sylius/Bundle/AddressingBundle/Resources/translations/messages.en.yml b/src/Sylius/Bundle/AddressingBundle/Resources/translations/messages.en.yml
index <HASH>..<HASH> 100644
--- a/src/Sylius/Bundle/AddressingBundle/Resources/translations/messages.en.yml
+++ b/src/Sylius/Bundle/AddressingBundle/Resources/translations/messages.en.yml
@@ -11,6 +11,7 @@ sylius:
street: Street
province: Province
country:
+ add_province: Add province
name: Name
provinces: Provinces
select: Select
@@ -18,6 +19,7 @@ sylius:
name: Name
select: Select
zone:
+ add_member: Add member
members: Members
name: Name
type: Type
diff --git a/src/Sylius/Bundle/CoreBundle/Form/Type/CountryType.php b/src/Sylius/Bundle/CoreBundle/Form/Type/CountryType.php
index <HASH>..<HASH> 100644
--- a/src/Sylius/Bundle/CoreBundle/Form/Type/CountryType.php
+++ b/src/Sylius/Bundle/CoreBundle/Form/Type/CountryType.php
@@ -74,7 +74,7 @@ class CountryType extends AbstractResourceType
'allow_add' => true,
'allow_delete' => true,
'by_reference' => false,
- 'button_add_label' => 'sylius.country.add_province',
+ 'button_add_label' => 'sylius.form.country.add_province',
))
;
}
diff --git a/src/Sylius/Bundle/PromotionBundle/Form/Type/PromotionType.php b/src/Sylius/Bundle/PromotionBundle/Form/Type/PromotionType.php
index <HASH>..<HASH> 100644
--- a/src/Sylius/Bundle/PromotionBundle/Form/Type/PromotionType.php
+++ b/src/Sylius/Bundle/PromotionBundle/Form/Type/PromotionType.php
@@ -54,11 +54,11 @@ class PromotionType extends AbstractResourceType
))
->add('rules', 'sylius_promotion_rule_collection', array(
'label' => 'sylius.form.promotion.rules',
- 'button_add_label' => 'sylius.promotion.add_rule',
+ 'button_add_label' => 'sylius.form.promotion.add_rule',
))
->add('actions', 'sylius_promotion_action_collection', array(
'label' => 'sylius.form.promotion.actions',
- 'button_add_label' => 'sylius.promotion.add_action',
+ 'button_add_label' => 'sylius.form.promotion.add_action',
))
->addEventSubscriber(new AddCodeFormSubscriber())
;
diff --git a/src/Sylius/Bundle/PromotionBundle/Resources/translations/messages.en.yml b/src/Sylius/Bundle/PromotionBundle/Resources/translations/messages.en.yml
index <HASH>..<HASH> 100644
--- a/src/Sylius/Bundle/PromotionBundle/Resources/translations/messages.en.yml
+++ b/src/Sylius/Bundle/PromotionBundle/Resources/translations/messages.en.yml
@@ -46,6 +46,8 @@ sylius:
expires_at: Expires at
promotion:
actions: Actions
+ add_action: Add action
+ add_rule: Add rule
coupon_based: Coupon based
exclusive: Exclusive
description: Description
|
[Translations] Fixed missing / wrong form translations
|
Sylius_Sylius
|
train
|
114b1e465d7d41b391dde0954e780e7521e13f18
|
diff --git a/mode/turtle/turtle.js b/mode/turtle/turtle.js
index <HASH>..<HASH> 100644
--- a/mode/turtle/turtle.js
+++ b/mode/turtle/turtle.js
@@ -151,7 +151,9 @@ CodeMirror.defineMode("turtle", function(config) {
return context.col + (closing ? 0 : 1);
else
return context.indent + (closing ? 0 : indentUnit);
- }
+ },
+
+ lineComment: "#"
};
});
|
[turtle mode] Add comment syntax
|
codemirror_CodeMirror
|
train
|
d8666918354b67bcfb717b1618c1ba5e7151cc32
|
diff --git a/hvac/v1/__init__.py b/hvac/v1/__init__.py
index <HASH>..<HASH> 100644
--- a/hvac/v1/__init__.py
+++ b/hvac/v1/__init__.py
@@ -1,11 +1,15 @@
from __future__ import unicode_literals
import json
-import urlparse
import requests
from hvac import exceptions
+try:
+ from urlparse import urljoin
+except ImportError:
+ from urllib.parse import urljoin
+
class Client(object):
def __init__(self, url='http://localhost:8200', token=None,
cert=None, verify=True, timeout=30, proxies=None,
@@ -597,7 +601,7 @@ class Client(object):
return self.__request('delete', url, **kwargs)
def __request(self, method, url, headers=None, **kwargs):
- url = urlparse.urljoin(self._url, url)
+ url = urljoin(self._url, url)
if not headers:
headers = {}
@@ -613,7 +617,7 @@ class Client(object):
# NOTE(ianunruh): workaround for https://github.com/ianunruh/hvac/issues/51
while response.is_redirect and self.allow_redirects:
- url = urlparse.urljoin(self._url, response.headers['Location'])
+ url = urljoin(self._url, response.headers['Location'])
response = self.session.request(method, url, headers=headers,
allow_redirects=False, **_kwargs)
|
Fix urljoin usage in Python 3
|
hvac_hvac
|
train
|
930b261e3ca7c427def162b5c5f8f91c63aa4116
|
diff --git a/src/main/java/com/socrata/ssync/PatchBuilder.java b/src/main/java/com/socrata/ssync/PatchBuilder.java
index <HASH>..<HASH> 100644
--- a/src/main/java/com/socrata/ssync/PatchBuilder.java
+++ b/src/main/java/com/socrata/ssync/PatchBuilder.java
@@ -6,7 +6,7 @@ import java.io.*;
public class PatchBuilder {
private final OutputStreamWriteHelper out;
- private final int maxDataBlockSize;
+ private final int blockSize;
// Does NOT take ownership of the outputstream!
public PatchBuilder(OutputStream outStream, String checksumAlgorithm, int blockSize) throws IOException, NoSuchAlgorithmException {
@@ -14,7 +14,7 @@ public class PatchBuilder {
if(blockSize <= 0 || blockSize >= Patch.MaxBlockSize)
throw new IllegalArgumentException("blockSize");
- this.maxDataBlockSize = blockSize * 2;
+ this.blockSize = blockSize;
out.writeCheckumNameWithoutUpdatingChecksum();
out.writeInt(blockSize);
@@ -37,7 +37,7 @@ public class PatchBuilder {
public void writeData(byte[] data, int offset, int length) throws IOException {
while(length != 0) {
writeOp(Patch.Data);
- int toWrite = Math.min(length, maxDataBlockSize);
+ int toWrite = Math.min(length, blockSize);
out.writeInt(toWrite);
out.writeBytes(data, offset, toWrite);
length -= toWrite;
|
Remove one last vestage of compressed data chunks
We used to allow data chunks to be up to twice the size of the block
size to allow for incompressible chunks. Since compression is gone,
so can that be.
|
socrata-platform_ssync
|
train
|
d94eedede67dd3a9aed37b6d3d6c559d5efcbc28
|
diff --git a/lib/xbee-api.js b/lib/xbee-api.js
index <HASH>..<HASH> 100644
--- a/lib/xbee-api.js
+++ b/lib/xbee-api.js
@@ -71,6 +71,9 @@ XBeeAPI.prototype.buildFrame = function(frame) {
var payload = packet.slice(3); // Reference the buffer past the header
var builder = new BufferBuilder(payload);
+ if(!frame_builder[frame.type])
+ throw new Error('This library does not implement building the %d frame type.', frame.type);
+
// Let the builder fill the payload
frame_builder[frame.type](frame, builder);
|
Check if we can build the requested frame type
|
jankolkmeier_xbee-api
|
train
|
b02f26ea3ae380c29d51b2d33d95c66f59a96f58
|
diff --git a/lib/webkit_remote/process.rb b/lib/webkit_remote/process.rb
index <HASH>..<HASH> 100644
--- a/lib/webkit_remote/process.rb
+++ b/lib/webkit_remote/process.rb
@@ -8,10 +8,14 @@ module WebkitRemote
class Process
# Tracker for a yet-unlaunched process.
#
- # @param [Hash] opts
- # @option opts [Integer] port the port used by the remote debugging server
+ # @param [Hash] opts tweak the options below
+ # @option opts [Integer] port the port used by the remote debugging server;
+ # the default port is 9292
+ # @option opts [Number] timeout number of seconds to wait for the browser
+ # to start; the default timeout is 10 seconds
def initialize(opts = {})
@port = opts[:port] || 9292
+ @timeout = opts[:timeout] || 10
@running = false
@data_dir = Dir.mktmpdir 'webkit-remote'
@pid = nil
@@ -23,13 +27,27 @@ class Process
# @return [WebkitRemote::Process] self
def start
return self if running?
- @pid = POSIX::Spawn.spawn(*@cli)
- 100.times do
+ unless @pid = POSIX::Spawn.spawn(*@cli)
+ # The launch failed
+ return self
+ end
+
+ puts @cli.join(' ')
+
+ (@timeout * 20).times do
+ # Check if the browser exited.
+ begin
+ break if status = ::Process.wait(@pid, ::Process::WNOHANG)
+ rescue SystemCallError # no children
+ break
+ end
+
+ # Check if the browser finished starting up.
begin
Net::HTTP.get(URI.parse('http://localhost:9669/json'))
@running = true
return self
- rescue Errno::ECONNREFUSED
+ rescue SystemCallError # most likely ECONNREFUSED
Kernel.sleep 0.05
end
end
@@ -48,19 +66,19 @@ class Process
#
# @return [WebkitRemote::Process] self
def stop
- FileUtils.rm_r @data_dir if File.exists?(@data_dir)
return self unless running?
begin
::Process.kill 'TERM', @pid
::Process.wait @pid
end
+ FileUtils.rm_rf @data_dir if File.exists?(@data_dir)
@running = false
self
end
# Remove temporary directory if it's still there at garbage collection time.
def finalize
- PathUtils.rm_r @data_dir if File.exists?(@data_dir)
+ PathUtils.rm_rf @data_dir if File.exists?(@data_dir)
end
# Command-line that launches Google Chrome / Chromium
@@ -68,23 +86,35 @@ class Process
# @param [Hash] opts options passed to the WebkitRemote::Process constructor
# @return [Array<String>] command line for launching Chrome
def chrome_cli(opts)
+ # The Chromium wiki recommends this page for available flags:
+ # http://peter.sh/experiments/chromium-command-line-switches/
[
self.class.chrome_binary,
- '--bwsi', # don't sign into a google account
+ '--disable-default-apps', # no bundled apps
+ '--disable-desktop-shortcuts', # don't mess with the desktop
+ '--disable-extensions', # no extensions
+ '--disable-internal-flash', # no plugins
+ '--disable-java', # no plugins
'--disable-logging', # don't trash stdout / stderr
'--disable-plugins', # no native content
'--disable-prompt-on-repost', # no confirmation dialog on POST refresh
+ '--disable-sync', # no talking with the Google servers
'--incognito', # don't use old state, don't preserve state
'--homepage=about:blank', # don't go to Google in new tabs
'--keep-alive-for-test', # don't kill process if the last window dies
'--lang=en-US', # set a default language
'--log-level=3', # FATAL, because there's no setting for "none"
'--no-default-browser-check', # don't hang when Chrome isn't default
+ '--no-experiments', # not sure this is useful
+ '--no-first-run', # don't show the help UI
'--no-js-randomness', # consistent Date.now() and Math.random()
+ '--no-message-box', # don't let user scripts show dialogs
'--no-service-autorun', # don't mess with autorun settings
'--noerrdialogs', # don't hang on error dialogs
"--remote-debugging-port=#{@port}",
- "--user-data-dir=#{@datadir}", # really ensure a clean slate
+ "--user-data-dir=#{@data_dir}", # really ensure a clean slate
+ '--window-position=0,0', # remove randomness source
+ '--window-size=128,128', # remove randomness source
'about:blank' # don't load the homepage
]
end
|
Fixes for OSX Chrome.
|
pwnall_webkit_remote
|
train
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.