hash
stringlengths 40
40
| diff
stringlengths 131
114k
| message
stringlengths 7
980
| project
stringlengths 5
67
| split
stringclasses 1
value |
|---|---|---|---|---|
95dda5018c4e198675b7901fc9ac253470d6ebe3
|
diff --git a/lib/bolt/cli.rb b/lib/bolt/cli.rb
index <HASH>..<HASH> 100644
--- a/lib/bolt/cli.rb
+++ b/lib/bolt/cli.rb
@@ -204,6 +204,10 @@ module Bolt
if options[:subcommand] == 'apply' && (!options[:object] && !options[:code])
raise Bolt::CLIError, "a manifest file or --execute is required"
end
+
+ if options[:subcommand] == 'command' && (!options[:object] || options[:object].empty?)
+ raise Bolt::CLIError, "Must specify a command to run"
+ end
end
def handle_parser_errors
|
(BOLT-<I>) Error with helpful message when no CLI command given
Previously an missing command argument would result in a stack trace. This commit validates that a command is given when invoking `bolt command run` on the CLI is a string with at least one character. Note this validation is modeled after the plan function `run_command` which validates the command argument is of type `String[1]`.
|
puppetlabs_bolt
|
train
|
e90f41d83f2bc20e73fa8840c8ce73b987250bb1
|
diff --git a/bugzoo/cli/controllers/bug.py b/bugzoo/cli/controllers/bug.py
index <HASH>..<HASH> 100644
--- a/bugzoo/cli/controllers/bug.py
+++ b/bugzoo/cli/controllers/bug.py
@@ -151,6 +151,7 @@ class BugController(cement.Controller):
def coverage(self) -> None:
name_bug = self.app.pargs.bug
bz = self.app.daemon
+ bugs = self.app.daemon.bugs
try:
bug = bugs[name_bug]
except KeyError:
|
Fixed use-before-define bug in "bugzoo bug coverage" command (#<I>)
|
squaresLab_BugZoo
|
train
|
6fe0540eb870cb509acdf7c4c660c40d420c8d24
|
diff --git a/index.js b/index.js
index <HASH>..<HASH> 100644
--- a/index.js
+++ b/index.js
@@ -12,46 +12,61 @@ const format = function(msg, ...args) {
return util.formatWithOptions({colors: true}, msg, ...args);
};
+class Lap {
+ constructor(started, timer) {
+ this.elapsed = 0;
+ this.started = started;
+ this.paused = false;
+ this.timer = timer;
+ this.timerId = timer.id;
+ }
+ pause() {
+ if (this.timer) this.timer.pause(this);
+ return this;
+ }
+ resume() {
+ if (this.timer) this.timer.resume(this);
+ return this;
+ }
+ stop(print) {
+ if (this.timer) this.timer.stop(print, this);
+ return this;
+ }
+}
+
+let nextId = 1;
+
class Stopwatch {
constructor(msg) {
- this.msg = msg || '';
+ this.id = nextId++;
this.reset();
+ this.msg = msg || '';
}
reset() {
+ if (this.pending) {
+ this.id = nextId++;
+ }
this.lap = null;
- this.laps = 0;
- this.total = 0;
- this.paused = false;
+ this.laps = [];
+ this.elapsed = 0;
this.started = null;
- this.parallels = 0;
- return this;
- }
- add(time) {
- this.laps += 1;
- this.total += time;
+ this.pending = 0;
return this;
}
start() {
- this.parallels++;
- if (this.started === null) {
- this.paused ? (this.paused = false) : (this.lap = 0);
- this.started = process.hrtime();
- }
- return this;
- }
- time() {
- if (this.started === null) return 0;
- const time = process.hrtime(this.started);
- return time[0] * 1e3 + time[1] * 1e-6;
+ this.pending += 1;
+ const lap = new Lap(process.hrtime(), this);
+ if (!this.started) this.started = lap.started;
+ return this.lap = lap;
}
print(time) {
if (this.msg) {
- if (time == null) time = this.total;
+ if (time == null) time = this.elapsed;
time = Number(time.toFixed(time < 100 ? 1 : 0));
let msg = this.msg;
if (lapsRE.test(msg)) {
- msg = format(msg.replace(lapsRE, '%O'), this.laps);
+ msg = format(msg.replace(lapsRE, '%O'), this.laps.length);
}
if (elapsedRE.test(msg)) {
console.log(format(msg.replace(elapsedRE, '%O ms'), time));
@@ -61,35 +76,80 @@ class Stopwatch {
}
return this;
}
- pause() {
- if (this.started !== null) {
- if (--this.parallels) return this;
- this.lap += this.time();
- this.paused = true;
- this.started = null;
+ pause(lap = this.lap) {
+ if (lap && lap.started) {
+ lap.elapsed = lap.time();
+ lap.started = null;
+ lap.paused = true;
+
+ if (lap.timerId === this.id && --this.pending === 0) {
+ this.elapsed = this.time();
+ this.started = null;
+ }
}
return this;
}
- stop(print) {
- if (--this.parallels) return this;
- if (this.started || this.paused) {
- let time = this.lap += this.time();
- this.laps += 1;
- this.total += time;
- this.paused = false;
- this.started = null;
- print && this.print(time);
+ resume(lap = this.lap) {
+ if (lap && lap.paused) {
+ lap.paused = false;
+ lap.started = process.hrtime();
+
+ if (lap.timerId === this.id && ++this.pending === 1) {
+ this.started = lap.started;
+ }
+ }
+ return this;
+ }
+ stop(print, lap = this.lap) {
+ if (lap && lap.timer) {
+ lap.timer = null;
+
+ if (lap.paused) {
+ lap.paused = false;
+ } else if (lap.started) {
+ lap.elapsed = lap.time();
+ lap.started = null;
+ }
+
+ if (lap.timerId === this.id) {
+ if (--this.pending === 0) {
+ this.elapsed = this.time();
+ this.started = null;
+ }
+ if (lap === this.lap) {
+ this.lap = null;
+ }
+ this.laps.push(lap.elapsed);
+ print && this.print(lap.elapsed);
+ }
}
return this;
}
+ sum() {
+ let sum = 0, i = 0;
+ const laps = this.laps, len = laps.length;
+ while (i < len) sum += laps[i++];
+ return sum;
+ }
average() {
- return this.total / this.laps;
+ return this.sum() / this.laps.length;
}
}
+Lap.prototype.time =
+Stopwatch.prototype.time = function time() {
+ if (this.started) {
+ const time = process.hrtime(this.started);
+ return this.elapsed + time[0] * 1e3 + time[1] * 1e-6;
+ }
+ return this.elapsed;
+};
+
function elaps(...args) {
const msg = args.length > 1 ? format(...args) : args[0];
- return new Stopwatch(msg).start();
+ const timer = new Stopwatch(msg);
+ timer.start();
+ return timer;
}
module.exports = elaps;
|
rewrite
- add Lap class
- rename `total` property to `elapsed`
- rename `parallels` property to `pending`
- the `laps` property is now an array of times (instead of the lap count)
- remove `add` method
- add `sum` method
- make `average` method use `sum` instead of `elapsed`
|
aleclarson_elaps
|
train
|
507a204249fbfe528b8d3caae7a64b35beab5d14
|
diff --git a/odb.go b/odb.go
index <HASH>..<HASH> 100644
--- a/odb.go
+++ b/odb.go
@@ -22,7 +22,7 @@ type OdbBackend struct {
Ptr *C.git_odb_backend
}
-func InitOdb() (odb *Odb, err error) {
+func NewOdb() (odb *Odb, err error) {
odb = new(Odb)
ret := C.git_odb_new(&odb.ptr)
diff --git a/repository.go b/repository.go
index <HASH>..<HASH> 100644
--- a/repository.go
+++ b/repository.go
@@ -45,7 +45,7 @@ func InitRepository(path string, isbare bool) (*Repository, error) {
return repo, nil
}
-func InitRepositoryByWrapOdb(odb *Odb) (repo *Repository, err error) {
+func NewRepositoryWrapOdb(odb *Odb) (repo *Repository, err error) {
repo = new(Repository)
ret := C.git_repository_wrap_odb(&repo.ptr, odb.ptr)
|
Rename constructor functions to New...
|
libgit2_git2go
|
train
|
fe9bb1b4f2e96f3fc00038e04436be8afb749d93
|
diff --git a/src/main/webapp/js/Plugins/propertywindow.js b/src/main/webapp/js/Plugins/propertywindow.js
index <HASH>..<HASH> 100644
--- a/src/main/webapp/js/Plugins/propertywindow.js
+++ b/src/main/webapp/js/Plugins/propertywindow.js
@@ -1735,6 +1735,7 @@ Ext.form.ComplexNotificationsField = Ext.extend(Ext.form.TriggerField, {
var gridId = Ext.id();
var itemDeleter = new Extensive.grid.ItemDeleter();
+ var bodyEditor = new Ext.form.TextArea({ id: 'notificationsbodyeditor', width: 150, height: 650, allowBlank: true, disableKeyFilter:true, grow: true});
var grid = new Ext.grid.EditorGridPanel({
autoScroll: true,
autoHeight: true,
@@ -1856,38 +1857,50 @@ Ext.form.ComplexNotificationsField = Ext.extend(Ext.form.TriggerField, {
if(evt.column != 8)
return true;
- var win = new Ext.Window
- ({
- autoWidth: true,
- autoHeight: true,
- bodyBorder: false,
- closable: true,
- resizable: false,
- items:
- [{
- xtype: 'panel',
- html: "<p class='instructions'>Enter Notification body message.</p>"
- },
- {
- xtype: 'textarea',
- id: 'notificationbodyinput',
- width: 350,
- height: 300,
- modal: true,
- value: evt.value
- }],
- bbar:
- [{
- text: 'OK',
- handler: function()
- {
- evt.record.set('body', Ext.get('notificationbodyinput').getValue());
- win.close();
- }
- }]
- });
- win.show();
- return false;
+ var existingWindow = Ext.get("notificationsBodyEditorWindow");
+ if(!existingWindow) {
+ var win = new Ext.Window
+ ({
+ id: 'notificationsBodyEditorWindow',
+ modal : true,
+ collapsible : false,
+ fixedcenter : true,
+ shadow : true,
+ proxyDrag : true,
+ autoScroll : true,
+ autoWidth : true,
+ autoHeight : true,
+ bodyBorder : false,
+ closable : true,
+ resizable : true,
+ items:
+ [{
+ xtype: 'panel',
+ html: "<p class='instructions'>Enter Notification body message.</p>"
+ },
+ {
+ xtype: 'textarea',
+ id: 'notificationbodyinput',
+ width: 350,
+ height: 300,
+ modal: true,
+ value: evt.value
+ }],
+ bbar:
+ [{
+ text: 'OK',
+ handler: function()
+ {
+ evt.record.set('body', Ext.get('notificationbodyinput').getValue());
+ win.close();
+ }
+ }]
+ });
+ win.show();
+ return false;
+ } else {
+ return false;
+ }
}
}
});
|
BZ <I> - fixed notifications body editor window
|
kiegroup_jbpm-designer
|
train
|
c829e39b22374a808c5e2e6abc6e82e99e736998
|
diff --git a/director/lib/director/jobs/update_release.rb b/director/lib/director/jobs/update_release.rb
index <HASH>..<HASH> 100644
--- a/director/lib/director/jobs/update_release.rb
+++ b/director/lib/director/jobs/update_release.rb
@@ -71,7 +71,11 @@ module Bosh::Director
end
rescue Exception => e
@logger.error("#{e} - #{e.backtrace.join("\n")}")
- @release.delete if @release && !@release.new?
+
+ templates = Models::Template.find(:release_version => @release_version_entry)
+ templates.each {|template| template.delete}
+
+ @release_version_entry.delete if @release_version_entry && !@release_version_entry.new?
@task.state = :error
@task.result = e.to_s
@@ -81,7 +85,6 @@ module Bosh::Director
raise e
ensure
FileUtils.rm_rf(@tmp_release_dir)
- # TODO: delete any templates or other models created
# TODO: delete task status file or cleanup later?
end
end
|
cleanup models that were created during a bad request
|
cloudfoundry_bosh
|
train
|
1bedaa474e10b2d3698a851077818a904a7b96ea
|
diff --git a/setup.py b/setup.py
index <HASH>..<HASH> 100644
--- a/setup.py
+++ b/setup.py
@@ -26,6 +26,7 @@ INSTALL_REQUIRES = [
'requests>=2.5',
'cached-property>=1.5',
'python-dateutil>=2.4',
+ # NOTE: Can be removed after a fix:
# https://github.com/tobgu/pyrsistent/issues/208
'pyrsistent<0.17',
'jsonschema>=2.5',
|
Added a comment for the Travis/py2 problem
|
frictionlessdata_tableschema-py
|
train
|
ff5dea4a2a1aeb1772f51b75060410900883b7dd
|
diff --git a/tools/c7n_org/c7n_org/cli.py b/tools/c7n_org/c7n_org/cli.py
index <HASH>..<HASH> 100644
--- a/tools/c7n_org/c7n_org/cli.py
+++ b/tools/c7n_org/c7n_org/cli.py
@@ -17,11 +17,17 @@
from collections import Counter
import logging
import os
-import multiprocessing
import time
import subprocess
+import six
import sys
+# Try to set this early if offers any help against this OSX issue
+# https://bugs.python.org/issue33725
+# if sys.platform == 'darwin':
+# os.environ['OBJC_DISABLE_INITIALIZE_FORK_SAFETY'] = 'YES'
+
+import multiprocessing
from concurrent.futures import (
ProcessPoolExecutor,
as_completed)
@@ -47,11 +53,6 @@ from c7n.utils import UnicodeWriter
log = logging.getLogger('c7n_org')
-# On OSX High Sierra Workaround
-# https://github.com/ansible/ansible/issues/32499
-if sys.platform == 'darwin':
- os.environ['OBJC_DISABLE_INITIALIZE_FORK_SAFETY'] = 'YES'
-
WORKER_COUNT = int(
os.environ.get('C7N_ORG_PARALLEL', multiprocessing.cpu_count() * 4))
@@ -202,9 +203,22 @@ def resolve_regions(regions, partition='aws'):
def get_session(account, session_name, region):
if account.get('role'):
- return assumed_session(
- account['role'], session_name, region=region,
- external_id=account.get('external_id'))
+ roles = account['role']
+ if isinstance(roles, six.string_types):
+ roles = [roles]
+ s = None
+ for r in roles:
+ try:
+ s = assumed_session(
+ r, session_name, region=region,
+ external_id=account.get('external_id'),
+ session=s)
+ except ClientError as e:
+ log.error(
+ "unable to obtain credentials for account:%s role:%s error:%s",
+ account['name'], r, e)
+ raise
+ return s
elif account.get('profile'):
return SessionFactory(region, account['profile'])()
else:
@@ -372,21 +386,24 @@ def report(config, output, use, output_dir, accounts,
writer.writerows(rows)
+def _get_env_creds(session, region):
+ creds = session._session.get_credentials()
+ env = {}
+ env['AWS_ACCESS_KEY_ID'] = creds.access_key
+ env['AWS_SECRET_ACCESS_KEY'] = creds.secret_key
+ env['AWS_SESSION_TOKEN'] = creds.token
+ env['AWS_DEFAULT_REGION'] = region
+ return env
+
+
def run_account_script(account, region, output_dir, debug, script_args):
try:
session = get_session(account, "org-script", region)
- creds = session._session.get_credentials()
except ClientError:
- log.error(
- "unable to obtain credentials for account:%s role:%s",
- account['name'], account['role'])
return 1
env = os.environ.copy()
- env['AWS_ACCESS_KEY_ID'] = creds.access_key
- env['AWS_SECRET_ACCESS_KEY'] = creds.secret_key
- env['AWS_SESSION_TOKEN'] = creds.token
- env['AWS_DEFAULT_REGION'] = region
+ env.update(_get_env_creds(session, region))
log.info("running script on account:%s region:%s script: `%s`",
account['name'], region, " ".join(script_args))
@@ -492,9 +509,16 @@ def run_account(account, region, policies_config, output_path,
account_id=account['account_id'], metrics_enabled=metrics,
log_group=None, profile=None, external_id=None)
+ env_vars = account_tags(account)
+
if account.get('role'):
- config['assume_role'] = account['role']
- config['external_id'] = account.get('external_id')
+ if isinstance(account['role'], six.string_types):
+ config['assume_role'] = account['role']
+ config['external_id'] = account.get('external_id')
+ else:
+ env_vars.update(
+ _get_env_creds(get_session(account, 'custodian', region), region))
+
elif account.get('profile'):
config['profile'] = account['profile']
@@ -503,9 +527,8 @@ def run_account(account, region, policies_config, output_path,
success = True
st = time.time()
- with environ(**account_tags(account)):
+ with environ(**env_vars):
for p in policies:
-
# Variable expansion and non schema validation (not optional)
p.expand_variables(p.get_variables(account.get('vars', {})))
p.validate()
|
tools/c7n-org - chained sts role support (#<I>)
|
cloud-custodian_cloud-custodian
|
train
|
1a91395f1d28bf8b1a678f7ba0d5b4acc6deb360
|
diff --git a/lib/inline_forms.rb b/lib/inline_forms.rb
index <HASH>..<HASH> 100644
--- a/lib/inline_forms.rb
+++ b/lib/inline_forms.rb
@@ -1,15 +1,15 @@
require ('inline_forms/version.rb')
-#puts "Loading inline_forms version #{InlineForms::VERSION}"
+# InlineForms is a Rails Engine that let you setup an admin interface quick and
+# easy. Please install it as a gem or include it in your Gemfile.
module InlineForms
-
- # ActiveRecord::Migration comes with a set of column types.
- # They are listed here so they can be used alongside our Special Column Types.
+ # DEFAULT_COLUMN_TYPES holds the standard ActiveRecord::Migration column types.
+ # This list provides compatability with the standard types, but we add our own
+ # later in 'Special Column Types'.
#
- # These types will override the Special Column Types, so don't declare
- # types with these names as Special Column Types!
+ # These types will override Special Column Types of the same name.\
#
# Example:
- # rails g inline_forms Example name:string price:integer
+ # rails g inline_forms Example name:string price:integer
# will result in:
# class InlineFormsCreateExamples < ActiveRecord::Migration
# def self.up
@@ -40,7 +40,9 @@ module InlineForms
# :belongs_to => :belongs_to,
}
- # For each Default Column Type, we need to specify a Form Element for use in form creation.
+ # DEFAULT_FORM_ELEMENTS holds a mapping from Default Column Types to
+ # Form Elements. Form Elements are defined in app/helpers/form_elements
+ # and are pieces of code that display a form for a field.
#
# Example:
# rails g inline_forms Example name:string price:integer
@@ -70,12 +72,11 @@ module InlineForms
:boolean => :check_box,
}
- # This Hash will be used to map our Special Column Types to
- # ActiveRecord::Migration Column Types.
+ # SPECIAL_COLUMN_TYPES maps the column types that we define here and in
+ # app/helpers/form_elements to the standard ActiveRecord::Migration column
+ # types
#
- # The helpers in app/helpers/form_elements add to this Hash.
- #
- # Usage example: in app/helpers/form_elements/dropdown.rb
+ # Example: in app/helpers/form_elements/dropdown.rb
# InlineForms::SPECIAL_COLUMN_TYPES[:dropdown]=:belongs_to
# this maps the :dropdown form element to the :belongs_to column type.
#
@@ -89,6 +90,9 @@ module InlineForms
SPECIAL_COLUMN_TYPES = {
:associated => :no_migration
}
+
+ # RELATIONS defines a mapping between AR::Migrations columns and the Model.
+ #
# When a column has the type of :references or :belongs_to, then
# there will be a line in the migration reflecting that, but not in the model.
# == Why?
@@ -115,7 +119,9 @@ module InlineForms
:references => :belongs_to,
}
- # The stuff in this hash will add a line to the model, but little else.
+ # SPECIAL_RELATIONS maps AR relations to migrations.
+ # In most cases, these relations have no migration at all, but they do need
+ # a line in the model.
SPECIAL_RELATIONS = {
:has_many => :no_migration,
:has_many_destroy => :no_migration,
@@ -125,10 +131,10 @@ module InlineForms
}
# Declare as a Rails::Engine, see http://www.ruby-forum.com/topic/211017#927932
- class InlineFormsEngine < Rails::Engine
- initializer 'inline_forms.helper' do |app|
- ActionView::Base.send :include, InlineFormsHelper
- end
+ class Engine < Rails::Engine
+# initializer 'inline_forms.helper' do |app|
+# ActionView::Base.send :include, InlineFormsHelper
+# end
end
end
|
playing with the engine definition, and updated docs
|
acesuares_inline_forms
|
train
|
e0a83cb416af603e9f077cd863135cbad7e41b3d
|
diff --git a/lib/prawn_commander.rb b/lib/prawn_commander.rb
index <HASH>..<HASH> 100644
--- a/lib/prawn_commander.rb
+++ b/lib/prawn_commander.rb
@@ -7,6 +7,14 @@ module Prawn
@prawn_commands = []
@options = options
end
+
+ def prawn_commands(&block)
+ ctx = @prawn_commands
+ if block
+ block.arity < 1 ? ctx.instance_eval(&block) : block.call(ctx)
+ end
+ ctx
+ end
def raw_prawn_commands
raw_commands = []
diff --git a/spec/prawn_commander_spec.rb b/spec/prawn_commander_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/prawn_commander_spec.rb
+++ b/spec/prawn_commander_spec.rb
@@ -1,7 +1,7 @@
require File.expand_path(File.dirname(__FILE__) + "/spec_helper")
describe Prawn::Commander do
- let (:doc) { Prawn::Document.new(:page_size => "A4") }
+ let (:doc) { Prawn::Document.new }
before(:each) do
@commander = Prawn::Commander.new
@@ -17,6 +17,9 @@ describe Prawn::Commander do
it "should add 'move_down' to command stack" do
@commander.prawn_command(:move_down, 10)
@commander.prawn_commands.first.should be_command(:move_down, 10)
+ @commander.prawn_commands do |c|
+ c.first.should be_command(:move_down, 10)
+ end
end
end
|
added block arg to prawn_commands for testing convenience etc
|
kristianmandrup_prawn_commander
|
train
|
2b0071e8b0e091bc8368a9b05dddfec4400e5b9e
|
diff --git a/spec/frameworks_rules_spec.rb b/spec/frameworks_rules_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/frameworks_rules_spec.rb
+++ b/spec/frameworks_rules_spec.rb
@@ -26,7 +26,7 @@ describe 'Frameworks rules' do
expect(repository.primary_frameworks).to eq ['Rails']
end
- it 'does not returns Rails when commented out' do
+ it 'does not return Rails when commented out' do
repository = repository('Gemfile', "bogus\n# gem 'rails'\nbogus")
expect(repository.primary_frameworks).to_not eq ['Rails']
end
@@ -52,6 +52,21 @@ describe 'Frameworks rules' do
expect(repository.primary_frameworks).to eq ['Sinatra']
expect(repository.secondary_frameworks).to eq []
end
+
+ it 'returns Sinatra when specified with version' do
+ repository = repository('Gemfile', "bogus\ngem 'sinatra', '~> 4.3'\nbogus")
+ expect(repository.primary_frameworks).to eq ['Sinatra']
+ end
+
+ it 'returns Sinatra when indented' do
+ repository = repository('Gemfile', "bogus\n gem 'sinatra'\nbogus")
+ expect(repository.primary_frameworks).to eq ['Sinatra']
+ end
+
+ it 'does not return Sinatra when commented out' do
+ repository = repository('Gemfile', "bogus\n# gem 'sinatra'\nbogus")
+ expect(repository.primary_frameworks).to_not eq ['Sinatra']
+ end
end
describe 'Dashing' do
@@ -60,6 +75,21 @@ describe 'Frameworks rules' do
expect(repository.primary_frameworks).to eq ['Sinatra']
expect(repository.secondary_frameworks).to eq ['Dashing']
end
+
+ it 'returns Sinatra when specified with version' do
+ repository = repository('Gemfile', "bogus\ngem 'dashing', '~> 4.3'\nbogus")
+ expect(repository.primary_frameworks).to eq ['Sinatra']
+ end
+
+ it 'returns Sinatra when indented' do
+ repository = repository('Gemfile', "bogus\n gem 'dashing'\nbogus")
+ expect(repository.primary_frameworks).to eq ['Sinatra']
+ end
+
+ it 'does not return Sinatra when commented out' do
+ repository = repository('Gemfile', "bogus\n# gem 'dashing'\nbogus")
+ expect(repository.primary_frameworks).to_not eq ['Sinatra']
+ end
end
describe 'Middleman' do
@@ -68,6 +98,21 @@ describe 'Frameworks rules' do
expect(repository.primary_frameworks).to eq ['Middleman']
expect(repository.secondary_frameworks).to eq []
end
+
+ it 'returns Middleman when specified with version' do
+ repository = repository('Gemfile', "bogus\ngem 'middleman', '~> 4.3'\nbogus")
+ expect(repository.primary_frameworks).to eq ['Middleman']
+ end
+
+ it 'returns Middleman when indented' do
+ repository = repository('Gemfile', "bogus\n gem 'middleman'\nbogus")
+ expect(repository.primary_frameworks).to eq ['Middleman']
+ end
+
+ it 'does not return Middleman when commented out' do
+ repository = repository('Gemfile', "bogus\n# gem 'middleman'\nbogus")
+ expect(repository.primary_frameworks).to_not eq ['Middleman']
+ end
end
def repository(file_name, file_content)
|
explode additional rule specs for all gem based rules
We want full spec coverage for our matchers. That currently means we
duplicate the added specs for gem based rules from Rails to the other
ones.
We might introduce some extended rule matchers for such cases which
would allow to drop the number of copied specs later on.
|
koffeinfrei_technologist
|
train
|
ac318faf5ac08888a01564bc9a4530dbb4c003ca
|
diff --git a/cake/tests/cases/libs/html_coverage_report.test.php b/cake/tests/cases/libs/html_coverage_report.test.php
index <HASH>..<HASH> 100644
--- a/cake/tests/cases/libs/html_coverage_report.test.php
+++ b/cake/tests/cases/libs/html_coverage_report.test.php
@@ -61,7 +61,7 @@ class HtmlCoverageReportTest extends CakeTestCase {
function testFilterCoverageDataByPathRemovingElements() {
$data = array(
array(
- 'data' => array(
+ 'files' => array(
TEST_CAKE_CORE_INCLUDE_PATH . 'dispatcher.php' => array(
10 => -1,
12 => 1
@@ -87,28 +87,37 @@ class HtmlCoverageReportTest extends CakeTestCase {
function testFilterCoverageDataCorrectlyMergingValues() {
$data = array(
array(
- 'data' => array(
- TEST_CAKE_CORE_INCLUDE_PATH . 'dispatcher.php' => array(
- 10 => -1,
+ 'files' => array(
+ '/something/dispatcher.php' => array(
+ 10 => 1,
12 => 1
),
+ ),
+ 'executable' => array(
+ '/something/dispatcher.php' => array(
+ 10 => -1
+ )
)
),
array(
- 'data' => array(
- TEST_CAKE_CORE_INCLUDE_PATH . 'dispatcher.php' => array(
+ 'files' => array(
+ '/something/dispatcher.php' => array(
10 => 1,
- 12 => -1,
50 => 1,
- 51 => -1
),
+ ),
+ 'executable' => array(
+ '/something/dispatcher.php' => array(
+ 12 => -1,
+ 51 => -1
+ )
)
),
);
$this->Coverage->setCoverage($data);
- $result = $this->Coverage->filterCoverageDataByPath(TEST_CAKE_CORE_INCLUDE_PATH);
+ $result = $this->Coverage->filterCoverageDataByPath('/something/');
- $path = TEST_CAKE_CORE_INCLUDE_PATH . 'dispatcher.php';
+ $path = '/something/dispatcher.php';
$this->assertTrue(isset($result[$path]));
$this->assertEquals(1, $result[$path][10]);
$this->assertEquals(1, $result[$path][12]);
diff --git a/cake/tests/lib/coverage/html_coverage_report.php b/cake/tests/lib/coverage/html_coverage_report.php
index <HASH>..<HASH> 100644
--- a/cake/tests/lib/coverage/html_coverage_report.php
+++ b/cake/tests/lib/coverage/html_coverage_report.php
@@ -120,20 +120,17 @@ class HtmlCoverageReport {
public function filterCoverageDataByPath($path) {
$files = array();
foreach ($this->_rawCoverage as $testRun) {
- foreach ($testRun['data'] as $filename => $fileCoverage) {
+ foreach ($testRun['files'] as $filename => $fileCoverage) {
if (strpos($filename, $path) !== 0) {
continue;
}
+ $dead = isset($testRun['dead'][$filename]) ? $testRun['dead'][$filename] : array();
+ $executable = isset($testRun['executable'][$filename]) ? $testRun['executable'][$filename] : array();
+
if (!isset($files[$filename])) {
$files[$filename] = array();
}
- foreach ($fileCoverage as $line => $value) {
- if (!isset($files[$filename][$line])) {
- $files[$filename][$line] = $value;
- } elseif ($files[$filename][$line] < $value) {
- $files[$filename][$line] = $value;
- }
- }
+ $files[$filename] = $files[$filename] + $fileCoverage + $executable + $dead;
}
}
ksort($files);
diff --git a/cake/tests/lib/reporter/cake_html_reporter.php b/cake/tests/lib/reporter/cake_html_reporter.php
index <HASH>..<HASH> 100755
--- a/cake/tests/lib/reporter/cake_html_reporter.php
+++ b/cake/tests/lib/reporter/cake_html_reporter.php
@@ -176,7 +176,7 @@ class CakeHtmlReporter extends CakeBaseReporter implements PHPUnit_Framework_Tes
echo $this->_paintLinks();
echo '</div>';
if (isset($this->params['codeCoverage']) && $this->params['codeCoverage']) {
- $coverage = $result->getRawCodeCoverageInformation();
+ $coverage = $result->getCodeCoverageInformation();
echo $this->paintCoverage($coverage);
}
$this->paintDocumentEnd();
diff --git a/cake/tests/lib/test_manager.php b/cake/tests/lib/test_manager.php
index <HASH>..<HASH> 100644
--- a/cake/tests/lib/test_manager.php
+++ b/cake/tests/lib/test_manager.php
@@ -162,7 +162,7 @@ class TestManager {
*/
protected function run($reporter, $codeCoverage = false) {
$result = new PHPUnit_Framework_TestResult;
- $result->collectRawCodeCoverageInformation($codeCoverage);
+ $result->collectCodeCoverageInformation($codeCoverage);
$result->addListener($reporter);
$reporter->paintHeader();
$this->getTestSuite()->run($result);
|
Switching back to using non raw code coverage data as it has been filtered by phpunit's filters. combining the data from phpunit into a singular cohesive report.
|
cakephp_cakephp
|
train
|
b4100f88a80e621bca68627a88bb17bc27bdba32
|
diff --git a/agrona/src/main/java/org/agrona/concurrent/AgentInvoker.java b/agrona/src/main/java/org/agrona/concurrent/AgentInvoker.java
index <HASH>..<HASH> 100644
--- a/agrona/src/main/java/org/agrona/concurrent/AgentInvoker.java
+++ b/agrona/src/main/java/org/agrona/concurrent/AgentInvoker.java
@@ -146,7 +146,6 @@ public class AgentInvoker implements AutoCloseable
}
catch (final InterruptedException | ClosedByInterruptException ignore)
{
- Thread.interrupted();
close();
}
catch (final AgentTerminationException ex)
|
[Java] Remove clearing of interrupted flag in AgentInvoker. Issue #<I>.
|
real-logic_agrona
|
train
|
397a0756b8e9d43d08e0d6812a79349af5b454c4
|
diff --git a/lib/auth.strategies/anonymous.js b/lib/auth.strategies/anonymous.js
index <HASH>..<HASH> 100644
--- a/lib/auth.strategies/anonymous.js
+++ b/lib/auth.strategies/anonymous.js
@@ -1,5 +1,5 @@
/*!
- * Copyright(c) 2010 Ciaran Jessup <ciaranj@gmai.com>
+ * Copyright(c) 2010 Ciaran Jessup <ciaranj@gmail.com>
* MIT Licensed
*/
module.exports= function(options) {
diff --git a/lib/auth.strategies/facebook.js b/lib/auth.strategies/facebook.js
index <HASH>..<HASH> 100644
--- a/lib/auth.strategies/facebook.js
+++ b/lib/auth.strategies/facebook.js
@@ -1,5 +1,5 @@
/*!
- * Copyright(c) 2010 Ciaran Jessup <ciaranj@gmai.com>
+ * Copyright(c) 2010 Ciaran Jessup <ciaranj@gmail.com>
* MIT Licensed
*/
var OAuth= require("oauth").OAuth2,
diff --git a/lib/auth.strategies/github.js b/lib/auth.strategies/github.js
index <HASH>..<HASH> 100644
--- a/lib/auth.strategies/github.js
+++ b/lib/auth.strategies/github.js
@@ -1,5 +1,5 @@
/*!
- * Copyright(c) 2010 Ciaran Jessup <ciaranj@gmai.com>
+ * Copyright(c) 2010 Ciaran Jessup <ciaranj@gmail.com>
* MIT Licensed
*/
var OAuth= require("oauth").OAuth2,
diff --git a/lib/auth.strategies/http/base.js b/lib/auth.strategies/http/base.js
index <HASH>..<HASH> 100644
--- a/lib/auth.strategies/http/base.js
+++ b/lib/auth.strategies/http/base.js
@@ -1,5 +1,5 @@
/*!
- * Copyright(c) 2010 Ciaran Jessup <ciaranj@gmai.com>
+ * Copyright(c) 2010 Ciaran Jessup <ciaranj@gmail.com>
* MIT Licensed
*/
Base= module.exports= function () {
diff --git a/lib/auth.strategies/http/basic.js b/lib/auth.strategies/http/basic.js
index <HASH>..<HASH> 100644
--- a/lib/auth.strategies/http/basic.js
+++ b/lib/auth.strategies/http/basic.js
@@ -1,5 +1,5 @@
/*!
- * Copyright(c) 2010 Ciaran Jessup <ciaranj@gmai.com>
+ * Copyright(c) 2010 Ciaran Jessup <ciaranj@gmail.com>
* MIT Licensed
*/
diff --git a/lib/auth.strategies/http/digest.js b/lib/auth.strategies/http/digest.js
index <HASH>..<HASH> 100644
--- a/lib/auth.strategies/http/digest.js
+++ b/lib/auth.strategies/http/digest.js
@@ -1,5 +1,5 @@
/*!
- * Copyright(c) 2010 Ciaran Jessup <ciaranj@gmai.com>
+ * Copyright(c) 2010 Ciaran Jessup <ciaranj@gmail.com>
* MIT Licensed
*/
var Base= require("./base");
diff --git a/lib/auth.strategies/http/http.js b/lib/auth.strategies/http/http.js
index <HASH>..<HASH> 100644
--- a/lib/auth.strategies/http/http.js
+++ b/lib/auth.strategies/http/http.js
@@ -1,5 +1,5 @@
/*!
- * Copyright(c) 2010 Ciaran Jessup <ciaranj@gmai.com>
+ * Copyright(c) 2010 Ciaran Jessup <ciaranj@gmail.com>
* MIT Licensed
*/
diff --git a/lib/auth.strategies/janrain.js b/lib/auth.strategies/janrain.js
index <HASH>..<HASH> 100644
--- a/lib/auth.strategies/janrain.js
+++ b/lib/auth.strategies/janrain.js
@@ -1,5 +1,5 @@
/*!
- * Copyright(c) 2010 Ciaran Jessup <ciaranj@gmai.com>
+ * Copyright(c) 2010 Ciaran Jessup <ciaranj@gmail.com>
* MIT Licensed
*/
var OAuth= require("oauth").OAuth2,
diff --git a/lib/auth.strategies/never.js b/lib/auth.strategies/never.js
index <HASH>..<HASH> 100644
--- a/lib/auth.strategies/never.js
+++ b/lib/auth.strategies/never.js
@@ -1,5 +1,5 @@
/*!
- * Copyright(c) 2010 Ciaran Jessup <ciaranj@gmai.com>
+ * Copyright(c) 2010 Ciaran Jessup <ciaranj@gmail.com>
* MIT Licensed
*/
module.exports= function(options) {};
diff --git a/lib/auth.strategies/twitter.js b/lib/auth.strategies/twitter.js
index <HASH>..<HASH> 100644
--- a/lib/auth.strategies/twitter.js
+++ b/lib/auth.strategies/twitter.js
@@ -1,5 +1,5 @@
/*!
- * Copyright(c) 2010 Ciaran Jessup <ciaranj@gmai.com>
+ * Copyright(c) 2010 Ciaran Jessup <ciaranj@gmail.com>
* MIT Licensed
*/
var OAuth= require("oauth").OAuth,
diff --git a/lib/auth.strategies/yahoo.js b/lib/auth.strategies/yahoo.js
index <HASH>..<HASH> 100644
--- a/lib/auth.strategies/yahoo.js
+++ b/lib/auth.strategies/yahoo.js
@@ -1,5 +1,5 @@
/*!
- * Copyright(c) 2010 Ciaran Jessup <ciaranj@gmai.com>
+ * Copyright(c) 2010 Ciaran Jessup <ciaranj@gmail.com>
* MIT Licensed
*/
var OAuth= require("oauth").OAuth,
|
Oops, my copyright header had an invalid e-mail address
|
ciaranj_connect-auth
|
train
|
800dad316341f18b40e29db1acfc06d3dd21c093
|
diff --git a/securesystemslib/hash.py b/securesystemslib/hash.py
index <HASH>..<HASH> 100755
--- a/securesystemslib/hash.py
+++ b/securesystemslib/hash.py
@@ -194,7 +194,9 @@ def digest(algorithm=DEFAULT_HASH_ALGORITHM, hash_library=DEFAULT_HASH_LIBRARY):
else:
return hashlib.new(algorithm)
- except ValueError:
+ except (ValueError, TypeError):
+ # ValueError: the algorithm value was unknown
+ # TypeError: unexpected argument digest_size (on old python)
raise securesystemslib.exceptions.UnsupportedAlgorithmError(algorithm)
# Was a pyca_crypto digest object requested and is it supported?
|
hash: raise UnsupportedAlgorithmError, not TypeError
This raises TypeError on python < <I>:
hashlib.new('blake2b', digest_size=<I>)
because the argument is unexpected: re-raise as
UnsupportedAlgorithmError
|
secure-systems-lab_securesystemslib
|
train
|
289d99db7cca7c26be9d0e56a8512ff65ca999ab
|
diff --git a/ignite/metrics/gan/fid.py b/ignite/metrics/gan/fid.py
index <HASH>..<HASH> 100644
--- a/ignite/metrics/gan/fid.py
+++ b/ignite/metrics/gan/fid.py
@@ -22,7 +22,7 @@ def fid_score(
raise RuntimeError("fid_score requires numpy to be installed.")
try:
- import scipy
+ import scipy.linalg
except ImportError:
raise RuntimeError("fid_score requires scipy to be installed.")
|
Fix fid import scipy (#<I>)
* fix fid
* merged from master
|
pytorch_ignite
|
train
|
85c462847a564abd20e5c8aaa12b0d150de12d1e
|
diff --git a/ninio-core/src/test/java/com/davfx/ninio/core/TcpdumpTest.java b/ninio-core/src/test/java/com/davfx/ninio/core/TcpdumpTest.java
index <HASH>..<HASH> 100644
--- a/ninio-core/src/test/java/com/davfx/ninio/core/TcpdumpTest.java
+++ b/ninio-core/src/test/java/com/davfx/ninio/core/TcpdumpTest.java
@@ -4,6 +4,7 @@ import java.io.IOException;
import java.nio.ByteBuffer;
import org.assertj.core.api.Assertions;
+import org.junit.Ignore;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -18,6 +19,7 @@ public class TcpdumpTest {
private static final Logger LOGGER = LoggerFactory.getLogger(TcpdumpTest.class);
+ @Ignore
@Test
public void test() throws Exception {
System.setProperty("ninio.tcpdump.mode", "hex"); // raw not working on Mac OS X
|
Ignoring too much machine-dependent test
|
davidfauthoux_ninio
|
train
|
7fe931cfcea4fc5c5abcf1b95b874565afb61af3
|
diff --git a/base/assets/resource-smart-load.js b/base/assets/resource-smart-load.js
index <HASH>..<HASH> 100644
--- a/base/assets/resource-smart-load.js
+++ b/base/assets/resource-smart-load.js
@@ -1,3 +1,4 @@
+;
(function () {
"use strict";
if (window.yiiResourceSmartLoadPrivateObj) {
|
- refactored: restored leading semi-colon
|
IStranger_yii2-resource-smart-load
|
train
|
6e5e0c9363e1d47f33179806aaf4ba6d2612dbb6
|
diff --git a/index.php b/index.php
index <HASH>..<HASH> 100644
--- a/index.php
+++ b/index.php
@@ -187,6 +187,7 @@
if (!empty($USER->id)) {
$SESSION->fromdiscussion = $CFG->wwwroot;
+ $subtext = '';
if (forum_is_subscribed($USER->id, $newsforum)) {
if (!forum_is_forcesubscribed($newsforum)) {
$subtext = get_string('unsubscribe', 'forum');
|
"FORUM/MDL-<I>, declare subtext varible before use it, merged from <I>"
|
moodle_moodle
|
train
|
84a9db331f8642a22468b6a03afe140c9962fd7e
|
diff --git a/lang/en_utf8/forum.php b/lang/en_utf8/forum.php
index <HASH>..<HASH> 100644
--- a/lang/en_utf8/forum.php
+++ b/lang/en_utf8/forum.php
@@ -59,7 +59,7 @@ $string['displayperiod'] = 'Display Period';
$string['displaystart'] = 'Display start';
$string['eachuserforum'] = 'Each person posts one discussion';
$string['edit'] = 'Edit';
-$string['editedby'] = 'Edited by $a->name - $a->date';
+$string['editedby'] = 'Edited by $a->name - original submission $a->date';
$string['editing'] = 'Editing';
$string['emptymessage'] = 'Something was wrong with your post. Perhaps you left it blank, or the attachment was too big. Your changes have NOT been saved.';
$string['everyonecanchoose'] = 'Everyone can choose to be subscribed';
|
Bug #<I> - editing forum post bug; merged from MOODLE_<I>_STABLE
|
moodle_moodle
|
train
|
bc33e03679d99e5da67a40ef3f0173c1e3efc877
|
diff --git a/lib/omnibus/builder.rb b/lib/omnibus/builder.rb
index <HASH>..<HASH> 100644
--- a/lib/omnibus/builder.rb
+++ b/lib/omnibus/builder.rb
@@ -573,29 +573,6 @@ module Omnibus
# --------------------------------------------------
#
- # @!group Deprecated DSL methods
- #
- # The following DSL methods are available from within build blocks, but are
- # deprecated and will be removed in the next major release.
- # --------------------------------------------------
-
- #
- # @deprecated Use {Config.project_root} instead
- #
- def project_root
- Omnibus.logger.deprecated(log_key) do
- 'project_root (DSL). Please use Config.project_root instead.'
- end
-
- Config.project_root
- end
- expose :project_root
-
- #
- # @!endgroup
- # --------------------------------------------------
-
- #
# @!group Public API
#
# The following methods are considered part of the public API for a
|
Remove deprecated Builder.project_root
|
chef_omnibus
|
train
|
9852c7012e9707e24336bebc5e44eb55cba14344
|
diff --git a/fontbakery-check-ttf.py b/fontbakery-check-ttf.py
index <HASH>..<HASH> 100755
--- a/fontbakery-check-ttf.py
+++ b/fontbakery-check-ttf.py
@@ -247,7 +247,8 @@ ghm_report_files = []
class FontBakeryCheckLogger():
progressbar = False
- def __init__(self):
+ def __init__(self, config):
+ self.config = config
self.reset_report()
def reset_report(self):
@@ -277,17 +278,18 @@ class FontBakeryCheckLogger():
round(percent, 2)))
print (" Total: {} checks.\n".format(total))
- if not args.verbose:
+ if not self.config['verbose']:
filtered = []
for check in self.all_checks:
if check["result"] != "OK":
filtered.append(check)
self.all_checks = filtered
- if args.json:
+ if self.config['json']:
json_path = font_file + ".fontbakery.json"
fb.output_json_report(json_path)
- if args.ghm:
+
+ if self.config['ghm']:
md_path = font_file + ".fontbakery.md"
fb.output_github_markdown_report(md_path)
@@ -396,12 +398,10 @@ class FontBakeryCheckLogger():
self.current_check['log_messages'].append('HOTFIX: ' + msg)
self.current_check['result'] = "HOTFIX"
-fb = FontBakeryCheckLogger()
-
# =====================================
# HELPER FUNCTIONS
-args = None
font = None
+fb = None
fixes = []
@@ -595,7 +595,7 @@ parser.add_argument('-m', '--ghm', action='store_true',
# =====================================
# Main sequence of checkers & fixers
def fontbakery_check_ttf(config):
- global font
+ global font, fb
# set up a basic logging config
handler = logging.StreamHandler()
@@ -617,6 +617,8 @@ def fontbakery_check_ttf(config):
fb.progressbar = False
logger.setLevel(logging.ERROR)
+ fb = FontBakeryCheckLogger(config)
+
# ------------------------------------------------------
logging.debug("Checking each file is a ttf")
fonts_to_check = []
|
minor FontBakeryCheckLogger refactoring
gradually reducing reliance on global vars
|
googlefonts_fontbakery
|
train
|
c96f6a1a8c7b6bf2f4860c667867d90174799eb2
|
diff --git a/logger.go b/logger.go
index <HASH>..<HASH> 100644
--- a/logger.go
+++ b/logger.go
@@ -6,6 +6,7 @@ package logger
import (
"fmt"
+ "io/ioutil"
"log"
"os"
"strings"
@@ -37,6 +38,13 @@ type Logger struct {
var DefaultLogger = New()
func New() *Logger {
+ if os.Getenv("LOGGER_DISCARD") != "" {
+ // Hack to completely disable logging, for example when running benchmarks.
+ return &Logger{
+ logger: log.New(ioutil.Discard, "", 0),
+ }
+ }
+
return &Logger{
logger: log.New(os.Stdout, "", log.Ltime),
}
|
Support LOGGER_DISCARD
|
calmh_logger
|
train
|
0a1898e9a78882a29ce7d4b9a5fa60bc0609252c
|
diff --git a/CustomFields/CustomFieldChoice.php b/CustomFields/CustomFieldChoice.php
index <HASH>..<HASH> 100644
--- a/CustomFields/CustomFieldChoice.php
+++ b/CustomFields/CustomFieldChoice.php
@@ -177,7 +177,35 @@ class CustomFieldChoice extends AbstractCustomField
public function isEmptyValue($value, CustomField $customField)
{
- return $value['_choices'] === NULL;
+ if ($value === NULL) {
+ return true;
+ }
+
+ // if only one choice...
+ if (is_string($value)) {
+ return empty($value);
+ }
+
+ // if multiple choice OR multiple/single choice with other
+ if (is_array($value))
+ {
+ // if allow other
+ if (isset($value['_choices'])) {
+ if ($value['_choices'] === NULL) {
+ return true;
+ }
+ if (is_string($value['_choices'])) {
+ return empty($value);
+ }
+ if (is_array($value['_choices'])){
+ return count($value['_choices']) > 0;
+ }
+ } else { // we do not have 'allow other'
+ return count($value) > .0;
+ }
+ }
+
+ throw \LogicException("This case is not expected.");
}
/**
|
take into account the different type of choices in empty value
|
Chill-project_CustomFields
|
train
|
e73dfdc0e25adfed36594b0f32aade294c3b0593
|
diff --git a/taxi/commands.py b/taxi/commands.py
index <HASH>..<HASH> 100644
--- a/taxi/commands.py
+++ b/taxi/commands.py
@@ -431,7 +431,6 @@ class EditCommand(BaseTimesheetCommand):
if auto_fill_days:
t.prefill(auto_fill_days, limit=None)
- t.entries[datetime.date.today()] = []
TimesheetFile(self.options['file']).write(t.entries)
try:
|
Don't erase current date entries when running the edit command
|
liip_taxi
|
train
|
6fcc928d251827dbcc1f9474c753712806238849
|
diff --git a/src/KPhoen/DoctrineStateMachineBehavior/Listener/PersistenceListener.php b/src/KPhoen/DoctrineStateMachineBehavior/Listener/PersistenceListener.php
index <HASH>..<HASH> 100644
--- a/src/KPhoen/DoctrineStateMachineBehavior/Listener/PersistenceListener.php
+++ b/src/KPhoen/DoctrineStateMachineBehavior/Listener/PersistenceListener.php
@@ -43,13 +43,29 @@ class PersistenceListener extends AbstractListener
$entity = $eventArgs->getEntity();
$em = $eventArgs->getEntityManager();
$uow = $em->getUnitOfWork();
- $classMetadata = $em->getClassMetadata(ClassUtils::getClass($entity));
+ $className = ClassUtils::getClass($entity);
+ $classMetadata = $em->getClassMetadata($className);
+ $reflClass = $classMetadata->getReflectionClass();
+ $stateProperty = null;
- if (!$this->isEntitySupported($classMetadata->reflClass)) {
+ if (!$this->isEntitySupported($reflClass)) {
return;
}
- $stateProperty = $this->columnMapping[ClassUtils::getClass($entity)];
+ //find mapping for the entity class
+ if (array_key_exists($className, $this->columnMapping)) {
+ $stateProperty = $this->columnMapping[$className];
+ }
+ else {
+ //check if there is a mapping for a parent class
+ while ($parent = $reflClass->getParentClass()) {
+ $parentClassName = $parent->getName();
+ if (array_key_exists($parentClassName, $this->columnMapping)) {
+ $stateProperty = $this->columnMapping[$parentClassName];
+ break;
+ }
+ }
+ }
// make sure the entity is initialized
$this->injectStateMachine($entity);
|
doctrine inheritance support, by checking mapping for parent classes
|
K-Phoen_DoctrineStateMachineBehavior
|
train
|
eae67da2c771bee54b6b34b63f874c29005612af
|
diff --git a/lib/cms-fortress.rb b/lib/cms-fortress.rb
index <HASH>..<HASH> 100644
--- a/lib/cms-fortress.rb
+++ b/lib/cms-fortress.rb
@@ -3,6 +3,7 @@ require 'devise'
require 'cancan'
require 'aasm'
require 'tinymce-rails'
+require 'tinymce-rails-langs'
require_relative 'comfortable_mexican_sofa/fixture/page'
|
Require tinymce-rails-langs for proper langfile integration
|
melvinsembrano_cms-fortress
|
train
|
3fdf9e5c77cc79587aef3bcc4c4232e7f1f33408
|
diff --git a/CHANGELOG.md b/CHANGELOG.md
index <HASH>..<HASH> 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,6 +1,6 @@
## Master
-No changes yet.
+- [#435][] Fix pressing `C-c` when interactor thread is not started. ([@netzpirat][])
## 1.8.2 - 30 July, 2013
diff --git a/lib/guard.rb b/lib/guard.rb
index <HASH>..<HASH> 100644
--- a/lib/guard.rb
+++ b/lib/guard.rb
@@ -152,7 +152,7 @@ module Guard
if Signal.list.keys.include?('INT')
Signal.trap('INT') do
- if interactor
+ if interactor && interactor.thread
interactor.thread.raise(Interrupt)
else
::Guard.stop
diff --git a/spec/guard_spec.rb b/spec/guard_spec.rb
index <HASH>..<HASH> 100644
--- a/spec/guard_spec.rb
+++ b/spec/guard_spec.rb
@@ -197,7 +197,7 @@ describe Guard do
context 'with an interactor' do
let(:interactor) { double('interactor', :thread => double('thread')) }
- before { ::Guard.should_receive(:interactor).twice.and_return interactor }
+ before { allow(Guard).to receive(:interactor).and_return(interactor) }
it 'delegates to the Pry thread' do
interactor.thread.should_receive(:raise).with Interrupt
|
Fix pressing `C-c` when interactor thread is not started. (Fixes #<I>)
|
guard_guard
|
train
|
077655d9b6c2e9c2539037d8ab4d01814d6f5b95
|
diff --git a/lib/auxly/_modu.py b/lib/auxly/_modu.py
index <HASH>..<HASH> 100644
--- a/lib/auxly/_modu.py
+++ b/lib/auxly/_modu.py
@@ -60,11 +60,6 @@ def trycatch(*args, **kwargs):
- rethrow (str) [kwargs] - If true, exception will be re-thrown.
**Examples**:
- ::
-
- trycatch(myfunc)(myarg1, myarg2, kwarg=mykwarg)
- trycatch(myfunc, oncatch=mycatchfunc)(myarg1, myarg2, kwarg=mykwarg)
- trycatch(myfunc, rethrow=True)(myarg1, myarg2, kwarg=mykwarg)
"""
rethrow = kwargs.get('rethrow', False)
oncatch = kwargs.get('oncatch', None)
@@ -92,10 +87,6 @@ def callstop(*args, **kwargs):
- func (func) - Function to call. Only available when used as a function.
**Examples**:
- ::
-
- call = callstop(myfunc, limit=3)
- call(myarg1, myarg2)
"""
limit = kwargs.get('limit', 1)
def decor(func):
|
Attempt to fix docs.
|
jeffrimko_Auxly
|
train
|
b43e9192b313176602a8b9dc733f092260c8b301
|
diff --git a/aws-sdk-core/lib/seahorse/client/http/response.rb b/aws-sdk-core/lib/seahorse/client/http/response.rb
index <HASH>..<HASH> 100644
--- a/aws-sdk-core/lib/seahorse/client/http/response.rb
+++ b/aws-sdk-core/lib/seahorse/client/http/response.rb
@@ -12,6 +12,8 @@ module Seahorse
@body = options[:body] || StringIO.new
@listeners = Hash.new { |h,k| h[k] = [] }
@complete = false
+ @done = nil
+ @error = nil
end
# @return [Integer] Returns `0` if the request failed to generate
|
Initializing a few instance variable before use to squelch warnings.
Closes <URL>
|
aws_aws-sdk-ruby
|
train
|
7f593d9e90f12d4827ba7622a44e4c123b05bb31
|
diff --git a/Lib/fontParts/nonelab/image.py b/Lib/fontParts/nonelab/image.py
index <HASH>..<HASH> 100644
--- a/Lib/fontParts/nonelab/image.py
+++ b/Lib/fontParts/nonelab/image.py
@@ -51,6 +51,8 @@ class RImage(RBaseObject, BaseImage):
def _set_data(self, value):
from ufoLib.validators import pngValidator
+ if not isinstance(value, bytes):
+ raise FontPartsError("The image data provided is not valid.")
if not pngValidator(data=value):
raise FontPartsError("The image must be in PNG format.")
if self.font is None:
|
Don't assume that the incoming data is the right type.
|
robotools_fontParts
|
train
|
5f8483e648c33647166b45bb3a11c028e16492fe
|
diff --git a/netjsonconfig/backends/openwrt/converters.py b/netjsonconfig/backends/openwrt/converters.py
index <HASH>..<HASH> 100644
--- a/netjsonconfig/backends/openwrt/converters.py
+++ b/netjsonconfig/backends/openwrt/converters.py
@@ -215,8 +215,9 @@ class Interfaces(BaseConverter):
# to these physical names
interface['ifname'] = 'br-{ifname}'.format(**interface)
# do not repeat bridge attributes (they have already been processed)
- del interface['type']
- del interface['bridge_members']
+ for attr in ['type', 'bridge_members', 'stp', 'gateway']:
+ if attr in interface:
+ del interface[attr]
elif interface['type'] != 'bridge':
del interface['type']
return interface
|
[openwrt] Fixed repeated bridge gateway case
Bug inadvertently introduced in 4f8d<I>
|
openwisp_netjsonconfig
|
train
|
2c11a2a3a4a9fa3450866e9410d5b21c76277111
|
diff --git a/skyfield/tests/test_vs_novas.py b/skyfield/tests/test_vs_novas.py
index <HASH>..<HASH> 100644
--- a/skyfield/tests/test_vs_novas.py
+++ b/skyfield/tests/test_vs_novas.py
@@ -272,7 +272,7 @@ def test_equation_of_the_equinoxes_complimentary_terms(jd_float_or_vector):
def test_frame_tie():
xyz = array([1.1, 1.2, 1.3])
- epsilon = 0.0 # perfect
+ epsilon = 1e-15 # but can be 0.0 when running outside of tox!
eq(c.frame_tie(xyz, 0), xyz.dot(framelib.ICRS_to_J2000), epsilon)
eq(c.frame_tie(xyz, -1), xyz.dot(framelib.J2000_to_ICRS), epsilon)
|
Fix a test epsilon that only breaks under tox
Why would it only break under tox? Floating-point is mysterious.
|
skyfielders_python-skyfield
|
train
|
053485c396da55b6424ad82d9b6e6075d15c507e
|
diff --git a/app/src/main/java/com/orhanobut/waspsample/MyService.java b/app/src/main/java/com/orhanobut/waspsample/MyService.java
index <HASH>..<HASH> 100644
--- a/app/src/main/java/com/orhanobut/waspsample/MyService.java
+++ b/app/src/main/java/com/orhanobut/waspsample/MyService.java
@@ -49,7 +49,7 @@ public interface MyService {
CallBack<Ip> callBack
);
- // @RetryPolicy(initialTimeout = 1)
+ // @RetryPolicy(timeout = 1)
@PUT("/put")
void putFooMap(
@BodyMap Map bodyMap,
diff --git a/app/src/main/java/com/orhanobut/waspsample/WaspApplication.java b/app/src/main/java/com/orhanobut/waspsample/WaspApplication.java
index <HASH>..<HASH> 100644
--- a/app/src/main/java/com/orhanobut/waspsample/WaspApplication.java
+++ b/app/src/main/java/com/orhanobut/waspsample/WaspApplication.java
@@ -43,6 +43,24 @@ public class WaspApplication extends Application {
};
RequestInterceptor interceptor1 = new SimpleInterceptor() {
+
+ @Override
+ public void onHeadersAdded(Map<String, String> headers) {
+ super.onHeadersAdded(headers);
+ headers.put("key","value");
+ }
+
+ @Override
+ public void onQueryParamsAdded(Map<String, Object> params) {
+ super.onQueryParamsAdded(params);
+ params.put("name","something");
+ }
+
+ @Override
+ public WaspRetryPolicy getRetryPolicy() {
+ return new WaspRetryPolicy(45000, 3, 1.5f);
+ }
+
@Override
public AuthToken getAuthToken() {
return new AuthToken("asdfad", true);
diff --git a/wasp/src/main/java/com/orhanobut/wasp/MethodInfo.java b/wasp/src/main/java/com/orhanobut/wasp/MethodInfo.java
index <HASH>..<HASH> 100644
--- a/wasp/src/main/java/com/orhanobut/wasp/MethodInfo.java
+++ b/wasp/src/main/java/com/orhanobut/wasp/MethodInfo.java
@@ -81,7 +81,7 @@ final class MethodInfo {
if (annotationType == RetryPolicy.class) {
RetryPolicy policy = (RetryPolicy) annotation;
retryPolicy = new WaspRetryPolicy(
- policy.initialTimeout(), policy.maxNumRetries(), policy.backoffMultiplier()
+ policy.timeout(), policy.maxNumRetries(), policy.backoffMultiplier()
);
continue;
}
diff --git a/wasp/src/main/java/com/orhanobut/wasp/http/RetryPolicy.java b/wasp/src/main/java/com/orhanobut/wasp/http/RetryPolicy.java
index <HASH>..<HASH> 100644
--- a/wasp/src/main/java/com/orhanobut/wasp/http/RetryPolicy.java
+++ b/wasp/src/main/java/com/orhanobut/wasp/http/RetryPolicy.java
@@ -16,7 +16,7 @@ import static java.lang.annotation.RetentionPolicy.RUNTIME;
@Target(METHOD)
@Retention(RUNTIME)
public @interface RetryPolicy {
- int initialTimeout() default WaspRetryPolicy.DEFAULT_TIMEOUT_MS;
+ int timeout() default WaspRetryPolicy.DEFAULT_TIMEOUT_MS;
int maxNumRetries() default WaspRetryPolicy.DEFAULT_MAX_RETRIES;
|
RetryPolicy initialTimeout changed to timeout
|
orhanobut_wasp
|
train
|
56621e55118d991e60e34fc4aff57fb7d6a36077
|
diff --git a/liveandletdie/__init__.py b/liveandletdie/__init__.py
index <HASH>..<HASH> 100644
--- a/liveandletdie/__init__.py
+++ b/liveandletdie/__init__.py
@@ -259,14 +259,12 @@ class Base(object):
exitcode = self.process.wait()
raise LiveAndLetDieError(
'{0} server {1} didn\'t start in specified timeout {2} '
- 'seconds!\ncommand: {3}\nexit status: {4}\n'
- 'Captured stderr:\n{5}'.format(
+ 'seconds!\ncommand: {3}\nexit status: {4}\n'.format(
self.__class__.__name__,
self.check_url,
self.timeout,
' '.join(self.create_command()),
- exitcode,
- self.process.communicate()[1]
+ exitcode
)
)
sleeped = _get_total_seconds(datetime.now() - t)
@@ -288,7 +286,7 @@ class Base(object):
"""
pid = port_in_use(self.port, kill_port)
-
+
if pid:
raise LiveAndLetDieError(
'Port {0} is already being used by process {1}!'
@@ -297,15 +295,15 @@ class Base(object):
host = str(self.host)
if re.match(_VALID_HOST_PATTERN, host):
- if self.suppress_output:
- self.process = subprocess.Popen(self.create_command(),
- stdout=subprocess.PIPE,
- stderr=subprocess.PIPE,
- preexec_fn=os.setsid)
- else:
- self.process = subprocess.Popen(self.create_command(),
- stderr=subprocess.PIPE,
- preexec_fn=os.setsid)
+ with open(os.devnull, "w") as devnull:
+ if self.suppress_output:
+ self.process = subprocess.Popen(self.create_command(),
+ stderr=devnull,
+ stdout=devnull,
+ preexec_fn=os.setsid)
+ else:
+ self.process = subprocess.Popen(self.create_command(),
+ preexec_fn=os.setsid)
_log(self.logging, 'Starting process PID: {0}'
.format(self.process.pid))
|
Fixed a bug when app process hung when process.PIPE buffer was full.
|
authomatic_liveandletdie
|
train
|
1fc89660102d9c04a00922494fcff4370432a745
|
diff --git a/arquillian-portal-liferay-extension/src/main/java/org/arquillian/liferay/portal/servlet/PortalURLServlet.java b/arquillian-portal-liferay-extension/src/main/java/org/arquillian/liferay/portal/servlet/PortalURLServlet.java
index <HASH>..<HASH> 100644
--- a/arquillian-portal-liferay-extension/src/main/java/org/arquillian/liferay/portal/servlet/PortalURLServlet.java
+++ b/arquillian-portal-liferay-extension/src/main/java/org/arquillian/liferay/portal/servlet/PortalURLServlet.java
@@ -33,6 +33,8 @@ import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
+import java.util.logging.Level;
+import java.util.logging.Logger;
import javax.portlet.PortletPreferences;
@@ -73,7 +75,9 @@ public class PortalURLServlet extends HttpServlet {
layout.getPlid(), new ServiceContext());
}
catch (PortalException e) {
- e.printStackTrace();
+ _logger.log(
+ Level.WARNING,
+ "Error trying to delete layout " + layout.getPlid(), e);
}
}
}
@@ -141,7 +145,7 @@ public class PortalURLServlet extends HttpServlet {
response.sendRedirect("/"+uuid.toString());
}
catch (PortalException e) {
- e.printStackTrace(out);
+ _logger.log(Level.SEVERE, e.getMessage(), e);
}
}
@@ -150,6 +154,9 @@ public class PortalURLServlet extends HttpServlet {
//There are not init actions for this server
}
+ private static final Logger _logger = Logger.getLogger(
+ PortalURLServlet.class.getName());
+
private final transient CompanyLocalService _companyLocalService;
private final transient GroupLocalService _groupLocalService;
private final transient LayoutLocalService _layoutLocalService;
|
[arquillian/arquillian-extension-liferay#<I>] Log Exception
|
arquillian_arquillian-extension-liferay
|
train
|
aef36fa8445c524886203a4be61e16c1c5e92fe4
|
diff --git a/lib/CORL/provisioner/puppetnode.rb b/lib/CORL/provisioner/puppetnode.rb
index <HASH>..<HASH> 100644
--- a/lib/CORL/provisioner/puppetnode.rb
+++ b/lib/CORL/provisioner/puppetnode.rb
@@ -103,8 +103,10 @@ class Puppetnode < Nucleon.plugin_class(:CORL, :provisioner)
unless profiles.empty?
modulepath = profiles.collect do |profile|
- profile_directory = File.join(network.directory, locations[:puppet_module][profile.to_sym])
- File.directory?(profile_directory) ? profile_directory : nil
+ profile_path = locations[:puppet_module][profile.to_sym]
+ profile_directory = nil
+ profile_directory = File.join(network.directory, profile_path) if profile_path
+ profile_directory && File.directory?(profile_directory) ? profile_directory : nil
end.compact
end
|
Fixing path access issue in the Puppet initialization of the puppetnode provisioner provider.
|
coralnexus_corl
|
train
|
f204c9d549d97a39c6ddac49f855834b0bf541d1
|
diff --git a/test/image_test.rb b/test/image_test.rb
index <HASH>..<HASH> 100755
--- a/test/image_test.rb
+++ b/test/image_test.rb
@@ -141,15 +141,6 @@ class ImageTest < Test::Unit::TestCase
assert_equal('', image["EXIF:ExifVersion"])
image.destroy!
end
-
- # The test here isn't really to check to see if
- # the auto-orient function of ImageMagick works,
- # but to make sure we can send dashed commands.
- def test_auto_rotate
- image = Image.from_file(EXIF_IMAGE_PATH)
- image.auto_orient
- image.destroy!
- end
def test_original_at
image = Image.from_file(EXIF_IMAGE_PATH)
|
This test is a duplicate of what's in command_builder_test
so its not needed. My fault!
|
minimagick_minimagick
|
train
|
beb277fd27acdc2bbd1b2cbfd74fbd96a5e017cb
|
diff --git a/SurveyorCore/src/main/java/org/wwarn/surveyor/client/util/AsyncCallbackWithTimeout.java b/SurveyorCore/src/main/java/org/wwarn/surveyor/client/util/AsyncCallbackWithTimeout.java
index <HASH>..<HASH> 100644
--- a/SurveyorCore/src/main/java/org/wwarn/surveyor/client/util/AsyncCallbackWithTimeout.java
+++ b/SurveyorCore/src/main/java/org/wwarn/surveyor/client/util/AsyncCallbackWithTimeout.java
@@ -58,7 +58,7 @@ public abstract class AsyncCallbackWithTimeout<T> implements AsyncCallback<T> {
public static Timestamp latestServerCallTimeStamps = null;
protected Timestamp timeSend= null;
private static final String TIMEOUT_ERROR = "An action timed out. Please try refreshing your browser.";
- private static final int DEFAULT_TIMEOUT = 120000; // 2 minutes
+ private static final int DEFAULT_TIMEOUT = 40000; // 40 seconds
private boolean hasTimedOut = false;
|
Moving to a more aggressive time out, as people don't often wait 2 minutes, usually less than <I> seconds
|
WorldwideAntimalarialResistanceNetwork_WWARN-Maps-Surveyor
|
train
|
daaa03d9128f7a4b6225546b8a6160904587a0d0
|
diff --git a/v2/oapi/oapi.gen.go b/v2/oapi/oapi.gen.go
index <HASH>..<HASH> 100644
--- a/v2/oapi/oapi.gen.go
+++ b/v2/oapi/oapi.gen.go
@@ -153,6 +153,15 @@ const (
EnumComponentUsageReplica EnumComponentUsage = "replica"
)
+// Defines values for EnumIntegrationTypes.
+const (
+ EnumIntegrationTypesDatasource EnumIntegrationTypes = "datasource"
+
+ EnumIntegrationTypesMetrics EnumIntegrationTypes = "metrics"
+
+ EnumIntegrationTypesReadReplica EnumIntegrationTypes = "read_replica"
+)
+
// Defines values for EnumKafkaAclPermissions.
const (
EnumKafkaAclPermissionsAdmin EnumKafkaAclPermissions = "admin"
@@ -1525,6 +1534,9 @@ type EnumComponentRoute string
// EnumComponentUsage defines model for enum-component-usage.
type EnumComponentUsage string
+// EnumIntegrationTypes defines model for enum-integration-types.
+type EnumIntegrationTypes string
+
// EnumKafkaAclPermissions defines model for enum-kafka-acl-permissions.
type EnumKafkaAclPermissions string
@@ -2295,17 +2307,14 @@ type CreateAntiAffinityGroupJSONBody struct {
// CreateDbaasIntegrationJSONBody defines parameters for CreateDbaasIntegration.
type CreateDbaasIntegrationJSONBody struct {
- // A destination service
- DestService string `json:"dest-service"`
+ DestService DbaasServiceName `json:"dest-service"`
// Integration type
IntegrationType string `json:"integration-type"`
// Integration settings
- Settings *map[string]interface{} `json:"settings,omitempty"`
-
- // A source service
- SourceService string `json:"source-service"`
+ Settings *map[string]interface{} `json:"settings,omitempty"`
+ SourceService DbaasServiceName `json:"source-service"`
}
// UpdateDbaasIntegrationJSONBody defines parameters for UpdateDbaasIntegration.
@@ -2325,6 +2334,16 @@ type CreateDbaasServiceKafkaJSONBody struct {
Sasl *bool `json:"sasl,omitempty"`
} `json:"authentication-methods,omitempty"`
+ // Service integrations to enable for the service. Some integration types affect how a service is created and they must be provided as part of the creation call instead of being defined later.
+ Integrations *[]struct {
+ DestService *DbaasServiceName `json:"dest-service,omitempty"`
+
+ // Integration settings
+ Settings *map[string]interface{} `json:"settings,omitempty"`
+ SourceService *DbaasServiceName `json:"source-service,omitempty"`
+ Type EnumIntegrationTypes `json:"type"`
+ } `json:"integrations,omitempty"`
+
// Allow incoming connections from CIDR address block, e.g. '10.20.0.0/16'
IpFilter *[]string `json:"ip-filter,omitempty"`
@@ -2444,6 +2463,16 @@ type CreateDbaasServiceMysqlJSONBody struct {
BinlogRetentionPeriod *int64 `json:"binlog-retention-period,omitempty"`
ForkFromService *DbaasServiceName `json:"fork-from-service,omitempty"`
+ // Service integrations to enable for the service. Some integration types affect how a service is created and they must be provided as part of the creation call instead of being defined later.
+ Integrations *[]struct {
+ DestService *DbaasServiceName `json:"dest-service,omitempty"`
+
+ // Integration settings
+ Settings *map[string]interface{} `json:"settings,omitempty"`
+ SourceService *DbaasServiceName `json:"source-service,omitempty"`
+ Type EnumIntegrationTypes `json:"type"`
+ } `json:"integrations,omitempty"`
+
// Allow incoming connections from CIDR address block, e.g. '10.20.0.0/16'
IpFilter *[]string `json:"ip-filter,omitempty"`
@@ -2535,6 +2564,16 @@ type CreateDbaasServicePgJSONBody struct {
} `json:"backup-schedule,omitempty"`
ForkFromService *DbaasServiceName `json:"fork-from-service,omitempty"`
+ // Service integrations to enable for the service. Some integration types affect how a service is created and they must be provided as part of the creation call instead of being defined later.
+ Integrations *[]struct {
+ DestService *DbaasServiceName `json:"dest-service,omitempty"`
+
+ // Integration settings
+ Settings *map[string]interface{} `json:"settings,omitempty"`
+ SourceService *DbaasServiceName `json:"source-service,omitempty"`
+ Type EnumIntegrationTypes `json:"type"`
+ } `json:"integrations,omitempty"`
+
// Allow incoming connections from CIDR address block, e.g. '10.20.0.0/16'
IpFilter *[]string `json:"ip-filter,omitempty"`
@@ -2645,6 +2684,16 @@ type UpdateDbaasServicePgJSONBodyMaintenanceDow string
type CreateDbaasServiceRedisJSONBody struct {
ForkFromService *DbaasServiceName `json:"fork-from-service,omitempty"`
+ // Service integrations to enable for the service. Some integration types affect how a service is created and they must be provided as part of the creation call instead of being defined later.
+ Integrations *[]struct {
+ DestService *DbaasServiceName `json:"dest-service,omitempty"`
+
+ // Integration settings
+ Settings *map[string]interface{} `json:"settings,omitempty"`
+ SourceService *DbaasServiceName `json:"source-service,omitempty"`
+ Type EnumIntegrationTypes `json:"type"`
+ } `json:"integrations,omitempty"`
+
// Allow incoming connections from CIDR address block, e.g. '10.20.0.0/16'
IpFilter *[]string `json:"ip-filter,omitempty"`
|
v2: refresh code generated from public API spec
|
exoscale_egoscale
|
train
|
862285e51dc27141132430e770e114ded52d8b65
|
diff --git a/lib/wine_bouncer/oauth2.rb b/lib/wine_bouncer/oauth2.rb
index <HASH>..<HASH> 100644
--- a/lib/wine_bouncer/oauth2.rb
+++ b/lib/wine_bouncer/oauth2.rb
@@ -1,6 +1,7 @@
module WineBouncer
class OAuth2 < Grape::Middleware::Base
+ include Doorkeeper::Helpers::Controller
###
# returns the api context
###
@@ -22,18 +23,11 @@ module WineBouncer
###
# Returns the request context.
###
- def doorkeeper_request
+ def request
@_doorkeeper_request
end
###
- # Authenticates from a request and returns a valid or invalid token.
- ###
- def doorkeeper_token
- @_doorkeeper_token ||= Doorkeeper.authenticate(doorkeeper_request,Doorkeeper.configuration.access_token_methods)
- end
-
- ###
# Returns true if the doorkeeper token is valid, false otherwise.
###
def valid_doorkeeper_token?(*scopes)
|
Using more native methods from doorkeeper itself
|
antek-drzewiecki_wine_bouncer
|
train
|
48e713852368430ab19f5eb88c4967d3c8d9f008
|
diff --git a/tests/export/hazard_test.py b/tests/export/hazard_test.py
index <HASH>..<HASH> 100644
--- a/tests/export/hazard_test.py
+++ b/tests/export/hazard_test.py
@@ -19,6 +19,9 @@ import shutil
import tempfile
import unittest
+import nrml
+
+from lxml import etree
from nose.plugins.attrib import attr
from openquake.db import models
@@ -28,6 +31,15 @@ from openquake.export import hazard
from tests.utils import helpers
+def _number_of(elem_name, tree):
+ """
+ Given an element name (including the namespaces prefix, if applicable),
+ return the number of occurrences of the element in a given XML document.
+ """
+ expr = '//%s' % elem_name
+ return len(tree.xpath(expr, namespaces=nrml.PARSE_NS_MAP))
+
+
class HazardCurveExportTestCase(unittest.TestCase):
@attr('slow')
@@ -145,5 +157,9 @@ class EventBasedGMFExportTestCase(unittest.TestCase):
self.assertTrue(os.path.exists(exported_file))
self.assertTrue(os.path.isabs(exported_file))
self.assertTrue(os.path.getsize(exported_file) > 0)
+
+ # Check for the correct number of GMFs in the file:
+ tree = etree.parse(exported_file)
+ self.assertEqual(420, _number_of('nrml:gmf', tree))
finally:
shutil.rmtree(target_dir)
|
tests/export/hazard_test:
Added a test to check for the total number of GMFs in a `complete
logic tree GMF` (since the code which generates the complete lt gmf
is quite a bit more complex than it used to be.
|
gem_oq-engine
|
train
|
afc298c6efbd07b3568b65c55cb9a3886a1c65f6
|
diff --git a/framework/CHANGELOG.md b/framework/CHANGELOG.md
index <HASH>..<HASH> 100644
--- a/framework/CHANGELOG.md
+++ b/framework/CHANGELOG.md
@@ -30,6 +30,7 @@ Yii Framework 2 Change Log
- Bug #12053: `./yii migrate/create` was generating wrong code when using `bigPrimaryKey` (VojtechH, samdark)
- Bug #11907: Fixed `yii\helpers\Console::getScreenSize()` on Windows was giving out width and height swapped (Spell6inder, samdark, cebe)
- Bug #11973: Fixed `yii\helpers\BaseHtml::getAttributeValue()` to work with `items[]` notation correctly (silverfire)
+- Bug #12100: Fixed `yii\filters\HttpCache` was sending an empty Pragma header (sergeymakinen)
- Bug #12107: Fixed REST Serializer to validate input for 'expand' and 'fields' parameter, which crashed on array input (njspok, cebe)
diff --git a/framework/filters/HttpCache.php b/framework/filters/HttpCache.php
index <HASH>..<HASH> 100644
--- a/framework/filters/HttpCache.php
+++ b/framework/filters/HttpCache.php
@@ -193,7 +193,6 @@ class HttpCache extends ActionFilter
}
$headers = Yii::$app->getResponse()->getHeaders();
- $headers->set('Pragma');
if ($this->cacheControlHeader !== null) {
$headers->set('Cache-Control', $this->cacheControlHeader);
diff --git a/tests/framework/filters/HttpCacheTest.php b/tests/framework/filters/HttpCacheTest.php
index <HASH>..<HASH> 100644
--- a/tests/framework/filters/HttpCacheTest.php
+++ b/tests/framework/filters/HttpCacheTest.php
@@ -28,6 +28,18 @@ class HttpCacheTest extends \yiiunit\TestCase
$this->assertTrue($httpCache->beforeAction(null));
}
+ public function testEmptyPragma()
+ {
+ $httpCache = new HttpCache;
+ $httpCache->etagSeed = function($action, $params) {
+ return '';
+ };
+ $httpCache->beforeAction(null);
+ $response = Yii::$app->getResponse();
+ $this->assertFalse($response->getHeaders()->offsetExists('Pragma'));
+ $this->assertFalse($response->getHeaders()->get('Pragma') === '');
+ }
+
/**
* @covers yii\filters\HttpCache::validateCache
*/
|
Fixed HttpCache was sending an empty Pragma header (#<I>) (#<I>)
|
yiisoft_yii2
|
train
|
25bb301d9c392d7c38ac8e6f5b64ed64e7b95022
|
diff --git a/activerecord/test/cases/associations/has_many_associations_test.rb b/activerecord/test/cases/associations/has_many_associations_test.rb
index <HASH>..<HASH> 100644
--- a/activerecord/test/cases/associations/has_many_associations_test.rb
+++ b/activerecord/test/cases/associations/has_many_associations_test.rb
@@ -1178,12 +1178,4 @@ class HasManyAssociationsTest < ActiveRecord::TestCase
client = firm.clients_using_primary_key.create!(:name => 'test')
assert_equal firm.name, client.firm_name
end
-
- def test_normal_method_call_in_association_proxy
- assert_equal 'Welcome to the weblog', Comment.all.map { |comment| comment.post }.sort_by(&:id).first.title
- end
-
- def test_instance_eval_in_association_proxy
- assert_equal 'Welcome to the weblog', Comment.all.map { |comment| comment.post }.sort_by(&:id).first.instance_eval{title}
- end
end
|
Forgot to revert tests from that last commit
|
rails_rails
|
train
|
65b456695e5c1d591fe9c1c5cee18f2bf40e9a05
|
diff --git a/ifcfg/__init__.py b/ifcfg/__init__.py
index <HASH>..<HASH> 100644
--- a/ifcfg/__init__.py
+++ b/ifcfg/__init__.py
@@ -27,9 +27,9 @@ def get_parser(**kw):
The ifconfig (stdout) to pass to the parser (used for testing).
"""
- parser = kw.get('parser', None)
+ Parser = kw.get('parser', None)
ifconfig = kw.get('ifconfig', None)
- if not parser:
+ if not Parser:
distro = kw.get('distro', platform.system())
full_kernel = kw.get('kernel', platform.uname()[2])
split_kernel = full_kernel.split('.')[0:2]
@@ -45,21 +45,20 @@ def get_parser(**kw):
from .parser import Linux2Parser as LinuxParser
else:
from .parser import LinuxParser
- parser = LinuxParser(ifconfig=ifconfig)
+ Parser = LinuxParser
elif distro in ['Darwin', 'MacOSX']:
from .parser import MacOSXParser
- parser = MacOSXParser(ifconfig=ifconfig)
+ Parser = MacOSXParser
else:
raise exc.IfcfgParserError("Unknown distro type '%s'." % distro)
Log.debug("Distro detected as '%s'" % distro)
- Log.debug("Using '%s'" % parser)
- if not os.path.exists(parser.get_command()[0]):
+ Log.debug("Using '%s'" % Parser)
+ if not os.path.exists(Parser.get_command()[0]):
Log.debug("Could not find 'ifconfig' cmd, falling back to 'ip' cmd")
from .parser import UnixIPParser
- parser = UnixIPParser(ifconfig=ifconfig)
- else:
- parser = parser(ifconfig=ifconfig)
- return parser
+ Parser = UnixIPParser
+
+ return Parser(ifconfig=ifconfig)
def interfaces():
"""
diff --git a/ifcfg/parser.py b/ifcfg/parser.py
index <HASH>..<HASH> 100644
--- a/ifcfg/parser.py
+++ b/ifcfg/parser.py
@@ -16,7 +16,8 @@ class IfcfgParser(object):
self.encoding = kw.get('encoding', 'latin1')
self.parse(self.ifconfig_data)
- def get_command(self):
+ @classmethod
+ def get_command(cls):
ifconfig_cmd = 'ifconfig'
for path in ['/sbin','/usr/sbin','/bin','/usr/bin']:
if os.path.exists(os.path.join(path, ifconfig_cmd)):
@@ -24,7 +25,8 @@ class IfcfgParser(object):
break
return [ifconfig_cmd, '-a']
- def get_patterns(self):
+ @classmethod
+ def get_patterns(cls):
return [
'(?P<device>^[a-zA-Z0-9]+): flags=(?P<flags>.*) mtu (?P<mtu>.*)',
'.*(inet )(?P<inet>[^\s]*).*',
@@ -144,8 +146,9 @@ class UnixParser(IfcfgParser):
class LinuxParser(UnixParser):
- def get_patterns(self):
- return super(LinuxParser, self).get_patterns() + [
+ @classmethod
+ def get_patterns(cls):
+ return super(LinuxParser, cls).get_patterns() + [
'(?P<device>^[a-zA-Z0-9:]+)(.*)Link encap:(.*).*',
'(.*)Link encap:(.*)(HWaddr )(?P<ether>[^\s]*).*',
'.*(inet addr:)(?P<inet>[^\s]*).*',
@@ -170,7 +173,9 @@ class UnixIPParser(IfcfgParser):
"""
Because ifconfig is getting deprecated, we can use ip address instead
"""
- def get_command(self):
+
+ @classmethod
+ def get_command(cls):
ifconfig_cmd = 'ip'
for path in ['/sbin','/usr/sbin','/bin','/usr/bin']:
if os.path.exists(os.path.join(path, ifconfig_cmd)):
@@ -178,7 +183,8 @@ class UnixIPParser(IfcfgParser):
break
return [ifconfig_cmd, 'address', 'show']
- def get_patterns(self):
+ @classmethod
+ def get_patterns(cls):
return [
'\s*[0-9]+:\s+(?P<device>[a-zA-Z0-9]+):.*mtu (?P<mtu>.*)',
'.*(inet )(?P<inet>[^/]+).*',
@@ -193,9 +199,10 @@ class UnixIPParser(IfcfgParser):
class MacOSXParser(UnixParser):
-
- def get_patterns(self):
- return super(MacOSXParser, self).get_patterns() + [
+
+ @classmethod
+ def get_patterns(cls):
+ return super(MacOSXParser, cls).get_patterns() + [
'.*(status: )(?P<status>[^\s]*).*',
'.*(media: )(?P<media>.*)',
]
|
Refactor get_command and get_patterns as static class methods
|
ftao_python-ifcfg
|
train
|
c18c685c05975b3266a44b2e777cb9bffdaf4a0e
|
diff --git a/dev/com.ibm.ws.transport.http/src/com/ibm/ws/http/channel/h2internal/H2StreamProcessor.java b/dev/com.ibm.ws.transport.http/src/com/ibm/ws/http/channel/h2internal/H2StreamProcessor.java
index <HASH>..<HASH> 100644
--- a/dev/com.ibm.ws.transport.http/src/com/ibm/ws/http/channel/h2internal/H2StreamProcessor.java
+++ b/dev/com.ibm.ws.transport.http/src/com/ibm/ws/http/channel/h2internal/H2StreamProcessor.java
@@ -1735,9 +1735,9 @@ public class H2StreamProcessor {
}
if (currentFrame.isWriteFrame() && currentFrame.getInitialized()) {
WsByteBuffer writeFrameBuffer = null;
+ WsByteBuffer[] writeFrameBuffers = null;
try {
if (currentFrame.getFrameType() == FrameTypes.DATA) {
- WsByteBuffer[] writeFrameBuffers = null;
FrameData data = (FrameData) currentFrame;
boolean timedOut = false;
@@ -1785,11 +1785,28 @@ public class H2StreamProcessor {
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
Tr.debug(tc, "writeFrameSync caught an IOException: " + e);
}
+
} catch (InterruptedException e) {
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
Tr.debug(tc, "writeFrameSync interrupted: " + e);
}
+ } finally {
+ // release buffer used to synchronously write the frame
+ if (writeFrameBuffer != null) {
+ writeFrameBuffer.release();
+ } else if (writeFrameBuffers != null) {
+ for (int i = 0; i < writeFrameBuffers.length; i++) {
+ if (writeFrameBuffers[i] != null) {
+ // buffer at [1] is allocated by old channel code, it will clean it up
+ // later move this logic to a frame cleanup method that can take care of releasing
+ if (i != 1) {
+ writeFrameBuffers[i].release();
+ }
+ }
+ }
+ }
}
+
} else {
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
Tr.debug(tc, "writeFrameSync internal flow issue - exiting method ");
|
add another place to free a buffer when done writing
|
OpenLiberty_open-liberty
|
train
|
485b4d173e543aa52d93bb8df973101699d2369c
|
diff --git a/sdk/logical/system_view.go b/sdk/logical/system_view.go
index <HASH>..<HASH> 100644
--- a/sdk/logical/system_view.go
+++ b/sdk/logical/system_view.go
@@ -105,6 +105,10 @@ func (d StaticSystemView) Auditor() Auditor {
return noopAuditor{}
}
+func (d StaticSystemView) ForwardGenericRequest(ctx context.Context, req *Request) (*Response, error) {
+ return nil, errors.New("ForwardGenericRequest is not implemented in StaticSystemView")
+}
+
func (d StaticSystemView) DefaultLeaseTTL() time.Duration {
return d.DefaultLeaseTTLVal
}
|
core: add ForwardGenericRequest to StaticSystemView to satisfy ExtendedSystemView (#<I>)
|
hashicorp_vault
|
train
|
f7d841413346d617ade730dbd0904c5ec5d1f6e2
|
diff --git a/translator/src/main/java/com/google/devtools/j2objc/util/ClassFile.java b/translator/src/main/java/com/google/devtools/j2objc/util/ClassFile.java
index <HASH>..<HASH> 100644
--- a/translator/src/main/java/com/google/devtools/j2objc/util/ClassFile.java
+++ b/translator/src/main/java/com/google/devtools/j2objc/util/ClassFile.java
@@ -38,6 +38,7 @@ import com.strobel.decompiler.languages.java.ast.ParameterDeclaration;
import com.strobel.decompiler.languages.java.ast.TypeDeclaration;
import java.io.IOException;
import java.util.jar.JarFile;
+import java.util.stream.Collectors;
/**
* JVM class file model, which uses a Procyon TypeDefinition as a delegate.
@@ -166,24 +167,22 @@ public class ClassFile {
private String signature(MethodDeclaration method) {
StringBuilder sb = new StringBuilder();
- signature(method.getParameters(), sb);
+ sb.append(signature(method.getParameters()));
sb.append(signature(method.getReturnType()));
return sb.toString();
}
private String signature(ConstructorDeclaration cons) {
StringBuilder sb = new StringBuilder();
- signature(cons.getParameters(), sb);
+ sb.append(signature(cons.getParameters()));
sb.append('V');
return sb.toString();
}
- private void signature(AstNodeCollection<ParameterDeclaration> parameters, StringBuilder sb) {
- sb.append('(');
- for (ParameterDeclaration param : parameters) {
- sb.append(signature(param.getType()));
- }
- sb.append(')');
+ private String signature(AstNodeCollection<ParameterDeclaration> parameters) {
+ return parameters.stream()
+ .map(p -> signature(p.getType()))
+ .collect(Collectors.joining("", "(", ")"));
}
private String signature(AstType type) {
|
Updated string builder method to lambda expression.
|
google_j2objc
|
train
|
13ea4b9a389ebc2fff6595b561f6e84405e8da9e
|
diff --git a/netpyne/sim/save.py b/netpyne/sim/save.py
index <HASH>..<HASH> 100644
--- a/netpyne/sim/save.py
+++ b/netpyne/sim/save.py
@@ -302,20 +302,18 @@ def compactConnFormat():
#------------------------------------------------------------------------------
# Gathers data in master and saves it mid run
#------------------------------------------------------------------------------
-def intervalSave(t, gatherLFP=True):
+def intervalSave(simTime, gatherLFP=True):
"""
- Function for/to <short description of `netpyne.sim.save.intervalSave`>
+ Function to save data at a specific time point in the simulation
Parameters
----------
- t : <type>
- <Short description of t>
+ simTime : number
+ The time at which to save the data
**Default:** *required*
-
"""
-
from .. import sim
from ..specs import Dict
import pickle, os
@@ -440,7 +438,7 @@ def intervalSave(t, gatherLFP=True):
simDataVecs = simDataVecs + ['allWeights']
if sim.rank == 0: # simData
- print(' Saving data at intervals... {:0.0f} ms'.format(t))
+ print(' Saving data at intervals... {:0.0f} ms'.format(simTime))
sim.allSimData = Dict()
for k in list(gather[0]['simData'].keys()): # initialize all keys of allSimData dict
if gatherLFP and k == 'LFP':
@@ -492,7 +490,7 @@ def intervalSave(t, gatherLFP=True):
item.clear()
del item
- name = os.path.join(targetFolder, 'interval_{:0.0f}.pkl'.format(t))
+ name = os.path.join(targetFolder, 'interval_{:0.0f}.pkl'.format(simTime))
dataSave = {}
net = {}
|
updated intervalSave to work with improved runSimWithIntervalFunc
|
Neurosim-lab_netpyne
|
train
|
1a9f26593cfc2baf6bc6530e10c1c975adb89eea
|
diff --git a/setup.py b/setup.py
index <HASH>..<HASH> 100644
--- a/setup.py
+++ b/setup.py
@@ -43,4 +43,9 @@ setup(
"sphinx-autodoc-typehints",
],
},
+ entry_points={
+ 'console_scripts': [
+ 'delphi = delphi.cli:main',
+ ],
+ },
)
|
Add entry point for delphi.cli:main
This tells python to install a script called ``delphi`` that can be run from the command line, and will enter through the main function defined in cli.py
|
ml4ai_delphi
|
train
|
f4863f0ef4ef185ff57fff710f1d08dd9f5e6634
|
diff --git a/lib/FileSystemInfo.js b/lib/FileSystemInfo.js
index <HASH>..<HASH> 100644
--- a/lib/FileSystemInfo.js
+++ b/lib/FileSystemInfo.js
@@ -16,10 +16,12 @@ const { join, dirname, relative } = require("./util/fs");
/** @typedef {import("./util/fs").InputFileSystem} InputFileSystem */
const resolveContext = createResolver({
- resolveToContext: true
+ resolveToContext: true,
+ exportsFields: []
});
const resolve = createResolver({
- extensions: [".js", ".json", ".node"]
+ extensions: [".js", ".json", ".node"],
+ conditionNames: ["require"]
});
let FS_ACCURACY = 2000;
@@ -389,8 +391,10 @@ class FileSystemInfo {
if (
err.code === "ENOENT" ||
err.code === "UNDECLARED_DEPENDENCY"
- )
+ ) {
return callback();
+ }
+ err.message += `\nwhile resolving '${path}' in ${context} to a directory`;
return callback(err);
}
resolveResults.set(key, result);
@@ -425,8 +429,10 @@ class FileSystemInfo {
if (
err.code === "ENOENT" ||
err.code === "UNDECLARED_DEPENDENCY"
- )
+ ) {
return callback();
+ }
+ err.message += `\nwhile resolving '${path}' in ${context} as file`;
return callback(err);
}
resolveResults.set(key, result);
@@ -500,6 +506,7 @@ class FileSystemInfo {
break;
}
case RBDT_FILE_DEPENDENCIES: {
+ // TODO this probably doesn't work correctly with ESM dependencies
/** @type {NodeModule} */
const module = require.cache[path];
if (module && Array.isArray(module.children)) {
|
improve build dependencies resolving for dependencies with exports field
|
webpack_webpack
|
train
|
4a59586c96345e2490602aa3202046b41318fb8d
|
diff --git a/lib/onelogin/ruby-saml/idp_metadata_parser.rb b/lib/onelogin/ruby-saml/idp_metadata_parser.rb
index <HASH>..<HASH> 100644
--- a/lib/onelogin/ruby-saml/idp_metadata_parser.rb
+++ b/lib/onelogin/ruby-saml/idp_metadata_parser.rb
@@ -16,6 +16,11 @@ module OneLogin
attr_reader :document
+ def parse_remote(url, validate_cert = true)
+ idp_metadata = get_idp_metadata(url, validate_cert)
+ parse(idp_metadata)
+ end
+
def parse(idp_metadata)
@document = REXML::Document.new(idp_metadata)
@@ -29,6 +34,29 @@ module OneLogin
private
+ # Retrieve the remote IdP metadata from the URL or a cached copy
+ # # returns a REXML document of the metadata
+ def get_idp_metadata(url, validate_cert)
+ uri = URI.parse(url)
+ if uri.scheme == "http"
+ response = Net::HTTP.get_response(uri)
+ meta_text = response.body
+ elsif uri.scheme == "https"
+ http = Net::HTTP.new(uri.host, uri.port)
+ http.use_ssl = true
+ # Most IdPs will probably use self signed certs
+ if validate_cert
+ http.verify_mode = OpenSSL::SSL::VERIFY_PEER
+ else
+ http.verify_mode = OpenSSL::SSL::VERIFY_NONE
+ end
+ get = Net::HTTP::Get.new(uri.request_uri)
+ response = http.request(get)
+ meta_text = response.body
+ end
+ meta_text
+ end
+
def single_signon_service_url
node = REXML::XPath.first(document, "/md:EntityDescriptor/md:IDPSSODescriptor/md:SingleSignOnService/@Location", { "md" => METADATA })
node.value if node
diff --git a/test/idp_metadata_parser_test.rb b/test/idp_metadata_parser_test.rb
index <HASH>..<HASH> 100644
--- a/test/idp_metadata_parser_test.rb
+++ b/test/idp_metadata_parser_test.rb
@@ -1,7 +1,12 @@
require File.expand_path(File.join(File.dirname(__FILE__), "test_helper"))
+require 'net/http'
class IdpMetadataParserTest < Test::Unit::TestCase
+ class MockResponse
+ attr_accessor :body
+ end
+
context "parsing an IdP descriptor file" do
should "extract settings details from xml" do
idp_metadata_parser = OneLogin::RubySaml::IdpMetadataParser.new
@@ -14,4 +19,35 @@ class IdpMetadataParserTest < Test::Unit::TestCase
end
end
+ context "download and parse IdP descriptor file" do
+ setup do
+ mock_response = MockResponse.new
+ mock_response.body = idp_metadata
+ @url = "https://example.com"
+ uri = URI(@url)
+
+ @http = Net::HTTP.new(uri.host, uri.port)
+ Net::HTTP.expects(:new).returns(@http)
+ @http.expects(:request).returns(mock_response)
+ end
+
+
+ should "extract settings from remote xml" do
+ idp_metadata_parser = OneLogin::RubySaml::IdpMetadataParser.new
+ settings = idp_metadata_parser.parse_remote(@url)
+
+ assert_equal "https://example.hello.com/access/saml/login", settings.idp_sso_target_url
+ assert_equal "F1:3C:6B:80:90:5A:03:0E:6C:91:3E:5D:15:FA:DD:B0:16:45:48:72", settings.idp_cert_fingerprint
+ assert_equal "https://example.hello.com/access/saml/logout", settings.idp_slo_target_url
+ assert_equal OpenSSL::SSL::VERIFY_PEER, @http.verify_mode
+ end
+
+ should "accept self signed certificate if insturcted" do
+ idp_metadata_parser = OneLogin::RubySaml::IdpMetadataParser.new
+ settings = idp_metadata_parser.parse_remote(@url, false)
+
+ assert_equal OpenSSL::SSL::VERIFY_NONE, @http.verify_mode
+ end
+ end
+
end
|
download and parse remote idp server metadata
|
onelogin_ruby-saml
|
train
|
f536c0d635ed0799c9c96288353cc05898c634f6
|
diff --git a/src/Medoo.php b/src/Medoo.php
index <HASH>..<HASH> 100644
--- a/src/Medoo.php
+++ b/src/Medoo.php
@@ -174,6 +174,11 @@ class Medoo
{
$attr[ 'appname' ] = $options[ 'appname' ];
}
+
+ if (isset($options[ 'charset' ]))
+ {
+ $attr[ 'charset' ] = $options[ 'charset' ];
+ }
}
else
{
@@ -187,6 +192,39 @@ class Medoo
{
$attr[ 'APP' ] = $options[ 'appname' ];
}
+
+ $config = [
+ 'ApplicationIntent',
+ 'AttachDBFileName',
+ 'Authentication',
+ 'ColumnEncryption',
+ 'ConnectionPooling',
+ 'Encrypt',
+ 'Failover_Partner',
+ 'KeyStoreAuthentication',
+ 'KeyStorePrincipalId',
+ 'KeyStoreSecret',
+ 'LoginTimeout',
+ 'MultipleActiveResultSets',
+ 'MultiSubnetFailover',
+ 'Scrollable',
+ 'TraceFile',
+ 'TraceOn',
+ 'TransactionIsolation',
+ 'TransparentNetworkIPResolution',
+ 'TrustServerCertificate',
+ 'WSID',
+ ];
+
+ foreach ($config as $value)
+ {
+ $keyname = strtolower(preg_replace(['/([a-z\d])([A-Z])/', '/([^_])([A-Z][a-z])/'], '$1_$2', $value));
+
+ if (isset($options[ $keyname ]))
+ {
+ $attr[ $value ] = $options[ $keyname ];
+ }
+ }
}
// Keep MSSQL QUOTED_IDENTIFIER is ON for standard quoting
|
[feature] Add more connection option support for MSSQL
|
catfan_Medoo
|
train
|
0fb797240e73dcb506fdf6ad34e275039bc91039
|
diff --git a/lib/cursor.js b/lib/cursor.js
index <HASH>..<HASH> 100644
--- a/lib/cursor.js
+++ b/lib/cursor.js
@@ -50,8 +50,8 @@ Cursor.prototype.sort = function(sortQuery) {
/**
* Add the use of a projection
- * @param {Object} projection - MongoDB-style projection. {} means take all fields. Then it's {key1:1, key2:1} to take only key1 and key2
- * {key1: 0, key2: 0} to omit only key1 and key2. Except _id, you can't mix takes and omits
+ * @param {Object} projection - MongoDB-style projection. {} means take all fields. Then it's { key1: 1, key2: 1 } to take only key1 and key2
+ * { key1: 0, key2: 0 } to omit only key1 and key2. Except _id, you can't mix takes and omits
*/
Cursor.prototype.projection = function(projection) {
this._projection = projection;
@@ -85,7 +85,7 @@ Cursor.prototype.project = function (candidates) {
candidates.forEach(function (candidate) {
var toPush = action === 1 ? _.pick(candidate, keys) : _.omit(candidate, keys);
if (keepId) { toPush._id = candidate._id; }
- res.push(candidate);
+ res.push(toPush);
});
return res;
diff --git a/test/cursor.test.js b/test/cursor.test.js
index <HASH>..<HASH> 100644
--- a/test/cursor.test.js
+++ b/test/cursor.test.js
@@ -654,14 +654,21 @@ describe('Cursor', function () {
describe.only('Projections', function () {
+ var doc1, doc2, doc3, doc4, doc0;
+
beforeEach(function (done) {
// We don't know the order in which docs wil be inserted but we ensure correctness by testing both sort orders
- d.insert({ age: 5, name: 'Jo', planet: 'B' }, function (err) {
- d.insert({ age: 57, name: 'Louis', planet: 'R' }, function (err) {
- d.insert({ age: 52, name: 'Grafitti', planet: 'C' }, function (err) {
- d.insert({ age: 23, name: 'LM', planet: 'S' }, function (err) {
- d.insert({ age: 89, planet: 'Earth' }, function (err) {
+ d.insert({ age: 5, name: 'Jo', planet: 'B' }, function (err, _doc0) {
+ doc0 = _doc0;
+ d.insert({ age: 57, name: 'Louis', planet: 'R' }, function (err, _doc1) {
+ doc1 = _doc1;
+ d.insert({ age: 52, name: 'Grafitti', planet: 'C' }, function (err, _doc2) {
+ doc2 = _doc2;
+ d.insert({ age: 23, name: 'LM', planet: 'S' }, function (err, _doc3) {
+ doc3 = _doc3;
+ d.insert({ age: 89, planet: 'Earth' }, function (err, _doc4) {
+ doc4 = _doc4;
return done();
});
});
@@ -672,20 +679,49 @@ describe('Cursor', function () {
it('Takes all results if no projection or empty object given', function (done) {
var cursor = new Cursor(d, {});
+ cursor.sort({ age: 1 }); // For easier finding
cursor.exec(function (err, docs) {
assert.isNull(err);
docs.length.should.equal(5);
+ assert.deepEqual(docs[0], doc0);
+ assert.deepEqual(docs[1], doc3);
+ assert.deepEqual(docs[2], doc2);
+ assert.deepEqual(docs[3], doc1);
+ assert.deepEqual(docs[4], doc4);
cursor.projection({});
cursor.exec(function (err, docs) {
assert.isNull(err);
docs.length.should.equal(5);
+ assert.deepEqual(docs[0], doc0);
+ assert.deepEqual(docs[1], doc3);
+ assert.deepEqual(docs[2], doc2);
+ assert.deepEqual(docs[3], doc1);
+ assert.deepEqual(docs[4], doc4);
done();
});
});
});
+ it('Can take only the expected fields', function (done) {
+ var cursor = new Cursor(d, {});
+ cursor.sort({ age: 1 }); // For easier finding
+ cursor.projection({ age: 1, name: 1 });
+ cursor.exec(function (err, docs) {
+ assert.isNull(err);
+ docs.length.should.equal(5);
+ // Takes the _id by default
+ assert.deepEqual(docs[0], { age: 5, name: 'Jo', _id: doc0._id });
+ assert.deepEqual(docs[1], { age: 23, name: 'LM', _id: doc3._id });
+ assert.deepEqual(docs[2], { age: 52, name: 'Grafitti', _id: doc2._id });
+ assert.deepEqual(docs[3], { age: 57, name: 'Louis', _id: doc1._id });
+ assert.deepEqual(docs[4], { age: 89, _id: doc4._id }); // No problems if one field to take doesn't exist
+
+ done();
+ });
+ });
+
}); // ==== End of 'Projections' ====
});
|
Real test for empty projection and take-type projections
|
louischatriot_nedb
|
train
|
5014e22a4f9701c216c3403a0a63ab9e6124cb6b
|
diff --git a/lib/assets/Asset.js b/lib/assets/Asset.js
index <HASH>..<HASH> 100644
--- a/lib/assets/Asset.js
+++ b/lib/assets/Asset.js
@@ -71,6 +71,10 @@ function Asset(config) {
this._parseTree = config.parseTree;
config.parseTree = undefined;
}
+ if (config.sourceMap) {
+ this._sourceMap = config.sourceMap;
+ config.sourceMap = undefined;
+ }
if (config.url) {
this._url = config.url.trim();
if (!urlEndsWithSlashRegExp.test(this._url)) {
|
Asset constructor: Bypass the sourceMap setter when receiving config.sourceMap.
|
assetgraph_assetgraph
|
train
|
8732a1ea3d118a9008081950af4418aaacb9133a
|
diff --git a/aiobotocore/paginate.py b/aiobotocore/paginate.py
index <HASH>..<HASH> 100644
--- a/aiobotocore/paginate.py
+++ b/aiobotocore/paginate.py
@@ -59,12 +59,14 @@ class AioPageIterator(PageIterator):
self._starting_truncation = 0
self._inject_starting_params(self._current_kwargs)
- @asyncio.coroutine
- def next_page(self):
+ async def __aiter__(self):
+ return self
+
+ async def __anext__(self):
if self._is_stop:
- return None
+ raise StopAsyncIteration
- response = yield from self._make_request(self._current_kwargs)
+ response = await self._make_request(self._current_kwargs)
parsed = self._extract_parsed_response(response)
if self._first_request:
# The first request is handled differently. We could
|
add async for support to pagination
|
aio-libs_aiobotocore
|
train
|
06aa1724e7151a644322a8e065347f4cb2246b75
|
diff --git a/logs.go b/logs.go
index <HASH>..<HASH> 100644
--- a/logs.go
+++ b/logs.go
@@ -12,5 +12,9 @@ var cmdLogs = &Command{
}
func runLogs(cmd *Command, args []string) {
+ if len(args) != 1 {
+ panic("You must supply a job id")
+ }
+
must(Get(os.Stdout, "/apps/"+mustApp()+"/jobs/"+args[0]+"/logs"))
}
|
cli: More descriptive error when job id is left blank on logs command.
|
flynn_flynn
|
train
|
74c4f9813c9bea74ca6b3a147298904e5e52e716
|
diff --git a/xwiki-commons-core/xwiki-commons-job/src/main/java/org/xwiki/job/AbstractJob.java b/xwiki-commons-core/xwiki-commons-job/src/main/java/org/xwiki/job/AbstractJob.java
index <HASH>..<HASH> 100644
--- a/xwiki-commons-core/xwiki-commons-job/src/main/java/org/xwiki/job/AbstractJob.java
+++ b/xwiki-commons-core/xwiki-commons-job/src/main/java/org/xwiki/job/AbstractJob.java
@@ -153,6 +153,8 @@ public abstract class AbstractJob<R extends Request> implements Job
this.status.setState(JobStatus.State.RUNNING);
this.status.startListening();
+
+ this.logger.info("Starting job of type [{}] with identifier [{}]", getType(), getStatus().getRequest().getId());
}
/**
@@ -173,6 +175,9 @@ public abstract class AbstractJob<R extends Request> implements Job
// Indicate when the job ended
this.status.setEndDate(new Date());
+ this.logger.info("Finished job of type [{}] with identifier [{}]", getType(), getStatus().getRequest()
+ .getId());
+
// Stop updating job status (progress, log, etc.)
this.status.stopListening();
|
Add some more log to begin and close job log
|
xwiki_xwiki-commons
|
train
|
e9fad599f8925e24f08e98eff7f4013009e78932
|
diff --git a/src/core/Singleton.php b/src/core/Singleton.php
index <HASH>..<HASH> 100644
--- a/src/core/Singleton.php
+++ b/src/core/Singleton.php
@@ -3,6 +3,8 @@ namespace rosasurfer\core;
use rosasurfer\exception\InvalidArgumentException;
use rosasurfer\exception\RuntimeException;
+use function rosasurfer\is_class;
+use rosasurfer\exception\ClassNotFoundException;
/**
@@ -41,6 +43,8 @@ abstract class Singleton extends Object {
throw new RuntimeException('Infinite loop: recursive call to '.__METHOD__."($class) detected");
$currentCreations[$class] = true;
+ if (!is_class($class)) throw new ClassNotFoundException('Class not found: '.$class );
+
// Parameter ermitteln
$args = null;
if (func_num_args() > 1) {
|
check class for existence and produce more meaningful error message
|
rosasurfer_ministruts
|
train
|
653a9f35abe61e4e127d738821a157348969fd5a
|
diff --git a/safe_qgis/test_dock.py b/safe_qgis/test_dock.py
index <HASH>..<HASH> 100644
--- a/safe_qgis/test_dock.py
+++ b/safe_qgis/test_dock.py
@@ -496,12 +496,13 @@ class DockTest(unittest.TestCase):
myRunButton = DOCK.pbnRunStop
myFileList = ['kabupaten_jakarta_singlepart_0_good_attr.shp',
'kabupaten_jakarta_singlepart_1_good_attr.shp',
- 'kabupaten_jakarta_singlepart_3_good_attr.shp'
+ 'kabupaten_jakarta_singlepart_3_good_attr.shp',
+ 'kabupaten_jakarta_singlepart_with_None_keyword.shp'
]
#add additional layers
loadLayers(myFileList, theClearFlag=False, theDataDirectory=TESTDATA)
- # with aggregation attribute defined in .keyword using
+ # with KAB_NAME aggregation attribute defined in .keyword using
# kabupaten_jakarta_singlepart.shp
myResult, myMessage = setupScenario(
theHazard='A flood in Jakarta like in 2007',
@@ -516,6 +517,21 @@ class DockTest(unittest.TestCase):
(DOCK.aggregationAttribute))
self.assertEqual(DOCK.aggregationAttribute, 'KAB_NAME', myMessage)
+ # with None aggregation attribute defined in .keyword using
+ # kabupaten_jakarta_singlepart_with_None_keyword.shp
+ myResult, myMessage = setupScenario(
+ theHazard='A flood in Jakarta like in 2007',
+ theExposure='People',
+ theFunction='Need evacuation',
+ theFunctionId='Flood Evacuation Function',
+ theAggregation='kabupaten jakarta singlepart with None keyword')
+ assert myResult, myMessage
+ # Press RUN
+ QTest.mouseClick(myRunButton, QtCore.Qt.LeftButton)
+ myMessage = ('The aggregation should be None. Found: %s' %
+ (DOCK.aggregationAttribute))
+ assert DOCK.aggregationAttribute is None, myMessage
+
# with no good aggregation attribute using
# kabupaten_jakarta_singlepart_0_good_attr.shp
myResult, myMessage = setupScenario(
|
adding aggregation attributr None in keyword file test
|
inasafe_inasafe
|
train
|
2db1fc1a6a4c087b1aaabeb407d02ee30e62bf77
|
diff --git a/modules/activiti-engine/src/main/java/org/activiti/engine/task/TaskQuery.java b/modules/activiti-engine/src/main/java/org/activiti/engine/task/TaskQuery.java
index <HASH>..<HASH> 100644
--- a/modules/activiti-engine/src/main/java/org/activiti/engine/task/TaskQuery.java
+++ b/modules/activiti-engine/src/main/java/org/activiti/engine/task/TaskQuery.java
@@ -98,8 +98,9 @@ public interface TaskQuery extends Query<TaskQuery, Task>{
TaskQuery taskCandidateGroup(String candidateGroup);
/** Select tasks that has been claimed or assigned to user or waiting to claim by user (candidate user or groups).
- * If set <strong>isDbIdentityUsed</strong> to <strong>false</strong> you can invoke {@link #taskCandidateGroupIn(List)}
- * to include tasks that can be claimed by a user in the given groups.
+ * You can invoke {@link #taskCandidateGroupIn(List)} to include tasks that can be claimed by a user in the given groups
+ * while set property <strong>dbIdentityUsed</strong> to <strong>false</strong> in process engine configuration
+ * or using custom session factory of GroupIdentityManager.
*/
TaskQuery taskCandidateOrAssigned(String userIdForCandidateAndAssignee);
diff --git a/modules/activiti-engine/src/main/resources/org/activiti/db/mapping/entity/Task.xml b/modules/activiti-engine/src/main/resources/org/activiti/db/mapping/entity/Task.xml
index <HASH>..<HASH> 100644
--- a/modules/activiti-engine/src/main/resources/org/activiti/db/mapping/entity/Task.xml
+++ b/modules/activiti-engine/src/main/resources/org/activiti/db/mapping/entity/Task.xml
@@ -513,14 +513,14 @@
</if>
<choose>
<when test="bothCandidateAndAssigned">
- <!-- if isDbIdentityUsed set true -->
+ <!-- if dbIdentityUsed set true in process engine configuration -->
<if test="userIdForCandidateAndAssignee != null">
<if test="candidateGroups == null">
and (RES.ASSIGNEE_ = #{userIdForCandidateAndAssignee} or (RES.ASSIGNEE_ is null and I.USER_ID_ = #{userIdForCandidateAndAssignee}
or I.GROUP_ID_ IN (select g.GROUP_ID_ from ACT_ID_MEMBERSHIP g where g.USER_ID_ = #{userIdForCandidateAndAssignee} ) ) )
</if>
</if>
- <!-- if isDbIdentityUsed set false -->
+ <!-- if dbIdentityUsed set false in process engine configuration of using custom session factory of GroupIdentityManager -->
<if test="candidateGroups != null">
and (RES.ASSIGNEE_ = #{userIdForCandidateAndAssignee}
or (RES.ASSIGNEE_ is null
diff --git a/modules/activiti-engine/src/test/java/org/activiti/engine/test/api/task/TaskQueryTest.java b/modules/activiti-engine/src/test/java/org/activiti/engine/test/api/task/TaskQueryTest.java
index <HASH>..<HASH> 100644
--- a/modules/activiti-engine/src/test/java/org/activiti/engine/test/api/task/TaskQueryTest.java
+++ b/modules/activiti-engine/src/test/java/org/activiti/engine/test/api/task/TaskQueryTest.java
@@ -343,7 +343,7 @@ public class TaskQueryTest extends PluggableActivitiTestCase {
List<Task> tasks = query.list();
assertEquals(11, tasks.size());
- // if isDbIdentityUsed set false
+ // if dbIdentityUsed set false in process engine configuration of using custom session factory of GroupIdentityManager
ArrayList candidateGroups = new ArrayList();
candidateGroups.add("management");
candidateGroups.add("accountancy");
|
Document for method taskCandidateOrAssigned in TaskQuery
|
Activiti_Activiti
|
train
|
6a6ce0eef6d2020bbe078b07941f46c076aeb3d8
|
diff --git a/submit/views.py b/submit/views.py
index <HASH>..<HASH> 100644
--- a/submit/views.py
+++ b/submit/views.py
@@ -93,15 +93,17 @@ def details(request, subm_id):
@login_required
def new(request, ass_id):
ass = get_object_or_404(Assignment, pk=ass_id)
+
+ # Check whether submissions are allowed.
+ if not ass.can_create_submission(user=request.user):
+ messages.error(request, "You are not authorized to create a submission for this assignment right now.")
+ return redirect('dashboard')
+
# get submission form according to the assignment type
SubmissionForm = getSubmissionForm(ass)
+
# Analyze submission data
if request.POST:
- # Make sure that the submission is still possible, since web page rendering
- # and POST data sending may be indefinitly delayed
- if not ass.can_create_submission(user=request.user):
- messages.error(request, "You are not authorized to create a submission for this assignment right now.")
- return redirect('dashboard')
# we need to fill all forms here, so that they can be rendered on validation errors
submissionForm = SubmissionForm(request.user, ass, request.POST, request.FILES)
if submissionForm.is_valid():
|
Display "new submission" page only if submission is possible
|
troeger_opensubmit
|
train
|
f86486a4d86382a8677a35128f39a97507454ad5
|
diff --git a/aws_google_auth/configuration.py b/aws_google_auth/configuration.py
index <HASH>..<HASH> 100644
--- a/aws_google_auth/configuration.py
+++ b/aws_google_auth/configuration.py
@@ -2,7 +2,10 @@
import os
import botocore.session
-import configparser
+try:
+ from backports import configparser
+except ImportError:
+ import configparser
from . import util
from . import amazon
|
Be explicit about which configparser (Issue #<I>)
|
cevoaustralia_aws-google-auth
|
train
|
3849e8439679d2ba086f061ba0c1c6a873848de4
|
diff --git a/modules/orionode/lib/cf/apps.js b/modules/orionode/lib/cf/apps.js
index <HASH>..<HASH> 100644
--- a/modules/orionode/lib/cf/apps.js
+++ b/modules/orionode/lib/cf/apps.js
@@ -533,7 +533,7 @@ function updateApp(req, appTarget){
}
function getStackGuidByName(userId, stackname ,appTarget){
logger.debug("Getting stack guid=" + theApp.appName);
- return target.cfRequest("GET", userId, appTarget.Url + "/v2/stacks", {"q":"name:"+ stackname,"inline-relations-depth":"1"})
+ return target.cfRequest("GET", userId, appTarget.Url + "/v2/stacks", {"q":"name:"+ stackname,"inline-relations-depth":"1"}, null, null, null, appTarget)
.then(function(result){
return result.resources[0] && result.resources[0].metadata.guid || null;
});
|
Bug <I> - Exception trying to deploy app
|
eclipse_orion.client
|
train
|
28379077e9a631419d778894c388b4b5222300c2
|
diff --git a/tests/test_winazurearm.py b/tests/test_winazurearm.py
index <HASH>..<HASH> 100644
--- a/tests/test_winazurearm.py
+++ b/tests/test_winazurearm.py
@@ -280,7 +280,8 @@ class WinAzureARMTestCase(TestCase):
self.assertEqual(1, client.resource.resource_groups.delete.call_count)
self.assertIs(True, poller.is_done)
- def test_delete_resources_only_network(self, is_mock):
+ # https://bugs.launchpad.net/juju-ci-tools/+bug/1613767
+ def xxx_test_delete_resources_only_network(self, is_mock):
now = datetime.now(tz=pytz.utc)
client = ARMClient('subscription_id', 'client_id', 'secret', 'tenant')
client.init_services()
diff --git a/winazurearm.py b/winazurearm.py
index <HASH>..<HASH> 100755
--- a/winazurearm.py
+++ b/winazurearm.py
@@ -185,7 +185,8 @@ class ResourceGroupDetails:
# left behind when Juju cannot complete a delete in time.
log.debug('{} only has a network, likely a failed delete'.format(
self.name))
- return True
+ # https://bugs.launchpad.net/juju-ci-tools/+bug/1613767
+ # return True
return False
def delete(self):
|
Do not delete resource groups with just a network because azure-arm-deploy-bundle-lxd is getting clobbered.
|
juju_juju
|
train
|
4472646082be0c29af72a017614dbb4231a2d6b7
|
diff --git a/biodata-models/src/main/java/org/opencb/biodata/models/variant/ga4gh/GAVariantFactory.java b/biodata-models/src/main/java/org/opencb/biodata/models/variant/ga4gh/GAVariantFactory.java
index <HASH>..<HASH> 100644
--- a/biodata-models/src/main/java/org/opencb/biodata/models/variant/ga4gh/GAVariantFactory.java
+++ b/biodata-models/src/main/java/org/opencb/biodata/models/variant/ga4gh/GAVariantFactory.java
@@ -25,10 +25,18 @@ public class GAVariantFactory {
for (ArchivedVariantFile file : variant.getFiles().values()) {
String[] vcfLine = file.getAttribute("src").split("\t");
- GAVariant ga = new GAVariant(vcfLine[2], file.getFileId(), vcfLine[2].split(","), 0, 0,
- vcfLine[0], Integer.parseInt(vcfLine[1]), Integer.parseInt(vcfLine[1]) + vcfLine[3].length(),
- vcfLine[3], vcfLine[4].split(","), parseInfo(vcfLine[7].split(";")),
- parseCalls(vcfLine[8].split(":"), Arrays.copyOfRange(vcfLine, 9, vcfLine.length), file.getFileId()));
+ GAVariant ga;
+ if (vcfLine.length > 8) {
+ ga = new GAVariant(vcfLine[2], file.getFileId(), vcfLine[2].split(","), 0, 0,
+ vcfLine[0], Integer.parseInt(vcfLine[1]), Integer.parseInt(vcfLine[1]) + vcfLine[3].length(),
+ vcfLine[3], vcfLine[4].split(","), parseInfo(vcfLine[7].split(";")),
+ parseCalls(vcfLine[8].split(":"), Arrays.copyOfRange(vcfLine, 9, vcfLine.length), file.getFileId()));
+ } else {
+ ga = new GAVariant(vcfLine[2], file.getFileId(), vcfLine[2].split(","), 0, 0,
+ vcfLine[0], Integer.parseInt(vcfLine[1]), Integer.parseInt(vcfLine[1]) + vcfLine[3].length(),
+ vcfLine[3], vcfLine[4].split(","), parseInfo(vcfLine[7].split(";")), null);
+ }
+
gaVariants.add(ga);
}
}
@@ -37,18 +45,19 @@ public class GAVariantFactory {
}
private static GAKeyValue[] parseInfo(String[] infoFields) {
- List<GAKeyValue> kvs = new LinkedList<>();
+ GAKeyValue[] kvs = new GAKeyValue[infoFields.length];
- for (String subfield : infoFields) {
+ for (int i = 0; i < infoFields.length; i++) {
+ String subfield = infoFields[i];
String[] parts = subfield.split("=");
if (parts.length > 1) {
- kvs.add(new GAKeyValue(parts[0], parts[1]));
+ kvs[i] = new GAKeyValue(parts[0], parts[1]);
} else {
- kvs.add(new GAKeyValue(parts[0], null));
+ kvs[i] = new GAKeyValue(parts[0], null);
}
}
- return (GAKeyValue[]) Arrays.copyOf(kvs.toArray(), kvs.size());
+ return kvs;
}
private static GACall[] parseCalls(String[] formatFields, String[] samplesFields, String callSetName) {
@@ -58,7 +67,7 @@ public class GAVariantFactory {
for (String sample : samplesFields) {
String[] parts = sample.split(":");
- String[] alleles = parts[0].split("|/");
+ String[] alleles = parts[0].split("/|\\|", -1);
int[] genotype = new int[alleles.length];
for (int i = 0; i < alleles.length; i++) {
genotype[i] = (alleles[i].equals(".")) ? -1 : Integer.parseInt(alleles[i]);
@@ -89,10 +98,11 @@ public class GAVariantFactory {
}
}
- calls.add(new GACall(callSetName, callSetName, genotype, sample, genotypeLikelihood, info));
+ calls.add(new GACall(callSetName, callSetName, genotype, phaseSet, genotypeLikelihood, info));
}
- return (GACall[]) Arrays.copyOf(calls.toArray(), calls.size());
+ GACall[] retCalls = new GACall[calls.size()];
+ return calls.toArray(retCalls);
}
}
|
Fixes some exceptions for null pointer access and list to array conversions
|
opencb_biodata
|
train
|
7ba20b905912af7adc4d6a93c11920d2f9098e27
|
diff --git a/src/js/Buttons/FloatingButton.js b/src/js/Buttons/FloatingButton.js
index <HASH>..<HASH> 100644
--- a/src/js/Buttons/FloatingButton.js
+++ b/src/js/Buttons/FloatingButton.js
@@ -2,7 +2,6 @@ import React, { Component, PropTypes } from 'react';
import PureRenderMixin from 'react-addons-pure-render-mixin';
import classnames from 'classnames';
-import { isPropEnabled } from '../utils';
import IconButton from './IconButton';
export default class FloatingButton extends Component {
@@ -19,18 +18,31 @@ export default class FloatingButton extends Component {
fixed: PropTypes.bool,
mini: PropTypes.bool,
avatar: PropTypes.node,
+ primary: PropTypes.bool,
+ secondary: PropTypes.bool,
};
render() {
- const { iconClassName, children, className, ...props } = this.props;
+ const {
+ className,
+ fixed,
+ mini,
+ primary,
+ secondary,
+ children,
+ iconClassName,
+ ...props,
+ } = this.props;
return (
<IconButton
+ {...props}
className={classnames('md-floating-btn', className, {
- 'fixed': isPropEnabled(props, 'fixed'),
- 'mini': isPropEnabled(props, 'mini'),
+ mini,
+ fixed,
+ 'md-primary': primary,
+ 'md-secondary': secondary,
})}
iconClassName={iconClassName}
- {...props}
>
{children}
</IconButton>
diff --git a/src/js/Buttons/IconButton.js b/src/js/Buttons/IconButton.js
index <HASH>..<HASH> 100644
--- a/src/js/Buttons/IconButton.js
+++ b/src/js/Buttons/IconButton.js
@@ -1,7 +1,7 @@
import React, { Component, PropTypes } from 'react';
import PureRenderMixin from 'react-addons-pure-render-mixin';
+import classnames from 'classnames';
-import { isPropEnabled, mergeClassNames } from '../utils';
import FontIcon from '../FontIcons';
import Ink from '../Inks';
import Tooltip from '..//Tooltips';
@@ -23,6 +23,7 @@ export default class IconButton extends Component {
tooltipPosition: PropTypes.string,
href: PropTypes.string,
type: PropTypes.string,
+ disabled: PropTypes.bool,
};
static defaultProps = {
@@ -30,10 +31,23 @@ export default class IconButton extends Component {
};
render() {
- const { iconClassName, children, className, href, type, tooltip, tooltipClassName, tooltipPosition, ...props } = this.props;
- let btnProps = {
+ const {
+ iconClassName,
+ children,
+ className,
+ href,
+ type,
+ tooltip,
+ tooltipClassName,
+ tooltipPosition,
+ disabled,
...props,
- className: mergeClassNames(props, 'md-btn', 'md-icon-btn', className),
+ } = this.props;
+
+ const btnProps = {
+ ...props,
+ disabled,
+ className: classnames('md-btn md-icon-btn', className),
};
if(href) {
@@ -47,7 +61,6 @@ export default class IconButton extends Component {
displayedChildren = <FontIcon iconClassName={iconClassName}>{children}</FontIcon>;
}
- const disabled = isPropEnabled(props, 'disabled');
const wrappedButton = (
<Ink disabled={disabled}>
{React.createElement(href ? 'a' : 'button', btnProps, displayedChildren)}
|
Removed isPropEnabled and mergeClassNames from floating/icon buttons
|
mlaursen_react-md
|
train
|
167b8113867a8f2a5ee7515127a43c4acd7b829d
|
diff --git a/src/main/java/org/la4j/factory/CRSFactory.java b/src/main/java/org/la4j/factory/CRSFactory.java
index <HASH>..<HASH> 100644
--- a/src/main/java/org/la4j/factory/CRSFactory.java
+++ b/src/main/java/org/la4j/factory/CRSFactory.java
@@ -23,7 +23,6 @@ package org.la4j.factory;
import java.util.ArrayList;
import java.util.Arrays;
-import java.util.Collection;
import java.util.Random;
import org.la4j.matrix.Matrices;
|
Update CRSFactory.java
Imports optimized.
|
vkostyukov_la4j
|
train
|
7d86fe2e280974312e8106f6e67cf063284194de
|
diff --git a/lib/xmlhttprequest.js b/lib/xmlhttprequest.js
index <HASH>..<HASH> 100644
--- a/lib/xmlhttprequest.js
+++ b/lib/xmlhttprequest.js
@@ -37,11 +37,68 @@
XMLHttpRequestEventTarget.call(this);
options = options || {};
this._flag.anonymous = !!options.anon;
- Object.defineProperty(this, 'upload', {
- configurable: true,
- enumerable: true,
- value: new XMLHttpRequestUpload(),
- writable: false
+ Object.defineProperties(this, {
+ upload: {
+ configurable: true,
+ enumerable: true,
+ value: new XMLHttpRequestUpload(),
+ writable: false
+ },
+ _properties: {
+ configurable: false,
+ enumerable: false,
+ value: Object.create(Object.prototype, {
+ auth: {
+ configurable: false,
+ enumerable: true,
+ value: '',
+ writable: true
+ },
+ client: {
+ configurable: false,
+ enumerable: true,
+ value: null,
+ writable: true,
+ },
+ method: {
+ configurable: false,
+ enumerable: true,
+ value: undefined,
+ writable: true
+ },
+ responseHeaders: {
+ configurable: false,
+ enumerable: true,
+ value: {},
+ writable: true,
+ },
+ responseBuffer: {
+ configurable: false,
+ enumerable: true,
+ value: null,
+ writable: true,
+ },
+ responseType: {
+ configurable: false,
+ enumerable: true,
+ value: '',
+ writable: true,
+ },
+ requestHeaders: {
+ configurable: false,
+ enumerable: true,
+ value: {},
+ writable: true,
+ },
+ uri: {
+ configurable: true,
+ enumerable: true,
+ value: '',
+ writable: true
+ }
+ }),
+ writable: false
+ }
});
}
@@ -135,61 +192,6 @@
return flag;
}
},
- _properties: {
- configurable: false,
- enumerable: false,
- value: Object.create(Object.prototype, {
- auth: {
- configurable: false,
- enumerable: true,
- value: '',
- writable: true
- },
- client: {
- configurable: false,
- enumerable: true,
- value: null,
- writable: true,
- },
- method: {
- configurable: false,
- enumerable: true,
- value: undefined,
- writable: true
- },
- responseHeaders: {
- configurable: false,
- enumerable: true,
- value: {},
- writable: true,
- },
- responseBuffer: {
- configurable: false,
- enumerable: true,
- value: null,
- writable: true,
- },
- responseType: {
- configurable: false,
- enumerable: true,
- value: '',
- writable: true,
- },
- requestHeaders: {
- configurable: false,
- enumerable: true,
- value: {},
- writable: true,
- },
- uri: {
- configurable: true,
- enumerable: true,
- value: '',
- writable: true
- }
- }),
- writable: false
- },
readyState: {
configurable: true,
enumerable: true,
|
Define private _properties as an instance variable.
When _properties are defined only in XMLHttpRequest.prototype, bad
things happen when one uses several instances of XMLHttpRequest in
parallel. (For example this._properties.responseBuffer points to the
same buffer in all instances.)
|
ykzts_node-xmlhttprequest
|
train
|
ded6b3f0814be79816a6d3a85dc3057680b25bb3
|
diff --git a/phe/tests/cli_test.py b/phe/tests/cli_test.py
index <HASH>..<HASH> 100644
--- a/phe/tests/cli_test.py
+++ b/phe/tests/cli_test.py
@@ -106,7 +106,6 @@ class TestConsoleEncryption(TestCase):
def test_encrypt_float(self):
numbers = [0.0, 1.1, -0.0001, 100000.01, '1e-20', '-10550e20']
-
for num in numbers:
result = self.runner.invoke(cli, ['encrypt', self.public_keyfile.name, "--", str(num)])
assert result.exit_code == 0
@@ -119,3 +118,57 @@ class TestConsoleEncryption(TestCase):
result = self.runner.invoke(cli, ['encrypt', self.public_keyfile.name, "--", str(num)])
assert result.exit_code == 0
+ def test_decrypt_positive_integers(self):
+ numbers = [0, 1, 2, 5, 10, '1', '10550']
+
+ for num in numbers:
+ with tempfile.NamedTemporaryFile() as encfile:
+ fname = encfile.name
+
+ self.runner.invoke(cli, [
+ 'encrypt', self.public_keyfile.name, str(num), '--output', fname
+ ])
+
+ result = self.runner.invoke(cli, [
+ 'decrypt', self.private_keyfile.name, fname
+ ])
+ assert result.exit_code == 0
+
+ assert "{}".format(num) in result.output
+
+ def test_decrypt_signed_integers(self):
+ numbers = [0, 1, -1, 10, '1', '-10550']
+
+ for num in numbers:
+ with tempfile.NamedTemporaryFile() as encfile:
+ fname = encfile.name
+ self.runner.invoke(cli, [
+ 'encrypt', self.public_keyfile.name, '--output', fname, '--', str(num),
+ ])
+
+ result = self.runner.invoke(cli, [
+ 'decrypt', self.private_keyfile.name, fname
+ ])
+ assert result.exit_code == 0
+
+ print(result.output)
+ assert "{}".format(num) in result.output
+
+ def test_decrypt_float(self):
+ numbers = [0.0, 1.1, -0.0001, 100000.01, '1e-20', '-10550e20']
+
+ for num in numbers:
+ with tempfile.NamedTemporaryFile() as encfile:
+ fname = encfile.name
+ self.runner.invoke(cli, [
+ 'encrypt', self.public_keyfile.name, '--output', fname, '--', str(num),
+ ])
+
+ with tempfile.NamedTemporaryFile() as outfile:
+ result = self.runner.invoke(cli, [
+ 'decrypt', self.private_keyfile.name, fname, '--output', outfile.name
+ ])
+ assert result.exit_code == 0
+
+ out = outfile.read()
+ self.assertAlmostEqual(float(num), float(out))
|
#6 Add decryption tests
|
n1analytics_python-paillier
|
train
|
613ee9926af16439e817534ef855421335abae76
|
diff --git a/xchange-core/src/main/java/org/knowm/xchange/currency/Currency.java b/xchange-core/src/main/java/org/knowm/xchange/currency/Currency.java
index <HASH>..<HASH> 100644
--- a/xchange-core/src/main/java/org/knowm/xchange/currency/Currency.java
+++ b/xchange-core/src/main/java/org/knowm/xchange/currency/Currency.java
@@ -237,6 +237,7 @@ public class Currency implements Comparable<Currency>, Serializable {
public static final Currency UYU = createCurrency("UYU", "Uruguayan Peso", null);
public static final Currency UZS = createCurrency("UZS", "Uzbekistan Som", null);
public static final Currency VEF = createCurrency("VEF", "Venezuelan Bolívar", null);
+ public static final Currency VET = createCurrency("VET", "Hub Culture's Vet", null, "VEN");
public static final Currency VEN = createCurrency("VEN", "Hub Culture's Ven", null, "XVN");
public static final Currency XVN = getInstance("XVN");
public static final Currency VIB = createCurrency("VIB", "Viberate", null);
diff --git a/xchange-core/src/main/java/org/knowm/xchange/currency/CurrencyPair.java b/xchange-core/src/main/java/org/knowm/xchange/currency/CurrencyPair.java
index <HASH>..<HASH> 100644
--- a/xchange-core/src/main/java/org/knowm/xchange/currency/CurrencyPair.java
+++ b/xchange-core/src/main/java/org/knowm/xchange/currency/CurrencyPair.java
@@ -170,6 +170,21 @@ public class CurrencyPair implements Comparable<CurrencyPair>, Serializable {
public static final CurrencyPair STEEM_BNB = new CurrencyPair(Currency.STEEM, Currency.BNB);
public static final CurrencyPair STEEM_KRW = new CurrencyPair(Currency.STEEM, Currency.KRW);
+ public static final CurrencyPair VET_BTC = new CurrencyPair(Currency.VET, Currency.BTC);
+ public static final CurrencyPair VET_USDT = new CurrencyPair(Currency.VET, Currency.USDT);
+ public static final CurrencyPair VET_ETH = new CurrencyPair(Currency.VET, Currency.ETH);
+ public static final CurrencyPair VET_BNB = new CurrencyPair(Currency.VET, Currency.BNB);
+
+ public static final CurrencyPair ADA_BTC = new CurrencyPair(Currency.ADA, Currency.BTC);
+ public static final CurrencyPair ADA_USDT = new CurrencyPair(Currency.ADA, Currency.USDT);
+ public static final CurrencyPair ADA_ETH = new CurrencyPair(Currency.ADA, Currency.ETH);
+ public static final CurrencyPair ADA_BNB = new CurrencyPair(Currency.ADA, Currency.BNB);
+
+ public static final CurrencyPair TRX_BTC = new CurrencyPair(Currency.TRX, Currency.BTC);
+ public static final CurrencyPair TRX_USDT = new CurrencyPair(Currency.TRX, Currency.USDT);
+ public static final CurrencyPair TRX_ETH = new CurrencyPair(Currency.TRX, Currency.ETH);
+ public static final CurrencyPair TRX_BNB = new CurrencyPair(Currency.TRX, Currency.BNB);
+
// start of extra ANX supported pair
// BTC
public static final CurrencyPair BTC_XDC = new CurrencyPair(Currency.BTC, Currency.XDC);
|
[Core] Added 3 currencies for Binance
|
knowm_XChange
|
train
|
0ad3cd6d31fa9c1d500f91e3fc108095ef2776c5
|
diff --git a/go/vt/vtadmin/rbac/rbac.go b/go/vt/vtadmin/rbac/rbac.go
index <HASH>..<HASH> 100644
--- a/go/vt/vtadmin/rbac/rbac.go
+++ b/go/vt/vtadmin/rbac/rbac.go
@@ -75,17 +75,24 @@ type Resource string
const (
ClusterResource Resource = "Cluster"
+ /* generic topo resources */
+
KeyspaceResource Resource = "Keyspace"
ShardResource Resource = "Shard"
TabletResource Resource = "Tablet"
VTGateResource Resource = "VTGate"
+ /* vschema resources */
+
SrvVSchemaResource Resource = "SrvVSchema"
VSchemaResource Resource = "VSchema"
- BackupResource Resource = "Backup"
- SchemaResource Resource = "Schema"
- WorkflowResource Resource = "Workflow"
+ /* misc resources */
+
+ BackupResource Resource = "Backup"
+ SchemaResource Resource = "Schema"
+ ShardReplicationPositionResource Resource = "ShardReplicationPosition"
+ WorkflowResource Resource = "Workflow"
VTExplainResource Resource = "VTExplain"
)
|
Add new resource for ShardReplicationPosition
Also adjust structure and annotate the resource sections a bit
|
vitessio_vitess
|
train
|
b3a4b48b9509d6bf32b974161c635301462f250c
|
diff --git a/src/main/java/com/marklogic/client/impl/GraphManagerImpl.java b/src/main/java/com/marklogic/client/impl/GraphManagerImpl.java
index <HASH>..<HASH> 100644
--- a/src/main/java/com/marklogic/client/impl/GraphManagerImpl.java
+++ b/src/main/java/com/marklogic/client/impl/GraphManagerImpl.java
@@ -15,6 +15,7 @@
*/
package com.marklogic.client.impl;
+import java.util.ArrayList;
import java.util.Iterator;
import com.marklogic.client.Transaction;
|
(small fix that was breaking compile) round 2 of minimal implementation API stubs
|
marklogic_java-client-api
|
train
|
2e56fb6087fcd106b7f5ddb2052748fbfcfa49cd
|
diff --git a/tomodachi/protocol/protobuf_base.py b/tomodachi/protocol/protobuf_base.py
index <HASH>..<HASH> 100644
--- a/tomodachi/protocol/protobuf_base.py
+++ b/tomodachi/protocol/protobuf_base.py
@@ -29,8 +29,8 @@ class ProtobufBase(object):
message.metadata.timestamp = time.time()
message.metadata.topic = topic
message.metadata.data_encoding = 'base64'
- message.data = base64.b64encode(data.SerializeToString())
- return base64.b64encode(message.SerializeToString())
+ message.data = base64.b64encode(data.SerializeToString()).decode('ascii')
+ return base64.b64encode(message.SerializeToString()).decode('ascii')
@classmethod
async def parse_message(cls, payload: str, proto_class: Any, validator: Any = None) -> Union[Dict, Tuple]:
|
changed encoding to ascii for the base<I> message
|
kalaspuff_tomodachi
|
train
|
f2e7fd02b1197bac931804b54853fe326c9cd0d1
|
diff --git a/autopep8.py b/autopep8.py
index <HASH>..<HASH> 100755
--- a/autopep8.py
+++ b/autopep8.py
@@ -1684,7 +1684,8 @@ def format_block_comments(source):
# Optimization.
return source
- string_line_numbers = multiline_string_lines(source)
+ string_line_numbers = multiline_string_lines(source,
+ include_docstrings=True)
fixed_lines = []
sio = StringIO(source)
for (line_number, line) in enumerate(sio.readlines(), start=1):
|
Do not format comments in docstrings
|
hhatto_autopep8
|
train
|
9a24b61d8132d5e5a0816d1080b1f291007e1aee
|
diff --git a/lib/mpd_protocol.js b/lib/mpd_protocol.js
index <HASH>..<HASH> 100644
--- a/lib/mpd_protocol.js
+++ b/lib/mpd_protocol.js
@@ -1320,7 +1320,7 @@ function writePlaylistInfo(self, start, end) {
}
function forEachMatchingTrack(self, filters, caseSensitive, fn) {
- // TODO: support 'any' and 'in' as tag types
+ // TODO: support 'in' as tag type
var trackTable = self.player.libraryIndex.trackTable;
if (!caseSensitive) {
filters.forEach(function(filter) {
@@ -1329,10 +1329,11 @@ function forEachMatchingTrack(self, filters, caseSensitive, fn) {
}
for (var key in trackTable) {
var track = trackTable[key];
- var matches = true;
+ var matches = false;
for (var filterIndex = 0; filterIndex < filters.length; filterIndex += 1) {
var filter = filters[filterIndex];
- var filterField = track[filter.field];
+ var filterField = String(track[filter.field]);
+ if (!filterField) continue;
if (!caseSensitive && filterField) filterField = filterField.toLowerCase();
/* assumes:
@@ -1341,11 +1342,11 @@ function forEachMatchingTrack(self, filters, caseSensitive, fn) {
*/
if (caseSensitive) {
if (filterField === filter.value) {
- matches = false;
+ matches = true;
break;
}
- } else if (filterField.indexOf(filter.value) < 0) {
- matches = false;
+ } else if (filterField.indexOf(filter.value) > -1) {
+ matches = true;
break;
}
}
@@ -1393,12 +1394,23 @@ function parseFindArgs(self, args, caseSensitive, onTrack, cb, onFinish) {
}
var filters = [];
for (var i = 0; i < args.length; i += 2) {
- var tagType = tagTypes[args[i].toLowerCase()];
- if (!tagType) return cb(ERR_CODE_ARG, "\"" + args[i] + "\" is not known");
- filters.push({
- field: tagType.grooveTag,
- value: args[i+1],
- });
+ var tagsToSearch = [];
+ if (args[i].toLowerCase() === "any") {
+ // Special case the any key. Just search everything.
+ for (var tagType in tagTypes) {
+ tagsToSearch.push(tagTypes[tagType]);
+ }
+ } else {
+ var tagType = tagTypes[args[i].toLowerCase()];
+ if (!tagType) return cb(ERR_CODE_ARG, "\"" + args[i] + "\" is not known");
+ tagsToSearch.push(tagType);
+ }
+ for (var j = 0; j < tagsToSearch.length; j++) {
+ filters.push({
+ field: tagsToSearch[j].grooveTag,
+ value: args[i+1],
+ });
+ }
forEachMatchingTrack(self, filters, caseSensitive, onTrack);
}
onFinish();
|
MPD: Support "any" as a search type in find and search.
Currently I am just searching all the defined tag types. I am not sure if
there should be a specific order they are searched in or whether we should
just be searching string ones.
Now coerces the tag value to a string.
|
andrewrk_groovebasin
|
train
|
36216cc9f2c5f9a71e361501c4d32b2c7f078c14
|
diff --git a/bigtable-client-core-parent/bigtable-hbase/src/main/java/com/google/cloud/bigtable/hbase/AbstractBigtableTable.java b/bigtable-client-core-parent/bigtable-hbase/src/main/java/com/google/cloud/bigtable/hbase/AbstractBigtableTable.java
index <HASH>..<HASH> 100644
--- a/bigtable-client-core-parent/bigtable-hbase/src/main/java/com/google/cloud/bigtable/hbase/AbstractBigtableTable.java
+++ b/bigtable-client-core-parent/bigtable-hbase/src/main/java/com/google/cloud/bigtable/hbase/AbstractBigtableTable.java
@@ -356,8 +356,8 @@ public abstract class AbstractBigtableTable implements Table {
@Override
public void put(Put put) throws IOException {
LOG.trace("put(Put)");
- RowMutation request = hbaseAdapter.adapt(put);
- mutateRow(put, request, "put");
+ RowMutation rowMutation = hbaseAdapter.adapt(put);
+ mutateRow(put, rowMutation, "put");
}
/** {@inheritDoc} */
@@ -403,8 +403,8 @@ public abstract class AbstractBigtableTable implements Table {
@Override
public void delete(Delete delete) throws IOException {
LOG.trace("delete(Delete)");
- RowMutation request = hbaseAdapter.adapt(delete);
- mutateRow(delete, request, "delete");
+ RowMutation rowMutation = hbaseAdapter.adapt(delete);
+ mutateRow(delete, rowMutation, "delete");
}
/** {@inheritDoc} */
@@ -471,11 +471,11 @@ public abstract class AbstractBigtableTable implements Table {
}
}
- private void mutateRow(Mutation mutation, RowMutation mutateRowRequest, String type)
+ private void mutateRow(Mutation mutation, RowMutation rowMutation, String type)
throws IOException {
Span span = TRACER.spanBuilder("BigtableTable." + type).startSpan();
try (Scope scope = TRACER.withSpan(span)) {
- clientWrapper.mutateRow(mutateRowRequest);
+ clientWrapper.mutateRow(rowMutation);
} catch (Throwable t) {
span.setStatus(Status.UNKNOWN);
throw logAndCreateIOException(type, mutation.getRow(), t);
|
rename variables (#<I>)
|
googleapis_cloud-bigtable-client
|
train
|
343e7a10bd695374af04f05db14c905b252bb56f
|
diff --git a/core/src/test/java/com/google/common/truth/DoubleSubjectTest.java b/core/src/test/java/com/google/common/truth/DoubleSubjectTest.java
index <HASH>..<HASH> 100644
--- a/core/src/test/java/com/google/common/truth/DoubleSubjectTest.java
+++ b/core/src/test/java/com/google/common/truth/DoubleSubjectTest.java
@@ -545,7 +545,15 @@ public class DoubleSubjectTest extends BaseSubjectTestCase {
assertThat(-1.0 * Double.MIN_VALUE).isNotNaN();
assertThat(Double.POSITIVE_INFINITY).isNotNaN();
assertThat(Double.NEGATIVE_INFINITY).isNotNaN();
+ }
+
+ @Test
+ public void isNotNaNIsNaN() {
assertThatIsNotNaNFails(Double.NaN);
+ }
+
+ @Test
+ public void isNotNaNIsNull() {
assertThatIsNotNaNFails(null);
}
diff --git a/core/src/test/java/com/google/common/truth/FloatSubjectTest.java b/core/src/test/java/com/google/common/truth/FloatSubjectTest.java
index <HASH>..<HASH> 100644
--- a/core/src/test/java/com/google/common/truth/FloatSubjectTest.java
+++ b/core/src/test/java/com/google/common/truth/FloatSubjectTest.java
@@ -545,7 +545,15 @@ public class FloatSubjectTest extends BaseSubjectTestCase {
assertThat(-1.0 * Float.MIN_VALUE).isNotNaN();
assertThat(Float.POSITIVE_INFINITY).isNotNaN();
assertThat(Float.NEGATIVE_INFINITY).isNotNaN();
+ }
+
+ @Test
+ public void isNotNaNIsNaN() {
assertThatIsNotNaNFails(Float.NaN);
+ }
+
+ @Test
+ public void isNotNaNIsNull() {
assertThatIsNotNaNFails(null);
}
|
Split tests of isNotNaN() failures into their own methods.
This will let me start using expectFailure.whenTesting() with them (since that method is possible to use only once per test method).
RELNOTES=n/a
-------------
Created by MOE: <URL>
|
google_truth
|
train
|
b1e1a62dd59efc19f727649b6ff28d571fa28646
|
diff --git a/Installation/AdditionalInstaller.php b/Installation/AdditionalInstaller.php
index <HASH>..<HASH> 100644
--- a/Installation/AdditionalInstaller.php
+++ b/Installation/AdditionalInstaller.php
@@ -17,7 +17,6 @@ use Icap\LessonBundle\Installation\Updater\Updater13;
class AdditionalInstaller extends BaseInstaller
{
-
public function postUpdate($currentVersion, $targetVersion)
{
if (version_compare($currentVersion, '1.3', '<') && version_compare($targetVersion, '1.3', '>=') ) {
@@ -26,9 +25,4 @@ class AdditionalInstaller extends BaseInstaller
$updater13->postUpdate();
}
}
-
- public function displayLog($message)
- {
- $this->log($message);
- }
}
\ No newline at end of file
|
[LessonBundle] Remove unused method
|
claroline_Distribution
|
train
|
858d8b5658676fd227c2610a3726cad7bcdd49d9
|
diff --git a/helios-services/src/main/java/com/spotify/helios/master/MasterService.java b/helios-services/src/main/java/com/spotify/helios/master/MasterService.java
index <HASH>..<HASH> 100644
--- a/helios-services/src/main/java/com/spotify/helios/master/MasterService.java
+++ b/helios-services/src/main/java/com/spotify/helios/master/MasterService.java
@@ -17,16 +17,12 @@
package com.spotify.helios.master;
-import com.google.common.base.Strings;
-import com.google.common.base.Throwables;
-import com.google.common.collect.ImmutableList;
-import com.google.common.collect.ImmutableSet;
-import com.google.common.collect.Lists;
-import com.google.common.collect.Sets;
-import com.google.common.io.Resources;
-import com.google.common.util.concurrent.AbstractIdleService;
+import static com.google.common.base.Charsets.UTF_8;
+import static com.google.common.base.Strings.isNullOrEmpty;
+import static com.spotify.helios.servicescommon.ServiceRegistrars.createServiceRegistrar;
+import static com.spotify.helios.servicescommon.ZooKeeperAclProviders.digest;
+import static com.spotify.helios.servicescommon.ZooKeeperAclProviders.heliosAclProvider;
-import com.codahale.metrics.MetricRegistry;
import com.spotify.helios.common.HeliosRuntimeException;
import com.spotify.helios.master.http.VersionResponseFilter;
import com.spotify.helios.master.metrics.HealthCheckGauge;
@@ -66,6 +62,24 @@ import com.spotify.helios.servicescommon.statistics.Metrics;
import com.spotify.helios.servicescommon.statistics.MetricsImpl;
import com.spotify.helios.servicescommon.statistics.NoopMetrics;
+import ch.qos.logback.access.jetty.RequestLogImpl;
+import com.codahale.metrics.MetricRegistry;
+import com.codahale.metrics.jvm.GarbageCollectorMetricSet;
+import com.codahale.metrics.jvm.MemoryUsageGaugeSet;
+import com.google.common.base.Strings;
+import com.google.common.base.Throwables;
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.ImmutableSet;
+import com.google.common.collect.Lists;
+import com.google.common.collect.Sets;
+import com.google.common.io.Resources;
+import com.google.common.util.concurrent.AbstractIdleService;
+import io.dropwizard.configuration.ConfigurationException;
+import io.dropwizard.jetty.GzipFilterFactory;
+import io.dropwizard.jetty.RequestLogFactory;
+import io.dropwizard.logging.AppenderFactory;
+import io.dropwizard.server.DefaultServerFactory;
+import io.dropwizard.setup.Environment;
import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.AuthInfo;
import org.apache.curator.framework.CuratorFramework;
@@ -92,20 +106,6 @@ import java.util.concurrent.TimeUnit;
import javax.servlet.DispatcherType;
import javax.servlet.FilterRegistration;
-import ch.qos.logback.access.jetty.RequestLogImpl;
-import io.dropwizard.configuration.ConfigurationException;
-import io.dropwizard.jetty.GzipFilterFactory;
-import io.dropwizard.jetty.RequestLogFactory;
-import io.dropwizard.logging.AppenderFactory;
-import io.dropwizard.server.DefaultServerFactory;
-import io.dropwizard.setup.Environment;
-
-import static com.google.common.base.Charsets.UTF_8;
-import static com.google.common.base.Strings.isNullOrEmpty;
-import static com.spotify.helios.servicescommon.ServiceRegistrars.createServiceRegistrar;
-import static com.spotify.helios.servicescommon.ZooKeeperAclProviders.digest;
-import static com.spotify.helios.servicescommon.ZooKeeperAclProviders.heliosAclProvider;
-
/**
* The Helios master service.
*/
@@ -152,6 +152,9 @@ public class MasterService extends AbstractIdleService {
// Configure metrics
final MetricRegistry metricsRegistry = environment.metrics();
+ metricsRegistry.registerAll(new GarbageCollectorMetricSet());
+ metricsRegistry.registerAll(new MemoryUsageGaugeSet());
+
final RiemannSupport riemannSupport = new RiemannSupport(metricsRegistry,
config.getRiemannHostPort(), config.getName(), "helios-master");
final RiemannFacade riemannFacade = riemannSupport.getFacade();
|
master: add MemoryUsageMetricSet and GarbageCollectorMetricSet
It would be nice to keep these stats and have them emitted via the
metrics reporter. This will help for tracking heap size (of different
generations), time spent in GC, etc etc.
|
spotify_helios
|
train
|
3aba8e20a21f23bcba55dd52ac61d27f12e4b003
|
diff --git a/src/CsvMigration.php b/src/CsvMigration.php
index <HASH>..<HASH> 100644
--- a/src/CsvMigration.php
+++ b/src/CsvMigration.php
@@ -91,9 +91,9 @@ class CsvMigration extends AbstractMigration
$tableFields = $this->_getTableFields();
if (empty($tableFields)) {
- $this->_createFromCsv($csvData);
+ $this->_createFromCsv($csvData, $tableName);
} else {
- $this->_updateFromCsv($csvData, $tableFields);
+ $this->_updateFromCsv($csvData, $tableName, $tableFields);
}
}
@@ -193,16 +193,17 @@ class CsvMigration extends AbstractMigration
}
/**
- * Create new fields from csv data.
+ * Create new fields from csv data
*
- * @param array $csvData csv data
+ * @param array $csvData CSV data
+ * @param string $table Table name
* @return void
*/
- protected function _createFromCsv(array $csvData)
+ protected function _createFromCsv(array $csvData, $table)
{
foreach ($csvData as $col) {
$csvField = new CsvField($col);
- $dbFields = $this->_fhf->fieldToDb($csvField);
+ $dbFields = $this->_fhf->fieldToDb($csvField, $table);
if (empty($dbFields)) {
continue;
@@ -215,13 +216,14 @@ class CsvMigration extends AbstractMigration
}
/**
- * Update (modify/delete) table fields in comparison to the csv data.
+ * Update (modify/delete) table fields in comparison to the CSV data
*
- * @param array $csvData csv data
- * @param array $tableFields existing table fields
+ * @param array $csvData CSV data
+ * @param string $table Table name
+ * @param array $tableField Existing table fields
* @return void
*/
- protected function _updateFromCsv(array $csvData, array $tableFields)
+ protected function _updateFromCsv(array $csvData, $table, array $tableFields)
{
// get existing table column names
foreach ($tableFields as &$tableField) {
@@ -232,7 +234,7 @@ class CsvMigration extends AbstractMigration
$editedColumns = [];
foreach ($csvData as $col) {
$csvField = new CsvField($col);
- $dbFields = $this->_fhf->fieldToDb($csvField);
+ $dbFields = $this->_fhf->fieldToDb($csvField, $table);
if (empty($dbFields)) {
continue;
diff --git a/src/FieldHandlers/FieldHandlerFactory.php b/src/FieldHandlers/FieldHandlerFactory.php
index <HASH>..<HASH> 100644
--- a/src/FieldHandlers/FieldHandlerFactory.php
+++ b/src/FieldHandlers/FieldHandlerFactory.php
@@ -104,8 +104,12 @@ class FieldHandlerFactory
* @param string $field Field name
* @return array list of DbField instances
*/
- public function fieldToDb(CsvField $csvField, $table, $field)
+ public function fieldToDb(CsvField $csvField, $table, $field = null)
{
+ if (empty($field)) {
+ $field = $csvField->getName();
+ }
+
$handler = $this->_getHandler($table, $field);
$fields = $handler->fieldToDb($csvField);
|
Fixed CSV Migrations
* Updated the call to `fieldToDb()` method from CsvMigration.
* Updated `fieldToDb()` method in FieldHandlerFactory to use name
from CsvField data, if not provided as parameter.
* Minor documentation updates
|
QoboLtd_cakephp-csv-migrations
|
train
|
1b3cdd2c980c9a0cc591f8c32a7844c16dfd0fd3
|
diff --git a/few/few.py b/few/few.py
index <HASH>..<HASH> 100644
--- a/few/few.py
+++ b/few/few.py
@@ -60,7 +60,8 @@ class FEW(SurvivalMixin, VariationMixin, EvaluationMixin, PopMixin,
random_state=None, verbosity=0,
scoring_function=None, disable_update_check=False,
elitism=True, boolean = False,classification=False,clean=False,
- track_diversity=False,mdr=False,otype='f',c=True, weight_parents=False):
+ track_diversity=False,mdr=False,otype='f',c=True,
+ weight_parents=True):
# sets up GP.
# Save params to be recalled later by get_params()
|
sets weight_parents default to True
|
lacava_few
|
train
|
5e5f405faea4b2d1baa40238a1af977532225b7c
|
diff --git a/salt/modules/virt.py b/salt/modules/virt.py
index <HASH>..<HASH> 100644
--- a/salt/modules/virt.py
+++ b/salt/modules/virt.py
@@ -2717,6 +2717,56 @@ def network_info(name, **kwargs):
return result
+def network_start(name, **kwargs):
+ '''
+ Start a defined virtual network.
+
+ :param name: virtual network name
+ :param connection: libvirt connection URI, overriding defaults
+ :param username: username to connect with, overriding defaults
+ :param password: password to connect with, overriding defaults
+
+ ..versionadded:: Fluorine
+
+ CLI Example:
+
+ .. code-block:: bash
+
+ salt '*' virt.network_start default
+ '''
+ conn = __get_conn(**kwargs)
+ try:
+ net = conn.networkLookupByName(name)
+ return not bool(net.create())
+ finally:
+ conn.close()
+
+
+def network_stop(name, **kwargs):
+ '''
+ Stop a defined virtual network.
+
+ :param name: virtual network name
+ :param connection: libvirt connection URI, overriding defaults
+ :param username: username to connect with, overriding defaults
+ :param password: password to connect with, overriding defaults
+
+ ..versionadded:: Fluorine
+
+ CLI Example:
+
+ .. code-block:: bash
+
+ salt '*' virt.network_stop default
+ '''
+ conn = __get_conn(**kwargs)
+ try:
+ net = conn.networkLookupByName(name)
+ return not bool(net.destroy())
+ finally:
+ conn.close()
+
+
def pool_define_build(name, **kwargs):
'''
Create libvirt pool.
|
Add functions to start/stop virtual networks
From this commit on, users can start and stop their virtual networks
using virt.network_start and virt.network_stop functions.
|
saltstack_salt
|
train
|
1656a6f564b5fc4da8b8c90f4686930d2ecfe9c0
|
diff --git a/spyderplugins/widgets/condapackagesgui.py b/spyderplugins/widgets/condapackagesgui.py
index <HASH>..<HASH> 100644
--- a/spyderplugins/widgets/condapackagesgui.py
+++ b/spyderplugins/widgets/condapackagesgui.py
@@ -4,7 +4,7 @@
# Licensed under the terms of the MIT License
# (see spyderlib/__init__.py for details)
-"""Packager manager widget"""
+"""Conda Packager Manager Widget"""
# pylint: disable=C01031
# pylint: disable=R0903
@@ -93,6 +93,10 @@ dependencies.add("conda", _("Conda package manager"),
def _call_conda_2(extra_args, abspath=True):
+ """ Patched version of the conda api returning only the cmd list
+
+ Allows using this trhough QProcess instead of Popen
+ """
# call conda with the list of extra arguments, and return the tuple
# stdout, stderr
ROOT_PREFIX = conda_api.ROOT_PREFIX
@@ -1651,9 +1655,11 @@ class CondaPackagesWidget(QWidget):
self.env_remove_button = create_action(self, _('Remove'),
icon=get_icon('editdelete.png'),
triggered=self.remove_env)
- actions = [self.env_create_button, self.env_clone_button,
- self.env_remove_button, self.env_options_submenu]
- add_actions(self.env_options_menu, actions)
+
+ self.env_actions = [self.env_create_button, self.env_clone_button,
+ self.env_remove_button]
+ add_actions(self.env_options_menu, [self.env_options_submenu])
+ add_actions(self.env_options_submenu, self.env_actions)
self.env_options_button = QToolButton()
self.env_options_button.setAutoRaise(True)
@@ -1709,8 +1715,6 @@ class CondaPackagesWidget(QWidget):
self.environments = self.table.source_model.environments
self._setup_widget()
-
-
middle_layout = QHBoxLayout()
middle_layout.addWidget(self.table)
@@ -1758,6 +1762,8 @@ class CondaPackagesWidget(QWidget):
self.env_options_submenu.clear()
actions[selected_index].setCheckable(True)
actions[selected_index].setChecked(True)
+ add_actions(self.env_options_submenu, self.env_actions)
+ self.env_options_submenu.addSeparator()
add_actions(self.env_options_submenu, actions)
envs = self.envs
|
updated envirionments menu look
|
spyder-ide_spyder
|
train
|
5af2089b4249c7992be7ca92612febbb000d4344
|
diff --git a/qa_tests/classical_psha_unittest.py b/qa_tests/classical_psha_unittest.py
index <HASH>..<HASH> 100644
--- a/qa_tests/classical_psha_unittest.py
+++ b/qa_tests/classical_psha_unittest.py
@@ -73,7 +73,7 @@ class ClassicalPSHACalculatorAssuranceTestCase(
@attr("qa")
def test_peer_test_set_1_case_2(self):
- expected_results = self._load_results("PeerTestSet1Case2")
+ expected_results = self._load_exp_hazcurve_results("PeerTestSet1Case2")
run_job(helpers.demo_file(
os.path.join("PeerTestSet1Case2", "config.gem")))
@@ -82,7 +82,7 @@ class ClassicalPSHACalculatorAssuranceTestCase(
@attr("qa")
def test_peer_test_set_1_case_5(self):
- expected_results = self._load_results("PeerTestSet1Case5")
+ expected_results = self._load_exp_hazcurve_results("PeerTestSet1Case5")
run_job(helpers.demo_file(
os.path.join("PeerTestSet1Case5", "config.gem")))
@@ -91,7 +91,8 @@ class ClassicalPSHACalculatorAssuranceTestCase(
@attr("qa")
def test_peer_test_set_1_case_8a(self):
- expected_results = self._load_results("PeerTestSet1Case8a")
+ expected_results = self._load_exp_hazcurve_results(
+ "PeerTestSet1Case8a")
run_job(helpers.demo_file(
os.path.join("PeerTestSet1Case8a", "config.gem")))
@@ -100,7 +101,8 @@ class ClassicalPSHACalculatorAssuranceTestCase(
@attr("qa")
def test_peer_test_set_1_case_10(self):
- expected_results = self._load_results("PeerTestSet1Case10")
+ expected_results = self._load_exp_hazcurve_results(
+ "PeerTestSet1Case10")
run_job(helpers.demo_file(
os.path.join("PeerTestSet1Case10", "config.gem")))
@@ -154,8 +156,7 @@ class ClassicalPSHACalculatorAssuranceTestCase(
"Expected %s within a tolerance of %s, but was %s"
% (expected, tolerance, actual))
-
- def _load_results(self, test_name):
+ def _load_exp_hazcurve_results(self, test_name):
"""Return the hazard curves read from the expected_results/ dir.
:returns: the expected hazard curves.
|
renamed a utility function
|
gem_oq-engine
|
train
|
b6e747a7d224a10e6730cc023e9b5219cd85cc27
|
diff --git a/test/tests.js b/test/tests.js
index <HASH>..<HASH> 100644
--- a/test/tests.js
+++ b/test/tests.js
@@ -503,6 +503,10 @@ describe("compiler", function () {
node.expression.callee.property.name, propertyName);
}
+ if (ast.type === "File") {
+ ast = ast.program;
+ }
+
assert.strictEqual(ast.type, "Program");
assert.strictEqual(ast.body.length, 6);
|
Tolerate root AST nodes with type "File" in tests.
|
benjamn_reify
|
train
|
c79a5d18d2d4ae31d24eeb7673f47bd85796408b
|
diff --git a/setup.py b/setup.py
index <HASH>..<HASH> 100644
--- a/setup.py
+++ b/setup.py
@@ -7,7 +7,10 @@ projects managed with cirrus.
"""
import setuptools
-import ConfigParser
+try:
+ import ConfigParser
+except ImportError:
+ import configparser as ConfigParser
def get_default(parser, section, option, default):
|
python3 support in setup.py
|
evansde77_dockerstache
|
train
|
56852f8bd541bb84412e50cf451e0bfc881d7e82
|
diff --git a/src/test/org/openscience/cdk/io/MDLWriterTest.java b/src/test/org/openscience/cdk/io/MDLWriterTest.java
index <HASH>..<HASH> 100644
--- a/src/test/org/openscience/cdk/io/MDLWriterTest.java
+++ b/src/test/org/openscience/cdk/io/MDLWriterTest.java
@@ -26,6 +26,9 @@ package org.openscience.cdk.io;
import java.io.StringWriter;
+import javax.vecmath.Point2d;
+import javax.vecmath.Point3d;
+
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
@@ -141,4 +144,23 @@ public class MDLWriterTest extends ChemObjectIOTest {
Assert.assertNotNull(output);
Assert.assertNotSame(0, output.length());
}
+
+ @Test public void testPrefer3DCoordinateOutput() throws Exception {
+ StringWriter writer = new StringWriter();
+ IMolecule molecule = builder.newMolecule();
+ IAtom atom = builder.newAtom("C");
+ atom.setPoint2d(new Point2d(1.0, 2.0));
+ atom.setPoint3d(new Point3d(3.0, 4.0, 5.0));
+ molecule.addAtom(atom);
+
+ MDLWriter mdlWriter = new MDLWriter(writer);
+ mdlWriter.write(molecule);
+ mdlWriter.close();
+ String output = writer.toString();
+ // the current behavior is that if both 2D and 3D coordinates
+ // are available, the 3D is outputed, and the 2D not
+ Assert.assertTrue(output.contains("3.0"));
+ Assert.assertTrue(output.contains("4.0"));
+ Assert.assertTrue(output.contains("5.0"));
+ }
}
|
Added unit test to verify that if 2D and 3D coordinates are available, the 3D coordinates are outputted.
* formalizing the current writer implementation
|
cdk_cdk
|
train
|
44a999e098b812a4157db8129a926ab246a1f049
|
diff --git a/go/vt/tabletserver/proto/sqlquery.go b/go/vt/tabletserver/proto/sqlquery.go
index <HASH>..<HASH> 100644
--- a/go/vt/tabletserver/proto/sqlquery.go
+++ b/go/vt/tabletserver/proto/sqlquery.go
@@ -18,7 +18,7 @@ type SqlQuery interface {
// FIXME(sugu) Note the client will support both returning an
// int64 or a structure. Using the structure will be rolled
// out after the client is rolled out.
- Begin(context *rpcproto.Context, session *Session, transactionId *int64) error
+ Begin(context *rpcproto.Context, session *Session, txInfo *TransactionInfo) error
Commit(context *rpcproto.Context, session *Session, noOutput *string) error
Rollback(context *rpcproto.Context, session *Session, noOutput *string) error
diff --git a/go/vt/tabletserver/proto/structs.go b/go/vt/tabletserver/proto/structs.go
index <HASH>..<HASH> 100644
--- a/go/vt/tabletserver/proto/structs.go
+++ b/go/vt/tabletserver/proto/structs.go
@@ -46,6 +46,10 @@ type ConnectionInfo struct {
ConnectionId int64
}
+type TransactionInfo struct {
+ TransactionId int64
+}
+
type DmlType struct {
Table string
Keys []interface{}
diff --git a/go/vt/tabletserver/sqlquery.go b/go/vt/tabletserver/sqlquery.go
index <HASH>..<HASH> 100644
--- a/go/vt/tabletserver/sqlquery.go
+++ b/go/vt/tabletserver/sqlquery.go
@@ -237,13 +237,13 @@ func (sq *SqlQuery) GetSessionId(sessionParams *proto.SessionParams, sessionInfo
return nil
}
-func (sq *SqlQuery) Begin(context *rpcproto.Context, session *proto.Session, transactionId *int64) (err error) {
+func (sq *SqlQuery) Begin(context *rpcproto.Context, session *proto.Session, txInfo *proto.TransactionInfo) (err error) {
logStats := newSqlQueryStats("Begin", context)
logStats.OriginalSql = "begin"
defer handleError(&err, logStats)
sq.checkState(session.SessionId, false)
- *transactionId = sq.qe.Begin(logStats, session.ConnectionId)
+ txInfo.TransactionId = sq.qe.Begin(logStats, session.ConnectionId)
return nil
}
@@ -358,9 +358,11 @@ func (sq *SqlQuery) ExecuteBatch(context *rpcproto.Context, queryList *proto.Que
if session.TransactionId != 0 {
panic(NewTabletError(FAIL, "Nested transactions disallowed"))
}
- if err = sq.Begin(context, &session, &session.TransactionId); err != nil {
+ var txInfo proto.TransactionInfo
+ if err = sq.Begin(context, &session, &txInfo); err != nil {
return err
}
+ session.TransactionId = txInfo.TransactionId
begin_called = true
reply.List = append(reply.List, mproto.QueryResult{})
case "commit":
|
return transaction id in a struct for rpc calls
|
vitessio_vitess
|
train
|
1c9742d228af62b951b4c9d8727019189e2194d3
|
diff --git a/pkg/suse/salt.spec b/pkg/suse/salt.spec
index <HASH>..<HASH> 100644
--- a/pkg/suse/salt.spec
+++ b/pkg/suse/salt.spec
@@ -250,13 +250,13 @@ install -Dpm 0644 %{SOURCE8} %{buildroot}%{_sysconfdir}/sysconfig/SuSEfirewall2
%{_mandir}/man1/salt-run.1.*
%{_sbindir}/rcsalt-master
%config(noreplace) %{_sysconfdir}/init.d/salt-master
+%config(noreplace) %{_sysconfdir}/sysconfig/SuSEfirewall2.d/services/salt
%attr(0644, root, root) %config(noreplace) %{_sysconfdir}/salt/master
%{_sysconfdir}/salt/master.d
%dir /srv/salt
%if 0%{?_unitdir:1}
%_unitdir/salt-master.service
%endif
-%{_sysconfdir}/sysconfig/SuSEfirewall2.d/services/salt
%files
%defattr(-,root,root,-)
diff --git a/salt/modules/munin.py b/salt/modules/munin.py
index <HASH>..<HASH> 100644
--- a/salt/modules/munin.py
+++ b/salt/modules/munin.py
@@ -1,4 +1,3 @@
-#!/usr/bin/env python
'''
Run munin plugins/checks from salt and format the output as data.
'''
diff --git a/salt/returners/sentry_return.py b/salt/returners/sentry_return.py
index <HASH>..<HASH> 100644
--- a/salt/returners/sentry_return.py
+++ b/salt/returners/sentry_return.py
@@ -1,6 +1,3 @@
-#!/usr/bin/env python
-# -*- coding: utf-8 -*-
-
'''
Salt returner that report execution results back to sentry. The returner will
inspect the payload to identify errors and flag them as such.
|
updated suse spec file
Fixed non-executable-scripts warning from python checks
|
saltstack_salt
|
train
|
c0a490ea3c2b38f4f69442cdfa36f393e3d0c38c
|
diff --git a/classes/fields/pick.php b/classes/fields/pick.php
index <HASH>..<HASH> 100644
--- a/classes/fields/pick.php
+++ b/classes/fields/pick.php
@@ -297,8 +297,11 @@ class PodsField_Pick extends PodsField {
$data[ $custom_value ] = $custom_label;
}
}
- else
- $data = array_merge( $data, $custom );
+ else {
+ foreach ( $custom as $custom_value => $custom_label ) {
+ $data[ $custom_value ] = $custom_label;
+ }
+ }
}
elseif ( '' != pods_var( 'pick_object', $options, '' ) && array() == pods_var_raw( 'data', $options, array(), null, true ) ) {
$options[ 'table_info' ] = pods_api()->get_table_info( pods_var( 'pick_object', $options ), pods_var( 'pick_val', $options ) );
|
Fix array_merge issue with numeric ids in custom value filter
|
pods-framework_pods
|
train
|
a34763248c6cff58944cd1d73b7c487fda1b80ea
|
diff --git a/src/scene.js b/src/scene.js
index <HASH>..<HASH> 100755
--- a/src/scene.js
+++ b/src/scene.js
@@ -78,7 +78,7 @@ export default class Scene {
this.last_selection_render = -1; // frame counter for last selection render pass
this.media_capture = new MediaCapture();
this.selection = null;
- this.introspection = false;
+ this.introspection = (options.introspection === true) ? true : false;
this.resetTime();
this.container = options.container;
|
allow introspection to be passed as scene option
|
tangrams_tangram
|
train
|
7a45cca5aec62a7f1816e38c36b8835b716ae729
|
diff --git a/examples/user_guide/Geometries.ipynb b/examples/user_guide/Geometries.ipynb
index <HASH>..<HASH> 100644
--- a/examples/user_guide/Geometries.ipynb
+++ b/examples/user_guide/Geometries.ipynb
@@ -14,7 +14,7 @@
"import cartopy.feature as cf\n",
"from cartopy import crs as ccrs\n",
"\n",
- "hv.extension('matplotlib', 'bokeh')\n",
+ "gv.extension('matplotlib', 'bokeh')\n",
"\n",
"%output dpi=120 fig='svg'"
]
@@ -77,7 +77,7 @@
"%%opts Feature.Land.110m [scale='110m']\n",
"%%opts Feature.Land.50m [scale='50m']\n",
"(gf.ocean * gf.land().relabel(label='110m') * gv.Feature(graticules, group='Lines') + \n",
- " gf.ocean * gf.land().relabel(label='50m') * gv.Feature(graticules, group='Lines'))"
+ " gf.ocean * gf.land().relabel(label='50m') * gv.Feature(graticules, group='Lines'))"
]
},
{
@@ -270,7 +270,7 @@
"outputs": [],
"source": [
"%%output backend='bokeh'\n",
- "%%opts Polygons [width=600 height=500 tools=['hover']] (cmap='tab20')\n",
+ "%%opts Polygons [width=600 height=400 tools=['hover']] (cmap='tab20')\n",
"gv.Polygons(world, vdims=['continent', 'name', 'pop_est']).redim.range(Latitude=(-60, 90))"
]
},
diff --git a/examples/user_guide/Projections.ipynb b/examples/user_guide/Projections.ipynb
index <HASH>..<HASH> 100644
--- a/examples/user_guide/Projections.ipynb
+++ b/examples/user_guide/Projections.ipynb
@@ -13,7 +13,7 @@
"import geoviews.feature as gf \n",
"from cartopy import crs\n",
"\n",
- "hv.extension('matplotlib', 'bokeh')"
+ "gv.extension('matplotlib', 'bokeh')"
]
},
{
@@ -22,7 +22,7 @@
"source": [
"The GeoViews package provides a library of [HoloViews](https://holoviews.org) Element types which make it very easy to plot data on various geographic projections and other utilities to plot in geographic coordinate systems. Elements are very simple wrappers around the data the only thing that distinguishes a GeoViews element from a HoloViews one is the addition of a ``crs`` parameter, which defines a cartopy coordinate reference system declaring the coordinate system of the data. This allows GeoViews to automatically project the data. By default all elements assume a ``PlateCarree`` projection (also sometimes known as the equirectangular projection), which lets you define the data in longitudes and latitudes.\n",
"\n",
- "By default the plot will follow the specified ``crs`` when using matplotlib:"
+ "By default the plot will follow the specified ``crs`` when using matplotlib and automatically project data to Web mercator when plotting with bokeh."
]
},
{
diff --git a/geoviews/__init__.py b/geoviews/__init__.py
index <HASH>..<HASH> 100644
--- a/geoviews/__init__.py
+++ b/geoviews/__init__.py
@@ -1,6 +1,8 @@
import param
-from holoviews import extension, help, opts, output, renderer, Store, Cycle, Palette # noqa (API import)
+from holoviews import (extension, help, opts, output, renderer, Store, # noqa (API import)
+ Cycle, Palette, Overlay, Layout, NdOverlay, NdLayout,
+ HoloMap, DynamicMap, GridSpace, Dimension)
from .element import (_Element, Feature, Tiles, # noqa (API import)
WMTS, LineContours, FilledContours, Text, Image,
diff --git a/geoviews/plotting/bokeh/__init__.py b/geoviews/plotting/bokeh/__init__.py
index <HASH>..<HASH> 100644
--- a/geoviews/plotting/bokeh/__init__.py
+++ b/geoviews/plotting/bokeh/__init__.py
@@ -1,6 +1,7 @@
import copy
import param
+import numpy as np
import shapely.geometry
from bokeh.models import WMTSTileSource, BBoxTileSource, QUADKEYTileSource
@@ -35,9 +36,9 @@ class TilePlot(GeoPlot):
def get_extents(self, element, ranges):
extents = super(TilePlot, self).get_extents(element, ranges)
- if not self.overlaid:
+ if not self.overlaid and all(e is None or not np.isfinite(e) for e in extents):
global_extent = (-20026376.39, -20048966.10, 20026376.39, 20048966.10)
- return util.max_extents([extents, global_extent])
+ return global_extent
return extents
def get_data(self, element, ranges, style):
diff --git a/geoviews/plotting/bokeh/plot.py b/geoviews/plotting/bokeh/plot.py
index <HASH>..<HASH> 100644
--- a/geoviews/plotting/bokeh/plot.py
+++ b/geoviews/plotting/bokeh/plot.py
@@ -85,7 +85,7 @@ class GeoPlot(ElementPlot):
key = formatter if formatter in ('$x', '$y') else dim
formatters[key] = customjs
formatter += '{custom}'
- tooltips.append((name, formatter))
+ tooltips.append((name, formatter))
hover.tooltips = tooltips
hover.formatters = formatters
|
Minor fixes before <I> release (#<I>)
|
pyviz_geoviews
|
train
|
1b6ed2b65d5f6df6f817f8ad8219dee852eb92f6
|
diff --git a/index.js b/index.js
index <HASH>..<HASH> 100644
--- a/index.js
+++ b/index.js
@@ -1,6 +1,6 @@
'use strict';
-var spawn = require('child_process').spawn;
+var child_process = require('child_process');
var path = require('path');
var say = exports;
var childD;
@@ -69,7 +69,7 @@ say.speak = function(text, voice, speed, callback) {
}
var options = (process.platform === 'win32') ? { windowsVerbatimArguments: true } : undefined;
- childD = spawn(say.speaker, commands, options);
+ childD = child_process.spawn(say.speaker, commands, options);
childD.stdin.setEncoding('ascii');
childD.stderr.setEncoding('ascii');
@@ -134,7 +134,7 @@ say.export = function(text, voice, speed, filename, callback) {
});
}
- childD = spawn(say.speaker, commands);
+ childD = child_process.spawn(say.speaker, commands);
childD.stdin.setEncoding('ascii');
childD.stderr.setEncoding('ascii');
@@ -180,9 +180,12 @@ exports.stop = function(callback) {
// childD.pid + 1 sh process. Kill it and nothing happens. There's also a childD.pid + 2
// aplay process. Kill that and the audio actually stops.
process.kill(childD.pid + 2);
+ } else if (process.platform === 'win32') {
+ childD.stdin.pause();
+ child_process.exec('taskkill /pid ' + childD.pid + ' /T /F')
} else {
childD.stdin.pause();
- childD.kill('SIGINT');
+ childD.kill();
}
childD = null;
|
Switch Stop to use SigTerm and Kill Process Properly On Windows
Issue #<I>
**Bug**
I was seeing `stop` now working when the library was used inside of an electron app.
**Fix**
For osx, use SIGTERM to kill instead of SIGINT.
Also adds windows logic to kill the child process properly
|
Marak_say.js
|
train
|
6510975059b211284ca022e36c1c163c1890226b
|
diff --git a/src/VirtualFileSystem/Wrapper.php b/src/VirtualFileSystem/Wrapper.php
index <HASH>..<HASH> 100644
--- a/src/VirtualFileSystem/Wrapper.php
+++ b/src/VirtualFileSystem/Wrapper.php
@@ -277,7 +277,8 @@ class Wrapper
'gid' => $file->group(),
'atime' => $file->atime(),
'mtime' => $file->mtime(),
- 'ctime' => $file->ctime()
+ 'ctime' => $file->ctime(),
+ 'size' => $file->size()
));
} catch (NotFoundException $e) {
return false;
|
Fixed broken filesize
Noticed that the filesize was incorrect for files.
|
michael-donat_php-vfs
|
train
|
61bfbe9050d024ab196dc6c7ef084a6c4ecf7e4d
|
diff --git a/api.php b/api.php
index <HASH>..<HASH> 100644
--- a/api.php
+++ b/api.php
@@ -186,7 +186,7 @@ class Boots_Form
private function generate_html($Args)
{
- return $Args;
+ return $Args['html'];
}
private function generate_textbox($Args, $flavour = 'text')
|
Require html as an arg so that x arg can be provided for grid
|
wpboots_form
|
train
|
a7e11f3839537cfee4d80c1e6de5a621b7faa143
|
diff --git a/lib/steam/browser/html_unit/actions.rb b/lib/steam/browser/html_unit/actions.rb
index <HASH>..<HASH> 100644
--- a/lib/steam/browser/html_unit/actions.rb
+++ b/lib/steam/browser/html_unit/actions.rb
@@ -63,7 +63,10 @@ module Steam
end
def submit_form(element, options = {})
- respond_to { locate_in_browser(:form, element, options).submit(nil) }
+ respond_to do
+ scope = [:form, element, options]
+ locate_in_browser(:input, :type => 'submit', :within => scope).click
+ end
end
def drag_and_drop(element, options = {})
|
htmlforms can't be submitted any more in htmlunit <I>. this method was removed because it was considered private api.
|
svenfuchs_steam
|
train
|
80a9b738d0536a452f8f16cd5462a932b9f8cd3b
|
diff --git a/lib/standup/settings.rb b/lib/standup/settings.rb
index <HASH>..<HASH> 100755
--- a/lib/standup/settings.rb
+++ b/lib/standup/settings.rb
@@ -1,11 +1,13 @@
if File.exists?('config/standup.yml')
- class Standup::Settings < Settingslogic
- source 'config/standup.yml'
- load!
-
- aws['account_id'].gsub!(/\D/, '') if aws['account_id']
- # keypair_file default to ~/.ssh/keypair_name.pem
- aws['keypair_file'] ||= "#{File.expand_path '~'}/.ssh/#{aws.keypair_name}.pem"
+ module Standup
+ class Settings < Settingslogic
+ source 'config/standup.yml'
+ load!
+
+ aws['account_id'].gsub!(/\D/, '') if aws['account_id']
+ # keypair_file default to ~/.ssh/keypair_name.pem
+ aws['keypair_file'] ||= "#{File.expand_path '~'}/.ssh/#{aws.keypair_name}.pem"
+ end
end
else
Standup.const_set :Settings, ActiveSupport::HashWithIndifferentAccess.new('nodes' => {})
|
Fix for #<I> "standup <I> crashes on startup"
|
cloudcastle_standup
|
train
|
3a258c6dd4f266704895c4e1c4013a26e11c3d24
|
diff --git a/js/deribit.js b/js/deribit.js
index <HASH>..<HASH> 100644
--- a/js/deribit.js
+++ b/js/deribit.js
@@ -196,6 +196,7 @@ module.exports = class deribit extends Exchange {
'get_order_history_by_instrument',
'get_order_margin_by_ids',
'get_order_state',
+ 'get_stop_order_history',
'get_trigger_order_history',
'get_user_trades_by_currency',
'get_user_trades_by_currency_and_time',
|
deribit get_stop_order_history restored for backward-compatibility
|
ccxt_ccxt
|
train
|
0b17242997e87dc4aa4db8bdfeb194b712140e66
|
diff --git a/aws-sdk-core/lib/aws-sdk-core/signers/v4.rb b/aws-sdk-core/lib/aws-sdk-core/signers/v4.rb
index <HASH>..<HASH> 100644
--- a/aws-sdk-core/lib/aws-sdk-core/signers/v4.rb
+++ b/aws-sdk-core/lib/aws-sdk-core/signers/v4.rb
@@ -123,7 +123,7 @@ module Aws
[
request.http_method,
path(request.endpoint),
- normalized_querystring(request.endpoint.query),
+ normalized_querystring(request.endpoint.query || ''),
canonical_headers(request) + "\n",
signed_headers(request),
body_digest
@@ -140,15 +140,14 @@ module Aws
end
def normalized_querystring(querystring)
- if querystring
- querystring.split('&').map do |item|
- if /=/.match(item)
- item
- else
- item + "="
- end
- end.sort.join('&')
+ params = querystring.split('&')
+ params = params.map { |p| p.match(/=/) ? p : p + '=' }
+ params = params.sort do |left, right|
+ left_name = left.split('=').first
+ right_name = right.split('=').first
+ left_name == right_name ? -1 : left_name <=> right_name
end
+ params.join('&')
end
def signed_headers(request)
diff --git a/aws-sdk-core/spec/aws/signers/v4_spec.rb b/aws-sdk-core/spec/aws/signers/v4_spec.rb
index <HASH>..<HASH> 100644
--- a/aws-sdk-core/spec/aws/signers/v4_spec.rb
+++ b/aws-sdk-core/spec/aws/signers/v4_spec.rb
@@ -137,6 +137,7 @@ xyz:1
end
context '#normalized_querystring' do
+
it 'enforces the trailing = character on valueless keys' do
input = "other=&test&x-amz-header=foo"
expected = "other=&test=&x-amz-header=foo"
@@ -150,8 +151,15 @@ xyz:1
actual = signer.normalized_querystring(input)
expect(actual).to eq(expected)
end
- end
+ it 'sorts by name, params with same name stay in the same order' do
+ input = "q.options=abc&q=xyz&q=mno"
+ expected = "q=xyz&q=mno&q.options=abc"
+ actual = signer.normalized_querystring(input)
+ expect(actual).to eq(expected)
+ end
+
+ end
end
end
end
|
Resolved an issue with sigv4 signatures.
The normalized query params were being sorted by "name=value".
This caused an issue when two params were named as such:
"q=value"
"q.options=value"
The sort cause q.options to be first, when it should have been
q, because of the precedence of =. This fix ensures they are
sorted by name only, and that two params with the same name
do not change places.
Fixes #<I>
|
aws_aws-sdk-ruby
|
train
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.