hash
stringlengths
40
40
diff
stringlengths
131
114k
message
stringlengths
7
980
project
stringlengths
5
67
split
stringclasses
1 value
58486be8e3723a6e6d689296e8c1f187bfcd91b7
diff --git a/zarr/util.py b/zarr/util.py index <HASH>..<HASH> 100644 --- a/zarr/util.py +++ b/zarr/util.py @@ -1,7 +1,7 @@ # -*- coding: utf-8 -*- from __future__ import absolute_import, print_function, division import operator -from textwrap import TextWrapper +from textwrap import TextWrapper, dedent import numbers from asciitree import BoxStyle, LeftAligned @@ -383,6 +383,104 @@ class ZarrGroupTraversal(Traversal): return name +def custom_html_sublist(group, indent): + traverser = ZarrGroupTraversal(tree=group) + result = "" + + result += ( + """{0}<li><div>{1}</div>""".format( + indent, traverser.get_text(group) + ) + ) + + children = traverser.get_children(group) + if children: + result += """\n{0}{0}<ul>\n""".format(indent) + for c in children: + for l in custom_html_sublist(c, indent).splitlines(): + result += "{0}{0}{1}\n".format(indent, l) + if children: + result += "{0}{0}</ul>\n{0}".format(indent) + + result += ( + """</li>\n""".format( + indent, traverser.get_text(group) + ) + ) + + return result + + +def custom_html_list(group, indent=" "): + result = "" + + # Add custom CSS style for our HTML list + result += """<style type="text/css">\n""" + result += dedent("""\ + div.zarrTree { + font-family: Courier, monospace; + font-size: 11pt; + font-style: normal; + } + + div.zarrTree ul, + div.zarrTree li, + div.zarrTree li > div { + display: block; + position: relative; + } + + div.zarrTree ul, + div.zarrTree li { + list-style-type: none; + } + + div.zarrTree li { + border-left: 2px solid #000; + margin-left: 1em; + } + + div.zarrTree li > div { + padding-left: 1.3em; + padding-top: 0.225em; + padding-bottom: 0.225em; + } + + div.zarrTree li > div::before { + content: ''; + position: absolute; + top: 0; + left: -2px; + bottom: 50%; + width: 1.2em; + border-left: 2px solid #000; + border-bottom: 2px solid #000; + } + + div.zarrTree > ul > li:first-child > div { + padding-left: 4%; + } + + div.zarrTree > ul > li:first-child > div::before { + border: 0 none transparent; + } + + div.zarrTree ul > li:last-child { + border-left: 2px solid transparent; + } + """) + result += "</style>\n\n" + + # Insert the HTML list + result += """<div class="zarrTree">\n""" + result += "<ul>\n" + result += custom_html_sublist(group, indent=indent) + result += "</ul>\n" + result += "</div>\n" + + return result + + class TreeHierarchy(object): def __init__(self, group): @@ -411,3 +509,6 @@ class TreeHierarchy(object): def __repr__(self): return self.ascii_draw(self.group) + + def _repr_html_(self): + return custom_html_list(self.group)
Add an HTML representation of TreeHierarchy Provides an HTML representation of TreeHierarchy that can be used for representation of Zarr's `tree` method in the notebook.
zarr-developers_zarr
train
486d72ea26a81249454429b9e815717f63232316
diff --git a/example/goauth2client/goauth2client.go b/example/goauth2client/goauth2client.go index <HASH>..<HASH> 100644 --- a/example/goauth2client/goauth2client.go +++ b/example/goauth2client/goauth2client.go @@ -16,8 +16,6 @@ func main() { config := osin.NewServerConfig() // goauth2 checks errors using status codes config.ErrorStatusCode = 401 - // goauth2 passes client secret in params instead of Authorization headers - config.AllowClientSecretInParams = true server := osin.NewServer(config, example.NewTestStorage())
* GoAuth2 now sends client secret on Basic Auth, no need to allow it on params any more. fixes #<I>
openshift_osin
train
e7804ecc7b2aeb6b74b63685c1dec1da4f27d601
diff --git a/packages/react-split/src/index.js b/packages/react-split/src/index.js index <HASH>..<HASH> 100644 --- a/packages/react-split/src/index.js +++ b/packages/react-split/src/index.js @@ -33,6 +33,7 @@ class SplitWrapper extends React.Component { } = prevProps const otherProps = [ + 'maxSize', 'expandToMin', 'gutterSize', 'gutterAlign', @@ -107,6 +108,7 @@ class SplitWrapper extends React.Component { const { sizes, minSize, + maxSize, expandToMin, gutterSize, gutterAlign,
exclude maxSize prop from component render
nathancahill_split
train
851d7af75a864415b25fdd80494b47370745d371
diff --git a/docs/conf.py b/docs/conf.py index <HASH>..<HASH> 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -30,7 +30,7 @@ import os import sys # Load all of the global Astropy configuration -from astropy.sphinx.conf import * +from astropy_helpers.sphinx.conf import * # Get configuration information from setup.cfg from distutils import config
Switch to using astropy_helpers for docs build.
astropy_photutils
train
bdc7839a0696ad87861943e009cc461c067eeea8
diff --git a/src/Shell/GenerateModulesShell.php b/src/Shell/GenerateModulesShell.php index <HASH>..<HASH> 100644 --- a/src/Shell/GenerateModulesShell.php +++ b/src/Shell/GenerateModulesShell.php @@ -45,6 +45,13 @@ class GenerateModulesShell extends Shell 'short' => 'f', 'boolean' => true, 'help' => 'Force overwriting existing files without prompting.', + ])->addOption('module-path', [ + 'default' => CONFIG . 'Modules' . DS, + 'help' => 'Override the application path to folder with module json files, which defaults to `config/Modules/`', + ])->addOption('skip-decorators', [ + 'boolean' => true, + 'default' => false, + 'help' => 'Skip running module decorators', ]); return $parser; @@ -61,8 +68,20 @@ class GenerateModulesShell extends Shell foreach ($modules as $module) { $this->info(sprintf('Generate module %s', $module)); + + $command = ['generate_modules', 'module', $module]; + if (!empty($this->param('module-path'))) { + $command[] = '--module-path'; + $command[] = $this->param('module-path'); + } + if ((bool)$this->param('force') === true) { + $command[] = '-f'; + } + if ((bool)$this->param('skip-decorators') === true) { + $command[] = '--skip-decorators'; + } - $this->Module->main($module); + $this->dispatchShell(compact('command')); } return true; diff --git a/src/Shell/Task/ModuleTask.php b/src/Shell/Task/ModuleTask.php index <HASH>..<HASH> 100644 --- a/src/Shell/Task/ModuleTask.php +++ b/src/Shell/Task/ModuleTask.php @@ -92,7 +92,10 @@ class ModuleTask extends SimpleBakeTask $views = $this->getModuleViews(); $data = compact('config', 'migration', 'lists', 'fields', 'menus', 'views'); - $data = $this->runDecorators($data); + $skipDecorators = $this->param('skip-decorators'); + if (!$skipDecorators) { + $data = $this->runDecorators($data); + } foreach ($data as $key => $value) { $data[$key] = var_export($value, true); @@ -213,6 +216,11 @@ class ModuleTask extends SimpleBakeTask 'default' => CONFIG . 'Modules' . DS, 'help' => 'Override the application path to folder with module json files, which defaults to `config/Modules/`', ]); + $parser->addOption('skip-decorators', [ + 'boolean' => true, + 'default' => false, + 'help' => 'Skip running module decorators', + ]); return $parser; }
Allow to skip decorators (task #<I>)
QoboLtd_cakephp-utils
train
4be061a5cc28527ef3e2b9f0d428a2711bd1ffe9
diff --git a/src/layer/vector/Path.SVG.js b/src/layer/vector/Path.SVG.js index <HASH>..<HASH> 100644 --- a/src/layer/vector/Path.SVG.js +++ b/src/layer/vector/Path.SVG.js @@ -106,7 +106,8 @@ L.Path = L.Path.extend({ this.fire(e.type, { latlng: latlng, layerPoint: layerPoint, - containerPoint: containerPoint + containerPoint: containerPoint, + ctrlKey: e.ctrlKey }); L.DomEvent.stopPropagation(e);
add ctrlKey to mouse event
axyjo_leaflet-rails
train
f7443577aed1fa94d3fca8db8ac0ca06d84550b1
diff --git a/Gruntfile.js b/Gruntfile.js index <HASH>..<HASH> 100644 --- a/Gruntfile.js +++ b/Gruntfile.js @@ -60,7 +60,8 @@ module.exports = function (grunt) { }, all: [ 'Gruntfile.js', - '<%= yeoman.app %>/scripts/{,*/}*.js' + '<%= yeoman.app %>/scripts/{,*/}*.js', + 'test/spec/{,*/}*.js' ] }, karma: { @@ -224,6 +225,7 @@ module.exports = function (grunt) { // ]); grunt.registerTask('test', [ + 'jshint', 'clean:server', // 'coffee', // 'compass', @@ -239,7 +241,6 @@ module.exports = function (grunt) { grunt.registerTask('build', [ 'clean:gen', - 'jshint', 'test', 'concat', 'copy',
Add jshint task to grunt test task to perform linting of specs
jonashartmann_webcam-directive
train
498aca88fc914a5754b855a89d889da06a43fe62
diff --git a/girder/utility/system.py b/girder/utility/system.py index <HASH>..<HASH> 100644 --- a/girder/utility/system.py +++ b/girder/utility/system.py @@ -140,7 +140,9 @@ def getStatus(mode='basic', user=None): connDict['type']) connections.append(connDict) status['connections'] = connections - status['ioCounters'] = _objectToDict(process.io_counters()) + if hasattr(process, 'io_counters'): + status['ioCounters'] = _objectToDict(process.io_counters()) + status['cherrypyThreads'] = {} for threadId in cherrypy.tools.status.seenThreads:
Fix server_system test on OSX psutil.Process does not have io_counters method on OSX
girder_girder
train
706856734a516079663b4d2820cb7529372a41b0
diff --git a/lightadmin-core/src/main/resources/META-INF/resources/scripts/lightadmin.js b/lightadmin-core/src/main/resources/META-INF/resources/scripts/lightadmin.js index <HASH>..<HASH> 100644 --- a/lightadmin-core/src/main/resources/META-INF/resources/scripts/lightadmin.js +++ b/lightadmin-core/src/main/resources/META-INF/resources/scripts/lightadmin.js @@ -46,7 +46,9 @@ DOMAIN_TYPE_METADATA = {}; json[attrName] = false; break; case 'DATE': - json[attrName] = -377743392000001; + if (usePlaceholders) { + json[attrName] = -377743392000001; + } break; } } );
LA-<I>: Not using NULL placeholder for dates in creation screen (#<I>)
la-team_light-admin
train
77d6cec90a2b471ebc4cda46f8f45020fc7b29b4
diff --git a/Product/ProductPriceManager.php b/Product/ProductPriceManager.php index <HASH>..<HASH> 100644 --- a/Product/ProductPriceManager.php +++ b/Product/ProductPriceManager.php @@ -79,6 +79,28 @@ class ProductPriceManager implements ProductPriceManagerInterface } /** + * Returns the special price for the product by a given currency + * + * @param ProductInterface $product + * @param null|string $currency + * + * @return null|\Sulu\Bundle\ProductBundle\Entity\ProductPrice + */ + public function getSpecialPriceForCurrency(ProductInterface $product, $currency = null) + { + $currency = $currency ?: $this->defaultCurrency; + if ($prices = $product->getSpecialPrices()) { + foreach ($prices as $price) { + if ($price->getCurrency()->getCode() == $currency) { + return $price; + } + } + } + + return null; + } + + /** * Helper function to get a formatted price for a given currency and locale * * @param Integer $price
reverted ProductPriceManager.php
sulu_SuluProductBundle
train
9e68ccc77df51615cd21390bc21208119b940ac1
diff --git a/betfairlightweight/resources/baseresource.py b/betfairlightweight/resources/baseresource.py index <HASH>..<HASH> 100644 --- a/betfairlightweight/resources/baseresource.py +++ b/betfairlightweight/resources/baseresource.py @@ -17,7 +17,7 @@ class BaseResource: def __init__(self, **kwargs): self._datetime_sent = kwargs.pop('date_time_sent', None) now = datetime.datetime.utcnow() - self._datetime_created = now + self.datetime_created = now self._datetime_updated = now self._sub_resource_map = getattr(self.Meta, 'sub_resources', {}) self._data = kwargs @@ -84,7 +84,7 @@ class BaseResource: Elapsed time between datetime sent and datetime created """ if self._datetime_sent: - return (self._datetime_created-self._datetime_sent).total_seconds() + return (self.datetime_created-self._datetime_sent).total_seconds() def __getattr__(self, item): """ diff --git a/tests/test_baseresource.py b/tests/test_baseresource.py index <HASH>..<HASH> 100644 --- a/tests/test_baseresource.py +++ b/tests/test_baseresource.py @@ -16,7 +16,7 @@ class BaseResourceInit(unittest.TestCase): assert base_resource.Meta.sub_resources == {} assert base_resource.Meta.datetime_attributes == () assert base_resource._datetime_sent is None - assert base_resource._datetime_created is not None + assert base_resource.datetime_created is not None assert base_resource._datetime_updated is not None assert base_resource.elapsed_time is None assert base_resource.id is None
datetime_created reverted _
liampauling_betfair
train
a434cfd5ff69f60037103bea6d447a3f40162237
diff --git a/django_libs/__init__.py b/django_libs/__init__.py index <HASH>..<HASH> 100644 --- a/django_libs/__init__.py +++ b/django_libs/__init__.py @@ -1,2 +1,2 @@ # -*- coding: utf-8 -*- -__version__ = '1.66.14' +__version__ = '1.66.15' diff --git a/django_libs/tests/mixins.py b/django_libs/tests/mixins.py index <HASH>..<HASH> 100644 --- a/django_libs/tests/mixins.py +++ b/django_libs/tests/mixins.py @@ -13,8 +13,6 @@ from django.core.urlresolvers import reverse, resolve from django.http import Http404 from django.test import RequestFactory -from django_libs.tests.factories import UserFactory - class ViewTestMixin(object): """Mixin that provides commonly tested assertions.""" @@ -331,7 +329,7 @@ class ViewTestMixin(object): """ if not url: url = self.get_url() - user_no_permissions = UserFactory() + user_no_permissions = AnonymousUser() self.login(user_no_permissions) resp = self.client.get(url, data=self.get_data_payload()) self.assertRedirects(resp,
removed userfactory from view test mixins
bitlabstudio_django-libs
train
6ad82a3c9164817416cfb91d08d2cc254966de83
diff --git a/lib/node.js b/lib/node.js index <HASH>..<HASH> 100644 --- a/lib/node.js +++ b/lib/node.js @@ -786,5 +786,5 @@ declare module "assert" { declare function ifError(value: any): void; } -declare function setImmediate(callback: ((...args: Array<any>) => void), ...args: Array<any>): any; -declare function clearImmediate(immediateObject: any): void; +declare function setImmediate(callback: ((...args: Array<any>) => void), ...args: Array<any>): Object; +declare function clearImmediate(immediateObject: Object): void;
Use `Object` as the type of the immediateObject entity returned by setImmediate and taken by clearImmediate
facebook_flow
train
3bb71349ca1f371a1be3f6f9bf8f7399102f87ea
diff --git a/l2cs.py b/l2cs.py index <HASH>..<HASH> 100644 --- a/l2cs.py +++ b/l2cs.py @@ -12,6 +12,7 @@ import sys import whoosh.qparser import whoosh.qparser.plugins import whoosh.qparser.syntax +import whoosh.qparser.taggers import whoosh.query @@ -55,10 +56,17 @@ def build_field(clause): yield clause.text -@handler(whoosh.query.And, whoosh.query.Or, whoosh.query.Not) +@handler(whoosh.query.And, whoosh.query.Or, whoosh.query.Not, + whoosh.query.AndMaybe) def build_grouper(clause): yield "(" - yield clause.__class__.__name__.lower() + # CloudSearch only supports 'and' and 'or' clauses; neither really fit + # with the concept of "AndMaybe", which tries to "boost" results that + # include the "Maybe" portion of the clause. + if isinstance(clause, whoosh.query.AndMaybe): + yield "and" + else: + yield clause.__class__.__name__.lower() for child_clause in clause.children(): yield " " for piece in walk_clause(child_clause): @@ -154,40 +162,46 @@ class FieldAliasPlugin(PseudoFieldPlugin): return node -class PlusMinusPlugin(whoosh.qparser.plugins.PlusMinusPlugin): - '''The default PlusMinus plugin doesn't respect the parser's - default grouping, instead blindly using "OR" groupings. This modified - version takes the parser's desired grouping into account +class MinusPlugin(whoosh.qparser.plugins.Plugin): + '''This differs from whoosh's PlusMinusPlugin. The concept of "AndMaybe" + isn't one that applies to CloudSearch, so "+" actions aren't needed. + Additionally, the logic is simplified from the whoosh version to just + swap out the nodes ''' - def do_plusminus(self, parser, group): + class Minus(whoosh.qparser.syntax.MarkerNode): + pass + + def __init__(self, minusexpr="-"): + self.minusexpr = minusexpr + + def taggers(self, parser): + minus_tagger = whoosh.qparser.taggers.FnTagger(self.minusexpr, + self.Minus, + "minus") + return [(minus_tagger, 0)] + + def filters(self, parser): + return [(self.do_minus, 505)] + + def do_minus(self, parser, group): '''This filter sorts nodes in a flat group into "required", "default", and "banned" subgroups based on the presence of plus and minus nodes. ''' - required = whoosh.qparser.syntax.AndGroup() - banned = whoosh.qparser.syntax.OrGroup() - default = parser.group() - - # Which group to put the next node we see into - next_ = default + grouper = group.__class__() + + next_not = None for node in group: - if isinstance(node, self.Plus): - # +: put the next node in the required group - next_ = required - elif isinstance(node, self.Minus): - # -: put the next node in the banned group - next_ = banned + if isinstance(node, self.Minus): + # -: Replace with a NOT node + next_not = whoosh.qparser.syntax.NotGroup() + grouper.append(next_not) + elif next_not is not None: + next_not.append(node) + next_not = None else: - # Anything else: put it in the appropriate group - next_.append(node) - # Reset to putting things in the optional group by default - next_ = default - - group = default - if required: - group = whoosh.qparser.syntax.AndMaybeGroup([required, group]) - if banned: - group = whoosh.qparser.syntax.AndNotGroup([group, banned]) - return group + grouper.append(node) + + return grouper DEFAULT_PLUGINS = ( @@ -200,7 +214,7 @@ DEFAULT_PLUGINS = ( whoosh.qparser.plugins.OperatorsPlugin(AndMaybe=None, Require=None), whoosh.qparser.plugins.EveryPlugin(), - PlusMinusPlugin(), + MinusPlugin(), ) diff --git a/test_l2cs.py b/test_l2cs.py index <HASH>..<HASH> 100644 --- a/test_l2cs.py +++ b/test_l2cs.py @@ -79,8 +79,14 @@ class l2csTester(unittest.TestCase): def test_alias1(self): self._run_test("alias1:foo", "(field alias 'foo')") def test_alias2(self): - '''Make sure the reference the base of the alias still works''' + '''Make sure that referencing the base of the alias still works''' self._run_test("alias:foo", "(field alias 'foo')") + + # Unsupported "+" syntax gets ignored, AndMaybe clauses are avoided + def test_plus1(self): + self._run_test("learn c++ programming", "(and (field text 'learn') (field text 'c++') (field text 'programming'))") + def test_plus2(self): + self._run_test("learn c++", "(and (field text 'learn') (field text 'c++'))") if __name__ == '__main__':
Issue #7: AndMaybe clause problems with PlusMinus This removes the generation of AndMaybe clauses by l2cs.PlusMinusPlugin. The plugin's support of '+' is also removed, since CloudSearch has no concept of 'AndMaybe' type clauses. The Plugin is renamed to "MinusPlugin" and cleaned up slightly.
kemitche_l2cs
train
acb1ad9fd9555daec098ff9186279ade76f2c040
diff --git a/lib/modules/migration/lib/migrationState.js b/lib/modules/migration/lib/migrationState.js index <HASH>..<HASH> 100644 --- a/lib/modules/migration/lib/migrationState.js +++ b/lib/modules/migration/lib/migrationState.js @@ -27,7 +27,7 @@ module.exports = function(self,deps){ this.err = dbModel.errors; } var ddlSyncOne = function(dbname, scheme){ - return deps.databases.getDatabase(dbname).then(function(db){ + return deps.database.getDatabase(dbname).then(function(db){ var def = Q.defer(); if (dbg) console.log("Syncing "+dbname); var sync = new Sync({
migrationState.js err in getDatabase
Kreees_muon
train
ca76dbd94a2175877cfa0ac06bce09822b4f43dd
diff --git a/js/coinbase.js b/js/coinbase.js index <HASH>..<HASH> 100644 --- a/js/coinbase.js +++ b/js/coinbase.js @@ -400,6 +400,7 @@ module.exports = class coinbase extends Exchange { 'symbol': symbol, 'type': type, 'side': side, + 'takerOrMaker': undefined, 'price': price, 'amount': amount, 'cost': cost, @@ -474,7 +475,7 @@ module.exports = class coinbase extends Exchange { 'askVolume': undefined, 'vwap': undefined, 'open': undefined, - 'close': undefined, + 'close': last, 'previousClose': undefined, 'change': undefined, 'percentage': undefined,
coinbase fetchTicker last = close
ccxt_ccxt
train
2941cb3e03115ac579ea2de3f06c25071705fac5
diff --git a/ants/segmentation/__init__.py b/ants/segmentation/__init__.py index <HASH>..<HASH> 100644 --- a/ants/segmentation/__init__.py +++ b/ants/segmentation/__init__.py @@ -1,9 +1,9 @@ - from .anti_alias import * from .atropos import * from .kmeans import * from .kelly_kapowski import * -from .joint_label_fusion import * +from .joint_label_fusion import joint_label_fusion +from .joint_label_fusion import local_joint_label_fusion from .label_geometry_measures import * from .otsu import * -from .prior_based_segmentation import * \ No newline at end of file +from .prior_based_segmentation import *
WIP: local_jlf not found on linux
ANTsX_ANTsPy
train
205375dee0062a0d8aa0d9cf86436919aebdabfb
diff --git a/src/main/java/io/reactivex/Observable.java b/src/main/java/io/reactivex/Observable.java index <HASH>..<HASH> 100644 --- a/src/main/java/io/reactivex/Observable.java +++ b/src/main/java/io/reactivex/Observable.java @@ -12538,7 +12538,6 @@ public abstract class Observable<T> implements ObservableSource<T> { final Function<? super T, ? extends V> valueSelector, Callable<? extends Map<K, V>> mapSupplier) { ObjectHelper.requireNonNull(keySelector, "keySelector is null"); - ObjectHelper.requireNonNull(keySelector, "keySelector is null"); ObjectHelper.requireNonNull(valueSelector, "valueSelector is null"); ObjectHelper.requireNonNull(mapSupplier, "mapSupplier is null"); return collect(mapSupplier, Functions.toMapKeyValueSelector(keySelector, valueSelector));
Remove duplicate nullity check line (#<I>)
ReactiveX_RxJava
train
1277f3bfeac4679b4b121fcfb908e44c9a7edac1
diff --git a/web/src/main/java/uk/ac/ebi/atlas/search/analyticsindex/AnalyticsSearchDao.java b/web/src/main/java/uk/ac/ebi/atlas/search/analyticsindex/AnalyticsSearchDao.java index <HASH>..<HASH> 100644 --- a/web/src/main/java/uk/ac/ebi/atlas/search/analyticsindex/AnalyticsSearchDao.java +++ b/web/src/main/java/uk/ac/ebi/atlas/search/analyticsindex/AnalyticsSearchDao.java @@ -19,7 +19,7 @@ import java.io.IOException; public class AnalyticsSearchDao { public static final String ABOVE_CUTOFF = "(" + "(experimentType:(rnaseq_mrna_baseline OR proteomics_baseline) AND expressionLevel:[0.5 TO *]) OR " + - "(experimentType:(rnaseq_mrna_differential OR microarray_1colour_mrna_differential OR microarray_2colour_mrna_differential OR microarray_1colour_microrna_differential) AND foldChange:[1.0 TO *])" + + "(experimentType:(rnaseq_mrna_differential OR microarray_1colour_mrna_differential OR microarray_2colour_mrna_differential OR microarray_1colour_microrna_differential) AND foldChange:([1.0 TO *] OR [* TO -1.0]))" + ")"; private static final Logger LOGGER = Logger.getLogger(AnalyticsSearchDao.class); @@ -49,14 +49,24 @@ public class AnalyticsSearchDao { } private SolrQuery buildQuery(GeneQuery geneQuery) { - String identifierSearch = geneQuery.asString(); //TODO: support multiple gene query terms - SolrQuery solrQuery = new SolrQuery("identifierSearch:" + identifierSearch); + + StringBuilder sb = new StringBuilder("identifierSearch:("); + if (geneQuery.terms().size() > 0) { + for (int i = 0 ; i < geneQuery.terms().size() - 1 ; i++) { + sb.append(geneQuery.terms().get(i)).append(" OR "); + } + sb.append(geneQuery.terms().get(geneQuery.terms().size() - 1)); + } + sb.append(")"); + + SolrQuery solrQuery = new SolrQuery(sb.toString()); + solrQuery.setRows(0); solrQuery.setFilterQueries(ABOVE_CUTOFF); solrQuery.setFacet(true); solrQuery.addFacetField("experimentType"); solrQuery.setFacetMinCount(1); return solrQuery; - } + } }
Add support for multiple genes in new search ; include results with foldChange -<I> and lower
ebi-gene-expression-group_atlas
train
c4a6eb1929ce3c5e652269676134a53c2dc8d98c
diff --git a/tests/test_cli.py b/tests/test_cli.py index <HASH>..<HASH> 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -146,7 +146,7 @@ def test_force_stop(pyscript): assert result.stderr == ('ERROR: Timed out while waiting for process ' '(PID {pid}) to terminate\n').format( pid=pid).encode('utf-8') - assert 1.0 <= (t2 - t1) <= 1.5 + assert 1.0 <= (t2 - t1) < 2.0 def test_force_stop_custom_timeout(pyscript): @@ -181,7 +181,7 @@ def test_force_stop_custom_timeout(pyscript): assert result.stderr == ('ERROR: Timed out while waiting for process ' '(PID {pid}) to terminate\n').format( pid=pid).encode('utf-8') - assert 1.0 <= (t2 - t1) <= 1.5 + assert 1.0 <= (t2 - t1) < 2.0 def test_status_json(pyscript):
Be more lenient with timings
jnrbsn_daemonocle
train
2fffd338dd8f3158c536ea38ece08b5c5df0785b
diff --git a/packages/veritone-react-common/src/components/FilePicker/FileListItem.js b/packages/veritone-react-common/src/components/FilePicker/FileListItem.js index <HASH>..<HASH> 100644 --- a/packages/veritone-react-common/src/components/FilePicker/FileListItem.js +++ b/packages/veritone-react-common/src/components/FilePicker/FileListItem.js @@ -27,8 +27,12 @@ class FileListItem extends Component { <div className={styles.fileListItem}> <img src={this.state.dataUrl} className={styles.fileListItemImage}></img> <div className={styles.fileListItemText}> - {this.props.file.name} - {this.props.file.size} + <span className={styles.fileListItemNameText}> + {this.props.file.name} + </span> + <span className={styles.fileListItemFileSizeText}> + {this.formatBytes(this.props.file.size)} + </span> </div> <IconButton className={styles.fileListItemDeleteIcon} aria-label="Delete"> diff --git a/packages/veritone-react-common/src/components/FilePicker/index.js b/packages/veritone-react-common/src/components/FilePicker/index.js index <HASH>..<HASH> 100644 --- a/packages/veritone-react-common/src/components/FilePicker/index.js +++ b/packages/veritone-react-common/src/components/FilePicker/index.js @@ -27,7 +27,7 @@ export default class FilePicker extends Component { render () { return ( - <Paper className={styles.filePicker}> + <Paper> File Picker <Tabs value={this.state.value} indicatorColor="primary" diff --git a/packages/veritone-react-common/src/components/FilePicker/styles.scss b/packages/veritone-react-common/src/components/FilePicker/styles.scss index <HASH>..<HASH> 100644 --- a/packages/veritone-react-common/src/components/FilePicker/styles.scss +++ b/packages/veritone-react-common/src/components/FilePicker/styles.scss @@ -1,11 +1,8 @@ @import 'src/styles/modules/variables'; @import 'src/styles/modules/muiTypography'; -.filePicker { -} - .filePickerBody { - padding: 10px; + padding: 15px; } .filePickerTabs { @@ -13,7 +10,13 @@ } .filePickerButtons { - padding: 10px; + display: -webkit-flex; + display: flex; + -webkit-flex-direction: row; + flex-direction: row; + -webkit-justify-content: flex-end; + justify-content: flex-end; + padding: 0 15px 15px 15px; } .fileUploader { @@ -50,6 +53,19 @@ overflow: hidden; text-overflow: ellipsis; padding: 4px; + span { + width: 100%; + display: inline-block; + } +} + +.fileListItemNameText { + @include mui-text('body1'); +} + +.fileListItemFileSizeText { + @include mui-text('body1'); + color: $grey-5; } .fileListItemImage {
Added some stying for the text in the file items.
veritone_veritone-sdk
train
7989391134fef2c3a8632334ebdf1ef4197b8302
diff --git a/nifty-examples/src/test/java/com/facebook/nifty/server/TestNiftyJavaSslServer.java b/nifty-examples/src/test/java/com/facebook/nifty/server/TestNiftyJavaSslServer.java index <HASH>..<HASH> 100644 --- a/nifty-examples/src/test/java/com/facebook/nifty/server/TestNiftyJavaSslServer.java +++ b/nifty-examples/src/test/java/com/facebook/nifty/server/TestNiftyJavaSslServer.java @@ -93,7 +93,7 @@ public class TestNiftyJavaSslServer private ThriftServerDefBuilder getThriftServerDefBuilder(SslServerConfiguration sslServerConfiguration) { return new ThriftServerDefBuilder() - .listen(8080) + .listen(0) .withSSLConfiguration(sslServerConfiguration) .withProcessor(new scribe.Processor<>(new scribe.Iface() { @Override diff --git a/nifty-examples/src/test/java/com/facebook/nifty/server/TestNiftyOpenSslServer.java b/nifty-examples/src/test/java/com/facebook/nifty/server/TestNiftyOpenSslServer.java index <HASH>..<HASH> 100644 --- a/nifty-examples/src/test/java/com/facebook/nifty/server/TestNiftyOpenSslServer.java +++ b/nifty-examples/src/test/java/com/facebook/nifty/server/TestNiftyOpenSslServer.java @@ -97,7 +97,7 @@ public class TestNiftyOpenSslServer TransportAttachObserver configUpdater) { return new ThriftServerDefBuilder() - .listen(8080) + .listen(0) .withSSLConfiguration(sslServerConfiguration) .withTransportAttachObserver(configUpdater) .withProcessor(new scribe.Processor<>(new scribe.Iface() {
[nifty] fix ssl tests not to depend on port <I>
facebookarchive_nifty
train
d21b4642ad31720d78e7211da819dfa47334a49b
diff --git a/fake_useragent/utils.py b/fake_useragent/utils.py index <HASH>..<HASH> 100644 --- a/fake_useragent/utils.py +++ b/fake_useragent/utils.py @@ -22,7 +22,7 @@ try: from gevent import sleep else: from time import sleep -except ImportError, AttributeError: +except (ImportError, AttributeError): from time import sleep
Fix Python3+ except statment.
hellysmile_fake-useragent
train
df4ff05441eaac7ca99f5725956f500344bc257d
diff --git a/superset/connectors/druid/models.py b/superset/connectors/druid/models.py index <HASH>..<HASH> 100644 --- a/superset/connectors/druid/models.py +++ b/superset/connectors/druid/models.py @@ -372,7 +372,7 @@ class DruidColumn(Model, BaseColumn): for metric in metrics.values(): dbmetric = dbmetrics.get(metric.metric_name) if dbmetric: - for attr in ['json', 'metric_type', 'verbose_name']: + for attr in ['json', 'metric_type']: setattr(dbmetric, attr, getattr(metric, attr)) else: with db.session.no_autoflush: diff --git a/tests/druid_tests.py b/tests/druid_tests.py index <HASH>..<HASH> 100644 --- a/tests/druid_tests.py +++ b/tests/druid_tests.py @@ -376,13 +376,19 @@ class DruidTests(SupersetTestCase): 'double{}'.format(agg.capitalize()), ) - # Augment a metric. - metadata = SEGMENT_METADATA[:] - metadata[0]['columns']['metric1']['type'] = 'LONG' - instance = PyDruid.return_value - instance.segment_metadata.return_value = metadata - cluster.refresh_datasources() + @patch('superset.connectors.druid.models.PyDruid') + def test_refresh_metadata_augment_type(self, PyDruid): + self.login(username='admin') + cluster = self.get_cluster(PyDruid) + cluster.refresh_datasources() + metadata = SEGMENT_METADATA[:] + metadata[0]['columns']['metric1']['type'] = 'LONG' + instance = PyDruid.return_value + instance.segment_metadata.return_value = metadata + cluster.refresh_datasources() + + for i, datasource in enumerate(cluster.datasources): metrics = ( db.session.query(DruidMetric) .filter(DruidMetric.datasource_id == datasource.id) @@ -397,6 +403,37 @@ class DruidTests(SupersetTestCase): 'long{}'.format(agg.capitalize()), ) + @patch('superset.connectors.druid.models.PyDruid') + def test_refresh_metadata_augment_verbose_name(self, PyDruid): + self.login(username='admin') + cluster = self.get_cluster(PyDruid) + cluster.refresh_datasources() + + for i, datasource in enumerate(cluster.datasources): + metrics = ( + db.session.query(DruidMetric) + .filter(DruidMetric.datasource_id == datasource.id) + .filter(DruidMetric.metric_name.like('%__metric1')) + ) + + for metric in metrics: + metric.verbose_name = metric.metric_name + + db.session.commit() + + # The verbose name should not change during a refresh. + cluster.refresh_datasources() + + for i, datasource in enumerate(cluster.datasources): + metrics = ( + db.session.query(DruidMetric) + .filter(DruidMetric.datasource_id == datasource.id) + .filter(DruidMetric.metric_name.like('%__metric1')) + ) + + for metric in metrics: + self.assertEqual(metric.verbose_name, metric.metric_name) + def test_urls(self): cluster = self.get_test_cluster_obj() self.assertEquals(
[druid] Excluding refreshing verbose name (#<I>)
apache_incubator-superset
train
a3ba16f7e055f5a3895fd9639cef965828f1e4b3
diff --git a/tests/test_io.py b/tests/test_io.py index <HASH>..<HASH> 100644 --- a/tests/test_io.py +++ b/tests/test_io.py @@ -43,21 +43,21 @@ class ReverseReadlineTest(unittest.TestCase): raise ValueError("an empty file is being read!") -class ScratchDirTest(unittest.TestCase): - - def test_with(self): - scratch = tempfile.gettempdir() - with ScratchDir(scratch) as d: - with open("scratch_text", "w") as f: - f.write("write") - files = os.listdir(d) - self.assertIn("scratch_text", files) - - #Make sure the tempdir is deleted. - self.assertFalse(os.path.exists(d)) - files = os.listdir(".") - self.assertIn("scratch_text", files) - os.remove("scratch_text") +# class ScratchDirTest(unittest.TestCase): +# +# def test_with(self): +# scratch = tempfile.gettempdir() +# with ScratchDir(scratch) as d: +# with open("scratch_text", "w") as f: +# f.write("write") +# files = os.listdir(d) +# self.assertIn("scratch_text", files) +# +# #Make sure the tempdir is deleted. +# self.assertFalse(os.path.exists(d)) +# files = os.listdir(".") +# self.assertIn("scratch_text", files) +# os.remove("scratch_text") if __name__ == "__main__":
iSeems like travis can't do IO testing, even with tep directory.
materialsvirtuallab_monty
train
2e02cf4a8f51e52fe4e458d7022d47b0bd2845eb
diff --git a/spec/rubocop/cop/style/redundant_self_spec.rb b/spec/rubocop/cop/style/redundant_self_spec.rb index <HASH>..<HASH> 100644 --- a/spec/rubocop/cop/style/redundant_self_spec.rb +++ b/spec/rubocop/cop/style/redundant_self_spec.rb @@ -89,44 +89,88 @@ describe RuboCop::Cop::Style::RedundantSelf do expect(cop.offenses).to be_empty end - it 'accepts a self receiver used to distinguish from blockarg' do - src = ['def requested_specs(&groups)', - ' some_method(self.groups)', - 'end' - ] - inspect_source(cop, src) - expect(cop.offenses).to be_empty - end - - it 'accepts a self receiver used to distinguish from argument' do - src = ['def requested_specs(groups)', - ' some_method(self.groups)', - 'end' - ] - inspect_source(cop, src) - expect(cop.offenses).to be_empty + describe 'instance methods' do + it 'accepts a self receiver used to distinguish from blockarg' do + src = ['def requested_specs(&groups)', + ' some_method(self.groups)', + 'end' + ] + inspect_source(cop, src) + expect(cop.offenses).to be_empty + end + + it 'accepts a self receiver used to distinguish from argument' do + src = ['def requested_specs(groups)', + ' some_method(self.groups)', + 'end' + ] + inspect_source(cop, src) + expect(cop.offenses).to be_empty + end + + it 'accepts a self receiver used to distinguish from argument' do + src = ['def requested_specs(final = true)', + ' something if self.final != final', + 'end' + ] + inspect_source(cop, src) + expect(cop.offenses).to be_empty + end + + it 'accepts a self receiver used to distinguish from local variable' do + src = ['def requested_specs', + ' @requested_specs ||= begin', + ' groups = self.groups - Bundler.settings.without', + ' groups.map! { |g| g.to_sym }', + ' specs_for(groups)', + ' end', + 'end' + ] + inspect_source(cop, src) + expect(cop.offenses).to be_empty + end end - it 'accepts a self receiver used to distinguish from argument' do - src = ['def requested_specs(final = true)', - ' something if self.final != final', - 'end' - ] - inspect_source(cop, src) - expect(cop.offenses).to be_empty - end - - it 'accepts a self receiver used to distinguish from local variable' do - src = ['def requested_specs', - ' @requested_specs ||= begin', - ' groups = self.groups - Bundler.settings.without', - ' groups.map! { |g| g.to_sym }', - ' specs_for(groups)', - ' end', - 'end' - ] - inspect_source(cop, src) - expect(cop.offenses).to be_empty + describe 'class methods' do + it 'accepts a self receiver used to distinguish from blockarg' do + src = ['def self.requested_specs(&groups)', + ' some_method(self.groups)', + 'end' + ] + inspect_source(cop, src) + expect(cop.offenses).to be_empty + end + + it 'accepts a self receiver used to distinguish from argument' do + src = ['def self.requested_specs(groups)', + ' some_method(self.groups)', + 'end' + ] + inspect_source(cop, src) + expect(cop.offenses).to be_empty + end + + it 'accepts a self receiver used to distinguish from argument' do + src = ['def self.requested_specs(final = true)', + ' something if self.final != final', + 'end' + ] + inspect_source(cop, src) + expect(cop.offenses).to be_empty + end + + it 'accepts a self receiver used to distinguish from local variable' do + src = ['def self.requested_specs', + ' @requested_specs ||= begin', + ' groups = self.groups - Bundler.settings.without', + ' groups.map! { |g| g.to_sym }', + ' specs_for(groups)', + ' end', + 'end' + ] + inspect_source(cop, src) + expect(cop.offenses).to be_empty + end end it 'accepts a self receiver used to distinguish from constant' do
Test RedundantSelf with class methods, too
rubocop-hq_rubocop
train
51088d938a3e99b51ff2ad8d4e2f3a8f6fa06f05
diff --git a/salt/modules/influx.py b/salt/modules/influx.py index <HASH>..<HASH> 100644 --- a/salt/modules/influx.py +++ b/salt/modules/influx.py @@ -512,15 +512,15 @@ def retention_policy_add(database, return True -def retention_policy_modify(database, - name, - duration, - replication, - default=False, - user=None, - password=None, - host=None, - port=None): +def retention_policy_alter(database, + name, + duration, + replication, + default=False, + user=None, + password=None, + host=None, + port=None): ''' Modify an existing retention policy. diff --git a/tests/unit/modules/influx_test.py b/tests/unit/modules/influx_test.py index <HASH>..<HASH> 100644 --- a/tests/unit/modules/influx_test.py +++ b/tests/unit/modules/influx_test.py @@ -249,6 +249,42 @@ class InfluxTestCase(TestCase): host='localhost', port=8000)) + def test_retention_policy_get(self): + client = MockInfluxDBClient() + policy = {'name': 'foo'} + with patch.object(influx, '_client', MagicMock(return_value=client)): + client.get_list_retention_policies = MagicMock(return_value=[policy]) + self.assertEqual( + policy, + influx.retention_policy_get(database='db', name='foo') + ) + + def test_retention_policy_add(self): + client = MockInfluxDBClient() + with patch.object(influx, '_client', MagicMock(return_value=client)): + client.create_retention_policy = MagicMock() + self.assertTrue(influx.retention_policy_add( + database='db', + name='name', + duration='30d', + replication=1, + )) + client.create_retention_policy.assert_called_once_with( + 'name', '30d', 1, 'db', False) + + def test_retention_policy_modify(self): + client = MockInfluxDBClient() + with patch.object(influx, '_client', MagicMock(return_value=client)): + client.alter_retention_policy = MagicMock() + self.assertTrue(influx.retention_policy_alter( + database='db', + name='name', + duration='30d', + replication=1, + )) + client.alter_retention_policy.assert_called_once_with( + 'name', 'db', '30d', 1, False) + if __name__ == '__main__': from integration import run_tests run_tests(InfluxTestCase, needs_daemon=False)
add tests, rename a function to more closely mirror influxdb
saltstack_salt
train
57854693b36bff1e38f8698c7a15c50f30926adf
diff --git a/means.py b/means.py index <HASH>..<HASH> 100644 --- a/means.py +++ b/means.py @@ -3,29 +3,32 @@ from __future__ import division, print_function, absolute_import -import numpy as np - -from .calculus import definite_integral def mean_rotor_in_chordal_metric(R, t=None): """Return rotor that is closest to all R in the least-squares sense This can be done (quasi-)analytically because of the simplicity of - the chordal metric function. The only approximation is the simple - 2nd-order discrete formula for the definite integral of the input - rotor function. + the chordal metric function. It is assumed that the input R values + all are normalized (or at least have the same norm). Note that the `t` argument is optional. If it is present, the times are used to weight the corresponding integral. If it is not present, a simple sum is used instead (which may be slightly - faster). + faster). However, because a spline is used to do this integral, + the number of input points must be at least 4 (one more than the + degree of the spline). """ + import numpy as np + from . import as_float_array + from .calculus import definite_integral if t is None: return np.sum(R).normalized() - mean = definite_integral(R, t) - return mean.normalized() + if len(t) < 4 or len(R) < 4: + raise ValueError('Input arguments must have length greater than 3; their lengths are {0} and {1}.'.format(len(R), len(t))) + mean = definite_integral(as_float_array(R), t) + return np.quaternion(*mean).normalized() def optimal_alignment_in_chordal_metric(Ra, Rb, t=None): diff --git a/test/test_quaternion.py b/test/test_quaternion.py index <HASH>..<HASH> 100644 --- a/test/test_quaternion.py +++ b/test/test_quaternion.py @@ -1472,6 +1472,23 @@ def test_integrate_angular_velocity(): assert np.max(phi_Delta) < 1e-4, np.max(phi_Delta) +def test_mean_rotor_in_chordal_metric(): + # Test interpolation of some random constant quaternion + q = quaternion.quaternion(*np.random.rand(4)).normalized() + qs = np.array([q]*10) + ts = np.linspace(0.1, 23.4, num=10) + for length in range(1, 4): + mean1 = quaternion.mean_rotor_in_chordal_metric(qs[:length]) + assert np.abs(q-mean1) < 1e-15, (q, mean1, length) + with pytest.raises(ValueError): + quaternion.mean_rotor_in_chordal_metric(qs[:length], ts[:length]) + for length in range(4, 11): + mean1 = quaternion.mean_rotor_in_chordal_metric(qs[:length]) + assert np.abs(q-mean1) < 1e-15, (q, mean1, length) + mean2 = quaternion.mean_rotor_in_chordal_metric(qs[:length], ts[:length]) + assert np.abs(q-mean2) < 1e-15, (q, mean2, length) + + def test_numpy_save_and_load(): import tempfile a = quaternion.as_quat_array(np.random.rand(5,3,4))
Fix means to work with new definite_integral
moble_quaternion
train
82216757473f97ab918814cc2e121e159dcffde0
diff --git a/salt/modules/schedule.py b/salt/modules/schedule.py index <HASH>..<HASH> 100644 --- a/salt/modules/schedule.py +++ b/salt/modules/schedule.py @@ -192,6 +192,7 @@ def build_schedule_item(name, **kwargs): if not name: ret['comment'] = 'Job name is required.' ret['result'] = False + return ret schedule = {} schedule[name] = salt.utils.odict.OrderedDict() @@ -203,7 +204,9 @@ def build_schedule_item(name, **kwargs): time_conflict = True if time_conflict: - return 'Error: Unable to use "seconds", "minutes", "hours", or "days" with "when" option.' + ret['result'] = False + ret['comment'] = 'Unable to use "seconds", "minutes", "hours", or "days" with "when" option.' + return ret for item in ['seconds', 'minutes', 'hours', 'days']: if item in kwargs: @@ -279,6 +282,7 @@ def add(name, **kwargs): if time_conflict: ret['result'] = False ret['comment'] = 'Error: Unable to use "seconds", "minutes", "hours", or "days" with "when" option.' + return ret _new = build_schedule_item(name, **kwargs) @@ -320,6 +324,7 @@ def modify(name, **kwargs): if time_conflict: ret['result'] = False ret['comment'] = 'Error: Unable to use "seconds", "minutes", "hours", or "days" with "when" option.' + return ret current_schedule = __opts__['schedule'].copy() if 'schedule' in __pillar__: diff --git a/salt/states/schedule.py b/salt/states/schedule.py index <HASH>..<HASH> 100644 --- a/salt/states/schedule.py +++ b/salt/states/schedule.py @@ -113,6 +113,14 @@ def present(name, if name in current_schedule: new_item = __salt__['schedule.build_schedule_item'](name, **kwargs) + + # See if the new_item is valid + if isinstance(new_item, dict): + if 'result' in new_item and not new_item['result']: + ret['result'] = new_item['result'] + ret['comment'] = new_item['comment'] + return ret + if new_item == current_schedule[name]: ret['comment'].append('Job {0} in correct state'.format(name)) else: @@ -125,7 +133,7 @@ def present(name, result = __salt__['schedule.modify'](name, **kwargs) if not result['result']: ret['result'] = result['result'] - ret['comment'].append(result['comment']) + ret['comment'] = result['comment'] return ret else: ret['comment'].append('Modifying job {0} in schedule'.format(name)) @@ -139,7 +147,7 @@ def present(name, result = __salt__['schedule.add'](name, **kwargs) if not result['result']: ret['result'] = result['result'] - ret['comment'].append(result['comment']) + ret['comment'] = result['comment'] return ret else: ret['comment'].append('Adding new job {0} to schedule'.format(name)) @@ -175,7 +183,8 @@ def absent(name, **kwargs): result = __salt__['schedule.delete'](name, **kwargs) if not result['result']: ret['result'] = result['result'] - ret['comment'].append(result['comment']) + ret['comment'] = result['comment'] + return ret else: ret['comment'].append('Removed job {0} from schedule'.format(name)) else:
Fixes to schedule module and state for error conditions.
saltstack_salt
train
8727f956e1e59e899e8363951f62c8d95d96a950
diff --git a/pairwise.rb b/pairwise.rb index <HASH>..<HASH> 100644 --- a/pairwise.rb +++ b/pairwise.rb @@ -8,15 +8,15 @@ class Pairwise class << self def generate(inputs) - raise InvalidInput, "Minimum of 2 inputs are required to generate pairwise test set" if inputs.length < 2 || inputs[0].values[0].empty? && inputs[1].values[0].empty? + raw_inputs = inputs.map {|input| input.values[0]} - inputs_without_labels = inputs.map {|input| input.values[0]} + raise InvalidInput, "Minimum of 2 inputs are required to generate pairwise test set" unless valid_inputs?(raw_inputs) - test_set = generate_pairs_between(inputs_without_labels[0], [inputs_without_labels[1]]) + test_set = generate_pairs_between(raw_inputs[0], [raw_inputs[1]]) count = 0 - if inputs_without_labels.size > 2 - for i in 2.. inputs_without_labels.size-1 - test_set, pi = ipo_h(test_set, inputs_without_labels[i], inputs_without_labels[0..(i-1)]) + if raw_inputs.size > 2 + for i in 2..raw_inputs.size-1 + test_set, pi = ipo_h(test_set, raw_inputs[i], raw_inputs[0..(i-1)]) test_set = ipo_v(test_set, pi) end end @@ -25,26 +25,30 @@ class Pairwise private + def valid_inputs?(inputs) + inputs.length >= 2 && !inputs[0].empty? && !inputs[1].empty? + end + #TODO: Look at using zip when extending tests def ipo_h(test_set, parameter_i, inputs) pi = generate_pairs_between(parameter_i, inputs) q = parameter_i.size if test_set.size <= q - for j in 0..test_set.size do - extended_test = test_set[j] << parameter_i[j] + test_set.enum_for(:each_with_index).each do |test, j| + extended_test = test << parameter_i[j] pi = remove_pairs_covered_by(extended_test, pi) end else - for j in 0...q do + test_set[0...q].enum_for(:each_with_index).each do |test, j| extended_test = test_set[j] << parameter_i[j] pi = remove_pairs_covered_by(extended_test, pi) end - for i in q...test_set.size do - extended_test = select_value_that_covers_most_pairs(test_set[i], parameter_i, pi) + test_set[q..-1] = test_set[q..-1].map do |test| + extended_test = select_value_that_covers_most_pairs(test, parameter_i, pi) pi = remove_pairs_covered_by(extended_test, pi) - test_set[i] = extended_test + extended_test end end diff --git a/pairwise_spec.rb b/pairwise_spec.rb index <HASH>..<HASH> 100644 --- a/pairwise_spec.rb +++ b/pairwise_spec.rb @@ -5,22 +5,41 @@ require File.dirname(__FILE__) + '/pairwise' describe "pairwise" do - it "should be invalid when running with no input" do - lambda{ Pairwise.generate([]) }.should raise_error(Pairwise::InvalidInput) - lambda{ Pairwise.generate([{:A => []}]) }.should raise_error(Pairwise::InvalidInput) + context "invalid inputs" do + it "should be invalid when running with no input" do + lambda{ Pairwise.generate([]) }.should raise_error(Pairwise::InvalidInput) + lambda{ Pairwise.generate([{:A => []}]) }.should raise_error(Pairwise::InvalidInput) + end + + it "should be invalid when running with only 1 input" do + lambda{ Pairwise.generate([{:A => [:A1, :A2]}])}.should raise_error(Pairwise::InvalidInput) + end end - it "should be invalid when running with only 1 input" do - lambda{ Pairwise.generate([{:A => [:A1, :A2]}])}.should raise_error(Pairwise::InvalidInput) + it "should generate pairs for 2 parameters of 1 value" do + data = [{:A => [:A1]}, {:B => [:B1]}] + + Pairwise.generate(data).should == [[:A1, :B1]] end - it "should generate all pairs for two parameters" do - data = [{:A => [:A1, :A2]}, - {:B => [:B1, :B2]}] + it "should generate all pairs for 2 parameters of 2 values" do + data = [{:A => [:A1, :A2]}, {:B => [:B1, :B2]}] Pairwise.generate(data).should == [[:A1, :B1], [:A1, :B2], [:A2, :B1], [:A2, :B2]] end + it "should generate all pairs for 3 parameters of 1 value" do + data = [{:A => [:A1]}, {:B => [:B1]}, {:C => [:C1]}] + + Pairwise.generate(data).should == [[:A1, :B1, :C1]] + end + + it "should generate all pairs for 3 parameters of 1,1,2 values" do + data = [{:A => [:A1]}, {:B => [:B1]}, {:C => [:C1, :C2]}] + + Pairwise.generate(data).should == [[:A1, :B1, :C1], + [:A1, :B1, :C2]] + end describe 'ipo horizontal growth' do before(:each) do @@ -28,7 +47,7 @@ describe "pairwise" do @data = [[:A1, :A2],[:B1, :B2],[:C1 , :C2 , :C3 ]] end - + it "should return pairs extended with C's inputs" do test_set, _ = Pairwise.send(:ipo_h, @test_pairs, @data[2], @data[0..1]) @@ -48,7 +67,6 @@ describe "pairwise" do end end - context "with dataset with unequal input sizes" do it "should generate pairs for three paramters" do data = [{:A => [:A1, :A2]}, @@ -76,5 +94,5 @@ describe "pairwise" do [:A2, :B2, :C1]] end end - + end
Cleanup inputs first thing. Get ride of for loops for nicer each/maps
josephwilk_pairwise
train
0ebfd65080a1f085ce4023a05a913f5ba2448ae9
diff --git a/HISTORY.rst b/HISTORY.rst index <HASH>..<HASH> 100644 --- a/HISTORY.rst +++ b/HISTORY.rst @@ -13,6 +13,7 @@ v0.8.1 (NEXT) * Add BMDS version and python BMDS version to session dictionary outputs * Set exponential model direction based on dataset instead of letting model guess- this should fix failures where exponential models write "Error in closing opened file" to stdout * Improved documentation on model recommendation logic +* Revise ``ContinuousDataset.is_increasing`` for better edge-case checks v0.8.0 (2017-04-28) ------------------- diff --git a/bmds/datasets.py b/bmds/datasets.py index <HASH>..<HASH> 100644 --- a/bmds/datasets.py +++ b/bmds/datasets.py @@ -251,13 +251,11 @@ class ContinuousDataset(Dataset): @property def is_increasing(self): - inc = 0 - for i in range(len(self.means) - 1): - if self.means[i + 1] > self.means[i]: - inc += 1 - else: - inc -= 1 - return inc >= 0 + # increasing or decreasing with respect to control? + change = 0. + for i in range(1, len(self.means)): + change += self.means[i] - self.means[0] + return change >= 0 def drop_dose(self): """ diff --git a/tests/test_datasets.py b/tests/test_datasets.py index <HASH>..<HASH> 100644 --- a/tests/test_datasets.py +++ b/tests/test_datasets.py @@ -79,13 +79,27 @@ def test_dfile_outputs(): def test_is_increasing(): dummy4 = [1, 2, 3, 4] - ds = bmds.ContinuousDataset(doses=dummy4, ns=dummy4, means=dummy4, stdevs=dummy4) + ds = bmds.ContinuousDataset(doses=dummy4, ns=dummy4, + means=dummy4, stdevs=dummy4) assert ds.is_increasing is True rev = list(reversed(dummy4)) - ds = bmds.ContinuousDataset(doses=dummy4, ns=dummy4, means=rev, stdevs=dummy4) + ds = bmds.ContinuousDataset(doses=dummy4, ns=dummy4, + means=rev, stdevs=dummy4) assert ds.is_increasing is False + ds = bmds.ContinuousDataset(doses=dummy4, ns=dummy4, + means=[1, 2, 3, 0], stdevs=dummy4) + assert ds.is_increasing is True + + ds = bmds.ContinuousDataset(doses=dummy4, ns=dummy4, + means=[1, 3, 2, 1], stdevs=dummy4) + assert ds.is_increasing is True + + ds = bmds.ContinuousDataset(doses=dummy4, ns=dummy4, + means=[0, 2, -1, 0], stdevs=dummy4) + assert ds.is_increasing is True + def test_dose_drops(cidataset):
Revise ContinuousDataset.is_increasing for better edge-case checks
shapiromatron_bmds
train
079246fd371ad2b95ee44cb95488da6d6205cb3a
diff --git a/src/jquery.jcarousel.js b/src/jquery.jcarousel.js index <HASH>..<HASH> 100644 --- a/src/jquery.jcarousel.js +++ b/src/jquery.jcarousel.js @@ -113,10 +113,10 @@ return this; } - var all = this.items(); + var items = this.items().unbind('.jcarousel'); $.each(itemData, function(i, name) { - all.removeData('jcarousel' + name); + items.removeData('jcarousel' + name); }); $(window).unbind('resize.jcarousel', this.onWindowResize);
Also unbind events from items in destroy()
jsor_jcarousel
train
1677464e1d0eed3f2758c886a18242d6b7b26495
diff --git a/src/Sulu/Bundle/ContactBundle/Controller/ContactController.php b/src/Sulu/Bundle/ContactBundle/Controller/ContactController.php index <HASH>..<HASH> 100644 --- a/src/Sulu/Bundle/ContactBundle/Controller/ContactController.php +++ b/src/Sulu/Bundle/ContactBundle/Controller/ContactController.php @@ -538,6 +538,7 @@ class ContactController extends AbstractContactController // add urls, phones, emails, tags, bankAccounts, notes, addresses,.. $this->addNewContactRelations($contact, $request); + $this->processCategories($contact, $request->get('categories', array())); $em->persist($contact); $em->flush(); diff --git a/src/Sulu/Bundle/ContactBundle/Tests/Functional/Controller/ContactControllerTest.php b/src/Sulu/Bundle/ContactBundle/Tests/Functional/Controller/ContactControllerTest.php index <HASH>..<HASH> 100644 --- a/src/Sulu/Bundle/ContactBundle/Tests/Functional/Controller/ContactControllerTest.php +++ b/src/Sulu/Bundle/ContactBundle/Tests/Functional/Controller/ContactControllerTest.php @@ -570,6 +570,14 @@ class ContactControllerTest extends DatabaseTestCase 'salutation' => 'Sehr geehrte Frau Dr Mustermann', 'formOfAddress' => array( 'id' => 0 + ), + 'categories' => array( + array( + 'id' => 1 + ), + array( + 'id' => 2 + ) ) ) ); @@ -607,6 +615,8 @@ class ContactControllerTest extends DatabaseTestCase $this->assertEquals('Sehr geehrte Frau Dr Mustermann', $response->salutation); $this->assertEquals(0, $response->disabled); + $this->assertEquals(2, count($response->categories)); + $client->request('GET', '/api/contacts/' . $response->id); $response = json_decode($client->getResponse()->getContent()); @@ -639,6 +649,8 @@ class ContactControllerTest extends DatabaseTestCase $this->assertEquals(0, $response->formOfAddress); $this->assertEquals('Sehr geehrte Frau Dr Mustermann', $response->salutation); $this->assertEquals(0, $response->disabled); + + $this->assertEquals(2, count($response->categories)); } public function testPostWithoutAdditionalData() @@ -947,6 +959,7 @@ class ContactControllerTest extends DatabaseTestCase $this->assertEquals(0, $response->formOfAddress); $this->assertEquals('Sehr geehrter John', $response->salutation); $this->assertEquals(0, $response->disabled); + $this->assertEquals(2, count($response->categories)); $client->request('GET', '/api/contacts/' . $response->id); @@ -981,6 +994,8 @@ class ContactControllerTest extends DatabaseTestCase $this->assertEquals(0, $response->formOfAddress); $this->assertEquals('Sehr geehrter John', $response->salutation); $this->assertEquals(0, $response->disabled); + + $this->assertEquals(2, count($response->categories)); } public function testPutDeleteAndAddWithoutId()
fixed bug in contact post action and added testcases
sulu_sulu
train
6a0137b3add3704bcca5882bb0a8d3d3f8cd2871
diff --git a/tests/SpdxLicensesTest.php b/tests/SpdxLicensesTest.php index <HASH>..<HASH> 100644 --- a/tests/SpdxLicensesTest.php +++ b/tests/SpdxLicensesTest.php @@ -152,7 +152,7 @@ class SpdxLicensesTest extends TestCase { /** @var SPDXLicense $license */ $license = $this->licenses->getLicenseByIdentifier('AGPL-1.0-only'); - $this->assertIsArray($license); + $this->assertTrue(is_array($license)); $this->assertEquals('Affero General Public License v1.0 only', $license[0]); $this->assertFalse($license[1]); $this->assertStringStartsWith('https://spdx.org/licenses/', $license[2]); @@ -187,7 +187,7 @@ class SpdxLicensesTest extends TestCase /** @var SPDXLicenseException $license */ $license = $this->licenses->getExceptionByIdentifier('Font-exception-2.0'); - $this->assertIsArray($license); + $this->assertTrue(is_array($license)); $this->assertSame('Font exception 2.0', $license[0]); }
Avoid using assertIsArray which is missing on <I>
composer_spdx-licenses
train
a70318efe3f66209645893073679a6c21230e1fc
diff --git a/lib/rack/jekyll/version.rb b/lib/rack/jekyll/version.rb index <HASH>..<HASH> 100644 --- a/lib/rack/jekyll/version.rb +++ b/lib/rack/jekyll/version.rb @@ -1,7 +1,7 @@ module Rack class Jekyll def self.version - '0.4.3' + '0.4.5' end end end
Release <I> Replacement for gem releases <I> and <I>, which were not properly pushed to RubyGems.org (wrong commit). It only provides a tiny fix for commit <I>ee<I>b.
adaoraul_rack-jekyll
train
3dfce2a6c122fe7fb54ea9fcc22b175107e078a2
diff --git a/niworkflows/utils/spaces.py b/niworkflows/utils/spaces.py index <HASH>..<HASH> 100644 --- a/niworkflows/utils/spaces.py +++ b/niworkflows/utils/spaces.py @@ -423,8 +423,8 @@ class SpatialReferences: spaces = [spaces] self.__iadd__(spaces) - if checkpoint is True: - self.checkpoint() + if checkpoint is True: + self.checkpoint() def __iadd__(self, b): """Append a list of transforms to the internal list."""
enh: allow checkpointing only if spaces are given at instantiation
poldracklab_niworkflows
train
5e9f487b61e8e0cef2ec2ad0e5b84a7c339dee45
diff --git a/server/const.go b/server/const.go index <HASH>..<HASH> 100644 --- a/server/const.go +++ b/server/const.go @@ -40,7 +40,7 @@ var ( const ( // VERSION is the current version for the server. - VERSION = "2.2.0-beta.3" + VERSION = "2.2.0-beta.4" // PROTO is the currently supported protocol. // 0 was the original diff --git a/server/filestore.go b/server/filestore.go index <HASH>..<HASH> 100644 --- a/server/filestore.go +++ b/server/filestore.go @@ -931,7 +931,8 @@ func (mb *msgBlock) updateAccounting(seq uint64, ts int64, rl uint64) { mb.first.seq = seq mb.first.ts = ts } - mb.last.seq = seq + // Need atomics here for selectMsgBlock speed. + atomic.StoreUint64(&mb.last.seq, seq) mb.last.ts = ts mb.bytes += rl mb.msgs++ @@ -1409,7 +1410,9 @@ func (fs *fileStore) flushPendingWrites() error { for lbb := fs.wmb.Len(); lbb > 0; lbb = fs.wmb.Len() { n, err := fs.wmb.WriteTo(mb.mfd) if err != nil { - fs.removeMsgBlockIndex(mb) + mb.mu.Lock() + mb.removeIndex() + mb.mu.Unlock() return err } @@ -1619,7 +1622,9 @@ func (fs *fileStore) Purge() uint64 { fs.lmb = nil for _, mb := range blks { + mb.mu.Lock() fs.removeMsgBlock(mb) + mb.mu.Unlock() } // Now place new write msg block with correct info. fs.newMsgBlockForWrite() @@ -1645,7 +1650,8 @@ func (fs *fileStore) numMsgBlocks() int { return len(fs.blks) } -func (fs *fileStore) removeMsgBlockIndex(mb *msgBlock) { +// Lock should be held. +func (mb *msgBlock) removeIndex() { if mb.ifd != nil { mb.ifd.Close() mb.ifd = nil @@ -1654,10 +1660,9 @@ func (fs *fileStore) removeMsgBlockIndex(mb *msgBlock) { } // Removes the msgBlock -// Lock should be held. +// Both locks should be held. func (fs *fileStore) removeMsgBlock(mb *msgBlock) { - fs.removeMsgBlockIndex(mb) - + mb.removeIndex() if mb.mfd != nil { mb.mfd.Close() mb.mfd = nil diff --git a/server/memstore.go b/server/memstore.go index <HASH>..<HASH> 100644 --- a/server/memstore.go +++ b/server/memstore.go @@ -278,7 +278,13 @@ func (ms *memStore) removeMsg(seq uint64, secure bool) bool { ss = memStoreMsgSize(sm.subj, sm.msg) ms.state.Bytes -= ss if seq == ms.state.FirstSeq { - ms.state.FirstSeq++ + var nseq uint64 + for nseq = ms.state.FirstSeq + 1; nseq < ms.state.LastSeq; nseq++ { + if _, ok := ms.msgs[nseq]; ok { + break + } + } + ms.state.FirstSeq = nseq } if secure { rand.Read(sm.msg) diff --git a/test/jetstream_test.go b/test/jetstream_test.go index <HASH>..<HASH> 100644 --- a/test/jetstream_test.go +++ b/test/jetstream_test.go @@ -637,7 +637,7 @@ func TestJetStreamCreateConsumer(t *testing.T) { defer sub.Unsubscribe() nc.Flush() - // Subjects can not be AckAll. + // Filtered subjects can not be AckAll. if _, err := mset.AddConsumer(&server.ConsumerConfig{ Delivery: delivery, DeliverAll: true, @@ -4085,14 +4085,11 @@ func TestJetStreamDeleteMsg(t *testing.T) { s := RunBasicJetStreamServer() defer s.Shutdown() - config := s.JetStreamConfig() - if config == nil { - t.Fatalf("Expected non-nil config") + if config := s.JetStreamConfig(); config != nil && config.StoreDir != "" { + defer os.RemoveAll(config.StoreDir) } - defer os.RemoveAll(config.StoreDir) - cfg := &server.StreamConfig{Name: "foo", Storage: server.FileStorage} - mset, err := s.GlobalAccount().AddStream(cfg) + mset, err := s.GlobalAccount().AddStream(c.mconfig) if err != nil { t.Fatalf("Unexpected error adding stream: %v", err) } @@ -4137,7 +4134,7 @@ func TestJetStreamDeleteMsg(t *testing.T) { // Delete one from the middle deleteAndCheck(5, 1) - // Now make sure sequences are update properly. + // Now make sure sequences are updated properly. // Delete first msg. deleteAndCheck(1, 2) // Now last @@ -4154,6 +4151,11 @@ func TestJetStreamDeleteMsg(t *testing.T) { deleteAndCheck(16, 12) deleteAndCheck(20, 12) + // Only file storage beyond here. + if c.mconfig.Storage == server.MemoryStorage { + return + } + // Shutdown the server. s.Shutdown()
Fixes for test and locking, bumped version
nats-io_gnatsd
train
067fd6c33e2031f52168cc5f03914e941d7f9830
diff --git a/test/Mustache/Test/Functional/InheritanceTest.php b/test/Mustache/Test/Functional/InheritanceTest.php index <HASH>..<HASH> 100644 --- a/test/Mustache/Test/Functional/InheritanceTest.php +++ b/test/Mustache/Test/Functional/InheritanceTest.php @@ -286,6 +286,29 @@ class Mustache_Test_Functional_InheritanceTest extends PHPUnit_Framework_TestCas ); } + public function testInheritSpacingWhenOverridingAPartial() + { + $partials = array( + 'parent' => 'collaborate_and{{$id}}{{/id}}', + 'child' => '{{<parent}}{{$id}}_listen{{/id}}{{/parent}}', + ); + + $this->mustache->setPartials($partials); + + $tpl = $this->mustache->loadTemplate( + 'stop: + {{>child}}' + ); + + $data = array(); + + $this->assertEquals( + 'stop: + collaborate_and_listen', + $tpl->render($data) + ); + } + public function testOverrideOneSubstitutionButNotTheOther() { $partials = array(
Failing Test For Inheritance Indentation inside a replacement variable.
bobthecow_mustache.php
train
81210fde5f832353ae0124198938f82585cc8e28
diff --git a/core/src/main/java/io/undertow/server/protocol/ajp/AjpServerRequestConduit.java b/core/src/main/java/io/undertow/server/protocol/ajp/AjpServerRequestConduit.java index <HASH>..<HASH> 100644 --- a/core/src/main/java/io/undertow/server/protocol/ajp/AjpServerRequestConduit.java +++ b/core/src/main/java/io/undertow/server/protocol/ajp/AjpServerRequestConduit.java @@ -265,16 +265,13 @@ public class AjpServerRequestConduit extends AbstractStreamSourceConduit<StreamS remaining -= read; } this.totalRead += read; - if (remaining == 0) { - this.state = STATE_FINISHED; - if (finishListener != null) { - finishListener.handleEvent(this); + if (remaining != 0) { + if (chunkRemaining == 0) { + headerBuffer.clear(); + this.state = STATE_SEND_REQUIRED; + } else { + this.state = (state & ~STATE_MASK) | chunkRemaining; } - } else if (chunkRemaining == 0) { - headerBuffer.clear(); - this.state = STATE_SEND_REQUIRED; - } else { - this.state = (state & ~STATE_MASK) | chunkRemaining; } return read; } finally {
Fix issue with AJP request stream
undertow-io_undertow
train
129d4ff927969d13a67d2e64d3caf1163c6837d2
diff --git a/salt/modules/selinux.py b/salt/modules/selinux.py index <HASH>..<HASH> 100644 --- a/salt/modules/selinux.py +++ b/salt/modules/selinux.py @@ -10,10 +10,10 @@ Execute calls on selinux documentation for your distro to ensure that the proper packages are installed. ''' -from __future__ import absolute_import # Import python libs import os +from __future__ import absolute_import # Import salt libs import salt.utils @@ -163,7 +163,7 @@ def setsebools(pairs, persist=False): cmd = 'setsebool -P ' else: cmd = 'setsebool ' - for boolean, value in list(pairs.items()): + for boolean, value in pairs.items(): cmd = '{0} {1}={2}'.format(cmd, boolean, value) return not __salt__['cmd.retcode'](cmd)
List call not needed. Changing it back to what it was
saltstack_salt
train
db5e3b268aeac9b0a8375a003339d3d0fbfc56b9
diff --git a/packages/react-swipeable-views/src/SwipeableViews.js b/packages/react-swipeable-views/src/SwipeableViews.js index <HASH>..<HASH> 100644 --- a/packages/react-swipeable-views/src/SwipeableViews.js +++ b/packages/react-swipeable-views/src/SwipeableViews.js @@ -429,6 +429,11 @@ class SwipeableViews extends Component { onTouchStart, } = this.props; + // Latency and rapid rerenders on some devices can leave a period where rootNode briefly equals null + if (this.rootNode === null){ + return; + } + if (onTouchStart) { onTouchStart(event); } @@ -471,6 +476,11 @@ class SwipeableViews extends Component { this.handleTouchStart(event); return; } + + // Latency and rapid rerenders on some devices can leave a period where rootNode briefly equals null + if (this.rootNode === null) { + return; + } // We are not supposed to hanlde this touch move. if (nodeHowClaimedTheScroll !== null && nodeHowClaimedTheScroll !== this.rootNode) {
Handle ref loss gracefully Gracefully handle a reference equaling null
oliviertassinari_react-swipeable-views
train
ab827eaf935aba776715c4693ec9f320008a6708
diff --git a/sqlparse/filters.py b/sqlparse/filters.py index <HASH>..<HASH> 100644 --- a/sqlparse/filters.py +++ b/sqlparse/filters.py @@ -347,6 +347,7 @@ class ReindentFilter: nl = self.nl() added.add(nl) tlist.insert_before(token, nl) + offset += 1 token = _next_token(tlist.token_index(nl) + offset) def _split_statements(self, tlist):
Update offset when adding line break (fixes <I>). This change fixes a regression introduced in 8c5c<I>ac<I>ab7d0c5e<I>c<I>f<I>f9.
andialbrecht_sqlparse
train
a89454c759bc5099aa697bd8b99c5163d97d9bff
diff --git a/asciimathml.py b/asciimathml.py index <HASH>..<HASH> 100644 --- a/asciimathml.py +++ b/asciimathml.py @@ -198,22 +198,28 @@ def trace_parser(p): return wrapped -def parse_expr(s, required=False): +def parse_expr(s, siblings, required=False): s, n = parse_m(s, required=required) if not n is None: - if n.get('_opening', False): + # Being both an _opening and a _closing element is a trait of + # symmetrical delimiters (e.g. ||). + # In that case, act as an opening delimiter only if there is not + # already one of the same kind among the preceding siblings. + if n.get('_opening', False) \ + and (not n.get('_closing', False) \ + or find_node_backwards(siblings, n.text) == -1): s, children = parse_exprs(s, [n], inside_parens=True) n = El('mrow', *children) if n.tag == 'mtext': s, n = parse_string(s) elif n.get('_arity', 0) == 1: - s, m = parse_expr(s, True) + s, m = parse_expr(s, [], True) n = unary(n, m, n.get('_swap', False)) elif n.get('_arity', 0) == 2: - s, m1 = parse_expr(s, True) - s, m2 = parse_expr(s, True) + s, m1 = parse_expr(s, [], True) + s, m2 = parse_expr(s, [], True) n = binary(n, m1, m2, n.get('_swap', False)) return s, n @@ -225,6 +231,13 @@ def find_node(ns, text): return -1 +def find_node_backwards(ns, text): + for i, n in enumerate(reversed(ns)): + if n.text == text: + return len(ns) - i + + return -1 + def nodes_to_row(row): mrow = El('mtr') @@ -261,7 +274,7 @@ def parse_exprs(s, nodes=None, inside_parens=False): inside_matrix = False while True: - s, n = parse_expr(s) + s, n = parse_expr(s, nodes) if not n is None: nodes.append(n) @@ -448,6 +461,7 @@ Symbol(input="]", el=El("mo", "]", _closing=True)) Symbol(input="{", el=El("mo", "{", _opening=True)) Symbol(input="}", el=El("mo", "}", _closing=True)) Symbol(input="|", el=El("mo", u"|", _opening=True, _closing=True)) +Symbol(input="||", el=El("mo", u"||", _opening=True, _closing=True)) Symbol(input="(:", el=El("mo", u"\u2329", _opening=True)) Symbol(input=":)", el=El("mo", u"\u232A", _closing=True)) Symbol(input="<<", el=El("mo", u"\u2329", _opening=True))
handle symmetrical delimiters by passing more contest to parse_expr()
favalex_python-asciimathml
train
f26ef0b79d1e9fa5233e0ac8a498f72343b50dc2
diff --git a/src/tanokInReact.js b/src/tanokInReact.js index <HASH>..<HASH> 100644 --- a/src/tanokInReact.js +++ b/src/tanokInReact.js @@ -23,7 +23,6 @@ export class TanokInReact extends React.Component { this.view = view; this.tanokStream = tanokStream; this.store = store; - } componentWillUnmount() { @@ -34,7 +33,7 @@ export class TanokInReact extends React.Component { render() { return ( <Root store={this.store} tanokStream={this.tanokStream}> - <this.view /> + <this.view tanokStream={this.tanokStream} {...this.store.getState()} /> </Root> ) } diff --git a/test/tanokInReact.test.js b/test/tanokInReact.test.js index <HASH>..<HASH> 100644 --- a/test/tanokInReact.test.js +++ b/test/tanokInReact.test.js @@ -5,7 +5,10 @@ import React from 'react'; import expect from 'expect'; import { mount } from 'enzyme'; -import { TanokInReact, TanokDispatcher, on, connect } from '../src/tanok.js'; +import { + TanokInReact, TanokDispatcher, + on, connect, tanokComponent +} from '../src/tanok.js'; describe('tanokInReact', () => { @@ -27,7 +30,7 @@ describe('tanokInReact', () => { } } - it('tanokInReact renderred as want', function (done) { + it('with store renderred as want', function (done) { const update = new TestDispatcher; const eventStream = new Rx.Subject(); const testMiddleware = (stream) => { @@ -52,4 +55,29 @@ describe('tanokInReact', () => { done(); }); + @tanokComponent + class TestComponent2 extends React.Component { + render() { + return ( + <div>{this.props.number}</div> + ); + } + } + + it('without store renderred as want', function (done) { + const update = new TestDispatcher; + const eventStream = new Rx.Subject(); + const wrapper = mount( + <TanokInReact + initialState={{ number: 3 }} + update={update} + view={TestComponent2} + /> + ); + const comp = wrapper.find(TestComponent2).children(); + expect(comp.html()).toEqual('<div>3</div>'); + wrapper.unmount(); + done(); + }); + });
Fixed v1/v2 compatability in TanokInReact
brabadu_tanok
train
42648db87910e392170b6c9c41545dddab0aa1a2
diff --git a/descent/utils.py b/descent/utils.py index <HASH>..<HASH> 100644 --- a/descent/utils.py +++ b/descent/utils.py @@ -2,7 +2,7 @@ from __future__ import (absolute_import, division, print_function, unicode_liter import sys import numpy as np from toolz.curried import concat, map, pipe -from toolz.functoolz import isunary +from toolz.functoolz import is_arity from toolz import first, second, compose from collections import OrderedDict from multipledispatch import dispatch @@ -77,7 +77,7 @@ def lrucache(func, size): """ # this only works for unary functions - assert isunary(func), "The function must be unary (take a single argument)" + assert is_arity(1, func), "The function must be unary (take a single argument)" # initialize the cache cache = OrderedDict()
Updated to work with the latest version of toolz
nirum_descent
train
0bc4ecc10b353160827de39badda5ac1e2e17ed0
diff --git a/libzfs/utils/jsonify.py b/libzfs/utils/jsonify.py index <HASH>..<HASH> 100644 --- a/libzfs/utils/jsonify.py +++ b/libzfs/utils/jsonify.py @@ -31,7 +31,12 @@ def jsonify(o, max_depth=-1, parse_enums=PARSE_KEEP): return o max_depth -= 1 if isinstance(o, dict): - return {key: jsonify(getattr(o, key, value), max_depth=max_depth, parse_enums=parse_enums) + def _getter(key, value): + other = getattr(o, key, value) + if callable(other): + other = value + return value + return {key: jsonify(_getter(key, value), max_depth=max_depth, parse_enums=parse_enums) for key, value in six.iteritems(o)} elif isinstance(o, list): return [jsonify(x, max_depth=max_depth, parse_enums=parse_enums) for x in o]
-Fix: Don't use callables when jsonifying a dict.. that way keys that are also callables on a dict (keys, items, values and the sorts) don't cause issues.
Xaroth_libzfs-python
train
07b1811ceee85ce730a1911df47bbed9b49347a7
diff --git a/vlcp/event/ratelimiter.py b/vlcp/event/ratelimiter.py index <HASH>..<HASH> 100644 --- a/vlcp/event/ratelimiter.py +++ b/vlcp/event/ratelimiter.py @@ -58,6 +58,8 @@ class RateLimiter(object): `limit` number of "resources" are permitted. :param use: number of "resouces" to be used. + + :return: True if is limited """ c = self._counter self._counter = c + use @@ -66,3 +68,6 @@ class RateLimiter(object): if c >= self._bottom_line: # Limited await RateLimitingEvent.createMatcher(self, c // self._limit) + return True + else: + return False diff --git a/vlcp/protocol/zookeeper.py b/vlcp/protocol/zookeeper.py index <HASH>..<HASH> 100644 --- a/vlcp/protocol/zookeeper.py +++ b/vlcp/protocol/zookeeper.py @@ -21,6 +21,7 @@ from vlcp.event.ratelimiter import RateLimiter from vlcp.event.future import RoutineFuture from vlcp.event.runnable import RoutineException from vlcp.event.runnable import _close_generator +from vlcp.event.lock import Lock @withIndices('state', 'connection', 'connmark', 'createby') class ZooKeeperConnectionStateEvent(Event): @@ -116,7 +117,7 @@ class ZooKeeper(Protocol): priority = ZooKeeperWriteEvent.HIGH), None, self.writequeuesize) # Use limiter to limit the request serialization in one iteration - connection._rate_limiter = (RateLimiter(256, connection), RateLimiter(256, connection)) + connection._rate_limiter = (RateLimiter(0xfffff, connection), RateLimiter(0xfffff, connection)) await self.reconnect_init(connection) async def reconnect_init(self, connection): @@ -212,7 +213,7 @@ class ZooKeeper(Protocol): timeout, r = await container.execute_with_timeout( 10, container.with_callback( - self.requests(connection, extrapackets, container, priority=ZooKeeperWriteEvent.HIGH), + self.requests(connection, extrapackets, container, priority=ZooKeeperWriteEvent.MIDDLE), callback, handshake_matcher ) @@ -253,34 +254,35 @@ class ZooKeeper(Protocol): :return: (matchers, sendall), where matchers are event matchers for the requests; sendall is an async function to send to requests. Use `await sendall()` to send the requests. ''' - matchers = [] - for r in requests: - xid = self._pre_assign_xid(connection, r) - resp_matcher = ZooKeeperResponseEvent.createMatcher(connection, connection.connmark, None, xid) - matchers.append(resp_matcher) - alldata = [] - for i in range(0, len(requests), 100): - size = min(100, len(requests) - i) - if priority < ZooKeeperWriteEvent.HIGH: - await connection._rate_limiter[priority].limit(size) - for j in range(i, i + size): - r = requests[j] + async with Lock((connection, 'async_requests', priority), connection.scheduler): + matchers = [] + for r in requests: + xid = self._pre_assign_xid(connection, r) + resp_matcher = ZooKeeperResponseEvent.createMatcher(connection, connection.connmark, None, xid) + matchers.append(resp_matcher) + alldata = [] + for r in requests: + if priority < ZooKeeperWriteEvent.HIGH: + # Test if already limited by consuming 1 byte + await connection._rate_limiter[priority].limit(1) data = r._tobytes() if len(data) >= 0xfffff: # This is the default limit of ZooKeeper, reject this request raise ZooKeeperRequestTooLargeException('The request is %d bytes which is too large for ZooKeeper' % len(data)) + if priority < ZooKeeperWriteEvent.HIGH: + await connection._rate_limiter[priority].limit(len(data) - 1) alldata.append(data) - for r in requests: - self._register_xid(connection, r) - async def _sendall(): - sent_requests = [] - for data in alldata: - try: - sent_requests.append(await self._senddata(connection, data, container, priority)) - except ZooKeeperRetryException: - raise ZooKeeperRetryException(sent_requests) - return sent_requests - return (matchers, _sendall) + for r in requests: + self._register_xid(connection, r) + async def _sendall(): + sent_requests = [] + for data in alldata: + try: + sent_requests.append(await self._senddata(connection, data, container, priority)) + except ZooKeeperRetryException: + raise ZooKeeperRetryException(sent_requests) + return sent_requests + return (matchers, _sendall) async def requests(self, connection, requests, container = None, callback = None, priority = 0): ''' diff --git a/vlcp/service/debugging/console.py b/vlcp/service/debugging/console.py index <HASH>..<HASH> 100644 --- a/vlcp/service/debugging/console.py +++ b/vlcp/service/debugging/console.py @@ -274,8 +274,10 @@ console_help() except SystemExit: pass finally: + async def _quit(): + scheduler.quit() + self.sendEventQueue.put((ConsoleServiceCall(routine=_quit()),)) self.sendEventQueue.put(None) - scheduler.quit() if self.startinconsole: print('Wait for scheduler end, this may take some time...') t.join()
- fix console threading race - limit with structure size
hubo1016_vlcp
train
6af0d2737c559642b711903b09e1f380e1c10c4f
diff --git a/sphinx_gallery/docs_resolv.py b/sphinx_gallery/docs_resolv.py index <HASH>..<HASH> 100644 --- a/sphinx_gallery/docs_resolv.py +++ b/sphinx_gallery/docs_resolv.py @@ -383,9 +383,10 @@ def _embed_code_links(app, gallery_conf, gallery_dir): parts = name.split('.') name_html = period.join(orig_pattern % part for part in parts) - str_repl[name_html] = link_pattern % (link, - '%s.%s' % (cobj['module'], cobj['name']), - name_html) + full_function_name = '%s.%s' % ( + cobj['module'], cobj['name']) + str_repl[name_html] = link_pattern % ( + link, full_function_name, name_html) # do the replacement in the html file # ensure greediness
COSMIT break nested formatting on two lines
sphinx-gallery_sphinx-gallery
train
c3dd6074b0f07cd7e57d677cc06b4c57a302a02f
diff --git a/container/container_unix.go b/container/container_unix.go index <HASH>..<HASH> 100644 --- a/container/container_unix.go +++ b/container/container_unix.go @@ -118,7 +118,9 @@ func (container *Container) NetworkMounts() []Mount { if _, err := os.Stat(container.ResolvConfPath); err != nil { logrus.Warnf("ResolvConfPath set to %q, but can't stat this filename (err = %v); skipping", container.ResolvConfPath, err) } else { - label.Relabel(container.ResolvConfPath, container.MountLabel, shared) + if !container.HasMountFor("/etc/resolv.conf") { + label.Relabel(container.ResolvConfPath, container.MountLabel, shared) + } writable := !container.HostConfig.ReadonlyRootfs if m, exists := container.MountPoints["/etc/resolv.conf"]; exists { writable = m.RW @@ -135,7 +137,9 @@ func (container *Container) NetworkMounts() []Mount { if _, err := os.Stat(container.HostnamePath); err != nil { logrus.Warnf("HostnamePath set to %q, but can't stat this filename (err = %v); skipping", container.HostnamePath, err) } else { - label.Relabel(container.HostnamePath, container.MountLabel, shared) + if !container.HasMountFor("/etc/hostname") { + label.Relabel(container.HostnamePath, container.MountLabel, shared) + } writable := !container.HostConfig.ReadonlyRootfs if m, exists := container.MountPoints["/etc/hostname"]; exists { writable = m.RW @@ -152,7 +156,9 @@ func (container *Container) NetworkMounts() []Mount { if _, err := os.Stat(container.HostsPath); err != nil { logrus.Warnf("HostsPath set to %q, but can't stat this filename (err = %v); skipping", container.HostsPath, err) } else { - label.Relabel(container.HostsPath, container.MountLabel, shared) + if !container.HasMountFor("/etc/hosts") { + label.Relabel(container.HostsPath, container.MountLabel, shared) + } writable := !container.HostConfig.ReadonlyRootfs if m, exists := container.MountPoints["/etc/hosts"]; exists { writable = m.RW diff --git a/daemon/create.go b/daemon/create.go index <HASH>..<HASH> 100644 --- a/daemon/create.go +++ b/daemon/create.go @@ -142,8 +142,8 @@ func (daemon *Daemon) create(params types.ContainerCreateConfig) (retC *containe return container, nil } -func (daemon *Daemon) generateSecurityOpt(ipcMode containertypes.IpcMode, pidMode containertypes.PidMode) ([]string, error) { - if ipcMode.IsHost() || pidMode.IsHost() { +func (daemon *Daemon) generateSecurityOpt(ipcMode containertypes.IpcMode, pidMode containertypes.PidMode, privileged bool) ([]string, error) { + if ipcMode.IsHost() || pidMode.IsHost() || privileged { return label.DisableSecOpt(), nil } diff --git a/daemon/daemon_unix.go b/daemon/daemon_unix.go index <HASH>..<HASH> 100644 --- a/daemon/daemon_unix.go +++ b/daemon/daemon_unix.go @@ -247,7 +247,7 @@ func (daemon *Daemon) adaptContainerSettings(hostConfig *containertypes.HostConf } var err error if hostConfig.SecurityOpt == nil { - hostConfig.SecurityOpt, err = daemon.generateSecurityOpt(hostConfig.IpcMode, hostConfig.PidMode) + hostConfig.SecurityOpt, err = daemon.generateSecurityOpt(hostConfig.IpcMode, hostConfig.PidMode, hostConfig.Privileged) if err != nil { return err }
Multiple fixes for SELinux labels. SELinux labeling should be disabled when using --privileged mode /etc/hosts, /etc/resolv.conf, /etc/hostname should not be relabeled if they are volume mounted into the container.
containers_storage
train
ce5ae9c7fe14648a27c8ed7c432fa921e7be7b00
diff --git a/options.go b/options.go index <HASH>..<HASH> 100644 --- a/options.go +++ b/options.go @@ -206,6 +206,7 @@ type Options struct { Interlace bool StripMetadata bool Trim bool + Lossless bool Extend Extend Rotate Angle Background Color diff --git a/resizer.go b/resizer.go index <HASH>..<HASH> 100644 --- a/resizer.go +++ b/resizer.go @@ -165,6 +165,7 @@ func saveImage(image *C.VipsImage, o Options) ([]byte, error) { Interpretation: o.Interpretation, OutputICC: o.OutputICC, StripMetadata: o.StripMetadata, + Lossless: o.Lossless, } // Finally get the resultant buffer return vipsSave(image, saveOptions) diff --git a/vips.go b/vips.go index <HASH>..<HASH> 100644 --- a/vips.go +++ b/vips.go @@ -56,6 +56,7 @@ type vipsSaveOptions struct { Interlace bool NoProfile bool StripMetadata bool + Lossless bool OutputICC string // Absolute path to the output ICC profile Interpretation Interpretation } @@ -423,6 +424,7 @@ func vipsSave(image *C.VipsImage, o vipsSaveOptions) ([]byte, error) { interlace := C.int(boolToInt(o.Interlace)) quality := C.int(o.Quality) strip := C.int(boolToInt(o.StripMetadata)) + lossless := C.int(boolToInt(o.Lossless)) if o.Type != 0 && !IsTypeSupportedSave(o.Type) { return nil, fmt.Errorf("VIPS cannot save to %#v", ImageTypes[o.Type]) @@ -430,7 +432,7 @@ func vipsSave(image *C.VipsImage, o vipsSaveOptions) ([]byte, error) { var ptr unsafe.Pointer switch o.Type { case WEBP: - saveErr = C.vips_webpsave_bridge(tmpImage, &ptr, &length, strip, quality) + saveErr = C.vips_webpsave_bridge(tmpImage, &ptr, &length, strip, quality, lossless) case PNG: saveErr = C.vips_pngsave_bridge(tmpImage, &ptr, &length, strip, C.int(o.Compression), quality, interlace) case TIFF: diff --git a/vips.h b/vips.h index <HASH>..<HASH> 100644 --- a/vips.h +++ b/vips.h @@ -306,10 +306,11 @@ vips_pngsave_bridge(VipsImage *in, void **buf, size_t *len, int strip, int compr } int -vips_webpsave_bridge(VipsImage *in, void **buf, size_t *len, int strip, int quality) { +vips_webpsave_bridge(VipsImage *in, void **buf, size_t *len, int strip, int quality, int lossless) { return vips_webpsave_buffer(in, buf, len, "strip", INT_TO_GBOOLEAN(strip), "Q", quality, + "lossless", INT_TO_GBOOLEAN(lossless), NULL ); }
Add lossless option for saving webp
h2non_bimg
train
c6fd9048369ecbe38181f6f6a6231ecd2b4a346b
diff --git a/lib/scoped_search/auto_complete_builder.rb b/lib/scoped_search/auto_complete_builder.rb index <HASH>..<HASH> 100644 --- a/lib/scoped_search/auto_complete_builder.rb +++ b/lib/scoped_search/auto_complete_builder.rb @@ -185,13 +185,13 @@ module ScopedSearch opts = value_conditions(field, val) if field.key_field - klass = field.key_klass opts.merge!(:conditions => {field.key_field => key_name}) - return klass.first(opts).send(field.relation).map(&field.field).uniq + key_klass = field.key_klass.first(opts) + raise ScopedSearch::QueryNotSupported, "Field '#{key_name}' not recognized for searching!" unless key_klass + return key_klass.send(field.relation).map(&field.field).uniq else - klass = field.klass opts.merge!(:limit => 10, :select => field.field, :group => field.field ) - return klass.all(opts).map(&field.field).compact + return field.klass.all(opts).map(&field.field).compact end end
value auto completer handle better a case where in a key-value the key doesn't exist
wvanbergen_scoped_search
train
7f9747882b2ce904545a634e5e38e0671fa62ab8
diff --git a/src/main/java/com/googlecode/lanterna/terminal/swing/TerminalEmulatorDeviceConfiguration.java b/src/main/java/com/googlecode/lanterna/terminal/swing/TerminalEmulatorDeviceConfiguration.java index <HASH>..<HASH> 100644 --- a/src/main/java/com/googlecode/lanterna/terminal/swing/TerminalEmulatorDeviceConfiguration.java +++ b/src/main/java/com/googlecode/lanterna/terminal/swing/TerminalEmulatorDeviceConfiguration.java @@ -144,21 +144,116 @@ public class TerminalEmulatorDeviceConfiguration { } /** - * Returns a copy of this device configuration but with a different size of the scrollback buffer - * @param lineBufferScrollbackSize Size of the scrollback buffer (in number of lines) the copy should have - * @return Copy of this device configuration with a specified size for the scrollback buffer + * Copies the current configuration. The new object has the given value. + * @param blinkLengthInMilliSeconds How many milliseconds does a 'blink' last + * @return A copy of the current configuration with the changed value. + */ + public TerminalEmulatorDeviceConfiguration withBlinkLengthInMilliSeconds(int blinkLengthInMilliSeconds) { + if (this.blinkLengthInMilliSeconds == blinkLengthInMilliSeconds) { + return this; + } else { + return new TerminalEmulatorDeviceConfiguration( + this.lineBufferScrollbackSize, + blinkLengthInMilliSeconds, + this.cursorStyle, + this.cursorColor, + this.cursorBlinking, + this.clipboardAvailable); + } + } + + /** + * Copies the current configuration. The new object has the given value. + * @param lineBufferScrollbackSize How many lines of scrollback buffer should the terminal save? + * @return A copy of the current configuration with the changed value. */ public TerminalEmulatorDeviceConfiguration withLineBufferScrollbackSize(int lineBufferScrollbackSize) { if(this.lineBufferScrollbackSize == lineBufferScrollbackSize) { return this; - } - else { + } else { return new TerminalEmulatorDeviceConfiguration( lineBufferScrollbackSize, - blinkLengthInMilliSeconds, + this.blinkLengthInMilliSeconds, + this.cursorStyle, + this.cursorColor, + this.cursorBlinking, + this.clipboardAvailable); + } + } + + /** + * Copies the current configuration. The new object has the given value. + * @param cursorStyle Style of the terminal text cursor + * @return A copy of the current configuration with the changed value. + */ + public TerminalEmulatorDeviceConfiguration withCursorStyle(CursorStyle cursorStyle) { + if(this.cursorStyle == cursorStyle) { + return this; + } else { + return new TerminalEmulatorDeviceConfiguration( + this.lineBufferScrollbackSize, + this.blinkLengthInMilliSeconds, cursorStyle, + this.cursorColor, + this.cursorBlinking, + this.clipboardAvailable); + } + } + + /** + * Copies the current configuration. The new object has the given value. + * @param cursorColor Color of the terminal text cursor + * @return A copy of the current configuration with the changed value. + */ + public TerminalEmulatorDeviceConfiguration withCursorColor(TextColor cursorColor) { + if(this.cursorColor == cursorColor) { + return this; + } else { + return new TerminalEmulatorDeviceConfiguration( + this.lineBufferScrollbackSize, + this.blinkLengthInMilliSeconds, + this.cursorStyle, cursorColor, - cursorBlinking); + this.cursorBlinking, + this.clipboardAvailable); + } + } + + /** + * Copies the current configuration. The new object has the given value. + * @param cursorBlinking Should the terminal text cursor blink? + * @return A copy of the current configuration with the changed value. + */ + public TerminalEmulatorDeviceConfiguration withCursorBlinking(boolean cursorBlinking) { + if(this.cursorBlinking == cursorBlinking) { + return this; + } else { + return new TerminalEmulatorDeviceConfiguration( + this.lineBufferScrollbackSize, + this.blinkLengthInMilliSeconds, + this.cursorStyle, + this.cursorColor, + cursorBlinking, + this.clipboardAvailable); + } + } + + /** + * Copies the current configuration. The new object has the given value. + * @param clipboardAvailable Should the terminal support pasting text from the clipboard? + * @return A copy of the current configuration with the changed value. + */ + public TerminalEmulatorDeviceConfiguration withClipboardAvailable(boolean clipboardAvailable) { + if(this.clipboardAvailable == clipboardAvailable) { + return this; + } else { + return new TerminalEmulatorDeviceConfiguration( + this.lineBufferScrollbackSize, + this.blinkLengthInMilliSeconds, + this.cursorStyle, + this.cursorColor, + this.cursorBlinking, + clipboardAvailable); } } @@ -166,22 +261,29 @@ public class TerminalEmulatorDeviceConfiguration { * Different cursor styles supported by SwingTerminal */ public enum CursorStyle { + /** * The cursor is drawn by inverting the front- and background colors of the cursor position */ REVERSED, + /** * The cursor is drawn by using the cursor color as the background color for the character at the cursor position */ FIXED_BACKGROUND, + /** * The cursor is rendered as a thick horizontal line at the bottom of the character */ UNDER_BAR, + /** * The cursor is rendered as a left-side aligned vertical line */ VERTICAL_BAR, + ; + } + }
Backporting merged change for issue #<I> from master
mabe02_lanterna
train
d72a0c586e92ad2a7870a337b066ad234b389ce0
diff --git a/packages/app-admin/src/plugins/Menu/Navigation/index.js b/packages/app-admin/src/plugins/Menu/Navigation/index.js index <HASH>..<HASH> 100755 --- a/packages/app-admin/src/plugins/Menu/Navigation/index.js +++ b/packages/app-admin/src/plugins/Menu/Navigation/index.js @@ -331,7 +331,7 @@ class Navigation extends React.Component<Props> { > Webiny.com </a> - <p>© {new Date().getFullYear()} Webiny, Ltd</p> + <p>© {new Date().getFullYear()} Webiny Ltd, London, UK</p> </div> </ListItem> </List>
Updated the menu footer company signature
Webiny_webiny-js
train
af9e074b804c4ee2ac460ec90f05ce9116f911ef
diff --git a/resources/lang/fi-FI/pagination.php b/resources/lang/fi-FI/pagination.php index <HASH>..<HASH> 100644 --- a/resources/lang/fi-FI/pagination.php +++ b/resources/lang/fi-FI/pagination.php @@ -22,7 +22,7 @@ return [ | */ - 'previous' => 'Previous', - 'next' => 'Next', + 'previous' => 'Edellinen', + 'next' => 'Seuraava', ];
New translations pagination.php (Finnish)
CachetHQ_Cachet
train
dae0d8e75541e810275e789a23971a61e60a2154
diff --git a/lib/html2rss/attribute_post_processors.rb b/lib/html2rss/attribute_post_processors.rb index <HASH>..<HASH> 100644 --- a/lib/html2rss/attribute_post_processors.rb +++ b/lib/html2rss/attribute_post_processors.rb @@ -1,5 +1,5 @@ -require_relative 'attribute_post_processors/parse_uri' require_relative 'attribute_post_processors/parse_time' +require_relative 'attribute_post_processors/parse_uri' require_relative 'attribute_post_processors/sanitize_html' require_relative 'attribute_post_processors/template' diff --git a/lib/html2rss/config.rb b/lib/html2rss/config.rb index <HASH>..<HASH> 100644 --- a/lib/html2rss/config.rb +++ b/lib/html2rss/config.rb @@ -38,7 +38,7 @@ module Html2rss end def options(name) - feed_config.dig('selectors', name).merge('channel' => channel_config) + feed_config.dig('selectors').fetch(name, {}).merge('channel' => channel_config) end def selector(name) @@ -46,8 +46,8 @@ module Html2rss end def attribute_names - attribute_names = feed_config.fetch('selectors', {}).keys.map(&:to_sym) - attribute_names.delete(:items) + attribute_names = feed_config.fetch('selectors', {}).keys.map(&:to_s) + attribute_names.delete('items') attribute_names end end diff --git a/lib/html2rss/feed_builder.rb b/lib/html2rss/feed_builder.rb index <HASH>..<HASH> 100644 --- a/lib/html2rss/feed_builder.rb +++ b/lib/html2rss/feed_builder.rb @@ -31,12 +31,14 @@ module Html2rss end def feed_items - Item.from_url config.url, config + @feed_items ||= Item.from_url config.url, config end def add_item_to_items(feed_item, items) + raise 'item is invalid' unless feed_item.valid? + items.new_item do |rss_item| - config.attribute_names.each do |attribute_name| + feed_item.available_attributes.each do |attribute_name| rss_item.send("#{attribute_name}=".to_sym, feed_item.send(attribute_name)) rss_item.guid.content = Digest::SHA1.hexdigest(feed_item.title) diff --git a/lib/html2rss/item.rb b/lib/html2rss/item.rb index <HASH>..<HASH> 100644 --- a/lib/html2rss/item.rb +++ b/lib/html2rss/item.rb @@ -31,6 +31,16 @@ module Html2rss value end + def available_attributes + # category enclosure pubDate source + @available_attributes ||= (%w(title link description author comments) & @config.attribute_names) + end + + def valid? + return false if [title.to_s, description.to_s].join('') == '' + true + end + def self.from_url(url, config) connection = Faraday.new(url: url, headers: config.headers) page = Nokogiri::HTML(connection.get.body)
fix: only set supported attributes on rss item
gildesmarais_html2rss
train
b4a5f0b7975feaa8ae72000fe06809316a75f2ef
diff --git a/holoviews/plotting/bokeh/chart.py b/holoviews/plotting/bokeh/chart.py index <HASH>..<HASH> 100644 --- a/holoviews/plotting/bokeh/chart.py +++ b/holoviews/plotting/bokeh/chart.py @@ -10,7 +10,9 @@ from bokeh.transform import jitter from ...core.data import Dataset from ...core.dimension import dimension_name -from ...core.util import OrderedDict, max_range, basestring, dimension_sanitizer, isfinite, range_pad +from ...core.util import ( + OrderedDict, max_range, basestring, dimension_sanitizer, + isfinite, range_pad, dimension_range) from ...element import Bars from ...operation import interpolate_curve from ...util.transform import dim @@ -812,6 +814,8 @@ class BarPlot(ColorbarPlot, LegendPlot): else: y0 = 0 + y0, y1 = dimension_range(y0, y1, self.ylim, (None, None)) + # Ensure x-axis is picked up as categorical x0 = xdim.pprint_value(extents[0]) x1 = xdim.pprint_value(extents[2]) diff --git a/holoviews/tests/plotting/bokeh/testbarplot.py b/holoviews/tests/plotting/bokeh/testbarplot.py index <HASH>..<HASH> 100644 --- a/holoviews/tests/plotting/bokeh/testbarplot.py +++ b/holoviews/tests/plotting/bokeh/testbarplot.py @@ -92,6 +92,13 @@ class TestBarPlot(TestBokehPlot): self.assertEqual(y_range.start, 0.001) self.assertEqual(y_range.end, 3.0000000000000013) + def test_bars_ylim(self): + bars = Bars([1, 2, 3]).opts(ylim=(0, 200)) + plot = bokeh_renderer.get_plot(bars) + y_range = plot.handles['y_range'] + self.assertEqual(y_range.start, 0) + self.assertEqual(y_range.end, 200) + def test_bars_padding_square(self): points = Bars([(1, 2), (2, -1), (3, 3)]).options(padding=0.1) plot = bokeh_renderer.get_plot(points)
Fix range issues on Bars (#<I>) * Fix range issues on Bars * Add test
pyviz_holoviews
train
47214af04f5c7ed32f9227a8df4741a1c6c67a02
diff --git a/injector.py b/injector.py index <HASH>..<HASH> 100644 --- a/injector.py +++ b/injector.py @@ -240,8 +240,8 @@ import types __author__ = 'Alec Thomas <alec@swapoff.org>' -__version__ = '0.2' -__version_tag__ = '' +__version__ = '0.3' +__version_tag__ = 'dev' class Error(Exception): @@ -262,6 +262,10 @@ class CircularDependency(Error): """Circular dependency detected.""" +class UnknownProvider(Error): + """Tried to bind to a type whose provider couldn't be determined.""" + + class Provider(object): """Provides class instances.""" @@ -270,8 +274,7 @@ class Provider(object): class ClassProvider(Provider): - """Provides instances from a given class, created using an Injector. - """ + """Provides instances from a given class, created using an Injector.""" def __init__(self, cls, injector): self._cls = cls @@ -316,18 +319,36 @@ class ListOfProviders(Provider): class MultiBindProvider(ListOfProviders): """Used by :meth:`Binder.multibind` to flatten results of providers that - return sequences. - """ + return sequences.""" def get(self): return [i for provider in self._providers for i in provider.get()] +class MapBindProvider(ListOfProviders): + """A provider for map bindings.""" + + def get(self): + map = {} + for provider in self._providers: + map.update(provider.get()) + return map + # These classes are used internally by the Binder. class BindingKey(tuple): """A key mapping to a Binding.""" def __new__(cls, what, annotation): + if isinstance(what, list): + if len(what) != 1: + raise Error('list bindings must have a single interface ' + 'element') + what = (list, BindingKey(what[0], None)) + elif isinstance(what, dict): + if len(what) != 1: + raise Error('dictionary bindings must have a single interface ' + 'key and value') + what = (dict, BindingKey(what.items()[0], None)) return tuple.__new__(cls, (what, annotation)) @property @@ -408,7 +429,10 @@ class Binder(object): """ key = BindingKey(interface, annotation) if key not in self._bindings: - provider = MultiBindProvider() + if isinstance(interface, dict): + provider = MapBindProvider() + else: + provider = MultiBindProvider() binding = self.create_binding( interface, provider, annotation, scope) self._bindings[key] = binding @@ -417,6 +441,10 @@ class Binder(object): assert isinstance(provider, ListOfProviders) provider.append(self.provider_for(key.interface, to)) + def install(self, module): + """Install a module into this binder.""" + module(self) + def create_binding(self, interface, to=None, annotation=None, scope=None): to = to or interface provider = self.provider_for(interface, to) @@ -429,16 +457,20 @@ class Binder(object): def provider_for(self, interface, to=None): if isinstance(to, Provider): return to - elif isinstance(to, interface): - return InstanceProvider(to) + elif isinstance(to, (types.FunctionType, types.LambdaType, + types.MethodType)): + return CallableProvider(to) elif type(to) is type: return ClassProvider(to, self.injector) elif type(interface) is type and issubclass(interface, BaseKey): if callable(to): return CallableProvider(to) return InstanceProvider(to) + elif isinstance(to, interface): + return InstanceProvider(to) else: - return CallableProvider(to) + raise UnknownProvider('couldn\'t determine provider for %r to %r' % + (interface, to)) def get_binding(self, cls, key): try: @@ -585,7 +617,6 @@ class Injector(object): # Initialise modules for module in modules: module(self.binder) - self._modules = modules def get(self, interface, annotation=None, scope=None): """Get an instance of the given interface. diff --git a/test.py b/test.py index <HASH>..<HASH> 100644 --- a/test.py +++ b/test.py @@ -440,3 +440,47 @@ def test_custom_scope(): assert_true(handler.request is request) assert_raises(UnsatisfiedRequirement, injector.get, Handler) + + +def test_bind_interface_of_list_of_types(): + + def configure(binder): + binder.multibind([int], to=[1, 2, 3]) + binder.multibind([int], to=[4, 5, 6]) + + injector = Injector(configure) + assert_equal(injector.get([int]), [1, 2, 3, 4, 5, 6]) + + +def test_map_binding_and_extends(): + + def configure(binder): + binder.multibind({str: int}, to={'one': 1}) + binder.multibind({str: int}, to={'two': 2}) + + class MyModule(Module): + @extends({str: int}) + def provide_numbers(self): + return {'three': 3} + + @extends({str: int}) + def provide_more_numbers(self): + return {'four': 4} + + injector = Injector([configure, MyModule()]) + assert_equal(injector.get({str: int}), + {'one': 1, 'two': 2, 'three': 3, 'four': 4}) + + +def test_binder_install(): + class ModuleA(Module): + def configure(self, binder): + binder.bind(str, to='hello world') + + class ModuleB(Module): + def configure(self, binder): + binder.install(ModuleA()) + + injector = Injector([ModuleB()]) + assert_equal(injector.get(str), 'hello world') +
Support mapping bindings. Also simplified how composite bindings are referenced. Instead of having to use an explicit Key() for lists or dictionaries, you can use a list or dictionary with one element. For example, a mapping of strings to plugins: {str: Plugin} Or a sequence of plugins: [Plugin] Pass these forms to get(), @extends() and multibind().
alecthomas_injector
train
f7cc6ac7e8c4a5f3807f1eae27b0d28607b8caa0
diff --git a/kdcount/cluster.py b/kdcount/cluster.py index <HASH>..<HASH> 100644 --- a/kdcount/cluster.py +++ b/kdcount/cluster.py @@ -82,17 +82,13 @@ class fof(object): def sum(self, weights=None): """ return the sum of weights of each object """ if weights is None: - weights = self.data._weights - if weights is None: - weights = 1.0 + weights = self.data.weights return utils.bincount(self.labels, weights, self.N) def center(self, weights=None): """ return the center of each object """ if weights is None: - weights = self.data._weights - if weights is None: - weights = 1.0 + weights = self.data.weights mass = utils.bincount(self.labels, weights, self.N) cp = numpy.empty((len(mass), self.data.pos.shape[-1]), 'f8') for d in range(self.data.pos.shape[-1]):
update fof to respect weights.
rainwoodman_kdcount
train
c21fe40b69f0cdaff188b3a293e0ab266436f3b6
diff --git a/packages/jsio.js b/packages/jsio.js index <HASH>..<HASH> 100644 --- a/packages/jsio.js +++ b/packages/jsio.js @@ -57,6 +57,7 @@ // Creates an object containing metadata about a module. function ModuleDef (path) { this.path = path; + this.friendlyPath = path; util.splitPath(path, this); }; @@ -592,7 +593,7 @@ var src = moduleDef.src; delete moduleDef.src; - var code = "(function(_){with(_){delete _;return function $$" + moduleDef.friendlyPath.replace(/[\/.]/g, '_') + "(){" + src + "\n}}})"; + var code = "(function(_){with(_){delete _;return function $$" + moduleDef.friendlyPath.replace(/[\:\\\/.]/g, '_') + "(){" + src + "\n}}})"; var fn = ENV.eval(code, moduleDef.path, src); fn = fn(context); fn.call(context.exports); diff --git a/packages/preprocessors/cls.js b/packages/preprocessors/cls.js index <HASH>..<HASH> 100644 --- a/packages/preprocessors/cls.js +++ b/packages/preprocessors/cls.js @@ -13,7 +13,7 @@ function replacer(base, prefix, name) { } exports = function(path, moduleDef, opts) { - var moduleCtor = moduleDef.path.replace(/(^[.\/]+|\.([^.]+?)$)/g, '').replace(/[\/\-\.]/g, '_'); + var moduleCtor = moduleDef.path.replace(/(^[.\/]+|\.([^.]+?)$)/g, '').replace(/[\:\\\/\-\.]/g, '_'); moduleDef.src = moduleDef.src .replace(classExport, 'var ' + moduleCtor + '=__class__;$1exports=' + moduleCtor + '(function ' + moduleCtor + '(){return this.init&&this.init.apply(this,arguments)},') .replace(class2Export, replacer); diff --git a/packages/preprocessors/import.js b/packages/preprocessors/import.js index <HASH>..<HASH> 100644 --- a/packages/preprocessors/import.js +++ b/packages/preprocessors/import.js @@ -1,12 +1,12 @@ -var importExpr = /^(\s*)(import\s+[^=+*"'\r\n]+|from\s+[^=+*"'\r\n]+)$/gm; +var importExpr = /^(\s*)(import\s+[^=+*"'\r\n;\/]+|from\s+[^=+"'\r\n;\/]+)(;|\/|$)/gm; -function replace(raw, p1, p2) { +function replace(raw, p1, p2, p3) { if (!/\/\//.test(p1)) { - return p1 + 'jsio("' + p2 + '");'; + return p1 + 'jsio("' + p2 + '")' + p3; } return raw; } -exports = function(path, moduleDef, opts) { +exports = function (path, moduleDef, opts) { moduleDef.src = moduleDef.src.replace(importExpr, replace); }
allow more special characters " and :
gameclosure_js.io
train
7fe978e95ef2d3ca5bdc943425edfe005ed2ccc6
diff --git a/client.go b/client.go index <HASH>..<HASH> 100644 --- a/client.go +++ b/client.go @@ -454,7 +454,7 @@ func (c *Client) ListContainers() ([]string, error) { return names, nil } -func (c *Client) PutImage(filename string) (*Response, error) { +func (c *Client) PostImage(filename string) (*Response, error) { uri := c.url(shared.APIVersion, "images") f, err := os.Open(filename) @@ -463,7 +463,7 @@ func (c *Client) PutImage(filename string) (*Response, error) { } defer f.Close() - req, err := http.NewRequest("PUT", uri, f) + req, err := http.NewRequest("POST", uri, f) if err != nil { return nil, err } @@ -768,7 +768,7 @@ func (c *Client) PushFile(container string, p string, gid int, uid int, mode os. query := url.Values{"path": []string{p}} uri := c.url(shared.APIVersion, "containers", container, "files") + "?" + query.Encode() - req, err := http.NewRequest("PUT", uri, buf) + req, err := http.NewRequest("POST", uri, buf) if err != nil { return err } diff --git a/lxc/image.go b/lxc/image.go index <HASH>..<HASH> 100644 --- a/lxc/image.go +++ b/lxc/image.go @@ -140,7 +140,7 @@ func (c *imageCmd) run(config *lxd.Config, args []string) error { return err } - _, err = d.PutImage(imagefile) + _, err = d.PostImage(imagefile) if err != nil { return err } diff --git a/lxd/containers.go b/lxd/containers.go index <HASH>..<HASH> 100644 --- a/lxd/containers.go +++ b/lxd/containers.go @@ -508,7 +508,7 @@ func containerFileHandler(d *Daemon, r *http.Request) Response { switch r.Method { case "GET": return containerFileGet(r, p) - case "PUT": + case "POST": return containerFilePut(r, p) default: return NotFound @@ -588,7 +588,7 @@ func containerFilePut(r *http.Request, p string) Response { return EmptySyncResponse } -var containerFileCmd = Command{name: "containers/{name}/files", get: containerFileHandler, put: containerFileHandler} +var containerFileCmd = Command{name: "containers/{name}/files", get: containerFileHandler, post: containerFileHandler} func snapshotsDir(c *lxdContainer) string { return shared.VarPath("lxc", c.name, "snapshots") diff --git a/lxd/images.go b/lxd/images.go index <HASH>..<HASH> 100644 --- a/lxd/images.go +++ b/lxd/images.go @@ -25,7 +25,7 @@ func getSize(f *os.File) (int64, error) { return fi.Size(), nil } -func imagesPut(d *Daemon, r *http.Request) Response { +func imagesPost(d *Daemon, r *http.Request) Response { shared.Debugf("responding to images:put") public, err := strconv.Atoi(r.Header.Get("X-LXD-public")) @@ -183,7 +183,7 @@ func imagesGet(d *Daemon, r *http.Request) Response { return SyncResponse(true, result) } -var imagesCmd = Command{name: "images", put: imagesPut, get: imagesGet} +var imagesCmd = Command{name: "images", post: imagesPost, get: imagesGet} func imageDelete(d *Daemon, r *http.Request) Response { shared.Debugf("responding to image:delete")
Fix /files and /images to use the right methods Adding a new object to a collection should be done with a POST.
lxc_lxd
train
54eaf33dc826f55d2b707e4f268044713f71e181
diff --git a/lxd/rsync.go b/lxd/rsync.go index <HASH>..<HASH> 100644 --- a/lxd/rsync.go +++ b/lxd/rsync.go @@ -8,6 +8,7 @@ import ( "os" "os/exec" "syscall" + "time" "github.com/gorilla/websocket" "github.com/pborman/uuid" @@ -87,6 +88,7 @@ func rsyncSendSetup(name string, path string, bwlimit string, execPath string, f if err != nil { return nil, nil, nil, err } + defer l.Close() /* * Here, the path /tmp/foo is ignored. Since we specify localhost, @@ -135,15 +137,34 @@ func rsyncSendSetup(name string, path string, bwlimit string, execPath string, f return nil, nil, nil, err } - conn, err := l.Accept() - if err != nil { + var conn *net.Conn + chConn := make(chan *net.Conn, 1) + + go func() { + conn, err := l.Accept() + if err != nil { + chConn <- nil + return + } + + chConn <- &conn + }() + + select { + case conn = <-chConn: + if conn == nil { + cmd.Process.Kill() + cmd.Wait() + return nil, nil, nil, fmt.Errorf("Failed to connect to rsync socket") + } + + case <-time.After(10 * time.Second): cmd.Process.Kill() cmd.Wait() - return nil, nil, nil, err + return nil, nil, nil, fmt.Errorf("rsync failed to spawn after 10s") } - l.Close() - return cmd, conn, stderr, nil + return cmd, *conn, stderr, nil } // RsyncSend sets up the sending half of an rsync, to recursively send the
lxd/migration: Handle crashing rsync
lxc_lxd
train
cfa78b0c2b4d437187e4c1dcb23f13c746fcf351
diff --git a/src/Service/Misc/Encoding.php b/src/Service/Misc/Encoding.php index <HASH>..<HASH> 100644 --- a/src/Service/Misc/Encoding.php +++ b/src/Service/Misc/Encoding.php @@ -264,7 +264,7 @@ class Encoding * @return string|false * The result. */ - public function mbDetectEncoding(string $string, string $encodinglist = 'auto', $strict = false) + public function mbDetectEncoding(string $string, string $encodinglist = 'auto', bool $strict = false) { return mb_detect_encoding($string, $encodinglist, $strict); } @@ -404,7 +404,7 @@ class Encoding // The first regex detects all allowed characters. // For some reason, they also allow BOM characters. - return $cache[$propName] = (bool) preg_match("/^[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*$/", $propName) && + return $cache[$propName] = (bool) preg_match("/^[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*$/", (string)$propName) && !(bool) preg_match("/[\xEF\xBB\xBF]$/", $propName); } }
Removed some findings from code inspection.
brainworxx_kreXX
train
d43fe85405818a5f9d1105cfb1f53e768b424d80
diff --git a/modules/activiti-spring-boot/spring-boot-starters/spring-boot-starter-basic/src/main/java/org/activiti/spring/boot/AbstractProcessEngineAutoConfiguration.java b/modules/activiti-spring-boot/spring-boot-starters/spring-boot-starter-basic/src/main/java/org/activiti/spring/boot/AbstractProcessEngineAutoConfiguration.java index <HASH>..<HASH> 100644 --- a/modules/activiti-spring-boot/spring-boot-starters/spring-boot-starter-basic/src/main/java/org/activiti/spring/boot/AbstractProcessEngineAutoConfiguration.java +++ b/modules/activiti-spring-boot/spring-boot-starters/spring-boot-starter-basic/src/main/java/org/activiti/spring/boot/AbstractProcessEngineAutoConfiguration.java @@ -58,6 +58,9 @@ public abstract class AbstractProcessEngineAutoConfiguration conf.setDatabaseSchemaUpdate(defaultText( activitiProperties.getDatabaseSchemaUpdate(), conf.getDatabaseSchemaUpdate())); + + conf.setMailServerHost(activitiProperties.getMailServerHost()); + conf.setMailServerPort(activitiProperties.getMailServerPort()); return conf; diff --git a/modules/activiti-spring-boot/spring-boot-starters/spring-boot-starter-basic/src/main/java/org/activiti/spring/boot/ActivitiProperties.java b/modules/activiti-spring-boot/spring-boot-starters/spring-boot-starter-basic/src/main/java/org/activiti/spring/boot/ActivitiProperties.java index <HASH>..<HASH> 100644 --- a/modules/activiti-spring-boot/spring-boot-starters/spring-boot-starter-basic/src/main/java/org/activiti/spring/boot/ActivitiProperties.java +++ b/modules/activiti-spring-boot/spring-boot-starters/spring-boot-starter-basic/src/main/java/org/activiti/spring/boot/ActivitiProperties.java @@ -12,6 +12,8 @@ public class ActivitiProperties { private boolean checkProcessDefinitions = true ; private boolean restApiEnabled; private String deploymentName; + private String mailServerHost = "localhost"; + private int mailServerPort = 1025; public boolean isRestApiEnabled() { return restApiEnabled; @@ -109,4 +111,20 @@ public class ActivitiProperties { this.processDefinitionLocationSuffix = processDefinitionLocationSuffix; } + public String getMailServerHost() { + return mailServerHost; + } + + public void setMailServerHost(String mailServerHost) { + this.mailServerHost = mailServerHost; + } + + public int getMailServerPort() { + return mailServerPort; + } + + public void setMailServerPort(int mailServerPort) { + this.mailServerPort = mailServerPort; + } + }
[Spring Boot] Adding Email server config
Activiti_Activiti
train
f52a4f40c67c301435d705507eddf78a3539ab63
diff --git a/src/test/java/cleanzephyr/rubycollect4j/RubyEnumerableTest.java b/src/test/java/cleanzephyr/rubycollect4j/RubyEnumerableTest.java index <HASH>..<HASH> 100644 --- a/src/test/java/cleanzephyr/rubycollect4j/RubyEnumerableTest.java +++ b/src/test/java/cleanzephyr/rubycollect4j/RubyEnumerableTest.java @@ -712,4 +712,11 @@ public class RubyEnumerableTest { })); } + @Test + public void testMemberʔ() { + re = new RubyEnumerable<Integer>(1, 2, 3, 4); + assertTrue(re.memberʔ(1)); + assertFalse(re.memberʔ(5)); + } + }
Add test for RubyEnumerable::member?
wnameless_rubycollect4j
train
7a8ffe6268d9113ad935f430e6fc41045ef06175
diff --git a/kaggler/preprocessing/data.py b/kaggler/preprocessing/data.py index <HASH>..<HASH> 100644 --- a/kaggler/preprocessing/data.py +++ b/kaggler/preprocessing/data.py @@ -454,11 +454,11 @@ class TargetEncoder(base.BaseEstimator): .map(self.target_encoders[i]) .fillna(self.target_mean)) else: - x = np.zeros_like((X.shape[0], ), dtype=float) for i_enc, target_encoder in enumerate(self.target_encoders[i], 1): - x += (X[col].fillna(NAN_INT) - .map(target_encoder) - .fillna(self.target_mean)) + if i_enc == 1: + x = X[col].fillna(NAN_INT).map(target_encoder).fillna(self.target_mean) + else: + x += X[col].fillna(NAN_INT).map(target_encoder).fillna(self.target_mean) X.loc[:, col] = x / i_enc
2nd try to resolve pytest error in travis
jeongyoonlee_Kaggler
train
dfccace0250e13c8c6f702c43f7c441d654693f9
diff --git a/gulpfile.js b/gulpfile.js index <HASH>..<HASH> 100644 --- a/gulpfile.js +++ b/gulpfile.js @@ -543,6 +543,7 @@ const compileTypescript = ((cache) => .pipe( gulpReplace("import { BN } from 'bn.js';", "import BN from 'bn.js';"), ) + .pipe(gulpReplace('../static', './static')) .pipe( gulpRename((name) => { name.dirname = name.dirname
fix(gulp): fix static imports in neo-one-react-common
neo-one-suite_neo-one
train
a5a7257dd90ba11398ad9289c7277f4931183916
diff --git a/lib/sensu/api.rb b/lib/sensu/api.rb index <HASH>..<HASH> 100644 --- a/lib/sensu/api.rb +++ b/lib/sensu/api.rb @@ -642,17 +642,20 @@ module Sensu unless stashes.empty? stashes.each_with_index do |path, index| $redis.get('stash:' + path) do |stash_json| - unless stash_json.nil? - item = { - :path => path, - :content => Oj.load(stash_json) - } - response << item - else - $redis.srem('stashes', path) - end - if index == stashes.size - 1 - body Oj.dump(pagination(response)) + $redis.ttl('stash:' + path) do |ttl| + unless stash_json.nil? + item = { + :path => path, + :content => Oj.load(stash_json), + :expire => ttl + } + response << item + else + $redis.srem('stashes', path) + end + if index == stashes.size - 1 + body Oj.dump(pagination(response)) + end end end end
return expire time for stashes on /stashes
sensu_sensu
train
e423da6f484e2357512e53ad3f4c11cd04ff038f
diff --git a/src/View.php b/src/View.php index <HASH>..<HASH> 100644 --- a/src/View.php +++ b/src/View.php @@ -1,4 +1,35 @@ <?php +/** + * Slim - a micro PHP 5 framework + * + * @author Josh Lockhart <info@slimframework.com> + * @copyright 2011 Josh Lockhart + * @link http://www.slimframework.com + * @license http://www.slimframework.com/license + * @version 2.4.2 + * @package Slim + * + * MIT LICENSE + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ namespace Slender; use \Slim\Collection;
Retain Slim copyright notice as per #6 request from @codeguy
alanpich_slender
train
1f2472f4c29388cdf61573ed8433206252a0f351
diff --git a/bookstore/__init__.py b/bookstore/__init__.py index <HASH>..<HASH> 100644 --- a/bookstore/__init__.py +++ b/bookstore/__init__.py @@ -1,15 +1,15 @@ -# TODO: refactor the import, PACKAGE_DIR, del import os -from ._version import __version__, version_info -from .archive import BookstoreContentsArchiver -from .bookstore_config import BookstoreSettings -from .handlers import load_jupyter_server_extension - PACKAGE_DIR: str = os.path.realpath(os.path.dirname(__file__)) del os +from .archive import BookstoreContentsArchiver +from .bookstore_config import BookstoreSettings +from .handlers import load_jupyter_server_extension +from ._version import __version__ +from ._version import version_info + def _jupyter_server_extension_paths(): return [dict(module="bookstore")]
remove todo on package dir and make consistent with master
nteract_bookstore
train
8e61e35748d16f2c4f5a45802a64426616c81edc
diff --git a/owncloud/test/test.py b/owncloud/test/test.py index <HASH>..<HASH> 100644 --- a/owncloud/test/test.py +++ b/owncloud/test/test.py @@ -791,12 +791,29 @@ class TestUserAndGroupActions(unittest.TestCase): self.not_existing_group = Config['not_existing_group'] self.test_group = Config['test_group'] self.share2user = Config['owncloud_share2user'] + try: + self.client.create_user(self.share2user, 'share') + except: + pass + try: + self.client.create_group(self.test_group) + except: + pass def tearDown(self): for group in self.groups_to_create: self.assertTrue(self.client.delete_group(group)) self.assertTrue(self.client.remove_user_from_group(self.share2user,self.test_group)) + try: + self.client.delete_user(self.share2user) + except: + pass + + try: + self.client.delete_group(self.test_group) + except: + pass self.client.logout()
autocreate test user and group share2user and test_group is created automatically for TestUserAndGroupActions
owncloud_pyocclient
train
0f03c06408f5f579586813b9a1e1c24024715a53
diff --git a/__init__.py b/__init__.py index <HASH>..<HASH> 100644 --- a/__init__.py +++ b/__init__.py @@ -100,6 +100,12 @@ class TinyDB(object): """ return len(self._table) + def __contains__(self, item): + """ + A shorthand for ``field(...) == ... in db.table()`` + """ + return item in self.table() + def __getattr__(self, name): return getattr(self._table, name) @@ -120,6 +126,7 @@ class Table(object): """ self.name = name self._db = db + self._queries_cache = {} try: self._last_id = self._read().pop()['id'] @@ -144,6 +151,7 @@ class Table(object): :type values: list """ + self._clear_query_cache() self._db._write(values, self.name) def __len__(self): @@ -191,8 +199,8 @@ class Table(object): :type where: has """ - to_remove = self.get(where) - self._write([e for e in self._read() if e != to_remove]) + to_remove = self.search(where) + self._write([e for e in self._read() if e not in to_remove]) def purge(self): """ @@ -211,7 +219,13 @@ class Table(object): :rtype: list """ - return [e for e in self._read() if where(e)] + if where in self._queries_cache: + return self._queries_cache[where] + else: + elems = [e for e in self._read() if where(e)] + self._queries_cache[where] = elems + + return elems def get(self, where): """ @@ -227,3 +241,9 @@ class Table(object): for el in self._read(): if where(el): return el + + def _clear_query_cache(self): + """ + + """ + self._queries_cache = {} \ No newline at end of file diff --git a/queries.py b/queries.py index <HASH>..<HASH> 100644 --- a/queries.py +++ b/queries.py @@ -203,6 +203,9 @@ class query(AndOrMixin): def __repr__(self): return self._repr + def __hash__(self): + return hash(repr(self)) + field = query diff --git a/tests/tests_tinydb.py b/tests/tests_tinydb.py index <HASH>..<HASH> 100644 --- a/tests/tests_tinydb.py +++ b/tests/tests_tinydb.py @@ -37,6 +37,8 @@ def test_insert(): def test_insert_multiple(): db.purge() + assert_equal(len(db.search(field('int') == 1)), 0) + db.insert({'int': 1, 'char': 'a'}) db.insert({'int': 1, 'char': 'b'}) db.insert({'int': 1, 'char': 'c'}) @@ -55,6 +57,16 @@ def test_remove(): db.remove(field('char') == 'b') assert_equal(len(db), 2) + assert_equal(len(db.search(field('int') == 1)), 2) + + +def test_remove_multiple(): + db.insert({'int': 1, 'char': 'a'}) + db.insert({'int': 1, 'char': 'b'}) + db.insert({'int': 1, 'char': 'c'}) + + db.remove(field('int') == 1) + assert_equal(len(db), 0) def test_search(): @@ -71,6 +83,25 @@ def test_search(): assert_equal(results[1]['char'], 'b') assert_equal(results[2]['char'], 'c') + +def test_contians(): + db.purge() + + db.insert({'int': 1, 'char': 'a'}) + db.insert({'int': 1, 'char': 'b'}) + db.insert({'int': 1, 'char': 'c'}) + + if (field('int') == 1) in db: + assert_true(True, True) + else: + assert_true(True, False) + + if (field('int') == 0) in db: + assert_true(True, False) + else: + assert_true(True, True) + + def test_get(): db.purge()
Added query caching and fixed some bugs
msiemens_tinydb
train
d538b3708a1b96c408b2a60ac7cb0eec97bfb4f8
diff --git a/test/commands/verify_test.rb b/test/commands/verify_test.rb index <HASH>..<HASH> 100644 --- a/test/commands/verify_test.rb +++ b/test/commands/verify_test.rb @@ -16,7 +16,7 @@ class InteragentHyperSchemaVerifyTest < Minitest::Test errors = verify assert_equal 1, errors.count assert_match /^#: /, errors[0] - assert_match /Missing required keys "title" in object/, errors[0] + assert_match /"title" wasn't supplied\./, errors[0] end def test_api_property_format @@ -25,7 +25,7 @@ class InteragentHyperSchemaVerifyTest < Minitest::Test }) errors = verify assert_match %r{^#/properties/app: }, errors[0] - assert_match /Missing required keys "\$ref" in object/, errors[0] + assert_match /"\$ref" wasn't supplied\./, errors[0] end # @@ -37,7 +37,7 @@ class InteragentHyperSchemaVerifyTest < Minitest::Test errors = verify assert_equal 1, errors.count assert_match %r{^#/definitions/app: }, errors[0] - assert_match /Missing required keys "title" in object/, errors[0] + assert_match /"title" wasn't supplied\./, errors[0] end def test_resource_identity_format @@ -47,7 +47,7 @@ class InteragentHyperSchemaVerifyTest < Minitest::Test errors = verify assert_equal 1, errors.count assert_match %r{^#/definitions/app/definitions/identity: }, errors[0] - assert_match /any subschema of "anyOf" condition./, errors[0] + assert_match /No subschema in "anyOf" matched\./, errors[0] end # an empty schema can be specified to bypass the identity check @@ -66,7 +66,7 @@ class InteragentHyperSchemaVerifyTest < Minitest::Test errors = verify assert_equal 1, errors.count assert_match %r{^#/definitions/app/properties: }, errors[0] - assert_match /Extra keys in object: my-property/, errors[0] + assert_match /"my-property" is not a permitted key\./, errors[0] end def test_resource_strict_properties @@ -76,7 +76,7 @@ class InteragentHyperSchemaVerifyTest < Minitest::Test errors = verify assert_equal 1, errors.count assert_match %r{^#/definitions/app/strictProperties: }, errors[0] - assert_match /to be a member of enum \[true\], value was: false/, errors[0] + assert_match /false is not a member of \[true\]/, errors[0] end # @@ -90,7 +90,7 @@ class InteragentHyperSchemaVerifyTest < Minitest::Test errors = verify assert_equal 1, errors.count assert_match %r{^#/definitions/app/definitions/name: }, errors[0] - assert_match /Data matched subschema of "not" condition/, errors[0] + assert_match /Matched "not" subschema/, errors[0] end def test_resource_definition_required @@ -98,7 +98,7 @@ class InteragentHyperSchemaVerifyTest < Minitest::Test errors = verify assert_equal 1, errors.count assert_match %r{^#/definitions/app/definitions/name: }, errors[0] - assert_match /Missing required keys "description" in object/, errors[0] + assert_match /"description" wasn't supplied\./, errors[0] end # @@ -112,7 +112,7 @@ class InteragentHyperSchemaVerifyTest < Minitest::Test errors = verify assert_equal 1, errors.count assert_match %r{^#/definitions/app/links/0/href: }, errors[0] - assert_match /Expected string to match pattern/, errors[0] + assert_match /\/my_apps does not match /, errors[0] end def test_resource_link_required @@ -120,7 +120,7 @@ class InteragentHyperSchemaVerifyTest < Minitest::Test errors = verify assert_equal 1, errors.count assert_match %r{^#/definitions/app/links/0: }, errors[0] - assert_match /Missing required keys "method" in object/, errors[0] + assert_match /"method" wasn't supplied\./, errors[0] end private
Updated tests to match latest json-schema errors
interagent_prmd
train
08944c54de13054b4b7a76dbcba79218779f02d3
diff --git a/intg/src/main/java/org/apache/atlas/type/AtlasTypeRegistry.java b/intg/src/main/java/org/apache/atlas/type/AtlasTypeRegistry.java index <HASH>..<HASH> 100644 --- a/intg/src/main/java/org/apache/atlas/type/AtlasTypeRegistry.java +++ b/intg/src/main/java/org/apache/atlas/type/AtlasTypeRegistry.java @@ -65,7 +65,7 @@ public class AtlasTypeRegistry { // used only by AtlasTransientTypeRegistry protected AtlasTypeRegistry(AtlasTypeRegistry other) { - registryData = new RegistryData(other.registryData); + registryData = new RegistryData(); updateSynchronizer = other.updateSynchronizer; } @@ -245,15 +245,6 @@ public class AtlasTypeRegistry { allTypes.addType(new AtlasBuiltInTypes.AtlasObjectIdType()); } - RegistryData(RegistryData other) { - allTypes = new TypeCache(other.allTypes); - enumDefs = new TypeDefCache<>(other.enumDefs, allTypes); - structDefs = new TypeDefCache<>(other.structDefs, allTypes); - classificationDefs = new TypeDefCache<>(other.classificationDefs, allTypes); - entityDefs = new TypeDefCache<>(other.entityDefs, allTypes); - allDefCaches = new TypeDefCache[] { enumDefs, structDefs, classificationDefs, entityDefs }; - } - AtlasBaseTypeDef getTypeDefByName(String name) { AtlasBaseTypeDef ret = null; @@ -320,8 +311,17 @@ public class AtlasTypeRegistry { private List<AtlasBaseTypeDef> deletedTypes = new ArrayList<>(); - private AtlasTransientTypeRegistry(AtlasTypeRegistry parent) { + private AtlasTransientTypeRegistry(AtlasTypeRegistry parent) throws AtlasBaseException { super(parent); + + addTypesWithNoRefResolve(parent.getAllEnumDefs()); + addTypesWithNoRefResolve(parent.getAllStructDefs()); + addTypesWithNoRefResolve(parent.getAllClassificationDefs()); + addTypesWithNoRefResolve(parent.getAllEntityDefs()); + + addedTypes.clear(); + updatedTypes.clear(); + deletedTypes.clear(); } private void resolveReferences() throws AtlasBaseException { diff --git a/intg/src/test/java/org/apache/atlas/type/TestAtlasTypeRegistry.java b/intg/src/test/java/org/apache/atlas/type/TestAtlasTypeRegistry.java index <HASH>..<HASH> 100644 --- a/intg/src/test/java/org/apache/atlas/type/TestAtlasTypeRegistry.java +++ b/intg/src/test/java/org/apache/atlas/type/TestAtlasTypeRegistry.java @@ -482,6 +482,83 @@ public class TestAtlasTypeRegistry { } } + /* create 2 entity types: L0 and L1, with L0 as superType of L1 + * add entity type L2, with L0, L1 and L2 as super-types - this should fail due to L2 self-referencing itself in super-types + * verify that after the update failure, the registry still has correct super-type/sub-type information for L0 and L1 + */ + @Test + public void testRegistryValidityOnInvalidUpdate() { + AtlasEntityDef entL0 = new AtlasEntityDef("L0"); + AtlasEntityDef entL1 = new AtlasEntityDef("L1"); + + entL1.addSuperType(entL0.getName()); + + entL0.addAttribute(new AtlasAttributeDef("L0_a1", AtlasBaseTypeDef.ATLAS_TYPE_INT)); + entL1.addAttribute(new AtlasAttributeDef("L1_a1", AtlasBaseTypeDef.ATLAS_TYPE_INT)); + + AtlasTypesDef typesDef = new AtlasTypesDef(); + + typesDef.getEntityDefs().add(entL0); + typesDef.getEntityDefs().add(entL1); + + AtlasTypeRegistry typeRegistry = new AtlasTypeRegistry(); + AtlasTransientTypeRegistry ttr = null; + boolean commit = false; + String failureMsg = null; + + try { + ttr = typeRegistry.lockTypeRegistryForUpdate(); + + ttr.addTypes(typesDef); + + commit = true; + } catch (AtlasBaseException excp) { + failureMsg = excp.getMessage(); + } finally { + typeRegistry.releaseTypeRegistryForUpdate(ttr, commit); + } + assertNull(failureMsg); + + validateSuperTypes(typeRegistry, "L0", new HashSet<String>()); + validateSubTypes(typeRegistry, "L0", new HashSet<>(Arrays.asList("L1"))); + + validateSuperTypes(typeRegistry, "L1", new HashSet<>(Arrays.asList("L0"))); + validateSubTypes(typeRegistry, "L1", new HashSet<String>()); + + + // create a circular reference + AtlasEntityDef entL2 = new AtlasEntityDef("L2"); + entL2.addSuperType(entL0.getName()); + entL2.addSuperType(entL1.getName()); + entL2.addSuperType(entL2.getName()); + + typesDef.clear(); + typesDef.getEntityDefs().add(entL2); + + try { + commit = false; + + ttr = typeRegistry.lockTypeRegistryForUpdate(); + + ttr.updateTypes(typesDef); + + commit = true; + } catch (AtlasBaseException excp) { + failureMsg = excp.getMessage(); + } finally { + typeRegistry.releaseTypeRegistryForUpdate(ttr, commit); + } + assertNotNull(failureMsg); + + assertNull(typeRegistry.getEntityTypeByName("L2")); + + validateSuperTypes(typeRegistry, "L0", new HashSet<String>()); + validateSubTypes(typeRegistry, "L0", new HashSet<>(Arrays.asList("L1"))); + + validateSuperTypes(typeRegistry, "L1", new HashSet<>(Arrays.asList("L0"))); + validateSubTypes(typeRegistry, "L1", new HashSet<String>()); + } + private boolean addType(AtlasTypeRegistry typeRegistry, AtlasBaseTypeDef typeDef) { boolean ret = false; AtlasTransientTypeRegistry ttr = null;
ATLAS-<I>: fix type-update handling to ensure that active type registry state is not updated while processing the changes
apache_incubator-atlas
train
1b100e8c676754f61745f131db491da1ebe7c1a0
diff --git a/devices/tuya.js b/devices/tuya.js index <HASH>..<HASH> 100644 --- a/devices/tuya.js +++ b/devices/tuya.js @@ -138,7 +138,9 @@ module.exports = [ model: 'ZN231392', vendor: 'TuYa', description: 'Smart water/gas valve', - extend: extend.switch(), + toZigbee: extend.switch().toZigbee.concat([tz.moes_power_on_behavior]), + fromZigbee: extend.switch().fromZigbee.concat([fz.moes_power_on_behavior]), + exposes: extend.switch().exposes.concat([exposes.presets.power_on_behavior()]), }, { fingerprint: [{modelID: 'TS011F', manufacturerName: '_TZ3000_1hwjutgo'}, {modelID: 'TS011F', manufacturerName: '_TZ3000_lnggrqqi'}],
Attempt to support power on behaviour for ZN<I>. <URL>
Koenkk_zigbee-shepherd-converters
train
82e1f74447ca7c922908773460bed8aa130a9781
diff --git a/apispec/core.py b/apispec/core.py index <HASH>..<HASH> 100644 --- a/apispec/core.py +++ b/apispec/core.py @@ -9,7 +9,7 @@ import yaml from apispec.compat import iterkeys, iteritems, PY2, unicode from apispec.lazy_dict import LazyDict -from .exceptions import PluginError, APISpecError +from .exceptions import PluginError, APISpecError, PluginMethodNotImplementedError from .utils import OpenAPIVersion VALID_METHODS = [ @@ -239,7 +239,7 @@ class APISpec(object): for plugin in self.plugins: try: ret = plugin.path_helper(path=path, operations=path.operations, **kwargs) - except (NotImplementedError, TypeError): + except PluginMethodNotImplementedError: continue if isinstance(ret, Path): ret.path = normalize_path(ret.path) @@ -262,7 +262,7 @@ class APISpec(object): for plugin in self.plugins: try: plugin.operation_helper(path=path, operations=path.operations, **kwargs) - except NotImplementedError: + except PluginMethodNotImplementedError: continue # Deprecated interface for func in self._operation_helpers: @@ -276,7 +276,7 @@ class APISpec(object): for plugin in self.plugins: try: response.update(plugin.response_helper(method, status_code, **kwargs) or {}) - except NotImplementedError: + except PluginMethodNotImplementedError: continue # Deprecated interface # Rule is that method + http status exist in both operations and helpers @@ -312,7 +312,7 @@ class APISpec(object): for plugin in self.plugins: try: ret.update(plugin.definition_helper(name, definition=ret, **kwargs)) - except (NotImplementedError, TypeError): + except PluginMethodNotImplementedError: continue # Deprecated interface for func in self._definition_helpers: diff --git a/apispec/exceptions.py b/apispec/exceptions.py index <HASH>..<HASH> 100644 --- a/apispec/exceptions.py +++ b/apispec/exceptions.py @@ -4,16 +4,15 @@ import warnings class APISpecError(Exception): """Base class for all apispec-related errors.""" - pass class PluginError(APISpecError): """Raised when a plugin cannot be found or is invalid.""" - pass + +class PluginMethodNotImplementedError(APISpecError, NotImplementedError): + """Raised when calling an unimplemented helper method in a plugin""" class OpenAPIError(APISpecError): """Raised when a OpenAPI spec validation fails.""" - pass - class SwaggerError(OpenAPIError): """ diff --git a/apispec/plugin.py b/apispec/plugin.py index <HASH>..<HASH> 100644 --- a/apispec/plugin.py +++ b/apispec/plugin.py @@ -1,6 +1,9 @@ # -*- coding: utf-8 -*- """Base class for Plugin classes.""" + +from .exceptions import PluginMethodNotImplementedError + class BasePlugin(object): """Base class for APISpec plugin @@ -15,19 +18,19 @@ class BasePlugin(object): def definition_helper(self, name, definition, **kwargs): """Must return definition as a dict.""" - raise NotImplementedError + raise PluginMethodNotImplementedError def path_helper(self, path=None, operations=None, **kwargs): """Should return a Path instance. Any other return value type is ignored""" - raise NotImplementedError + raise PluginMethodNotImplementedError def operation_helper(self, path=None, operations=None, **kwargs): """Should mutate operations. Return value ignored.""" - raise NotImplementedError + raise PluginMethodNotImplementedError def response_helper(self, method, status_code, **kwargs): """Should return a dict to update the response description. Returning None is equivalent to returning an empty dictionary. """ - raise NotImplementedError + raise PluginMethodNotImplementedError
BasePlugin: raise PluginMethodNotImplementedError rather than NotImplementedError Also, don't catch TypeError from plugin methods in APISpec.
marshmallow-code_apispec
train
096c57f666ae2e1fd0b2e0fce0551a170ff70a87
diff --git a/plugins/Goals/Controller.php b/plugins/Goals/Controller.php index <HASH>..<HASH> 100644 --- a/plugins/Goals/Controller.php +++ b/plugins/Goals/Controller.php @@ -452,10 +452,10 @@ class Controller extends \Piwik\Plugin\Controller foreach ($allReports as $category => $reports) { $categoryText = Piwik::translate('Goals_ViewGoalsBy', $category); foreach ($reports as $report) { - $customParams['viewDataTable'] = 'tableGoals'; - if (in_array($report['action'], array('getVisitsUntilConversion', 'getDaysToConversion'))) { - $customParams['viewDataTable'] = 'table'; + if(empty($report['viewDataTable'])) { + $report['viewDataTable'] = 'tableGoals'; } + $customParams['viewDataTable'] = $report['viewDataTable']; $goalReportsByDimension->addReport( $categoryText, $report['name'], $report['module'] . '.' . $report['action'], $customParams); diff --git a/plugins/Goals/Goals.php b/plugins/Goals/Goals.php index <HASH>..<HASH> 100644 --- a/plugins/Goals/Goals.php +++ b/plugins/Goals/Goals.php @@ -419,12 +419,14 @@ class Goals extends \Piwik\Plugin array('category' => Piwik::translate('General_Visit'), 'name' => Piwik::translate('Goals_VisitsUntilConv'), 'module' => 'Goals', - 'action' => 'getVisitsUntilConversion' + 'action' => 'getVisitsUntilConversion', + 'viewDataTable' => 'table', ), array('category' => Piwik::translate('General_Visit'), 'name' => Piwik::translate('Goals_DaysToConv'), 'module' => 'Goals', - 'action' => 'getDaysToConversion' + 'action' => 'getDaysToConversion', + 'viewDataTable' => 'table', ) ); $dimensions = array_merge($dimensions, $reportWithGoalMetrics);
Removing one hardcoded hack
matomo-org_matomo
train
5046c1c6e5c5f355b83a0882bf1a401a4ea5fdbf
diff --git a/ford/__init__.py b/ford/__init__.py index <HASH>..<HASH> 100644 --- a/ford/__init__.py +++ b/ford/__init__.py @@ -273,6 +273,8 @@ def initialize(): print('Warning: license "{}" not recognized.'.format(proj_data['license'])) proj_data['license'] = '' # Return project data, docs, and the Markdown reader + md.reset() + md.Meta = {} return (proj_data, proj_docs, md) diff --git a/ford/sourceform.py b/ford/sourceform.py index <HASH>..<HASH> 100644 --- a/ford/sourceform.py +++ b/ford/sourceform.py @@ -259,6 +259,7 @@ class FortranBase(object): self.doc = md.convert(self.doc) self.meta = md.Meta md.reset() + md.Meta = {} else: if self.settings['warn'].lower() == 'true' and self.obj != 'sourcefile' and self.obj != 'genericsource': #TODO: Add ability to print line number where this item is in file @@ -269,7 +270,9 @@ class FortranBase(object): if self.parent: self.display = self.parent.display + #~ print (self.meta) for key in self.meta: + #~ print(key, self.meta[key]) if key == 'display': tmp = [ item.lower() for item in self.meta[key] ] if type(self) == FortranSourceFile: @@ -1923,7 +1926,16 @@ def line_to_variables(source, line, inherit_permission, parent): search_from = 0 while QUOTES_RE.search(initial[search_from:]): num = int(QUOTES_RE.search(initial[search_from:]).group()[1:-1]) - string = NBSP_RE.sub('&nbsp;',parent.strings[num]) + old_string = NBSP_RE.sub('&nbsp;',parent.strings[num]) + string = '' + for i in range(len(old_string)): + if old_string[i] == "\\" and (old_string[i+1] in '0123456789' or + old_string[i+1] == 'g'): + string += r'\\' + elif old_string[i] == '(' and old_string[i+1] =='?': + string += r'\(' + else: + string += old_string[i] initial = initial[0:search_from] + QUOTES_RE.sub(string,initial[search_from:],count=1) search_from += QUOTES_RE.search(initial[search_from:]).end(0)
Fixed regex substitutions with \g and introduced for MD metadata bug.
Fortran-FOSS-Programmers_ford
train
4edba3c680463b7d334a7ca835a497f4d04681e8
diff --git a/handler/src/main/java/com/networknt/handler/Handler.java b/handler/src/main/java/com/networknt/handler/Handler.java index <HASH>..<HASH> 100644 --- a/handler/src/main/java/com/networknt/handler/Handler.java +++ b/handler/src/main/java/com/networknt/handler/Handler.java @@ -20,6 +20,8 @@ import java.util.List; import java.util.Map; import java.util.Random; +import static io.undertow.util.PathTemplateMatch.ATTACHMENT_KEY; + /** * @author Nicholas Azar */ @@ -152,6 +154,11 @@ public class Handler { PathTemplateMatcher.PathMatchResult<String> result = pathTemplateMatcher.match(httpServerExchange.getRequestPath()); if (result != null) { // Found a match, configure and return true; + // Add path variables to query params. + httpServerExchange.putAttachment(ATTACHMENT_KEY, new io.undertow.util.PathTemplateMatch(result.getMatchedTemplate(), result.getParameters())); + for (Map.Entry<String, String> entry : result.getParameters().entrySet()) { + httpServerExchange.addQueryParam(entry.getKey(), entry.getValue()); + } String id = result.getValue(); httpServerExchange.putAttachment(CHAIN_ID, id); httpServerExchange.putAttachment(CHAIN_SEQ, 0);
Fix issue causing query params to be missing from path.
networknt_light-4j
train
a8f477475299a25c0a2a550a5bff3294aeb41bbb
diff --git a/clients/android/src/org/camlistore/DownloadService.java b/clients/android/src/org/camlistore/DownloadService.java index <HASH>..<HASH> 100644 --- a/clients/android/src/org/camlistore/DownloadService.java +++ b/clients/android/src/org/camlistore/DownloadService.java @@ -45,6 +45,7 @@ public class DownloadService extends Service { private static final int BUFFER_SIZE = 4096; private static final String USERNAME = "TODO-DUMMY-USER"; private static final String SEARCH_BLOBREF = "search"; + private static final String PARTIAL_DOWNLOAD_SUFFIX = ".partial"; private final IBinder mBinder = new LocalBinder(); private final Handler mHandler = new Handler(); @@ -200,7 +201,7 @@ public class DownloadService extends Service { // Load |mBlobRef| from the cache, returning a File on success or null on failure. private File loadBlobFromCache() { Util.assertNotMainThread(); - if (canBlobBeCached(mBlobRef)) + if (!canBlobBeCached(mBlobRef)) return null; File file = new File(mBlobDir, mBlobRef); @@ -219,8 +220,6 @@ public class DownloadService extends Service { Util.getBasicAuthHeaderValue( USERNAME, mSharedPrefs.getString(Preferences.PASSWORD, ""))); - boolean success = false; - File file = null; FileOutputStream outputStream = null; try { @@ -231,15 +230,22 @@ public class DownloadService extends Service { return null; } + // Temporary location where we download the file and final path to which + // we rename it after it's complete. + File tempFile = null; + File finalFile = null; + if (canBlobBeCached(mBlobRef)) { - file = new File(mBlobDir, mBlobRef); - file.createNewFile(); + finalFile = new File(mBlobDir, mBlobRef); + tempFile = new File(finalFile.getPath() + PARTIAL_DOWNLOAD_SUFFIX); + tempFile.createNewFile(); } else { // FIXME: Don't write uncacheable blobs to disk at all. - file = File.createTempFile(mBlobRef, null, mBlobDir); - file.deleteOnExit(); + // deleteOnExit() doesn't work on Android, either. + tempFile = finalFile = File.createTempFile(mBlobRef, null, mBlobDir); + tempFile.deleteOnExit(); } - outputStream = new FileOutputStream(file); + outputStream = new FileOutputStream(tempFile); int bytesRead = 0; byte[] buffer = new byte[BUFFER_SIZE]; @@ -248,8 +254,10 @@ public class DownloadService extends Service { outputStream.write(buffer, 0, bytesRead); } - success = true; - return file; + if (tempFile != finalFile) { + tempFile.renameTo(finalFile); + } + return finalFile; } catch (ClientProtocolException e) { Log.e(TAG, "protocol error while downloading " + mBlobRef, e); @@ -261,9 +269,6 @@ public class DownloadService extends Service { if (outputStream != null) { try { outputStream.close(); } catch (IOException e) {} } - if (!success && file != null && file.exists()) { - file.delete(); - } } }
android: download files to temporary location also fix lame inverted-logic bug in cache-checking code :-(
perkeep_perkeep
train
9ca955d9c0494be5cb09e44f27453067a8a2e163
diff --git a/ipyvolume/pylab.py b/ipyvolume/pylab.py index <HASH>..<HASH> 100644 --- a/ipyvolume/pylab.py +++ b/ipyvolume/pylab.py @@ -1005,7 +1005,7 @@ for style_name, __ in ipv.styles.styles.items(): def plot_plane(where="back", texture=None): """Plots a plane at a particular location in the viewbox - :param str where: 'back', 'front', 'left', 'right' + :param str where: 'back', 'front', 'left', 'right', 'top', 'bottom' :param texture: {texture} :return: :any:`Mesh` """ @@ -1022,13 +1022,21 @@ def plot_plane(where="back", texture=None): y = [ymin, ymin, ymax, ymax] z = [zmax, zmax, zmax, zmax] if where == "left": - x = [xmin, xmin, xmin, zmin] + x = [xmin, xmin, xmin, xmin] y = [ymin, ymin, ymax, ymax] z = [zmin, zmax, zmax, zmin] if where == "right": - x = [xmax, xmax, xmax, zmax] + x = [xmax, xmax, xmax, xmax] y = [ymin, ymin, ymax, ymax] z = [zmin, zmax, zmax, zmin][::-1] + if where == "top": + x = [xmin, xmax, xmax, xmin] + y = [ymax, ymax, ymax, ymax] + z = [zmax, zmax, zmin, zmin] + if where == "bottom": + x = [xmax, xmin, xmin, xmax] + y = [ymin, ymin, ymin, ymin] + z = [zmin, zmin, zmax, zmax] triangles = [(0, 1, 2), (0, 2, 3)] u = v = None if texture is not None:
add top and bottom to plot_plane (#<I>)
maartenbreddels_ipyvolume
train
e6a2c53a466fe4fab7f23352d11f82faecc9c156
diff --git a/packages/cli/tests/e2e/hosting.test-e2e.js b/packages/cli/tests/e2e/hosting.test-e2e.js index <HASH>..<HASH> 100644 --- a/packages/cli/tests/e2e/hosting.test-e2e.js +++ b/packages/cli/tests/e2e/hosting.test-e2e.js @@ -108,7 +108,7 @@ describe('[E2E] CLI Hosting', function () { it('can set hosting config with flags', function (done) { testNixt() .run(`${cliLocation} hosting config ${hostingName} --browser-router false --remove-cname my.dom.ain`) - .stdout(/^((?!CNAME: http:\/\/my.dom.ain)[\s\S])*$/) + .stdout(/^((?!CNAME: http:\/\/my.dom.ain)[\s\S])*$/) .stdout(/BrowserRouter: x/) .end(done) })
test(hosting): Remove space
Syncano_syncano-node
train
978bf670868212a9ad2595fdc1f7ac589e5519a6
diff --git a/tlc/permissions.go b/tlc/permissions.go index <HASH>..<HASH> 100644 --- a/tlc/permissions.go +++ b/tlc/permissions.go @@ -9,6 +9,8 @@ import ( const minScannedFileSize = 4 func (c *Container) FixPermissions(fp sync.FilePool) error { + defer fp.Close() + buf := make([]byte, minScannedFileSize) for index, f := range c.Files { if f.Size < minScannedFileSize {
Close file pool after fixing permissions, closes <URL>
itchio_wharf
train
3c873270054c82f358bd52a28e96963085292522
diff --git a/catalog/app/containers/Bucket/PackageCreateDialog.js b/catalog/app/containers/Bucket/PackageCreateDialog.js index <HASH>..<HASH> 100644 --- a/catalog/app/containers/Bucket/PackageCreateDialog.js +++ b/catalog/app/containers/Bucket/PackageCreateDialog.js @@ -574,7 +574,11 @@ function PackageCreateDialog({ bucket, open, workflowsConfig, onClose, refresh } name="workflow" workflowsConfig={workflowsConfig} initialValue={PD.defaultWorkflowFromConfig(workflowsConfig)} + validate={validators.required} validateFields={['meta', 'workflow']} + errors={{ + required: 'Workflow is required for this bucket.', + }} /> <input type="submit" style={{ display: 'none' }} /> diff --git a/catalog/app/containers/Bucket/PackageDialog/PackageDialog.js b/catalog/app/containers/Bucket/PackageDialog/PackageDialog.js index <HASH>..<HASH> 100644 --- a/catalog/app/containers/Bucket/PackageDialog/PackageDialog.js +++ b/catalog/app/containers/Bucket/PackageDialog/PackageDialog.js @@ -178,10 +178,11 @@ const useWorkflowInputStyles = M.makeStyles((t) => ({ }, })) -export function WorkflowInput({ input, meta, workflowsConfig }) { +export function WorkflowInput({ input, meta, workflowsConfig, errors = {} }) { const classes = useWorkflowInputStyles() const disabled = meta.submitting || meta.submitSucceeded + const errorKey = meta.submitFailed && meta.error return ( <SelectWorkflow @@ -190,6 +191,7 @@ export function WorkflowInput({ input, meta, workflowsConfig }) { onChange={input.onChange} value={input.value} disabled={disabled} + error={errorKey ? (errors[errorKey] || errorKey) : undefined} /> ) } diff --git a/catalog/app/containers/Bucket/PackageDialog/SelectWorkflow.js b/catalog/app/containers/Bucket/PackageDialog/SelectWorkflow.js index <HASH>..<HASH> 100644 --- a/catalog/app/containers/Bucket/PackageDialog/SelectWorkflow.js +++ b/catalog/app/containers/Bucket/PackageDialog/SelectWorkflow.js @@ -4,17 +4,27 @@ import * as M from '@material-ui/core' import { docs } from 'constants/urls' const useStyles = M.makeStyles((t) => ({ - spinner: { - flex: 'none', - marginRight: t.spacing(3), - }, crop: { textOverflow: 'ellipsis', overflow: 'hidden', }, + error: { + marginRight: t.spacing(1), + }, + spinner: { + flex: 'none', + marginRight: t.spacing(3), + }, })) -export default function SelectWorkflow({ className, disabled, items, onChange, value }) { +export default function SelectWorkflow({ + className, + disabled, + error, + items, + onChange, + value, +}) { const classes = useStyles() const noChoice = items.length === 1 @@ -25,6 +35,7 @@ export default function SelectWorkflow({ className, disabled, items, onChange, v disabled={disabled || noChoice} fullWidth size="small" + error={!!error} > <M.InputLabel id="schema-select">Metadata quality workflow</M.InputLabel> <M.Select @@ -51,6 +62,7 @@ export default function SelectWorkflow({ className, disabled, items, onChange, v ))} </M.Select> <M.FormHelperText> + {!!error && <span className={classes.error}>{error}</span>} <M.Link href={`${docs}/advanced-usage/workflows`} target="_blank"> Learn about quality workflows </M.Link> diff --git a/catalog/app/utils/workflows.js b/catalog/app/utils/workflows.js index <HASH>..<HASH> 100644 --- a/catalog/app/utils/workflows.js +++ b/catalog/app/utils/workflows.js @@ -18,7 +18,6 @@ const COPY_DATA_DEFAULT = true export const emptyConfig = { copyData: COPY_DATA_DEFAULT, - isRequired: false, successors: [], workflows: [getNoWorkflow({}, false)], } @@ -73,7 +72,6 @@ export function parse(workflowsYaml) { const successors = data.successors || {} return { - isRequired: data.is_workflow_required, successors: Object.entries(successors).map(([url, successor]) => parseSuccessor(url, successor), ),
Workflow is required always, even when no default workflow (#<I>)
quiltdata_quilt
train
65768de6a6d5014feab59d224c70e363fa9db742
diff --git a/openquake/calculators/scenario_risk.py b/openquake/calculators/scenario_risk.py index <HASH>..<HASH> 100644 --- a/openquake/calculators/scenario_risk.py +++ b/openquake/calculators/scenario_risk.py @@ -128,8 +128,6 @@ class ScenarioRiskCalculator(base.RiskCalculator): except KeyError: self.param['weights'] = [1 / self.R for _ in range(self.R)] self.param['event_slice'] = self.event_slice - self.param['asset_loss_table'] = self.oqparam.asset_loss_table - self.param['loss_ratio_threshold'] = oq.loss_ratio_threshold self.param['ael_dt'] = ael_dt = self.crmodel.aid_eid_loss_dt() A = len(self.assetcol)
Removed obsolete line [skip CI]
gem_oq-engine
train
2d816b0d9a841b70cff46ed21cca8b823b754c1d
diff --git a/src/components/victory-axis/helper-methods.js b/src/components/victory-axis/helper-methods.js index <HASH>..<HASH> 100644 --- a/src/components/victory-axis/helper-methods.js +++ b/src/components/victory-axis/helper-methods.js @@ -1,4 +1,7 @@ import isFunction from "lodash/lang/isFunction"; +import includes from "lodash/collection/includes"; +import without from "lodash/array/without"; +import range from "lodash/utility/range"; import Scale from "../../helpers/scale"; import Axis from "../../helpers/axis"; @@ -44,13 +47,13 @@ module.exports = { getTicks(props, scale) { if (props.tickValues) { if (Axis.stringTicks(props)) { - return props.tickValues.map((val, index) => index + 1); + return range(1, props.tickValues.length + 1); } return props.tickValues; } else if (scale.ticks && isFunction(scale.ticks)) { const ticks = scale.ticks(props.tickCount); if (props.crossAxis) { - return ticks.indexOf(0) !== -1 ? ticks.filter((val) => val !== 0) : ticks; + return includes(ticks, 0) ? without(ticks, 0) : ticks; } return ticks; } diff --git a/src/components/victory-scatter/path-helpers.js b/src/components/victory-scatter/path-helpers.js index <HASH>..<HASH> 100644 --- a/src/components/victory-scatter/path-helpers.js +++ b/src/components/victory-scatter/path-helpers.js @@ -1,3 +1,5 @@ +import range from "lodash/utility/range"; + module.exports = { circle(x, y, size) { return `M ${x}, ${y} m ${-size}, 0 @@ -60,7 +62,7 @@ module.exports = { star(x, y, size) { const baseSize = 1.35 * size; const angle = Math.PI / 5; - const starCoords = Array(...Array(10)).map((val, index) => { + const starCoords = range(10).map((index) => { const length = index % 2 === 0 ? baseSize : baseSize / 2; return `${length * Math.sin(angle * (index + 1)) + x}, ${length * Math.cos(angle * (index + 1)) + y}`; diff --git a/src/helpers/domain.js b/src/helpers/domain.js index <HASH>..<HASH> 100644 --- a/src/helpers/domain.js +++ b/src/helpers/domain.js @@ -1,4 +1,5 @@ import flatten from "lodash/array/flatten"; +import includes from "lodash/collection/includes"; import zipObject from "lodash/array/zipObject"; import Data from "./data"; import Axis from "./axis"; @@ -128,9 +129,9 @@ module.exports = { const axisValues = []; datasets.forEach((dataset) => { dataset.forEach((data) => { - if (data.category !== undefined && categories.indexOf(data.category) === -1) { + if (data.category !== undefined && !includes(categories, data.category)) { categories.push(data.category); - } else if (axisValues.indexOf(data[axis]) === -1) { + } else if (!includes(axisValues, data[axis])) { axisValues.push(data[axis]); } }); diff --git a/src/helpers/scale.js b/src/helpers/scale.js index <HASH>..<HASH> 100644 --- a/src/helpers/scale.js +++ b/src/helpers/scale.js @@ -1,4 +1,5 @@ import flatten from "lodash/array/flatten"; +import includes from "lodash/collection/includes"; import isFunction from "lodash/lang/isFunction"; import { Collection, Helpers } from "victory-core"; import d3Scale from "d3-scale"; @@ -10,7 +11,7 @@ module.exports = { if (typeof scale === "function") { return (isFunction(scale.copy) && isFunction(scale.domain) && isFunction(scale.range)); } else if (typeof scale === "string") { - return supportedScaleStrings.indexOf(scale) !== -1; + return includes(supportedScaleStrings, scale); } return false; }, @@ -30,7 +31,7 @@ module.exports = { } const scale = props.scale[axis] || props.scale; if (this.validScale(scale)) { - return typeof scale === "function" ? scale : d3Scale[scale](); + return isFunction(scale) ? scale : d3Scale[scale](); } }, @@ -58,7 +59,7 @@ module.exports = { if (!scale) { return this.getScaleTypeFromData(props, axis); } else if (typeof scale === "string") { - return supportedScaleStrings.indexOf(scale) !== -1 ? scale : "invalid"; + return includes(supportedScaleStrings, scale) ? scale : "invalid"; } else if (!this.validScale(scale)) { return "invalid"; }
use lodash range, includes, without
FormidableLabs_victory
train
be594f3c4ba06ddac550a1251aec5b77162a8c42
diff --git a/engine.py b/engine.py index <HASH>..<HASH> 100644 --- a/engine.py +++ b/engine.py @@ -115,4 +115,7 @@ class Strategy(object): def _append_to_array_item_to_dictionary_key(adict, key, array_item): if key not in adict: adict[key] = [] - adict[key].append(array_item) + if array_item in adict[key]: + raise SyntaxError("%s already exists in the target %s" % (array_item, key)) + else: + adict[key].append(array_item)
resolve #3, moban now throws SyntaxError
moremoban_moban-handlebars
train
66246e8381d8536daed907a0e7cdb5a42feecb99
diff --git a/setup.py b/setup.py index <HASH>..<HASH> 100755 --- a/setup.py +++ b/setup.py @@ -23,7 +23,7 @@ import subprocess # in development set version to none and ... -PYPI_VERSION = "1.2.0 +PYPI_VERSION = "1.2.0" " # Return the git revision as a string (from numpy)
Update setup.py Actually, it's worse than that !
underworldcode_stripy
train
b37c506ce7b73a961facc9860f8fcbc6e2dda5f8
diff --git a/OpenPNM/Base/__Core__.py b/OpenPNM/Base/__Core__.py index <HASH>..<HASH> 100644 --- a/OpenPNM/Base/__Core__.py +++ b/OpenPNM/Base/__Core__.py @@ -1240,9 +1240,9 @@ class Core(Base): mapping['target'] = locsT if return_mapping == False: - if sp.any(locsS < 0): + if sp.any(locsS < 0) or (sp.shape(locsS)[0] == 0): raise Exception('Some locations were not found on the source object') - if sp.any(locsT < 0): + if sp.any(locsT < 0) or (sp.shape(locsT)[0] == 0): raise Exception('Some locations were not found on the target object') return mapping['target'] else: diff --git a/OpenPNM/Network/__GenericNetwork__.py b/OpenPNM/Network/__GenericNetwork__.py index <HASH>..<HASH> 100644 --- a/OpenPNM/Network/__GenericNetwork__.py +++ b/OpenPNM/Network/__GenericNetwork__.py @@ -744,8 +744,10 @@ class GenericNetwork(Core): for item in self._geometries+self._physics+self._phases: Pnet = self['pore.'+item.name]*Pkeep Tnet = self['throat.'+item.name]*Tkeep - Ps = self._map('pore',sp.where(Pnet)[0],item) - Ts = self._map('throat',sp.where(Tnet)[0],item) + temp = self.map_pores(pores=sp.where(Pnet)[0],target=item,return_mapping=True) + Ps = temp['target'] + temp = self.map_throats(throats=sp.where(Tnet)[0],target=item,return_mapping=True) + Ts = temp['target'] # Then resize 'all item.update({'pore.all' : sp.ones((sp.sum(Pnet),),dtype=bool)}) item.update({'throat.all' : sp.ones((sp.sum(Tnet),),dtype=bool)}) @@ -772,7 +774,7 @@ class GenericNetwork(Core): self.update({'throat.conns' : sp.vstack((Tnew1,Tnew2)).T}) # Overwrite remaining data and info for item in self.keys(): - if item.split('.')[1] not in ['conns','all']: + if item.split('.')[-1] not in ['conns','all']: temp = self.pop(item) if item.split('.')[0] == 'throat': self[item] = temp[Tkeep] @@ -780,12 +782,12 @@ class GenericNetwork(Core): self[item] = temp[Pkeep] #Reset network graphs - self._update_network(mode='regenerate') +# self._update_network(mode='regenerate') #Check Network health - health = self.check_network_health() - if health['trim_pores'] != []: - self._logger.warning('Isolated pores exist! Run check_network_health to ID which pores to remove.') +# health = self.check_network_health() +# if health['trim_pores'] != []: +# self._logger.warning('Isolated pores exist! Run check_network_health to ID which pores to remove.') def _stitch(self,network_2,pores_1,pores_2,method='delaunay',len_max=sp.inf): r'''
Fixed small bug in mapping that let empty lists pass. - You can get an empty list only if you select return_mapping=True Also changed the logic in trim to accommodate this change. - When trimming an entire geometry, the list of target pores will be empty so need to use the return_mapping option
PMEAL_OpenPNM
train
8bcfaa80fe5f45224f28eeab74b5813b7064e311
diff --git a/lib/node_tracers.js b/lib/node_tracers.js index <HASH>..<HASH> 100644 --- a/lib/node_tracers.js +++ b/lib/node_tracers.js @@ -37,7 +37,7 @@ * keystone client to use to authenticate against keystone to get a token * and tenant id */ - module.exports.RESTkinTracer = function (trace_url, keystone_client) { + module.exports.RESTkinTracer = function(trace_url, keystone_client) { var self = this; if (trace_url.charAt(trace_url.length - 1) === '/') { @@ -58,6 +58,10 @@ "Content-Type": "application/json" }, body: body + }, function(err) { + if (err) { + console.log('Error while sending trace to RESTkin endpoint: ' + err.toString()); + } }); };
Add callback to request method and log an error instead of exploding if it occurs.
tryfer_node-tryfer
train
452875de514722b070f28c5c1cf70e2efba1e55e
diff --git a/examples/hello_world.py b/examples/hello_world.py index <HASH>..<HASH> 100644 --- a/examples/hello_world.py +++ b/examples/hello_world.py @@ -3,5 +3,5 @@ import hug @hug.get() def hello(request): - """Says hello""" - return 'Hello World!' + """Says hellos""" + return 'Hello World! dude' diff --git a/hug/development_runner.py b/hug/development_runner.py index <HASH>..<HASH> 100644 --- a/hug/development_runner.py +++ b/hug/development_runner.py @@ -83,6 +83,8 @@ def hug(file: 'A Python file that contains a Hug API'=None, module: 'A Python mo sys.exit(1) ran = True for module in [name for name in sys.modules.keys() if name not in INIT_MODULES]: + if module == 'pdb': + sys.modules['pdb'].clear() del(sys.modules[module]) if file: api_module = importlib.machinery.SourceFileLoader(file.split(".")[0],
Auto clear pdb on restart
hugapi_hug
train
efc55b95c224a8d7964748147402954c4a26efe7
diff --git a/samples/physics-mecanum/src/physics.py b/samples/physics-mecanum/src/physics.py index <HASH>..<HASH> 100644 --- a/samples/physics-mecanum/src/physics.py +++ b/samples/physics-mecanum/src/physics.py @@ -49,9 +49,11 @@ class PhysicsEngine(object): ''' # Simulate the drivetrain - lr_motor = wpilib.DigitalModule._pwm[0].Get() + # -> Remember, in the constructor we inverted the left motors, so + # invert the motor values here too! + lr_motor = -wpilib.DigitalModule._pwm[0].Get() rr_motor = wpilib.DigitalModule._pwm[1].Get() - lf_motor = wpilib.DigitalModule._pwm[2].Get() + lf_motor = -wpilib.DigitalModule._pwm[2].Get() rf_motor = wpilib.DigitalModule._pwm[3].Get() vx, vy, vw = drivetrains.mecanum_drivetrain(lr_motor, rr_motor, lf_motor, rf_motor) diff --git a/samples/physics-mecanum/src/robot.py b/samples/physics-mecanum/src/robot.py index <HASH>..<HASH> 100644 --- a/samples/physics-mecanum/src/robot.py +++ b/samples/physics-mecanum/src/robot.py @@ -23,6 +23,12 @@ class MyRobot(wpilib.SimpleRobot): self.robot_drive = wpilib.RobotDrive(self.lr_motor, self.rr_motor, self.lf_motor, self.rf_motor) + # The output function of a mecanum drive robot is always + # +1 for all output wheels. However, traditionally wired + # robots will be -1 on the left, 1 on the right. + self.robot_drive.SetInvertedMotor(wpilib.RobotDrive.kFrontLeftMotor, True) + self.robot_drive.SetInvertedMotor(wpilib.RobotDrive.kRearLeftMotor, True) + # Position gets automatically updated as robot moves self.gyro = wpilib.Gyro(1)
Update mechanum example to show inverted motors
robotpy_pyfrc
train
93edc53b938f07528120b51c86f435026803aede
diff --git a/src/link_finder.php b/src/link_finder.php index <HASH>..<HASH> 100644 --- a/src/link_finder.php +++ b/src/link_finder.php @@ -431,7 +431,7 @@ class LinkFinder{ } protected function _shortenUrl($url){ - $max_acceptable_length = 50; + $max_acceptable_length = 65; // In emails, lines should not be larger than 70 characters. if(strlen($url)<=$max_acceptable_length){ return $url; } @@ -442,7 +442,7 @@ class LinkFinder{ } $out = $matches["proto"].$matches["domain"]; - $length = $max_acceptable_length - strlen($out); + $length = $max_acceptable_length - strlen($out) - 3; // 3 for "..." if($length<5){ $length = 5; } $out = $out.substr($matches["uri"],0,$length)."..."; diff --git a/test/tc_link_finder.php b/test/tc_link_finder.php index <HASH>..<HASH> 100644 --- a/test/tc_link_finder.php +++ b/test/tc_link_finder.php @@ -359,7 +359,7 @@ or <a href="mailto:we@earth.net">we@earth.net</a></p>',$lfinder->process($src,ar $src = 'Long URL: https://venturebeat.com/2018/05/01/donkey-kong-country-tropical-freeze-review-a-funky-fresh-switch-update/, short URL: https://cz.ign.com/se/?q=mario'; $lfinder = new LinkFinder(); - $this->assertEquals('Long URL: <a href="https://venturebeat.com/2018/05/01/donkey-kong-country-tropical-freeze-review-a-funky-fresh-switch-update/">https://venturebeat.com/2018/05/01/donkey-kong-cou...</a>, short URL: <a href="https://cz.ign.com/se/?q=mario">https://cz.ign.com/se/?q=mario</a>',$lfinder->process($src)); + $this->assertEquals('Long URL: <a href="https://venturebeat.com/2018/05/01/donkey-kong-country-tropical-freeze-review-a-funky-fresh-switch-update/">https://venturebeat.com/2018/05/01/donkey-kong-country-tropica...</a>, short URL: <a href="https://cz.ign.com/se/?q=mario">https://cz.ign.com/se/?q=mario</a>',$lfinder->process($src)); $lfinder = new LinkFinder(array("shorten_long_urls" => false)); $this->assertEquals('Long URL: <a href="https://venturebeat.com/2018/05/01/donkey-kong-country-tropical-freeze-review-a-funky-fresh-switch-update/">https://venturebeat.com/2018/05/01/donkey-kong-country-tropical-freeze-review-a-funky-fresh-switch-update/</a>, short URL: <a href="https://cz.ign.com/se/?q=mario">https://cz.ign.com/se/?q=mario</a>',$lfinder->process($src));
URLs are shortened to a maximum of <I> characters
yarri_LinkFinder
train
8d917cc3a40333def2e51cfeff16eb1cdf54720d
diff --git a/jupyter-js-widgets/src/widget_selection.js b/jupyter-js-widgets/src/widget_selection.js index <HASH>..<HASH> 100644 --- a/jupyter-js-widgets/src/widget_selection.js +++ b/jupyter-js-widgets/src/widget_selection.js @@ -47,6 +47,7 @@ var DropdownView = widget.DOMWidgetView.extend({ .addClass('dropdown-toggle') .addClass('widget-combo-carrot-btn') .attr('data-toggle', 'dropdown') + .click(this._showDropdown.bind(this)) .append($('<span />').addClass("caret")) .appendTo(this.$buttongroup); this.$droplist = $('<ul />') @@ -60,6 +61,37 @@ var DropdownView = widget.DOMWidgetView.extend({ this.update(); }, + /** + * Show the dropdown list. + * + * If the dropdown list doesn't fit below the dropdown label, this will + * cause the dropdown to be dropped "up". + * @param {Event} e + */ + _showDropdown: function(e) { + // Don't allow bootstrap to show the dropdown! + e.stopImmediatePropagation(); + e.preventDefault(); + + // Get the bottom of the dropdown label, and the bottom of the nb site. + // The difference is the maximum height of the dropmenu when displayed + // below the button. + var droplabelRect = this.$droplabel[0].getBoundingClientRect(); + var siteRect = document.querySelector('#site').getBoundingClientRect(); + var maxHeight = siteRect.bottom - droplabelRect.bottom; + + // If the maximum height of the dropdown's space is less than the + // height of the dropdown itself, make it drop up! + if (maxHeight < 200) { + this.$buttongroup[0].classList.add('dropup'); + } else { + this.$buttongroup[0].classList.remove('dropup'); + } + + // Show the dropdown(or up) + this.$dropbutton.dropdown('toggle'); + }, + update : function(options) { /** * Update the contents of this view
Drop the dropdown upwards if it's too long.
jupyter-widgets_ipywidgets
train
aa220d7727ee869c0d8f864f8acc67112b819b59
diff --git a/src/lib/builtins.js b/src/lib/builtins.js index <HASH>..<HASH> 100644 --- a/src/lib/builtins.js +++ b/src/lib/builtins.js @@ -20,9 +20,9 @@ export class FTLNumber extends FTLBase { constructor(value, opts) { super(parseFloat(value), opts); } - toString(bundle, lang) { + toString(bundle) { const nf = bundle._memoizeIntlObject( - L20nIntl.NumberFormat, lang, this.opts + L20nIntl.NumberFormat, this.opts ); return nf.format(this.value); } @@ -32,9 +32,9 @@ export class FTLDateTime extends FTLBase { constructor(value, opts) { super(new Date(value), opts); } - toString(bundle, lang) { + toString(bundle) { const dtf = bundle._memoizeIntlObject( - L20nIntl.DateTimeFormat, lang, this.opts + L20nIntl.DateTimeFormat, this.opts ); return dtf.format(this.value); } @@ -45,7 +45,7 @@ export class FTLKeyword extends FTLBase { const { name, namespace } = this.value; return namespace ? `${namespace}:${name}` : name; } - match(bundle, lang, other) { + match(bundle, other) { const { name, namespace } = this.value; if (other instanceof FTLKeyword) { return name === other.value.name && namespace === other.value.namespace; @@ -55,7 +55,7 @@ export class FTLKeyword extends FTLBase { return name === other; } else if (other instanceof FTLNumber) { const pr = bundle._memoizeIntlObject( - L20nIntl.PluralRules, lang, other.opts + L20nIntl.PluralRules, other.opts ); return name === pr.select(other.valueOf()); } @@ -63,12 +63,12 @@ export class FTLKeyword extends FTLBase { } export class FTLList extends Array { - toString(bundle, lang) { + toString(bundle) { const lf = bundle._memoizeIntlObject( - L20nIntl.ListFormat, lang // XXX add this.opts + L20nIntl.ListFormat // XXX add this.opts ); const elems = this.map( - elem => elem.toString(bundle, lang) + elem => elem.toString(bundle) ); return lf.format(elems); } diff --git a/src/lib/bundle.js b/src/lib/bundle.js index <HASH>..<HASH> 100644 --- a/src/lib/bundle.js +++ b/src/lib/bundle.js @@ -19,15 +19,15 @@ export class Bundle { } format(entity, args) { - return format(this, this.lang, args, entity); + return format(this, args, entity); } - _memoizeIntlObject(ctor, lang, opts) { + _memoizeIntlObject(ctor, opts) { const cache = this._intls.get(ctor) || {}; - const id = lang + JSON.stringify(opts); + const id = JSON.stringify(opts); if (!cache[id]) { - cache[id] = new ctor(lang, opts); + cache[id] = new ctor(this.lang, opts); this._intls.set(ctor, cache); } diff --git a/src/lib/resolver.js b/src/lib/resolver.js index <HASH>..<HASH> 100644 --- a/src/lib/resolver.js +++ b/src/lib/resolver.js @@ -55,17 +55,17 @@ function* MemberExpression({obj, key}) { return { val: entity }; } - const { bundle, lang } = yield ask(); + const { bundle } = yield ask(); const keyword = yield* Value(key); for (let member of entity.traits) { const memberKey = yield* Value(member.key); - if (keyword.match(bundle, lang, memberKey)) { + if (keyword.match(bundle, memberKey)) { return member; } } - yield err(`Unknown trait: ${key.toString(bundle, lang)}`); + yield err(`Unknown trait: ${key.toString(bundle)}`); return { val: yield* Entity(entity) }; @@ -86,10 +86,10 @@ function* SelectExpression({exp, vars}) { return variant; } - const { bundle, lang } = yield ask(); + const { bundle } = yield ask(); if (key instanceof FTLKeyword && - key.match(bundle, lang, selector)) { + key.match(bundle, selector)) { return variant; } } @@ -196,7 +196,7 @@ function* CallExpression({name, args}) { } function* Pattern(ptn) { - const { bundle, lang, dirty } = yield ask(); + const { bundle, dirty } = yield ask(); if (dirty.has(ptn)) { yield err('Cyclic reference'); @@ -213,7 +213,7 @@ function* Pattern(ptn) { const value = part.length === 1 ? yield* Value(part[0]) : yield* mapValues(part); - const str = value.toString(bundle, lang); + const str = value.toString(bundle); if (str.length > MAX_PLACEABLE_LENGTH) { yield err( 'Too many characters in placeable ' + @@ -252,12 +252,12 @@ function* toString(entity) { return value.toString(); } -export function format(bundle, lang, args, entity) { +export function format(bundle, args, entity) { if (typeof entity === 'string') { return [entity, []]; } return resolve(toString(entity)).run({ - bundle, lang, args, dirty: new WeakSet() + bundle, args, dirty: new WeakSet() }); }
Use bundle.lang in the resolver
l20n_l20n.js
train
19f127b7ff177bed0a0ebdfd2e0720f6acfc6bd2
diff --git a/lib/chef/data_bag.rb b/lib/chef/data_bag.rb index <HASH>..<HASH> 100644 --- a/lib/chef/data_bag.rb +++ b/lib/chef/data_bag.rb @@ -32,7 +32,8 @@ class Chef include Chef::Mixin::FromFile include Chef::Mixin::ParamsValidate - VALID_NAME = /^[\.\-[:alnum:]_]+$/.freeze + # Regex reference: https://rubular.com/r/oIMySIO4USPm5x + VALID_NAME = /^[\-[:alnum:]_]+$/.freeze RESERVED_NAMES = /^(node|role|environment|client)$/.freeze def self.validate_name!(name) diff --git a/lib/chef/data_bag_item.rb b/lib/chef/data_bag_item.rb index <HASH>..<HASH> 100644 --- a/lib/chef/data_bag_item.rb +++ b/lib/chef/data_bag_item.rb @@ -36,7 +36,8 @@ class Chef include Chef::Mixin::FromFile include Chef::Mixin::ParamsValidate - VALID_ID = /^[\.\-[:alnum:]_]+$/.freeze + # Regex reference: https://rubular.com/r/oIMySIO4USPm5x + VALID_ID = /^[\-[:alnum:]_]+$/.freeze def self.validate_id!(id_str) if id_str.nil? || ( id_str !~ VALID_ID ) diff --git a/spec/unit/data_bag_item_spec.rb b/spec/unit/data_bag_item_spec.rb index <HASH>..<HASH> 100644 --- a/spec/unit/data_bag_item_spec.rb +++ b/spec/unit/data_bag_item_spec.rb @@ -73,11 +73,11 @@ describe Chef::DataBagItem do end it "should accept alphanum.alphanum for the id" do - expect { data_bag_item.raw_data = { "id" => "foo.bar" } }.not_to raise_error + expect { data_bag_item.raw_data = { "id" => "foo.bar" } }.to raise_error(ArgumentError) end it "should accept .alphanum for the id" do - expect { data_bag_item.raw_data = { "id" => ".bozo" } }.not_to raise_error + expect { data_bag_item.raw_data = { "id" => ".bozo" } }.to raise_error(ArgumentError) end it "should raise an exception if the id contains anything but alphanum/-/_" do diff --git a/spec/unit/data_bag_spec.rb b/spec/unit/data_bag_spec.rb index <HASH>..<HASH> 100644 --- a/spec/unit/data_bag_spec.rb +++ b/spec/unit/data_bag_spec.rb @@ -49,7 +49,7 @@ describe Chef::DataBag do expect { @data_bag.name({}) }.to raise_error(ArgumentError) end - [ ".", "-", "_", "1"].each do |char| + ["-", "_", "1"].each do |char| it "should allow a '#{char}' character in the data bag name" do expect(@data_bag.name("clown#{char}clown")).to eq("clown#{char}clown") end
Fixed Validation failed while creating databag and databag item
chef_chef
train
5709f229f4046b14d7c23a67540abbe153a55156
diff --git a/setup.py b/setup.py index <HASH>..<HASH> 100755 --- a/setup.py +++ b/setup.py @@ -42,7 +42,7 @@ setup(name='deepdiff', long_description=long_description, long_description_content_type='text/markdown', install_requires=reqs, - python_requires='>=3.4', + python_requires='>=3.5', extras_require={ "murmur": ["mmh3"], }, @@ -50,7 +50,6 @@ setup(name='deepdiff', "Intended Audience :: Developers", "Operating System :: OS Independent", "Topic :: Software Development", - "Programming Language :: Python :: 3.4", "Programming Language :: Python :: 3.5", "Programming Language :: Python :: 3.6", "Programming Language :: Python :: 3.7",
updating setup.py to remove <I> as supported
seperman_deepdiff
train
f7ea16d757a3000580897914ef2343ced19048a1
diff --git a/lib/discovery/worker/inside/blocks.js b/lib/discovery/worker/inside/blocks.js index <HASH>..<HASH> 100644 --- a/lib/discovery/worker/inside/blocks.js +++ b/lib/discovery/worker/inside/blocks.js @@ -30,6 +30,12 @@ export function loadBlockRange(initialState: AccountInfo): Promise<BlockRange> { console.warn('Blockhash mismatch', pBlock, block); return nullBlock; } + }, (err) => { + if (err.message === 'RPCError: Block height out of range') { + console.warn('Block height out of range', pBlock.height); + return nullBlock; + } + throw err; }) : Promise.resolve(nullBlock);
Add correct detection of longer orphaned chain
trezor_hd-wallet
train
f6761cfe6499cb08bea662553e5d0c8e3deaece2
diff --git a/tests/org.eclipse.xtext.tests/src/org/eclipse/xtext/util/formallang/FollowerFunctionTest.java b/tests/org.eclipse.xtext.tests/src/org/eclipse/xtext/util/formallang/FollowerFunctionTest.java index <HASH>..<HASH> 100644 --- a/tests/org.eclipse.xtext.tests/src/org/eclipse/xtext/util/formallang/FollowerFunctionTest.java +++ b/tests/org.eclipse.xtext.tests/src/org/eclipse/xtext/util/formallang/FollowerFunctionTest.java @@ -26,8 +26,8 @@ public class FollowerFunctionTest extends TestCase { public String apply(ProdElement from) { if (from == null) return "null"; - if (from.value != null) - return "'" + from.value + "'"; + if (from.getValue() != null) + return "'" + from.getValue() + "'"; return from.toString(); } }
[util.formallang] access properties via getters; this broke the build
eclipse_xtext-extras
train
893672d0e3c1864d3cb3f1da7b5d45b48bbaca02
diff --git a/data.py b/data.py index <HASH>..<HASH> 100644 --- a/data.py +++ b/data.py @@ -1,3 +1,4 @@ +from collections import OrderedDict from wtforms.ext.sqlalchemy.fields import QuerySelectField # , QuerySelectMultipleField from wtforms_alchemy import ModelForm @@ -62,7 +63,9 @@ class TagForm(SessionModelForm): tagkind_controller = sa_controller.SQLAlchemyController( - model_class=TagKind, db_session=Session) + db_session=Session, + model_class=TagKind, +) tagkind_display = display.Display( form_class=KindForm, list=rules.ColumnSet(['id', 'name']), @@ -76,12 +79,11 @@ tagkind_display = display.Display( tag_controller = sa_controller.SQLAlchemyController( db_session=Session, model_class=Tag, - filters={ - 'search': sa_filters.SearchFilter([Tag.name, Tag.rules]), - 'kind': sa_filters.JoinColumnFilter( - TagKind.name, TagKind), - 'name': sa_filters.ColumnFilter(Tag.name), - }, + filters=OrderedDict([ + ('search', sa_filters.SearchFilter([Tag.name, Tag.rules])), + ('name', sa_filters.ColumnFilter(Tag.name)), + ('kind', sa_filters.JoinColumnFilter(TagKind.name, TagKind)), + ]) ) tag_display = display.Display( form_class=TagForm,
use a orderect dict to sort filters
hellupline_flask-manager
train
350743b9f3ee57d3d16e9349c03e2be722d71752
diff --git a/lib/x-router-angular.js b/lib/x-router-angular.js index <HASH>..<HASH> 100755 --- a/lib/x-router-angular.js +++ b/lib/x-router-angular.js @@ -265,9 +265,8 @@ var cache = window._xrouter_angular_cache_ || (window._xrouter_angular_cache_ = function engine(defaults) { defaults = defaults || {}; - var util = angularutil(defaults.app); - return function(options, done) { + var util = angularutil(options.app || defaults.app); var src = options.src; var html = options.html; var target = options.target; @@ -289,7 +288,7 @@ function engine(defaults) { if( ie && ie <= 11 ) usecache = false; if( response ) { - response.angular = response.angular || util; + response.angular = util; } if( controller && typeof controller === 'string' ) {
fix 'app' option to work
attrs_x-router-angular
train