hash
stringlengths
40
40
diff
stringlengths
131
114k
message
stringlengths
7
980
project
stringlengths
5
67
split
stringclasses
1 value
09d765d7c413f11149a15006b2f300a3e27e5ed1
diff --git a/lib/webrat/core/scope.rb b/lib/webrat/core/scope.rb index <HASH>..<HASH> 100644 --- a/lib/webrat/core/scope.rb +++ b/lib/webrat/core/scope.rb @@ -175,7 +175,7 @@ module Webrat @dom ||= Hpricot(scoped_html) end - def element_labeled(label) + def field_labeled(label) find_field(label, TextField, TextareaField, CheckboxField, RadioField, HiddenField) end diff --git a/lib/webrat/core/session.rb b/lib/webrat/core/session.rb index <HASH>..<HASH> 100644 --- a/lib/webrat/core/session.rb +++ b/lib/webrat/core/session.rb @@ -161,6 +161,6 @@ module Webrat def_delegators :current_scope, :click_button, :clicks_button def_delegators :current_scope, :should_see def_delegators :current_scope, :should_not_see - def_delegators :current_scope, :element_labeled + def_delegators :current_scope, :field_labeled end end diff --git a/spec/api/element_labeled_spec.rb b/spec/api/element_labeled_spec.rb index <HASH>..<HASH> 100644 --- a/spec/api/element_labeled_spec.rb +++ b/spec/api/element_labeled_spec.rb @@ -1,7 +1,7 @@ require File.expand_path(File.dirname(__FILE__) + "/../spec_helper") -describe "element_labeled" do +describe "field_labeled" do class << self def using_this_html html @@ -11,27 +11,27 @@ describe "element_labeled" do end end - def element_labeled label + def field_labeled label @label = label yield end def should_return_a type, opts it "should return a textfield" do - @session.element_labeled(opts[:for]).should be_an_instance_of(type) + @session.field_labeled(opts[:for]).should be_an_instance_of(type) end end def with_an_id_of id, opts it "should return an element with the correct id" do - @session.element_labeled(opts[:for]).should match_id(id) + @session.field_labeled(opts[:for]).should match_id(id) end end def should_raise_error_matching regexp, opts it "should raise with wrong label" do lambda { - @session.element_labeled(opts[:for]) + @session.field_labeled(opts[:for]) }.should raise_error(regexp) end end
Rename element_labeled to field_labeled
brynary_webrat
train
18a42a2d35b7ccf2392c7e5e67359505245eabf9
diff --git a/src/directives/scrollspy.js b/src/directives/scrollspy.js index <HASH>..<HASH> 100644 --- a/src/directives/scrollspy.js +++ b/src/directives/scrollspy.js @@ -15,7 +15,7 @@ angular.module('duScroll.scrollspy', ['duScroll.spyAPI']) Spy.prototype.getTargetElement = function() { if (!this.target && this.targetId) { - this.target = document.getElementById(this.targetId); + this.target = document.getElementById(this.targetId) || document.getElementsByName(this.targetId)[0] } return this.target; }; @@ -42,6 +42,8 @@ angular.module('duScroll.scrollspy', ['duScroll.spyAPI']) targetId = href.replace(/.*(?=#[^\s]+$)/, '').substring(1); } else if($attr.duScrollspy) { targetId = $attr.duScrollspy; + } else if($attr.duSmoothScroll) { + targetId = $attr.duSmoothScroll; } if(!targetId) return; diff --git a/src/directives/smooth-scroll.js b/src/directives/smooth-scroll.js index <HASH>..<HASH> 100644 --- a/src/directives/smooth-scroll.js +++ b/src/directives/smooth-scroll.js @@ -9,7 +9,7 @@ angular.module('duScroll.smoothScroll', ['duScroll.scrollHelpers', 'duScroll.scr var id = $attr.href ? $attr.href.replace(/.*(?=#[^\s]+$)/, '').substring(1) : $attr.duSmoothScroll; - var target = document.getElementById(id); + var target = document.getElementById(id) || document.getElementsByName(id)[0]; if(!target || !target.getBoundingClientRect) return; if (e.stopPropagation) e.stopPropagation();
Added support for name and duSmoothScroll attributes in the scrollSpy directive. #<I> #<I> #<I>
oblador_angular-scroll
train
42198bc59e9d8a55486661291174b1ad1c1e15b1
diff --git a/card.go b/card.go index <HASH>..<HASH> 100644 --- a/card.go +++ b/card.go @@ -31,6 +31,7 @@ type Card struct { Closed bool `json:"closed"` Subscribed bool `json:"subscribed"` DateLastActivity *time.Time `json:"dateLastActivity"` + DueComplete bool `json:"dueComplete"` // Board Board *Board
added dueComplete field to Card based on the dueComplete field returned by GET card calls: <URL>
adlio_trello
train
70a9c27884a1b6767f73e288a168d161b62c0ca6
diff --git a/app/models/agents/shell_command_agent.rb b/app/models/agents/shell_command_agent.rb index <HASH>..<HASH> 100644 --- a/app/models/agents/shell_command_agent.rb +++ b/app/models/agents/shell_command_agent.rb @@ -68,7 +68,7 @@ module Agents errors.add(:base, "command must be a shell command line string or an array of command line arguments.") end - unless File.directory?(options['path']) + unless File.directory?(interpolated['path']) errors.add(:base, "#{options['path']} is not a real directory.") end end
Update shell_command_agent.rb (#<I>) Change to make path accept stored credentials.
huginn_huginn
train
cf7324df2840b8107162d746b8de9c3d400b22bc
diff --git a/geoviews/plotting/mpl/__init__.py b/geoviews/plotting/mpl/__init__.py index <HASH>..<HASH> 100644 --- a/geoviews/plotting/mpl/__init__.py +++ b/geoviews/plotting/mpl/__init__.py @@ -213,18 +213,15 @@ class GeoImagePlot(GeoPlot, ImagePlot): style_opts = ['alpha', 'cmap', 'visible', 'filterrad', 'clims', 'norm'] def get_data(self, element, ranges, style): - if not self.geographic: - return super(GeoImagePlot, self).get_data(element, ranges, style) self._norm_kwargs(element, ranges, style, element.vdims[0]) style.pop('interpolation', None) xs, ys, zs = geo_mesh(element) - style['transform'] = element.crs + if self.geographic: + style['transform'] = element.crs return (xs, ys, zs), style, {} def init_artists(self, ax, plot_args, plot_kwargs): - if not self.geographic: - return super(GeoImagePlot, self).init_artists(ax, plot_args, plot_kwargs) artist = ax.pcolormesh(*plot_args, **plot_kwargs) return {'artist': artist}
Fixed GeoImagePlot for non-geographic plots
pyviz_geoviews
train
83b397701ec8376afc0b6edc200334828e1032cc
diff --git a/lib/natural/brill_pos_tagger/lib/Brill_POS_Trainer.js b/lib/natural/brill_pos_tagger/lib/Brill_POS_Trainer.js index <HASH>..<HASH> 100644 --- a/lib/natural/brill_pos_tagger/lib/Brill_POS_Trainer.js +++ b/lib/natural/brill_pos_tagger/lib/Brill_POS_Trainer.js @@ -140,7 +140,7 @@ function neighbourhood(corpus, site) { return list; } -// corpus: an array of tagged sentences +// corpus: an array of token arrays // templates: an array of rule templates // lexicon: lexicon that provides method tagWord(word) Brill__POS_Trainer.prototype.train = function(corpus, templates, lexicon) { diff --git a/lib/natural/brill_pos_tagger/lib/Corpus.js b/lib/natural/brill_pos_tagger/lib/Corpus.js index <HASH>..<HASH> 100644 --- a/lib/natural/brill_pos_tagger/lib/Corpus.js +++ b/lib/natural/brill_pos_tagger/lib/Corpus.js @@ -16,12 +16,37 @@ along with this program. If not, see <http://www.gnu.org/licenses/>. */ +var Token = require('./Token'); +const BROWN = 1; // sentences: an array of annotated sentences // A sentence is an array of annotated tokens // A token is an object with (token, tag, testTag, ruleList) -function Corpus(sentences) { - this.sentences = sentences; +function Corpus(data, typeOfCorpus) { + switch (typeOfCorpus) { + case BROWN: + this.processBrownCorpus(data); + break; + default: + // Assume it is an array of tagged sentences + this.sentences = data; + } } +Corpus.prototype.processBrownCorpus = function(data) { + this.sentences = []; + var lines = data.split('\n'); + var that = this; + lines.forEach(function(line) { + var taggedSentence = []; + var tokens = line.trim().split(/\s+/); + tokens.forEach(function(token) { + var wordPlusTag = token.split('_'); + var newToken = new Token(wordPlusTag[0], wordPlusTag[1], "", []); + taggedSentence.push(newToken); + }); + that.sentences.push(taggedSentence); + }); +}; + module.exports = Corpus;
Added processing of the Brown corpus.
NaturalNode_natural
train
a2de17d36ef6956e751dbad6f5c3a9ff0a19e05f
diff --git a/src/Caster.php b/src/Caster.php index <HASH>..<HASH> 100644 --- a/src/Caster.php +++ b/src/Caster.php @@ -48,12 +48,12 @@ class Caster implements LoggerAwareInterface protected function updateSwaggerParams(ParsedSwaggerInterface $swagger) { $updatedParams = []; - foreach ($swagger->getParams() as $param) { + foreach ($swagger->getParams() as $key => $param) { $updatedParam = array_merge($param, [ 'originalValue' => $param['value'], 'value' => $this->castType($param['value'], $param), ]); - array_push($updatedParams, $updatedParam); + $updatedParams[$key] = $updatedParam; } $swagger->setParams($updatedParams); return $swagger;
Param updating should preserve param keys
avalanche-development_swagger-caster-middleware
train
df03baa337ae1c87803a7b1a76a393f8a59813f3
diff --git a/src/Assetic/Filter/GoogleClosure/BaseCompilerFilter.php b/src/Assetic/Filter/GoogleClosure/BaseCompilerFilter.php index <HASH>..<HASH> 100644 --- a/src/Assetic/Filter/GoogleClosure/BaseCompilerFilter.php +++ b/src/Assetic/Filter/GoogleClosure/BaseCompilerFilter.php @@ -40,6 +40,7 @@ abstract class BaseCompilerFilter implements FilterInterface const LANGUAGE_ECMASCRIPT5 = 'ECMASCRIPT5'; const LANGUAGE_ECMASCRIPT5_STRICT = 'ECMASCRIPT5_STRICT'; + protected $timeout; protected $compilationLevel; protected $jsExterns; protected $externsUrl; @@ -49,6 +50,11 @@ abstract class BaseCompilerFilter implements FilterInterface protected $warningLevel; protected $language; + public function setTimeout($timeout) + { + $this->timeout = $timeout; + } + public function setCompilationLevel($compilationLevel) { $this->compilationLevel = $compilationLevel; diff --git a/src/Assetic/Filter/GoogleClosure/CompilerApiFilter.php b/src/Assetic/Filter/GoogleClosure/CompilerApiFilter.php index <HASH>..<HASH> 100644 --- a/src/Assetic/Filter/GoogleClosure/CompilerApiFilter.php +++ b/src/Assetic/Filter/GoogleClosure/CompilerApiFilter.php @@ -80,6 +80,9 @@ class CompilerApiFilter extends BaseCompilerFilter 'header' => 'Content-Type: application/x-www-form-urlencoded', 'content' => http_build_query($query), )); + if (null !== $this->timeout) { + $contextOptions['http']['timeout'] = $this->timeout; + } if ($this->proxy) { $contextOptions['http']['proxy'] = $this->proxy; $contextOptions['http']['request_fulluri'] = (Boolean) $this->proxyFullUri; @@ -97,6 +100,9 @@ class CompilerApiFilter extends BaseCompilerFilter curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_POSTFIELDS, $query); curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 15); + if (null !== $this->timeout) { + curl_setopt($curl, CURLOPT_TIMEOUT, $this->timeout); + } if ($this->proxy) { curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, TRUE); curl_setopt($ch, CURLOPT_PROXY, $this->proxy); diff --git a/src/Assetic/Filter/GoogleClosure/CompilerJarFilter.php b/src/Assetic/Filter/GoogleClosure/CompilerJarFilter.php index <HASH>..<HASH> 100644 --- a/src/Assetic/Filter/GoogleClosure/CompilerJarFilter.php +++ b/src/Assetic/Filter/GoogleClosure/CompilerJarFilter.php @@ -42,6 +42,10 @@ class CompilerJarFilter extends BaseCompilerFilter $this->jarPath, )); + if (null !== $this->timeout) { + $pb->setTimeout($this->timeout); + } + if (null !== $this->compilationLevel) { $pb->add('--compilation_level')->add($this->compilationLevel); }
added timeout to closure filters see #<I>
kriswallsmith_assetic
train
949510fa3f09662b6b831cf48ed835a930cb318a
diff --git a/kitty/model/low_level/mutated_field.py b/kitty/model/low_level/mutated_field.py index <HASH>..<HASH> 100644 --- a/kitty/model/low_level/mutated_field.py +++ b/kitty/model/low_level/mutated_field.py @@ -356,7 +356,7 @@ class MutableField(OneOf): ''' fields = [] max_len_bytes = len(value) - fields.append(ByteFlips(value, bytes_range=filter(lambda x: x <= max_len_bytes, [1, 2, 4]), fuzzable=fuzzable, name='byteflips')) + fields.append(ByteFlips(value, bytes_range=[x for x in [1, 2, 4] if x <= max_len_bytes], fuzzable=fuzzable, name='byteflips')) fields.append(BitFlips(value, fuzzable=fuzzable, name='bitflips')) if max_len_bytes > 4: size = 4
[DataModel] minor internal changes, should not affect usage
cisco-sas_kitty
train
0d88d175590e3b7d575c0bf976b48c8cc1a0ca5e
diff --git a/src/Sylius/Bundle/SalesBundle/Model/Order.php b/src/Sylius/Bundle/SalesBundle/Model/Order.php index <HASH>..<HASH> 100644 --- a/src/Sylius/Bundle/SalesBundle/Model/Order.php +++ b/src/Sylius/Bundle/SalesBundle/Model/Order.php @@ -101,20 +101,6 @@ class Order implements OrderInterface, TimestampableInterface protected $updatedAt; /** - * Total items count. - * - * @var integer - */ - protected $totalItems; - - /** - * Total quantity of items. - * - * @var integer - */ - protected $totalQuantity; - - /** * Is cart locked? * Locked carts should not be removed * even if expired. @@ -142,8 +128,6 @@ class Order implements OrderInterface, TimestampableInterface $this->total = 0; $this->confirmed = true; $this->createdAt = new \DateTime(); - $this->totalItems = 0; - $this->totalQuantity = 0; $this->locked = false; $this->incrementExpiresAt(); } @@ -476,35 +460,7 @@ class Order implements OrderInterface, TimestampableInterface */ public function getTotalItems() { - return $this->totalItems; - } - - /** - * {@inheritdoc} - */ - public function setTotalItems($totalItems) - { - if (0 > $totalItems) { - throw new \OutOfRangeException('Total items must not be less than 0'); - } - - $this->totalItems = $totalItems; - - return $this; - } - - /** - * {@inheritdoc} - */ - public function changeTotalItems($amount) - { - $this->totalItems += $amount; - - if (0 > $this->totalItems) { - $this->totalItems = 0; - } - - return $this; + return count($this->items); } /** @@ -512,31 +468,13 @@ class Order implements OrderInterface, TimestampableInterface */ public function getTotalQuantity() { - return $this->totalQuantity; - } + $quantity = 0; - /** - * {@inheritdoc} - */ - public function setTotalQuantity($totalQuantity) - { - if (0 > $totalQuantity) { - throw new \OutOfRangeException('Total quantity must not be less than 0'); + foreach ($this->items as $item) { + $quantity += $item->getQuantity(); } - $this->totalQuantity = $totalQuantity; - } - - /** - * {@inheritdoc} - */ - public function changeTotalQuantity($amount) - { - $this->totalQuantity += $amount; - - if (0 > $this->totalQuantity) { - $this->totalQuantity = 0; - } + return $quantity; } /** diff --git a/src/Sylius/Bundle/SalesBundle/Model/OrderInterface.php b/src/Sylius/Bundle/SalesBundle/Model/OrderInterface.php index <HASH>..<HASH> 100644 --- a/src/Sylius/Bundle/SalesBundle/Model/OrderInterface.php +++ b/src/Sylius/Bundle/SalesBundle/Model/OrderInterface.php @@ -147,20 +147,6 @@ interface OrderInterface extends AdjustableInterface public function getTotalItems(); /** - * Sets number of items in cart. - * - * @param integer $totalItems - */ - public function setTotalItems($totalItems); - - /** - * Change total items number by given amount. - * - * @param integer $amount - */ - public function changeTotalItems($amount); - - /** * Returns total quantity of items in cart. * * @return integer @@ -168,20 +154,6 @@ interface OrderInterface extends AdjustableInterface public function getTotalQuantity(); /** - * Sets total quantity of items in cart. - * - * @param integer $totalQuantity - */ - public function setTotalQuantity($totalQuantity); - - /** - * Change total quantity number by given amount. - * - * @param integer $amount - */ - public function changeTotalQuantity($amount); - - /** * Checks whether the cart is locked or not. * If cart is left unlocked, it should be deleted after expiration time. * diff --git a/src/Sylius/Bundle/SalesBundle/Resources/config/doctrine/Order.orm.xml b/src/Sylius/Bundle/SalesBundle/Resources/config/doctrine/Order.orm.xml index <HASH>..<HASH> 100644 --- a/src/Sylius/Bundle/SalesBundle/Resources/config/doctrine/Order.orm.xml +++ b/src/Sylius/Bundle/SalesBundle/Resources/config/doctrine/Order.orm.xml @@ -19,8 +19,6 @@ <gedmo:timestampable on="update"/> </field> <field name="locked" column="locked" type="boolean" /> - <field name="totalItems" column="total_items" type="integer" /> - <field name="totalQuantity" column="total_quantity" type="integer" /> <field name="expiresAt" column="expires_at" type="datetime" /> </mapped-superclass>
Remove denormalized totalItems and totalQuantity
Sylius_Sylius
train
1c36243f775200167df522998ad61db0c73545a5
diff --git a/src/CCapture.js b/src/CCapture.js index <HASH>..<HASH> 100755 --- a/src/CCapture.js +++ b/src/CCapture.js @@ -716,8 +716,12 @@ function CCapture( settings ) { return this._hookedTime + _settings.startTime; }; - Object.defineProperty( HTMLVideoElement.prototype, 'currentTime', { get: hookCurrentTime } ) - Object.defineProperty( HTMLAudioElement.prototype, 'currentTime', { get: hookCurrentTime } ) + try { + Object.defineProperty( HTMLVideoElement.prototype, 'currentTime', { get: hookCurrentTime } ) + Object.defineProperty( HTMLAudioElement.prototype, 'currentTime', { get: hookCurrentTime } ) + } catch (err) { + _log(err); + } }
Don't set currentTime if it's already defined.
spite_ccapture.js
train
b983616c4d3292f92af65970ff5e79ee4acacc6e
diff --git a/cli/src/lib/libDefs.js b/cli/src/lib/libDefs.js index <HASH>..<HASH> 100644 --- a/cli/src/lib/libDefs.js +++ b/cli/src/lib/libDefs.js @@ -27,6 +27,8 @@ export type LibDef = {| testFilePaths: Array<string>, |}; +export const TEST_FILE_NAME_RE = /(^test_.*\.js$|^.*\.md$)/; + const CACHE_DIR = path.join(os.homedir(), '.flow-typed'); const CACHE_REPO_DIR = path.join(CACHE_DIR, 'repo'); const GIT_REPO_DIR = path.join(__dirname, '..', '..', '..'); @@ -372,7 +374,6 @@ export function parseRepoDirItem( /** * Given a path to an assumed test file, ensure that it is named as expected. */ -const TEST_FILE_NAME_RE = /^test_.*\.js$/; function validateTestFile(testFilePath, context, validationErrs) { const testFileName = path.basename(testFilePath); if (!TEST_FILE_NAME_RE.test(testFileName)) { diff --git a/cli/src/lib/npm/npmLibDefs.js b/cli/src/lib/npm/npmLibDefs.js index <HASH>..<HASH> 100644 --- a/cli/src/lib/npm/npmLibDefs.js +++ b/cli/src/lib/npm/npmLibDefs.js @@ -33,6 +33,7 @@ import got from 'got'; import type {ValidationErrors as VErrors} from '../validationErrors'; import {validationError} from '../validationErrors'; +import {TEST_FILE_NAME_RE} from '../libDefs'; const P = Promise; @@ -52,8 +53,6 @@ export type NpmLibDefFilter = {| flowVersion?: FlowVersion, |}; -const TEST_FILE_NAME_RE = /^test_.*\.js$/; - async function extractLibDefsFromNpmPkgDir( pkgDirPath: string, scope: null | string,
Allow any .md file in libdef folders. (#<I>)
flow-typed_flow-typed
train
7b354050335caaf8316cf5cf17d45af64649dbb1
diff --git a/src/_pytest/deprecated.py b/src/_pytest/deprecated.py index <HASH>..<HASH> 100644 --- a/src/_pytest/deprecated.py +++ b/src/_pytest/deprecated.py @@ -10,8 +10,6 @@ in case of warnings which need to format their messages. """ from _pytest.warning_types import PytestDeprecationWarning -YIELD_TESTS = "yield tests were removed in pytest 4.0 - {name} will be ignored" - # set of plugins which have been integrated into the core; we use this list to ignore # them during registration to avoid conflicts DEPRECATED_EXTERNAL_PLUGINS = { diff --git a/src/_pytest/python.py b/src/_pytest/python.py index <HASH>..<HASH> 100644 --- a/src/_pytest/python.py +++ b/src/_pytest/python.py @@ -12,7 +12,6 @@ from textwrap import dedent import py import _pytest -from _pytest import deprecated from _pytest import fixtures from _pytest import nodes from _pytest._code import filter_traceback @@ -218,7 +217,9 @@ def pytest_pycollect_makeitem(collector, name, obj): elif getattr(obj, "__test__", True): if is_generator(obj): res = Function(name, parent=collector) - reason = deprecated.YIELD_TESTS.format(name=name) + reason = "yield tests were removed in pytest 4.0 - {name} will be ignored".format( + name=name + ) res.add_marker(MARK_GEN.xfail(run=False, reason=reason)) res.warn(PytestCollectionWarning(reason)) else:
Remove YIELD_TESTS from deprecated module as it is now an error
pytest-dev_pytest
train
394901db841a7b2dcf57879897b7f96312250bb2
diff --git a/examples/viewer/examples.js b/examples/viewer/examples.js index <HASH>..<HASH> 100644 --- a/examples/viewer/examples.js +++ b/examples/viewer/examples.js @@ -20,6 +20,30 @@ var sourceRentListings = { } }; +var sourceExpensiveRentListings = { + id: 'expensive-airbnb-source', + type: 'source', + params: { + query: 'select * from airbnb_madrid_oct_2015_listings where price > 100' + } +} + +var sourceBarrios = { + id: 'barrios-source', + type: 'source', + params: { + query: 'select * from barrios' + } +}; + +var sourceLaLatina = { + id: 'barrios-source', + type: 'source', + params: { + query: "select * from barrios where codbarrio like '10%'" + } +}; + var tradeAreaDefinition = { id: 'ta-example', type: 'trade-area', @@ -27,7 +51,30 @@ var tradeAreaDefinition = { source: sourceAtmDef, kind: TRADE_AREA_WALK, time: TRADE_AREA_15M, - isolines: ISOLINES + isolines: ISOLINES, + dissolved: false + } +}; + + +var intersectionDefinition = { + id: 'intersection-example-1', + type: 'intersection', + params: { + source: sourceLaLatina, + target: sourceRentListings + } +}; + + +var aggregateIntersectionDefinition = { + id: 'aggregate-intersection-example-1', + type: 'aggregate-intersection', + params: { + source: sourceRentListings, + target: sourceBarrios, + aggregate_function: 'max', + aggregate_column: 'price' } }; @@ -67,6 +114,18 @@ var moranDefinition = { } }; +var tradeAreaAtmMachines = { + id: 'taam-example', + type: 'trade-area', + params: { + source: sourceAtmDef, + kind: TRADE_AREA_WALK, + time: 1000, + isolines: ISOLINES, + dissolved: false + } +}; + var examples = { population_in_trade_area: { name: 'population in trade area', @@ -86,6 +145,22 @@ var examples = { center: [40.44, -3.7], zoom: 12 }, + atm_machines_in_trade_area: { + name: 'atm machines in trade area', + def: tradeAreaAtmMachines, + cartocss: [ + '#layer{', + ' polygon-fill: red;', + ' polygon-opacity: 0.6;', + ' polygon-opacity: 0.7;', + ' line-color: #FFF;', + ' line-width: 0.5;', + ' line-opacity: 1;', + '}' + ].join('\n'), + center: [40.44, -3.7], + zoom: 12 + }, population_in_moran: { name: 'population in moran', def: { @@ -472,5 +547,37 @@ var examples = { }, center: [40.44, -3.7], zoom: 12 + }, + intersection: { + name: 'airbnb and districts intersection', + def: intersectionDefinition, + cartocss: [ + '#layer{', + ' polygon-fill: red;', + ' polygon-opacity: 0.6;', + ' polygon-opacity: 0.7;', + ' line-color: #FFF;', + ' line-width: 0.5;', + ' line-opacity: 1;', + '}' + ].join('\n'), + center: [40.44, -3.7], + zoom: 12 + }, + 'aggregate-intersection': { + name: 'airbnb and districts intersection with max price aggregation', + def: aggregateIntersectionDefinition, + cartocss: [ + '#layer{', + ' polygon-fill: ramp([max_price], colorbrewer(Reds));', + ' polygon-opacity: 0.6;', + ' polygon-opacity: 0.7;', + ' line-color: #FFF;', + ' line-width: 0.5;', + ' line-opacity: 1;', + '}' + ].join('\n'), + center: [40.44, -3.7], + zoom: 12 } };
Added trade-areas, intersection and aggregate-intersection analysis examples
CartoDB_camshaft
train
2229c26442ea28b7d69819e0b52b9bbc45afae4a
diff --git a/pandas/core/generic.py b/pandas/core/generic.py index <HASH>..<HASH> 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -4462,6 +4462,30 @@ class NDFrame(PandasObject): 2000-01-01 00:06:00 26 Freq: 3T, dtype: int64 + For DataFrame objects, the keyword ``on`` can be used to specify the + column instead of the index for resampling. + + >>> df = pd.DataFrame(data=9*[range(4)], columns=['a', 'b', 'c', 'd']) + >>> df['time'] = pd.date_range('1/1/2000', periods=9, freq='T') + >>> df.resample('3T', on='time').sum() + a b c d + time + 2000-01-01 00:00:00 0 3 6 9 + 2000-01-01 00:03:00 0 3 6 9 + 2000-01-01 00:06:00 0 3 6 9 + + For a DataFrame with MultiIndex, the keyword ``level`` can be used to + specify on level the resampling needs to take place. + + >>> time = pd.date_range('1/1/2000', periods=5, freq='T') + >>> df2 = pd.DataFrame(data=10*[range(4)], + columns=['a', 'b', 'c', 'd'], + index=pd.MultiIndex.from_product([time, [1, 2]]) + ) + >>> df2.resample('3T', level=0).sum() + a b c d + 2000-01-01 00:00:00 0 6 12 18 + 2000-01-01 00:03:00 0 4 8 12 """ from pandas.tseries.resample import (resample, _maybe_process_deprecations)
DOC: add example for DataFrame.resample: keywords on and level (#<I>)
pandas-dev_pandas
train
1cb22a0bd2d82b2bbcb0c0094ac2088fc790abf7
diff --git a/doc/changelogs/3.5/unstable/CHANGELOG-3.5.0rc1-to-3.5.0rc2 b/doc/changelogs/3.5/unstable/CHANGELOG-3.5.0rc1-to-3.5.0rc2 index <HASH>..<HASH> 100644 --- a/doc/changelogs/3.5/unstable/CHANGELOG-3.5.0rc1-to-3.5.0rc2 +++ b/doc/changelogs/3.5/unstable/CHANGELOG-3.5.0rc1-to-3.5.0rc2 @@ -28,5 +28,7 @@ Changes from 3.5.0rc1 to 3.5.0rc2 http://ez.no/community/bug_reports/time_attribute_can_t_be_left_empty - Fixed bug of toolbar templates search use id in html input element. http://ez.no/community/bug_reports/invalid_xhtml_with_two_search_box +- Fixed bug with generating package names with non-standard-latin characters. + http://ez.no/community/bug_reports/3_5_package_create_no_utf_8_package_name *Library: diff --git a/kernel/classes/ezpackagecreationhandler.php b/kernel/classes/ezpackagecreationhandler.php index <HASH>..<HASH> 100644 --- a/kernel/classes/ezpackagecreationhandler.php +++ b/kernel/classes/ezpackagecreationhandler.php @@ -672,7 +672,12 @@ class eZPackageCreationHandler if ( $http->hasPostVariable( 'PackageName' ) ) { $packageName = trim( $http->postVariable( 'PackageName' ) ); - $packageName = str_replace( " ", "_", $packageName ); + + /* Make sure to generate a package name that can be called through + * a urlalias */ + include 'lib/ezi18n/classes/ezchartransform.php'; + $trans = new eZCharTransform; + $packageName = $trans->transformByGroup( $packageName, 'urlalias' ); } if ( $http->hasPostVariable( 'PackageSummary' ) ) $packageSummary = $http->postVariable( 'PackageSummary' ); diff --git a/kernel/classes/packagecreators/ezcontentobject/ezcontentobjectpackagecreator.php b/kernel/classes/packagecreators/ezcontentobject/ezcontentobjectpackagecreator.php index <HASH>..<HASH> 100644 --- a/kernel/classes/packagecreators/ezcontentobject/ezcontentobjectpackagecreator.php +++ b/kernel/classes/packagecreators/ezcontentobject/ezcontentobjectpackagecreator.php @@ -297,7 +297,12 @@ class eZContentObjectPackageCreator extends eZPackageCreationHandler } } - $packageInformation['name'] = strtolower( implode( ',', $nodeNames ) ); + /* Make sure to generate a package name that can be called through + * a urlalias */ + include 'lib/ezi18n/classes/ezchartransform.php'; + $trans = new eZCharTransform; + $packageInformation['name'] = $trans->transformByGroup( implode( ',', $nodeNames ), 'urlalias' ); + $packageInformation['summary'] = implode( ', ', $nodeNames ); $packageInformation['description'] = $description; }
- Fixed bug with generating package names with non-standard-latin characters. <URL>
ezsystems_ezpublish-legacy
train
19d5b346827576c804f73f861388d4e346307c57
diff --git a/tests/test-timber-twig-filters.php b/tests/test-timber-twig-filters.php index <HASH>..<HASH> 100644 --- a/tests/test-timber-twig-filters.php +++ b/tests/test-timber-twig-filters.php @@ -39,4 +39,20 @@ $this->assertEquals('septiembre 28th, 1983 8:14pm', $str); } } + + function testTwigFilterDateI18nWordPressOption(){ + if (WPLANG == 'es_ES'){ + global $wp_locale; + $data['day'] = '1983-09-28'; + $str = Timber::compile_string("{{day|date}}", $data); + $this->assertEquals('28 septiembre, 1983', $str); + } + } + + function testTwigFilterDateWordPressOption(){ + $format = get_option('date_format'); + $str = Timber::compile_string("{{now|date('".$format."')}}"); + $empty = Timber::compile_string("{{now|date}}"); + $this->assertSame($str, $empty); + } }
finished remainder of tests. confirm that this closes #<I>
timber_timber
train
cf8b098dda5212cc9de9b84cd5b6522e48120148
diff --git a/pkg/kubelet/cm/topologymanager/policy_best_effort.go b/pkg/kubelet/cm/topologymanager/policy_best_effort.go index <HASH>..<HASH> 100644 --- a/pkg/kubelet/cm/topologymanager/policy_best_effort.go +++ b/pkg/kubelet/cm/topologymanager/policy_best_effort.go @@ -91,6 +91,43 @@ func iterateAllProviderTopologyHints(allProviderHints [][]TopologyHint, callback iterate(0, []TopologyHint{}) } +// Merge a TopologyHints permutation to a single hint by performing a bitwise-AND +// of their affinity masks. The hint shall be preferred if all hits in the permutation +// are preferred. +func mergePermutation(policy Policy, numaNodes []int, permutation []TopologyHint) TopologyHint { + // Get the NUMANodeAffinity from each hint in the permutation and see if any + // of them encode unpreferred allocations. + defaultAffinity, _ := bitmask.NewBitMask(numaNodes...) + preferred := true + var numaAffinities []bitmask.BitMask + for _, hint := range permutation { + // Only consider hints that have an actual NUMANodeAffinity set. + if hint.NUMANodeAffinity == nil { + numaAffinities = append(numaAffinities, defaultAffinity) + } else { + numaAffinities = append(numaAffinities, hint.NUMANodeAffinity) + } + + if !hint.Preferred { + preferred = false + } + + // Special case PolicySingleNumaNode to only prefer hints where + // all providers have a single NUMA affinity set. + if policy != nil && policy.Name() == PolicySingleNumaNode && hint.NUMANodeAffinity != nil && hint.NUMANodeAffinity.Count() > 1 { + preferred = false + } + + } + + // Merge the affinities using a bitwise-and operation. + mergedAffinity, _ := bitmask.NewBitMask(numaNodes...) + mergedAffinity.And(numaAffinities...) + // Build a mergedHint from the merged affinity mask, indicating if an + // preferred allocation was used to generate the affinity mask or not. + return TopologyHint{mergedAffinity, preferred} +} + // Merge the hints from all hint providers to find the best one. func mergeProvidersHints(policy Policy, numaNodes []int, providersHints []map[string][]TopologyHint) TopologyHint { // Set the default affinity as an any-numa affinity containing the list @@ -136,33 +173,7 @@ func mergeProvidersHints(policy Policy, numaNodes []int, providersHints []map[st iterateAllProviderTopologyHints(allProviderHints, func(permutation []TopologyHint) { // Get the NUMANodeAffinity from each hint in the permutation and see if any // of them encode unpreferred allocations. - preferred := true - var numaAffinities []bitmask.BitMask - for _, hint := range permutation { - if hint.NUMANodeAffinity == nil { - numaAffinities = append(numaAffinities, defaultAffinity) - } else { - numaAffinities = append(numaAffinities, hint.NUMANodeAffinity) - } - - if !hint.Preferred { - preferred = false - } - - // Special case PolicySingleNumaNode to only prefer hints where - // all providers have a single NUMA affinity set. - if policy != nil && policy.Name() == PolicySingleNumaNode && hint.NUMANodeAffinity != nil && hint.NUMANodeAffinity.Count() > 1 { - preferred = false - } - } - - // Merge the affinities using a bitwise-and operation. - mergedAffinity, _ := bitmask.NewBitMask(numaNodes...) - mergedAffinity.And(numaAffinities...) - - // Build a mergedHintfrom the merged affinity mask, indicating if an - // preferred allocation was used to generate the affinity mask or not. - mergedHint := TopologyHint{mergedAffinity, preferred} + mergedHint := mergePermutation(policy, numaNodes, permutation) // Only consider mergedHints that result in a NUMANodeAffinity > 0 to // replace the current bestHint.
Refactor policy-best-effort - Modularize code with mergePermutation method
kubernetes_kubernetes
train
f0a396003d964612ef653c601178ac47b096daca
diff --git a/classes/phing/system/io/Win32FileSystem.php b/classes/phing/system/io/Win32FileSystem.php index <HASH>..<HASH> 100644 --- a/classes/phing/system/io/Win32FileSystem.php +++ b/classes/phing/system/io/Win32FileSystem.php @@ -471,19 +471,7 @@ class Win32FileSystem extends FileSystem { @closedir($dir); return $vv; } - - /** - * Whether file can be deleted. - * - * This is currently returning whether the specified file is - * writable. This is likely wrong for NTFS file systems, but - * I'm not sure whether PHP can see the NTFS delete perm ... - * - * @param PhingFile $f - * @return boolean - */ - abstract function canDelete(PhingFile $f); } -?> +?> \ No newline at end of file
Applying fix to abstract method, leftover from patch for #<I>
phingofficial_phing
train
7797aa5d76d6aca9db27fa8a4544482b79dd884d
diff --git a/cilium-health/launch/endpoint.go b/cilium-health/launch/endpoint.go index <HASH>..<HASH> 100644 --- a/cilium-health/launch/endpoint.go +++ b/cilium-health/launch/endpoint.go @@ -41,6 +41,7 @@ import ( "github.com/cilium/cilium/pkg/node" "github.com/cilium/cilium/pkg/option" "github.com/cilium/cilium/pkg/pidfile" + "github.com/cilium/cilium/pkg/sysctl" "github.com/containernetworking/plugins/pkg/ns" "github.com/vishvananda/netlink" @@ -120,7 +121,12 @@ func configureHealthInterface(netNS ns.NetNS, ifName string, ip4Addr, ip6Addr *n return err } - if ip6Addr != nil { + if ip6Addr == nil { + name := fmt.Sprintf("net.ipv6.conf.%s.disable_ipv6", ifName) + // Ignore the error; if IPv6 is completely disabled + // then it's okay if we can't write the sysctl. + _ = sysctl.Write(name, "1") + } else { if err = netlink.AddrAdd(link, &netlink.Addr{IPNet: ip6Addr}); err != nil { return err }
health: Configure sysctl when IPv6 is disabled When IPv6 is disabled, ensure that the health endpoint's device is configured to disable IPv6 so that it doesn't emit any IPv6 autoconf frames or similar.
cilium_cilium
train
82382aa5f64660f70a9a9b2c5b85e304ba03a01e
diff --git a/.gitignore b/.gitignore index <HASH>..<HASH> 100644 --- a/.gitignore +++ b/.gitignore @@ -3,3 +3,5 @@ tests-report.xml !test/unit/**/node_modules !examples/sprout/node_modules .idea +*.swp +*.swo diff --git a/index.js b/index.js index <HASH>..<HASH> 100644 --- a/index.js +++ b/index.js @@ -257,3 +257,12 @@ function printVersion(logger) { logger.info('Starting %s v%s in %s mode', pkg.name, pkg.version, process.env.NODE_ENV || 'development'); //the config loader defaults to development } + +/* + * testUtility must be explicitly called in order to gain access to utility methods that are + * helpful for testing Sprout Server projects. Not intended for use in non-test environments. + */ +module.exports.testUtility = function () { + return require('./test/unit/util'); +}; + diff --git a/test/unit/util.js b/test/unit/util.js index <HASH>..<HASH> 100644 --- a/test/unit/util.js +++ b/test/unit/util.js @@ -2,7 +2,8 @@ //Some utilities to help with testing services var di = require('../../lib/di'), - _ = require('lodash') + _ = require('lodash'), + fs = require('fs'), sinon = require('sinon'); //creates a mock config service @@ -57,8 +58,60 @@ exports.initService = function(module, config, injections, callback) { callback(); } -} +}; + +/* + * This method lets you include unmodified Sprout services into your tests. One use case is + * when testing your own service that depends on Sprout services, but the particular method + * you want to test does not. Rather than replicating mocked/stubbed functionality that already + * exists in the native services, you can just inject the native services themselves so + * init() and logic/calls within init() doesn't break. + * + * @param {Array|String} modules - An single name of a module or an array of module names + * @param {object} config - Your local config or mocked config as needed + * @param {function} callback - Called after all modules are required and init()'d. An object with + * the mapping, `{ <module_name>: <module>, ... }` is returned. + */ +exports.injectNative = function (modules, config, callback) { + var nativeModules = fs.readdirSync(__dirname + '/../../services/'), + servicePattern = /^[a-z]+(.js)$/i, + initializedModules = {}, + initializedCount = 0, + temp; + + for(var i = 0; i < nativeModules.length; i++) { + if(!servicePattern.test(nativeModules[i])) { + nativeModules.splice(i, 1); + } + + nativeModules[i] = nativeModules[i].split('.')[0]; + } + + if(!(modules instanceof Array)) { + modules = [modules]; + } + for(var i = 0; i < modules.length; i++) { + temp = {}; + + if(nativeModules.indexOf(modules[i]) === -1) { + throw new Error('Given module name is not a native service'); + } + + initializedModules[modules[i]] = require('../../services/' + modules[i]); + + this.initService(initializedModules[modules[i]], config, function (error) { + if(error) { + throw new Error('Unable to inject native service'); + } + + initializedCount++; + if(initializedCount === modules.length) { + callback(initializedModules); + } + }); + } +}; /* This is a new init method to replace initService * mod: the module to init @@ -76,7 +129,7 @@ exports.init = function(mod, serviceMap, serviceCallback, callback) { global.services = { get: function(name) { - console.log("Get", name) + console.log("Get", name); return serviceMap[name]; } }; @@ -86,6 +139,7 @@ exports.init = function(mod, serviceMap, serviceCallback, callback) { paramNames.forEach(function(paramName) { if (!serviceMap[paramName]) { + console.log(__dirname); //since it's possible that this has already been loaded once and //has stubbed out methods, delete it from the cache var modPath = require.resolve('./mocks/' + paramName); @@ -112,4 +166,4 @@ exports.init = function(mod, serviceMap, serviceCallback, callback) { exports.restore = function() { -} \ No newline at end of file +}
Expose test utility methods Exposing the existing test utility methods and adding injection for native services adds greater flexibility in testing sprout-server projects. It can also reduce, or in some cases, eliminate the need to create mocks/stubs of Sprout services in order to test your local project.
BlueOakJS_blueoak-server
train
6caae0257e03e4f7affb90673a4d301de1bb45e9
diff --git a/modules/wyc/src/wyc/lang/Expr.java b/modules/wyc/src/wyc/lang/Expr.java index <HASH>..<HASH> 100755 --- a/modules/wyc/src/wyc/lang/Expr.java +++ b/modules/wyc/src/wyc/lang/Expr.java @@ -876,8 +876,8 @@ public interface Expr extends SyntacticElement { public static class RationalLVal extends SyntacticElement.Impl implements LVal { - public final LVal numerator; - public final LVal denominator; + public LVal numerator; + public LVal denominator; public RationalLVal(LVal num, LVal den, Attribute... attributes) { super(attributes); diff --git a/modules/wyc/src/wyc/stages/FlowTyping.java b/modules/wyc/src/wyc/stages/FlowTyping.java index <HASH>..<HASH> 100755 --- a/modules/wyc/src/wyc/stages/FlowTyping.java +++ b/modules/wyc/src/wyc/stages/FlowTyping.java @@ -278,8 +278,8 @@ public final class FlowTyping { private Environment propagate(Stmt.Assign stmt, Environment environment) throws Exception { - - Expr.LVal lhs = stmt.lhs; + + Expr.LVal lhs = propagate(stmt.lhs,environment); Expr rhs = resolver.resolve(stmt.rhs,environment,current); if(lhs instanceof Expr.RationalLVal) { @@ -347,8 +347,7 @@ public final class FlowTyping { syntaxError(errorMessage(INVALID_TUPLE_LVAL),filename,f); } } - } else { - lhs = propagate(lhs,environment); + } else { Expr.AssignedVariable av = inferAfterType(lhs, rhs.result()); environment = environment.put(av.var, av.afterType); } @@ -674,6 +673,11 @@ public final class FlowTyping { Expr.AssignedVariable lv = new Expr.AssignedVariable(av.var, av.attributes()); lv.type = p; return lv; + } else if(lval instanceof Expr.RationalLVal) { + Expr.RationalLVal av = (Expr.RationalLVal) lval; + av.numerator = propagate(av.numerator,environment); + av.denominator = propagate(av.numerator,environment); + return av; } else if(lval instanceof Expr.Dereference) { Expr.Dereference pa = (Expr.Dereference) lval; Expr.LVal src = propagate((Expr.LVal) pa.src,environment);
WyC: better support for rational lval
Whiley_WhileyCompiler
train
812013b1c1783819bbd922baf3d4dabf41dfab56
diff --git a/lib/phpunit/lib.php b/lib/phpunit/lib.php index <HASH>..<HASH> 100644 --- a/lib/phpunit/lib.php +++ b/lib/phpunit/lib.php @@ -423,6 +423,7 @@ class phpunit_util { // reset all static caches accesslib_clear_all_caches(true); get_string_manager()->reset_caches(); + events_get_handlers('reset'); //TODO: add more resets here and probably refactor them to new core function // purge dataroot
MDL-<I> reset event handlers in phpunit test reset
moodle_moodle
train
bffd1feef02341568c7cf7c6b01e7838bc876091
diff --git a/Unosquare.Tubular/Javascript/tubular/tubular-directives-editors.js b/Unosquare.Tubular/Javascript/tubular/tubular-directives-editors.js index <HASH>..<HASH> 100644 --- a/Unosquare.Tubular/Javascript/tubular/tubular-directives-editors.js +++ b/Unosquare.Tubular/Javascript/tubular/tubular-directives-editors.js @@ -59,8 +59,9 @@ if (angular.isDefined($scope.match) && $scope.match) { if ($scope.value != $scope.$component.model[$scope.match]) { + var label = $filter('filter')($scope.$component.fields, { name: $scope.match }, true)[0].label; $scope.$valid = false; - $scope.state.$errors = [$filter('translate')('EDITOR_MATCH', $scope.match)]; + $scope.state.$errors = [$filter('translate')('EDITOR_MATCH', label)]; return; } }
Added the correct label to the error string.
unosquare_tubular
train
9436b56303c75353cbad80658ce7f89b7295cf43
diff --git a/src/Graviton/DocumentBundle/DependencyInjection/Compiler/SolrDefinitionCompilerPass.php b/src/Graviton/DocumentBundle/DependencyInjection/Compiler/SolrDefinitionCompilerPass.php index <HASH>..<HASH> 100644 --- a/src/Graviton/DocumentBundle/DependencyInjection/Compiler/SolrDefinitionCompilerPass.php +++ b/src/Graviton/DocumentBundle/DependencyInjection/Compiler/SolrDefinitionCompilerPass.php @@ -39,6 +39,8 @@ class SolrDefinitionCompilerPass implements CompilerPassInterface } } + var_dump($map); + $container->setParameter('graviton.document.solr.map', $map); } diff --git a/src/Graviton/DocumentBundle/DependencyInjection/Compiler/Utils/Document.php b/src/Graviton/DocumentBundle/DependencyInjection/Compiler/Utils/Document.php index <HASH>..<HASH> 100644 --- a/src/Graviton/DocumentBundle/DependencyInjection/Compiler/Utils/Document.php +++ b/src/Graviton/DocumentBundle/DependencyInjection/Compiler/Utils/Document.php @@ -26,6 +26,10 @@ class Document * @var array */ private $solrFields = []; + /** + * @var array + */ + private $solrAggregate = []; /** * Constructor @@ -80,4 +84,20 @@ class Document { $this->solrFields = $solrFields; } + + /** + * @return array + */ + public function getSolrAggregate() + { + return $this->solrAggregate; + } + + /** + * @param array $solrAggregate + */ + public function setSolrAggregate(array $solrAggregate) + { + $this->solrAggregate = $solrAggregate; + } } diff --git a/src/Graviton/DocumentBundle/DependencyInjection/Compiler/Utils/DocumentMap.php b/src/Graviton/DocumentBundle/DependencyInjection/Compiler/Utils/DocumentMap.php index <HASH>..<HASH> 100644 --- a/src/Graviton/DocumentBundle/DependencyInjection/Compiler/Utils/DocumentMap.php +++ b/src/Graviton/DocumentBundle/DependencyInjection/Compiler/Utils/DocumentMap.php @@ -191,8 +191,11 @@ class DocumentMap $doc = new Document($className, $fields); // stuff that belongs to the whole document - if (isset($schemaMapping['_base']['solr'])) { - $doc->setSolrFields($schemaMapping['_base']['solr']); + if (isset($schemaMapping['_base']['solr']['fields'])) { + $doc->setSolrFields($schemaMapping['_base']['solr']['fields']); + } + if (isset($schemaMapping['_base']['solr']['aggregate'])) { + $doc->setSolrAggregate($schemaMapping['_base']['solr']['aggregate']); } return $doc; diff --git a/src/Graviton/GeneratorBundle/Definition/JsonDefinition.php b/src/Graviton/GeneratorBundle/Definition/JsonDefinition.php index <HASH>..<HASH> 100644 --- a/src/Graviton/GeneratorBundle/Definition/JsonDefinition.php +++ b/src/Graviton/GeneratorBundle/Definition/JsonDefinition.php @@ -484,6 +484,20 @@ class JsonDefinition } /** + * gets the solr aggregate pipeline + * + * @return array|\stdClass[] + */ + public function getSolrAggregate() + { + $solr = $this->def->getSolr(); + if (!$solr instanceof Solr) { + return []; + } + return $solr->getAggregate(); + } + + /** * Can record origin be modified * * @return bool diff --git a/src/Graviton/GeneratorBundle/Generator/ResourceGenerator.php b/src/Graviton/GeneratorBundle/Generator/ResourceGenerator.php index <HASH>..<HASH> 100644 --- a/src/Graviton/GeneratorBundle/Generator/ResourceGenerator.php +++ b/src/Graviton/GeneratorBundle/Generator/ResourceGenerator.php @@ -157,7 +157,8 @@ class ResourceGenerator extends AbstractGenerator ->setParameter('collection', $this->json->getServiceCollection()) ->setParameter('indexes', $this->json->getIndexes()) ->setParameter('textIndexes', $this->json->getAllTextIndexes()) - ->setParameter('solr', $this->json->getSolrFields()) + ->setParameter('solrFields', $this->json->getSolrFields()) + ->setParameter('solrAggregate', $this->json->getSolrAggregate()) ->getParameters(); $this->generateDocument($parameters, $bundleDir, $document); diff --git a/src/Graviton/GeneratorBundle/Resources/skeleton/model/schema.json.twig b/src/Graviton/GeneratorBundle/Resources/skeleton/model/schema.json.twig index <HASH>..<HASH> 100644 --- a/src/Graviton/GeneratorBundle/Resources/skeleton/model/schema.json.twig +++ b/src/Graviton/GeneratorBundle/Resources/skeleton/model/schema.json.twig @@ -109,7 +109,10 @@ } }, - "solr": {{ solr|json_encode() }}, + "solr": { + "fields": {{ solrFields|json_encode() }}, + "aggregate": {{ solrAggregate|json_encode() }} + }, {# the whole recordOrigin thing is kinda messed up as you need 2 vars to correctly detect what should be done.
move solr data around in schema..
libgraviton_graviton
train
4223d2ee2e846a2b5377f3b0de2c22f90d4498a3
diff --git a/src/angular-nvd3.js b/src/angular-nvd3.js index <HASH>..<HASH> 100644 --- a/src/angular-nvd3.js +++ b/src/angular-nvd3.js @@ -135,8 +135,12 @@ if (options['styles'] || scope._config.extended) configureStyles(); nv.addGraph(function() { + // Remove resize handler. Due to async execution should be placed here, not in the clearElement + if (scope.chart.resizeHandler) { + scope.chart.resizeHandler.clear(); + } // Update the chart when window resizes - scope.chart.resizeHandler = nv.utils.windowResize(function() { scope.chart.update(); }); + scope.chart.resizeHandler = nv.utils.windowResize(function() { scope.chart.update && scope.chart.update(); }); return scope.chart; }, options.chart['callback']); }, @@ -165,9 +169,6 @@ element.find('.caption').remove(); element.empty(); if (scope.chart) { - // clear window resize event handler - if (scope.chart.resizeHandler) scope.chart.resizeHandler.clear(); - // remove chart from nv.graph list for (var i = 0; i < nv.graphs.length; i++) if (nv.graphs[i].id === scope.chart.id) { @@ -374,4 +375,4 @@ } }; }); -})(); \ No newline at end of file +})();
Issue-<I> Fix removing resize handler
krispo_angular-nvd3
train
316e47f9e41562643ddd1ce9f6f92ffd4ba9b83c
diff --git a/codemach/assembler.py b/codemach/assembler.py index <HASH>..<HASH> 100644 --- a/codemach/assembler.py +++ b/codemach/assembler.py @@ -4,23 +4,9 @@ import types __all__ = ['Assembler'] def inst_to_bytes(inst): - if inst.opname in ( - 'LOAD_CONST', - 'LOAD_NAME', - 'STORE_NAME', - 'CALL_FUNCTION', - ): - return bytes([ - inst.opcode, - inst.arg, - 0]) - elif inst.opname in ( - 'BINARY_ADD', - 'RETURN_VALUE', - ): - return bytes([inst.opcode]) - else: - raise RuntimeError('unsupported op {}'.format(inst.opname)) + return bytes([ + inst.opcode, + inst.arg]) class Assembler(object): def __init__(self): @@ -51,7 +37,7 @@ class Assembler(object): None, False) - self.offset += 3 + self.offset += 2 self.insts.append(inst) @@ -66,7 +52,7 @@ class Assembler(object): None, False) - self.offset += 3 + self.offset += 2 self.insts.append(inst) @@ -81,7 +67,7 @@ class Assembler(object): None, False) - self.offset += 3 + self.offset += 2 self.insts.append(inst) @@ -89,7 +75,7 @@ class Assembler(object): inst = dis.Instruction( 'BINARY_ADD', dis.opname.index('BINARY_ADD'), - None, + 0, None, '', self.offset, @@ -104,14 +90,14 @@ class Assembler(object): inst = dis.Instruction( 'RETURN_VALUE', dis.opname.index('RETURN_VALUE'), - None, + 0, None, '', self.offset, None, False) - self.offset += 1 + self.offset += 2 self.insts.append(inst) @@ -126,13 +112,13 @@ class Assembler(object): None, False) - self.offset += 3 + self.offset += 2 self.insts.append(inst) def code(self): - - b = b''.join(inst_to_bytes(i) for i in self.insts) + + b = b''.join(bytes([i.opcode, i.arg]) for i in self.insts) c = types.CodeType( 0, diff --git a/codemach/machine.py b/codemach/machine.py index <HASH>..<HASH> 100644 --- a/codemach/machine.py +++ b/codemach/machine.py @@ -309,7 +309,7 @@ class Machine(object): self.__stack.append(TOS.__next__()) except StopIteration: self.__stack.pop() - self._ii.jump(i.arg + i.offset + 3) + self._ii.jump(i.arg + i.offset + 2) def __inst_jump_absolute(self, i): self._ii.jump(i.arg)
move to <I>. bytecode length changes from <I> to <I>
chuck1_codemach
train
d66f96b68348d64f6456e79113616f5e0b574ab9
diff --git a/setup.py b/setup.py index <HASH>..<HASH> 100644 --- a/setup.py +++ b/setup.py @@ -33,7 +33,7 @@ setup( version=__version__, description='Python client for the Serf orchestration tool', long_description=long_description, - url='TBD', + url='https://github.com/KushalP/serfclient-py', author='Kushal Pisavadia', author_email='kushal@violentlymild.com', maintainer='Kushal Pisavadia',
The homepage for the project is the GitHub URL It's kinder to point back at the repository page for peopel that want to add some code (y)
KushalP_serfclient-py
train
1b35dda11a93f8dada39db632da90205dbdd1583
diff --git a/text/bayes.go b/text/bayes.go index <HASH>..<HASH> 100644 --- a/text/bayes.go +++ b/text/bayes.go @@ -193,7 +193,7 @@ func (b *NaiveBayes) Predict(sentence string) uint8 { sentence, _, _ = transform.String(b.sanitize, sentence) w := strings.Split(strings.ToLower(sentence), " ") for _, word := range w { - if _, ok := b.Words[word]; len(word) < 3 || !ok { + if _, ok := b.Words[word]; !ok { continue } @@ -305,7 +305,7 @@ func (b *NaiveBayes) UpdateSanitize(sanitize func(rune) bool) { // we're using it to print the model as the equation h(θ)=... // where h is the perceptron hypothesis model. func (b *NaiveBayes) String() string { - return fmt.Sprintf("h(θ) = argmax_c{log(P(y = c)) + ΣP(x|y = c)}\n\tClasses: %v\n\tWords evaluated in model: %v\n", len(b.Count), int(b.DocumentCount)) + return fmt.Sprintf("h(θ) = argmax_c{log(P(y = c)) + ΣP(x|y = c)}\n\tClasses: %v\n\tDocuments evaluated in model: %v\n\tWords evaluated in model: %v\n", len(b.Count), int(b.DocumentCount), int(b.DictCount)) } // PersistToFile takes in an absolute filepath and saves the diff --git a/text/bayes_test.go b/text/bayes_test.go index <HASH>..<HASH> 100644 --- a/text/bayes_test.go +++ b/text/bayes_test.go @@ -61,8 +61,6 @@ func TestExampleClassificationShouldPass1(t *testing.T) { } } - fmt.Printf("Words: %v", model.Words) - // now you can predict like normal class := model.Predict("My mother is in Los Angeles") // 0 assert.EqualValues(t, 0, class, "Class should be 0") @@ -140,9 +138,65 @@ func TestAreaClassificationShouldPass1(t *testing.T) { } } - fmt.Printf("Words: %v", model.Words) + // now you can predict like normal + class := model.Predict("a lot of Japanese People live in Japan") + assert.EqualValues(t, 1, class, "Class should be 1") +} + +func TestPersistPerceptronShouldPass1(t *testing.T) { + // create the channel of data and errors + stream := make(chan base.TextDatapoint, 100) + errors := make(chan error) + + model := NewNaiveBayes(stream, 3, base.OnlyWordsAndNumbers) + + go model.OnlineLearn(errors) + + stream <- base.TextDatapoint{ + X: "I love the city", + Y: 0, + } + + stream <- base.TextDatapoint{ + X: "I hate Los Angeles", + Y: 1, + } + + stream <- base.TextDatapoint{ + X: "My mother is not a nice lady", + Y: 1, + } + + close(stream) + + for { + err, more := <-errors + if more { + fmt.Printf("Error passed: %v", err) + } else { + // training is done! + break + } + } + + // now you can predict like normal + class := model.Predict("My mother is in Los Angeles") // 0 + assert.EqualValues(t, 1, class, "Class should be 0") + + // now persist to file + err := model.PersistToFile("/tmp/.goml/NaiveBayes.json") + assert.Nil(t, err, "Persistance error should be nil") + + model = NewNaiveBayes(stream, 3, base.OnlyWordsAndNumbers) + + class = model.Predict("My mother is in Los Angeles") // 0 + assert.EqualValues(t, 0, class, "Class should be 0") + + // restore from file + err = model.RestoreFromFile("/tmp/.goml/NaiveBayes.json") + assert.Nil(t, err, "Persistance error should be nil") // now you can predict like normal - class := model.Predict("a lot of Japanese People live in Japan") // 0 + class = model.Predict("My mother is in Los Angeles") // 0 assert.EqualValues(t, 1, class, "Class should be 0") }
Added testing for persistance of models
cdipaolo_goml
train
dc65cc6861c3d2771163fc4a37840899a5492e23
diff --git a/pandas/tseries/period.py b/pandas/tseries/period.py index <HASH>..<HASH> 100644 --- a/pandas/tseries/period.py +++ b/pandas/tseries/period.py @@ -109,7 +109,7 @@ class Period(object): dt = value if freq is None: raise ValueError('Must supply freq for datetime value') - elif isinstance(value, (int, long)): + elif isinstance(value, (int, long, np.integer)): if value <= 0: raise ValueError("Value must be positive") self.ordinal = value
Integers extracted from arrays can also be numpy scalars.
pandas-dev_pandas
train
f8cc233758d46975b0435c9dc663ed63e41b2443
diff --git a/wallet/wallet.go b/wallet/wallet.go index <HASH>..<HASH> 100644 --- a/wallet/wallet.go +++ b/wallet/wallet.go @@ -95,7 +95,8 @@ type Wallet struct { chainClientSynced bool chainClientSyncMtx sync.Mutex - lockedOutpoints map[wire.OutPoint]struct{} + lockedOutpoints map[wire.OutPoint]struct{} + lockedOutpointsMtx sync.Mutex recoveryWindow uint32 @@ -2826,6 +2827,9 @@ func (w *Wallet) ImportPrivateKey(scope waddrmgr.KeyScope, wif *btcutil.WIF, // LockedOutpoint returns whether an outpoint has been marked as locked and // should not be used as an input for created transactions. func (w *Wallet) LockedOutpoint(op wire.OutPoint) bool { + w.lockedOutpointsMtx.Lock() + defer w.lockedOutpointsMtx.Unlock() + _, locked := w.lockedOutpoints[op] return locked } @@ -2833,18 +2837,27 @@ func (w *Wallet) LockedOutpoint(op wire.OutPoint) bool { // LockOutpoint marks an outpoint as locked, that is, it should not be used as // an input for newly created transactions. func (w *Wallet) LockOutpoint(op wire.OutPoint) { + w.lockedOutpointsMtx.Lock() + defer w.lockedOutpointsMtx.Unlock() + w.lockedOutpoints[op] = struct{}{} } // UnlockOutpoint marks an outpoint as unlocked, that is, it may be used as an // input for newly created transactions. func (w *Wallet) UnlockOutpoint(op wire.OutPoint) { + w.lockedOutpointsMtx.Lock() + defer w.lockedOutpointsMtx.Unlock() + delete(w.lockedOutpoints, op) } // ResetLockedOutpoints resets the set of locked outpoints so all may be used // as inputs for new transactions. func (w *Wallet) ResetLockedOutpoints() { + w.lockedOutpointsMtx.Lock() + defer w.lockedOutpointsMtx.Unlock() + w.lockedOutpoints = map[wire.OutPoint]struct{}{} } @@ -2852,6 +2865,9 @@ func (w *Wallet) ResetLockedOutpoints() { // intended to be used by marshaling the result as a JSON array for // listlockunspent RPC results. func (w *Wallet) LockedOutpoints() []btcjson.TransactionInput { + w.lockedOutpointsMtx.Lock() + defer w.lockedOutpointsMtx.Unlock() + locked := make([]btcjson.TransactionInput, len(w.lockedOutpoints)) i := 0 for op := range w.lockedOutpoints {
wallet: add mutex for locked outpoints
btcsuite_btcwallet
train
19739034fea7f337773093ca53cf246c37b0a4ae
diff --git a/code/template/helper/behavior.php b/code/template/helper/behavior.php index <HASH>..<HASH> 100644 --- a/code/template/helper/behavior.php +++ b/code/template/helper/behavior.php @@ -274,7 +274,7 @@ class TemplateHelperBehavior extends TemplateHelperAbstract /** * Keep session alive * - * This will send an ascynchronous request to the server via AJAX on an interval in miliseconds + * This will send an ascynchronous request to the server via AJAX on an interval in secs * * @param array $config An optional array with configuration options * @return string The html output @@ -283,8 +283,8 @@ class TemplateHelperBehavior extends TemplateHelperAbstract { $config = new ObjectConfigJson($config); $config->append(array( - 'refresh' => 15 * 60000, //default refresh is 15min - 'url' => '', //default to window.location.url + 'refresh' => 15 * 60, //default refresh is 15min + 'url' => '', //default to window.location.url )); $html = ''; @@ -296,16 +296,16 @@ class TemplateHelperBehavior extends TemplateHelperAbstract if($session->isActive()) { //Get the config session lifetime - $lifetime = $session->getLifetime() * 1000; + $lifetime = $session->getLifetime(); //Refresh time is 1 minute less than the lifetime - $refresh = ($lifetime <= 60000) ? 30000 : $lifetime - 60000; + $refresh = ($lifetime <= 60) ? 30 : $lifetime - 60; } else $refresh = (int) $config->refresh; // Longest refresh period is one hour to prevent integer overflow. - if ($refresh > 3600000 || $refresh <= 0) { - $refresh = 3600000; + if ($refresh > 3600 || $refresh <= 0) { + $refresh = 3600; } if(empty($config->url)) { @@ -315,22 +315,18 @@ class TemplateHelperBehavior extends TemplateHelperAbstract } // Build the keep alive script. - //See: http://stackoverflow.com/questions/5052543/how-to-fire-ajax-request-periodically $html = "<script> - (function keepalive(){ - kQuery(function($) { + (function($){ + var refresh = '" . $refresh . "'; + setInterval(function() { $.ajax({ url: $url, method: 'HEAD', - cache: false, - complete: function() { - // Schedule the next request when the current one's complete - setTimeout(keepalive, '" . $refresh . "'); - } + cache: false }) - }); - })();</script>"; + }, refresh * 1000); + })(kQuery);</script>"; self::$_loaded['keepalive'] = true; }
Issue #<I>: Improve keepalive script
timble_kodekit
train
c090a0f862302b7abc29276eaecea0fb02f47390
diff --git a/src/component.spec.js b/src/component.spec.js index <HASH>..<HASH> 100644 --- a/src/component.spec.js +++ b/src/component.spec.js @@ -224,6 +224,24 @@ describe('Component', () => { }) }) + it('should trigger a callback from rendering a store property', () => { + const callback = sinon.stub() + const store = createStore('name', createPluggable()) + const Test = createComponent(R.F, { test: store }, callback) + + store.getProperty() + .map(<Test />) + .map(shallow) + .first() + .onValue() + + chai.expect(callback.calledOnce).to.be.true + chai.expect(callback.lastCall.args[0]).to.eql({ + test: null, + props: {} + }) + }) + it('should trigger multiple callbacks after subscription', () => { const callback1 = sinon.stub() const callback2 = sinon.stub()
Add unit test to trigger component callbacks
Intai_bdux
train
e502069649501d9abac64a04fc54f97775319de3
diff --git a/libgit/autogit_manager.go b/libgit/autogit_manager.go index <HASH>..<HASH> 100644 --- a/libgit/autogit_manager.go +++ b/libgit/autogit_manager.go @@ -15,6 +15,17 @@ import ( type getNewConfigFn func(context.Context) ( context.Context, libkbfs.Config, string, error) +const ( + // Debug tag ID for an individual autogit operation + ctxAutogitOpID = "AGID" +) + +type ctxAutogitTagKey int + +const ( + ctxAutogitIDKey ctxAutogitTagKey = iota +) + // AutogitManager can clone and pull source git repos into a // destination folder, potentially across different TLFs. New // requests for an operation in a destination repo are blocked by any @@ -93,8 +104,8 @@ func (am *AutogitManager) BatchChanges( for _, node := range nodes { node := node go func() { - // TODO(KBFS-3429): fill in context. - ctx := context.TODO() + ctx := libkbfs.CtxWithRandomIDReplayable( + context.Background(), ctxAutogitIDKey, ctxAutogitOpID, am.log) am.config.KBFSOps().InvalidateNodeAndChildren(ctx, node) }() } diff --git a/libgit/autogit_node_wrappers.go b/libgit/autogit_node_wrappers.go index <HASH>..<HASH> 100644 --- a/libgit/autogit_node_wrappers.go +++ b/libgit/autogit_node_wrappers.go @@ -71,6 +71,8 @@ var _ libkbfs.Node = (*repoFileNode)(nil) func (rfn repoFileNode) GetFile(ctx context.Context) billy.File { // Make a new Browser for every request, for the sole purpose of // using the appropriate debug tags. + ctx = libkbfs.CtxWithRandomIDReplayable( + context.Background(), ctxAutogitIDKey, ctxAutogitOpID, rfn.am.log) repoFS := rfn.repoFS.WithContext(ctx) b, err := NewBrowser(repoFS, rfn.am.config.Clock(), rfn.branch) if err != nil { @@ -118,6 +120,8 @@ func (rdn *repoDirNode) ShouldCreateMissedLookup( func (rdn repoDirNode) GetFS(ctx context.Context) billy.Filesystem { // Make a new Browser for every request, for the sole purpose of // using the appropriate debug tags. + ctx = libkbfs.CtxWithRandomIDReplayable( + context.Background(), ctxAutogitIDKey, ctxAutogitOpID, rdn.am.log) repoFS := rdn.repoFS.WithContext(ctx) b, err := NewBrowser(repoFS, rdn.am.config.Clock(), rdn.branch) if err != nil { @@ -153,9 +157,8 @@ func (rdn repoDirNode) WrapChild(child libkbfs.Node) libkbfs.Node { } } - // Wrap this child so that it will show all the - // repos. TODO(KBFS-3429): fill in context. - ctx := context.TODO() + ctx := libkbfs.CtxWithRandomIDReplayable( + context.Background(), ctxAutogitIDKey, ctxAutogitOpID, rdn.am.log) fs := rdn.GetFS(ctx) fi, err := fs.Lstat(name) if err != nil { @@ -191,7 +194,8 @@ type autogitRootNode struct { var _ libkbfs.Node = (*autogitRootNode)(nil) func (arn autogitRootNode) GetFS(ctx context.Context) billy.Filesystem { - arn.am.log.CDebugf(ctx, "autogit root node GetFS() called") + ctx = libkbfs.CtxWithRandomIDReplayable( + context.Background(), ctxAutogitIDKey, ctxAutogitOpID, arn.am.log) return arn.fs.WithContext(ctx) } @@ -244,18 +248,18 @@ func (rn *rootNode) ShouldCreateMissedLookup(ctx context.Context, name string) ( h, err := rn.am.config.KBFSOps().GetTLFHandle(ctx, rn) if err != nil { - rn.am.log.CDebugf(nil, "Error getting handle: %+v", err) + rn.am.log.CDebugf(ctx, "Error getting handle: %+v", err) return rn.Node.ShouldCreateMissedLookup(ctx, name) } - // Wrap this child so that it will show all the - // repos. TODO(KBFS-3429): fill in context. - ctx := context.TODO() + // Wrap this child so that it will show all the repos. + ctx := libkbfs.CtxWithRandomIDReplayable( + context.Background(), ctxAutogitIDKey, ctxAutogitOpID, rn.am.log) fs, err := libfs.NewFS( ctx, rn.am.config, h, rn.GetFolderBranch().Branch, kbfsRepoDir, "", keybase1.MDPriorityNormal) if err != nil { - rn.am.log.CDebugf(nil, "Error making repo FS: %+v", err) + rn.am.log.CDebugf(ctx, "Error making repo FS: %+v", err) return rn.Node.ShouldCreateMissedLookup(ctx, name) } rn.fs = fs
autogit: tag all autogit contexts with a new AGID tag This will let us get some fuzzy notion of autogit usage in server stats. Issue: KBFS-<I>
keybase_client
train
cf6a4913177e1f44d7939e975ebd610c1852257f
diff --git a/nx/viper/service/mysql.py b/nx/viper/service/mysql.py index <HASH>..<HASH> 100644 --- a/nx/viper/service/mysql.py +++ b/nx/viper/service/mysql.py @@ -1,6 +1,7 @@ from twisted.logger import Logger -from twisted.internet import defer +from twisted.internet import reactor, defer from twisted.enterprise import adbapi +from twisted.python.failure import Failure from nx.viper.application import Application as ViperApplication @@ -66,10 +67,160 @@ class Service: ) except Exception as e: self.log.error( - "[Viper.Database] Cannot connect to server. Error: {error}", + "[Viper.MySQL] Cannot connect to server. Error: {error}", error=str(e) ) + if "init" in self.application.config["viper.mysql"] \ + and self.application.config["viper.mysql"]["init"]["runIfEmpty"]: + self._checkIfDatabaseIsEmpty( + lambda isEmpty: + self._scheduleDatabaseInit(isEmpty) + , + lambda: + self.log.error("[Viper.MySQL] Cannot initialize database.") + ) + + def _checkIfDatabaseIsEmpty(self, successHandler=None, failHandler=None): + """ + Check if database contains any tables. + + :param successHandler: <function(<bool>)> method called if interrogation was successful where the first argument + is a boolean flag specifying if the database is empty or not + :param failHandler: <function> method called if interrogation failed + :return: <void> + """ + def failCallback(error): + if failHandler is not None: + reactor.callInThread(failHandler) + + def selectCallback(transaction, successHandler): + querySelect = \ + "SELECT `TABLE_NAME` " \ + "FROM " \ + "INFORMATION_SCHEMA.TABLES " \ + "WHERE " \ + "`TABLE_SCHEMA` = %s" \ + ";" + + try: + transaction.execute( + querySelect, + (self.application.config["viper.mysql"]["name"],) + ) + + tables = transaction.fetchall() + except Exception as e: + failCallback(e) + return + + if successHandler is not None: + reactor.callInThread(successHandler, len(tables) == 0) + + interaction = self.runInteraction(selectCallback, successHandler) + interaction.addErrback(failCallback) + + def _initDatabase(self): + """ + Initializes the database structure based on application configuration. + + :return: <void> + """ + queries = [] + + if len(self.application.config["viper.mysql"]["init"]["scripts"]) > 0: + for scriptFilePath in self.application.config["viper.mysql"]["init"]["scripts"]: + sqlFile = open(scriptFilePath, "r") + queriesInFile = self.extractFromSQLFile(sqlFile) + sqlFile.close() + + queries.extend(queriesInFile) + + def failCallback(error): + errorMessage = str(error) + if isinstance(error, Failure): + errorMessage = error.getErrorMessage() + + self.log.error( + "[Viper.MySQL] _initDatabase() database error: {errorMessage}", + errorMessage=errorMessage + ) + + def runCallback(transaction, queries): + try: + for query in queries: + transaction.execute(query) + except Exception as e: + failCallback(e) + return + + interaction = self.runInteraction(runCallback, queries) + interaction.addErrback(failCallback) + + def _scheduleDatabaseInit(self, isEmpty): + """ + Schedule database initialization if database is empty. + + :param isEmpty: <bool> flag for database empty status + :return: <void> + """ + if isEmpty: + self._initDatabase() + + def extractFromSQLFile(self, filePointer, delimiter=";"): + """ + Process an SQL file and extract all the queries sorted. + + :param filePointer: <io.TextIOWrapper> file pointer to SQL file + :return: <list> list of queries + """ + data = filePointer.read() + + # reading file and splitting it into lines + dataLines = [] + dataLinesIndex = 0 + for c in data: + if len(dataLines) - 1 < dataLinesIndex: + dataLines.append("") + + if c == "\r\n" or c == "\r" or c == "\n": + dataLinesIndex += 1 + else: + dataLines[dataLinesIndex] = "{}{}".format( + dataLines[dataLinesIndex], + c + ) + + # forming SQL statements from all lines provided + statements = [] + statementsIndex = 0 + for line in dataLines: + # ignoring comments + if line.startswith("--") or line.startswith("#"): + continue + + # removing spaces + line = line.strip() + + # ignoring blank lines + if len(line) == 0: + continue + + # appending each character to it's statement until delimiter is reached + for c in line: + if len(statements) - 1 < statementsIndex: + statements.append("") + + statements[statementsIndex] = "{}{}".format( + statements[statementsIndex], + c + ) + + if c == delimiter: + statementsIndex += 1 + + return statements + def runInteraction(self, interaction, *args, **kwargs): """ Interact with the database and return the result.
Database initialization -added option to automatically execute SQL scripts against the database if found empty on startup
Nixiware_viper
train
4184f832c0ea90a521e769bf35529ef13ee6e652
diff --git a/languagetool-server/src/main/java/org/languagetool/server/TextChecker.java b/languagetool-server/src/main/java/org/languagetool/server/TextChecker.java index <HASH>..<HASH> 100644 --- a/languagetool-server/src/main/java/org/languagetool/server/TextChecker.java +++ b/languagetool-server/src/main/java/org/languagetool/server/TextChecker.java @@ -153,6 +153,7 @@ abstract class TextChecker { try { matches = future.get(limits.getMaxCheckTimeMillis(), TimeUnit.MILLISECONDS); } catch (ExecutionException e) { + future.cancel(true); if (params.allowIncompleteResults && ExceptionUtils.getRootCause(e) instanceof ErrorRateTooHighException) { print(e.getMessage() + " - returning " + ruleMatchesSoFar.size() + " matches found so far"); matches = new ArrayList<>(ruleMatchesSoFar); // threads might still be running, so make a copy @@ -192,6 +193,7 @@ abstract class TextChecker { List<RemoteRuleMatch> tmpHiddenMatches = hiddenMatchesFuture.get(config.getHiddenMatchesServerTimeout(), TimeUnit.MILLISECONDS); hiddenMatches = resultExtender.getFilteredExtensionMatches(matches, tmpHiddenMatches); } catch (TimeoutException e) { + hiddenMatchesFuture.cancel(true); print("Warn: Failed to query hidden matches server at " + config.getHiddenMatchesServer() + " due to timeout (" + config.getHiddenMatchesServerTimeout() + "ms): " + e.getMessage()); } catch (Exception e) {
on exception, stop the running thread that caused e.g. a timeout
languagetool-org_languagetool
train
3e96c8be7bb9e1d71390eb856e912fb382ade233
diff --git a/.gitignore b/.gitignore index <HASH>..<HASH> 100644 --- a/.gitignore +++ b/.gitignore @@ -2,6 +2,7 @@ __pycache__/ *.py[cod] *$py.class +fontconfig/ # C extensions *.so diff --git a/django_toolset/__init__.py b/django_toolset/__init__.py index <HASH>..<HASH> 100644 --- a/django_toolset/__init__.py +++ b/django_toolset/__init__.py @@ -1,5 +1,5 @@ # coding=utf-8 -VERSION = (0, 1, 3, 'DEV') +VERSION = (0, 1, 4, 'DEV') # Dynamically calculate the version based on VERSION tuple if len(VERSION) > 2 and VERSION[2] is not None: diff --git a/django_toolset/templatetags/custom_tags.py b/django_toolset/templatetags/custom_tags.py index <HASH>..<HASH> 100644 --- a/django_toolset/templatetags/custom_tags.py +++ b/django_toolset/templatetags/custom_tags.py @@ -7,37 +7,47 @@ register = template.Library() @register.simple_tag(takes_context=True) -def active(context, pattern_or_urlname, class_name='active'): +def active(context, pattern_or_urlname, class_name='active', *args, **kwargs): """Based on a URL Pattern or name, determine if it is the current page. This is useful if you're creating a navigation component and want to give the active URL a specific class for UI purposes. It will accept a named - URL or a regex pattern. + URL or a regex pattern. If you have a URL which accepts args or kwargs then + you may pass them into the tag and they will be picked up for matching as + well. Usage: {% load custom_tags %} - <nav> - <ul> - <li class="nav-home {% active 'url-name' %}"><a href="#">Home</a></li> - <li class="nav-blog {% active '^/regex/' %}"><a href="#">Blog</a></li> - </ul> - </nav> - - or - - <nav> - <ul> - <li class="nav-home {% active 'url-name' class_name='current' %}"><a href="#">Home</a></li> - <li class="nav-blog {% active '^/regex/' class_name='current' %}"><a href="#">Blog</a></li> - </ul> - </nav> + + <li class="nav-home {% active 'url-name' %}"> + <a href="#">Home</a> + </li> + + OR + + <li class="nav-home {% active '^/regex/' %}"> + <a href="#">Home</a> + </li> + + OR + + <li class="nav-home {% active 'url-name' class_name='current' %}"> + <a href="#">Home</a> + </li> + + OR + + <li class="nav-home {% active 'url-name' username=user.username %}"> + <a href="#">Home</a> + </li> """ request = context.dicts[1].get('request') try: - pattern = '^%s$' % reverse(pattern_or_urlname) + pattern = '^%s$' % reverse(pattern_or_urlname, args=args, + kwargs=kwargs) except NoReverseMatch: pattern = pattern_or_urlname @@ -45,3 +55,4 @@ def active(context, pattern_or_urlname, class_name='active'): return class_name return '' + diff --git a/setup.py b/setup.py index <HASH>..<HASH> 100644 --- a/setup.py +++ b/setup.py @@ -44,7 +44,7 @@ setup( include_package_data=True, license='MIT License', description='A set of helper functions and utilities for a Django application', - download_url = 'https://github.com/codezeus/django-toolset/tarball/0.1.3', + download_url = 'https://github.com/codezeus/django-toolset/tarball/0.1.4', long_description=README, cmdclass=cmdclasses, url='https://github.com/codezeus/django-toolset',
Allow args and kwargs in active tag
dansackett_django-toolset
train
e1b9451a6c5e9c130cc6e94121a2effc4b854e26
diff --git a/tests/test_svcreg.py b/tests/test_svcreg.py index <HASH>..<HASH> 100644 --- a/tests/test_svcreg.py +++ b/tests/test_svcreg.py @@ -60,12 +60,12 @@ def test_unique_service(rr): svcreg.unique_service('example-role', candidate={}) svc01 = { "role": "example-role", - "ttl": 0.4, + "ttl": 1.2, "node": "test01.example.com" } svc02 = { "role": "example-role", - "ttl": 0.4, + "ttl": 1.2, "node": "test02.example.com" } # register svc01. output should be svc01. @@ -117,12 +117,12 @@ def test_service_registry(rr): svc0 = { "role": "yes-such-role", "load": 100.0, - "ttl": 0.4, + "ttl": 1.2, } svc1 = { "role": "yes-such-role", "load": 200.0, - "ttl": 0.4, + "ttl": 1.2, } svc0 = svcreg.heartbeat(svc0) svc1 = svcreg.heartbeat(svc1) @@ -188,12 +188,12 @@ def test_service_registry(rr): svc0 = { "role": "yes-such-role", "load": 100.0, - "ttl": 0.4, + "ttl": 1.2, } svc1 = { "role": "yes-such-role", "load": 200.0, - "ttl": 0.4, + "ttl": 1.2, } svc0 = svcreg.heartbeat(svc0) svc1 = svcreg.heartbeat(svc1) @@ -205,22 +205,22 @@ def test_service_registry(rr): svc0 = { "role": "yes-such-role", "load": 100.0, - "ttl": 0.4, + "ttl": 1.2, } svc1 = { "role": "yes-such-role", "load": 200.0, - "ttl": 0.4, + "ttl": 1.2, } svc2 = { "role": "another-such-role", "load": 200.0, - "ttl": 0.4, + "ttl": 1.2, } svc3 = { "role": "yet-another-such-role", "load": 200.0, - "ttl": 0.4, + "ttl": 1.2, } svc0 = svcreg.heartbeat(svc0) svc1 = svcreg.heartbeat(svc1) @@ -245,7 +245,7 @@ def test_svcreg_heartbeat_server_down(rr): svc0 = { "role": "role-foo", "load": 100.0, - "ttl": 0.4, + "ttl": 1.2, } # no exception thrown svc0 = svcreg.heartbeat(svc0)
forgot to multiply the constants by 3
internetarchive_doublethink
train
68a79fc6a32bab9406083545e667a65ba67b0a3e
diff --git a/github/users.go b/github/users.go index <HASH>..<HASH> 100644 --- a/github/users.go +++ b/github/users.go @@ -76,6 +76,7 @@ func (u User) String() string { // user. // // GitHub API docs: https://developer.github.com/v3/users/#get-a-single-user +// and: https://developer.github.com/v3/users/#get-the-authenticated-user func (s *UsersService) Get(ctx context.Context, user string) (*User, *Response, error) { var u string if user != "" {
Godoc: Add GitHub API doc link for "Get the authenticated user" (#<I>)
google_go-github
train
fd535f10b3189fa46d1b72c64841da187128dc2c
diff --git a/Dropbox/OAuth/Consumer/ConsumerAbstract.php b/Dropbox/OAuth/Consumer/ConsumerAbstract.php index <HASH>..<HASH> 100644 --- a/Dropbox/OAuth/Consumer/ConsumerAbstract.php +++ b/Dropbox/OAuth/Consumer/ConsumerAbstract.php @@ -114,7 +114,7 @@ abstract class ConsumerAbstract $params['oauth_signature'] = $signature; // Build the signed request URL - $query = '?' . http_build_query($params,'','&'); + $query = '?' . http_build_query($params, '', '&'); return array( 'url' => $url . $call . $query, 'postfields' => $params,
Separated function arguments with single space character
BenExile_Dropbox
train
88711492fa1c37f680d583385ec36f4079bee598
diff --git a/src/DependencyInjection/Compiler/FilterTypePass.php b/src/DependencyInjection/Compiler/FilterTypePass.php index <HASH>..<HASH> 100644 --- a/src/DependencyInjection/Compiler/FilterTypePass.php +++ b/src/DependencyInjection/Compiler/FilterTypePass.php @@ -23,6 +23,14 @@ final class FilterTypePass implements CompilerPassInterface { // type guessers $guessers = $this->findAndSortTaggedServices('easyadmin.filter.type_guesser', $container); + // the filter type guesser created by the user (in the app side) becomes + // a form type guesser too due to autoconfiguration, and that can cause + // issues in new/edit forms, so we need to exclude the filter type guesser + // from the form type guessers group + foreach ($guessers as $guesser) { + $container->getDefinition((string) $guesser) + ->clearTag('form.type_guesser'); + } // types Map $typesMap = []; $servicesMap = []; diff --git a/src/EasyAdminBundle.php b/src/EasyAdminBundle.php index <HASH>..<HASH> 100644 --- a/src/EasyAdminBundle.php +++ b/src/EasyAdminBundle.php @@ -19,7 +19,9 @@ class EasyAdminBundle extends Bundle public function build(ContainerBuilder $container) { $container->addCompilerPass(new EasyAdminFormTypePass(), PassConfig::TYPE_BEFORE_REMOVING); - $container->addCompilerPass(new FilterTypePass()); + // this compiler pass must run earlier than FormPass to clear + // the 'form.type_guesser' tag for 'easyadmin.filter.type_guesser' services + $container->addCompilerPass(new FilterTypePass(), PassConfig::TYPE_BEFORE_OPTIMIZATION, 10); $container->addCompilerPass(new EasyAdminConfigPass()); } }
Excluding the filter type guesser from the form type guessers group
EasyCorp_EasyAdminBundle
train
f7b5c3c1281fbdadef820a95f2e26e1b4647b485
diff --git a/lib/site_prism/element_checker.rb b/lib/site_prism/element_checker.rb index <HASH>..<HASH> 100644 --- a/lib/site_prism/element_checker.rb +++ b/lib/site_prism/element_checker.rb @@ -34,7 +34,7 @@ module SitePrism test_sections = new_mapped_items[:sections].select { |name| _expected_items.include?(name) } test_iframe = new_mapped_items[:iframe].select { |name| _expected_items.include?(name) } - regular_items_to_check = [test_element, test_elements, test_section, test_sections, test_iframe] + regular_items_to_check = [test_element, test_elements, test_section, test_sections, test_iframe].flatten regular_items_all_there = regular_items_to_check.all? { |name| there?(name) } return regular_items_all_there unless regular_items_all_there diff --git a/lib/site_prism/recursion_checker.rb b/lib/site_prism/recursion_checker.rb index <HASH>..<HASH> 100644 --- a/lib/site_prism/recursion_checker.rb +++ b/lib/site_prism/recursion_checker.rb @@ -36,7 +36,7 @@ module SitePrism end def all_there? - regular_items_all_there = expected_item_map.all? { |name| there?(name) } + regular_items_all_there = expected_item_map.flatten.all? { |name| there?(name) } return regular_items_all_there unless regular_items_all_there section_all_there = diff --git a/spec/site_prism/element_checker_spec.rb b/spec/site_prism/element_checker_spec.rb index <HASH>..<HASH> 100644 --- a/spec/site_prism/element_checker_spec.rb +++ b/spec/site_prism/element_checker_spec.rb @@ -39,22 +39,24 @@ describe SitePrism::ElementChecker do context 'with recursion set to one' do subject { page.all_there?(recursion: 'one') } - let!(:section) { double('SitePrism::Section') } + let!(:section) { instance_double('SitePrism::Section') } before do allow(page).to receive(:section_one).and_return(section) - allow(section).to receive(:has_inner_element_one?).and_return(true) - allow(section).to receive(:has_inner_element_two?).and_return(true) - allow(section).to receive(:has_iframe?).and_return(true) + # allow(section).to receive(:all_there?).and_call_original + allow(section).to receive(:there?).with(:inner_element_one).and_return(true) + allow(section).to receive(:there?).with(:inner_element_two).and_return(true) + allow(section).to receive(:there?).with(:iframe).and_return(true) end - it { is_expected.to be true } + # it { is_expected.to be true } it 'checks each item in expected elements plus all first-generation descendants' do expected_items.each do |name| expect(page).to receive(:there?).with(name).once.and_call_original end + expect(section).to receive(:all_there?).with({ recursion: 'none' }).and_call_original expect(section).to receive(:has_inner_element_one?) expect(section).to receive(:has_inner_element_two?) expect(section).to receive(:has_iframe?) @@ -79,7 +81,7 @@ describe SitePrism::ElementChecker do subject end - expect(lines(log_messages)).to eq(2) + expect(lines(log_messages)).to eq(1) end end end diff --git a/spec/site_prism/element_spec.rb b/spec/site_prism/element_spec.rb index <HASH>..<HASH> 100644 --- a/spec/site_prism/element_spec.rb +++ b/spec/site_prism/element_spec.rb @@ -3,6 +3,7 @@ describe 'Element' do # This stops the stdout process leaking between tests before(:each) { wipe_logger! } + let(:expected_elements) { SitePrism::SpecHelper.present_stubs } shared_examples 'an element' do describe '.element' do @@ -45,7 +46,7 @@ describe 'Element' do describe '#elements_present' do it 'only lists the SitePrism objects that are present on the page' do - expect(page.elements_present).to eq(%i[element_one element_three]) + expect(page.elements_present.sort).to eq(expected_elements.sort) end end
WIP: Fix rspec tests, not currently complete
natritmeyer_site_prism
train
45987c428c77f30ea62220bbacbc48bdd4e09f10
diff --git a/examples/sandbox/sandbox.py b/examples/sandbox/sandbox.py index <HASH>..<HASH> 100644 --- a/examples/sandbox/sandbox.py +++ b/examples/sandbox/sandbox.py @@ -205,6 +205,6 @@ simConfig['analysis'] = {} # 'saveName': 'fig1.png'} # (include = ['all'], timeRange = None, maxSpikes = 1e8, orderBy = 'gid', orderInverse = False, spikeHist = None, syncLines = False, saveData = None, saveFig = None): -simConfig['analysis']['plotRaster']={'include': ['PYR', 'allNetStims', 'background2', ('PYR',[5,6,7,8])], +simConfig['analysis']['plotSpikeHist']={'include': ['PYR', 'allNetStims', 'background2', ('PYR',[5,6,7,8])], 'timeRange': [400,600], 'binSize': 10, 'overlay':True, 'graphType': 'line', 'yaxis': 'count', 'saveData': None, 'saveFig': None, 'showFig': True} diff --git a/netpyne/analysis.py b/netpyne/analysis.py index <HASH>..<HASH> 100644 --- a/netpyne/analysis.py +++ b/netpyne/analysis.py @@ -24,9 +24,9 @@ def plotData (): sim.timing('start', 'plotTime') # Call analysis functions specified by user - for funcName, args in sim.cfg['analysis']: + for funcName, kwargs in sim.cfg['analysis'].iteritems(): func = getattr(sim.analysis, funcName) # get pointer to function - func(args) # call function with user arguments + func(**kwargs) # call function with user arguments # Print timings if sim.cfg['timing']: @@ -317,6 +317,8 @@ def plotSpikeHist (include = ['allCells', 'eachPop'], timeRange = None, binSize - Returns figure handle ''' + print('Plotting spike histogram...') + colorList = [[0.42,0.67,0.84], [0.90,0.76,0.00], [0.42,0.83,0.59], [0.90,0.32,0.00], [0.34,0.67,0.67], [0.90,0.59,0.00], [0.42,0.82,0.83], [1.00,0.85,0.00], [0.33,0.67,0.47], [1.00,0.38,0.60], [0.57,0.67,0.33], [0.5,0.2,0.0],
added plotSpikeHist() (issue #<I>)
Neurosim-lab_netpyne
train
eaa75283c89b5eebde30532f75dbd3e8694a959e
diff --git a/src/Staq/Core/Data/Stack/Router.php b/src/Staq/Core/Data/Stack/Router.php index <HASH>..<HASH> 100644 --- a/src/Staq/Core/Data/Stack/Router.php +++ b/src/Staq/Core/Data/Stack/Router.php @@ -16,6 +16,8 @@ class Router extends Router\__Parent{ $page = new \Stack\View; $page[ 'content' ] = $model; $page[ 'template' ] = 'model/' . \Staq\Util::stack_sub_query( $model, '/' ); + } else { + $page = $model; } return parent::render( $page ); }
BugFix: Page was not always setted
Elephant418_Staq
train
4fbf5d8beeef6111aa8d99320d4c624537ceb239
diff --git a/modules/clipboard.js b/modules/clipboard.js index <HASH>..<HASH> 100644 --- a/modules/clipboard.js +++ b/modules/clipboard.js @@ -456,6 +456,12 @@ function matchStyles(node, delta) { if (style.fontStyle === 'italic') { formats.italic = true; } + if (style.textDecoration === 'underline') { + formats.underline = true; + } + if (style.textDecoration === 'line-through') { + formats.strike = true; + } if ( style.fontWeight.startsWith('bold') || parseInt(style.fontWeight, 10) >= 700
Add style match for underline and strike
quilljs_quill
train
73d992633205bef154ba9e00fb7c3aacf06f3458
diff --git a/lib/hutch/waiter.rb b/lib/hutch/waiter.rb index <HASH>..<HASH> 100644 --- a/lib/hutch/waiter.rb +++ b/lib/hutch/waiter.rb @@ -12,7 +12,9 @@ module Hutch end def self.supported_signals_of(list) - list.keep_if { |s| Signal.list.keys.include? s } + list.keep_if { |s| Signal.list.keys.include?(s) }.tap do |result| + result.delete('QUIT') if defined?(JRUBY_VERSION) + end end SHUTDOWN_SIGNALS = supported_signals_of(%w(QUIT TERM INT)).freeze
Waiter: QUIT is not supported on JRuby
gocardless_hutch
train
9c0074497740a86843845456f0683f363382ca12
diff --git a/src/Draggy/Autocode/Project.php b/src/Draggy/Autocode/Project.php index <HASH>..<HASH> 100644 --- a/src/Draggy/Autocode/Project.php +++ b/src/Draggy/Autocode/Project.php @@ -238,6 +238,8 @@ class Project extends ProjectBase $xmlDesign = simplexml_load_file($file); $this->loadDesign($xmlDesign); + + return $this; } public function loadDesign(\SimpleXMLElement $xmlDesign)
Added fluent interface to loadFile
j-d_draggy
train
f4115d3832c77ed37188974e6b61f73f04616ead
diff --git a/jbpm-flow/src/main/java/org/jbpm/workflow/instance/node/EndNodeInstance.java b/jbpm-flow/src/main/java/org/jbpm/workflow/instance/node/EndNodeInstance.java index <HASH>..<HASH> 100644 --- a/jbpm-flow/src/main/java/org/jbpm/workflow/instance/node/EndNodeInstance.java +++ b/jbpm-flow/src/main/java/org/jbpm/workflow/instance/node/EndNodeInstance.java @@ -59,11 +59,7 @@ public class EndNodeInstance extends ExtendedNodeInstanceImpl { getProcessInstance().setState( ProcessInstance.STATE_COMPLETED ); } else { - // handle composite nodes such as embedded sub process - // deactivate all node instances of this composite node instance - ((CompositeNodeInstance) getNodeInstanceContainer()).cancel(); - - ((NodeInstanceContainer) getNodeInstanceContainer()).nodeInstanceCompleted(this, null); + ((NodeInstanceContainer) getNodeInstanceContainer()).nodeInstanceCompleted(this, null); } } else {
- removed not needed cancel on NodeInstanceContainer
kiegroup_jbpm
train
2898d6f11a4b042a9554f9faa89e7257e6568d63
diff --git a/spec/Fixture/Plugin/Double/NullableInterface.php b/spec/Fixture/Plugin/Double/NullableInterface.php index <HASH>..<HASH> 100644 --- a/spec/Fixture/Plugin/Double/NullableInterface.php +++ b/spec/Fixture/Plugin/Double/NullableInterface.php @@ -3,5 +3,6 @@ namespace Kahlan\Spec\Fixture\Plugin\Double; interface NullableInterface { - public function foo(?int $limit = null): ?int; + public function foo(?int $integer = null): ?int; + public function doz(?\Kahlan\Spec\Fixture\Plugin\Double\Doz $instance = null): ?\Kahlan\Spec\Fixture\Plugin\Double\Doz; } diff --git a/spec/Suite/Plugin/Double.spec.php b/spec/Suite/Plugin/Double.spec.php index <HASH>..<HASH> 100644 --- a/spec/Suite/Plugin/Double.spec.php +++ b/spec/Suite/Plugin/Double.spec.php @@ -565,7 +565,8 @@ namespace Kahlan\\Spec\\Plugin\\Double; class Double implements \\Kahlan\\Spec\\Fixture\\Plugin\\Double\\NullableInterface { - public function foo(?int \$limit = NULL) : ?int {} + public function foo(?int \$integer = NULL) : ?int {} + public function doz(?\Kahlan\Spec\Fixture\Plugin\Double\Doz \$instance = NULL) : ?\Kahlan\Spec\Fixture\Plugin\Double\Doz {} } ?> diff --git a/src/Plugin/Double.php b/src/Plugin/Double.php index <HASH>..<HASH> 100644 --- a/src/Plugin/Double.php +++ b/src/Plugin/Double.php @@ -407,12 +407,12 @@ EOT; $type = $method->getReturnType(); $allowsNull = ''; if ($type) { - if (!$type->isBuiltin()) { - $type = '\\' . $type; - } if (method_exists($type, 'allowsNull') && $type->allowsNull()) { $allowsNull = '?'; } + if (!$type->isBuiltin()) { + $type = '\\' . $type; + } if (defined('HHVM_VERSION')) { $type = preg_replace('~\\\?HH\\\(mixed|void)?~', '', $type); }
Fix Nullable types for non built-in types.
kahlan_kahlan
train
c287097d62ee14046b4761e493c874da6f1d54da
diff --git a/tests/perf/src/test/java/org/sonarsource/sonarqube/perf/scanner/suite/IssuesModeTest.java b/tests/perf/src/test/java/org/sonarsource/sonarqube/perf/scanner/suite/IssuesModeTest.java index <HASH>..<HASH> 100644 --- a/tests/perf/src/test/java/org/sonarsource/sonarqube/perf/scanner/suite/IssuesModeTest.java +++ b/tests/perf/src/test/java/org/sonarsource/sonarqube/perf/scanner/suite/IssuesModeTest.java @@ -21,6 +21,7 @@ package org.sonarsource.sonarqube.perf.scanner.suite; import com.sonar.orchestrator.Orchestrator; import com.sonar.orchestrator.build.SonarRunner; +import com.sonar.orchestrator.build.SonarScanner; import org.sonarsource.sonarqube.perf.PerfRule; import org.sonarsource.sonarqube.perf.PerfTestCase; import java.io.File; @@ -57,7 +58,7 @@ public class IssuesModeTest extends PerfTestCase { File userHome = temp.newFolder(); orchestrator.getServer().provisionProject("sample", "xoo-sample"); orchestrator.getServer().associateProjectToQualityProfile("sample", "xoo", "one-xoo-issue-per-line"); - SonarRunner runner = newScanner( + SonarScanner runner = newScanner( "-Xmx512m -server -XX:MaxPermSize=64m", "sonar.analysis.mode", "issues", "sonar.userHome", userHome.getAbsolutePath(), @@ -67,7 +68,7 @@ public class IssuesModeTest extends PerfTestCase { long duration = System.currentTimeMillis() - start; System.out.println("Issues analysis: " + duration + "ms"); - perfRule.assertDurationAround(duration, 4450L); + perfRule.assertDurationAround(duration, 5230L); } @Test diff --git a/tests/perf/src/test/java/org/sonarsource/sonarqube/perf/server/ServerTest.java b/tests/perf/src/test/java/org/sonarsource/sonarqube/perf/server/ServerTest.java index <HASH>..<HASH> 100644 --- a/tests/perf/src/test/java/org/sonarsource/sonarqube/perf/server/ServerTest.java +++ b/tests/perf/src/test/java/org/sonarsource/sonarqube/perf/server/ServerTest.java @@ -47,7 +47,7 @@ public class ServerTest extends PerfTestCase { .build(); try { long startupDuration = start(orchestrator); - assertDurationAround(startupDuration, 46000); + assertDurationAround(startupDuration, 41000); long shutdownDuration = stop(orchestrator); // can't use percent margins because logs are second-grained but not milliseconds
Fix timings in performance tests due to hardware/OS change
SonarSource_sonarqube
train
0a2a567c4158ee2a513e941337dc6e8b4e7cab16
diff --git a/api/users/forms.py b/api/users/forms.py index <HASH>..<HASH> 100644 --- a/api/users/forms.py +++ b/api/users/forms.py @@ -12,7 +12,7 @@ User = get_user_model() class RegistrationForm(UserCreationForm): - username = forms.EmailField( + email = forms.EmailField( help_text='email address', required=True, validators=[ @@ -26,10 +26,3 @@ class RegistrationForm(UserCreationForm): 'required': validators.TOS_REQUIRED, } ) - - def save(self, commit=True): - user = super(RegistrationForm, self).save(commit=False) - user.email = user.username - if commit: - user.save() - return user
Default to normal behaviour with usernames
polyaxon_polyaxon
train
877d885fbd30c45618fa801fd3350e2564ae1ace
diff --git a/test/on_yubikey/test_fips_u2f_commands.py b/test/on_yubikey/test_fips_u2f_commands.py index <HASH>..<HASH> 100644 --- a/test/on_yubikey/test_fips_u2f_commands.py +++ b/test/on_yubikey/test_fips_u2f_commands.py @@ -40,6 +40,9 @@ class TestFipsU2fCommands(DestructiveYubikeyTestCase): FIPS_U2F_CMD.VERIFY_PIN, P1, P2, 0, 6, b'012345' )) + if verify_res1 == b'\x63\xc0': + self.skipTest('PIN set to something other than 012345') + if verify_res1 == b'\x90\x00': res = dev.driver._dev.call( CTAPHID.MSG,
Skip FIPS U2F PIN test if PIN is set to something else than <I>
Yubico_yubikey-manager
train
3fe7a536532f1bfd65c45134d8a23a789825476d
diff --git a/test/compile.js b/test/compile.js index <HASH>..<HASH> 100644 --- a/test/compile.js +++ b/test/compile.js @@ -64,6 +64,10 @@ module.exports.tests.current_schema = function(test, common) { // common.diff(schemaCopy, fixture); // console.error( JSON.stringify( schemaCopy, null, 2 ) ); + // code to write expected output to the fixture + //const fs = require('fs'); + //fs.writeFileSync(path.resolve( __dirname + '/fixtures/expected.json' ), JSON.stringify(schemaCopy, null, 2)); + t.deepEqual(schemaCopy, fixture); t.end(); });
Add commented out code to write expected schema to fixture this can help in updating that massive file
pelias_schema
train
d33f33d666746028eeb16a6b3c210c2f17647169
diff --git a/lib/plugins/index.js b/lib/plugins/index.js index <HASH>..<HASH> 100644 --- a/lib/plugins/index.js +++ b/lib/plugins/index.js @@ -263,8 +263,8 @@ function getRules(req, port, callback) { var options = url.parse(req.fullUrl); options.headers = extend({}, req.headers); options.headers[FULL_URL_HEADER] = encodeURIComponent(req.fullUrl); - options.headers[METHOD_HEADER] = req.isTunnel ? 'TUNNEL' : encodeURIComponent(req.method || ''); - if (req.isTunnel || options.protocol == 'https:' || options.protocol == 'wss:') { + options.headers[METHOD_HEADER] = encodeURIComponent(req.method || ''); + if (options.protocol == 'https:' || options.protocol == 'wss:') { options.headers[SSL_FLAG_HEADER] = 'true'; }
feat: Let websocket, tunnel support the built-in rules of the disable and filter attributes
avwo_whistle
train
dc6a14af38b14eba75c6381e4cfafa46d4bfe5b6
diff --git a/function-scout.js b/function-scout.js index <HASH>..<HASH> 100644 --- a/function-scout.js +++ b/function-scout.js @@ -57,7 +57,7 @@ module.exports = function functionScout(object, { mutate = false } = {}) { if (typeof node !== 'function') return const info = scoutFunction(node) functions.push({ path: this.path, key: this.key, level: this.level, info: info }) - this.update(info) + if (mutate) this.update(info) } // we don't mutate by default
fix: not mutating during traverse when turned off
nodesource_function-scout
train
de2b9caeeb7770a97b8aa561ddd71f42df287aa3
diff --git a/gns3server/compute/qemu/qemu_vm.py b/gns3server/compute/qemu/qemu_vm.py index <HASH>..<HASH> 100644 --- a/gns3server/compute/qemu/qemu_vm.py +++ b/gns3server/compute/qemu/qemu_vm.py @@ -1722,11 +1722,21 @@ class QemuVM(BaseNode): async def _import_config(self): disk_name = getattr(self, "config_disk_name") + if not disk_name: + return + disk = os.path.join(self.working_dir, disk_name) zip_file = os.path.join(self.working_dir, "config.zip") - if not disk_name or not os.path.exists(zip_file): + startup_config = self.hdd_disk_image + if startup_config and startup_config.lower().endswith(".zip") and \ + not os.path.exists(zip_file) and not os.path.exists(disk): + try: + shutil.copyfile(startup_config, zip_file) + except OSError as e: + log.warning("Can't access startup config: {}".format(e)) + self.project.emit("log.warning", {"message": "{}: Can't access startup config: {}".format(self._name, e)}) + if not os.path.exists(zip_file): return config_dir = os.path.join(self.working_dir, "configs") - disk = os.path.join(self.working_dir, disk_name) disk_tmp = disk + ".tmp" try: os.mkdir(config_dir)
Use HDD disk image as startup QEMU config disk
GNS3_gns3-server
train
198ab1d7cd71ad0064cf0b58427d2e35eeeefc96
diff --git a/lib/pghero/methods/indexes.rb b/lib/pghero/methods/indexes.rb index <HASH>..<HASH> 100644 --- a/lib/pghero/methods/indexes.rb +++ b/lib/pghero/methods/indexes.rb @@ -13,8 +13,9 @@ module PgHero def index_caching select_all <<-SQL SELECT - indexrelname AS index, + schemaname AS schema, relname AS table, + indexrelname AS index, CASE WHEN idx_blks_hit + idx_blks_read = 0 THEN 0 ELSE diff --git a/lib/pghero/methods/tables.rb b/lib/pghero/methods/tables.rb index <HASH>..<HASH> 100644 --- a/lib/pghero/methods/tables.rb +++ b/lib/pghero/methods/tables.rb @@ -14,6 +14,7 @@ module PgHero def table_caching select_all <<-SQL SELECT + schemaname AS schema, relname AS table, CASE WHEN heap_blks_hit + heap_blks_read = 0 THEN 0
Added schema to more queries [skip ci]
ankane_pghero
train
847be8cb13e2f0882837b4e0742164d74efeb3bb
diff --git a/ramda.js b/ramda.js index <HASH>..<HASH> 100644 --- a/ramda.js +++ b/ramda.js @@ -4864,8 +4864,7 @@ '\u2029\uFEFF'; var zeroWidth = '\u200b'; var hasProtoTrim = (typeof String.prototype.trim === 'function'); - var hasTrimBug = ws.trim() || !zeroWidth.trim(); - if (!hasProtoTrim || hasTrimBug) { + if (!hasProtoTrim || (ws.trim() || !zeroWidth.trim())) { return function _trim(str) { var beginRx = new RegExp('^[' + ws + '][' + ws + ']*'); var endRx = new RegExp('[' + ws + '][' + ws + ']*$');
fix trim for IE < 9. yay. my favorite.
ramda_ramda
train
3581e19993c8967b362e4ad51e46ca3dc4519a69
diff --git a/lib/calyx.rb b/lib/calyx.rb index <HASH>..<HASH> 100644 --- a/lib/calyx.rb +++ b/lib/calyx.rb @@ -1,6 +1,8 @@ module Calyx class Grammar class << self + attr_accessor :registry + def start(*productions, &production) registry[:start] = construct_rule(productions) end @@ -9,8 +11,13 @@ module Calyx registry[name.to_sym] = construct_rule(productions) end - def registry + def inherit_registry(rules) @registry ||= {} + @registry.merge!(rules || {}) + end + + def inherited(subclass) + subclass.inherit_registry(@registry) end def construct_rule(productions) diff --git a/lib/calyx/version.rb b/lib/calyx/version.rb index <HASH>..<HASH> 100644 --- a/lib/calyx/version.rb +++ b/lib/calyx/version.rb @@ -1,3 +1,3 @@ module Calyx - VERSION = '0.1.1'.freeze + VERSION = '0.2.0'.freeze end diff --git a/spec/calyx_spec.rb b/spec/calyx_spec.rb index <HASH>..<HASH> 100644 --- a/spec/calyx_spec.rb +++ b/spec/calyx_spec.rb @@ -23,4 +23,18 @@ describe Calyx do grammar = OneTwo.new expect(grammar.generate).to eq('One. Two.') end + + specify 'rule inheritance' do + class BaseRules < Calyx::Grammar + rule :one, 'One.' + rule :two, 'Two.' + end + + class StartRule < BaseRules + start '{one} {two}' + end + + grammar = StartRule.new + expect(grammar.generate).to eq('One. Two.') + end end
Support subclassing grammars to share rule sets
maetl_calyx
train
d7469e469490b00f83b61d04e02cef856c805b93
diff --git a/java/src/test/java/org/msgpack/TestCases.java b/java/src/test/java/org/msgpack/TestCases.java index <HASH>..<HASH> 100644 --- a/java/src/test/java/org/msgpack/TestCases.java +++ b/java/src/test/java/org/msgpack/TestCases.java @@ -21,9 +21,6 @@ public class TestCases { @Test public void testCases() throws Exception { - System.out.println( new File(".").getAbsoluteFile().getParent() ); - - Unpacker pac = new Unpacker(); Unpacker pac_compact = new Unpacker(); @@ -34,13 +31,10 @@ public class TestCases { while(pac.next(result)) { UnpackResult result_compact = new UnpackResult(); assertTrue( pac_compact.next(result_compact) ); - System.out.println("obj: "+result_compact.getData()); - if(!result.getData().equals(result_compact.getData())) { - System.out.println("compact: "+result_compact.getData().asString()); - System.out.println("data : "+result.getData().asString()); - } assertTrue( result.getData().equals(result_compact.getData()) ); } + + assertFalse( pac_compact.next(result) ); } };
java: fixes cross-language test case
msgpack_msgpack-ruby
train
5e1342bed85018dbd974f883b212a09a2fc89128
diff --git a/daemon/policy.go b/daemon/policy.go index <HASH>..<HASH> 100644 --- a/daemon/policy.go +++ b/daemon/policy.go @@ -252,6 +252,7 @@ func (d *Daemon) PolicyAdd(rules policyAPI.Rules, opts *AddOptions) (uint64, err // Only recompile if configuration has changed. log.Debug("CIDR policy has changed; recompiling base programs") if err := d.compileBase(); err != nil { + _ = d.prefixLengths.Delete(prefixes) metrics.PolicyImportErrors.Inc() err2 := fmt.Errorf("Unable to recompile base programs: %s", err) log.WithError(err2).WithField("prefixes", prefixes).Warn( @@ -261,6 +262,7 @@ func (d *Daemon) PolicyAdd(rules policyAPI.Rules, opts *AddOptions) (uint64, err } if err := ipcache.AllocateCIDRs(bpfIPCache.IPCache, prefixes); err != nil { + _ = d.prefixLengths.Delete(prefixes) metrics.PolicyImportErrors.Inc() log.WithError(err).WithField("prefixes", prefixes).Warn( "Failed to allocate identities for CIDRs during policy add") @@ -270,6 +272,7 @@ func (d *Daemon) PolicyAdd(rules policyAPI.Rules, opts *AddOptions) (uint64, err rev, err := d.policyAdd(rules, opts, prefixes) if err != nil { // Don't leak identities allocated above. + _ = d.prefixLengths.Delete(prefixes) if err2 := ipcache.ReleaseCIDRs(prefixes); err2 != nil { log.WithError(err2).WithField("prefixes", prefixes).Warn( "Failed to release CIDRs during policy import failure")
daemon: Fix prefix length tracking on policy failure In policy addition, one of the first functions adds references to the specified prefixes into the prefix length tracker. However, when the policy add fails it was not guaranteeing to release these references. Fix this up by adding a call to d.prefixLengths.Remove() in each of the error conditions. Fixes: #<I>
cilium_cilium
train
1fdd643cf6fb1b7fa5bfa6c93125106fb83a5296
diff --git a/immutablefield/admin.py b/immutablefield/admin.py index <HASH>..<HASH> 100644 --- a/immutablefield/admin.py +++ b/immutablefield/admin.py @@ -15,7 +15,7 @@ class ImmutableModelAdmin(admin.ModelAdmin): obj.save() def render_change_form(self, request, context, add=False, change=False, form_url='', obj=None): - if obj.is_signed_off(): + if not obj is None and obj.is_signed_off(): context['adminform'].form.fields['sign_off'].widget.attrs['disabled'] = True return super(ImmutableModelAdmin, self).render_change_form(
Correct render_change_form to adjust when adding a immutable object.
red56_django-immutablemodel
train
daa1bf0cc04d5963c4addc47609c3388ab85bcf5
diff --git a/src/index.js b/src/index.js index <HASH>..<HASH> 100644 --- a/src/index.js +++ b/src/index.js @@ -15,7 +15,7 @@ export const update = (intl) => { return updateIntl(intl) } -const initialState = { +export const initialState = { locale: 'en', messages: {}, }
Export initial state so it can be extended.
ratson_react-intl-redux
train
85709c45ed458dd1090f7837f76a868e62ba3461
diff --git a/setup.py b/setup.py index <HASH>..<HASH> 100644 --- a/setup.py +++ b/setup.py @@ -29,7 +29,7 @@ def create_command(text, commands): with open( - os.path.join(os.path.dirname(__file__), "README.rst"), encoding="utf-8" + os.path.join(os.path.dirname(__file__), "README.md"), encoding="utf-8" ) as readme: README = readme.read().split("h1>\n\n", 2)[1]
setup.py should read markdown README
SectorLabs_django-postgres-extra
train
84552cebbfd8f7e543bc9c751a24c4183763d24b
diff --git a/acos_client/client.py b/acos_client/client.py index <HASH>..<HASH> 100644 --- a/acos_client/client.py +++ b/acos_client/client.py @@ -41,6 +41,7 @@ from acos_client.v30.file import File as v30_File from acos_client.v30.ha import HA as v30_HA from acos_client.v30.interface import Interface as v30_Interface from acos_client.v30.license_manager import LicenseManager as v30_LicenseManager +from acos_client.v30.glm.flexpool import Flexpool as Flexpool from acos_client.v30.nat import Nat as v30_Nat from acos_client.v30.network import Network as v30_Network from acos_client.v30.overlay import Overlay as v30_Overlay @@ -85,7 +86,8 @@ VERSION_IMPORTS = { 'File': v30_File, 'Vlan': v30_Vlan, 'VRRPA': v30_VRRPA, - 'DeviceContext': v30_DeviceContext + 'DeviceContext': v30_DeviceContext, + 'Flexpool': Flexpool }, } @@ -168,7 +170,7 @@ class Client(object): if self._version != '30': LOG.error("AXAPIv21 is not supported for the glm attribute") return - return VERSION_IMPORTS['30']["GlobalLicenseManager"](self) + return VERSION_IMPORTS['30']["Flexpool"](self) @property def overlay(self): diff --git a/acos_client/v30/dns.py b/acos_client/v30/dns.py index <HASH>..<HASH> 100644 --- a/acos_client/v30/dns.py +++ b/acos_client/v30/dns.py @@ -55,5 +55,5 @@ class DNS(base.BaseV30): if secondary is not None: self._delete(self.url_prefix + 'secondary') - if summary is not None: + if suffix is not None: self._delete(self.url_prefix + 'suffix')
Adjusted naming of glm modules and subsequent imports
a10networks_acos-client
train
4be2e7d550493a3ca7518abdab88950e4016cf17
diff --git a/filterpy/kalman/SUKF.py b/filterpy/kalman/SUKF.py index <HASH>..<HASH> 100644 --- a/filterpy/kalman/SUKF.py +++ b/filterpy/kalman/SUKF.py @@ -173,7 +173,6 @@ class ScaledUnscentedKalmanFilter(object): # calculate sigma points for given mean and covariance sigmas = self.sigma_points(self.x, self.P, self.kappa) - for i in range(self._num_sigmas): self.sigmas_f[i] = self.fx(sigmas[i], self._dt) @@ -213,9 +212,13 @@ class ScaledUnscentedKalmanFilter(object): UT = unscented_transform # transform sigma points into measurement space + sigmas_h2 = self.hx(sigmas_f) + for i in range(self._num_sigmas): sigmas_h[i] = self.hx(sigmas_f[i]) + assert sigmas_h2.all() == sigmas_h.all() + # mean and covariance of prediction passed through UT zp, Pz = UT(sigmas_h, Wm, Wc, self.R) @@ -290,7 +293,7 @@ class ScaledUnscentedKalmanFilter(object): if np.isscalar(P): P = eye(n)*P - Sigmas = zeros((2*n+1, n)) # sigma points + sigmas = zeros((2*n+1, n)) # sigma points # efficient square root of matrix calculation. Implements # U'*U = lambda_*P. @@ -301,10 +304,10 @@ class ScaledUnscentedKalmanFilter(object): #U = sqrtm((lambda_)*P).T for k in range(n): - Sigmas[k+1] = x + U[k] - Sigmas[n+k+1] = x - U[k] + sigmas[k+1] = x + U[k] + sigmas[n+k+1] = x - U[k] # handle value for the mean separately as special case - Sigmas[0] = x + sigmas[0] = x - return Sigmas \ No newline at end of file + return sigmas diff --git a/filterpy/kalman/UKF.py b/filterpy/kalman/UKF.py index <HASH>..<HASH> 100644 --- a/filterpy/kalman/UKF.py +++ b/filterpy/kalman/UKF.py @@ -286,21 +286,42 @@ class UnscentedKalmanFilter(object): return sigmas -def unscented_transform(Sigmas, Wm, Wc, noise_cov): - """ Computes unscented transform of a set of sigma points and weights. - returns the mean and covariance in a tuple. +def unscented_transform(sigmas, Wm, Wc, noise_cov): + """ Computes the mean and covariance of a set of sigma points. + + + **Parameters** + + Sigmas : np.array((n, 2n+1) + sigma points + + Wm : np.array(2n+1) + weights for the means + + Wc : np.array(2n+1) + weights for the covariance + + noise_cov : np.array((n, n)) + covariance matrix of noise in system + + **Returns** + x : np.array(n) + mean of the sigma points + + P : np.array(n, n) + covariance of the sigma points """ - kmax, n = Sigmas.shape + kmax, n = sigmas.shape # new mean is just the sum of the sigmas * weight - x = dot(Wm, Sigmas) # dot = \Sigma^n_1 (W[k]*Xi[k]) + x = dot(Wm, sigmas) # dot = \Sigma^n_1 (W[k]*Xi[k]) # new covariance is the sum of the outer product of the residuals # times the weights P = zeros((n, n)) for k in range(kmax): - y = Sigmas[k] - x + y = sigmas[k] - x P += Wc[k] * np.outer(y, y) - return (x, P + noise_cov) \ No newline at end of file + return (x, P + noise_cov)
Better variable names, better docstrings.
rlabbe_filterpy
train
305e1288e64016fa71c15c9417c99873b34678a6
diff --git a/stricttuple/__init__.py b/stricttuple/__init__.py index <HASH>..<HASH> 100644 --- a/stricttuple/__init__.py +++ b/stricttuple/__init__.py @@ -2,7 +2,7 @@ # -*- coding: utf-8 -*- # @Author: codykochmann # @Date: 2017-04-06 13:35:45 -# @Last Modified time: 2017-09-27 09:18:23 +# @Last Modified time: 2017-09-27 09:28:45 from collections import namedtuple from inspect import getsource @@ -53,7 +53,10 @@ class namedtuple_converter(): table.valign='m' return table.get_string() except: - return namedtuple.__repr__(nt) + try: + return '{}({})'.format(type(nt).__name__,{f:getattr(nt,f) for f in nt._fields}) + except: + return tuple.__repr__(nt) @staticmethod def to_dict(nt): @@ -221,6 +224,20 @@ if __name__ == '__main__': print(t) + HardToPrint = stricttuple( + 'HardToPrint', + data=( + lambda data:type(data) == list, + lambda data:len(data) > 0 + ) + ) + + print(HardToPrint(data=[ + iter(range(1,10)), + iter(range(30,40)), + (i for i in range(60)) + ])) + Point = stricttuple( "Point", x = (
added a backup function for stricttuple.__repr__
CodyKochmann_stricttuple
train
71153d26d12d7d63357c298831a8c1e34b532b62
diff --git a/src/ol/expr/expressions.js b/src/ol/expr/expressions.js index <HASH>..<HASH> 100644 --- a/src/ol/expr/expressions.js +++ b/src/ol/expr/expressions.js @@ -175,39 +175,30 @@ ol.expr.Comparison.isValidOp = (function() { /** * @inheritDoc */ -ol.expr.Comparison.prototype.evaluate = function(opt_scope, opt_fns, - opt_this) { +ol.expr.Comparison.prototype.evaluate = function(opt_scope, opt_fns, opt_this) { var result; var rightVal = this.right_.evaluate(opt_scope, opt_fns, opt_this); var leftVal = this.left_.evaluate(opt_scope, opt_fns, opt_this); - switch (this.operator_) { - case ol.expr.ComparisonOp.EQ: - result = leftVal == rightVal; - break; - case ol.expr.ComparisonOp.NEQ: - result = leftVal != rightVal; - break; - case ol.expr.ComparisonOp.STRICT_EQ: - result = leftVal === rightVal; - break; - case ol.expr.ComparisonOp.STRICT_NEQ: - result = leftVal !== rightVal; - break; - case ol.expr.ComparisonOp.GT: - result = leftVal > rightVal; - break; - case ol.expr.ComparisonOp.LT: - result = leftVal < rightVal; - break; - case ol.expr.ComparisonOp.GTE: - result = leftVal >= rightVal; - break; - case ol.expr.ComparisonOp.LTE: - result = leftVal <= rightVal; - break; - default: - throw new Error('Unsupported comparison operator: ' + this.operator_); + var op = this.operator_; + if (op === ol.expr.ComparisonOp.EQ) { + result = leftVal == rightVal; + } else if (op === ol.expr.ComparisonOp.NEQ) { + result = leftVal != rightVal; + } else if (op === ol.expr.ComparisonOp.STRICT_EQ) { + result = leftVal === rightVal; + } else if (op === ol.expr.ComparisonOp.STRICT_NEQ) { + result = leftVal !== rightVal; + } else if (op === ol.expr.ComparisonOp.GT) { + result = leftVal > rightVal; + } else if (op === ol.expr.ComparisonOp.LT) { + result = leftVal < rightVal; + } else if (op === ol.expr.ComparisonOp.GTE) { + result = leftVal >= rightVal; + } else if (op === ol.expr.ComparisonOp.LTE) { + result = leftVal <= rightVal; + } else { + throw new Error('Unsupported comparison operator: ' + this.operator_); } return result; }; @@ -498,24 +489,19 @@ ol.expr.Math.prototype.evaluate = function(opt_scope, opt_fns, opt_this) { * math functions where available elsewhere */ - switch (this.operator_) { - case ol.expr.MathOp.ADD: - result = leftVal + rightVal; - break; - case ol.expr.MathOp.SUBTRACT: - result = Number(leftVal) - Number(rightVal); - break; - case ol.expr.MathOp.MULTIPLY: - result = Number(leftVal) * Number(rightVal); - break; - case ol.expr.MathOp.DIVIDE: - result = Number(leftVal) / Number(rightVal); - break; - case ol.expr.MathOp.MOD: - result = Number(leftVal) % Number(rightVal); - break; - default: - throw new Error('Unsupported math operator: ' + this.operator_); + var op = this.operator_; + if (op === ol.expr.MathOp.ADD) { + result = leftVal + rightVal; + } else if (op === ol.expr.MathOp.SUBTRACT) { + result = Number(leftVal) - Number(rightVal); + } else if (op === ol.expr.MathOp.MULTIPLY) { + result = Number(leftVal) * Number(rightVal); + } else if (op === ol.expr.MathOp.DIVIDE) { + result = Number(leftVal) / Number(rightVal); + } else if (op === ol.expr.MathOp.MOD) { + result = Number(leftVal) % Number(rightVal); + } else { + throw new Error('Unsupported math operator: ' + this.operator_); } return result; };
Prefer if/else to switch
openlayers_openlayers
train
2cec3cb3f2585f9595f4aeeb08b02e8856b68080
diff --git a/PROTOCOLS.md b/PROTOCOLS.md index <HASH>..<HASH> 100644 --- a/PROTOCOLS.md +++ b/PROTOCOLS.md @@ -167,12 +167,19 @@ ### 10. Send user dump { - "request" : 9, + "request" : 10, "data" : { "setting name" : "setting value" } } +### 11. Get current user dump + { + "request" : 11, + "data" : { + } + } + ### 112. Change name { "request" : 112, diff --git a/pychatjs/server/parser.py b/pychatjs/server/parser.py index <HASH>..<HASH> 100644 --- a/pychatjs/server/parser.py +++ b/pychatjs/server/parser.py @@ -80,7 +80,10 @@ class Parser(object): conn.write_message(create_user_dump(room.get_user(username))) break else: - conn.write_message(create_error(3, 'User not found in any active rooms')) + if username == conn.id.name: + conn.write_message(create_user_dump(conn.id)) + else: + conn.write_message(create_error(3, 'User not found in any active rooms')) elif request_name == 'get_users_dump': room = conn.get_room(data['room']) @@ -89,8 +92,7 @@ class Parser(object): conn.write_message(create_users_dump(room.get_users_connected)) elif request_name == 'send_dump': - for prop, value in data.iteritems(): - setattr(conn.id, prop, value) + conn.id._load_from_json(data) elif request_name == 'next_slide': room = conn.get_room(data['room']) diff --git a/pychatjs/server/user_server.py b/pychatjs/server/user_server.py index <HASH>..<HASH> 100644 --- a/pychatjs/server/user_server.py +++ b/pychatjs/server/user_server.py @@ -16,6 +16,10 @@ class User(object): def _to_json(self): """ Gets a dict of this object's properties so that it can be used to send a dump to the client """ return self.__dict__ + + def _load_from_json(self, properties): + for proper, value in properties.iteritems(): + setattr(self, proper, value) def release_name(self): """ release the username from the user server """ @@ -63,4 +67,4 @@ class UserServer(object): """ release a name and add it to the temp list """ self.temp_names.append(username) if self.is_username_used(username): - self.registered_names.remove(username) + self.registered_names.remove(username)
updated to make user dump/load work
eeue56_PyChat.js
train
78685d6b746e26df6e54add47405ce93710b99a1
diff --git a/hooks-admin.php b/hooks-admin.php index <HASH>..<HASH> 100644 --- a/hooks-admin.php +++ b/hooks-admin.php @@ -190,6 +190,7 @@ if ( $is_book ) { add_filter( 'wp_link_query_args', '\Pressbooks\Editor\customize_wp_link_query_args' ); add_filter( 'wp_link_query', '\Pressbooks\Editor\add_anchors_to_wp_link_query', 1, 2 ); add_action( 'edit_form_after_title', '\Pressbooks\Metadata\add_expanded_metadata_box' ); + add_action( 'add_meta_boxes', '\Pressbooks\Admin\Metaboxes\replace_authordiv' ); } // ------------------------------------------------------------------------------------------------------------------- diff --git a/inc/admin/metaboxes/namespace.php b/inc/admin/metaboxes/namespace.php index <HASH>..<HASH> 100644 --- a/inc/admin/metaboxes/namespace.php +++ b/inc/admin/metaboxes/namespace.php @@ -606,7 +606,7 @@ function add_meta_boxes() { x_add_metadata_field( 'pb_authors', 'front-matter', [ - 'group' => 'front-matter-metadata-metadata', + 'group' => 'front-matter-metadata', 'label' => __( 'Author(s)', 'pressbooks' ), 'field_type' => 'taxonomy_multi_select', 'taxonomy' => Contributors::TAXONOMY, @@ -649,7 +649,7 @@ function add_meta_boxes() { x_add_metadata_field( 'pb_authors', 'back-matter', [ - 'group' => 'back-matter-metadata-metadata', + 'group' => 'back-matter-metadata', 'label' => __( 'Author(s)', 'pressbooks' ), 'field_type' => 'taxonomy_multi_select', 'taxonomy' => Contributors::TAXONOMY, @@ -1144,3 +1144,21 @@ function save_contributor_meta( $term_id, $tt_id, $taxonomy ) { update_term_meta( $term_id, 'contributor_last_name', $new_last_name ); } } + +/** + * Distinguish between front matter/chapter/back matter authors and WP author + * + * @param string $post_type Post type. + */ +function replace_authordiv( $post_type ) { + // See: wp-admin/edit-form-advanced.php + $post_type_object = get_post_type_object( $post_type ); + if ( post_type_supports( $post_type, 'author' ) && current_user_can( $post_type_object->cap->edit_others_posts ) ) { + + remove_meta_box( 'authordiv', $post_type, 'normal' ); + remove_meta_box( 'authordiv', $post_type, 'side' ); + remove_meta_box( 'authordiv', $post_type, 'advanced' ); + + add_meta_box( 'authordiv', __( 'Owner', 'pressbooks' ), 'post_author_meta_box', $post_type ); + } +}
Distinguish PB authors from WP author (fixes #<I>) (#<I>)
pressbooks_pressbooks
train
d15a258aa1f8e506bb6f29e0cc7966fe825eb588
diff --git a/tt/riemannian/riemannian_test.py b/tt/riemannian/riemannian_test.py index <HASH>..<HASH> 100644 --- a/tt/riemannian/riemannian_test.py +++ b/tt/riemannian/riemannian_test.py @@ -4,7 +4,7 @@ import copy import numpy as np import tt from copy import deepcopy -import tt.riemannian +import riemannian class TestTTLearning(unittest.TestCase): @@ -15,9 +15,11 @@ class TestTTLearning(unittest.TestCase): np.random.seed(2) def test_projector_splitting_add(self): - Y = tt.rand([5, 2, 3], 3, [1, 2, 3, 1]) - my_res = riemannian.projector_splitting_add(Y.copy(), Y.copy(), debug=True) - np.testing.assert_array_almost_equal(2 * Y.full(), my_res.full()) + for debug_mode in [False, True]: + Y = tt.rand([5, 2, 3], 3, [1, 2, 3, 1]) + my_res = riemannian.projector_splitting_add(Y.copy(), Y.copy(), + debug=debug_mode) + np.testing.assert_array_almost_equal(2 * Y.full(), my_res.full()) def test_project(self): def random_tanget_space_point(X): @@ -25,35 +27,64 @@ class TestTTLearning(unittest.TestCase): point = 0 * tt.ones(X.n) for dim in range(X.d): curr = deepcopy(coresX) - curr[dim] = np.random.rand(curr[dim].shape[0], curr[dim].shape[1], curr[dim].shape[2]) + curr[dim] = np.random.rand(curr[dim].shape[0], + curr[dim].shape[1], + curr[dim].shape[2]) point += tt.tensor.from_list(curr) return point - X = tt.rand([4, 4, 4], 3, [1, 4, 4, 1]) - Z = random_tanget_space_point(X) - PZ = riemannian.project(X, Z, debug=True) - np.testing.assert_array_almost_equal(Z.full(), PZ.full()) - - X = tt.rand([2, 3, 4], 3, [1, 5, 4, 1]) - Z = random_tanget_space_point(X) - PZ = riemannian.project(X, Z, debug=True) - np.testing.assert_array_almost_equal(Z.full(), PZ.full()) - - def test_project_sum(self): - - X = tt.rand([4, 4, 4], 3, [1, 4, 4, 1]) - Z = [0] * 15 - Z[0] = tt.rand([4, 4, 4], 3, [1, 4, 4, 1]) - Z[1] = tt.rand([4, 4, 4], 3, [1, 4, 3, 1]) - Z[2] = tt.rand([4, 4, 4], 3, [1, 2, 3, 1]) - for idx in range(3, 15): - Z[idx] = tt.rand([4, 4, 4], 3, [1, 2, 2, 1]) - project_sum = riemannian.project(X, Z, debug=True) - - sum_project = X * 0 - for idx in range(len(Z)): - sum_project += riemannian.project(X, Z[idx], debug=True) - np.testing.assert_array_almost_equal(sum_project.full(), project_sum.full()) + for debug_mode in [False, True]: + for use_jit in [False, True]: + X = tt.rand([4, 4, 4], 3, [1, 4, 4, 1]) + Z = random_tanget_space_point(X) + PZ = riemannian.project(X, Z, use_jit=use_jit, + debug=debug_mode) + np.testing.assert_array_almost_equal(Z.full(), PZ.full()) + + X = tt.rand([2, 3, 4], 3, [1, 5, 4, 1]) + Z = random_tanget_space_point(X) + PZ = riemannian.project(X, Z, use_jit=use_jit, + debug=debug_mode) + np.testing.assert_array_almost_equal(Z.full(), PZ.full()) + + def test_project_sum_equal_ranks(self): + for debug_mode in [False, True]: + for use_jit in [False, True]: + X = tt.rand([4, 4, 4], 3, [1, 4, 4, 1]) + Z = [0] * 7 + for idx in range(7): + Z[idx] = tt.rand([4, 4, 4], 3, [1, 2, 3, 1]) + project_sum = riemannian.project(X, Z, use_jit=use_jit, + debug=debug_mode) + + sum_project = X * 0 + for idx in range(len(Z)): + sum_project += riemannian.project(X, Z[idx], + use_jit=use_jit, + debug=debug_mode) + np.testing.assert_array_almost_equal(sum_project.full(), + project_sum.full()) + + def test_project_sum_different_ranks(self): + for debug_mode in [False, True]: + for use_jit in [False, True]: + X = tt.rand([4, 4, 4], 3, [1, 4, 4, 1]) + Z = [0] * 7 + Z[0] = tt.rand([4, 4, 4], 3, [1, 4, 4, 1]) + Z[1] = tt.rand([4, 4, 4], 3, [1, 4, 3, 1]) + Z[2] = tt.rand([4, 4, 4], 3, [1, 2, 3, 1]) + for idx in range(3, 7): + Z[idx] = tt.rand([4, 4, 4], 3, [1, 2, 2, 1]) + project_sum = riemannian.project(X, Z, use_jit=use_jit, + debug=debug_mode) + + sum_project = X * 0 + for idx in range(len(Z)): + sum_project += riemannian.project(X, Z[idx], + use_jit=use_jit, + debug=debug_mode) + np.testing.assert_array_almost_equal(sum_project.full(), + project_sum.full()) if __name__ == '__main__': unittest.main()
Test jit and non-jit versions; debug and non-debug versions
oseledets_ttpy
train
ae5f866b37ba9903614965e0aef4366feabd32a6
diff --git a/karma.conf.js b/karma.conf.js index <HASH>..<HASH> 100644 --- a/karma.conf.js +++ b/karma.conf.js @@ -88,7 +88,7 @@ module.exports = function(config) { base: 'Safari' }, Chrome_Stable: { - base: 'Chrome' + base: 'ChromeHeadless' }, Firefox_Stable: { base: 'Firefox' @@ -99,7 +99,7 @@ module.exports = function(config) { const customLaunchers = ciLauncher ? {target_browser: ciLauncher} : { stable_chrome: { - base: 'Chrome' + base: 'ChromeHeadless' }, stable_firefox: { base: 'Firefox'
Migrate base Chrome profiles to ChromeHeadless (#<I>)
niklasvh_html2canvas
train
523f05b01ab4173e41dae76f013bb80a958168ac
diff --git a/src/Oci8/Oci8ServiceProvider.php b/src/Oci8/Oci8ServiceProvider.php index <HASH>..<HASH> 100644 --- a/src/Oci8/Oci8ServiceProvider.php +++ b/src/Oci8/Oci8ServiceProvider.php @@ -71,10 +71,10 @@ class Oci8ServiceProvider extends ServiceProvider $sessionVars = array_merge($sessionVars, $config['session']); } - if(isset($config['edition'])) { + if (isset($config['edition'])) { $sessionVars = array_merge( $sessionVars, - ["EDITION" => $config['edition']] + ['EDITION' => $config['edition']] ); }
Fixed some more PSR-4 bits highlighted
yajra_laravel-oci8
train
a1d60a685b715d978f7adb095932424733bb8a26
diff --git a/core/src/main/java/com/threerings/resource/ResourceManager.java b/core/src/main/java/com/threerings/resource/ResourceManager.java index <HASH>..<HASH> 100644 --- a/core/src/main/java/com/threerings/resource/ResourceManager.java +++ b/core/src/main/java/com/threerings/resource/ResourceManager.java @@ -407,8 +407,8 @@ public class ResourceManager if (_rdir == null) { return null; } - if (!"/".equals(File.separator)) { - path = path.replace("/", File.separator); + if ('/' != File.separatorChar) { + path = path.replace('/', File.separatorChar); } // first try a locale-specific file String localePath = getLocalePath(path);
Use File.separatorChar where it makes sense.
threerings_nenya
train
01ebbcee243a58db6a1f1e4dd700f86a87c94b7e
diff --git a/src/findBin.js b/src/findBin.js index <HASH>..<HASH> 100644 --- a/src/findBin.js +++ b/src/findBin.js @@ -7,7 +7,7 @@ module.exports = function findBin (binName, paths, config, cb) { * If package.json has script with binName defined * we want it to be executed first */ - if (config.scripts[binName] !== undefined) { + if (config.scripts && config.scripts[binName] !== undefined) { // Support for scripts from package.json cb.call(this, null, binPath, args) } else { diff --git a/test/findBin.spec.js b/test/findBin.spec.js index <HASH>..<HASH> 100644 --- a/test/findBin.spec.js +++ b/test/findBin.spec.js @@ -43,6 +43,16 @@ describe('findBin', () => { }) }) + it('should return bin from node_modules/.bin on missed scripts in package.json', done => { + findBin.__set__('npmWhich', npmWichMockGood) + findBin('eslint', 'test.js test2.js', { }, (err, bin, args) => { + expect(err).toBe(null) + expect(bin).toEqual('eslint') + expect(args).toEqual(['--', 'test.js test2.js']) + done() + }) + }) + it('should return error if bin not found and there is no entry in scripts section', () => { findBin.__set__('npmWhich', npmWichMockBad) expect(() => {
Work with no scripts in package.json
okonet_lint-staged
train
f909bb29249c5682bfccf829c9d7f84dd0dd9c56
diff --git a/python_modules/dagster/dagster/core/definitions/events.py b/python_modules/dagster/dagster/core/definitions/events.py index <HASH>..<HASH> 100644 --- a/python_modules/dagster/dagster/core/definitions/events.py +++ b/python_modules/dagster/dagster/core/definitions/events.py @@ -149,19 +149,19 @@ class Output( ], ) ): - """Event corresponding to one of a solid's outputs. + """Event corresponding to one of a op's outputs. - Solid compute functions must explicitly yield events of this type when they have more than - one output, or when they also yield events of other types, or when defining a solid using the - :py:class:`SolidDefinition` API directly. + Op compute functions must explicitly yield events of this type when they have more than + one output, or when they also yield events of other types, or when defining a op using the + :py:class:`OpDefinition` API directly. - Outputs are values produced by solids that will be consumed by downstream solids in a pipeline. - They are type-checked at solid boundaries when their corresponding :py:class:`OutputDefinition` - or the downstream :py:class:`InputDefinition` is typed. + Outputs are values produced by ops that will be consumed by downstream ops in a job. + They are type-checked at op boundaries when their corresponding :py:class:`Out` + or the downstream :py:class:`In` is typed. Args: value (Any): The value returned by the compute function. - output_name (Optional[str]): Name of the corresponding output definition. (default: + output_name (Optional[str]): Name of the corresponding out. (default: "result") metadata_entries (Optional[Union[EventMetadataEntry, PartitionMetadataEntry]]): (Experimental) A set of metadata entries to attach to events related to this Output. @@ -211,7 +211,7 @@ class DynamicOutput( ): """ (Experimental) Variant of :py:class:`Output <dagster.Output>` used to support - dynamic mapping & collect. Each ``DynamicOutput`` produced by a solid represents + dynamic mapping & collect. Each ``DynamicOutput`` produced by an op represents one item in a set that can be processed individually with ``map`` or gathered with ``collect``. @@ -222,10 +222,10 @@ class DynamicOutput( The value returned by the compute function. mapping_key (str): The key that uniquely identifies this dynamic value relative to its peers. - This key will be used to identify the downstream solids when mapped, ie - ``mapped_solid[example_mapping_key]`` + This key will be used to identify the downstream ops when mapped, ie + ``mapped_op[example_mapping_key]`` output_name (Optional[str]): - Name of the corresponding :py:class:`DynamicOutputDefinition` defined on the solid. + Name of the corresponding :py:class:`DynamicOut` defined on the op. (default: "result") metadata_entries (Optional[Union[EventMetadataEntry, PartitionMetadataEntry]]): (Experimental) A set of metadata entries to attach to events related to this output. @@ -392,12 +392,12 @@ class Materialization( ], ) ): - """Event indicating that a solid has materialized a value. + """Event indicating that an op has materialized a value. Solid compute functions may yield events of this type whenever they wish to indicate to the Dagster framework (and the end user) that they have produced a materialized value as a - side effect of computation. Unlike outputs, materializations can not be passed to other solids, - and their persistence is controlled by solid logic, rather than by the Dagster framework. + side effect of computation. Unlike outputs, materializations can not be passed to other ops, + and their persistence is controlled by op logic, rather than by the Dagster framework. Solid authors should use these events to organize metadata about the side effects of their computations to enable downstream tooling like artifact catalogues and diff tools. @@ -408,7 +408,7 @@ class Materialization( metadata_entries (Optional[List[EventMetadataEntry]]): Arbitrary metadata about the materialized value. asset_key (Optional[Union[str, AssetKey]]): An optional parameter to identify the materialized asset - across pipeline runs + across runs partition (Optional[str]): The name of the partition that was materialized. tags (Optional[Dict[str, str]]): (Experimental) Tag metadata for a given asset materialization. Used for search and organization of the asset entry in the asset @@ -492,7 +492,7 @@ class ExpectationResult( ): """Event corresponding to a data quality test. - Solid compute functions may yield events of this type whenever they wish to indicate to the + Op compute functions may yield events of this type whenever they wish to indicate to the Dagster framework (and the end user) that a data quality test has produced a (positive or negative) result. @@ -587,9 +587,9 @@ class TypeCheck( class Failure(Exception): - """Event indicating solid failure. + """Event indicating op failure. - Raise events of this type from within solid compute functions or custom type checks in order to + Raise events of this type from within op compute functions or custom type checks in order to indicate an unrecoverable failure in user code to the Dagster machinery and return structured metadata about the failure. @@ -621,7 +621,7 @@ class Failure(Exception): class RetryRequested(Exception): """ - An exception to raise from a solid to indicate that it should be retried. + An exception to raise from an op to indicate that it should be retried. Args: max_retries (Optional[int]): @@ -634,7 +634,7 @@ class RetryRequested(Exception): .. code-block:: python - @solid + @op def flakes(): try: flakey_operation()
Migrate user-facing event docstrings to crag (#<I>)
dagster-io_dagster
train
632eecd1715be2ab98455dcb4a0598ae402fd425
diff --git a/analysis.go b/analysis.go index <HASH>..<HASH> 100644 --- a/analysis.go +++ b/analysis.go @@ -11,6 +11,7 @@ import ( "sort" "strconv" "strings" + "syscall" "unicode" ) @@ -80,6 +81,7 @@ func ListPackages(fileRoot, importRoot string) (PackageTree, error) { if err != nil { return PackageTree{}, err } + err = filepath.Walk(fileRoot, func(wp string, fi os.FileInfo, err error) error { if err != nil && err != filepath.SkipDir { return err @@ -103,6 +105,24 @@ func ListPackages(fileRoot, importRoot string) (PackageTree, error) { return filepath.SkipDir } + // The entry error is nil when visiting a directory that itself is + // untraversable, as it's still governed by the parent directory's + // perms. We have to check readability of the dir here, because + // otherwise we'll have an empty package entry when we fail to read any + // of the dir's contents. + // + // If we didn't check here, then the next time this closure is called it + // would have an err with the same path as is called this time, as only + // then will filepath.Walk have attempted to descend into the directory + // and encountered an error. + _, err = os.Open(wp) + if err != nil { + if terr, ok := err.(*os.PathError); ok && terr.Err == syscall.Errno(syscall.EACCES) { + return filepath.SkipDir + } + return err + } + // Compute the import path. Run the result through ToSlash(), so that windows // paths are normalized to Unix separators, as import paths are expected // to be. @@ -203,6 +223,9 @@ func fillPackage(p *build.Package) error { for _, file := range gofiles { pf, err := parser.ParseFile(token.NewFileSet(), file, nil, parser.ImportsOnly|parser.ParseComments) if err != nil { + if terr, ok := err.(*os.PathError); ok && terr.Err == syscall.Errno(syscall.EACCES) { + continue + } return err } testFile := strings.HasSuffix(file, "_test.go") diff --git a/analysis_test.go b/analysis_test.go index <HASH>..<HASH> 100644 --- a/analysis_test.go +++ b/analysis_test.go @@ -994,17 +994,6 @@ func TestListPackagesNoPerms(t *testing.T) { }, }, }, - "ren/simple": { - P: Package{ - ImportPath: "ren/simple", - CommentPath: "", - Name: "simple", - Imports: []string{ - "github.com/sdboyer/gps", - "sort", - }, - }, - }, }, }
Implement handling for perms errs in ListPackages
sdboyer_gps
train
4ce5e527f43bac165e91ddd6c6030785c32f65bf
diff --git a/pyOCD/interface/pyusb_backend.py b/pyOCD/interface/pyusb_backend.py index <HASH>..<HASH> 100644 --- a/pyOCD/interface/pyusb_backend.py +++ b/pyOCD/interface/pyusb_backend.py @@ -104,7 +104,8 @@ class PyUSB(Interface): ) product_name = usb.util.get_string(board, 256, 2) vendor_name = usb.util.get_string(board, 256, 1) - if ep_out is None or ep_in is None: + """If there is no EP for OUT then we can use CTRL EP""" + if ep_in is None: #ep_out is None or logging.error('Endpoints not found') return None @@ -125,7 +126,9 @@ class PyUSB(Interface): write data on the OUT endpoint associated to the HID interface """ if self.ep_out is None: - raise ValueError('EP_OUT endpoint is NULL') + self.dev.ctrl_transfer(0x21,0x9,0x200,0x3,data) + return + #raise ValueError('EP_OUT endpoint is NULL') self.ep_out.write(data) #logging.debug('sent: %s', data)
Pyusb backend fix for using EP0 Instead of raising an exception when no OUT EP is present, the pyusb_backend will use the control endpoint for HID OUT transfers. Tested withNRF mkit.
mbedmicro_pyOCD
train
86c92146a48e4bbdf9a30961d1a4d3c82463b003
diff --git a/src/Arrayy.php b/src/Arrayy.php index <HASH>..<HASH> 100644 --- a/src/Arrayy.php +++ b/src/Arrayy.php @@ -523,7 +523,7 @@ class Arrayy extends CollectionMethods implements \Countable, \IteratorAggregate } /** - * Get the last elements from index $from. + * Get the last elements from index $from until the end of this array. * * @param int $from *
[*]: only code-comment
voku_Arrayy
train
d1e0bc7c17b1be2766e9fca228b4c61e01988b34
diff --git a/railties/lib/rails/generators.rb b/railties/lib/rails/generators.rb index <HASH>..<HASH> 100644 --- a/railties/lib/rails/generators.rb +++ b/railties/lib/rails/generators.rb @@ -218,6 +218,7 @@ module Rails rails.delete("app") rails.delete("plugin") rails.delete("encrypted_secrets") + rails.delete("credentials") hidden_namespaces.each { |n| groups.delete(n.to_s) } diff --git a/railties/test/application/generators_test.rb b/railties/test/application/generators_test.rb index <HASH>..<HASH> 100644 --- a/railties/test/application/generators_test.rb +++ b/railties/test/application/generators_test.rb @@ -188,10 +188,11 @@ module ApplicationTests Rails::Command.send(:remove_const, "APP_PATH") end - test "help does not show hidden namespaces" do + test "help does not show hidden namespaces and hidden commands" do FileUtils.cd(rails_root) do output = rails("generate", "--help") assert_no_match "active_record:migration", output + assert_no_match "credentials", output output = rails("destroy", "--help") assert_no_match "active_record:migration", output
Do not show credentials in generators help Since credentials generator is executed via the credentials command and does not need to be executed directly, so it is not necessary to show it in help.
rails_rails
train
a2be0a94dc8e4b3f3a659ecb7fcaf319d5c39e0e
diff --git a/exercises/am_i_ready/exercise.js b/exercises/am_i_ready/exercise.js index <HASH>..<HASH> 100644 --- a/exercises/am_i_ready/exercise.js +++ b/exercises/am_i_ready/exercise.js @@ -131,7 +131,7 @@ function checkGcc (pass, callback) { + chalk.bold('v' + MIN_GCC_VERSION) ) } - } else if (versionMatch = stderr.toString().match(/Apple LLVM version (\d+\.\d+) /)) { + } else if (versionMatch = stderr.toString().match(/Apple LLVM version (\d+\.\d+)/)) { versionString = versionMatch && versionMatch[1] + '.0' if (!semver.satisfies(versionString, '>=' + MIN_LLVM_VERSION)) {
Remove a space in the Apple LLVM check
workshopper_goingnative
train
7cc0da2bc72b739881e3fdc21b5e13fa14ab52ab
diff --git a/setup.py b/setup.py index <HASH>..<HASH> 100644 --- a/setup.py +++ b/setup.py @@ -18,11 +18,16 @@ class RunTests(Command): raise SystemExit(errno) +with open('README.md') as readme: + long_description = readme.read() + + setup( name='parserutils', description='A collection of performant parsing utilities', + long_description=long_description, keywords='parser,parsing,utils,utilities,collections,dates,elements,numbers,strings,url,xml', - version='1.1', + version='1.1.1', packages=[ 'parserutils', 'parserutils.tests' ],
Add README as long_description
consbio_parserutils
train
f591c247cadb090b294bfbba4489ea3f740a4e6c
diff --git a/repository/boxnet/locallib.php b/repository/boxnet/locallib.php index <HASH>..<HASH> 100644 --- a/repository/boxnet/locallib.php +++ b/repository/boxnet/locallib.php @@ -116,6 +116,8 @@ function repository_boxnet_migrate_references_from_apiv1() { continue; } + mtrace('Starting migration of file reference ' . $file->get_referencefileid()); + // Manually import the file to the file pool to prevent timeout limitations of the repository method get_file(). // We ignore the fact that the content of the file could exist locally because we want to synchronize the file // now to prevent the repository to try to download the file as well. diff --git a/repository/boxnet/migrationv1.php b/repository/boxnet/migrationv1.php index <HASH>..<HASH> 100644 --- a/repository/boxnet/migrationv1.php +++ b/repository/boxnet/migrationv1.php @@ -31,6 +31,8 @@ * @todo Deprecate/remove this tool after the 14th of December 2013. */ +define('NO_OUTPUT_BUFFERING', true); + require_once(__DIR__ . '/../../config.php'); require_once($CFG->libdir . '/adminlib.php'); require_once($CFG->dirroot . '/repository/boxnet/locallib.php'); @@ -40,7 +42,7 @@ require_capability('moodle/site:config', context_system::instance()); $title = get_string('migrationtool', 'repository_boxnet'); $PAGE->set_context(context_system::instance()); -$PAGE->set_pagelayout('admin'); +$PAGE->set_pagelayout('maintenance'); $PAGE->set_title($title); $PAGE->set_heading($title); $PAGE->set_url(new moodle_url('/repository/boxnet/migrationv1.php'));
MDL-<I> repository_boxnet: Improved output during migration
moodle_moodle
train
f997e9749477df12cb8f3473614dcaf74690798a
diff --git a/pyrogram/client/client.py b/pyrogram/client/client.py index <HASH>..<HASH> 100644 --- a/pyrogram/client/client.py +++ b/pyrogram/client/client.py @@ -337,13 +337,17 @@ class Client: size=document.size, progress=progress ) - elif isinstance(media, types.MessageMediaPhoto): - photo = media.photo + elif isinstance(media, (types.MessageMediaPhoto, types.Photo)): + if isinstance(media, types.MessageMediaPhoto): + photo = media.photo + else: + photo = media if isinstance(photo, types.Photo): if not file_name: - file_name = "photo_{}.jpg".format( - datetime.fromtimestamp(photo.date).strftime("%Y-%m-%d_%H-%M-%S") + file_name = "photo_{}_{}.jpg".format( + datetime.fromtimestamp(photo.date).strftime("%Y-%m-%d_%H-%M-%S"), + self.rnd_id() ) photo_loc = photo.sizes[-1].location @@ -2587,11 +2591,15 @@ class Client: Raises: :class:`pyrogram.Error` """ - if isinstance(message, types.Message): + if isinstance(message, (types.Message, types.Photo)): done = Event() - media = message.media path = [None] + if isinstance(message, types.Message): + media = message.media + else: + media = message + if media is not None: self.download_queue.put((media, file_name, done, progress, path)) else: @@ -2602,6 +2610,48 @@ class Client: return path[0] + def download_photo(self, + photo: types.Photo or types.UserProfilePhoto or types.ChatPhoto, + file_name: str = None, + block: bool = True): + """Use this method to download a photo not contained inside a Message. + For example, a photo of a User or a Chat/Channel. + + Photos are saved in the *downloads* folder. + + Args: + photo (:obj:`Photo <pyrogram.api.types.Photo>` | :obj:`UserProfilePhoto <pyrogram.api.types.UserProfilePhoto>` | :obj:`ChatPhoto <pyrogram.api.types.ChatPhoto>`): + The photo object. + + file_name (:obj:`str`, optional): + Specify a custom *file_name* to be used. + + block (:obj:`bool`, optional): + Blocks the code execution until the photo has been downloaded. + Defaults to True. + + Returns: + The relative path of the downloaded photo. + + Raises: + :class:`pyrogram.Error` + """ + if isinstance(photo, (types.UserProfilePhoto, types.ChatPhoto)): + photo = types.Photo( + id=0, + access_hash=0, + date=int(time.time()), + sizes=[types.PhotoSize( + type="", + location=photo.photo_big, + w=0, + h=0, + size=0 + )] + ) + + return self.download_media(photo, file_name, block) + def add_contacts(self, contacts: list): """Use this method to add contacts to your Telegram address book.
Add support for downloading photos not contained inside a Message
pyrogram_pyrogram
train
1146b551f4fa0939da955bc239b8cb107120d08d
diff --git a/spyderlib/plugins/ipythonconsole.py b/spyderlib/plugins/ipythonconsole.py index <HASH>..<HASH> 100644 --- a/spyderlib/plugins/ipythonconsole.py +++ b/spyderlib/plugins/ipythonconsole.py @@ -68,10 +68,9 @@ class IPythonConsoleConfigPage(PluginConfigPage): class IPythonClient(QWidget): """Find in files DockWidget""" CONF_SECTION = 'ipython' - def __init__(self, parent, connection_file, kernel_widget_id, client_name, + def __init__(self, plugin, connection_file, kernel_widget_id, client_name, ipython_widget): - super(IPythonClient, self).__init__(parent) - + super(IPythonClient, self).__init__(plugin) self.options_button = None self.connection_file = connection_file @@ -84,6 +83,9 @@ class IPythonClient(QWidget): layout.addWidget(self.ipython_widget) self.setLayout(layout) + exit_callback = lambda widget=self: plugin.close_console(widget=self) + set_ipython_exit_callback(self.ipython_widget, exit_callback) + #------ Public API -------------------------------------------------------- def get_name(self): """Return client name""" @@ -92,10 +94,6 @@ class IPythonClient(QWidget): def get_control(self): """Return the QPlainTextEdit widget (or similar) to give focus to""" return self.ipython_widget._control - - def set_exit_callback(self, exit_callback): - """Set IPython widget exit callback""" - set_ipython_exit_callback(self.ipython_widget, exit_callback) def get_options_menu(self): """Return options menu""" @@ -297,9 +295,6 @@ class IPythonConsole(SpyderPluginWidget): shellwidget = IPythonClient(self, connection_file, kernel_widget_id, client_name, ipython_widget) - exit_callback = lambda widget=shellwidget:\ - self.close_console(widget=shellwidget) - shellwidget.set_exit_callback(exit_callback) # Apply settings to newly created client widget: shellwidget.set_font( self.get_plugin_font() )
IPython console/client: clarified the 'set_exit_callback' mechanism
spyder-ide_spyder
train
99f6c7ebba44e24bbeb9fb5d88f586bd3214945e
diff --git a/betfairlightweight/streaming/listener.py b/betfairlightweight/streaming/listener.py index <HASH>..<HASH> 100644 --- a/betfairlightweight/streaming/listener.py +++ b/betfairlightweight/streaming/listener.py @@ -18,6 +18,7 @@ class BaseListener: self.stream_unique_id = None def register_stream(self, unique_id: int, operation: str) -> None: + logger.info("Register: %s %s" % (operation, unique_id)) if self.stream is not None: logger.warning( "[Listener: %s]: stream already registered, replacing data" % unique_id @@ -56,8 +57,11 @@ class BaseListener: if self.stream is not None: return self.stream._clk - def _add_stream(self, unique_id: int, operation: str) -> None: - logger.info("Register: %s %s" % (operation, unique_id)) + def _add_stream(self, unique_id: int, operation: str) -> BaseStream: + if operation == "marketSubscription": + return MarketStream(self) + elif operation == "orderSubscription": + return OrderStream(self) def __str__(self) -> str: return "{0}".format(self.__class__.__name__) @@ -156,12 +160,6 @@ class StreamListener(BaseListener): elif change_type == "UPDATE": self.stream.on_update(data) - def _add_stream(self, unique_id: int, stream_type: str) -> BaseStream: - if stream_type == "marketSubscription": - return MarketStream(self) - elif stream_type == "orderSubscription": - return OrderStream(self) - @staticmethod def _error_handler(data: dict, unique_id: int) -> Optional[bool]: """Called when data first received diff --git a/tests/unit/test_listener.py b/tests/unit/test_listener.py index <HASH>..<HASH> 100644 --- a/tests/unit/test_listener.py +++ b/tests/unit/test_listener.py @@ -44,8 +44,16 @@ class BaseListenerTest(unittest.TestCase): def test_on_data(self): self.base_listener.on_data({}) - def test_add_stream(self): - self.base_listener._add_stream(1, "operation") + @mock.patch("betfairlightweight.streaming.listener.OrderStream", return_value=456) + @mock.patch("betfairlightweight.streaming.listener.MarketStream", return_value=123) + def test_add_stream(self, mock_market_stream, mock_order_stream): + new_stream = self.base_listener._add_stream(1, "marketSubscription") + assert new_stream == 123 + mock_market_stream.assert_called_with(self.base_listener) + + new_stream = self.base_listener._add_stream(1, "orderSubscription") + assert new_stream == 456 + mock_order_stream.assert_called_with(self.base_listener) def test_snap(self): mock_stream = mock.Mock() @@ -175,17 +183,6 @@ class StreamListenerTest(unittest.TestCase): self.stream_listener._on_change_message(mock_response.json(), 1) stream.on_subscribe.assert_called_with(mock_response.json()) - @mock.patch("betfairlightweight.streaming.listener.OrderStream", return_value=456) - @mock.patch("betfairlightweight.streaming.listener.MarketStream", return_value=123) - def test_add_stream(self, mock_market_stream, mock_order_stream): - new_stream = self.stream_listener._add_stream(1, "marketSubscription") - assert new_stream == 123 - mock_market_stream.assert_called_with(self.stream_listener) - - new_stream = self.stream_listener._add_stream(1, "orderSubscription") - assert new_stream == 456 - mock_order_stream.assert_called_with(self.stream_listener) - def test_error_handler(self): mock_response = create_mock_json("tests/resources/streaming_connection.json") self.stream_listener._error_handler(mock_response.json(), 1)
add_stream moved to baselistener so it is consistent
liampauling_betfair
train
b6f3a85301d9cf364f53cf80a5f8f288ef73f701
diff --git a/cbpro/authenticated_client.py b/cbpro/authenticated_client.py index <HASH>..<HASH> 100644 --- a/cbpro/authenticated_client.py +++ b/cbpro/authenticated_client.py @@ -995,3 +995,16 @@ class AuthenticatedClient(PublicClient): """ return self._send_message('get', '/users/self/trailing-volume') + + def get_fees(self): + """ Get your maker & taker fee rates and 30-day trailing volume. + + Returns: + dict: Fee information and USD volume:: + { + "maker_fee_rate": "0.0015", + "taker_fee_rate": "0.0025", + "usd_volume": "25000.00" + } + """ + return self._send_message('get', '/fees') diff --git a/tests/test_authenticated_client.py b/tests/test_authenticated_client.py index <HASH>..<HASH> 100644 --- a/tests/test_authenticated_client.py +++ b/tests/test_authenticated_client.py @@ -186,3 +186,7 @@ class TestAuthenticatedClient(object): def test_get_trailing_volume(self, client): r = client.get_trailing_volume() assert type(r) is list + + def test_get_fees(self, client): + r = client.get_fees() + assert type(r) is dict
Add authenticated client get_fees method and test (#<I>) * Add authenticated client get_fees method This adds the ability to get your: * current maker & taker fee rates * <I>-day trailing volume See: <URL>
danpaquin_coinbasepro-python
train
c57e940eca5813c6de21646885692d1d6aa0c4f0
diff --git a/setup.py b/setup.py index <HASH>..<HASH> 100755 --- a/setup.py +++ b/setup.py @@ -18,7 +18,7 @@ setup( url='https://github.com/takeflight/wagtail-metadata', install_requires=[ - 'wagtail>=1.12', + 'wagtail>=1.12,<=1.9999', ], zip_safe=False, license='BSD License',
Restrict Wagtail version to < <I>
neon-jungle_wagtail-metadata
train
3a3b56de8b7ef1f7d5ccde34f6692cb6964481c6
diff --git a/artifactory.py b/artifactory.py index <HASH>..<HASH> 100755 --- a/artifactory.py +++ b/artifactory.py @@ -702,6 +702,16 @@ class ArtifactoryPath(pathlib.Path, PureArtifactoryPath): obj.auth = self.auth return obj + def __iter__(self): + """Iterate over the files in this directory. Does not yield any + result for the special paths '.' and '..'. + """ + for name in self._accessor.listdir(self): + if name in {'.', '..'}: + # Yielding a path object for these makes little sense + continue + yield self._make_child_relpath(name) + def open(self, mode='r', buffering=-1, encoding=None, errors=None, newline=None): """
Make ArtifactoryPath iterable Add __iter__ method to ArtifactoryPath. Solves #6
Parallels_artifactory
train
f8e65510e09ace2a74bc07253df52a7a41f18aa0
diff --git a/spec/c_zookeeper_spec.rb b/spec/c_zookeeper_spec.rb index <HASH>..<HASH> 100644 --- a/spec/c_zookeeper_spec.rb +++ b/spec/c_zookeeper_spec.rb @@ -16,27 +16,33 @@ if Module.const_defined?(:CZookeeper) wait_until(timeout) { @czk.state == ZookeeperConstants::ZOO_CONNECTED_STATE } end - before do - @event_queue = ZookeeperCommon::QueueWithPipe.new - @czk = CZookeeper.new('localhost:2181', @event_queue) - end - - after do - @czk.close rescue Exception - @event_queue.close rescue Exception - end + describe do + before do + @event_queue = ZookeeperCommon::QueueWithPipe.new + @czk = CZookeeper.new('localhost:2181', @event_queue) + end - it %[should be in connected state within a reasonable amount of time] do - wait_until_connected.should be_true - end + after do + @czk.close rescue Exception + @event_queue.close rescue Exception + end - describe :after_connected do - before do + it %[should be in connected state within a reasonable amount of time] do wait_until_connected.should be_true end - it %[should have a connection event after being connected] do + describe :after_connected do + before do + wait_until_connected.should be_true + end + it %[should have a connection event after being connected] do + event = wait_until(2) { @event_queue.pop } + event.should be + event[:req_id].should == ZookeeperCommon::ZKRB_GLOBAL_CB_REQ + event[:type].should == ZookeeperConstants::ZOO_SESSION_EVENT + event[:state].should == ZookeeperConstants::ZOO_CONNECTED_STATE + end end end end
check for our connection event after zkc_state says we're connected
zk-ruby_zookeeper
train
246ab9b78f57cb3093631738517c59b491510f67
diff --git a/lib/graph_matching/matching.rb b/lib/graph_matching/matching.rb index <HASH>..<HASH> 100644 --- a/lib/graph_matching/matching.rb +++ b/lib/graph_matching/matching.rb @@ -41,7 +41,7 @@ module GraphMatching augmenting_path_edges = ap.edges raise "invalid augmenting path: must have odd length" unless augmenting_path_edges.length.odd? ap.vertexes.each do |v| - w = match(v) + w = @ary[v] delete([v, w]) unless w.nil? end augmenting_path_edges.each_with_index do |edge, ix| @@ -79,12 +79,6 @@ module GraphMatching @ary.include?(v) end - # `match` returns the matched vertex (across the edge) or - # nil if `v` is not matched - def match(v) - @ary[v] - end - def inspect to_s end diff --git a/spec/graph_matching/matching_spec.rb b/spec/graph_matching/matching_spec.rb index <HASH>..<HASH> 100644 --- a/spec/graph_matching/matching_spec.rb +++ b/spec/graph_matching/matching_spec.rb @@ -70,15 +70,6 @@ RSpec.describe GraphMatching::Matching do end end - describe '#match' do - it 'returns the matched vertex (across the edge) or nil if not matched' do - m = described_class.new - expect(m.match(1)).to be_nil - m.add([1,2]) - expect(m.match(1)).to eq(2) - end - end - describe '#to_a' do it 'returns edges' do edges = [[1,2], [3,4]]
Optimize #augment by removing #match
jaredbeck_graph_matching
train
47523f248892faf2611b14f07612fee37f3b4353
diff --git a/modules/tools-json/src/main/java/com/wizzardo/tools/json/Binder.java b/modules/tools-json/src/main/java/com/wizzardo/tools/json/Binder.java index <HASH>..<HASH> 100644 --- a/modules/tools-json/src/main/java/com/wizzardo/tools/json/Binder.java +++ b/modules/tools-json/src/main/java/com/wizzardo/tools/json/Binder.java @@ -356,6 +356,12 @@ class Binder { sb.append('}'); } }; + private static Serializer genericSerializer = new Serializer(SerializerType.OBJECT) { + @Override + public void serialize(Object src, Appender sb, Generic generic) { + classToSerializer(src.getClass()).serialize(src, sb, null); + } + }; private static Serializer simpleBoxedSerializer = new ArrayBoxedSerializer(simpleSerializer); private static Serializer stringArraySerializer = new ArrayBoxedSerializer(stringSerializer); private static Serializer charArraySerializer = new ArrayBoxedSerializer(characterSerializer); @@ -412,7 +418,10 @@ class Binder { ) { // System.out.println("add field " + field); field.setAccessible(true); - fields.put(field.getName(), new FieldInfo(field, getReturnType(field))); + if (!field.getGenericType().getTypeName().equals(field.getType().getCanonicalName())) + fields.put(field.getName(), new FieldInfo(field, genericSerializer)); + else + fields.put(field.getName(), new FieldInfo(field, getReturnType(field))); } } cl = cl.getSuperclass(); diff --git a/src/test/java/com/wizzardo/tools/json/JsonParseBytesTest.java b/src/test/java/com/wizzardo/tools/json/JsonParseBytesTest.java index <HASH>..<HASH> 100644 --- a/src/test/java/com/wizzardo/tools/json/JsonParseBytesTest.java +++ b/src/test/java/com/wizzardo/tools/json/JsonParseBytesTest.java @@ -376,4 +376,15 @@ public class JsonParseBytesTest { } } } + +// public void test_json_1() throws UnsupportedEncodingException { +// byte[] data = "{\"key\":\"value\"}".getBytes("utf-8"); +// +// JsonBinder binder = new JsonObjectBinder(); +// JsonObject.parse(data, 0, data.length, binder); +// } + + @Test + public void test_parseKey_1() { + } } diff --git a/src/test/java/com/wizzardo/tools/json/JsonTest.java b/src/test/java/com/wizzardo/tools/json/JsonTest.java index <HASH>..<HASH> 100644 --- a/src/test/java/com/wizzardo/tools/json/JsonTest.java +++ b/src/test/java/com/wizzardo/tools/json/JsonTest.java @@ -1487,4 +1487,15 @@ public class JsonTest { } assert exception; } + + static class GenericHolder<T> { + T value; + } + + @Test + public void test_serialize_generic() { + GenericHolder<String> holder = new GenericHolder<String>(); + holder.value = "value"; + Assert.assertEquals("{\"value\":\"value\"}", JsonTools.serialize(holder)); + } }
resolve serializer every time for generics
wizzardo_tools
train
e403ea9daa8d9bde98c542d1f77bbef5848804bd
diff --git a/webpack/ForemanTasks/Components/TasksTable/TasksTableSelectors.js b/webpack/ForemanTasks/Components/TasksTable/TasksTableSelectors.js index <HASH>..<HASH> 100644 --- a/webpack/ForemanTasks/Components/TasksTable/TasksTableSelectors.js +++ b/webpack/ForemanTasks/Components/TasksTable/TasksTableSelectors.js @@ -32,7 +32,9 @@ export const selectResults = createSelector( ({ results }) => results.map(result => ({ ...result, - action: result.action || result.label.replace(/::/g, ' '), + action: + result.action || + (result.label ? result.label.replace(/::/g, ' ') : result.id), username: result.username || '', state: result.state + (result.frozen ? ` ${__('Disabled')}` : ''), duration: getDuration(result.started_at, result.ended_at),
Fixes #<I> - task id fallback when there is no label (#<I>)
theforeman_foreman-tasks
train
e5900f6322259d46a495631d981e2c0840037769
diff --git a/lib/router.js b/lib/router.js index <HASH>..<HASH> 100644 --- a/lib/router.js +++ b/lib/router.js @@ -70,10 +70,18 @@ Router.prototype._loadModule = function (modDef, symbols) { default: throw new Error('unknown module type ' + modDef.type + ' (for module ' + modDef.name + ').'); } + // append the log property to module options, if it is not present + if (modDef.options) { + modDef.options.log = modDef.options.log || this._options.log; + } // let the error propagate in case the module cannot be loaded var modObj = require(loadPath)(modDef.options); this._modules.set(modDef, modObj); for (var symbol in modObj) { + if (!modObj.hasOwnProperty(symbol)) { + // toString() or something else, skip this + continue; + } // check for duplicate symbols if (symbols[symbol]) { throw new Error("Duplicate symbol " + symbol + " in module " + modDef.name);
T<I>: Minor improvements to lib/router.js When loading modules, append the log function to its configuration. Also, when checking for dumplicate symbols, filter out toString() and friends.
wikimedia_restbase
train
80f5e136af07fbdfce1321d1efd0771568f749be
diff --git a/spyder/plugins/variableexplorer/widgets/main_widget.py b/spyder/plugins/variableexplorer/widgets/main_widget.py index <HASH>..<HASH> 100644 --- a/spyder/plugins/variableexplorer/widgets/main_widget.py +++ b/spyder/plugins/variableexplorer/widgets/main_widget.py @@ -72,8 +72,6 @@ class VariableExplorerContextMenuActions: ImshowAction = 'imshow_action' SaveArrayAction = 'save_array_action' InsertAction = 'insert_action' - InsertActionAbove = 'insert_action_above' - InsertActionBelow = 'insert_action_below' RemoveAction = 'remove_action' RenameAction = 'rename_action' DuplicateAction = 'duplicate_action' @@ -219,12 +217,14 @@ class VariableExplorerWidget(ShellConnectMainWidget): resize_rows_action = self.create_action( VariableExplorerContextMenuActions.ResizeRowsAction, text=_("Resize rows to contents"), + icon=self.create_icon('collapse_row'), triggered=self.resize_rows ) resize_columns_action = self.create_action( VariableExplorerContextMenuActions.ResizeColumnsAction, _("Resize columns to contents"), + icon=self.create_icon('collapse_column'), triggered=self.resize_columns ) diff --git a/spyder/utils/icon_manager.py b/spyder/utils/icon_manager.py index <HASH>..<HASH> 100644 --- a/spyder/utils/icon_manager.py +++ b/spyder/utils/icon_manager.py @@ -195,6 +195,8 @@ class IconManager(): 'hist': [('mdi.chart-histogram',), {'color': self.MAIN_FG_COLOR}], 'imshow': [('mdi.image',), {'color': self.MAIN_FG_COLOR}], 'insert': [('mdi.login',), {'color': self.MAIN_FG_COLOR}], + 'insert_above': [('mdi.table-arrow-up',), {'color': self.MAIN_FG_COLOR}], + 'insert_below': [('mdi.table-arrow-down',), {'color': self.MAIN_FG_COLOR}], 'rename': [('mdi.rename-box',), {'color': self.MAIN_FG_COLOR}], 'move': [('mdi.file-move',), {'color': self.MAIN_FG_COLOR}], 'edit_add': [('mdi.plus',), {'color': self.MAIN_FG_COLOR}], diff --git a/spyder/widgets/collectionseditor.py b/spyder/widgets/collectionseditor.py index <HASH>..<HASH> 100644 --- a/spyder/widgets/collectionseditor.py +++ b/spyder/widgets/collectionseditor.py @@ -666,12 +666,12 @@ class BaseTableView(QTableView, SpyderConfigurationAccessor): ) self.insert_action_above = create_action( self, _("Insert above"), - icon=ima.icon('insert'), + icon=ima.icon('insert_above'), triggered=lambda: self.insert_item(below=False) ) self.insert_action_below = create_action( self, _("Insert below"), - icon=ima.icon('insert'), + icon=ima.icon('insert_below'), triggered=lambda: self.insert_item(below=True) ) self.remove_action = create_action(self, _("Remove"),
Collections: Use new icons for insert above/below actions
spyder-ide_spyder
train
b6e03f20a58e0a7563ba13cce8c82d8906eabb44
diff --git a/astroid/interpreter/_import/spec.py b/astroid/interpreter/_import/spec.py index <HASH>..<HASH> 100644 --- a/astroid/interpreter/_import/spec.py +++ b/astroid/interpreter/_import/spec.py @@ -281,7 +281,7 @@ def _precache_zipimporters(path=None): zipimporter instances. :param path: paths that has to be added into the cache - :return: association between paths stored into the cache and zipimporter instances + :return: association between paths stored in the cache and zipimporter instances """ pic = sys.path_importer_cache
Update astroid/interpreter/_import/spec.py Taking into account @GergelyKalmar suggestion
PyCQA_astroid
train
c871ce95f58d246908f4a90f142e15718f9dcbb0
diff --git a/js/mixins/uploader.js b/js/mixins/uploader.js index <HASH>..<HASH> 100644 --- a/js/mixins/uploader.js +++ b/js/mixins/uploader.js @@ -50,6 +50,15 @@ export default { }; }, ready() { + this.$dnd = new qq.DragAndDrop({ + dropZoneElements: [this.$el], + classes: { + dropActive: this.$options.dropActive || 'drop-active' + }, + callbacks: { + processingDroppedFilesComplete: this.on_dropped_files_complete + } + }); this._build_uploader(); }, @@ -123,16 +132,6 @@ export default { messages: messages, validation: {allowedExtensions: allowedExtensions.items} }); - - this.$dnd = new qq.DragAndDrop({ - dropZoneElements: [this.$el], - classes: { - dropActive: this.$options.dropActive || 'drop-active' - }, - callbacks: { - processingDroppedFilesComplete: this.on_dropped_files_complete - } - }); }, /**
Prevent multiple drag and drop handlers to spawn
opendatateam_udata
train
0d240c165f45d974042511079d5f602017f1d9a5
diff --git a/haproxy/tests/test_argparse.py b/haproxy/tests/test_argparse.py index <HASH>..<HASH> 100644 --- a/haproxy/tests/test_argparse.py +++ b/haproxy/tests/test_argparse.py @@ -158,6 +158,13 @@ class ArgumentParsingTest(unittest.TestCase): '-f', 'haproxy/tests/files/huge.log', ] parse_arguments(self.parser.parse_args(arguments)) + def test_arg_parser_filters_without_closing_bracket(self): + """Test that trying to input an invalid filter expression fails.""" + with self.assertRaises(ValueError): + arguments = ['--filter', 'ip],ssl', + '-f', 'haproxy/tests/files/huge.log', ] + parse_arguments(self.parser.parse_args(arguments)) + def test_arg_parser_list_commands(self): """Test that list commands argument is parsed.""" arguments = ['--list-commands', ]
Add test for filter expression without closing brackets
gforcada_haproxy_log_analysis
train
4d630f0e5fbb0769001a2a8b3f1e0b44c36882e7
diff --git a/examples/postman_echo/request_methods/request_with_functions_test.py b/examples/postman_echo/request_methods/request_with_functions_test.py index <HASH>..<HASH> 100644 --- a/examples/postman_echo/request_methods/request_with_functions_test.py +++ b/examples/postman_echo/request_methods/request_with_functions_test.py @@ -15,13 +15,13 @@ class TestCaseRequestWithFunctions(HttpRunner): teststeps = [ Step("get with params") .with_variables(foo1="bar1", foo2="session_bar2", sum_v="${sum_two(1, 2)}") + .set_extractor("session_foo2", "body.args.foo2") .run_request( Request() .get("/get") .with_params(foo1="$foo1", foo2="$foo2", sum_v="$sum_v") .with_headers(**{"User-Agent": "HttpRunner/${get_httprunner_version()}"}) ) - .extract("session_foo2", "body.args.foo2") .assert_equal("status_code", 200) .assert_equal("body.args.foo1", "session_bar1") .assert_equal("body.args.sum_v", "3") diff --git a/httprunner/testcase.py b/httprunner/testcase.py index <HASH>..<HASH> 100644 --- a/httprunner/testcase.py +++ b/httprunner/testcase.py @@ -1,5 +1,5 @@ import inspect -from typing import Text, Any +from typing import Text, Any, Dict from httprunner.schema import ( TConfig, @@ -126,39 +126,33 @@ class Request(object): return RequestWithOptionalArgs(MethodEnum.PATCH, url) -class Step(object): - def __init__(self, name: Text): +class StepValidation(object): + def __init__( + self, name: Text, variables: Dict, extractors: Dict, request: TRequest + ): self.__name = name - self.__variables = {} - self.__request = None - self.__extract = {} + self.__variables = variables + self.__extractors = extractors + self.__request = request self.__validators = [] - def with_variables(self, **variables) -> "Step": - self.__variables.update(variables) - return self - @property def request(self) -> TRequest: return self.__request - def run_request(self, req_obj: RequestWithOptionalArgs) -> "Step": - self.__request = req_obj.perform() - return self - - def extract(self, var_name: Text, jmes_path: Text) -> "Step": - self.__extract[var_name] = jmes_path - return self - - def assert_equal(self, jmes_path: Text, expected_value: Any) -> "Step": + def assert_equal(self, jmes_path: Text, expected_value: Any) -> "StepValidation": self.__validators.append({"eq": [jmes_path, expected_value]}) return self - def assert_greater_than(self, jmes_path: Text, expected_value: Any) -> "Step": + def assert_greater_than( + self, jmes_path: Text, expected_value: Any + ) -> "StepValidation": self.__validators.append({"gt": [jmes_path, expected_value]}) return self - def assert_less_than(self, jmes_path: Text, expected_value: Any) -> "Step": + def assert_less_than( + self, jmes_path: Text, expected_value: Any + ) -> "StepValidation": self.__validators.append({"lt": [jmes_path, expected_value]}) return self @@ -167,6 +161,28 @@ class Step(object): name=self.__name, variables=self.__variables, request=self.__request, - extract=self.__extract, + extract=self.__extractors, validate=self.__validators, ) + + +class Step(object): + def __init__(self, name: Text): + self.__name = name + self.__variables = {} + self.__extractors = {} + self.__request = None + + def with_variables(self, **variables) -> "Step": + self.__variables.update(variables) + return self + + def set_extractor(self, var_name: Text, jmes_path: Text) -> "Step": + self.__extractors[var_name] = jmes_path + return self + + def run_request(self, req_obj: RequestWithOptionalArgs) -> "StepValidation": + self.__request = req_obj.perform() + return StepValidation( + self.__name, self.__variables, self.__extractors, self.__request + )
refactor: StepValidation
HttpRunner_HttpRunner
train
16de6865fa4dada6061e607477f612483ab7db0e
diff --git a/lib/poise_python/python_providers.rb b/lib/poise_python/python_providers.rb index <HASH>..<HASH> 100644 --- a/lib/poise_python/python_providers.rb +++ b/lib/poise_python/python_providers.rb @@ -23,6 +23,8 @@ module PoisePython # # @since 1.0.0 module PythonProviders + autoload :Base, 'poise_python/python_providers/base' + Chef::Platform::ProviderPriorityMap.instance.priority(:python_runtime, [ PoisePython::PythonProviders::Scl, PoisePython::PythonProviders::System, diff --git a/lib/poise_python/resources/python_virtualenv.rb b/lib/poise_python/resources/python_virtualenv.rb index <HASH>..<HASH> 100644 --- a/lib/poise_python/resources/python_virtualenv.rb +++ b/lib/poise_python/resources/python_virtualenv.rb @@ -17,11 +17,8 @@ require 'chef/mixin/which' require 'poise' -require 'poise_python/resources/python_runtime' -require 'poise_python/python_providers/base' - -require 'poise_python/python_command_mixin' - +# Break a require loop by letting autoload work its magic. +require 'poise_python' module PoisePython
Break a require loop where python_virtualenv loads providers/base, which tries to autoload PythonProviders, which loads providers/scl, which dies because Base isn't a symbol yet.
poise_poise-python
train