hash
stringlengths
40
40
diff
stringlengths
131
114k
message
stringlengths
7
980
project
stringlengths
5
67
split
stringclasses
1 value
df3cf6679be00a837b904f846c313918758889d3
diff --git a/commands/ping.py b/commands/ping.py index <HASH>..<HASH> 100755 --- a/commands/ping.py +++ b/commands/ping.py @@ -20,7 +20,7 @@ from helpers.misc import recordping from helpers.command import Command -@Command('ping', ['handler', 'target', 'config']) +@Command('ping', ['handler', 'target', 'config', 'nick']) def cmd(send, msg, args): """Ping something. Syntax: !ping <target> @@ -28,9 +28,9 @@ def cmd(send, msg, args): if not msg: send("Ping what?") return - channel = args['target'] if args['target'] != 'private' else args['config']['core']['channel'] + channel = args['target'] if args['target'] != 'private' else args['nick'] # CTCP PING - if msg.lower() in args['handler'].channels[channel].users(): + if "." not in msg: args['handler'].connection.ctcp("PING", msg, " ".join(str(time()).split('.'))) recordping(msg, channel) return
make ping do more ctcp
tjcsl_cslbot
train
d160e92cae5177b5f0fc79a5f13bfcf17315b8dc
diff --git a/lib/client.js b/lib/client.js index <HASH>..<HASH> 100644 --- a/lib/client.js +++ b/lib/client.js @@ -618,22 +618,22 @@ var ace, exec, load, io, join, daffy, restafary, loadRemote; function loadFiles(callback) { exec.series([ function(callback) { - exec.if(load, callback, function() { - loadScript(PREFIX + DIR + 'load/load.js', callback); - }); - }, - - function(callback) { - exec.if(join, callback, function() { - loadScript(PREFIX + '/join/join.js', callback); + var scripts = [ + PREFIX + '/lib/client/loadremote.js' + ]; + + if (!load) + scripts.push(PREFIX + DIR + 'load/load.js'); + + if (!join) + scripts.push(PREFIX + '/join/join.js'); + + exec.if(!scripts.length, callback, function() { + loadScript(scripts, callback); }); }, function(callback) { - load.js(PREFIX + '/lib/client/loadremote.js', callback); - }, - - function(callback) { loadRemote .setPrefix(PREFIX) .load('ace', callback); @@ -658,21 +658,36 @@ var ace, exec, load, io, join, daffy, restafary, loadRemote; }, function() { - callback(null); + callback(); } ]); } - function loadScript(src, callback) { - var element = document.createElement('script'); + function loadScript(srcs, callback) { + var i, + func = function() { + --i; + + if (!i) + callback(); + }; - element.src = src; - element.addEventListener('load', function load() { - callback(null); - element.removeEventListener('load', load); - }); + if (typeof srcs === 'string') + srcs = [srcs]; - document.body.appendChild(element); + i = srcs.length; + + srcs.forEach(function(src) { + var element = document.createElement('script'); + + element.src = src; + element.addEventListener('load', function load() { + func(); + element.removeEventListener('load', load); + }); + + document.body.appendChild(element); + }); } function Story() {
feature(client) speed up: load join.js and load.js in parallel only when they need
cloudcmd_edward
train
15955e62a695a10327455d1b8bb7c6afe07fb282
diff --git a/lib/logger-events/index.js b/lib/logger-events/index.js index <HASH>..<HASH> 100644 --- a/lib/logger-events/index.js +++ b/lib/logger-events/index.js @@ -2,6 +2,8 @@ var Emitter = require('component-emitter'); var utils = require('./utils'); +var Mode = require('./mode'); +var Modifier = require('./modifier'); var Stack = require('./stack'); function create() { @@ -17,7 +19,10 @@ function create() { if (!(this instanceof Logger)) { return new Logger(); } + this.methods = {}; + this.modes = {}; + this.modifiers = {}; this.stack = new Stack(); } @@ -38,7 +43,12 @@ function create() { Logger.prototype._emit = function(name/*, message*/) { var args = [].slice.call(arguments, 1); - this.stack.setName(name); + var logger = this.modifiers[name]; + if (!logger) { + throw new Error('Unable to find logger "' + name + '"'); + } + this.stack.setName(logger); + // console.log(this.stack.items); this.stack.process(function(stats) { stats.args = args; this.emit.call(this, '*', stats); @@ -55,12 +65,12 @@ function create() { * @api public */ - Logger.prototype.create = function(name) { + Logger.prototype.create = function(name, options) { this.methods[name] = null; Object.defineProperty(Logger.prototype, name, { configurable: true, enumerable: true, - get: buildLogger.call(this, name), + get: buildLogger.call(this, name, options), set: function(fn) { this.methods[name] = fn; return fn; @@ -70,22 +80,20 @@ function create() { }; /** - * Add arbitrary modifiers to be used for creating namespaces for logger methods. + * Add arbitrary modes to be used for creating namespaces for logger methods. * - * @param {Array|String} `modifiers` Modifier or array of modifiers to add to the logger. + * @param {String} `mode` Mode to add to the logger. + * @param {Object} `options` Options to describe the mode. * @return {Object} `Logger` for chaining * @api public */ - Logger.prototype.modifiers = function(modifiers) { - modifiers = utils.arrayify(modifiers); - modifiers.forEach(function(modifier) { - Object.defineProperty(Logger.prototype, modifier, { - configurable: true, - enumerable: true, - get: buildModifier.call(this, modifier) - }); - }, this); + Logger.prototype.mode = function(mode, options) { + Object.defineProperty(Logger.prototype, mode, { + configurable: true, + enumerable: true, + get: buildMode.call(this, mode, options) + }); return this; }; @@ -96,39 +104,52 @@ function create() { * @return {Function} getter function to be used in `defineProperty` */ - function buildLogger(name) { + function buildLogger(name, options) { + var opts = utils.extend({name: name, type: 'logger'}, options); + var logger = new Modifier(opts); + this.modifiers[name] = logger; + return function() { - this.stack.addLogger(name); - var logger; + if (utils.hasType(logger.type, 'logger')) { + this.stack.addLogger(logger); + } else { + this.stack.addModifier(logger); + } + var method; if (typeof this.methods[name] === 'function') { - logger = this.methods[name]; + method = this.methods[name]; } else { - logger = function(/*message*/) { + method = function(/*message*/) { var args = [].slice.call(arguments); args.unshift(name); return this._emit.apply(this, args); }.bind(this); + this.methods[name] = method; } - logger.__proto__ = Logger.prototype; - return logger; + method.__proto__ = Logger.prototype; + return method; }.bind(this); } /** - * Create an instance of a modifier object that switches - * the current `modifier` of the logger. + * Create an instance of a mode object that switches + * the current `mode` of the logger. * - * @param {String} `modifier` modifier to set when getting this proeprty. + * @param {String} `mode` mode to set when getting this proeprty. * @return {Function} getter function to be used in `defineProperty` */ - function buildModifier(modifier) { + function buildMode(name, options) { + var opts = utils.extend({name: name, type: 'mode'}, options); + var mode = new Mode(opts); + this.modes[name] = mode; + /* jshint validthis: true */ var self = this; var getter = function() { - self.stack.addModifier(modifier); - var Modifier = function() {}; - var inst = new Modifier(); + self.stack.addMode(mode); + var ModeWrapper = function() {}; + var inst = new ModeWrapper(); inst.__proto__ = Logger.prototype; return inst; };
use classes when creating instances for modes and modifiers
jonschlinkert_verbalize
train
47e0e02297d6a43f8e9cb062e041802f93e4b09b
diff --git a/compiler/util.py b/compiler/util.py index <HASH>..<HASH> 100644 --- a/compiler/util.py +++ b/compiler/util.py @@ -22,7 +22,7 @@ import string import textwrap -_SIMPLE_CHARS = set(string.digits + string.letters + string.punctuation) +_SIMPLE_CHARS = set(string.digits + string.letters + string.punctuation + " ") _ESCAPES = {'\t': r'\t', '\r': r'\r', '\n': r'\n', '"': r'\"'}
make strings with spaces easier to read (#<I>)
google_grumpy
train
83990cd63c6b3963dd69632eb3baf6c276d6c67e
diff --git a/modules/activiti-webapp/src/main/webapp/js/activiti-widget.js b/modules/activiti-webapp/src/main/webapp/js/activiti-widget.js index <HASH>..<HASH> 100644 --- a/modules/activiti-webapp/src/main/webapp/js/activiti-widget.js +++ b/modules/activiti-webapp/src/main/webapp/js/activiti-widget.js @@ -134,7 +134,7 @@ Activiti.widget.createSubmitDialog = function(component, name) { var dialog = new YAHOO.widget.Dialog(component.id + "-" + name, { - fixedcenter: true, + fixedcenter: "contained", visible: false, constraintoviewport: true, modal: true, @@ -426,7 +426,7 @@ Activiti.widget.PopupManager = function() draggable:true, modal: true, constraintoviewport: true, - fixedcenter: true, + fixedcenter: "contained", effect: { effect:YAHOO.widget.ContainerEffect.FADE,
Made sure large images are scrollable as well, I assume they suffer from the same problem as in ACT-<I> & ACT-<I>
Activiti_Activiti
train
49a7671d553ea427d10d5995e94e9d753e7dabc2
diff --git a/Gruntfile.js b/Gruntfile.js index <HASH>..<HASH> 100644 --- a/Gruntfile.js +++ b/Gruntfile.js @@ -29,6 +29,7 @@ module.exports = function(grunt) { all: { src: [ 'tasks/**/*.js', + 'src/**/*.js', 'Gruntfile.js' ] } diff --git a/src/Job.js b/src/Job.js index <HASH>..<HASH> 100644 --- a/src/Job.js +++ b/src/Job.js @@ -93,10 +93,12 @@ Job.prototype.complete = function () { var body = result[1]; if (response.statusCode !== 200) { - throw ['Unexpected response from the Sauce Labs API.', + throw [ + 'Unexpected response from the Sauce Labs API.', request.method + ' ' + request.url, 'Response status: ' + response.statusCode, - 'Response body: ' + JSON.stringify(body)].join('\n'); + 'Response body: ' + JSON.stringify(body) + ].join('\n'); } return body; diff --git a/src/TestRunner.js b/src/TestRunner.js index <HASH>..<HASH> 100644 --- a/src/TestRunner.js +++ b/src/TestRunner.js @@ -172,10 +172,12 @@ TestRunner.prototype.startJob = function (browser, url) { var pollIds = body['js tests']; if (response.statusCode !== 200) { - throw ['Unexpected response from the Sauce Labs API.', + throw [ + 'Unexpected response from the Sauce Labs API.', request.method + ' ' + request.url, 'Response status: ' + response.statusCode, - 'Body: ' + JSON.stringify(body)].join('\n'); + 'Body: ' + JSON.stringify(body) + ].join('\n'); } else if (!pollIds || !pollIds.length) { throw 'Error starting tests through Sauce API: ' + JSON.stringify(body); }
Added the src directory to the coding style checking. Fixed the coding style errors.
axemclion_grunt-saucelabs
train
6529f30cb5bbef7ddb407939cd5d4feb58b51bb2
diff --git a/bundles/org.eclipse.orion.client.git/web/orion/git/gitCommands.js b/bundles/org.eclipse.orion.client.git/web/orion/git/gitCommands.js index <HASH>..<HASH> 100644 --- a/bundles/org.eclipse.orion.client.git/web/orion/git/gitCommands.js +++ b/bundles/org.eclipse.orion.client.git/web/orion/git/gitCommands.js @@ -150,7 +150,7 @@ var exports = {}; exports.handleProgressServiceResponse = function(jsonData, options, serviceRegistry, callback, callee, title){ - if (jsonData && jsonData.status !== 'undefined') { + if (jsonData && jsonData.status !== undefined) { jsonData = translateResponseToStatus(jsonData); } @@ -317,7 +317,7 @@ var exports = {}; exports.handleGitServiceResponse = function(jsonData, serviceRegistry, callback, sshCallback){ - if (jsonData && jsonData.status !== 'undefined') { + if (jsonData && jsonData.status !== undefined) { jsonData = translateResponseToStatus(jsonData); }
Bug <I> - Pull does not display known hosts error
eclipse_orion.client
train
0c5f3bc6daf8e41f98d1baf0a7d2843c6741fa75
diff --git a/lib/natto.rb b/lib/natto.rb index <HASH>..<HASH> 100644 --- a/lib/natto.rb +++ b/lib/natto.rb @@ -117,7 +117,9 @@ module Natto # @return parsing result from <tt>mecab</tt> # @raise [MeCabError] if the <tt>mecab</tt> parser cannot parse the given string <tt>str</tt> def parse(str) - self.mecab_sparse_tostr(@ptr, str) || raise(MeCabError.new(self.mecab_strerror(@ptr))) + self.mecab_nbest_init(@ptr, str) || raise(MeCabError.new(self.mecab_strerror(@ptr))) + self.mecab_nbest_sparse_tostr(@ptr, 3, str) || raise(MeCabError.new(self.mecab_strerror(@ptr))) + #self.mecab_sparse_tostr(@ptr, str) || raise(MeCabError.new(self.mecab_strerror(@ptr))) end # Returns a <tt>Proc</tt> that will properly free resources diff --git a/lib/natto/binding.rb b/lib/natto/binding.rb index <HASH>..<HASH> 100644 --- a/lib/natto/binding.rb +++ b/lib/natto/binding.rb @@ -54,6 +54,8 @@ module Natto attach_function :mecab_new2, [:string], :pointer attach_function :mecab_destroy, [:pointer], :void attach_function :mecab_sparse_tostr, [:pointer, :string], :string + attach_function :mecab_nbest_init, [:pointer, :string], :int + attach_function :mecab_nbest_sparse_tostr, [:pointer, :int, :string], :string attach_function :mecab_strerror, [:pointer],:string attach_function :mecab_dictionary_info, [:pointer], :pointer @@ -75,6 +77,10 @@ module Natto Natto::Binding.mecab_sparse_tostr(ptr, str) end + def mecab_nbest_sparse_tostr(ptr, n, str) + Natto::Binding.mecab_nbest_sparse_tostr(ptr, n, str) + end + def mecab_strerror(ptr) Natto::Binding.mecab_strerror(ptr) end diff --git a/test/natto/tc_binding.rb b/test/natto/tc_binding.rb index <HASH>..<HASH> 100644 --- a/test/natto/tc_binding.rb +++ b/test/natto/tc_binding.rb @@ -25,6 +25,7 @@ class TestNattoBinding < Test::Unit::TestCase :mecab_new2, :mecab_destroy, :mecab_sparse_tostr, + :mecab_nbest_sparse_tostr, :mecab_strerror, :mecab_dictionary_info ].each do |f| assert(@klass.respond_to? f)
On-going development to support nbest option. user: buruzaemon <<EMAIL>> branch 'default' changed lib/natto.rb changed lib/natto/binding.rb changed test/natto/tc_binding.rb
buruzaemon_natto
train
ceeebb24473e9f8109cf82ad3a22ef31ca006e8a
diff --git a/fenixedu/__init__.py b/fenixedu/__init__.py index <HASH>..<HASH> 100644 --- a/fenixedu/__init__.py +++ b/fenixedu/__init__.py @@ -153,11 +153,11 @@ class FenixEduClient(object): else: params = None - r = self._api_public_request(endpoints.DEGREE, {'id': id}) + r = self._api_public_request(endpoints.DEGREE, endpoint_params={'id': id}) return r.json() def get_degree_courses(self, id): - r = self._api_public_request(endpoints.DEGREE_COURSES, {'id': id}) + r = self._api_public_request(endpoints.DEGREE_COURSES, endpoint_params={'id': id}) return r.json() def get_spaces(self): @@ -202,10 +202,6 @@ class FenixEduClient(object): r = self._api_private_request(endpoints.PERSON_EVALUATIONS, user=user) return r.json() - def get_person_payments(self, user): - r = self._api_private_request(endpoints.PERSON + '/' + endpoints.PAYMENTS, user=user) - return r.json() - def enrol_person_in_evaluation(self, user, id, enrol_action = None): if enrol_action: params = {'enrol' : enrol_action} @@ -214,6 +210,10 @@ class FenixEduClient(object): r = self._api_private_request(endpoints.PERSON_EVALUATION, params = params, method = Requests.PUT, user=user, endpoint_params={'id': id}) return r - def get_person_evaluation(self, id, user): + def get_person_evaluation(self, user, id): r = self._api_private_request(endpoints.PERSON_EVALUATION, user=user, endpoint_params={'id': id}) return r + + def get_person_payments(self, user): + r = self._api_private_request(endpoints.PERSON + '/' + endpoints.PAYMENTS, user=user) + return r.json() diff --git a/fenixedu/endpoints.py b/fenixedu/endpoints.py index <HASH>..<HASH> 100644 --- a/fenixedu/endpoints.py +++ b/fenixedu/endpoints.py @@ -25,7 +25,7 @@ GROUPS = 'groups' STUDENTS = 'students' DEGREES = 'degrees' DEGREE = 'degrees/:id' -DEGREE = 'degrees/:id/courses' +DEGREE_COURSES = 'degrees/:id/courses' CALENDAR = 'calendar' PAYMENTS = 'payments' SPACES = 'spaces' diff --git a/setup.py b/setup.py index <HASH>..<HASH> 100644 --- a/setup.py +++ b/setup.py @@ -4,7 +4,7 @@ from distutils.core import setup, Extension -setup(name='fenixedu_api_sdk', +setup(name='fenixedu', version='2.0.1', description='FenixEdu API SDK for python', author='Samuel Coelho',
Fixed some not working endpoints and changed module name to just fenixedu
samfcmc_fenixedu-python-sdk
train
d5f06c508a03d403f1663859d76b61ebb1aded47
diff --git a/lib/client-sessions.js b/lib/client-sessions.js index <HASH>..<HASH> 100644 --- a/lib/client-sessions.js +++ b/lib/client-sessions.js @@ -287,7 +287,7 @@ var cookieSession = function(opts) { raw_session = new Session(req, res, cookies, opts); } catch (x) { // this happens only if there's a big problem - process.nextTick(function() {next("error", x.toString());}); + process.nextTick(function() {next("error: " + x.toString());}); return; } diff --git a/test/all-test.js b/test/all-test.js index <HASH>..<HASH> 100644 --- a/test/all-test.js +++ b/test/all-test.js @@ -1,3 +1,7 @@ +// a NODE_ENV of test will supress console output to stderr which +// connect likes to do when next() is called with a non-falsey error +// message. We test such codepaths here. +process.env['NODE_ENV'] = 'test'; var vows = require("vows"), assert = require("assert"),
improve error message when secure cookies are run on an insecure socket - also surpress this error from getting printed to stderr when tests are being run - closes #<I>
mozilla_node-client-sessions
train
7d8dcd2aae2547f8a0407618b60cba1ece8b8236
diff --git a/src/collection.js b/src/collection.js index <HASH>..<HASH> 100644 --- a/src/collection.js +++ b/src/collection.js @@ -50,6 +50,7 @@ internals.find = function (collection, modelData) { }; Collection.prototype.merge = function (models, options) { + if (!models) return this; if (!Array.isArray(models)) models = [models]; models .filter(function (model) { diff --git a/test/collection.js b/test/collection.js index <HASH>..<HASH> 100644 --- a/test/collection.js +++ b/test/collection.js @@ -70,6 +70,10 @@ describe('Collection', function () { collection.model = Model; }); + it('is a noop if the input is falsy', function () { + expect(collection.merge()).to.have.length(0); + }); + it('updates existing models in the collection in place by ID', function () { collection.push(model); model.matches = sinon.stub().withArgs(data).returns(true);
collection#merge is a noop with falsy input
bendrucker_consumr
train
f03fd2db27a273a40fa63b8c672e67a9f8df5b39
diff --git a/library/src/main/java/com/github/ksoichiro/android/observablescrollview/CacheFragmentStatePagerAdapter.java b/library/src/main/java/com/github/ksoichiro/android/observablescrollview/CacheFragmentStatePagerAdapter.java index <HASH>..<HASH> 100644 --- a/library/src/main/java/com/github/ksoichiro/android/observablescrollview/CacheFragmentStatePagerAdapter.java +++ b/library/src/main/java/com/github/ksoichiro/android/observablescrollview/CacheFragmentStatePagerAdapter.java @@ -43,7 +43,7 @@ public abstract class CacheFragmentStatePagerAdapter extends FragmentStatePagerA public CacheFragmentStatePagerAdapter(FragmentManager fm) { super(fm); - mPages = new SparseArray<Fragment>(); + mPages = new SparseArray<>(); mFm = fm; } diff --git a/library/src/main/java/com/github/ksoichiro/android/observablescrollview/ObservableGridView.java b/library/src/main/java/com/github/ksoichiro/android/observablescrollview/ObservableGridView.java index <HASH>..<HASH> 100644 --- a/library/src/main/java/com/github/ksoichiro/android/observablescrollview/ObservableGridView.java +++ b/library/src/main/java/com/github/ksoichiro/android/observablescrollview/ObservableGridView.java @@ -614,8 +614,7 @@ public class ObservableGridView extends GridView implements Scrollable { public static class HeaderViewGridAdapter implements WrapperListAdapter, Filterable { private final DataSetObservable mDataSetObservable = new DataSetObservable(); private final ListAdapter mAdapter; - static final ArrayList<FixedViewInfo> EMPTY_INFO_LIST = - new ArrayList<FixedViewInfo>(); + static final ArrayList<FixedViewInfo> EMPTY_INFO_LIST = new ArrayList<>(); // This ArrayList is assumed to NOT be null. ArrayList<FixedViewInfo> mHeaderViewInfos; diff --git a/library/src/main/java/com/github/ksoichiro/android/observablescrollview/ScrollUtils.java b/library/src/main/java/com/github/ksoichiro/android/observablescrollview/ScrollUtils.java index <HASH>..<HASH> 100644 --- a/library/src/main/java/com/github/ksoichiro/android/observablescrollview/ScrollUtils.java +++ b/library/src/main/java/com/github/ksoichiro/android/observablescrollview/ScrollUtils.java @@ -67,6 +67,7 @@ public final class ScrollUtils { public static void addOnGlobalLayoutListener(final View view, final Runnable runnable) { ViewTreeObserver vto = view.getViewTreeObserver(); vto.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() { + @SuppressWarnings("deprecation") @Override public void onGlobalLayout() { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) {
Fix some warnings by Android Studio. - Removed redundant type parameter. - Added SuppressWarnings annotation for intentional usage of deprecated method.
ksoichiro_Android-ObservableScrollView
train
9e6dc4a50834cf96e52d16e016dd4381dd9fb1a2
diff --git a/lib/index.js b/lib/index.js index <HASH>..<HASH> 100644 --- a/lib/index.js +++ b/lib/index.js @@ -120,7 +120,7 @@ function sailsGenerate(opts) { - descriptor.paths[path] = {}; + descriptor.paths[path] = descriptor.paths[path] || {}; descriptor.paths[path][route.method] = { description: path, tags: [_.capitalize(matches[1])]
fix: there can be many methods per endpoints
jasancheg_sails-custom-swagger-hook
train
835578cf298f9e643e7210aaa902a537d53db7e3
diff --git a/tests/test_ldlf.py b/tests/test_ldlf.py index <HASH>..<HASH> 100644 --- a/tests/test_ldlf.py +++ b/tests/test_ldlf.py @@ -349,6 +349,29 @@ class TestToAutomaton: assert dfa.accepts([i_a, i_b]) assert not dfa.accepts([i_a, i_a]) + def test_convertible_atomics(self): + parser = self.parser + i_, i_a, i_b, i_ab = self.i_, self.i_a, self.i_b, self.i_ab + + dfa = parser("A").to_automaton() + + assert not dfa.accepts([i_]) + assert dfa.accepts([i_a]) + assert dfa.accepts([i_ab, i_]) + assert not dfa.accepts([]) + + dfa = parser("A & B").to_automaton() + + assert not dfa.accepts([i_a]) + assert dfa.accepts([i_ab, i_]) + assert not dfa.accepts([]) + + dfa = parser("<true>true").to_automaton() + + assert not dfa.accepts([i_a]) + assert dfa.accepts([i_ab, i_]) + assert not dfa.accepts([]) + @pytest.fixture(scope="session", params=ldlf_formulas) def ldlf_formula_automa_pair(request):
New test: LDLf atomics to automaton.
MarcoFavorito_flloat
train
840f7e7d88f1dc2e21941ec3d5e110b423087b6a
diff --git a/src/Symfony/Component/Validator/Constraints/Length.php b/src/Symfony/Component/Validator/Constraints/Length.php index <HASH>..<HASH> 100644 --- a/src/Symfony/Component/Validator/Constraints/Length.php +++ b/src/Symfony/Component/Validator/Constraints/Length.php @@ -57,13 +57,6 @@ class Length extends Constraint parent::__construct($options); - if (null === $this->allowEmptyString) { - $this->allowEmptyString = true; - if (null !== $this->min) { - @trigger_error(sprintf('Using the "%s" constraint with the "min" option without setting the "allowEmptyString" one is deprecated and defaults to true. In 5.0, it will become optional and default to false.', self::class), E_USER_DEPRECATED); - } - } - if (null === $this->min && null === $this->max) { throw new MissingOptionsException(sprintf('Either option "min" or "max" must be given for constraint %s', __CLASS__), ['min', 'max']); } diff --git a/src/Symfony/Component/Validator/Constraints/LengthValidator.php b/src/Symfony/Component/Validator/Constraints/LengthValidator.php index <HASH>..<HASH> 100644 --- a/src/Symfony/Component/Validator/Constraints/LengthValidator.php +++ b/src/Symfony/Component/Validator/Constraints/LengthValidator.php @@ -30,7 +30,11 @@ class LengthValidator extends ConstraintValidator throw new UnexpectedTypeException($constraint, __NAMESPACE__.'\Length'); } - if (null === $value || ('' === $value && $constraint->allowEmptyString)) { + if (null !== $constraint->min && null === $constraint->allowEmptyString) { + @trigger_error(sprintf('Using the "%s" constraint with the "min" option without setting the "allowEmptyString" one is deprecated and defaults to true. In 5.0, it will become optional and default to false.', Length::class), E_USER_DEPRECATED); + } + + if (null === $value || ('' === $value && ($constraint->allowEmptyString ?? true))) { return; } diff --git a/src/Symfony/Component/Validator/Mapping/GenericMetadata.php b/src/Symfony/Component/Validator/Mapping/GenericMetadata.php index <HASH>..<HASH> 100644 --- a/src/Symfony/Component/Validator/Mapping/GenericMetadata.php +++ b/src/Symfony/Component/Validator/Mapping/GenericMetadata.php @@ -12,6 +12,8 @@ namespace Symfony\Component\Validator\Mapping; use Symfony\Component\Validator\Constraint; +use Symfony\Component\Validator\Constraints\Length; +use Symfony\Component\Validator\Constraints\NotBlank; use Symfony\Component\Validator\Constraints\Traverse; use Symfony\Component\Validator\Constraints\Valid; use Symfony\Component\Validator\Exception\ConstraintDefinitionException; @@ -167,6 +169,8 @@ class GenericMetadata implements MetadataInterface */ public function getConstraints() { + $this->configureLengthConstraints($this->constraints); + return $this->constraints; } @@ -187,9 +191,10 @@ class GenericMetadata implements MetadataInterface */ public function findConstraints($group) { - return isset($this->constraintsByGroup[$group]) - ? $this->constraintsByGroup[$group] - : []; + $constraints = $this->constraintsByGroup[$group] ?? []; + $this->configureLengthConstraints($constraints); + + return $constraints; } /** @@ -207,4 +212,26 @@ class GenericMetadata implements MetadataInterface { return $this->traversalStrategy; } + + private function configureLengthConstraints(array $constraints): void + { + $allowEmptyString = true; + + foreach ($constraints as $constraint) { + if ($constraint instanceof NotBlank) { + $allowEmptyString = false; + break; + } + } + + if ($allowEmptyString) { + return; + } + + foreach ($constraints as $constraint) { + if ($constraint instanceof Length && null === $constraint->allowEmptyString) { + $constraint->allowEmptyString = false; + } + } + } }
[Validator] Set Length::$allowEmptyString to false when a NotBlank contraint is defined
symfony_symfony
train
26d30f3d1a8c0caca854f7040d07555c6f794b0f
diff --git a/mwparserfromhell/parser/tokenizer.py b/mwparserfromhell/parser/tokenizer.py index <HASH>..<HASH> 100644 --- a/mwparserfromhell/parser/tokenizer.py +++ b/mwparserfromhell/parser/tokenizer.py @@ -461,7 +461,7 @@ class Tokenizer(object): return padding def _actually_handle_chunk(self, chunks, is_new): - if is_new: + if is_new and not self._context & contexts.TAG_OPEN_ATTR_BODY_QUOTED: padding = 0 while chunks: if chunks[0] == "": @@ -472,6 +472,15 @@ class Tokenizer(object): self._write(tokens.TagAttrStart(padding=" " * padding)) if chunks: chunk = chunks.pop(0) + if self._context & contexts.TAG_OPEN_ATTR_BODY: + self._context ^= contexts.TAG_OPEN_ATTR_BODY + self._context |= contexts.TAG_OPEN_ATTR_NAME + if self._context & contexts.TAG_OPEN_ATTR_BODY_QUOTED: + if re.search(r'[^\\]"', chunk[:-1]): + self._fail_route() + if re.search(r'[^\\]"$', chunk): + self._write_text(chunk[:-1]) + return self._pop() # Back to _handle_tag_attribute_body() self._write_text(chunk) def _handle_tag_chunk(self, text): @@ -490,26 +499,35 @@ class Tokenizer(object): self._actually_handle_chunk(chunks, True) is_new = False while chunks: - self._actually_handle_chunk(chunks, is_new) + should_exit = self._actually_handle_chunk(chunks, is_new) + if should_exit: + return should_exit is_new = True def _handle_tag_attribute_body(self): self._context ^= contexts.TAG_OPEN_ATTR_NAME self._context |= contexts.TAG_OPEN_ATTR_BODY - self._write(TagAttrEquals()) + self._write(tokens.TagAttrEquals()) next = self._read(1) if next not in self.MARKERS and next.startswith('"'): if re.search(r'[^\\]"$', next[1:]): if not re.search(r'[^\\]"', next[1:-1]): - self._write(TagAttrQuote()) + self._write(tokens.TagAttrQuote()) self._write_text(next[1:-1]) self._head += 1 else: if not re.search(r'[^\\]"', next[1:]): - self._push(contexts.TAG_OPEN_ATTR_BODY_QUOTED) - self._write(TagAttrQuote()) - self._write_text(next[1:]) self._head += 1 + reset = self._head + try: + attr = self._parse(contexts.TAG_OPEN_ATTR_BODY_QUOTED) + except BadRoute: + self._head = reset + self._write_text(next) + else: + self._write(tokens.TagAttrQuote()) + self._write_text(next[1:]) + self._write_all(attr) def _handle_tag_close_open(self): padding = self._actually_close_tag_opening() @@ -543,7 +561,9 @@ class Tokenizer(object): this = self._read() if this not in self.MARKERS: if self._context & contexts.TAG_OPEN: - self._handle_tag_chunk(this) + should_exit = self._handle_tag_chunk(this) + if should_exit: + return should_exit else: self._write_text(this) self._head += 1 @@ -593,6 +613,8 @@ class Tokenizer(object): elif this == "=" and not self._global & contexts.GL_HEADING: if self._read(-1) in ("\n", self.START): self._parse_heading() + elif self._context & contexts.TAG_OPEN_ATTR_NAME: + self._handle_tag_attribute_body() else: self._write_text("=") elif this == "=" and self._context & contexts.HEADING: @@ -618,7 +640,7 @@ class Tokenizer(object): self._handle_tag_close_open() elif this == "/" and next == ">": return self._handle_tag_selfclose() - elif this == "=": + elif this == "=" and self._context & contexts.TAG_OPEN_ATTR_NAME: self._handle_tag_attribute_body() elif this == "<" and next == "/" and ( self._context & contexts.TAG_BODY):
Seems to be working for quoted attributes now.
earwig_mwparserfromhell
train
dd046161430d7105a4a7c4dd15ed5229eeb02927
diff --git a/tests/test_reqparse.py b/tests/test_reqparse.py index <HASH>..<HASH> 100644 --- a/tests/test_reqparse.py +++ b/tests/test_reqparse.py @@ -26,7 +26,7 @@ class ReqParseTestCase(unittest.TestCase): req = Mock(['values']) req.values = MultiDict([('foo', 'three')]) parser.parse_args(req) - expected = '{"foo": "(Bad choice) three is not a valid choice"}' + expected = {'foo': '(Bad choice) three is not a valid choice'} abort.assert_called_with(400, message=expected) @patch('flask_restful.abort', side_effect=exceptions.BadRequest('Bad Request')) @@ -374,8 +374,9 @@ class ReqParseTestCase(unittest.TestCase): except exceptions.BadRequest as e: message = e.data['message'] - self.assertEquals(message, (u'{"foo": "Missing required parameter in the ' - 'post body or the query string"}')) + self.assertEquals(message, ({'foo': 'Missing required parameter in ' + 'the post body or the query ' + 'string'})) parser = RequestParser() parser.add_argument("bar", required=True, location=['values', 'cookies']) @@ -384,9 +385,10 @@ class ReqParseTestCase(unittest.TestCase): parser.parse_args(req) except exceptions.BadRequest as e: message = e.data['message'] - self.assertEquals(message, (u'{"bar": "Missing required parameter ' - 'in the post body or the query string or the ' - 'request\'s cookies"}')) + self.assertEquals(message, ({'bar': 'Missing required parameter in ' + 'the post body or the query ' + 'string or the request\'s ' + 'cookies'})) def test_parse_error_bundling(self): app = Flask(__name__) @@ -403,11 +405,12 @@ class ReqParseTestCase(unittest.TestCase): parser.parse_args(req) except exceptions.BadRequest as e: message = e.data['message'] - error_message = ('{"foo": "Missing required parameter in the ' - 'post body or the query string", "bar": "Missing required ' - 'parameter in the post body or the query string or the ' - 'request\'s cookies"}') - self.assertEquals(message, json.loads(error_message)) + error_message = {'foo': 'Missing required parameter in the post ' + 'body or the query string', + 'bar': 'Missing required parameter in the post ' + 'body or the query string or the ' + 'request\'s cookies'} + self.assertEquals(message, error_message) def test_parse_error_bundling_w_parser_arg(self): app = Flask(__name__) @@ -424,11 +427,12 @@ class ReqParseTestCase(unittest.TestCase): parser.parse_args(req) except exceptions.BadRequest as e: message = e.data['message'] - error_message = ('{"foo": "Missing required parameter in the ' - 'post body or the query string", "bar": "Missing required ' - 'parameter in the post body or the query string or the ' - 'request\'s cookies"}') - self.assertEquals(message, json.loads(error_message)) + error_message = {'foo': 'Missing required parameter in the post ' + 'body or the query string', + 'bar': 'Missing required parameter in the post ' + 'body or the query string or the request\'s ' + 'cookies'} + self.assertEquals(message, error_message) def test_parse_default_append(self): req = Request.from_values("/bubble")
Fixed tests to reflect the changes in error bundling/jsonifying
flask-restful_flask-restful
train
fa36dcbe098ad6f491507213223dc278ccc0d24f
diff --git a/examples/exception_monitoring.py b/examples/exception_monitoring.py index <HASH>..<HASH> 100644 --- a/examples/exception_monitoring.py +++ b/examples/exception_monitoring.py @@ -23,7 +23,7 @@ class CustomHandler(Handler): # and can do anything with it (log, send to external service, etc) # Some exceptions are trivial and built into Sanic (404s, etc) - if not issubclass(type(exception), SanicException): + if not isinstance(exception, SanicException): print(exception) # Then, we must finish handling the exception by returning diff --git a/sanic/exceptions.py b/sanic/exceptions.py index <HASH>..<HASH> 100644 --- a/sanic/exceptions.py +++ b/sanic/exceptions.py @@ -188,7 +188,7 @@ class Handler: def default(self, request, exception): log.error(format_exc()) - if issubclass(type(exception), SanicException): + if isinstance(exception, SanicException): return text( 'Error: {}'.format(exception), status=getattr(exception, 'status_code', 500)) diff --git a/tests/test_middleware.py b/tests/test_middleware.py index <HASH>..<HASH> 100644 --- a/tests/test_middleware.py +++ b/tests/test_middleware.py @@ -51,7 +51,7 @@ def test_middleware_response(): assert response.text == 'OK' assert type(results[0]) is Request assert type(results[1]) is Request - assert issubclass(type(results[2]), HTTPResponse) + assert isinstance(results[2], HTTPResponse) def test_middleware_override_request(): diff --git a/tests/test_views.py b/tests/test_views.py index <HASH>..<HASH> 100644 --- a/tests/test_views.py +++ b/tests/test_views.py @@ -152,7 +152,7 @@ def test_with_middleware_response(): assert response.text == 'I am get method' assert type(results[0]) is Request assert type(results[1]) is Request - assert issubclass(type(results[2]), HTTPResponse) + assert isinstance(results[2], HTTPResponse) def test_with_custom_class_methods():
Use ``isinstance(`` instead of ``issubclass(type(`` When we already have an `instance` it's less typing and faster to use `isinstance`.
huge-success_sanic
train
5977f63d4193af6dd8528db008d915fd2190c932
diff --git a/influxdb/_dataframe_client.py b/influxdb/_dataframe_client.py index <HASH>..<HASH> 100644 --- a/influxdb/_dataframe_client.py +++ b/influxdb/_dataframe_client.py @@ -87,7 +87,7 @@ class DataFrameClient(InfluxDBClient): def _to_dataframe(self, json_result, time_precision): dataframe = pd.DataFrame(data=json_result['points'], columns=json_result['columns']) - if 'sequence_number' in dataframe.keys(): + if 'sequence_number' in dataframe: dataframe.sort(['time', 'sequence_number'], inplace=True) else: dataframe.sort(['time'], inplace=True) diff --git a/influxdb/client.py b/influxdb/client.py index <HASH>..<HASH> 100755 --- a/influxdb/client.py +++ b/influxdb/client.py @@ -127,12 +127,12 @@ class InfluxDBClient(object): def format_query_response(response): """Returns a list of items from a query response""" series = {} - if 'results' in response.keys(): + if 'results' in response: for result in response['results']: - if 'series' in result.keys(): + if 'series' in result: for row in result['series']: items = [] - if 'name' in row.keys(): + if 'name' in row: name = row['name'] tags = row.get('tags', None) if tags: @@ -141,7 +141,7 @@ class InfluxDBClient(object): series[name] = items else: series = items # Special case for system queries. - if 'columns' in row.keys() and 'values' in row.keys(): + if 'columns' in row and 'values' in row: columns = row['columns'] for value in row['values']: item = {}
Pythonic: `x in dict.keys()` => `x in dict`
influxdata_influxdb-python
train
21d18138486776a3f3f33fcbfdd5486670cd2645
diff --git a/lib/codemirror.js b/lib/codemirror.js index <HASH>..<HASH> 100644 --- a/lib/codemirror.js +++ b/lib/codemirror.js @@ -1581,6 +1581,21 @@ window.CodeMirror = (function() { else if (dy == null) dy = e.wheelDelta; var scroll = cm.display.scroller; + // On some browsers, horizontal scrolling will cause redraws to + // happen before the gutter has been realigned, causing it to + // wriggle around in a most unseemly way. When we have an + // estimated pixels/delta value, we just handle horizontal + // scrolling entirely here. It'll be slightly off from native, but + // better than glitching out. + if (dx && !gecko && !opera && wheelPixelsPerUnit != null) { + if (dy) + setScrollTop(cm, Math.max(0, Math.min(scroll.scrollTop + dy * wheelPixelsPerUnit, scroll.scrollHeight - scroll.clientHeight))); + setScrollLeft(cm, Math.max(0, Math.min(scroll.scrollLeft + dx * wheelPixelsPerUnit, scroll.scrollWidth - scroll.clientWidth))); + e_preventDefault(e); + wheelStartX = null; // Abort measurement, if in progress + return; + } + if (dy && wheelPixelsPerUnit != null) { var pixels = dy * wheelPixelsPerUnit; var top = cm.view.scrollTop, bot = top + cm.display.wrapper.clientHeight; @@ -1594,11 +1609,13 @@ window.CodeMirror = (function() { } updateDisplay(cm, [], {top: top, bottom: bot}); } + if (wheelSamples < 20) { if (wheelStartX == null) { wheelStartX = scroll.scrollLeft; wheelStartY = scroll.scrollTop; wheelDX = dx; wheelDY = dy; setTimeout(function() { + if (wheelStartX == null) return; var movedX = scroll.scrollLeft - wheelStartX; var movedY = scroll.scrollTop - wheelStartY; var sample = (movedY && wheelDY && movedY / wheelDY) ||
Handle horizontal scroll directly, if ratio known, on browsers where needed Issue #<I>
codemirror_CodeMirror
train
0c49c675de62c722248a414e0339e77e4a56d9fe
diff --git a/src/symbolfunctions/modifier.js b/src/symbolfunctions/modifier.js index <HASH>..<HASH> 100644 --- a/src/symbolfunctions/modifier.js +++ b/src/symbolfunctions/modifier.js @@ -4,6 +4,9 @@ export default function modifier() { var drawArray1 = []; var drawArray2 = []; var bbox = new ms.BBox(this.metadata.baseGeometry.bbox); // clone the bbox + var color = this.style.frameColor + ? this.style.frameColor[this.metadata.affiliation] + : this.colors.iconColor[this.metadata.affiliation]; var gbbox = new ms.BBox(); // bounding box for the added geometries var geom; if (this.metadata.headquarters) { @@ -124,7 +127,7 @@ export default function modifier() { gapFiller = 2; geom = { type: "path", - fill: this.colors.frameColor[this.metadata.affiliation], + fill: color, d: "M85," + (bbox.y1 + gapFiller - this.style.strokeWidth / 2) + @@ -210,7 +213,7 @@ export default function modifier() { g: [ { type: "circle", - fill: this.colors.frameColor[this.metadata.affiliation], + fill: color, cx: 100, cy: bbox.y1 - 20, r: 7.5 @@ -222,14 +225,14 @@ export default function modifier() { g: [ { type: "circle", - fill: this.colors.frameColor[this.metadata.affiliation], + fill: color, cx: 115, cy: bbox.y1 - 20, r: 7.5 }, { type: "circle", - fill: this.colors.frameColor[this.metadata.affiliation], + fill: color, cx: 85, cy: bbox.y1 - 20, r: 7.5 @@ -241,21 +244,21 @@ export default function modifier() { g: [ { type: "circle", - fill: this.colors.frameColor[this.metadata.affiliation], + fill: color, cx: 100, cy: bbox.y1 - 20, r: 7.5 }, { type: "circle", - fill: this.colors.frameColor[this.metadata.affiliation], + fill: color, cx: 70, cy: bbox.y1 - 20, r: 7.5 }, { type: "circle", - fill: this.colors.frameColor[this.metadata.affiliation], + fill: color, cx: 130, cy: bbox.y1 - 20, r: 7.5 @@ -572,7 +575,7 @@ export default function modifier() { g: [ { type: "path", - fill: this.colors.frameColor[this.metadata.affiliation], + fill: color, d: "M 50,5 l 100,0 M50,0 l10,0 0,10 -10,0 z M150,0 l-10,0 0,10 10,0 z M100,0 l5,5 -5,5 -5,-5 z" } @@ -583,7 +586,7 @@ export default function modifier() { g: [ { type: "path", - fill: this.colors.frameColor[this.metadata.affiliation], + fill: color, d: "M 50,5 l 100,0 M50,0 l10,0 0,10 -10,0 z M150,0 l-10,0 0,10 10,0 z M105,0 l-10,0 0,10 10,0 z M75,0 l5,5 -5,5 -5,-5 z M125,0 l5,5 -5,5 -5,-5 z" } @@ -632,15 +635,13 @@ export default function modifier() { //Assign fill, stroke and stroke-width for (var i = 0; i < drawArray1.length; i++) { if (!drawArray1[i].hasOwnProperty("fill")) drawArray1[i].fill = false; - if (!drawArray1[i].hasOwnProperty("stroke")) - drawArray1[i].stroke = this.colors.frameColor[this.metadata.affiliation]; + if (!drawArray1[i].hasOwnProperty("stroke")) drawArray1[i].stroke = color; if (!drawArray1[i].hasOwnProperty("strokewidth")) drawArray1[i].strokewidth = this.style.strokeWidth; } for (i = 0; i < drawArray2.length; i++) { if (!drawArray2[i].hasOwnProperty("fill")) drawArray2[i].fill = false; - if (!drawArray2[i].hasOwnProperty("stroke")) - drawArray2[i].stroke = this.colors.frameColor[this.metadata.affiliation]; + if (!drawArray2[i].hasOwnProperty("stroke")) drawArray2[i].stroke = color; if (!drawArray2[i].hasOwnProperty("strokewidth")) drawArray2[i].strokewidth = this.style.strokeWidth; }
Fix handling of frame color override
spatialillusions_milsymbol
train
cc1cd22471f39f9c3c56d105486feebd336a1fb9
diff --git a/salt/states/dockerio.py b/salt/states/dockerio.py index <HASH>..<HASH> 100644 --- a/salt/states/dockerio.py +++ b/salt/states/dockerio.py @@ -961,17 +961,40 @@ def running(name, create = __salt__['docker.create_container'] image_name = _get_image_name(image, tag) iinfos = ins_image(image_name) + image_exists = iinfos['status'] + + if not image_exists: + return _invalid(comment='image "{0}" does not exists'.format(image_name)) + cinfos = ins_container(name) already_exists = cinfos['status'] - image_exists = iinfos['status'] - is_running = False - if already_exists: - is_running = __salt__['docker.is_running'](container) + already_exists_with_same_image = ( + # if container is known by name, + already_exists + # and the container is based on expected image, + and cinfos['out']['Image'] == iinfos['out']['Id'] + # then assume it already exists. + ) + + is_running = __salt__['docker.is_running'](container) + # if container exists but is not started, try to start it - if already_exists and (is_running or not start): + if already_exists_with_same_image and (is_running or not start): return _valid(comment='container {0!r} already exists'.format(name)) - if not image_exists: - return _invalid(comment='image "{0}" does not exist'.format(image)) + if not already_exists_with_same_image and already_exists: + # Outdated container: It means it runs against an old image. + # We're gonna have to stop and remove the old container, to let + # the name available for the new one. + if is_running: + stop_status = __salt__['docker.stop'](name) + if not stop_status['status']: + return _invalid(comment='Failed to stop outdated container {0!r}'.format(name)) + + remove_status = __salt__['docker.remove_container'](name) + if not remove_status['status']: + return _invalid(comment='Failed to remove outdated container {0!r}'.format(name)) + # now it's clear, the name is available for the new container + # parse input data exposeports, bindports, contvolumes, bindvolumes, denvironment, changes = [], {}, [], {}, {}, [] if not ports:
improve detection of changes of docker.running If a container is running with an outdated image, then we stop it and destroy it, before create and start a new one with the same name.
saltstack_salt
train
73fb9500e3d565c94bc53e80fe3fbf09ea8d25e6
diff --git a/photutils/segmentation/properties.py b/photutils/segmentation/properties.py index <HASH>..<HASH> 100644 --- a/photutils/segmentation/properties.py +++ b/photutils/segmentation/properties.py @@ -1045,19 +1045,18 @@ class SourceProperties: determined using bilinear interpolation. """ - from scipy.ndimage import map_coordinates - if self._background is not None: - # centroid can still be NaN if all data values are <= 0 - if (self._is_completely_masked or - np.any(~np.isfinite(self.centroid))): + from scipy.ndimage import map_coordinates + + # centroid can be NaN if segment is completely masked or if + # all data values are <= 0 + if np.any(~np.isfinite(self.centroid)): return np.nan * self._data_unit # unit for table else: value = map_coordinates(self._background, [[self.ycentroid.value], [self.xcentroid.value]], order=1, mode='nearest')[0] - return value * self._data_unit else: return None @@ -1644,6 +1643,24 @@ class SourceCatalog: return [None] * len(self._data) @lazyproperty + def background_at_centroid(self): + background = self._data[0]._background + if background is not None: + from scipy.ndimage import map_coordinates + + values = map_coordinates(background, + [[self.ycentroid.value], + [self.xcentroid.value]], order=1, + mode='nearest')[0] + + mask = np.isfinite(self.xcentroid) & np.isfinite(self.ycentroid) + values[~mask] = np.nan + + return values * self._data[0]._data_unit + else: + return self._none_list + + @lazyproperty def sky_centroid(self): if self.wcs is not None: # For a large catalog, it's much faster to calculate world
Add background_at_centroid SourceCatalog method for performance
astropy_photutils
train
54bce9bdedac1532d540631629c0c6461457ce3a
diff --git a/github_release.py b/github_release.py index <HASH>..<HASH> 100755 --- a/github_release.py +++ b/github_release.py @@ -99,7 +99,16 @@ def patch_release(repo_name, current_tag_name, **values): "draft": release["draft"], "prerelease": release["prerelease"] } + + updated = [] + for key in data: + if key in values and data[key] != values[key]: + updated.append("%s: '%s' -> '%s'" % (key, data[key], values[key])) + if updated: + print("updating release [%s]: \n %s" % (current_tag_name, "\n ".join(updated))) + data.update(values) + response = _request('PATCH', 'https://api.github.com/repos/{0}/releases/{1}'.format( repo_name, release['id']), data=json.dumps(data),
style: Update "gh_release_edit" to print summary of changes
j0057_github-release
train
e28cd40d7b4ac1e98a370cc6dcacedec6ef1d5b0
diff --git a/modules/activiti-engine/src/main/java/org/activiti/engine/impl/bpmn/parser/handler/EventBasedGatewayParseHandler.java b/modules/activiti-engine/src/main/java/org/activiti/engine/impl/bpmn/parser/handler/EventBasedGatewayParseHandler.java index <HASH>..<HASH> 100644 --- a/modules/activiti-engine/src/main/java/org/activiti/engine/impl/bpmn/parser/handler/EventBasedGatewayParseHandler.java +++ b/modules/activiti-engine/src/main/java/org/activiti/engine/impl/bpmn/parser/handler/EventBasedGatewayParseHandler.java @@ -31,6 +31,9 @@ public class EventBasedGatewayParseHandler extends AbstractActivityBpmnParseHand protected void executeParse(BpmnParse bpmnParse, EventGateway gateway) { ActivityImpl activity = createActivityOnCurrentScope(bpmnParse, gateway, BpmnXMLConstants.ELEMENT_GATEWAY_EVENT); activity.setActivityBehavior(bpmnParse.getActivityBehaviorFactory().createEventBasedGatewayActivityBehavior(gateway)); + + activity.setAsync(gateway.isAsynchronous()); + activity.setExclusive(!gateway.isNotExclusive()); activity.setScope(true); } diff --git a/modules/activiti-engine/src/main/java/org/activiti/engine/impl/bpmn/parser/handler/ExclusiveGatewayParseHandler.java b/modules/activiti-engine/src/main/java/org/activiti/engine/impl/bpmn/parser/handler/ExclusiveGatewayParseHandler.java index <HASH>..<HASH> 100644 --- a/modules/activiti-engine/src/main/java/org/activiti/engine/impl/bpmn/parser/handler/ExclusiveGatewayParseHandler.java +++ b/modules/activiti-engine/src/main/java/org/activiti/engine/impl/bpmn/parser/handler/ExclusiveGatewayParseHandler.java @@ -30,6 +30,10 @@ public class ExclusiveGatewayParseHandler extends AbstractActivityBpmnParseHandl protected void executeParse(BpmnParse bpmnParse, ExclusiveGateway gateway) { ActivityImpl activity = createActivityOnCurrentScope(bpmnParse, gateway, BpmnXMLConstants.ELEMENT_GATEWAY_EXCLUSIVE); + + activity.setAsync(gateway.isAsynchronous()); + activity.setExclusive(!gateway.isNotExclusive()); + activity.setActivityBehavior(bpmnParse.getActivityBehaviorFactory().createExclusiveGatewayActivityBehavior(gateway)); }
Exclusive and event based gateway can be async as well
Activiti_Activiti
train
c398e226a76135904d42c5816d982c8df2f0e9e4
diff --git a/janome/fst.py b/janome/fst.py index <HASH>..<HASH> 100644 --- a/janome/fst.py +++ b/janome/fst.py @@ -336,26 +336,6 @@ def compileFST(fst): return b''.join(arcs) -class Arc(object): - u""" - Arc class - """ - def __init__(self): - self.flag = 0 - self.label = 0 - self.output = bytes() - self.final_output = [b''] - self.target = 0 - - def __str__(self): - if PY3: - return "flag=%d, label=%s, target=%d, output=%s, final_output=%s" \ - % (self.flag, self.label, self.target, str(self.output), str(self.final_output)) - else: - return "flag=%d, label=%s, target=%d, output=%s, final_output=%s" \ - % (self.flag, self.label, self.target, unicode(self.output, encoding='utf8'), unicode(self.final_output, encoding='utf8')) - - class Matcher(object): def __init__(self, dict_data, max_cache_size=5000, max_cached_word_len=15): if dict_data: @@ -394,17 +374,18 @@ class Matcher(object): while pos < self.data_len: arc, incr = self.next_arc(pos) - if arc.flag & FLAG_FINAL_ARC: + flag, label, output, final_output, target = arc + if flag & FLAG_FINAL_ARC: # accepted accept = True - for out in arc.final_output: + for out in final_output: if common_prefix_match or i >= word_len: if PY3: outputs.add(bytes(buf + out)) else: outputs.add(str(buf + out)) pos += incr - if arc.flag & FLAG_LAST_ARC or i > word_len: + if flag & FLAG_LAST_ARC or i > word_len: break if i < self.max_cached_word_len: with self.lock: @@ -415,22 +396,22 @@ class Matcher(object): # check cache size if len(self.cache) >= self.max_cache_size: self.cache.popitem(last=False) - elif arc.flag & FLAG_LAST_ARC: + elif flag & FLAG_LAST_ARC: if i >= word_len: break - if word[i] == arc.label: - buf += arc.output + if word[i] == label: + buf += output i += 1 - pos += arc.target + pos += target else: break else: if i >= word_len: break - if word[i] == arc.label: - buf += arc.output + if word[i] == label: + buf += output i += 1 - pos += arc.target + pos += target else: pos += incr return accept, set(o for o in outputs if o) @@ -439,11 +420,13 @@ class Matcher(object): assert addr >= 0 # arc address pos = addr - # create the arc - arc = Arc() + # the arc + label = 0 + output = bytes() + final_output = [b''] + target = 0 # read flag flag = unpack('b', self.data[pos:pos+1])[0] - arc.flag = flag pos += 1 if flag & FLAG_FINAL_ARC: if flag & FLAG_ARC_HAS_FINAL_OUTPUT: @@ -457,32 +440,28 @@ class Matcher(object): if output_size: buf.append(self.data[pos:pos+output_size]) pos += output_size - arc.final_output = buf + final_output = buf else: # read label if PY3: label = unpack('B', self.data[pos:pos+1])[0] else: label = unpack('c', self.data[pos:pos+1])[0] - arc.label = label pos += 1 if flag & FLAG_ARC_HAS_OUTPUT: # read output output_size = unpack('I', self.data[pos:pos+4])[0] pos += 4 output = self.data[pos:pos+output_size] - arc.output = output pos += output_size # read target's (relative) address target = unpack('I', self.data[pos:pos+4])[0] - arc.target = target pos += 4 incr = pos - addr - # logging.debug(arc) + arc = (flag, label, output, final_output, target) return arc, incr - if __name__ == '__main__': logging.basicConfig(level=logging.DEBUG) inputs1 = [
Use tuple instead of Arc() object to reduce object creation cost.
mocobeta_janome
train
5037f87003488a12efc047e3b15c56b24e718f31
diff --git a/nodeconductor/iaas/log.py b/nodeconductor/iaas/log.py index <HASH>..<HASH> 100644 --- a/nodeconductor/iaas/log.py +++ b/nodeconductor/iaas/log.py @@ -133,6 +133,10 @@ class AggregateAlertFilter(BaseExternalFilter): """ def filter(self, request, queryset, view): + # Don't apply filter if aggregate is not specified + if 'aggregate' not in request.query_params: + return queryset + from nodeconductor.iaas import serializers as iaas_serializers, models as iaas_models aggregate_serializer = iaas_serializers.StatsAggregateSerializer(data=request.query_params) diff --git a/nodeconductor/logging/utils.py b/nodeconductor/logging/utils.py index <HASH>..<HASH> 100644 --- a/nodeconductor/logging/utils.py +++ b/nodeconductor/logging/utils.py @@ -4,4 +4,11 @@ from nodeconductor.logging import log def get_loggable_models(): - return [m for m in django_models.get_models() if issubclass(m, log.LoggableMixin)] + models = [m for m in django_models.get_models() if issubclass(m, log.LoggableMixin)] + + # Add subclasses of abstract loggable models (eg Service) + for model in log.LoggableMixin.__subclasses__(): + if model._meta.abstract: + models.extend(model.__subclasses__()) + + return models diff --git a/nodeconductor/openstack/models.py b/nodeconductor/openstack/models.py index <HASH>..<HASH> 100644 --- a/nodeconductor/openstack/models.py +++ b/nodeconductor/openstack/models.py @@ -5,7 +5,7 @@ from nodeconductor.structure import models as structure_models from nodeconductor.logging.log import LoggableMixin -class OpenStackService(LoggableMixin, structure_models.Service): +class OpenStackService(structure_models.Service): projects = models.ManyToManyField( structure_models.Project, related_name='openstack_services', through='OpenStackServiceProjectLink') diff --git a/nodeconductor/structure/models.py b/nodeconductor/structure/models.py index <HASH>..<HASH> 100644 --- a/nodeconductor/structure/models.py +++ b/nodeconductor/structure/models.py @@ -431,7 +431,7 @@ class ServiceSettings(core_models.UuidMixin, core_models.NameMixin, core_models. @python_2_unicode_compatible -class Service(core_models.UuidMixin, core_models.NameMixin): +class Service(core_models.UuidMixin, core_models.NameMixin, LoggableMixin): """ Base service class. """ class Meta(object):
Make services loggable (NC-<I>)
opennode_waldur-core
train
8c44fada4fa020b38a62e141ab611997452fc122
diff --git a/pymagicc/api.py b/pymagicc/api.py index <HASH>..<HASH> 100644 --- a/pymagicc/api.py +++ b/pymagicc/api.py @@ -324,6 +324,91 @@ class MAGICCBase(object): stepsperyear=12, ) + def set_output_variables(self, write_ascii=True, write_binary=False, **kwargs): + """ + Writes the configuration to control what variables are written + + # Parameters + write_binary (bool): If true, MAGICC is configured to write output files as human readable ascii files. + write_ascii (bool): If true, MAGICC is configured to write binary output files. These files are much faster + to process, but are not human readable. + kwargs: List of variables to write out. A list of possible options are as follows. This + may not be a complete list + + 'emissions', + 'gwpemissions', + 'sum_gwpemissions', + 'concentrations', + 'carboncycle', + 'forcing', + 'surfaceforcing', + 'permafrost', + 'temperature', + 'sealevel', + 'parameters', + 'misc', + 'lifetimes', + 'timeseriesmix', + 'rcpdata', + 'summaryidx', + 'inverseemis', + 'tempoceanlayers', + 'oceanarea', + 'heatuptake', + 'warnings', + 'precipinput', + 'aogcmtuning', + 'ccycletuning', + 'observationaltuning', + 'keydata_1', + 'keydata_2' + """ + + assert write_ascii or write_binary, 'write_binary and/or write_ascii must be configured' + if write_binary and write_ascii: + ascii_binary = 'BOTH' + elif write_ascii: + ascii_binary = 'ASCII' + else: + ascii_binary = 'BINARY' + + # defaults + outconfig = { + 'out_emissions': 0, + 'out_gwpemissions': 0, + 'out_sum_gwpemissions': 0, + 'out_concentrations': 0, + 'out_carboncycle': 0, + 'out_forcing': 0, + 'out_surfaceforcing': 0, + 'out_permafrost': 0, + 'out_temperature': 0, + 'out_sealevel': 0, + 'out_parameters': 0, + 'out_misc': 0, + 'out_lifetimes': 0, + 'out_timeseriesmix': 0, + 'out_rcpdata': 0, + 'out_summaryidx': 0, + 'out_inverseemis': 0, + 'out_tempoceanlayers': 0, + 'out_oceanarea': 0, + 'out_heatuptake': 0, + 'out_ascii_binary': ascii_binary, + 'out_warnings': 0, + 'out_precipinput': 0, + 'out_aogcmtuning': 0, + 'out_ccycletuning': 0, + 'out_observationaltuning': 0, + 'out_keydata_1': 0, + 'out_keydata_2': 0, + } + for kw in kwargs: + val = 1 if kwargs[kw] else 0 # convert values to 0/1 instead of booleans + outconfig['out_' + kw.lower()] = val + + self.update_config(**outconfig) + def get_executable(self): return config["executable_{}".format(self.version)] diff --git a/tests/test_api.py b/tests/test_api.py index <HASH>..<HASH> 100644 --- a/tests/test_api.py +++ b/tests/test_api.py @@ -622,4 +622,40 @@ def test_updates_namelist_missing(package): package.update_config('MAGTUNE_NOTEXISTS.CFG', test_value=1.2) updated_conf = f90nml.read(fname) - assert 'test_value' in updated_conf['nml_allcfgs'] \ No newline at end of file + assert 'test_value' in updated_conf['nml_allcfgs'] + + +def test_ascii_output(package): + fname = join(package.run_dir, "MAGTUNE_PYMAGICC.CFG") + + package.set_output_variables(write_ascii=True, write_binary=True) + raw_conf = f90nml.read(fname) + assert raw_conf['nml_allcfgs']['OUT_ASCII_BINARY'] == 'BOTH' + + package.set_output_variables(write_ascii=False, write_binary=True) + raw_conf = f90nml.read(fname) + assert raw_conf['nml_allcfgs']['OUT_ASCII_BINARY'] == 'BINARY' + + package.set_output_variables() + raw_conf = f90nml.read(fname) + assert raw_conf['nml_allcfgs']['OUT_ASCII_BINARY'] == 'ASCII' + + with pytest.raises(AssertionError): + package.set_output_variables(write_ascii=False, write_binary=False) + + +def test_output_variables(package): + fname = join(package.run_dir, "MAGTUNE_PYMAGICC.CFG") + + package.set_output_variables() + raw_conf = f90nml.read(fname) + assert raw_conf['nml_allcfgs']['OUT_TEMPERATURE'] == 0 + + package.set_output_variables(temperature=True) + raw_conf = f90nml.read(fname) + assert raw_conf['nml_allcfgs']['OUT_TEMPERATURE'] == 1 + + # Even accepts invalid variable names + package.set_output_variables(this_doesnt_exist=False) + raw_conf = f90nml.read(fname) + assert raw_conf['nml_allcfgs']['OUT_THIS_DOESNT_EXIST'] == 0
Added function to limit the variables MAGICC writes
openclimatedata_pymagicc
train
45659ed56616fc07d3f4b9a7b3897323039d74c1
diff --git a/src/Async.spec.js b/src/Async.spec.js index <HASH>..<HASH> 100644 --- a/src/Async.spec.js +++ b/src/Async.spec.js @@ -1,7 +1,7 @@ import "jest-dom/extend-expect" import React from "react" import { render, fireEvent, cleanup, waitForElement } from "react-testing-library" -import Async, { createInstance } from "./Async" +import Async, { createInstance } from "./index" const abortCtrl = { abort: jest.fn() } window.AbortController = jest.fn().mockImplementation(() => abortCtrl) diff --git a/src/useAsync.spec.js b/src/useAsync.spec.js index <HASH>..<HASH> 100644 --- a/src/useAsync.spec.js +++ b/src/useAsync.spec.js @@ -1,7 +1,7 @@ import "jest-dom/extend-expect" import React from "react" import { render, fireEvent, cleanup, waitForElement } from "react-testing-library" -import { useAsync, useFetch } from "." +import { useAsync, useFetch } from "./index" const abortCtrl = { abort: jest.fn(), signal: "SIGNAL" } window.AbortController = jest.fn(() => abortCtrl)
Import from the index to make sure it exports things correctly.
ghengeveld_react-async
train
905f3363ef17b042d064c598125216eed0eda8fb
diff --git a/parsers/mysql/mysql.go b/parsers/mysql/mysql.go index <HASH>..<HASH> 100644 --- a/parsers/mysql/mysql.go +++ b/parsers/mysql/mysql.go @@ -66,6 +66,7 @@ const ( normalizedQueryKey = "normalized_query" statementKey = "statement" tablesKey = "tables" + commentsKey = "comments" // Event attributes that apply to the host as a whole hostedOnKey = "hosted_on" readOnlyKey = "read_only" @@ -385,6 +386,9 @@ func (p *Parser) handleEvent(rawE []string) (map[string]interface{}, time.Time) if len(p.normalizer.LastTables) > 0 { sq[tablesKey] = strings.Join(p.normalizer.LastTables, " ") } + if len(p.normalizer.LastComments) > 0 { + sq[commentsKey] = "/* " + strings.Join(p.normalizer.LastComments, " */ /* ") + " */" + } sq[statementKey] = p.normalizer.LastStatement query = "" } diff --git a/parsers/mysql/mysql_test.go b/parsers/mysql/mysql_test.go index <HASH>..<HASH> 100644 --- a/parsers/mysql/mysql_test.go +++ b/parsers/mysql/mysql_test.go @@ -268,6 +268,25 @@ var sqds = []slowQueryData{ timestamp: t1, }, { + // query with a comment + rawE: []string{ + "# Time: 2016-04-01T00:31:09.817887Z", + "# User@Host: someuser @ hostfoo [192.168.2.1] Id: 666", + "SELECT /* from mysql.go:245 */ /* another comment */ * FROM orders WHERE total > 1000;", + }, + sq: map[string]interface{}{ + userKey: "someuser", + clientKey: "hostfoo", + clientIPKey: "192.168.2.1", + queryKey: "SELECT /* from mysql.go:245 */ /* another comment */ * FROM orders WHERE total > 1000", + normalizedQueryKey: "select * from orders where total > ?", + tablesKey: "orders", + statementKey: "select", + commentsKey: "/* from mysql.go:245 */ /* another comment */", + }, + timestamp: t1, + }, + { // query without its last line rawE: []string{ "# Time: 2016-04-01T00:31:09.817887Z",
[mysql] send comments as another event field
honeycombio_honeytail
train
104c06ac9d2aa2a403480a078b59278a4b1d2e06
diff --git a/mod/forum/locallib.php b/mod/forum/locallib.php index <HASH>..<HASH> 100644 --- a/mod/forum/locallib.php +++ b/mod/forum/locallib.php @@ -296,8 +296,8 @@ class forum_portfolio_caller extends portfolio_module_caller_base { $options = new stdClass(); $options->para = true; $format = $this->get('exporter')->get('format'); - $formattedtext = format_text($post->message, $post->messageformat, $options, $this->get('course')->id); - $formattedtext = portfolio_rewrite_pluginfile_urls($formattedtext, $this->modcontext->id, 'mod_forum', 'post', $post->id, $format); + $formattedtext = portfolio_rewrite_pluginfile_urls($post->message, $this->modcontext->id, 'mod_forum', 'post', $post->id, $format); + $formattedtext = format_text($formattedtext, $post->messageformat, $options, $this->get('course')->id); $output = '<table border="0" cellpadding="3" cellspacing="0" class="forumpost">';
Incorrect order of content processing during forum post portfolio export During the portfolio export, portfolio_rewrite_pluginfile_urls() must be called before format_text(). Otherwise some filters can interfere with internal raw record syntax. For example, the Algebra Notation uses @@ for its own purposes and it used to break @@PLUGINFILE@@ placeholder.
moodle_moodle
train
86aeacfdbdcb664440a216a55ab1b485a445100b
diff --git a/apio/commands/build.py b/apio/commands/build.py index <HASH>..<HASH> 100644 --- a/apio/commands/build.py +++ b/apio/commands/build.py @@ -15,6 +15,7 @@ if sys.version_info > (3, 0): unicode = str +# pylint: disable=W0622 @click.command("build") @click.pass_context @click.option( diff --git a/apio/commands/install.py b/apio/commands/install.py index <HASH>..<HASH> 100644 --- a/apio/commands/install.py +++ b/apio/commands/install.py @@ -23,6 +23,7 @@ platforms = [ ] +# pylint: disable=W0622 @click.command("install") @click.pass_context @click.argument("packages", nargs=-1) diff --git a/apio/commands/lint.py b/apio/commands/lint.py index <HASH>..<HASH> 100644 --- a/apio/commands/lint.py +++ b/apio/commands/lint.py @@ -14,6 +14,7 @@ if sys.version_info > (3, 0): unicode = str +# pylint: disable=W0622 @click.command("lint") @click.pass_context @click.option( diff --git a/apio/commands/time.py b/apio/commands/time.py index <HASH>..<HASH> 100644 --- a/apio/commands/time.py +++ b/apio/commands/time.py @@ -14,6 +14,7 @@ if sys.version_info > (3, 0): unicode = str +# pylint: disable=W0622 @click.command("time") @click.pass_context @click.option( diff --git a/apio/commands/uninstall.py b/apio/commands/uninstall.py index <HASH>..<HASH> 100644 --- a/apio/commands/uninstall.py +++ b/apio/commands/uninstall.py @@ -20,6 +20,7 @@ platforms = [ ] +# pylint: disable=W0622 @click.command("uninstall") @click.pass_context @click.argument("packages", nargs=-1) diff --git a/pyproject.toml b/pyproject.toml index <HASH>..<HASH> 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -64,5 +64,4 @@ disable = ["duplicate-code", "no-member", "consider-using-with", "lost-exception", - "eval-used", - "redefined-builtin"] + "eval-used"]
lint: "redefined-builtin" Errors fixed
FPGAwars_apio
train
91c58dd3ef36e9959741cadcd3b13934ca94310e
diff --git a/src/test/org/openscience/cdk/qsar/descriptors/molecular/WienerNumbersDescriptorTest.java b/src/test/org/openscience/cdk/qsar/descriptors/molecular/WienerNumbersDescriptorTest.java index <HASH>..<HASH> 100644 --- a/src/test/org/openscience/cdk/qsar/descriptors/molecular/WienerNumbersDescriptorTest.java +++ b/src/test/org/openscience/cdk/qsar/descriptors/molecular/WienerNumbersDescriptorTest.java @@ -50,5 +50,33 @@ public class WienerNumbersDescriptorTest extends MolecularDescriptorTest { Assert.assertEquals(testResult[0], retval.get(0), 0.0001); Assert.assertEquals(testResult[1], retval.get(1), 0.0001); } -} + /** + * Test if the descriptor returns the same results with and without explicit hydrogens. + */ + @Test + public void testWithExplicitHydrogens() throws Exception { + double [] testResult = {18, 2}; + SmilesParser sp = new SmilesParser(DefaultChemObjectBuilder.getInstance()); + IAtomContainer mol = sp.parseSmiles("[H]C([H])([H])C([H])([H])C(=O)O"); + DoubleArrayResult retval = (DoubleArrayResult) descriptor.calculate(mol).getValue(); + Assert.assertEquals(testResult[0], retval.get(0), 0.0001); + Assert.assertEquals(testResult[1], retval.get(1), 0.0001); + } + + /** + * Numbers extracted from {@cdk.cite Wiener1947}. + */ + @Test + public void testOriginalWienerPaperCompounds() throws Exception { + SmilesParser sp = new SmilesParser(DefaultChemObjectBuilder.getInstance()); + double [] testResult = {10, 20, 35, 56, 84, 120, 165, 220, 286}; + String smiles = "CCC"; + for (int i=0; i<testResult.length; i++) { + smiles += "C"; // create the matching paraffin + IAtomContainer mol = sp.parseSmiles(smiles); + DoubleArrayResult retval = (DoubleArrayResult)descriptor.calculate(mol).getValue(); + Assert.assertEquals(testResult[i], retval.get(0), 0.0001); + } + } +}
Added two further unit tests: one to see if the descriptor properly 'ignores' hydrogens; a second to reproduce the numbers in the original Wiener paper from <I>
cdk_cdk
train
8d88fbe71df8d7d1a3e2f6beb85a9cf0ebc8c870
diff --git a/src/org/parosproxy/paros/view/FindDialog.java b/src/org/parosproxy/paros/view/FindDialog.java index <HASH>..<HASH> 100644 --- a/src/org/parosproxy/paros/view/FindDialog.java +++ b/src/org/parosproxy/paros/view/FindDialog.java @@ -124,6 +124,13 @@ public class FindDialog extends AbstractDialog { String findText = txtFind.getText().toLowerCase(); String txt = txtComp.getText().toLowerCase(); int startPos = txt.indexOf(findText, txtComp.getCaretPosition()); + + // Enable Wrap Search + if (startPos <= 0) { + txtComp.setCaretPosition(0); + startPos = txt.indexOf(findText, txtComp.getCaretPosition()); + } + int length = findText.length(); if (startPos > -1) { txtComp.select(startPos,startPos+length); @@ -133,6 +140,7 @@ public class FindDialog extends AbstractDialog { Toolkit.getDefaultToolkit().beep(); } } catch (Exception e) { + System.out.println("Exception: " + e.getMessage()); } } /**
Feature: - Find (CTRL-F) now does Wrap Search Note: - User has to click first into text window to use find. This is a little usability problem.
zaproxy_zaproxy
train
d5dd4a92a373d562114201565da249cb218fbfd3
diff --git a/src/DataPool/SearchEngine/IntegrationTestSearchEngineAbstract.php b/src/DataPool/SearchEngine/IntegrationTestSearchEngineAbstract.php index <HASH>..<HASH> 100644 --- a/src/DataPool/SearchEngine/IntegrationTestSearchEngineAbstract.php +++ b/src/DataPool/SearchEngine/IntegrationTestSearchEngineAbstract.php @@ -399,8 +399,8 @@ abstract class IntegrationTestSearchEngineAbstract implements SearchEngine, Clea $direction = $sortOrderConfig->getSelectedDirection(); usort($result, function (SearchDocument $documentA, SearchDocument $documentB) use ($field, $direction) { - $fieldA = $this->getSearchDocumentFieldValue($documentA, $field); - $fieldB = $this->getSearchDocumentFieldValue($documentB, $field); + $fieldA = $this->getSortableSearchDocumentFieldValue($documentA, $field); + $fieldB = $this->getSortableSearchDocumentFieldValue($documentB, $field); if ($fieldA === $fieldB) { return 0; @@ -421,9 +421,9 @@ abstract class IntegrationTestSearchEngineAbstract implements SearchEngine, Clea /** * @param SearchDocument $document * @param AttributeCode $fieldName - * @return string + * @return mixed */ - private function getSearchDocumentFieldValue(SearchDocument $document, AttributeCode $fieldName) + private function getSortableSearchDocumentFieldValue(SearchDocument $document, AttributeCode $fieldName) { foreach ($document->getFieldsCollection()->getFields() as $field) { if ($field->getKey() !== (string) $fieldName) { @@ -436,10 +436,10 @@ abstract class IntegrationTestSearchEngineAbstract implements SearchEngine, Clea return $this->getFormattedSearchDocumentValue($values[0]); } - return ''; + return null; } - return ''; + return null; } /**
Issue #<I>: Rename test utility method
lizards-and-pumpkins_catalog
train
96ad71347369b21cf8cd4926c0240a3950c2bbb8
diff --git a/CHANGELOG.md b/CHANGELOG.md index <HASH>..<HASH> 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,7 @@ +# 0.9.1 +- Don't require aws keys for Stemcell::Launcher to allow for launching via iam role -# next release +# 0.9.0 - ... # 0.8.1 diff --git a/lib/stemcell/launcher.rb b/lib/stemcell/launcher.rb index <HASH>..<HASH> 100644 --- a/lib/stemcell/launcher.rb +++ b/lib/stemcell/launcher.rb @@ -10,8 +10,6 @@ module Stemcell class Launcher REQUIRED_OPTIONS = [ - 'aws_access_key', - 'aws_secret_key', 'region' ] @@ -78,9 +76,12 @@ module Stemcell @timeout = 300 @start_time = Time.new - AWS.config({ + aws_configs = {:region => @region} + aws_configs.merge!({ :access_key_id => @aws_access_key, - :secret_access_key => @aws_secret_key}) + :secret_access_key => @aws_secret_key + }) if @aws_access_key && @aws_secret_key + AWS.config(aws_configs) if opts['vpc_id'] puts 'using vpc tho' diff --git a/lib/stemcell/version.rb b/lib/stemcell/version.rb index <HASH>..<HASH> 100644 --- a/lib/stemcell/version.rb +++ b/lib/stemcell/version.rb @@ -1,3 +1,3 @@ module Stemcell - VERSION = "0.9.0" + VERSION = "0.9.1" end
Don't require AWS keys to launch instances This will let machines launch using IAM roles
airbnb_stemcell
train
a1d9c7e8cd95f84af9372a74922e3643ee30d2ce
diff --git a/src/Wave/Framework/External/Phroute/RouteResolver.php b/src/Wave/Framework/External/Phroute/RouteResolver.php index <HASH>..<HASH> 100644 --- a/src/Wave/Framework/External/Phroute/RouteResolver.php +++ b/src/Wave/Framework/External/Phroute/RouteResolver.php @@ -23,7 +23,7 @@ class RouteResolver implements HandlerResolverInterface public function resolve($handler) { if (is_array($handler) && is_string($handler[0])) { - $handler[0] = $this->resolver->reolve($handler[0]); + $handler[0] = $this->resolver->resolve($handler[0]); } return $handler;
Fixed typo for the method call 'reolve' -> 'resolve'
DaGhostman_codewave
train
35f65bde4068adb828521eb495d5cb7d9e743252
diff --git a/tests/base.py b/tests/base.py index <HASH>..<HASH> 100644 --- a/tests/base.py +++ b/tests/base.py @@ -33,7 +33,10 @@ def new_user(model): return self.user def __exit__(self, type, value, traceback): - self.user.delete() + try: + self.user.delete() + except: + pass return NewUser @@ -51,6 +54,7 @@ class TestCase(unittest.TestCase): self.User = c.register_model(User) self.new_user = new_user(User) self.new_admin = new_user(Admin) + self.client = c def tearDown(self): self.User.collection.drop() @@ -72,6 +76,7 @@ class CounterTestCase(unittest.TestCase): self.User = c.register_model(UserWithCounter) self.new_user = new_user(User) + self.client = c def tearDown(self): self.User.collection.drop() diff --git a/tests/test_counter.py b/tests/test_counter.py index <HASH>..<HASH> 100644 --- a/tests/test_counter.py +++ b/tests/test_counter.py @@ -62,6 +62,10 @@ class CounterTests(CounterTestCase): # `increase_by_6` is implemented in the base class self.assertEqual(self.Counter.increase_by_6('Final'), 6) - def test_exception(self): + def test_change_by_exception(self): # TODO: assert custom exception self.assertRaises(Exception, self.Counter.change_by, 'exception', -100) + + def test_delete_exception(self): + user = self.User(username='xx') + self.assertRaises(Exception, user.delete)
test exception for not_saved_model.delete()
tevino_mongu
train
94cd43db5d2051b81a608a9337be90f7507c0033
diff --git a/nion/swift/ProjectPanel.py b/nion/swift/ProjectPanel.py index <HASH>..<HASH> 100644 --- a/nion/swift/ProjectPanel.py +++ b/nion/swift/ProjectPanel.py @@ -476,7 +476,7 @@ class ProjectTreeCanvasItemDelegate(Widgets.ListCanvasItemDelegate): class ProjectTreeWidget(Widgets.CompositeWidgetBase): def __init__(self, ui, document_controller): - super().__init__(ui.create_column_widget(properties={"stylesheet": "border: #F00"})) + super().__init__(ui.create_column_widget()) column = self.content_widget @@ -635,7 +635,7 @@ class ProjectListCanvasItemDelegate(Widgets.ListCanvasItemDelegate): class ProjectsWidget(Widgets.CompositeWidgetBase): def __init__(self, ui: UserInterface.UserInterface, document_controller: "DocumentController.DocumentController"): - super().__init__(ui.create_column_widget(properties={"stylesheet": "border: #F00"})) + super().__init__(ui.create_column_widget()) column = self.content_widget @@ -828,7 +828,7 @@ class CollectionListCanvasItemDelegate(Widgets.ListCanvasItemDelegate): class CollectionsWidget(Widgets.CompositeWidgetBase): def __init__(self, ui, document_controller): - super().__init__(ui.create_column_widget(properties={"stylesheet": "border: #F00"})) + super().__init__(ui.create_column_widget()) column = self.content_widget @@ -951,7 +951,7 @@ class ProjectPanel(Panel.Panel): self._projects_section = ProjectsWidget(ui, document_controller) self._collections_section = CollectionsWidget(ui, document_controller) - column = ui.create_column_widget(properties={"stylesheet": "border: #F00"}) + column = ui.create_column_widget() column.add(self._projects_section) column.add(self._collections_section) column.add_stretch()
Remove unneeded stylesheet from project panel column widgets.
nion-software_nionswift
train
f9a4f2d3e9899ca012206abba00e52f3b36ffc19
diff --git a/src/main/java/com/j256/ormlite/dao/BaseDaoImpl.java b/src/main/java/com/j256/ormlite/dao/BaseDaoImpl.java index <HASH>..<HASH> 100644 --- a/src/main/java/com/j256/ormlite/dao/BaseDaoImpl.java +++ b/src/main/java/com/j256/ormlite/dao/BaseDaoImpl.java @@ -669,6 +669,7 @@ public abstract class BaseDaoImpl<T, ID> implements Dao<T, ID> { } public <FT> ForeignCollection<FT> getEmptyForeignCollection(String fieldName) throws SQLException { + checkForInitialized(); for (FieldType fieldType : tableInfo.getFieldTypes()) { if (fieldType.getDbColumnName().equals(fieldName)) { return fieldType.buildForeignCollection(null, true);
Added missing check for init.
j256_ormlite-core
train
bdaf4773ba6ac16b7119c511ba9a3926f14d4d41
diff --git a/examples/ptpython_config/config.py b/examples/ptpython_config/config.py index <HASH>..<HASH> 100644 --- a/examples/ptpython_config/config.py +++ b/examples/ptpython_config/config.py @@ -4,8 +4,11 @@ Configuration example for ``ptpython``. Copy this file to ~/.ptpython/config.py """ from __future__ import unicode_literals +from prompt_toolkit.filters import ViInsertMode +from prompt_toolkit.key_binding.input_processor import KeyPress from prompt_toolkit.keys import Keys from pygments.token import Token + from ptpython.layout import CompletionVisualisation __all__ = ( @@ -124,6 +127,14 @@ def configure(repl): if b.accept_action.is_returnable: b.accept_action.validate_and_handle(event.cli, b) + + # Typing 'jj' in Vi Insert mode, should send escape. (Go back to navigation + # mode.) + @repl.add_key_binding('j', 'j', filter=ViInsertMode()) + def _(event): + " Map 'jj' to Escape. " + event.cli.input_processor.feed(KeyPress(Keys.Escape)) + """ # Custom key binding for some simple autocorrection while typing. corrections = {
Added example of binding jj to escape in config.py example.
prompt-toolkit_ptpython
train
7a552b1817cdec34f74c2537d58dbbcbdc295e97
diff --git a/Kwf/Util/Build/Types/Assets.php b/Kwf/Util/Build/Types/Assets.php index <HASH>..<HASH> 100644 --- a/Kwf/Util/Build/Types/Assets.php +++ b/Kwf/Util/Build/Types/Assets.php @@ -73,7 +73,7 @@ class Kwf_Util_Build_Types_Assets extends Kwf_Util_Build_Types_Abstract } } if (Kwf_Component_Data_Root::getComponentClass()) { - foreach(Kwc_Abstract::getComponentClasses() as $c) { + foreach (Kwc_Abstract::getComponentClasses() as $c) { if (Kwc_Abstract::getFlag($c, 'hasAvailableLanguages')) { foreach (call_user_func(array($c, 'getAvailableLanguages'), $c) as $i) { if (!in_array($i, $langs)) $langs[] = $i; @@ -149,17 +149,6 @@ class Kwf_Util_Build_Types_Assets extends Kwf_Util_Build_Types_Abstract if (!file_exists($fileName) || strpos(file_get_contents($fileName), $cacheId."\n") === false) { file_put_contents($fileName, $cacheId."\n", FILE_APPEND); } - - foreach ($langs as $language) { - $urls = $p->getPackageUrls(self::$_mimeTypeByExtension[$extension], $language); - if (Kwf_Setup::getBaseUrl()) { - foreach ($urls as $k=>$i) { - $urls[$k] = substr($i, strlen(Kwf_Setup::getBaseUrl())); - } - } - $cacheId = $p->getPackageUrlsCacheId(self::$_mimeTypeByExtension[$extension], $language); - Kwf_Assets_BuildCache::getInstance()->save($urls, $cacheId); - } } } $progress->finish(); @@ -183,7 +172,7 @@ class Kwf_Util_Build_Types_Assets extends Kwf_Util_Build_Types_Abstract $progress->finish(); echo "generating packages...\n"; - $steps = count($packages) * count($langs) * count($exts) * 2; + $steps = count($packages) * count($langs) * count($exts) * 3; $c = new Zend_ProgressBar_Adapter_Console(); $c->setElements(array(Zend_ProgressBar_Adapter_Console::ELEMENT_PERCENT, Zend_ProgressBar_Adapter_Console::ELEMENT_BAR, @@ -201,10 +190,22 @@ class Kwf_Util_Build_Types_Assets extends Kwf_Util_Build_Types_Abstract $progress->next(1, "$depName $extension $language map"); $this->_buildPackageSourceMap($p, $extension, $language); + + $progress->next(1, "$depName $extension $language url"); + $urls = $p->getPackageUrls(self::$_mimeTypeByExtension[$extension], $language); + if (Kwf_Setup::getBaseUrl()) { + foreach ($urls as $k=>$i) { + $urls[$k] = substr($i, strlen(Kwf_Setup::getBaseUrl())); + } + } + $cacheId = $p->getPackageUrlsCacheId(self::$_mimeTypeByExtension[$extension], $language); + Kwf_Assets_BuildCache::getInstance()->save($urls, $cacheId); } + } } + Kwf_Assets_Cache::getInstance()->clean(); Kwf_Assets_BuildCache::getInstance()->building = false;
Build Assets: generate urls after generating package contents If we do that before too early scss files have to be compiled in the first step
koala-framework_koala-framework
train
0c68f45daeb34e257f47fdcaf684d47e105cb07c
diff --git a/stubs/GEOSGeometry.php b/stubs/GEOSGeometry.php index <HASH>..<HASH> 100644 --- a/stubs/GEOSGeometry.php +++ b/stubs/GEOSGeometry.php @@ -27,7 +27,7 @@ class GEOSGeometry * * @return float|null Returns NULL on error. */ - public function project(GEOSGeometry $other, $normalized) {} + public function project(GEOSGeometry $other, $normalized = false) {} /** * @param float $dist @@ -35,7 +35,7 @@ class GEOSGeometry * * @return GEOSGeometry|null Returns NULL on error. */ - public function interpolate($dist, $normalized) {} + public function interpolate($dist, $normalized = false) {} /** * @param float $dist @@ -90,11 +90,11 @@ class GEOSGeometry public function boundary() {} /** - * @param GEOSGeometry $otherGeom + * @param GEOSGeometry $otherGeom Optional, but explicit NULL is not allowed. * * @return GEOSGeometry|null Returns NULL on error. */ - public function union(GEOSGeometry $otherGeom) {} + public function union(GEOSGeometry $otherGeom = null) {} /** * @return GEOSGeometry|null Returns NULL on error. @@ -390,15 +390,16 @@ class GEOSGeometry * * @return GEOSGeometry|null Returns NULL on error. */ - public function delaunayTriangulation($tolerance, $onlyEdges) {} + public function delaunayTriangulation($tolerance = 0.0, $onlyEdges = false) {} /** * @param float $tolerance Snapping tolerance to use for improved robustness. * @param boolean $onlyEdges If true will return a MULTILINESTRING, otherwise (the default) * it will return a GEOMETRYCOLLECTION containing POLYGONs. * @param GEOSGeometry $extent Clip returned diagram by the extent of the given geometry. + * Optional, but explicit NULL value is not allowed. * * @return GEOSGeometry|null Returns NULL on error. */ - public function voronoiDiagram($tolerance = 0.0, $onlyEdges = false, GEOSGeometry $extent) {} + public function voronoiDiagram($tolerance = 0.0, $onlyEdges = false, GEOSGeometry $extent = null) {} }
Fixed GEOSGeometry stubs
brick_geo
train
10c81932e556f040b5ff6851bcf201354476df15
diff --git a/itools.py b/itools.py index <HASH>..<HASH> 100644 --- a/itools.py +++ b/itools.py @@ -151,3 +151,14 @@ def chunkGenerator( seq, size ): result = tuple( itertools.islice( seq, size ) ) if not result: break yield result + +def adjacentPairs( i ): + """Yield adjacent pairs of a single iterable as pairs + >>> tuple( adjacentPairs( iter( xrange( 5 ) ) ) + ((0, 1), (1, 2), (2, 3), (3, 4)) + """ + last = i.next() + while True: + next = i.next() + yield ( last, next ) + last = next \ No newline at end of file
Added adjacentPairs method (for seasearcher).
jaraco_jaraco.itertools
train
fcb06a126aae91e65ea9e050c8ad8d0c6f5be06e
diff --git a/lib/chef/resource/cron/cron_d.rb b/lib/chef/resource/cron/cron_d.rb index <HASH>..<HASH> 100644 --- a/lib/chef/resource/cron/cron_d.rb +++ b/lib/chef/resource/cron/cron_d.rb @@ -160,6 +160,7 @@ class Chef source ::File.expand_path("../support/cron.d.erb", __dir__) local true mode new_resource.mode + sensitive new_resource.sensitive variables( name: sanitized_name, predefined_value: new_resource.predefined_value,
Fixed cron_d resource ignoring sensitive property
chef_chef
train
4e82a1131199e101ff9f42810f64c00f83391a13
diff --git a/core/src/main/java/io/grpc/Channel.java b/core/src/main/java/io/grpc/Channel.java index <HASH>..<HASH> 100644 --- a/core/src/main/java/io/grpc/Channel.java +++ b/core/src/main/java/io/grpc/Channel.java @@ -41,11 +41,11 @@ import javax.annotation.concurrent.ThreadSafe; * * <p>Applications can add common cross-cutting behaviors to stubs by decorating Channel * implementations using {@link ClientInterceptor}. It is expected that most application - * code will not use this interface directly but rather work with stubs that have been bound to a + * code will not use this class directly but rather work with stubs that have been bound to a * Channel that was decorated during application initialization, */ @ThreadSafe -public interface Channel { +public abstract class Channel { /** * Create a {@link Call} to the remote operation specified by the given @@ -57,6 +57,6 @@ public interface Channel { * @return a {@link Call} bound to the specified method. * */ - public <RequestT, ResponseT> Call<RequestT, ResponseT> newCall( + public abstract <RequestT, ResponseT> Call<RequestT, ResponseT> newCall( MethodDescriptor<RequestT, ResponseT> methodDescriptor); } diff --git a/core/src/main/java/io/grpc/ChannelImpl.java b/core/src/main/java/io/grpc/ChannelImpl.java index <HASH>..<HASH> 100644 --- a/core/src/main/java/io/grpc/ChannelImpl.java +++ b/core/src/main/java/io/grpc/ChannelImpl.java @@ -52,7 +52,7 @@ import javax.annotation.concurrent.ThreadSafe; /** A communication channel for making outgoing RPCs. */ @ThreadSafe -public final class ChannelImpl implements Channel { +public final class ChannelImpl extends Channel { private static final Logger log = Logger.getLogger(ChannelImpl.class.getName()); diff --git a/core/src/main/java/io/grpc/ClientInterceptors.java b/core/src/main/java/io/grpc/ClientInterceptors.java index <HASH>..<HASH> 100644 --- a/core/src/main/java/io/grpc/ClientInterceptors.java +++ b/core/src/main/java/io/grpc/ClientInterceptors.java @@ -77,7 +77,7 @@ public class ClientInterceptors { return new InterceptorChannel(channel, interceptors); } - private static class InterceptorChannel implements Channel { + private static class InterceptorChannel extends Channel { private final Channel channel; private final Iterable<ClientInterceptor> interceptors; @@ -92,7 +92,7 @@ public class ClientInterceptors { } } - private static class ProcessInterceptorChannel implements Channel { + private static class ProcessInterceptorChannel extends Channel { private final Channel channel; private Iterator<ClientInterceptor> interceptors; diff --git a/core/src/main/java/io/grpc/Server.java b/core/src/main/java/io/grpc/Server.java index <HASH>..<HASH> 100644 --- a/core/src/main/java/io/grpc/Server.java +++ b/core/src/main/java/io/grpc/Server.java @@ -34,8 +34,8 @@ package io.grpc; import javax.annotation.concurrent.ThreadSafe; /** - * Server for listening for and dispatching incoming calls. Although Server is an interface, it is - * not expected to be implemented by application code or interceptors. + * Server for listening for and dispatching incoming calls. It is not expected to be implemented by + * application code or interceptors. */ @ThreadSafe -public interface Server {} +public abstract class Server {} diff --git a/core/src/main/java/io/grpc/ServerImpl.java b/core/src/main/java/io/grpc/ServerImpl.java index <HASH>..<HASH> 100644 --- a/core/src/main/java/io/grpc/ServerImpl.java +++ b/core/src/main/java/io/grpc/ServerImpl.java @@ -61,7 +61,7 @@ import java.util.concurrent.TimeUnit; * <p>Starting the server starts the underlying transport for servicing requests. Stopping the * server stops servicing new requests and waits for all connections to terminate. */ -public class ServerImpl implements Server { +public final class ServerImpl extends Server { private static final ServerStreamListener NOOP_LISTENER = new NoopListener(); /** Executor for application processing. */ diff --git a/integration-testing/src/test/java/io/grpc/stub/StubConfigTest.java b/integration-testing/src/test/java/io/grpc/stub/StubConfigTest.java index <HASH>..<HASH> 100644 --- a/integration-testing/src/test/java/io/grpc/stub/StubConfigTest.java +++ b/integration-testing/src/test/java/io/grpc/stub/StubConfigTest.java @@ -70,7 +70,7 @@ public class StubConfigTest { } - private static class FakeChannel implements Channel { + private static class FakeChannel extends Channel { @Override public <ReqT, RespT> Call<ReqT, RespT> newCall(MethodDescriptor<ReqT, RespT> method) { return null;
Make Channel/Server abstract classes Abstract classes allow us greater ability to change them over time. They previously were interfaces to allow us to use Guava's AbstractService.
grpc_grpc-java
train
9ff44e38d6e656e978cdbb3e0861168b0a26f86a
diff --git a/kubernetes/tracker/images/runner.py b/kubernetes/tracker/images/runner.py index <HASH>..<HASH> 100644 --- a/kubernetes/tracker/images/runner.py +++ b/kubernetes/tracker/images/runner.py @@ -29,6 +29,7 @@ logging.config.dictConfig({ # Setup Application from pyhadoopapi.apps.tracker.service import create_app, start_task_queue +from pyhadoopapi import ServiceError import json import os @@ -44,6 +45,10 @@ with open(conf_file) as json_data: # Create application and associate with configuration app = create_app('tracker_service') +@app.errorhandler(ServiceError) +def handle_service_error(e): + return e.message, e.status_code + app.config['KNOX'] = conf # The key is currently a separate dictionary item. If the encryption key does not exist, create it.
added ServiceError exception trapping for service
alexmilowski_pyox
train
31e380c841c57ae0435a3aec454370c7c4ed7287
diff --git a/lib/fluent/plugin_helper/event_loop.rb b/lib/fluent/plugin_helper/event_loop.rb index <HASH>..<HASH> 100644 --- a/lib/fluent/plugin_helper/event_loop.rb +++ b/lib/fluent/plugin_helper/event_loop.rb @@ -40,7 +40,11 @@ module Fluent end def event_loop_wait_until_start - ::Thread.pass until event_loop_running? + sleep(0.1) until event_loop_running? + end + + def event_loop_wait_until_stop + sleep(0.1) while event_loop_running? end def event_loop_running? @@ -74,7 +78,7 @@ module Fluent @_event_loop.watchers.each {|w| w.detach if w.attached? } end while @_event_loop_running - ::Thread.pass + sleep 0.1 end super diff --git a/lib/fluent/plugin_helper/thread.rb b/lib/fluent/plugin_helper/thread.rb index <HASH>..<HASH> 100644 --- a/lib/fluent/plugin_helper/thread.rb +++ b/lib/fluent/plugin_helper/thread.rb @@ -33,7 +33,13 @@ module Fluent def thread_wait_until_start until @_threads_mutex.synchronize{ @_threads.values.reduce(true){|r,t| r && t[:_fluentd_plugin_helper_thread_started] } } - ::Thread.pass + sleep 0.1 + end + end + + def thread_wait_until_stop + until @_threads_mutex.synchronize{ @_threads.values.reduce(true){|r,t| r && ![:_fluentd_plugin_helper_thread_running] } } + sleep 0.1 end end diff --git a/lib/fluent/test/driver/base.rb b/lib/fluent/test/driver/base.rb index <HASH>..<HASH> 100644 --- a/lib/fluent/test/driver/base.rb +++ b/lib/fluent/test/driver/base.rb @@ -136,6 +136,13 @@ module Fluent def run(expect_emits: nil, expect_records: nil, timeout: nil, start: true, shutdown: true, &block) instance_start if start + if @instance.respond_to?(:thread_wait_until_start) + @instance.thread_wait_until_start + end + if @instance.respond_to?(:event_loop_wait_until_start) + @instance.event_loop_wait_until_start + end + begin run_actual(expect_emits: expect_emits, expect_records: expect_records, timeout: timeout, &block) ensure @@ -158,6 +165,14 @@ module Fluent @instance.stop unless @instance.stopped? @instance.before_shutdown unless @instance.before_shutdown? @instance.shutdown unless @instance.shutdown? + + if @instance.respond_to?(:event_loop_wait_until_stop) + @instance.event_loop_wait_until_stop + end + if @instance.respond_to?(:thread_wait_until_stop) + @instance.thread_wait_until_stop + end + @instance.after_shutdown unless @instance.after_shutdown? @instance.close unless @instance.closed? @instance.terminate unless @instance.terminated?
fix to wait start/stop of plugin helpers before/after tests
fluent_fluentd
train
73764c5b60abeea6d88a907f41e0f7b2a2a856b1
diff --git a/datadog_checks_dev/datadog_checks/dev/tooling/e2e/docker.py b/datadog_checks_dev/datadog_checks/dev/tooling/e2e/docker.py index <HASH>..<HASH> 100644 --- a/datadog_checks_dev/datadog_checks/dev/tooling/e2e/docker.py +++ b/datadog_checks_dev/datadog_checks/dev/tooling/e2e/docker.py @@ -52,9 +52,10 @@ class DockerInterface(object): self.config_file = locate_config_file(check, env) self.config_file_name = config_file_name(self.check) - self.env_vars['DD_PYTHON_VERSION'] = str(self.python_version) + if self.agent_build and 'py' not in self.agent_build: + self.agent_build = '{}-py{}'.format(self.agent_build, self.python_version) - if self.metadata.get('use_jmx', False): + if self.agent_build and self.metadata.get('use_jmx', False): self.agent_build = '{}-jmx'.format(self.agent_build) @property
Use the new split images (#<I>)
DataDog_integrations-core
train
5456a4dc4735435951179846fa8e04a6d28f65c9
diff --git a/src/module.js b/src/module.js index <HASH>..<HASH> 100644 --- a/src/module.js +++ b/src/module.js @@ -23,7 +23,7 @@ const executeAndReturn = (command) => { const executeAndCapture = (command, log) => { const chunks = []; const tokens = command.split(/\s/); - const shell = spawn(tokens.shift(), tokens); + const shell = spawn(tokens.shift(), spawnargs(tokens.join(' '), { removequotes: true })); shell.stderr.on('readable', () => { const chunk = shell.stderr.read();
use spawn-args for all commands
chrisguttandin_karma-virtualbox-edge-launcher
train
7e0a240b762c766c5454f85f077baff473db46e8
diff --git a/public/source/staging.js b/public/source/staging.js index <HASH>..<HASH> 100644 --- a/public/source/staging.js +++ b/public/source/staging.js @@ -253,6 +253,10 @@ var ImageDiffViewModel = function(ancestor) { this.ancestor = ancestor; this.templateName = 'imageFileDiff'; this.diffs = ko.observable(); + this.firstElement = ko.observable(); + this.isFirstElementImage = ko.observable(); + this.secondElement = ko.observable(); + this.isSecondElementImage = ko.observable(); } ImageDiffViewModel.prototype.invalidateDiff = function(drawProgressBar) { var self = this; @@ -260,34 +264,32 @@ ImageDiffViewModel.prototype.invalidateDiff = function(drawProgressBar) { if (ancestor.showingDiffs()) { if (drawProgressBar) ancestor.diffsProgressBar.start(); - var isTextType = ancestor.type == 'text' ? true : false; - var firstElement, secondElement, isFirstElementImage, isSecondElementImage; var newDiffs = []; if (drawProgressBar) ancestor.diffsProgressBar.stop(); if(ancestor.isNew()) { - firstElement = '#'; - isFirstElementImage = false; - secondElement = getImageElement(ancestor.name(), ancestor.staging.repository.repoPath, 'current'); - isSecondElementImage = true; + this.firstElement = '#'; + this.isFirstElementImage = false; + this.secondElement = getImageElement(ancestor.name(), ancestor.staging.repository.repoPath, 'current'); + this.isSecondElementImage = true; } else { - firstElement = getImageElement(ancestor.name(), ancestor.staging.repository.repoPath, 'previous'); - isFirstElementImage = true; + this.firstElement = getImageElement(ancestor.name(), ancestor.staging.repository.repoPath, 'previous'); + this.isFirstElementImage = true; if(ancestor.removed()){ - secondElement = '#' - isSecondElementImage = false; + this.secondElement = '#' + this.isSecondElementImage = false; } else { - secondElement = getImageElement(ancestor.name(), ancestor.staging.repository.repoPath, 'current'); - isSecondElementImage = true; + this.secondElement = getImageElement(ancestor.name(), ancestor.staging.repository.repoPath, 'current'); + this.isSecondElementImage = true; } } newDiffs.push({ - firstElement: firstElement, - isFirstElementImage: isFirstElementImage, - secondElement: secondElement, - isSecondElementImage: isSecondElementImage + firstElement: this.firstElement, + isFirstElementImage: this.isFirstElementImage, + secondElement: this.secondElement, + isSecondElementImage: this.isSecondElementImage }); self.diffs(newDiffs);
Moving more object to ImagDiffVM
FredrikNoren_ungit
train
e19d391a62a78614c9e156e7303557d2467d2f86
diff --git a/Swat/SwatTableViewRowColumn.php b/Swat/SwatTableViewRowColumn.php index <HASH>..<HASH> 100644 --- a/Swat/SwatTableViewRowColumn.php +++ b/Swat/SwatTableViewRowColumn.php @@ -22,26 +22,35 @@ class SwatTableViewRowColumn extends SwatTableViewColumn public $offset = 0; // }}} - // {{{ protected function setupRenderers() + // {{{ public function display() /** - * Sets properties of renderers using data from current row + * Displays this column using a data object * - * @param mixed $data the data object being used to render the cell - * renderers of this field. + * The properties of the cell renderers are set from the data object + * through the datafield property mappings. + * + * @param mixed $row a data object used to display the cell renderers in + * this column. */ - protected function setupRenderers($data) + public function display($row) { - parent::setupRenderers($data); + if (!$this->visible) + return; + + $this->setupRenderers($row); - $this->visible = false; + $visible_renderers = false; foreach ($this->renderers as $renderer) { - if ($renderer->visible === true) { - $this->visible = true; + if ($renderer->visible) { + $visible_renderers = true; break; } } + + if ($visible_renderers) + $this->displayRenderers($row); } // }}}
Don't mangle the column visible property. svn commit r<I>
silverorange_swat
train
17110f4170644bd7679a8a486fce5e23bfa0841e
diff --git a/lxd/events.go b/lxd/events.go index <HASH>..<HASH> 100644 --- a/lxd/events.go +++ b/lxd/events.go @@ -11,7 +11,6 @@ import ( "github.com/lxc/lxd/lxd/rbac" "github.com/lxc/lxd/lxd/response" "github.com/lxc/lxd/shared" - "github.com/lxc/lxd/shared/logger" ) var eventTypes = []string{"logging", "operation", "lifecycle"} @@ -114,9 +113,7 @@ func eventsSocket(d *Daemon, r *http.Request, w http.ResponseWriter) error { return err } - logger.Debugf("New event listener: %s", listener.ID()) listener.Wait(r.Context()) - logger.Debugf("Event listener finished: %s", listener.ID()) return nil }
lxd/events: Removes duplicate event connection logging
lxc_lxd
train
081c35526cfbfff6f6393a4f6f67efff89306b14
diff --git a/lib/server/console.js b/lib/server/console.js index <HASH>..<HASH> 100644 --- a/lib/server/console.js +++ b/lib/server/console.js @@ -13,8 +13,6 @@ win = require('win32'), socket = require(DIR_SERVER + 'socket'), - equalPart = Util.isContainStrAtBegin, - ClientFuncs = [], ClientDirs = [], Clients = [], @@ -30,13 +28,6 @@ return text + newLine; }, - rmNewLine = function (text) { - var strs = ['\n', '\r'], - str = Util.rmStr(text, strs); - - return str; - }, - ConNum = 0, CHANNEL = 'console-data'; @@ -108,8 +99,8 @@ connName, ret, isVolume = win.isChangeVolume(command), - isCD = command.match(new RegExp('^cd ')), - isCDWin = command.match(new RegExp('^cd ', 'i')), + isCD = command.match(new RegExp('^cd ?')), + isCDWin = command.match(new RegExp('^cd ?', 'i')), symbolsExec = ['*', '&', '{', '}', '|', '\'', '"'], isSymbol = Util.isContainStr(command, symbolsExec), @@ -130,9 +121,9 @@ ret = true; onCD(command, dir, function(error, json) { - var path = ''; + var path; - if (!error) { + if (json.path) { path = json.path; ClientDirs[connNum] = path; } @@ -246,33 +237,91 @@ } } - function onCD(command, currDir, callback) { - var isChangeVolume = win.isChangeVolume(command), + function onCD(command, currDir, callback) { + var CD = 'cd ', + isChangeVolume = win.isChangeVolume(command), isVolume = win.isVolume(command), - paramDir = Util.rmStr(command, 'cd '), - isRootOrHome = equalPart(paramDir, ['/', '~']), - getDir = WIN ? 'chdir' : 'pwd'; + paramDir = Util.rmStrOnce(command, [CD, 'cd']), + + regStrEnd = getRegStrEnd(), + regStrHome = '^~$|^~', + regExpHome = new RegExp(regStrHome + regStrEnd), + isHome = paramDir.match(regExpHome) && !WIN; - if (!isRootOrHome && !isChangeVolume || isVolume) { - paramDir = path.join(currDir, paramDir); - command = 'cd ' + paramDir; + if (isHome) { + paramDir = process.env.HOME; + command = command.replace('~', paramDir); + } + + if (!paramDir && !WIN) + paramDir = '.'; + + if (!isHome && !isChangeVolume || isVolume) { + paramDir = getFirstWord(paramDir); + command = Util.rmStrOnce(command, [ + CD, + paramDir, + '\'' + paramDir + '\'', + '"' + paramDir + '"', + ]); + + if (paramDir !== '/') + paramDir = path.join(currDir, paramDir); + + command = CD + '"' + paramDir + '" ' + command; } - exec(command + ' && ' + getDir, {cwd : paramDir}, function (error, stdout, stderr) { - var errorStr = ''; + exec(command, {cwd: paramDir}, function (error, stdout, stderr) { + var path = paramDir, + errorStr = ''; - if (stderr) + if (stderr) { errorStr = stderr; - else if (error) + } else if (error) { errorStr = error.message; + path = ''; + } callback(error || stderr, { stderr : addNewLine(errorStr), - path : rmNewLine(stdout) + stdout : stdout, + path : path }); }); } + function getFirstWord(str) { + var word, result, + regStrEnd = getRegStrEnd(), + regStr = '^(.*?)', + regStrQuotes = '^"(.*)"', + regExp = new RegExp(regStr + regStrEnd), + regExpQuotes = new RegExp(regStrQuotes + regStrEnd + '?'), + is = Util.isString(str); + + if (is) { + result = str.match(regExpQuotes); + + if (result) { + word = result[1]; + } else { + result = str.match(regExp); + word = result && result[1]; + } + + if (!word) + word = str; + } + + return word; + } + + function getRegStrEnd() { + var regStrEnd = '(\\s|\\;|&&|\\|\\|)'; + + return regStrEnd; + } + function log(connNum, str, typeParam) { var ret, type = ' ';
feature(console) cd: works with ";, &&; ||" add command
cloudcmd_console-io
train
8eb3cd7699a91c9272447b4cc81e2c06dd9e4e07
diff --git a/lib/cocoapods_plugin.rb b/lib/cocoapods_plugin.rb index <HASH>..<HASH> 100644 --- a/lib/cocoapods_plugin.rb +++ b/lib/cocoapods_plugin.rb @@ -1,5 +1,4 @@ require 'cocoapods' -require 'pod/src/configuration' require 'pod/src/rewriter' module Pod
don't require things that don't exist
brianmichel_cocoapods-git_url_rewriter
train
11fef95f4e5c2f36357899a0ce8fd032abc6bc6a
diff --git a/Controller/HelperController.php b/Controller/HelperController.php index <HASH>..<HASH> 100644 --- a/Controller/HelperController.php +++ b/Controller/HelperController.php @@ -153,6 +153,7 @@ class HelperController $formBuilder = $admin->getFormBuilder(); $form = $formBuilder->getForm(); + $form->setData($subject); $form->handleRequest($request); $view = $this->helper->getChildFormView($form->createView(), $elementId); diff --git a/Tests/Controller/HelperControllerTest.php b/Tests/Controller/HelperControllerTest.php index <HASH>..<HASH> 100644 --- a/Tests/Controller/HelperControllerTest.php +++ b/Tests/Controller/HelperControllerTest.php @@ -390,6 +390,14 @@ class HelperControllerTest extends PHPUnit_Framework_TestCase { $object = new AdminControllerHelper_Foo(); + $request = new Request(array( + 'code' => 'sonata.post.admin', + 'objectId' => 42, + 'field' => 'enabled', + 'value' => 1, + 'context' => 'list', + ), array(), array(), array(), array(), array('REQUEST_METHOD' => 'POST')); + $modelManager = $this->createMock('Sonata\AdminBundle\Model\ModelManagerInterface'); $modelManager->expects($this->once())->method('find')->will($this->returnValue($object)); @@ -400,6 +408,15 @@ class HelperControllerTest extends PHPUnit_Framework_TestCase $mockForm = $this->getMockBuilder('Symfony\Component\Form\Form') ->disableOriginalConstructor() ->getMock(); + + $mockForm->expects($this->once()) + ->method('setData') + ->with($object); + + $mockForm->expects($this->once()) + ->method('handleRequest') + ->with($request); + $mockForm->expects($this->once()) ->method('createView') ->will($this->returnValue($mockView)); @@ -438,13 +455,6 @@ class HelperControllerTest extends PHPUnit_Framework_TestCase $twig->addRuntimeLoader($runtimeLoader); } - $request = new Request(array( - 'code' => 'sonata.post.admin', - 'objectId' => 42, - 'field' => 'enabled', - 'value' => 1, - 'context' => 'list', - ), array(), array(), array(), array(), array('REQUEST_METHOD' => 'POST')); $pool = new Pool($container, 'title', 'logo'); $pool->setAdminServiceIds(array('sonata.post.admin'));
Setting subject data form on retrieve form field element (#<I>) * Setting subject data form on retrieve form field element AdminInterface::getFormBuilder signature doesn't accept any parameter currently (it do nothing with $subject) so, before that, the form does not have a binded data ($subject) i.e their children cannot access to $form->getParent()->getData() into a custom form field type. * Added test * fix styleci
sonata-project_SonataAdminBundle
train
0591d92f53e91f9aec88e561634da9e437f793ad
diff --git a/lib/devise.rb b/lib/devise.rb index <HASH>..<HASH> 100755 --- a/lib/devise.rb +++ b/lib/devise.rb @@ -290,6 +290,10 @@ module Devise mattr_accessor :token_generator @@token_generator = nil + def self.rails51? # :nodoc: + Rails.gem_version >= Gem::Version.new("5.1.x") + end + # Default way to set up Devise. Run rails generate devise_install to create # a fresh initializer with all configuration values. def self.setup diff --git a/test/rails_app/config/boot.rb b/test/rails_app/config/boot.rb index <HASH>..<HASH> 100644 --- a/test/rails_app/config/boot.rb +++ b/test/rails_app/config/boot.rb @@ -4,10 +4,6 @@ end module Devise # Detection for minor differences between Rails 4 and 5, and 5.1 in tests. - def self.rails51? - Rails.version.start_with? '5.1' - end - def self.rails5? Rails.version.start_with? '5' end
Move the version check to the lib folder Closes #<I>. Fixes #<I>.
plataformatec_devise
train
12f2fbd5eabc4cc5d85386bfd4aa92a3b3a12797
diff --git a/provider.go b/provider.go index <HASH>..<HASH> 100644 --- a/provider.go +++ b/provider.go @@ -96,14 +96,15 @@ func createTokenPair(token string, p *policy) (string, error) { } permTokenOpts := struct { - Ttl string `json:"ttl,omitempty"` - Policies []string `json:"policies"` - Meta map[string]string `json:"meta,omitempty"` - NumUses int `json:"num_uses"` - NoParent bool `json:"no_parent"` - }{time.Duration(time.Duration(p.Ttl) * time.Second).String(), pol, p.Meta, p.NumUses, true} - - return createWrappedToken(token, permTokenOpts, 10 * time.Minute) + Ttl string `json:"ttl,omitempty"` + Policies []string `json:"policies"` + Meta map[string]string `json:"meta,omitempty"` + NumUses int `json:"num_uses"` + NoParent bool `json:"no_parent"` + Renewable bool `json:"renewable"` + }{time.Duration(time.Duration(p.Ttl) * time.Second).String(), pol, p.Meta, p.NumUses, true, true} + + return createWrappedToken(token, permTokenOpts, 10*time.Minute) } func Provide(c *gin.Context) {
provider: make the perm token renewable
nemosupremo_vault-gatekeeper
train
fd614bc0887844336a3fd81798ff28f8f7481979
diff --git a/core/amplify.core.js b/core/amplify.core.js index <HASH>..<HASH> 100644 --- a/core/amplify.core.js +++ b/core/amplify.core.js @@ -7,12 +7,18 @@ * * http://amplifyjs.com */ -(function( $, undefined ) { +(function( undefined ) { -var slice = [].slice, +var $ = ( this.jQuery || this.AMPLIFY ), + slice = [].slice, subscriptions = {}; this.amplify = { + each: $.each, + extend: $.extend +}; + +amplify.extend( amplify, { publish: function( topic ) { var args = slice.call( arguments, 1 ), ret; @@ -73,6 +79,6 @@ this.amplify = { } }); } -}; +}); -}( jQuery ) ); +}() ); diff --git a/store/amplify.store.js b/store/amplify.store.js index <HASH>..<HASH> 100644 --- a/store/amplify.store.js +++ b/store/amplify.store.js @@ -7,7 +7,7 @@ * * http://amplifyjs.com */ -(function( amplify, $, undefined ) { +(function( amplify, undefined ) { amplify.store = function( key, value, options ) { var type = amplify.store.type; @@ -17,7 +17,7 @@ amplify.store = function( key, value, options ) { return amplify.store.types[ type ]( key, value, options || {} ); }; -$.extend( amplify.store, { +amplify.extend( amplify.store, { types: {}, type: null, @@ -30,7 +30,7 @@ $.extend( amplify.store, { this.types[ type ] = store; amplify.store[ type ] = function( key, value, options ) { return amplify.store( key, value, - $.extend( { type: type }, options ) ); + amplify.extend( { type: type }, options ) ); }; } }); @@ -93,7 +93,7 @@ function createSimpleStorage( storageType, storage ) { // localStorage + sessionStorage // IE 8+, Firefox 3.5+, Safari 4+, Chrome 4+, Opera 10.5+, iPhone 2+, Android 2+ -$.each( [ "localStorage", "sessionStorage" ], function( i, storageType ) { +amplify.each( [ "localStorage", "sessionStorage" ], function( i, storageType ) { // try/catch for file protocol in Firefox try { if ( window[ storageType ].getItem ) { @@ -115,10 +115,11 @@ if ( window.globalStorage ) { // http://msdn.microsoft.com/en-us/library/ms531424(v=vs.85).aspx (function() { // append to html instead of body so we can do this from the head - var div = $( "<div>" ).hide().appendTo( "html" )[ 0 ], + var div = document.createElement( "div" ), attrKey = "amplify", attrs; - + div.style.display = "none"; + document.documentElement.appendChild( div ); if ( div.addBehavior ) { div.addBehavior( "#default#userdata" ); div.load( attrKey ); @@ -191,13 +192,15 @@ createSimpleStorage( "memory", {} ); // cookie // supported to enable a common API // never registers as the default for performance reasons -if ( $.cookie && $.support.cookie ) { - amplify.store.addType( "cookie", function( key, value, options ) { - return $.cookie( key, value, { - expires: options.expires || 99e9, - path: "/" +(function( $ ) { + if ( $ && $.cookie && $.support.cookie ) { + amplify.store.addType( "cookie", function( key, value, options ) { + return $.cookie( key, value, { + expires: options.expires || 99e9, + path: "/" + }); }); - }); -} + } +}( jQuery ) ); -}( amplify, jQuery ) ); +}( amplify ) );
Removed jQuery dependency for core and store.
nodeGame_shelf.js
train
e3b80fdb9e373f7f352f5d168c497fe32d66a007
diff --git a/peewee.py b/peewee.py index <HASH>..<HASH> 100644 --- a/peewee.py +++ b/peewee.py @@ -18,6 +18,7 @@ import uuid from collections import deque from collections import namedtuple from copy import deepcopy +from functools import wraps from inspect import isclass __all__ = [ @@ -2094,6 +2095,7 @@ class Database(object): return transaction(self) def commit_on_success(self, func): + @wraps(func) def inner(*args, **kwargs): with self.transaction(): return func(*args, **kwargs)
Use wraps decorator so we don't lose the identity of the decorated function
coleifer_peewee
train
2c43a3bcd09b72630d2ce8981bf41afd6499735e
diff --git a/src/Composer/DependencyResolver/Rule.php b/src/Composer/DependencyResolver/Rule.php index <HASH>..<HASH> 100644 --- a/src/Composer/DependencyResolver/Rule.php +++ b/src/Composer/DependencyResolver/Rule.php @@ -30,7 +30,7 @@ class Rule const RULE_PACKAGE_ALIAS = 13; /** - * The literals this rule consists of. + * READ-ONLY: The literals this rule consists of. * @var array */ public $literals; diff --git a/src/Composer/DependencyResolver/RuleSet.php b/src/Composer/DependencyResolver/RuleSet.php index <HASH>..<HASH> 100644 --- a/src/Composer/DependencyResolver/RuleSet.php +++ b/src/Composer/DependencyResolver/RuleSet.php @@ -23,9 +23,9 @@ class RuleSet implements \IteratorAggregate, \Countable const TYPE_LEARNED = 4; /** - * Lookup table for rule id to rule object + * READ-ONLY: Lookup table for rule id to rule object * - * @var array + * @var Rule[] */ public $ruleById; diff --git a/src/Composer/Package/BasePackage.php b/src/Composer/Package/BasePackage.php index <HASH>..<HASH> 100644 --- a/src/Composer/Package/BasePackage.php +++ b/src/Composer/Package/BasePackage.php @@ -45,8 +45,7 @@ abstract class BasePackage implements PackageInterface ); /** - * The package id, public for fast access in dependency solver - * Use getId() unless called extremely frequently. + * READ-ONLY: The package id, public for fast access in dependency solver * @var int */ public $id;
Improve docblocks of public properties
mothership-ec_composer
train
d1c325438e8e14318bda1689006927349c6a0fcd
diff --git a/examples/google.py b/examples/google.py index <HASH>..<HASH> 100644 --- a/examples/google.py +++ b/examples/google.py @@ -2,6 +2,14 @@ from rauth.service import OAuth2Service # Get a real consumer key & secret from: # https://code.google.com/apis/console/ +# +# When creating a client id choose: +# - Application type: Installed application +# - Installed application type: Other +# +# For existing client id's, from "Edit settings": +# - Platform: Other + google = OAuth2Service( name='google', authorize_url='https://accounts.google.com/o/oauth2/auth', @@ -9,14 +17,11 @@ google = OAuth2Service( consumer_key='', consumer_secret='') -redirect_uri = 'https://github.com/litl/rauth/' +redirect_uri = 'urn:ietf:wg:oauth:2.0:oob' print 'Visit this URL in your browser: ' + google.get_authorize_url(redirect_uri=redirect_uri, scope='profile email') -# This is a bit cumbersome, but you need to copy the code=something (just the -# `something` part) out of the URL that's redirected to AFTER you login and -# authorize the demo application -code = raw_input('Enter code parameter (code=something) from URL: ') +code = raw_input('Copy code from browser: ') # create a dictionary for the data we'll post on the get_access_token request data = dict(code=code, grant_type='authorization_code', redirect_uri=redirect_uri)
Fix redirect URI. This special URI tells Google to display a code with along instructions to copy-paste it. Added some instructional comments to help configure the Google API project properly. Also simplified the prompt for code (parameter).
litl_rauth
train
01bfad54566a308c9768a6fc28b124ac6b352300
diff --git a/dolo/compiler/compiler_matlab.py b/dolo/compiler/compiler_matlab.py index <HASH>..<HASH> 100644 --- a/dolo/compiler/compiler_matlab.py +++ b/dolo/compiler/compiler_matlab.py @@ -38,8 +38,8 @@ class CompilerMatlab(object): states = model.symbols_s['states'] parameters = model.symbols_s['parameters'] - txt_lb = compile_multiargument_function(lb_sym, [states], ['s'], parameters, fname = 'arbitrage_lb', diff=diff) - txt_ub = compile_multiargument_function(ub_sym, [states], ['s'], parameters, fname = 'arbitrage_ub', diff=diff) + txt_lb = compile_multiargument_function(lb_sym, [states], ['s'], parameters, fname = 'arbitrage_lb', diff=diff, default='-inf') + txt_ub = compile_multiargument_function(ub_sym, [states], ['s'], parameters, fname = 'arbitrage_ub', diff=diff, default='inf') incidence_matrices_text += 'model.infos.incidence_matrices.arbitrage_lb = ' + compile_incidence_matrices(lb_sym, [states]) + '\n' incidence_matrices_text += 'model.infos.incidence_matrices.arbitrage_ub = ' + compile_incidence_matrices(ub_sym, [states]) + '\n' diff --git a/dolo/compiler/function_compiler_matlab.py b/dolo/compiler/function_compiler_matlab.py index <HASH>..<HASH> 100644 --- a/dolo/compiler/function_compiler_matlab.py +++ b/dolo/compiler/function_compiler_matlab.py @@ -13,7 +13,7 @@ libraries for efficient vectorization: `numpy <http://numpy.scipy.org/>`_, `nume from __future__ import division -def compile_multiargument_function(equations, args_list, args_names, parms, diff=False, fname='anonymous_function'): +def compile_multiargument_function(equations, args_list, args_names, parms, diff=False, fname='anonymous_function', default=None): """ :param equations: list of sympy expressions :param args_list: list of lists of symbols (e.g. [[a_1,a_2], [b_1,b_2]]) @@ -62,10 +62,17 @@ end dp = DicPrinter(sub_list) - def write_eqs(eq_l,outname='val'): - eq_block = ' {0} = zeros( n, {1} );\n'.format(outname, len(eq_l)) + def write_eqs(eq_l, outname='val', default=None): + '''Format equations''' + if default: + eq_block = ' {0} = ' + default + '( n , {1} );\n' + eq_block = eq_block.format(outname, len(eq_l)) + else: + eq_block = ' {0} = zeros( n, {1} );\n'.format(outname, len(eq_l)) for i,eq in enumerate(eq_l): - eq_block += ' {0}(:,{1}) = {2};\n'.format(outname, i+1, dp.doprint_matlab(eq, vectorize=True)) + eq_txt = dp.doprint_matlab(eq, vectorize=True) + if eq_txt != default: + eq_block += ' {0}(:,{1}) = {2};\n'.format(outname, i+1, eq_txt) return eq_block def write_der_eqs(eq_l,v_l,lhs): @@ -79,7 +86,7 @@ end eq_block += ' {lhs}(:,{0},{1}) = {2};\n'.format(i+1,j+1,s,lhs=lhs) return eq_block - content = write_eqs(equations) + content = write_eqs(eq_l=equations, default=default) content += ''' if nargout <= 1
Add default values for equation compilation to suppress the writting of infinite bounds
EconForge_dolo
train
86c214e57856b0f12a3e5a83d23d2249f0816453
diff --git a/doc/source/v0.15.0.txt b/doc/source/v0.15.0.txt index <HASH>..<HASH> 100644 --- a/doc/source/v0.15.0.txt +++ b/doc/source/v0.15.0.txt @@ -794,6 +794,6 @@ needed interpolating (:issue:`7173`). (:issue:`8230`). - Bug with ``DatetimeIndex.asof`` incorrectly matching partial strings and returning the wrong date (:issue:`8245`). - - +- Bug in plotting methods modifying the global matplotlib +rcParams (:issue:`8242`). diff --git a/pandas/tests/test_graphics.py b/pandas/tests/test_graphics.py index <HASH>..<HASH> 100644 --- a/pandas/tests/test_graphics.py +++ b/pandas/tests/test_graphics.py @@ -479,6 +479,12 @@ class TestSeriesPlots(TestPlotBase): self._check_text_labels(ax.title, 'Test') self._check_axes_shape(ax, axes_num=1, layout=(1, 1), figsize=(16, 8)) + def test_dont_modify_rcParams(self): + # GH 8242 + colors = self.plt.rcParams['axes.color_cycle'] + Series([1, 2, 3]).plot() + self.assertEqual(colors, self.plt.rcParams['axes.color_cycle']) + def test_ts_line_lim(self): ax = self.ts.plot() xmin, xmax = ax.get_xlim() diff --git a/pandas/tools/plotting.py b/pandas/tools/plotting.py index <HASH>..<HASH> 100644 --- a/pandas/tools/plotting.py +++ b/pandas/tools/plotting.py @@ -116,7 +116,10 @@ def _get_standard_colors(num_colors=None, colormap=None, color_type='default', colors = color else: if color_type == 'default': - colors = plt.rcParams.get('axes.color_cycle', list('bgrcmyk')) + # need to call list() on the result to copy so we don't + # modify the global rcParams below + colors = list(plt.rcParams.get('axes.color_cycle', + list('bgrcmyk'))) if isinstance(colors, compat.string_types): colors = list(colors) elif color_type == 'random':
BUG: plot methods modified rcParams
pandas-dev_pandas
train
16e218edb02a0c63f61ab0ab3c5de49e75e226b4
diff --git a/ipyleaflet/leaflet.py b/ipyleaflet/leaflet.py index <HASH>..<HASH> 100644 --- a/ipyleaflet/leaflet.py +++ b/ipyleaflet/leaflet.py @@ -919,7 +919,6 @@ class Map(DOMWidget, InteractMixin): def __init__(self, **kwargs): super(Map, self).__init__(**kwargs) - self.on_displayed(self._fire_children_displayed) self.on_msg(self._handle_leaflet_event) if self.zoom_control: @@ -944,12 +943,6 @@ class Map(DOMWidget, InteractMixin): if self.attribution_control_instance in self.controls: self.remove_control(self.attribution_control_instance) - def _fire_children_displayed(self, widget, **kwargs): - for layer in self.layers: - layer._handle_displayed(**kwargs) - for control in self.controls: - control._handle_displayed(**kwargs) - _layer_ids = List() @validate('layers')
Remove on_displayed event listener
jupyter-widgets_ipyleaflet
train
a0c5d76e9fa9582b1c70a3cc34a112a522ac9fb3
diff --git a/TodoBase.py b/TodoBase.py index <HASH>..<HASH> 100644 --- a/TodoBase.py +++ b/TodoBase.py @@ -114,6 +114,14 @@ class TodoBase(object): """ Returns the todo text with tags stripped off. """ return self.text + def projects(self): + """ Returns a list of projects associated with this todo item. """ + return self.fields['projects'] + + def contexts(self): + """ Returns a list of contexts associated with this todo item. """ + return self.fields['contexts'] + def __print__(self): """ A printer for the todo item. """ print self.src + "\n"
Add two accessors for projects and contexts.
bram85_topydo
train
890ca99e177519cf330895e1e9b3eed010c7dcc7
diff --git a/src/capture.js b/src/capture.js index <HASH>..<HASH> 100644 --- a/src/capture.js +++ b/src/capture.js @@ -2,7 +2,7 @@ var Capture = module.exports = function (robot) { this.robot = robot; - this.captured = {}; + this.captured = []; this.completeCallback = function () {}; }; @@ -35,17 +35,17 @@ Capture.prototype._capture = function (id, msg) { }; Capture.prototype._isComplete = function () { - return ! Object.keys(this.captured).some(function (id) { - return this.captured[id].length === 0; + return ! this.captured.some(function (each) { + return each.length === 0; }.bind(this)); } Capture.prototype._checkCompletion = function () { while (this._isComplete()) { - var result = {}; + var result = []; - Object.keys(this.captured).forEach(function (id) { - result[id] = this.captured[id].shift(); + this.captured.forEach(function (each, i) { + result[i] = each.shift(); }.bind(this)); this.completeCallback(result); diff --git a/test/capture-test.js b/test/capture-test.js index <HASH>..<HASH> 100644 --- a/test/capture-test.js +++ b/test/capture-test.js @@ -19,17 +19,17 @@ describe("capture", function () { it("patches #send in the robot's adapter", function () { // Prevent the capture from being "complete" - capture.patchedRobot('other-id'); + capture.patchedRobot(1); - var patched = capture.patchedRobot('the-id'); + var patched = capture.patchedRobot(0); var result = patched.adapter.send({}, "something"); - expect(capture.captured['the-id']).to.deep.equal(["something"]); + expect(capture.captured[0]).to.deep.equal(["something"]); }); it("invokes its completion callback once all results are in", function () { - var patched0 = capture.patchedRobot('id0'); - var patched1 = capture.patchedRobot('id1'); + var patched0 = capture.patchedRobot(0); + var patched1 = capture.patchedRobot(1); var parts = null; capture.onComplete(function (p) { @@ -42,10 +42,10 @@ describe("capture", function () { expect(parts).to.be.null; patched1.adapter.send({}, "second part came in"); - expect(parts).to.deep.equal({ - id0: "first part came in", - id1: "second part came in" - }); + expect(parts).to.deep.equal([ + "first part came in", + "second part came in" + ]); }); });
Use indices to identity captured output
smashwilson_hubot-pipe
train
61c18fa3d024ddc9143ac21f14ac160fb68722a1
diff --git a/py25/bacpypes/npdu.py b/py25/bacpypes/npdu.py index <HASH>..<HASH> 100755 --- a/py25/bacpypes/npdu.py +++ b/py25/bacpypes/npdu.py @@ -744,6 +744,11 @@ class WhatIsNetworkNumber(NPDU): messageType = 0x12 + def __init__(self, *args, **kwargs): + super(WhatIsNetworkNumber, self).__init__(*args, **kwargs) + + self.npduNetMessage = WhatIsNetworkNumber.messageType + def encode(self, npdu): NPCI.update(npdu, self) @@ -764,10 +769,17 @@ register_npdu_type(WhatIsNetworkNumber) class NetworkNumberIs(NPDU): - _debug_contents = ('nniNET', 'nniFlag',) + _debug_contents = ('nniNet', 'nniFlag',) messageType = 0x13 + def __init__(self, net=None, flag=None, *args, **kwargs): + super(NetworkNumberIs, self).__init__(*args, **kwargs) + + self.npduNetMessage = NetworkNumberIs.messageType + self.nniNet = net + self.nniFlag = flag + def encode(self, npdu): NPCI.update(npdu, self) npdu.put_short( self.nniNET ) diff --git a/py27/bacpypes/npdu.py b/py27/bacpypes/npdu.py index <HASH>..<HASH> 100755 --- a/py27/bacpypes/npdu.py +++ b/py27/bacpypes/npdu.py @@ -741,6 +741,11 @@ class WhatIsNetworkNumber(NPDU): messageType = 0x12 + def __init__(self, *args, **kwargs): + super(WhatIsNetworkNumber, self).__init__(*args, **kwargs) + + self.npduNetMessage = WhatIsNetworkNumber.messageType + def encode(self, npdu): NPCI.update(npdu, self) @@ -761,25 +766,32 @@ register_npdu_type(WhatIsNetworkNumber) class NetworkNumberIs(NPDU): - _debug_contents = ('nniNET', 'nniFlag',) + _debug_contents = ('nniNet', 'nniFlag',) messageType = 0x13 + def __init__(self, net=None, flag=None, *args, **kwargs): + super(NetworkNumberIs, self).__init__(*args, **kwargs) + + self.npduNetMessage = NetworkNumberIs.messageType + self.nniNet = net + self.nniFlag = flag + def encode(self, npdu): NPCI.update(npdu, self) - npdu.put_short( self.nniNET ) + npdu.put_short( self.nniNet ) npdu.put( self.nniFlag ) def decode(self, npdu): NPCI.update(self, npdu) - self.nniNET = npdu.get_short() + self.nniNet = npdu.get_short() self.nniFlag = npdu.get() def npdu_contents(self, use_dict=None, as_class=dict): return key_value_contents(use_dict=use_dict, as_class=as_class, key_values=( ('function', 'NetorkNumberIs'), - ('net', self.nniNET), + ('net', self.nniNet), ('flag', self.nniFlag), )) diff --git a/py34/bacpypes/npdu.py b/py34/bacpypes/npdu.py index <HASH>..<HASH> 100755 --- a/py34/bacpypes/npdu.py +++ b/py34/bacpypes/npdu.py @@ -741,6 +741,11 @@ class WhatIsNetworkNumber(NPDU): messageType = 0x12 + def __init__(self, *args, **kwargs): + super(WhatIsNetworkNumber, self).__init__(*args, **kwargs) + + self.npduNetMessage = WhatIsNetworkNumber.messageType + def encode(self, npdu): NPCI.update(npdu, self) @@ -761,25 +766,32 @@ register_npdu_type(WhatIsNetworkNumber) class NetworkNumberIs(NPDU): - _debug_contents = ('nniNET', 'nniFlag',) + _debug_contents = ('nniNet', 'nniFlag',) messageType = 0x13 + def __init__(self, net=None, flag=None, *args, **kwargs): + super(NetworkNumberIs, self).__init__(*args, **kwargs) + + self.npduNetMessage = NetworkNumberIs.messageType + self.nniNet = net + self.nniFlag = flag + def encode(self, npdu): NPCI.update(npdu, self) - npdu.put_short( self.nniNET ) + npdu.put_short( self.nniNet ) npdu.put( self.nniFlag ) def decode(self, npdu): NPCI.update(self, npdu) - self.nniNET = npdu.get_short() + self.nniNet = npdu.get_short() self.nniFlag = npdu.get() def npdu_contents(self, use_dict=None, as_class=dict): return key_value_contents(use_dict=use_dict, as_class=as_class, key_values=( ('function', 'NetorkNumberIs'), - ('net', self.nniNET), + ('net', self.nniNet), ('flag', self.nniFlag), ))
fix WhatIsNetworkNumber and NetworkNumberIs encoding/decoding
JoelBender_bacpypes
train
55123c50234993157b5f85774e8b00307830fe4a
diff --git a/pcapkit/protocols/protocol.py b/pcapkit/protocols/protocol.py index <HASH>..<HASH> 100644 --- a/pcapkit/protocols/protocol.py +++ b/pcapkit/protocols/protocol.py @@ -30,7 +30,8 @@ from pcapkit.corekit.protochain import ProtoChain from pcapkit.protocols.data.protocol import Packet as DataType_Packet from pcapkit.utilities.compat import cached_property from pcapkit.utilities.decorators import beholder, seekset -from pcapkit.utilities.exceptions import ProtocolNotFound, ProtocolNotImplemented, StructError +from pcapkit.utilities.exceptions import (ProtocolNotFound, ProtocolNotImplemented, StructError, + UnsupportedCall) from pcapkit.utilities.logging import logger if TYPE_CHECKING: @@ -135,7 +136,13 @@ class Protocol(metaclass=abc.ABCMeta): @cached_property def packet(self) -> 'DataType_Packet': """DataType_Packet data of the protocol.""" - return self._read_packet(header=self.length) + try: + return self._read_packet(header=self.length) + except UnsupportedCall: + return DataType_Packet( + header=b'', + payload=self._read_packet(), + ) ########################################################################## # Methods.
revised protocol base cls (get packet in case when header length not supported)
JarryShaw_PyPCAPKit
train
4c3bcaf1cc418008ccf39cdd4658e85c36adff53
diff --git a/examples/webapi2/sample.py b/examples/webapi2/sample.py index <HASH>..<HASH> 100644 --- a/examples/webapi2/sample.py +++ b/examples/webapi2/sample.py @@ -13,20 +13,16 @@ CALLBACK_URL = "http://localhost:%d/callback" % PORT MAIN_PAGE_HTML = """\ <html> <body> - <script src="https://cdn.auth0.com/w2/auth0-widget-3.0.min.js"></script> + <script src="http://cdn.auth0.com/js/lock-6.6.1.min.js"></script> <script type="text/javascript"> - - var widget = new Auth0Widget({ - domain: '%s', - clientID: '%s', - callbackURL: '%s' - }); - + + var lock = new Auth0Lock({'%s', '%s'}); + </script> - <button onclick="widget.signin()">Login</button> + <button onclick="lock.show()">Login</button> </body> </html> -""" % (DOMAIN, CLIENT_ID, CALLBACK_URL) +""" % (CLIENT_ID, DOMAIN) class MainPage(webapp2.RequestHandler): @@ -38,16 +34,16 @@ class LoginCallback(webapp2.RequestHandler): def get(self): code = self.request.get("code") base_url = "https://{domain}".format(domain=DOMAIN) - data = urllib.urlencode([('client_id', CLIENT_ID), - ('redirect_uri', CALLBACK_URL), + data = urllib.urlencode([('client_id', CLIENT_ID), + ('redirect_uri', CALLBACK_URL), ('client_secret', CLIENT_SECRET), - ('code', code), + ('code', code), ('grant_type', 'authorization_code')]) req = urllib2.Request(base_url + "/oauth/token", data) response = urllib2.urlopen(req) oauth = json.loads(response.read()) userinfo = base_url + "/userinfo?access_token=" + oauth['access_token'] - + response = urllib2.urlopen(userinfo) data = response.read()
Migration Auth0Widget -> Auth0Lock
auth0_auth0-python
train
33ef46524cb90c79853870d76ea1c8eaf01d5ce3
diff --git a/lib/poolparty/core/kernel.rb b/lib/poolparty/core/kernel.rb index <HASH>..<HASH> 100644 --- a/lib/poolparty/core/kernel.rb +++ b/lib/poolparty/core/kernel.rb @@ -24,14 +24,21 @@ module Kernel ensure $-v = saved_verbosity end + + #redirect stdout and stderr to /dev/null and reopen after block def hide_output begin old_stdout = STDOUT.dup + old_stderr = STDERR.dup STDOUT.reopen(File.open((PLATFORM =~ /mswin/ ? "NUL" : "/dev/null"), 'w')) + STDERR.reopen(File.open((PLATFORM =~ /mswin/ ? "NUL" : "/dev/null"), 'w')) yield if block_given? ensure STDOUT.flush STDOUT.reopen(old_stdout) + STDERR.flush + STDERR.reopen(old_stderr) end end + end \ No newline at end of file
redirect stdout and stderr to /dev/null and reopen after block for hide_output method
auser_poolparty
train
8898eba97380b376129098afc2ad7f9a64ead9c9
diff --git a/jarn/mkrelease/tests/test_setuptools.py b/jarn/mkrelease/tests/test_setuptools.py index <HASH>..<HASH> 100644 --- a/jarn/mkrelease/tests/test_setuptools.py +++ b/jarn/mkrelease/tests/test_setuptools.py @@ -40,20 +40,20 @@ class SubversionTests(SubversionSetup): def testSubversionSdistPy(self): st = Setuptools(defaults, Process(quiet=True)) # This uses svn to create the manifest. - archive = st.run_sdist(self.clonedir, ['--formats=zip'], quiet=True) + archive = st.run_sdist(self.clonedir, ['--formats=zip']) self.assertEqual(contains(archive, 'subversion_only.py'), True) def testSubversionSdistTxt(self): st = Setuptools(defaults, Process(quiet=True)) # This uses svn to create the manifest. - archive = st.run_sdist(self.clonedir, ['--formats=zip'], quiet=True) + archive = st.run_sdist(self.clonedir, ['--formats=zip']) self.assertEqual(contains(archive, 'subversion_only.txt'), True) def testDefaultSdistPy(self): st = Setuptools(defaults, Process(quiet=True)) self.destroy(self.clonedir) # This uses ??? to create the manifest. - archive = st.run_sdist(self.clonedir, ['--formats=zip'], quiet=True) + archive = st.run_sdist(self.clonedir, ['--formats=zip']) self.assertEqual(contains(archive, 'subversion_only.py'), True) def testDefaultSdistTxt(self): @@ -61,7 +61,7 @@ class SubversionTests(SubversionSetup): self.destroy(self.clonedir) # This uses ??? to create the manifest. Note that the .txt file # is missing from the archive. - archive = st.run_sdist(self.clonedir, ['--formats=zip'], quiet=True) + archive = st.run_sdist(self.clonedir, ['--formats=zip']) self.assertEqual(contains(archive, 'subversion_only.txt'), False) @@ -77,14 +77,14 @@ class MercurialTests(MercurialSetup): st = Setuptools(defaults, Process(quiet=True)) self.clone() # This uses hg to create the manifest. - archive = st.run_sdist(self.clonedir, ['--formats=zip'], quiet=True) + archive = st.run_sdist(self.clonedir, ['--formats=zip']) self.assertEqual(contains(archive, 'mercurial_only.py'), True) def testMercurialSdistTxt(self): st = Setuptools(defaults, Process(quiet=True)) self.clone() # This uses hg to create the manifest. - archive = st.run_sdist(self.clonedir, ['--formats=zip'], quiet=True) + archive = st.run_sdist(self.clonedir, ['--formats=zip']) self.assertEqual(contains(archive, 'mercurial_only.txt'), True) @@ -100,13 +100,13 @@ class GitTests(GitSetup): st = Setuptools(defaults, Process(quiet=True)) self.clone() # This uses git to create the manifest. - archive = st.run_sdist(self.clonedir, ['--formats=zip'], quiet=True) + archive = st.run_sdist(self.clonedir, ['--formats=zip']) self.assertEqual(contains(archive, 'git_only.py'), True) def testGitSdistTxt(self): st = Setuptools(defaults, Process(quiet=True)) self.clone() # This uses git to create the manifest. - archive = st.run_sdist(self.clonedir, ['--formats=zip'], quiet=True) + archive = st.run_sdist(self.clonedir, ['--formats=zip']) self.assertEqual(contains(archive, 'git_only.txt'), True)
Don't need the quiet arg here.
Jarn_jarn.mkrelease
train
726d94c8e9f44986b58053e65ff52cdeb779eadd
diff --git a/callbacks.go b/callbacks.go index <HASH>..<HASH> 100644 --- a/callbacks.go +++ b/callbacks.go @@ -34,12 +34,12 @@ func BasicAuthorizer(credentials map[string]string) *Callback { }) } -// TimestampValidator will set timestamp fields on create and update operations. +// TimestampModifier will set timestamp fields on create and update operations. // The fields are inferred from the model using the "fire-created-timestamp" and // "fire-updated-timestamp" flags. Missing created timestamps are retroactively // set using the timestamp encoded in the model id. -func TimestampValidator() *Callback { - return C("fire/TimestampValidator", Only(Create, Update), func(ctx *Context) error { +func TimestampModifier() *Callback { + return C("fire/TimestampModifier", Only(Create, Update), func(ctx *Context) error { // get time now := time.Now() diff --git a/callbacks_test.go b/callbacks_test.go index <HASH>..<HASH> 100644 --- a/callbacks_test.go +++ b/callbacks_test.go @@ -52,7 +52,7 @@ func TestBasicAuthorizer(t *testing.T) { }) } -func TestTimestampValidator(t *testing.T) { +func TestTimestampModifier(t *testing.T) { withTester(t, func(t *testing.T, tester *Tester) { type model struct { coal.Base `json:"-" bson:",inline" coal:"posts"` @@ -63,7 +63,7 @@ func TestTimestampValidator(t *testing.T) { m := &model{} - validator := TimestampValidator() + validator := TimestampModifier() err := tester.RunCallback(&Context{Operation: Create, Model: m}, validator) assert.NoError(t, err) diff --git a/example/controllers.go b/example/controllers.go index <HASH>..<HASH> 100644 --- a/example/controllers.go +++ b/example/controllers.go @@ -16,9 +16,11 @@ func itemController(store *coal.Store, queue *axe.Queue, storage *blaze.Storage) Authorizers: fire.L{ flame.Callback(true), }, - Validators: fire.L{ + Modifiers: fire.L{ storage.Validator(), - fire.TimestampValidator(), + fire.TimestampModifier(), + }, + Validators: fire.L{ fire.RelationshipValidator(&Item{}, catalog), }, Decorators: fire.L{
renanmed to timestamp modifier
256dpi_fire
train
fa0c3ce1e6bb7d7fcbc1928a58f0253a879d051b
diff --git a/kitchen-tests/cookbooks/end_to_end/recipes/windows.rb b/kitchen-tests/cookbooks/end_to_end/recipes/windows.rb index <HASH>..<HASH> 100644 --- a/kitchen-tests/cookbooks/end_to_end/recipes/windows.rb +++ b/kitchen-tests/cookbooks/end_to_end/recipes/windows.rb @@ -47,6 +47,30 @@ windows_firewall_profile "Public" do action :disable end +windows_audit_policy "Update Some Advanced Audit Policies to Success and Failure" do + subcategory subcategory ["Application Generated", "Application Group Management", "Audit Policy Change"] + success true + failure true +end + +windows_audit_policy "Update Some Advanced Audit Policies to Success only" do + subcategory subcategory ["Authentication Policy Change", "Authorization Policy Change"] + success true + failure false +end + +windows_audit_policy "Update Some Advanced Audit Policies to Failure only" do + subcategory subcategory ["Central Policy Staging", "Certification Services", "Computer Account Management"] + success false + failure true +end + +windows_audit_policy "Update Some Advanced Audit Policies to No Auditing" do + subcategory subcategory ["Credential Validation", "DPAPI Activity", "Detailed File Share"] + success false + failure false +end + users_manage "remove sysadmin" do group_name "sysadmin" group_id 2300 diff --git a/lib/chef/resource/windows_audit_policy.rb b/lib/chef/resource/windows_audit_policy.rb index <HASH>..<HASH> 100644 --- a/lib/chef/resource/windows_audit_policy.rb +++ b/lib/chef/resource/windows_audit_policy.rb @@ -152,30 +152,6 @@ class Chef property :audit_base_directories, [true, false], description: "Setting this audit policy option to true will force the system to assign a System Access Control List to named objects to enable auditing of container objects such as directories." - def subcategory_configured?(sub_cat, success_value, failure_value) - setting = if success_value && failure_value - "Success and Failure$" - elsif success_value && !failure_value - "Success$" - elsif !success_value && failure_value - "(Failure$)&!(Success and Failure$)" - else - "No Auditing" - end - powershell_exec(<<-CODE).result - $auditpol_config = auditpol /get /subcategory:"#{sub_cat}" - if ($auditpol_config | Select-String "#{setting}") { return $true } else { return $false } - CODE - end - - def option_configured?(option_name, option_setting) - setting = option_setting ? "Enabled$" : "Disabled$" - powershell_exec(<<-CODE).result - $auditpol_config = auditpol /get /option:#{option_name} - if ($auditpol_config | Select-String "#{setting}") { return $true } else { return $false } - CODE - end - action :set do unless new_resource.subcategory.nil? new_resource.subcategory.each do |subcategory| @@ -225,6 +201,32 @@ class Chef end end end + + action_class do + def subcategory_configured?(sub_cat, success_value, failure_value) + setting = if success_value && failure_value + "Success and Failure$" + elsif success_value && !failure_value + "Success$" + elsif !success_value && failure_value + "#{sub_cat} \\s+ Failure$" + else + "No Auditing" + end + powershell_exec!(<<-CODE).result + $auditpol_config = auditpol /get /subcategory:"#{sub_cat}" + if ($auditpol_config | Select-String "#{setting}") { return $true } else { return $false } + CODE + end + + def option_configured?(option_name, option_setting) + setting = option_setting ? "Enabled$" : "Disabled$" + powershell_exec!(<<-CODE).result + $auditpol_config = auditpol /get /option:#{option_name} + if ($auditpol_config | Select-String "#{setting}") { return $true } else { return $false } + CODE + end + end end end end
fix for the windows_audit_policy resource and added some tests for it into the windows end-to-end kitchen testing.
chef_chef
train
0d0bc02950f75c8cc43d6b4f3af02c872ff42629
diff --git a/wolframalpha/__init__.py b/wolframalpha/__init__.py index <HASH>..<HASH> 100644 --- a/wolframalpha/__init__.py +++ b/wolframalpha/__init__.py @@ -113,8 +113,8 @@ class Client: resp = urllib.request.urlopen(url) assert resp.headers.get_content_type() == 'text/xml' assert resp.headers.get_param('charset') == 'utf-8' - doc = xmltodict.parse(resp) - return Result(doc['queryresult']) + doc = xmltodict.parse(resp, postprocessor=Document.make) + return doc['queryresult'] class ErrorHandler: @@ -135,6 +135,31 @@ class Document(dict): "Override the types from the document" @classmethod + def make(cls, path, key, value): + if key == 'queryresult': + value = Result(value) + if key == 'pod': + value = Pod(value) + key = 'pods' + if key == 'img': + value = Image(value) + if key == 'subpod': + value = Subpod(value) + key = 'subpods' + if key == 'assumption': + value = Assumption(value) + key = 'assumptions' + if key == 'warning': # pragma: nocover + value = Warning(value) + key = 'warnings' + if key in ('@height', '@width', '@numsubpods'): + value = int(value) + if key in ('@position',): + value = float(value) + + return key, value + + @classmethod def from_doc(cls, doc): """ Load instances from the xmltodict result. Always return @@ -173,21 +198,12 @@ class Image(Document): Holds information about an image included with an answer. """ - _attr_types = dict( - height=int, - width=int, - ) - class Subpod(Document): """ Holds a specific answer or additional information relevant to said answer. """ - _attr_types = dict( - img=Image.from_doc, - ) - def xml_bool(str_val): """ @@ -204,16 +220,6 @@ class Pod(ErrorHandler, Document): Groups answers and information contextualizing those answers. """ - _attr_types = dict( - position=float, - numsubpods=int, - subpod=Subpod.from_doc, - ) - - @property - def subpods(self): - return self.subpod - @property def primary(self): return '@primary' in self and xml_bool(self['@primary']) @@ -223,11 +229,15 @@ class Pod(ErrorHandler, Document): """ The text from each subpod in this pod as a list. """ - return [subpod.plaintext for subpod in self.subpod] + return [subpod.plaintext for subpod in self.subpods] @property def text(self): - return next(iter(self.subpod)).plaintext + return next(iter(self.subpods)).plaintext + + @property + def subpods(self): + return always_iterable(self.get('subpods'), base_type=dict) class Result(ErrorHandler, Document): @@ -244,15 +254,15 @@ class Result(ErrorHandler, Document): @property def pods(self): - return Pod.from_doc(self.get('pod')) + return always_iterable(self.get('pods'), base_type=dict) @property def assumptions(self): - return Assumption.from_doc(self.get('assumptions')) + return always_iterable(self.get('assumptions')) @property def warnings(self): - return Warning.from_doc(self.get('warnings')) + return always_iterable(self.get('warnings')) def __iter__(self): return self.info diff --git a/wolframalpha/test_client.py b/wolframalpha/test_client.py index <HASH>..<HASH> 100644 --- a/wolframalpha/test_client.py +++ b/wolframalpha/test_client.py @@ -47,7 +47,7 @@ def test_pod_attributes(temp_result): pod = next(temp_result.pods) assert isinstance(pod.position, float) assert isinstance(pod.id, str) - img = next(next(pod.subpod).img) + img = next(iter(pod.subpods)).img assert isinstance(img.height, int)
Process Document subclasses during the XML parsing.
jaraco_wolframalpha
train
6f952718643cd13c72a2b9fbfa8a79198d2a1bb6
diff --git a/src/com/google/javascript/jscomp/CheckRequiresForConstructors.java b/src/com/google/javascript/jscomp/CheckRequiresForConstructors.java index <HASH>..<HASH> 100644 --- a/src/com/google/javascript/jscomp/CheckRequiresForConstructors.java +++ b/src/com/google/javascript/jscomp/CheckRequiresForConstructors.java @@ -111,12 +111,9 @@ public class CheckRequiresForConstructors implements HotSwapCompilerPass, NodeTr this.codingConvention = compiler.getCodingConvention(); } - /** - * Uses Collections of new and goog.require nodes to create a compiler warning - * for each new class name without a corresponding goog.require(). - */ @Override public void process(Node externs, Node root) { + reset(); NodeTraversal.traverseRootsEs6(compiler, this, externs, root); } @@ -125,6 +122,7 @@ public class CheckRequiresForConstructors implements HotSwapCompilerPass, NodeTr // TODO(joeltine): Remove this and properly handle hot swap passes. See // b/28869281 for context. mode = Mode.SINGLE_FILE; + reset(); NodeTraversal.traverseEs6(compiler, scriptRoot, this); } @@ -249,6 +247,7 @@ public class CheckRequiresForConstructors implements HotSwapCompilerPass, NodeTr this.weakUsages.clear(); this.requires.clear(); this.closurizedNamespaces.clear(); + this.closurizedNamespaces.add("goog"); this.providedNames.clear(); this.googScopeBlock = null; } diff --git a/test/com/google/javascript/jscomp/MissingRequireTest.java b/test/com/google/javascript/jscomp/MissingRequireTest.java index <HASH>..<HASH> 100644 --- a/test/com/google/javascript/jscomp/MissingRequireTest.java +++ b/test/com/google/javascript/jscomp/MissingRequireTest.java @@ -444,6 +444,13 @@ public final class MissingRequireTest extends Es6CompilerTestCase { "missing require: 'example.Outer'"); } + public void testFailGoogArray() { + mode = CheckRequiresForConstructors.Mode.SINGLE_FILE; + testMissingRequireStrict( + "console.log(goog.array.contains([1, 2, 3], 4));", + "missing require: 'goog.array'"); + } + public void testPassConstant() { testSame("goog.require('example.Constants'); alert(example.Constants.FOO);"); testSame("goog.require('example.Outer'); alert(example.Outer.Inner.FOO);");
Treat "goog" as a Closurized namespace unconditionally. ------------- Created by MOE: <URL>
google_closure-compiler
train
367eb1f80c6dc7f6fbcbbef48a51bc95259514a3
diff --git a/lib/rest_pki/authentication.rb b/lib/rest_pki/authentication.rb index <HASH>..<HASH> 100755 --- a/lib/rest_pki/authentication.rb +++ b/lib/rest_pki/authentication.rb @@ -13,12 +13,12 @@ module RestPki def start_with_webpki(security_context_id) request = {securityContextId: security_context_id} - response = @restpki_client.post('Api/Authentications', data: request, object_model: 'authentication_model') + response = @restpki_client.post('Api/Authentications', request, 'authentication_model') response.token end def complete_with_webpki(token) - response = @restpki_client.post("Api/Authentications/#{token}/Finalize", data: null, object_model: 'authentication_model') + response = @restpki_client.post("Api/Authentications/#{token}/Finalize", nil, 'authentication_model') unless response.certificate.nil? @certificate = response.certificate end diff --git a/lib/rest_pki/full_xml_signature_starter.rb b/lib/rest_pki/full_xml_signature_starter.rb index <HASH>..<HASH> 100644 --- a/lib/rest_pki/full_xml_signature_starter.rb +++ b/lib/rest_pki/full_xml_signature_starter.rb @@ -12,12 +12,12 @@ module RestPki end request = get_request - response = @restpki_client.post('Api/XmlSignatures/FullXmlSignature', params: request, object_model: 'xml_model') + response = @restpki_client.post('Api/XmlSignatures/FullXmlSignature', request, 'xml_model') unless response.certificate.nil? - @signer_certificate = response.certificate - end - @done = true + @signer_certificate = response.certificate + end + @done = true response.token end diff --git a/lib/rest_pki/pades_signature_finisher.rb b/lib/rest_pki/pades_signature_finisher.rb index <HASH>..<HASH> 100644 --- a/lib/rest_pki/pades_signature_finisher.rb +++ b/lib/rest_pki/pades_signature_finisher.rb @@ -12,10 +12,10 @@ module RestPki end response = nil if @signature.nil? - response = @restpki_client.post("Api/PadesSignatures/#{@token}/Finalize", data: null, object_model: 'pades_model') + response = @restpki_client.post("Api/PadesSignatures/#{@token}/Finalize", nil, 'pades_model') else request = { signature: Base64.encode64(@signature) } - response = @restpki_client.post("Api/PadesSignatures/#{@token}/SignedBytes", data: request, object_model: 'pades_model') + response = @restpki_client.post("Api/PadesSignatures/#{@token}/SignedBytes", request, 'pades_model') end @signed_pdf_content = Base64.decode64(response.signedPdf) diff --git a/lib/rest_pki/pades_signature_starter.rb b/lib/rest_pki/pades_signature_starter.rb index <HASH>..<HASH> 100644 --- a/lib/rest_pki/pades_signature_starter.rb +++ b/lib/rest_pki/pades_signature_starter.rb @@ -55,7 +55,7 @@ module RestPki request['certificate'] = Base64.encode64(@signer_certificate) end - response = @restpki_client.post('Api/PadesSignatures', data: request, object_model: 'pades_model') + response = @restpki_client.post('Api/PadesSignatures', request, 'pades_model') unless response.certificate.nil? @signer_certificate = response.certificate diff --git a/lib/rest_pki/xml_element_signature_starter.rb b/lib/rest_pki/xml_element_signature_starter.rb index <HASH>..<HASH> 100644 --- a/lib/rest_pki/xml_element_signature_starter.rb +++ b/lib/rest_pki/xml_element_signature_starter.rb @@ -23,7 +23,7 @@ module RestPki request['idResolutionTable'] = @id_resolution_table.to_model end - response = @restpki_client.post('Api/XmlSignatures/XmlElementSignature', params: request, object_model: 'xml_model') + response = @restpki_client.post('Api/XmlSignatures/XmlElementSignature', request, 'xml_model') unless response.certificate.nil? @certificate = response.certificate diff --git a/lib/rest_pki/xml_signature_finisher.rb b/lib/rest_pki/xml_signature_finisher.rb index <HASH>..<HASH> 100644 --- a/lib/rest_pki/xml_signature_finisher.rb +++ b/lib/rest_pki/xml_signature_finisher.rb @@ -15,10 +15,10 @@ module RestPki end response = nil if @signature.nil? - response = @restpki_client.post("Api/XmlSignatures/#{@token}/Finalize", data: null, object_model: 'xml_model') + response = @restpki_client.post("Api/XmlSignatures/#{@token}/Finalize", nil, 'xml_model') else request = { signature: Base64.encode64(@signature) } - response = @restpki_client.post("Api/XmlSignatures/#{@token}/SignedBytes", data: request, object_model: 'xml_model') + response = @restpki_client.post("Api/XmlSignatures/#{@token}/SignedBytes", request, 'xml_model') end @signed_xml_content = Base64.decode64(response.signedXml)
Fixed request method calls and nil values;
LacunaSoftware_RestPkiRubyClient
train
dcd68633bc41fd7582bc327323a446c072d0a3a6
diff --git a/scripts/importer/mtasks/snfactory.py b/scripts/importer/mtasks/snfactory.py index <HASH>..<HASH> 100644 --- a/scripts/importer/mtasks/snfactory.py +++ b/scripts/importer/mtasks/snfactory.py @@ -7,18 +7,19 @@ from glob import glob import os from scripts import PATH -from . constants import TRAVIS_QUERY_LIMIT +from .. constants import TRAVIS_QUERY_LIMIT, OSC_BIBCODE, OSC_NAME, OSC_URL from .. import Events from .. funcs import add_spectrum, get_preferred_name, jd_to_mjd, uniq_cdl from ... utils import pretty_num def do_snf_aliases(events, stubs, args, tasks, task_obj, log): - with open('../sne-external/SNF/snf-aliases.csv') as f: + file_path = os.path.join(PATH.REPO_EXTERNAL, 'SNF/snf-aliases.csv') + with open(file_path, 'r') as f: for row in [x.split(',') for x in f.read().splitlines()]: events, name, source = Events.new_event(tasks, args, events, row[0], log, - bibcode = oscbibcode, refname = oscname, - url = oscurl, secondary = True) + bibcode = OSC_BIBCODE, srcname = OSC_NAME, + url = OSC_URL, secondary = True) events[name].add_quantity('alias', row[1], source) events, stubs = Events.journal_events(tasks, args, events, stubs, log)
MAINT: added missing OSC constants.
astrocatalogs_astrocats
train
f0cbace3536a7a4e8eea4944635f002a9501640f
diff --git a/lime/submodular_pick.py b/lime/submodular_pick.py index <HASH>..<HASH> 100644 --- a/lime/submodular_pick.py +++ b/lime/submodular_pick.py @@ -122,3 +122,4 @@ class SubmodularPick(object): remaining_indices -= {best_ind} self.sp_explanations = [self.explanations[i] for i in V] + self.V=V
saves picked indices close issue #<I>
marcotcr_lime
train
f71c078c289b7f89d00f0538cb8b3fcd1e743955
diff --git a/bigtable-grpc-interface/src/main/java/com/google/cloud/bigtable/grpc/ReconnectingChannel.java b/bigtable-grpc-interface/src/main/java/com/google/cloud/bigtable/grpc/ReconnectingChannel.java index <HASH>..<HASH> 100644 --- a/bigtable-grpc-interface/src/main/java/com/google/cloud/bigtable/grpc/ReconnectingChannel.java +++ b/bigtable-grpc-interface/src/main/java/com/google/cloud/bigtable/grpc/ReconnectingChannel.java @@ -40,7 +40,7 @@ import com.google.common.util.concurrent.ThreadFactoryBuilder; */ public class ReconnectingChannel extends Channel implements Closeable { - protected static final Logger log = Logger.getLogger(ChannelPool.class.getName()); + protected static final Logger log = Logger.getLogger(ReconnectingChannel.class.getName()); public static final long CHANNEL_TERMINATE_WAIT_MS = 5000; // This executor is used to shutdown & await termination of
Fixing the logger in ReconnectingChannel.
googleapis_cloud-bigtable-client
train
fd76b87ab8e2ffca83eb4affae63a1b72a455688
diff --git a/worker/uniter/storage/source.go b/worker/uniter/storage/source.go index <HASH>..<HASH> 100644 --- a/worker/uniter/storage/source.go +++ b/worker/uniter/storage/source.go @@ -210,7 +210,6 @@ func (s *storageHookQueue) Update(attachment params.StorageAttachment) error { if attachment.Life == params.Alive { s.hookInfo.Kind = hooks.StorageAttached } else { - // TODO(axw) this should be Detaching, not Detached. s.hookInfo.Kind = hooks.StorageDetaching } logger.Debugf("queued hook: %v", s.hookInfo)
worker/uniter/storage: remove TODO
juju_juju
train
c0efc5dc20952601722095cafb24a8152342e4ff
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 @@ -867,6 +867,7 @@ def purge(vm_, dirs=False): if dirs: for dir_ in directories: shutil.rmtree(dir_) + undefine(vm_) return True diff --git a/salt/runners/virt.py b/salt/runners/virt.py index <HASH>..<HASH> 100644 --- a/salt/runners/virt.py +++ b/salt/runners/virt.py @@ -64,7 +64,7 @@ def init(name, cpu, mem, image, hyper=None): ''' Initialize a new vm ''' - data = query(hyper) + data = query(hyper, quiet=True) if hyper: if not hyper in data: return @@ -87,3 +87,36 @@ def init(name, cpu, mem, image, hyper=None): return ret + +def vm_info(name, quiet=False): + ''' + Return the information on the named vm + ''' + data = query(quiet=True) + for hv_ in data: + if name in data[hv_].get('vm_info', {}): + ret = {hv_: {name: data[hv_]['vm_info'][name]}} + if not quiet: + salt.output.display_output( + ret, + 'nested', + __opts__) + return ret + + +def destroy(name): + ''' + Destroy the named vm + ''' + client = salt.client.LocalClient(__opts__['conf_file']) + data = vm_info(name, quiet=True) + if not data: + return + hyper = data.keys()[0] + vm_ = data[hyper].keys()[0] + cmd_ret = client.cmd_iter( + hyper, + 'virt.purge', + [vm_, True], + timeout=600) +
Add vm_info and destroy to the virt runner
saltstack_salt
train
b9aec349a7127e74b49578a9187143f2f0fda9ae
diff --git a/src/main/java/com/wiley/autotest/selenium/elements/upgrade/DefaultTeasyElementFactory.java b/src/main/java/com/wiley/autotest/selenium/elements/upgrade/DefaultTeasyElementFactory.java index <HASH>..<HASH> 100644 --- a/src/main/java/com/wiley/autotest/selenium/elements/upgrade/DefaultTeasyElementFactory.java +++ b/src/main/java/com/wiley/autotest/selenium/elements/upgrade/DefaultTeasyElementFactory.java @@ -6,7 +6,7 @@ package com.wiley.autotest.selenium.elements.upgrade; */ public class DefaultTeasyElementFactory extends TeasyElementFactory { - public DefaultTeasyElementFactory(TeasyElementData elementData) { + DefaultTeasyElementFactory(TeasyElementData elementData) { super(elementData); }
made constructor package-private as per suggestion in review
WileyLabs_teasy
train
28300467a81a23f6e488d8c82bcd64c94f7fe028
diff --git a/src/Model/MessagePerson.php b/src/Model/MessagePerson.php index <HASH>..<HASH> 100644 --- a/src/Model/MessagePerson.php +++ b/src/Model/MessagePerson.php @@ -83,6 +83,14 @@ class MessagePerson implements MessagePersonInterface /** * {@inheritdoc} */ + public function setNotRead() + { + $this->read = null; + } + + /** + * {@inheritdoc} + */ public function isRead() { return $this->read instanceof \DateTime; diff --git a/src/Model/MessagePersonInterface.php b/src/Model/MessagePersonInterface.php index <HASH>..<HASH> 100644 --- a/src/Model/MessagePersonInterface.php +++ b/src/Model/MessagePersonInterface.php @@ -41,6 +41,11 @@ interface MessagePersonInterface public function setRead(); /** + * Set the read date of the message as null (unread). + */ + public function setNotRead(); + + /** * Return the exact time the message was read by the person. * * @return \DateTime
Add setNotRead() method in MessagePerson
FriendsOfSymfony_FOSMessage
train
a468edd1646ba76a19221e43173dd4fb8677ee03
diff --git a/library/CM/Dom/NodeList.php b/library/CM/Dom/NodeList.php index <HASH>..<HASH> 100644 --- a/library/CM/Dom/NodeList.php +++ b/library/CM/Dom/NodeList.php @@ -138,7 +138,7 @@ class CM_Dom_NodeList implements Iterator, Countable { $xpath = preg_replace('/\[([\w-]+)\]/', '[@$1]', $xpath); $xpath = str_replace(':last', '[last()]', str_replace(':first', '[1]', $xpath)); $xpath = preg_replace_callback('/:eq\((\d+)\)/', function ($matches) { - return '"[".("' . $matches[1] . '"+1)."]"'; + return '[' . ($matches[1] + 1) . ']'; }, $xpath); $xpath = preg_replace('/\.([\w-]*)/', '[contains(concat(" ",@class," "),concat(" ","$1"," "))]', $xpath); $xpath = preg_replace('/#([\w-]*)/', '[@id="$1"]', $xpath);
Fixed callback in CM_Dom_NodeList
cargomedia_cm
train
e6d83459a37fc4f5f086311399a2f8beb41c6505
diff --git a/src/Krucas/Counter/Counter.php b/src/Krucas/Counter/Counter.php index <HASH>..<HASH> 100644 --- a/src/Krucas/Counter/Counter.php +++ b/src/Krucas/Counter/Counter.php @@ -155,6 +155,8 @@ class Counter return $values; } + + return new Exists(false); } /**
When not found any ranges return false
edvinaskrucas_counter
train
0144fce918fa755447557a218cbf70f71d46030a
diff --git a/main.js b/main.js index <HASH>..<HASH> 100755 --- a/main.js +++ b/main.js @@ -619,26 +619,28 @@ define(function (require, exports, module) { return; } var current_string_from_start_to_cursor = current_line.substr(0, cursor_position.ch); + var variable_name; + var char_before_search_name; var words_before_cursor = current_string_from_start_to_cursor.match(/[\w\d_]+/g); - words_before_cursor.pop(); - var variable_name = _.last(words_before_cursor); - var char_before_search_name = current_string_from_start_to_cursor.substr((current_string_from_start_to_cursor.lastIndexOf(variable_name) + variable_name.length), 1); + if (words_before_cursor.length > 0) { + words_before_cursor.pop(); + variable_name = _.last(words_before_cursor); + if (variable_name) { + char_before_search_name = current_string_from_start_to_cursor.substr((current_string_from_start_to_cursor.lastIndexOf(variable_name) + variable_name.length), 1); + } + } if (char_before_search_name === '.' && variable_name) { current_editor.setCursorPos({ line: current_line_position, ch: current_line.lastIndexOf(variable_name + '.' + search_name) }); - command_manager.execute(commands.NAVIGATE_JUMPTO_DEFINITION, current_editor).done(function () { - cursor_position = current_editor.getCursorPos(); - current_line_position = cursor_position.line; - current_line = current_editor._codeMirror.doc.getLine(current_line_position); - go_to_require(current_editor, current_line, search_name); - }); - } - else { + command_manager.execute(commands.NAVIGATE_JUMPTO_DEFINITION, current_editor).done(function () { + cursor_position = current_editor.getCursorPos(); + current_line_position = cursor_position.line; + current_line = current_editor._codeMirror.doc.getLine(current_line_position); go_to_require(current_editor, current_line, search_name); - } + }); }); editor_context_menu.addMenuItem(GO_TO_DECLARATION_COMMAND_ID, 'Ctrl-Alt-B', menus.LAST); /****************************************************************************/
added empty check for "go to declaration" command
yacut_brackets-nodejs-integration
train
6eb949701890fef8d0d81b9aa8ef908c02d471cb
diff --git a/gshell-assembly/src/main/java/org/apache/gshell/Main.java b/gshell-assembly/src/main/java/org/apache/gshell/Main.java index <HASH>..<HASH> 100644 --- a/gshell-assembly/src/main/java/org/apache/gshell/Main.java +++ b/gshell-assembly/src/main/java/org/apache/gshell/Main.java @@ -28,6 +28,7 @@ import org.apache.gshell.core.console.ConsolePrompterImpl; import org.apache.gshell.core.guice.GuiceShellBuilder; import org.fusesource.jansi.AnsiConsole; import jline.console.completers.AggregateCompleter; +import jline.WindowsTerminal; import java.io.PrintStream; @@ -71,6 +72,9 @@ public class Main final PrintStream err = System.err; System.setErr(new PrintStream(AnsiConsole.wrapOutputStream(err))); + // We support Ansi on windows with jansi so flip it on + System.setProperty(WindowsTerminal.ANSI, Boolean.TRUE.toString()); + try { new Main().boot(args); } diff --git a/gshell-core/src/main/java/org/apache/gshell/core/MainSupport.java b/gshell-core/src/main/java/org/apache/gshell/core/MainSupport.java index <HASH>..<HASH> 100644 --- a/gshell-core/src/main/java/org/apache/gshell/core/MainSupport.java +++ b/gshell-core/src/main/java/org/apache/gshell/core/MainSupport.java @@ -19,11 +19,11 @@ package org.apache.gshell.core; +import jline.TerminalFactory; import org.apache.gshell.Branding; import org.apache.gshell.Shell; import org.apache.gshell.VariableNames; import org.apache.gshell.Variables; -import org.apache.gshell.internal.Log; import org.apache.gshell.ansi.Ansi; import org.apache.gshell.ansi.AnsiRendererIO; import org.apache.gshell.cli.Argument; @@ -35,16 +35,13 @@ import org.apache.gshell.cli.Processor; import org.apache.gshell.cli.handler.StopHandler; import org.apache.gshell.i18n.MessageSource; import org.apache.gshell.i18n.ResourceBundleMessageSource; +import org.apache.gshell.internal.Log; import org.apache.gshell.io.IO; import org.apache.gshell.notification.ExitNotification; -import org.fusesource.jansi.AnsiConsole; import java.util.List; import java.util.concurrent.atomic.AtomicReference; -import jline.TerminalFactory; -import jline.WindowsTerminal; - /** * Support for booting shell applications. * @@ -168,8 +165,6 @@ public abstract class MainSupport // Setup environment defaults setConsoleLogLevel(Log.Level.WARN); - AnsiConsole.systemInstall(); - System.setProperty(WindowsTerminal.ANSI, Boolean.TRUE.toString()); setTerminalType(TerminalFactory.Type.AUTO); // Process command line options & arguments diff --git a/gshell-core/src/main/resources/org/apache/gshell/core/MainSupport.properties b/gshell-core/src/main/resources/org/apache/gshell/core/MainSupport.properties index <HASH>..<HASH> 100644 --- a/gshell-core/src/main/resources/org/apache/gshell/core/MainSupport.properties +++ b/gshell-core/src/main/resources/org/apache/gshell/core/MainSupport.properties @@ -23,8 +23,6 @@ option.stop=Stop processing options option.version=Display program version -option.interactive=Run in interactive mode - option.showErrorTraces=Produce execution error messages option.setDebug=Enable DEBUG output @@ -48,8 +46,9 @@ option.setSystemProperty=Define a system property option.setSystemProperty.token=NAME=VALUE option.enableAnsiColors=Enable or disable use of ANSI colors +option.enableAnsiColors.token=[true|false] -option.setTerminalType=Specify the terminal TYPE to use -option.setTerminalType.token=TYPE +option.setTerminalType=Specify the terminal to use +option.setTerminalType.token=[auto|win|unix|none|<type>] warning.abnormalShutdown=WARNING: Abnormal JVM shutdown detected \ No newline at end of file
Tidy, add better tokens for main --help, move ansi muck to Main for now
jdillon_gshell
train
aa0af0e8bf4e29fefa6bf074533fff266c38d566
diff --git a/src/main/java/io/github/classgraph/ClassInfo.java b/src/main/java/io/github/classgraph/ClassInfo.java index <HASH>..<HASH> 100644 --- a/src/main/java/io/github/classgraph/ClassInfo.java +++ b/src/main/java/io/github/classgraph/ClassInfo.java @@ -142,7 +142,7 @@ public class ClassInfo extends ScanResultObject implements Comparable<ClassInfo> AnnotationParameterValueList annotationDefaultParamValues; /** The type annotation decorators for the {@link ClassTypeSignature} instance. */ - List<ClassTypeAnnotationDecorator> typeAnnotationDecorators; + transient List<ClassTypeAnnotationDecorator> typeAnnotationDecorators; /** * Names of classes referenced by this class in class refs and type signatures in the constant pool of the diff --git a/src/main/java/io/github/classgraph/FieldInfo.java b/src/main/java/io/github/classgraph/FieldInfo.java index <HASH>..<HASH> 100644 --- a/src/main/java/io/github/classgraph/FieldInfo.java +++ b/src/main/java/io/github/classgraph/FieldInfo.java @@ -78,7 +78,7 @@ public class FieldInfo extends ScanResultObject implements Comparable<FieldInfo> AnnotationInfoList annotationInfo; /** The type annotation decorators for the {@link TypeSignature} instance of this field. */ - private List<TypeAnnotationDecorator> typeAnnotationDecorators; + private transient List<TypeAnnotationDecorator> typeAnnotationDecorators; // ------------------------------------------------------------------------------------------------------------- diff --git a/src/main/java/io/github/classgraph/MethodInfo.java b/src/main/java/io/github/classgraph/MethodInfo.java index <HASH>..<HASH> 100644 --- a/src/main/java/io/github/classgraph/MethodInfo.java +++ b/src/main/java/io/github/classgraph/MethodInfo.java @@ -104,7 +104,7 @@ public class MethodInfo extends ScanResultObject implements Comparable<MethodInf private boolean hasBody; /** The type annotation decorators for the {@link MethodTypeSignature} instance. */ - private List<MethodTypeAnnotationDecorator> typeAnnotationDecorators; + private transient List<MethodTypeAnnotationDecorator> typeAnnotationDecorators; private String[] thrownExceptionNames;
Solve JSON serialization exception (#<I>)
classgraph_classgraph
train
35cfd6991391de1876902290cf12d7646ce62289
diff --git a/qpth/qp.py b/qpth/qp.py index <HASH>..<HASH> 100755 --- a/qpth/qp.py +++ b/qpth/qp.py @@ -74,6 +74,14 @@ class QPFunction(Function): Returns: \hat z: a (nBatch, nz) Tensor. """ + if not np.all([x.is_cuda for x in [Q_,p_,G_,h_,A_,b_]]): + raise RuntimeError(""" +Error: Not using CUDA. +qpth currently silently fails on the CPU and returns bad solutions. +We are tracking progress on this issue at: +https://github.com/locuslab/qpth/issues/4""") + + start = time.time() nBatch = extract_nBatch(Q_, p_, G_, h_, A_, b_) Q, _ = expandParam(Q_, nBatch, 3)
Add RuntimeError if CUDA is not being used.
locuslab_qpth
train
da259a8ec77caa424d14d7e2f4f86b5a666cff50
diff --git a/gcloud/pubsub/_gax.py b/gcloud/pubsub/_gax.py index <HASH>..<HASH> 100644 --- a/gcloud/pubsub/_gax.py +++ b/gcloud/pubsub/_gax.py @@ -162,22 +162,16 @@ class _PublisherAPI(object): :raises: :exc:`gcloud.exceptions.NotFound` if the topic does not exist """ - options = CallOptions(is_bundling=True) message_pbs = [_message_pb_from_dict(message) for message in messages] try: - # result = self._gax_api.publish(topic_path, message_pbs, - # options=options) - - event = self._gax_api.publish(topic_path, message_pbs, - options=options) + event = self._gax_api.publish(topic_path, message_pbs) if not event.is_set(): event.wait() except GaxError as exc: if exc_to_code(exc.cause) == StatusCode.NOT_FOUND: raise NotFound(topic_path) raise - # return result.message_ids return event.result.message_ids def topic_list_subscriptions(self, topic_path, page_size=0, diff --git a/gcloud/pubsub/test__gax.py b/gcloud/pubsub/test__gax.py index <HASH>..<HASH> 100644 --- a/gcloud/pubsub/test__gax.py +++ b/gcloud/pubsub/test__gax.py @@ -223,7 +223,7 @@ class Test_PublisherAPI(_Base, unittest2.TestCase): message_pb, = message_pbs self.assertEqual(message_pb.data, B64) self.assertEqual(message_pb.attributes, {}) - self.assertEqual(options.is_bundling, True) + self.assertEqual(options, None) def test_topic_publish_hit_with_wait(self): import base64 @@ -245,7 +245,7 @@ class Test_PublisherAPI(_Base, unittest2.TestCase): message_pb, = message_pbs self.assertEqual(message_pb.data, B64) self.assertEqual(message_pb.attributes, {}) - self.assertEqual(options.is_bundling, True) + self.assertEqual(options, None) def test_topic_publish_miss_w_attrs_w_bytes_payload(self): import base64 @@ -264,7 +264,7 @@ class Test_PublisherAPI(_Base, unittest2.TestCase): message_pb, = message_pbs self.assertEqual(message_pb.data, B64) self.assertEqual(message_pb.attributes, {'foo': 'bar'}) - self.assertEqual(options.is_bundling, True) + self.assertEqual(options, None) def test_topic_publish_error(self): import base64 @@ -283,7 +283,7 @@ class Test_PublisherAPI(_Base, unittest2.TestCase): message_pb, = message_pbs self.assertEqual(message_pb.data, B64) self.assertEqual(message_pb.attributes, {}) - self.assertEqual(options.is_bundling, True) + self.assertEqual(options, None) def test_topic_list_subscriptions_no_paging(self): from google.gax import INITIAL_PAGE
Remove CallOptions and missed commented code.
googleapis_google-cloud-python
train
1f6591feb2bbbae660e03b4e0a5973e9e26ef08e
diff --git a/src/test/java/org/jboss/netty/bootstrap/AbstractSocketClientBootstrapTest.java b/src/test/java/org/jboss/netty/bootstrap/AbstractSocketClientBootstrapTest.java index <HASH>..<HASH> 100644 --- a/src/test/java/org/jboss/netty/bootstrap/AbstractSocketClientBootstrapTest.java +++ b/src/test/java/org/jboss/netty/bootstrap/AbstractSocketClientBootstrapTest.java @@ -71,6 +71,7 @@ public abstract class AbstractSocketClientBootstrapTest { public void testFailedConnectionAttempt() throws Exception { ClientBootstrap bootstrap = new ClientBootstrap(); bootstrap.setFactory(newClientSocketChannelFactory(executor)); + bootstrap.getPipeline().addLast("dummy", new DummyHandler()); bootstrap.setOption("remoteAddress", new InetSocketAddress("255.255.255.255", 1)); ChannelFuture future = bootstrap.connect(); future.awaitUninterruptibly();
Suppressed error log which occurs only in Windows on connection attempt failure, because it can mislead the developer to think there's a bug in the test / impl
netty_netty
train
2e80498c71b3f46c629df7a77b82c0b116976a88
diff --git a/bench.py b/bench.py index <HASH>..<HASH> 100755 --- a/bench.py +++ b/bench.py @@ -770,8 +770,7 @@ if __name__ == '__main__': train_args['d'] = args.cover_d # Always use all available threads in optimize mode. - if args.cover_k or args.cover_d: - train_args['threads'] = -1 + train_args['threads'] = -1 dict_data = zstd.train_dictionary(args.dict_size, training_chunks, **train_args)
bench: always use all threads when building dictionary
indygreg_python-zstandard
train
769b6bf86e7727dc1c41669d95a5468241d69d49
diff --git a/src/gitgraph.js b/src/gitgraph.js index <HASH>..<HASH> 100644 --- a/src/gitgraph.js +++ b/src/gitgraph.js @@ -390,7 +390,8 @@ author: commit.author, message: commit.message, date: commit.date, - sha1: commit.sha1 + sha1: commit.sha1, + commit: commit }; _emitEvent(self.canvas, "commit:" + event, mouseEventOptions);
Add commit object to the mouseEventOptions object This will allow users to work with the full commit object during mouse over and mouse out events
nicoespeon_gitgraph.js
train
601b2031c80df10ba3aa60544205222be622c397
diff --git a/lib/round/account.rb b/lib/round/account.rb index <HASH>..<HASH> 100644 --- a/lib/round/account.rb +++ b/lib/round/account.rb @@ -19,12 +19,17 @@ module Round ) end - def pay(payees, confirmations, redirect_uri = nil) + def pay(payees, confirmations, redirect_uri = nil, mfa_token: nil) raise ArgumentError, 'Payees must be specified' unless payees raise 'You must unlock the wallet before attempting a transaction' unless @wallet.multiwallet payment = self.transactions.create(payees, confirmations, redirect_uri: redirect_uri) - payment.sign(@wallet.multiwallet) + signed = payment.sign(@wallet.multiwallet) + if wallet.application + mfa_token = mfa_token || @wallet.application.get_mfa + signed.approve(mfa_token) + end + signed.refresh end def self.hash_identifier
Auto set mfa_token in app payments Sometimes, the mfa_token doesn't get used until after it has expired. So you can still send it if you want, but if not it will calculate it at the correct time.
GemHQ_round-rb
train
9f1ac360989b74f982812de3e401b9a74ba29435
diff --git a/parsl/dataflow/config_defaults.py b/parsl/dataflow/config_defaults.py index <HASH>..<HASH> 100644 --- a/parsl/dataflow/config_defaults.py +++ b/parsl/dataflow/config_defaults.py @@ -60,7 +60,7 @@ def update_config(config, rundir): config_base = {"sites": [], "globals": { - "lazyErrors": False, # Bool + "lazyErrors": True, # Bool "usageTracking": True, # Bool "strategy": 'simple', # ('simple',...) "appCache": True, # Bool diff --git a/parsl/dataflow/dflow.py b/parsl/dataflow/dflow.py index <HASH>..<HASH> 100644 --- a/parsl/dataflow/dflow.py +++ b/parsl/dataflow/dflow.py @@ -83,7 +83,7 @@ class DataFlowKernel(object): self.executors = epf.make(self.rundir, self._config) # set global vars from config - self.lazy_fail = self._config["globals"].get("lazyFail", lazy_fail) + self.lazy_fail = self._config["globals"].get("lazyErrors", lazy_fail) self.fail_retries = self._config["globals"].get("fail_retries", fail_retries) self.flowcontrol = FlowControl(self, self._config) else:
We now use lazyErrors in the config as well as DFK. This is not perfect, but it is consistent.
Parsl_parsl
train
b18099124080a77129ce50d03cf0dac1fd4fbf13
diff --git a/src/bootstrap.js b/src/bootstrap.js index <HASH>..<HASH> 100644 --- a/src/bootstrap.js +++ b/src/bootstrap.js @@ -53,23 +53,31 @@ return; } - let NODE_MODULES_PATH = appRoot ? path.join(appRoot, 'node_modules') : undefined; - if (!NODE_MODULES_PATH) { - NODE_MODULES_PATH = path.join(__dirname, '../node_modules'); - } else { - // use the drive letter casing of __dirname - // if it matches the drive letter of `appRoot` - // (https://github.com/microsoft/vscode/issues/128725) - if (process.platform === 'win32') { - const nodejsDriveLetter = __dirname.substr(0, 1); - const vscodeDriveLetter = appRoot.substr(0, 1); - if (nodejsDriveLetter.toLowerCase() === vscodeDriveLetter.toLowerCase()) { - NODE_MODULES_PATH = nodejsDriveLetter + NODE_MODULES_PATH.substr(1); - } + const NODE_MODULES_PATH = appRoot ? path.join(appRoot, 'node_modules') : path.join(__dirname, '../node_modules'); + + // Windows only: + // use both lowercase and uppercase drive letter + // as a way to ensure we do the right check on + // the node modules path: node.js might internally + // use a different case compared to what we have + let NODE_MODULES_ALTERNATIVE_PATH; + if (appRoot /* only used from renderer until `sandbox` enabled */ && process.platform === 'win32') { + const driveLetter = appRoot.substr(0, 1); + + let alternativeDriveLetter; + if (driveLetter.toLowerCase() !== driveLetter) { + alternativeDriveLetter = driveLetter.toLowerCase(); + } else { + alternativeDriveLetter = driveLetter.toUpperCase(); } + + NODE_MODULES_ALTERNATIVE_PATH = alternativeDriveLetter + NODE_MODULES_PATH.substr(1); + } else { + NODE_MODULES_ALTERNATIVE_PATH = undefined; } const NODE_MODULES_ASAR_PATH = `${NODE_MODULES_PATH}.asar`; + const NODE_MODULES_ASAR_ALTERNATIVE_PATH = NODE_MODULES_ALTERNATIVE_PATH ? `${NODE_MODULES_ALTERNATIVE_PATH}.asar` : undefined; // @ts-ignore const originalResolveLookupPaths = Module._resolveLookupPaths; @@ -84,9 +92,15 @@ asarPathAdded = true; paths.splice(i, 0, NODE_MODULES_ASAR_PATH); break; + } else if (paths[i] === NODE_MODULES_ALTERNATIVE_PATH) { + asarPathAdded = true; + paths.splice(i, 0, NODE_MODULES_ASAR_ALTERNATIVE_PATH); + break; } } if (!asarPathAdded && appRoot) { + // Assuming that adding just `NODE_MODULES_ASAR_PATH` is sufficient + // because nodejs should find it even if it has a different driver letter case paths.push(NODE_MODULES_ASAR_PATH); } }
asar - introduce alternative path to circumvent drive letter casing issues (#<I>) * asar - introduce alternative path to circumvent drive letter casing issues (#<I>) * Insert at most one additional lookup path
Microsoft_vscode
train
0de28ded2cd53d98bfe8cb08a2820d21075aa3e9
diff --git a/src/MetaModels/DcGeneral/Events/MetaModel/DuplicateModel.php b/src/MetaModels/DcGeneral/Events/MetaModel/DuplicateModel.php index <HASH>..<HASH> 100644 --- a/src/MetaModels/DcGeneral/Events/MetaModel/DuplicateModel.php +++ b/src/MetaModels/DcGeneral/Events/MetaModel/DuplicateModel.php @@ -23,6 +23,7 @@ namespace MetaModels\DcGeneral\Events\MetaModel; use ContaoCommunityAlliance\DcGeneral\Event\PostDuplicateModelEvent; +use ContaoCommunityAlliance\DcGeneral\Event\PreDuplicateModelEvent; use MetaModels\DcGeneral\Events\BaseSubscriber; /** @@ -38,7 +39,7 @@ class DuplicateModel extends BaseSubscriber protected function registerEventsInDispatcher() { $this->addListener( - PostDuplicateModelEvent::NAME, + PreDuplicateModelEvent::NAME, array($this, 'handle') ); } @@ -46,11 +47,11 @@ class DuplicateModel extends BaseSubscriber /** * Handle the paste into and after event. * - * @param PostDuplicateModelEvent $event The event. + * @param PreDuplicateModelEvent $event The event. * * @return void */ - public function handle(PostDuplicateModelEvent $event) + public function handle(PreDuplicateModelEvent $event) { $model = $event->getModel(); @@ -63,7 +64,9 @@ class DuplicateModel extends BaseSubscriber return; } - // Set the vargroup to null for auto creating. - $model->setProperty('vargroup', null); + // If we have a varbase, reset the vargroup because we got a new id. + if($model->getProperty('varbase') == 1){ + $model->setProperty('vargroup', null); + } } }
Change the handling of the copy mode of variants.
MetaModels_core
train
90cddeecef813e591dfb15abea7691aca3f997e2
diff --git a/RELEASE.rst b/RELEASE.rst index <HASH>..<HASH> 100644 --- a/RELEASE.rst +++ b/RELEASE.rst @@ -235,6 +235,7 @@ pandas 0.10.0 - DataFrame.combine_first will always result in the union of the index and columns, even if one DataFrame is length-zero (GH2525_) - Fix several DataFrame.icol/irow with duplicate indices issues (GH2228_, GH2259_) + - Use Series names for column names when using concat with axis=1 (GH2489_) .. _GH407: https://github.com/pydata/pandas/issues/407 .. _GH821: https://github.com/pydata/pandas/issues/821 @@ -353,6 +354,7 @@ pandas 0.10.0 .. _GH2525: https://github.com/pydata/pandas/issues/2525 .. _GH2228: https://github.com/pydata/pandas/issues/2228 .. _GH2259: https://github.com/pydata/pandas/issues/2259 +.. _GH2489: https://github.com/pydata/pandas/issues/2489 pandas 0.9.1 diff --git a/pandas/tools/merge.py b/pandas/tools/merge.py index <HASH>..<HASH> 100644 --- a/pandas/tools/merge.py +++ b/pandas/tools/merge.py @@ -1140,7 +1140,13 @@ class _Concatenator(object): if self.axis == 0: indexes = [x.index for x in self.objs] elif self.keys is None: - return Index(np.arange(len(self.objs))) + names = [] + for x in self.objs: + if x.name is not None: + names.append(x.name) + else: + return Index(np.arange(len(self.objs))) + return Index(names) else: return _ensure_index(self.keys) else: diff --git a/pandas/tools/tests/test_merge.py b/pandas/tools/tests/test_merge.py index <HASH>..<HASH> 100644 --- a/pandas/tools/tests/test_merge.py +++ b/pandas/tools/tests/test_merge.py @@ -1497,6 +1497,18 @@ class TestConcatenate(unittest.TestCase): expected = DataFrame(pieces, index=['A', 'B', 'C']).T assert_frame_equal(result, expected) + # preserve series names, #2489 + s = Series(randn(5), name='A') + s2 = Series(randn(5), name='B') + + result = concat([s, s2], axis=1) + expected = DataFrame({'A': s, 'B': s2}) + assert_frame_equal(result, expected) + + s2.name = None + result = concat([s, s2], axis=1) + self.assertTrue(np.array_equal(result.columns, range(2))) + def test_concat_single_with_key(self): df = DataFrame(np.random.randn(10, 4))
BUG: use Series name attributes for colnames in concat with axis=1. close #<I>
pandas-dev_pandas
train
87a683f65e7bdebf8a5401a27580dbf7388b6c8a
diff --git a/src/Cygnite/Http/Requests/Request.php b/src/Cygnite/Http/Requests/Request.php index <HASH>..<HASH> 100644 --- a/src/Cygnite/Http/Requests/Request.php +++ b/src/Cygnite/Http/Requests/Request.php @@ -9,8 +9,8 @@ */ namespace Cygnite\Http\Requests; -use Cygnite\Foundation\Collection; use Cygnite\Http\Header; +use Cygnite\Foundation\Collection; /** * Class Request. @@ -86,22 +86,6 @@ class Request protected static $httpMethodParameterOverride = false; /** - * Constructor of Request class. - * - * @param array $query - * @param array $post - * @param array $cookie - * @param array $server - * @param array $files - * @param array $env - * @param null $content - */ - public function __construct(array $query, array $post, array $cookie, array $server, array $files, array $env, $content = null) - { - $this->initialize($query, $post, $cookie, $server, $files, $env, $content); - } - - /** * Initialize parameters for current request. * * @param array $query @@ -130,6 +114,8 @@ class Request $this->setClientIPs(); $this->setPath(); $this->setUnsupportedMethodsIfExists(); + + return $this; } /** @@ -166,7 +152,8 @@ class Request 'CONTENT_TYPE' => 'HTTP_CONTENT_TYPE', ]); - return new static($query, $post, $cookie, $server, $files, $env, $content); + $static = new static(); + return $static->initialize($query, $post, $cookie, $server, $files, $env, $content); } /** @@ -320,7 +307,7 @@ class Request * * @return bool */ - public function setPath($path = null) + public function setPath($path = null) : bool { if ($path === null) { $uri = $this->server->get('REQUEST_URI'); @@ -461,7 +448,7 @@ class Request * * @return $this */ - public function setMethod($method) + public function setMethod($method) : Request { $this->method = null; $this->server->set('REQUEST_METHOD', $method); @@ -499,7 +486,7 @@ class Request /** * @return Collection */ - public function getCookie() + public function getCookie() : Collection { return $this->cookie; } @@ -507,7 +494,7 @@ class Request /** * @return Collection */ - public function getDelete() + public function getDelete() : Collection { return $this->delete; } @@ -515,7 +502,7 @@ class Request /** * @return Collection */ - public function getEnv() + public function getEnv() : Collection { return $this->env; } @@ -725,7 +712,7 @@ class Request /** * @return Collection */ - public function getPost() + public function getPost() : Collection { return $this->post; } @@ -733,7 +720,7 @@ class Request /** * @return Collection */ - public function getPut() + public function getPut() : Collection { return $this->put; } @@ -741,7 +728,7 @@ class Request /** * @return Collection */ - public function getQuery() + public function getQuery() : Collection { return $this->query; } @@ -749,7 +736,7 @@ class Request /** * @return Collection */ - public function getServer() + public function getServer() : Collection { return $this->server; } @@ -807,7 +794,7 @@ class Request /** * @return null|string */ - public function getMethod() + public function getMethod() :string { $method = $this->method; @@ -863,7 +850,7 @@ class Request * * @return bool */ - public function isAjax() + public function isAjax() : bool { return $this->header->get('X_REQUESTED_WITH') == 'XMLHttpRequest'; } @@ -873,7 +860,7 @@ class Request * * @return bool */ - public function isJson() + public function isJson() : bool { return preg_match("/application\/json/i", $this->header->get('CONTENT_TYPE')) === true; } @@ -920,7 +907,7 @@ class Request * * @return string */ - public function getBaseUrl() + public function getBaseUrl() : string { // Current Request URI $this->currentUrl = $this->server->get('REQUEST_URI'); @@ -936,7 +923,7 @@ class Request * * @return string */ - public function getCurrentUri() + public function getCurrentUri() : string { $basePath = $this->getBaseUrl(); $uri = $this->currentUrl; @@ -1015,4 +1002,15 @@ class Request $this->files = clone $this->files; $this->env = clone $this->env; } + + /** + * Check if POST array has input. + * + * @param $input + * @return bool + */ + public function postArrayHas($input) : bool + { + return filter_has_var(INPUT_POST, $input); + } }
Updated code to PHP7 and added postArrayHas() method.
cygnite_framework
train