diff
stringlengths
139
3.65k
message
stringlengths
8
627
diff_languages
stringclasses
1 value
diff --git a/cloud_blobstore/s3.py b/cloud_blobstore/s3.py index <HASH>..<HASH> 100644 --- a/cloud_blobstore/s3.py +++ b/cloud_blobstore/s3.py @@ -332,7 +332,7 @@ class S3BlobStore(BlobStore): Key=dst_key, ExtraArgs=kwargs, Config=TransferConfig( - multipart_threshold=64 * 1024 * 1024, + multipart_threshold=(64 * 1024 * 1024) + 1, multipart_chunksize=64 * 1024 * 1024, ), )
push the multipart threshold to <I>MB + 1B
py
diff --git a/ipfsApi/http.py b/ipfsApi/http.py index <HASH>..<HASH> 100644 --- a/ipfsApi/http.py +++ b/ipfsApi/http.py @@ -4,6 +4,7 @@ can/will eventually be supplemented with an asynchronous version. """ from __future__ import absolute_import +import re import requests import contextlib @@ -28,7 +29,10 @@ class HTTPClient(object): def __init__(self, host, port, base, default_enc, **defaults): self.host = host self.port = port - self.base = 'http://%s:%s/%s' % (host, port, base) + if not re.match('^https?://', host.lower()): + host = 'http://' + host + + self.base = '%s:%s/%s' % (host, port, base) # default request keyword-args if 'opts' in defaults:
Add support for specifying HTTPS or HTTP in the hostname.
py
diff --git a/molo/core/middleware.py b/molo/core/middleware.py index <HASH>..<HASH> 100644 --- a/molo/core/middleware.py +++ b/molo/core/middleware.py @@ -135,3 +135,14 @@ class MoloGoogleAnalyticsMiddleware(object): site_settings.global_ga_tracking_code, request, response) return response + + +class MultiSiteRedirectToHomepage(object): + + def process_request(self, request): + print request.site + print request.get_host() + + # if request.path and + # url = request.site.root_url + ':8000' + request.path_info + # return redirect(url)
adding middleware for site redirect (incomplete)
py
diff --git a/symbols/const.py b/symbols/const.py index <HASH>..<HASH> 100644 --- a/symbols/const.py +++ b/symbols/const.py @@ -30,7 +30,8 @@ class SymbolCONST(Symbol): @expr.setter def expr(self, value): - self.children[0] = value + assert isinstance(value, Symbol) + self.children = [value] @property def type_(self):
Asserts value checking for Symbol
py
diff --git a/monero_serialize/xmrtypes.py b/monero_serialize/xmrtypes.py index <HASH>..<HASH> 100644 --- a/monero_serialize/xmrtypes.py +++ b/monero_serialize/xmrtypes.py @@ -948,3 +948,14 @@ class CacheFileData(x.MessageType): ('cache_data', x.BlobType), ] + +class AccountKeys(x.MessageType): + FIELDS = [ + ('m_account_address', AccountPublicAddress), + ('m_spend_secret_key', SecretKey), + ('m_view_secret_key', SecretKey), + ('m_multisig_keys', x.ContainerType, SecretKey), + ] + + +
xmrtypes: account keys added
py
diff --git a/mpop/saturn/two_line_elements.py b/mpop/saturn/two_line_elements.py index <HASH>..<HASH> 100644 --- a/mpop/saturn/two_line_elements.py +++ b/mpop/saturn/two_line_elements.py @@ -58,7 +58,8 @@ if sys.version_info < (2, 5): """ return datetime.datetime(*time.strptime(string, fmt)[:6]) - +else: + strptime = datetime.datetime.strptime class Tle(object): def __init__(self, tle=None, satellite=None):
Bugfix: forgot strptime = datetime.strptime when python > <I>
py
diff --git a/setup.py b/setup.py index <HASH>..<HASH> 100644 --- a/setup.py +++ b/setup.py @@ -13,6 +13,7 @@ Copyright 2015, Andrew Colin Kissa Licensed under MPL 2.0. """ import os +import sys try: import multiprocessing
* Ensure unittest2 is only required on Py<I>
py
diff --git a/internetarchive/item.py b/internetarchive/item.py index <HASH>..<HASH> 100644 --- a/internetarchive/item.py +++ b/internetarchive/item.py @@ -83,6 +83,7 @@ class Item(object): self.server = None self.uniq = None self.updated = None + self.tasks = None self._json = self.get_metadata(metadata_timeout) self.exists = False if self._json == {} else True @@ -390,7 +391,7 @@ class Item(object): # Skip based on checksum. md5_sum = utils.get_md5(body) ia_file = self.get_file(key) - if (checksum) and (ia_file) and (ia_file.md5 == md5_sum): + if (checksum) and (not self.tasks) and (ia_file) and (ia_file.md5 == md5_sum): log.info('{f} already exists: {u}'.format(f=key, u=url)) if verbose: sys.stdout.write(' {f} already exists, skipping.\n'.format(f=key))
Only skip based on checksum if there are no pending tasks.
py
diff --git a/fermipy/jobs/link.py b/fermipy/jobs/link.py index <HASH>..<HASH> 100644 --- a/fermipy/jobs/link.py +++ b/fermipy/jobs/link.py @@ -625,6 +625,11 @@ class Link(object): """ self.jobs.clear() + def clean_jobs(self, clean_all=False): + """ """ + self._interface.clean_jobs(self, + job_archive=self._job_archive) + def get_jobs(self, recursive=True): """Return a dictionary with all the jobs
Added Link.clean_jobs
py
diff --git a/taxtastic/subcommands/taxtable.py b/taxtastic/subcommands/taxtable.py index <HASH>..<HASH> 100644 --- a/taxtastic/subcommands/taxtable.py +++ b/taxtastic/subcommands/taxtable.py @@ -162,8 +162,13 @@ def action(args): taxtable.update(dict(tax_rows)) all_ranks |= set(ranks) + # guppy requires that tax_id == parent_id for the root node + taxtable['1']['parent_id'] = '1' + sorted_ranks = sorted(all_ranks, key=order_ranks(tax.ranks[::-1])) - fieldnames = ['tax_id', 'parent_id', 'tax_name', 'rank'] + sorted_ranks + + # guppy requires this column order + fieldnames = ['tax_id', 'parent_id', 'rank', 'tax_name'] + sorted_ranks output = taxtable.values() log.info('sorting lineages')
fixes for guppy - set tax_id == parent_id == 1 for root node - fix field order in taxtable
py
diff --git a/rest_api/api.py b/rest_api/api.py index <HASH>..<HASH> 100644 --- a/rest_api/api.py +++ b/rest_api/api.py @@ -327,7 +327,9 @@ def assemble_pysb(): fname = 'model_%s.png' % export_format root = os.path.dirname(os.path.abspath(fname)) graph = pa.export_model(format=export_format, file_name=fname) - return static_file(fname, mimetype='image/png', root=root) + response = static_file(fname, mimetype='image/png', root=root) + response.set_header('Access-Control-allow-Origin', '*') + return response else: try: model_str = pa.export_model(format=export_format)
Add CORS header to static_file response
py
diff --git a/bika/lims/browser/bika_listing.py b/bika/lims/browser/bika_listing.py index <HASH>..<HASH> 100644 --- a/bika/lims/browser/bika_listing.py +++ b/bika/lims/browser/bika_listing.py @@ -223,7 +223,7 @@ class BikaListingView(BrowserView): # index filters. for k,v in self.columns.items(): - if not v.has_key('index'): + if not v.has_key('index') or v['index'] == 'review_state': continue request_key = "%s_%s" % (self.form_id, v['index']) if request_key in self.request:
Bika listing 'all' links fixed (closes #<I>)
py
diff --git a/glances/plugins/glances_network.py b/glances/plugins/glances_network.py index <HASH>..<HASH> 100644 --- a/glances/plugins/glances_network.py +++ b/glances/plugins/glances_network.py @@ -108,7 +108,8 @@ class Plugin(GlancesPlugin): network_new = netiocounters for net in network_new: # Do not take hidden interface into account - if self.is_hide(net): + # or KeyError: 'eth0' when interface is not connected #1348 + if self.is_hide(net) or net not in netstatus: continue try: cumulative_rx = network_new[net].bytes_recv
KeyError: 'eth0' when interface is not connected #<I>
py
diff --git a/dynamic_dynamodb/config/command_line_parser.py b/dynamic_dynamodb/config/command_line_parser.py index <HASH>..<HASH> 100644 --- a/dynamic_dynamodb/config/command_line_parser.py +++ b/dynamic_dynamodb/config/command_line_parser.py @@ -73,6 +73,12 @@ def parse(): the currently consumed read units reaches this many percent (default: 90)""") r_scaling_ag.add_argument( + '--throttled-read-upper-threshold', + type=int, + help="""Scale up the reads with --increase-reads-with percent if + the count of throttled read events exceeds this + count (default: 100)""") + r_scaling_ag.add_argument( '--reads-lower-threshold', type=int, help="""Scale down the reads with --decrease-reads-with percent if the @@ -112,6 +118,12 @@ def parse(): if the currently consumed write units reaches this many percent (default: 90)""") w_scaling_ag.add_argument( + '--throttled-write-upper-threshold', + type=int, + help="""Scale up the reads with --increase-writes-with percent if + the count of throttled write events exceeds this + count (default: 100)""") + w_scaling_ag.add_argument( '--writes-lower-threshold', type=int, help="""Scale down the writes with --decrease-writes-with percent
Add command line options for setting throttled read/write event thresholds
py
diff --git a/sos/plugins/docker.py b/sos/plugins/docker.py index <HASH>..<HASH> 100644 --- a/sos/plugins/docker.py +++ b/sos/plugins/docker.py @@ -77,10 +77,18 @@ class Docker(Plugin): if self.get_option('all'): ps_cmd = "{0} -a".format(ps_cmd) - result = self.get_command_output(ps_cmd) - if result['status'] == 0: - containers = [c for c in result['output'].splitlines()] - for container in containers: + img_cmd = '{0} images -q'.format(self.docker_cmd) + insp = set() + + for icmd in [ps_cmd, img_cmd]: + result = self.get_command_output(icmd) + if result['status'] == 0: + for con in result['output'].splitlines(): + insp.add(con) + + insp = list(insp) + if insp: + for container in insp: self.add_cmd_output( "{0} inspect {1}".format( self.docker_cmd,
[docker] Collect image inspect output (#<I>) Adds output for 'docker inspect' for each unique image on the host.
py
diff --git a/pylibdmtx/wrapper.py b/pylibdmtx/wrapper.py index <HASH>..<HASH> 100644 --- a/pylibdmtx/wrapper.py +++ b/pylibdmtx/wrapper.py @@ -278,7 +278,10 @@ def load_libdmtx(): else: raise PyLibDMTXError('Unable to find libdmtx DLL') else: - LIBDMTX = cdll.LoadLibrary(find_library('dmtx')) + path = find_library('dmtx') + if not path: + raise PyLibDMTXError('Unable to find libdmtx shared library') + LIBDMTX = cdll.LoadLibrary(path) return LIBDMTX
Better error handling if shared library not found
py
diff --git a/evergreen/core/utils.py b/evergreen/core/utils.py index <HASH>..<HASH> 100644 --- a/evergreen/core/utils.py +++ b/evergreen/core/utils.py @@ -59,6 +59,7 @@ class Result(object): return self._value finally: self._used = True + self._exc = self._value = Null def set_value(self, value): assert self._locked
Reset value and exception after calling Result.get
py
diff --git a/winpcapy/__init__.py b/winpcapy/__init__.py index <HASH>..<HASH> 100644 --- a/winpcapy/__init__.py +++ b/winpcapy/__init__.py @@ -17,7 +17,7 @@ __description__ = "A Modern Python wrapper for WinPcap" __uri__ = "https://github.com/orweis/winpcapy" __doc__ = __description__ + " <" + __uri__ + ">" __email__ = "py@bitweis.com" -__version__ = "1.0.1" +__version__ = "1.0.2" __license__ = "GPLv2" __copyright__ = "Copyright (c) 2015 Or Weis"
Inc version number, for PyPi upload
py
diff --git a/great_expectations/data_context/data_context.py b/great_expectations/data_context/data_context.py index <HASH>..<HASH> 100644 --- a/great_expectations/data_context/data_context.py +++ b/great_expectations/data_context/data_context.py @@ -682,6 +682,7 @@ class BaseDataContext(object): raise ValueError( "Unable to load datasource `%s` -- no configuration found or invalid configuration." % datasource_name ) + datasource_config = datasourceConfigSchema.load(datasource_config) datasource = self._build_datasource_from_config(datasource_name, datasource_config) self._datasources[datasource_name] = datasource return datasource
Load datasource config before building datasource from config
py
diff --git a/pygeoip/const.py b/pygeoip/const.py index <HASH>..<HASH> 100644 --- a/pygeoip/const.py +++ b/pygeoip/const.py @@ -354,7 +354,7 @@ COUNTRY_NAMES = ( 'Yemen', 'Mayotte', 'Serbia', 'South Africa', 'Zambia', 'Montenegro', 'Zimbabwe', 'Anonymous Proxy', 'Satellite Provider', 'Other', 'Aland Islands', 'Guernsey', 'Isle of Man', 'Jersey', 'Saint Barthelemy', - 'Saint Martin', 'Bonaire, Sint Eustatius and Saba', 'South Sudan, Republic of', + 'Saint Martin', 'Bonaire, Sint Eustatius and Saba', 'South Sudan' ) # storage / caching flags
Drop 'Republic of' from South Sudan
py
diff --git a/hpcbench/cli/benwait.py b/hpcbench/cli/benwait.py index <HASH>..<HASH> 100644 --- a/hpcbench/cli/benwait.py +++ b/hpcbench/cli/benwait.py @@ -6,11 +6,11 @@ Usage: ben-wait --version Options: - -l --log=LOGFILE Specify an option logfile to write to - -n <seconds>, --interval <seconds> Specify wait interval [default: 10] - -h --help Show this screen - --version Show version - -v -vv Increase program verbosity + -l --log=LOGFILE Specify an option logfile to write to. + -n <seconds>, --interval <seconds> Specify wait interval [default: 10]. + -h --help Show this screen. + --version Show version. + -v -vv Increase program verbosity. """ import logging
fix ben-wait: --interval default value was None
py
diff --git a/plans/views.py b/plans/views.py index <HASH>..<HASH> 100644 --- a/plans/views.py +++ b/plans/views.py @@ -431,5 +431,8 @@ class InvoiceDetailView(DetailView): return context def get_queryset(self): - return super(InvoiceDetailView, self).get_queryset().filter(user=self.request.user) + if self.request.user.is_superuser: + return super(InvoiceDetailView, self).get_queryset() + else: + return super(InvoiceDetailView, self).get_queryset().filter(user=self.request.user)
Invoice can be displayed also by superuser (not only owner).
py
diff --git a/bdbag/bdbag_cli.py b/bdbag/bdbag_cli.py index <HASH>..<HASH> 100644 --- a/bdbag/bdbag_cli.py +++ b/bdbag/bdbag_cli.py @@ -136,6 +136,12 @@ def parse_cli(): "The bag must first be extracted and then updated.\n\n") sys.exit(2) + if args.resolve_fetch and is_file: + sys.stderr.write("Error: It is not possible to resolve remote files directly into a bag archive. " + "The bag must first be extracted before the %s argument can be specified.\n\n" % + fetch_arg.option_strings) + sys.exit(2) + if args.update and args.resolve_fetch: sys.stderr.write("Error: The %s argument is not compatible with the %s argument.\n\n" % (update_arg.option_strings, fetch_arg.option_strings))
Don't allow --resolve-fetch against an archived bag.
py
diff --git a/setup.py b/setup.py index <HASH>..<HASH> 100755 --- a/setup.py +++ b/setup.py @@ -19,6 +19,10 @@ setup( long_description_content_type = "text/markdown", python_requires = ">=2.7, <4", + install_requires = [ + "docopt>=0.6" + ], + py_modules = [info.PKG_NAME], entry_points = { "console_scripts": [
Add missing install dependencies to setup.py
py
diff --git a/tweepy/api.py b/tweepy/api.py index <HASH>..<HASH> 100644 --- a/tweepy/api.py +++ b/tweepy/api.py @@ -296,7 +296,8 @@ class API: chunk_size = kwargs.pop('chunk_size', DEFAULT_CHUNKSIZE) chunk_size = max(min(chunk_size, MAX_CHUNKSIZE), MIN_CHUNKSIZE) - segments = file_size // (chunk_size * 1024) + bool(file_size % chunk_size) + segments, remainder = divmod(file_size, chunk_size * 1024) + segments += bool(remainder) for segment_index in range(segments): # The APPEND command returns an empty response body
Fix logic in determining number of segments in API.chunked_upload
py
diff --git a/cassiopeia/dto/requests.py b/cassiopeia/dto/requests.py index <HASH>..<HASH> 100644 --- a/cassiopeia/dto/requests.py +++ b/cassiopeia/dto/requests.py @@ -130,7 +130,10 @@ def execute_request(url, method, payload=""): response = urllib.request.urlopen(request) content = response.read() if content: - content = zlib.decompress(content, zlib.MAX_WBITS | 16).decode(encoding="UTF-8") + if "gzip" == response.getheader("Content-Encoding"): + content = zlib.decompress(content, zlib.MAX_WBITS | 16).decode(encoding="UTF-8") + else: + content = content.decode("UTF-8") return content finally: if response:
check for gzip support before decompressing
py
diff --git a/notario/engine.py b/notario/engine.py index <HASH>..<HASH> 100644 --- a/notario/engine.py +++ b/notario/engine.py @@ -66,6 +66,14 @@ class Validator(object): if failed: return failed + # if there are no callables in the schema keys, just + # find the missing data key directly + if all([not is_callable(s) for s in schema_keys]): + for schema_key in schema_keys: + if schema_key not in data_keys: + msg = "required key in data is missing: %s" % str(schema_key) + raise Invalid(None, tree, reason=msg, pair='key') + for schema_key in schema_keys: failure = enforce_once(data_keys, schema_key) if failure:
If only noncallable schema keys, identify the missing data exactly
py
diff --git a/master/buildbot/plugins/__init__.py b/master/buildbot/plugins/__init__.py index <HASH>..<HASH> 100644 --- a/master/buildbot/plugins/__init__.py +++ b/master/buildbot/plugins/__init__.py @@ -26,8 +26,7 @@ from buildbot.plugins.db import get_plugins __all__ = [ 'changes', 'schedulers', 'steps', 'util', 'reporters', 'statistics', - 'worker', 'secrets', 'webhooks', - 'buildslave', # deprecated, use 'worker' instead. + 'worker', 'secrets', 'webhooks' ] @@ -41,8 +40,5 @@ reporters = get_plugins('reporters', None) secrets = get_plugins('secrets', None) webhooks = get_plugins('webhooks', None) -# For plugins that are not updated to the new worker names, plus fallback of -# current Buildbot plugins for old configuration files. -buildslave = get_plugins('buildslave', IWorker) # Worker entry point for new/updated plugins. worker = get_plugins('worker', IWorker)
Remove remaining buildslave plugin importer
py
diff --git a/salt/modules/lxcdocker.py b/salt/modules/lxcdocker.py index <HASH>..<HASH> 100644 --- a/salt/modules/lxcdocker.py +++ b/salt/modules/lxcdocker.py @@ -1821,7 +1821,7 @@ def script_retcode(container, others params and documentation See cmd.retcode ''' - return script(container, + return _script(container, source=source, cwd=cwd, stdin=stdin,
docker: typo in ret_code
py
diff --git a/masonite/providers/UploadProvider.py b/masonite/providers/UploadProvider.py index <HASH>..<HASH> 100644 --- a/masonite/providers/UploadProvider.py +++ b/masonite/providers/UploadProvider.py @@ -15,5 +15,5 @@ class UploadProvider(ServiceProvider): self.app.bind('UploadS3Driver', UploadS3Driver) self.app.bind('UploadManager', UploadManager(self.app)) - def boot(self, UploadManager): - self.app.bind('Upload', UploadManager.driver('disk')) + def boot(self, UploadManager, StorageConfig): + self.app.bind('Upload', UploadManager.driver(StorageConfig.DRIVER))
fixed upload driver not defaulting to config driver
py
diff --git a/tests/contracts/test_normalization_of_return_types.py b/tests/contracts/test_normalization_of_return_types.py index <HASH>..<HASH> 100644 --- a/tests/contracts/test_normalization_of_return_types.py +++ b/tests/contracts/test_normalization_of_return_types.py @@ -28,7 +28,9 @@ from web3.utils.abi import normalize_return_type '0xbb9bc244d798123fde783fcc1c72d3bb8c189413', ], ), - ) + ), + ids=['nullbyte', 'soloaddr', 'addrlist'] + ) def test_normalizing_return_values(data_type, data_value, expected_value): actual_value = normalize_return_type(data_type, data_value)
cleaner formatting as a workaround for pytest <I> bug @see <URL>
py
diff --git a/theanets/recurrent.py b/theanets/recurrent.py index <HASH>..<HASH> 100644 --- a/theanets/recurrent.py +++ b/theanets/recurrent.py @@ -85,7 +85,9 @@ class Text(object): self.alpha = alpha if self.alpha is None: self.alpha = ''.join(sorted(set( - a for a, c in collections.Counter(text).items() if c >= min_count))) + a for a, c in + collections.Counter(text).items() + if c >= min_count and c != unknown))) self.text = re.sub(r'[^{}]'.format(re.escape(self.alpha)), unknown, text) assert unknown not in self.alpha self._rev_index = unknown + self.alpha
Exclude "unknown" from alphabet construction.
py
diff --git a/django_conneg/views.py b/django_conneg/views.py index <HASH>..<HASH> 100644 --- a/django_conneg/views.py +++ b/django_conneg/views.py @@ -222,8 +222,6 @@ class ContentNegotiatedView(BaseContentNegotiatedView): return self.error(request, e, args, kwargs, httplib.FORBIDDEN) except HttpNotAcceptable, e: return self.error(request, e, args, kwargs, httplib.NOT_ACCEPTABLE) - except Exception, e: - return self.error(request, e, args, kwargs, httplib.INTERNAL_SERVER_ERROR) def http_not_acceptable(self, request, tried_mimetypes, *args, **kwargs): raise HttpNotAcceptable(tried_mimetypes) @@ -266,11 +264,7 @@ class ContentNegotiatedView(BaseContentNegotiatedView): return self.error_view(request, context, self.error_template_names[httplib.NOT_ACCEPTABLE]) - def error_500(self, request, exception, *args, **kwargs): - # Be careful overriding this; you could well lose error-reporting. - # Much better to set handler500 in your urlconf. - raise - +# For backwards compatibility ErrorCatchingView = ContentNegotiatedView class HTMLView(ContentNegotiatedView):
Catching and re-raising Exception is just a hassle. Let's not do that
py
diff --git a/shinken/modules/ws_arbiter.py b/shinken/modules/ws_arbiter.py index <HASH>..<HASH> 100644 --- a/shinken/modules/ws_arbiter.py +++ b/shinken/modules/ws_arbiter.py @@ -54,7 +54,7 @@ app = None def get_page(): # We get all value we want - time_stamp = request.forms.get('time_stamp', 0) + time_stamp = request.forms.get('time_stamp', int(time.time())) host_name = request.forms.get('host_name', None) service_description = request.forms.get('service_description', None) return_code = request.forms.get('return_code', -1)
Fix: If no timestamp in POST data, then it is now()
py
diff --git a/processors/generic_processor.py b/processors/generic_processor.py index <HASH>..<HASH> 100644 --- a/processors/generic_processor.py +++ b/processors/generic_processor.py @@ -17,6 +17,7 @@ """Import processor that supports all Bazaar repository formats.""" +import os import time from bzrlib import ( builtins,
fix missing os import in generic_processor
py
diff --git a/tests/test_data_structures.py b/tests/test_data_structures.py index <HASH>..<HASH> 100644 --- a/tests/test_data_structures.py +++ b/tests/test_data_structures.py @@ -17,7 +17,24 @@ class TestCompressionParameters(unittest.TestCase): zstd.CompressionParameters() with self.assertRaises(TypeError): - zstd.CompressionParameters((0, 1)) + zstd.CompressionParameters(0, 1) + + def test_bounds(self): + zstd.CompressionParameters(zstd.WINDOWLOG_MIN, + zstd.CHAINLOG_MIN, + zstd.HASHLOG_MIN, + zstd.SEARCHLOG_MIN, + zstd.SEARCHLENGTH_MIN, + zstd.TARGETLENGTH_MIN, + zstd.STRATEGY_FAST) + + zstd.CompressionParameters(zstd.WINDOWLOG_MAX, + zstd.CHAINLOG_MAX, + zstd.HASHLOG_MAX, + zstd.SEARCHLOG_MAX, + zstd.SEARCHLENGTH_MAX, + zstd.TARGETLENGTH_MAX, + zstd.STRATEGY_BTOPT) def test_get_compression_parameters(self): p = zstd.get_compression_parameters(1)
Add test for CompressionParameters boundary values Still not comprehensive. But better than what we had before, which was nothing.
py
diff --git a/holoviews/plotting/plot.py b/holoviews/plotting/plot.py index <HASH>..<HASH> 100644 --- a/holoviews/plotting/plot.py +++ b/holoviews/plotting/plot.py @@ -585,7 +585,7 @@ class GenericElementPlot(DimensionedPlot): defaults=False) plot_opts.update(**{k: v[0] for k, v in inherited.items()}) - dynamic = False if not isinstance(element, DynamicMap) or element.sampled else element.mode + dynamic = isinstance(element, DynamicMap) and not element.sampled super(GenericElementPlot, self).__init__(keys=keys, dimensions=dimensions, dynamic=dynamic, **dict(params, **plot_opts))
Fixed reference to DynamicMap mode in GenericElementPlot
py
diff --git a/tests/SpiffWorkflow/bpmn/BpmnWorkflowSerializerTest.py b/tests/SpiffWorkflow/bpmn/BpmnWorkflowSerializerTest.py index <HASH>..<HASH> 100644 --- a/tests/SpiffWorkflow/bpmn/BpmnWorkflowSerializerTest.py +++ b/tests/SpiffWorkflow/bpmn/BpmnWorkflowSerializerTest.py @@ -51,6 +51,14 @@ class BpmnWorkflowSerializerTest(unittest.TestCase): version = self.serializer.get_version(spec_serialized) self.assertEqual(version, self.SERIALIZER_VERSION) + def testSerializeToOldSerializerThenNewSerializer(self): + old_serializer = BpmnSerializer() + old_json = old_serializer.serialize_workflow(self.workflow) + new_workflow = old_serializer.deserialize_workflow(old_json) + new_json = self.serializer.serialize_json(new_workflow) + new_workflow_2 = self.serializer.deserialize_json(new_json) + + def testSerializeWorkflow(self): json = self.serializer.serialize_json(self.workflow) print(json)
Test showing that deserializing a workflow with the old serializer produces a workflow that cannot be serialized with the new serializer.
py
diff --git a/d1_common_python/src/d1_common/__init__.py b/d1_common_python/src/d1_common/__init__.py index <HASH>..<HASH> 100644 --- a/d1_common_python/src/d1_common/__init__.py +++ b/d1_common_python/src/d1_common/__init__.py @@ -20,7 +20,7 @@ '''Shared code for DataONE Python libraries ''' -__version__ = "1.1.2" +__version__ = "1.1.2RC1" __all__ = [ 'const',
Updated version number to show that this is an RC.
py
diff --git a/flask_images/core.py b/flask_images/core.py index <HASH>..<HASH> 100755 --- a/flask_images/core.py +++ b/flask_images/core.py @@ -375,7 +375,7 @@ class Images(object): enlarge = query.get('enlarge', False) sharpen = query.get('sharpen') - sharpen = re.split(r'[;,_/ ]', sharpen) if sharpen else None + sharpen = re.split(r'[+:;,_/ ]', sharpen) if sharpen else None if use_cache:
Accept + and : as USM delimiter.
py
diff --git a/cli_helpers/__init__.py b/cli_helpers/__init__.py index <HASH>..<HASH> 100644 --- a/cli_helpers/__init__.py +++ b/cli_helpers/__init__.py @@ -1 +1 @@ -__version__ = '1.0.0' +__version__ = '1.0.1'
Releasing version <I>.
py
diff --git a/plenum/common/messages/message_base.py b/plenum/common/messages/message_base.py index <HASH>..<HASH> 100644 --- a/plenum/common/messages/message_base.py +++ b/plenum/common/messages/message_base.py @@ -59,6 +59,13 @@ class MessageBase(Mapping, MessageValidator): def __init__(self, *args, **kwargs): assert not (args and kwargs), '*args, **kwargs cannot be used together' + + argsLen = len(args or kwargs) + assert argsLen == len(self.schema), \ + "number of parameters should be the " \ + "same as a number of fields in schema, but it was {}"\ + .format(argsLen) + if args: input_as_dict = dict(zip(map(itemgetter(0), self.schema), args)) else:
add checking that number of init parameters of message is equal to number of fields declared in schema
py
diff --git a/gin/tf/utils.py b/gin/tf/utils.py index <HASH>..<HASH> 100644 --- a/gin/tf/utils.py +++ b/gin/tf/utils.py @@ -20,6 +20,7 @@ import os from gin import config import tensorflow as tf +from tensorflow import estimator as tf_estimator # pylint: disable=g-direct-tensorflow-import from tensorflow.core.framework import summary_pb2 @@ -36,7 +37,7 @@ def singleton_per_graph(constructor): return config.singleton_value(key, constructor) -class GinConfigSaverHook(tf.estimator.SessionRunHook): +class GinConfigSaverHook(tf_estimator.SessionRunHook): """A SessionRunHook that saves and summarizes the operative config. This hook will save Gin's operative configuration to a specified directory, as
Explicitly import estimator from tensorflow as a separate import instead of accessing it via tf.estimator and depend on the tensorflow estimator target. PiperOrigin-RevId: <I>
py
diff --git a/helpers/workers.py b/helpers/workers.py index <HASH>..<HASH> 100644 --- a/helpers/workers.py +++ b/helpers/workers.py @@ -106,6 +106,5 @@ class Workers(): row = session.query(Log).filter(or_(Log.type == 'pubmsg', Log.type == 'privmsg'), ~Log.msg.startswith(cmdchar), Log.target != ctrlchan).order_by(Log.id.desc()).first() if last is None or row is None: return - if last.last != row.id: - # FIXME: make this less sensitive? + if abs(last.last - row.id) > 1: raise Exception("Last row in babble cache (%d) does not match last row in log (%d)." % (last.last, row.id))
allow one-row diff in check_babble
py
diff --git a/spacy/tests/pipeline/test_pipe_methods.py b/spacy/tests/pipeline/test_pipe_methods.py index <HASH>..<HASH> 100644 --- a/spacy/tests/pipeline/test_pipe_methods.py +++ b/spacy/tests/pipeline/test_pipe_methods.py @@ -81,9 +81,9 @@ def test_replace_last_pipe(nlp): def test_replace_pipe_config(nlp): nlp.add_pipe("entity_linker") nlp.add_pipe("sentencizer") - assert nlp.get_pipe("entity_linker").cfg["incl_prior"] == True + assert nlp.get_pipe("entity_linker").cfg["incl_prior"] is True nlp.replace_pipe("entity_linker", "entity_linker", config={"incl_prior": False}) - assert nlp.get_pipe("entity_linker").cfg["incl_prior"] == False + assert nlp.get_pipe("entity_linker").cfg["incl_prior"] is False @pytest.mark.parametrize("old_name,new_name", [("old_pipe", "new_pipe")])
Fix code style in test [ci skip]
py
diff --git a/djangui/signals.py b/djangui/signals.py index <HASH>..<HASH> 100644 --- a/djangui/signals.py +++ b/djangui/signals.py @@ -1,7 +1,10 @@ from __future__ import absolute_import +from django.db.models.signals import post_delete + from celery.signals import task_postrun, task_prerun, task_revoked + @task_postrun.connect @task_prerun.connect def task_completed(sender=None, **kwargs): @@ -13,4 +16,14 @@ def task_completed(sender=None, **kwargs): if state: job.celery_state = state job.celery_id = kwargs.get('task_id') - job.save() \ No newline at end of file + job.save() + +def reload_scripts(**kwargs): + from .backend import utils + utils.load_scripts() + +from .models import Script, ScriptGroup, ScriptParameter, ScriptParameterGroup +post_delete.connect(reload_scripts, sender=Script) +post_delete.connect(reload_scripts, sender=ScriptGroup) +post_delete.connect(reload_scripts, sender=ScriptParameter) +post_delete.connect(reload_scripts, sender=ScriptParameterGroup) \ No newline at end of file
delete hook on model deletion for updating home screen
py
diff --git a/salt/log/setup.py b/salt/log/setup.py index <HASH>..<HASH> 100644 --- a/salt/log/setup.py +++ b/salt/log/setup.py @@ -631,6 +631,19 @@ def setup_logfile_logger(log_path, log_level='error', log_format=None, shutdown_multiprocessing_logging_listener() sys.exit(2) else: + # make sure, the logging directory exists and attempt to create it if necessary + log_dir = os.path.dirname(log_path) + if not os.path.exists(log_dir): + logging.getLogger(__name__).info( + 'Log directory not found, trying to create it: {0}'.format(log_dir) + ) + try: + os.makedirs(log_dir, mode=0o700) + except OSError as ose: + logging.getLogger(__name__).warning( + 'Failed to create directory for log file: {0} ({1})'.format(log_dir, ose) + ) + return try: # Logfile logging is UTF-8 on purpose. # Since salt uses YAML and YAML uses either UTF-8 or UTF-16, if a
Try to create the log directory when not present yet
py
diff --git a/baron/grammator_data_structures.py b/baron/grammator_data_structures.py index <HASH>..<HASH> 100644 --- a/baron/grammator_data_structures.py +++ b/baron/grammator_data_structures.py @@ -116,7 +116,7 @@ def include_data_structures(pg): @pg.production("atom : LEFT_SQUARE_BRACKET listmaker RIGHT_SQUARE_BRACKET") - def list(pack): + def list_(pack): (left_bracket, listmaker, right_bracket,) = pack return { "type": "list",
[mod] avoid overloading a buildin
py
diff --git a/abilian/services/base.py b/abilian/services/base.py index <HASH>..<HASH> 100644 --- a/abilian/services/base.py +++ b/abilian/services/base.py @@ -51,10 +51,19 @@ class Service(object): @property def app_state(self): """ Current service state in current application. + + :raise:RuntimeError if working outside application context. """ return current_app.extensions[self.name] @property def running(self): - return self.app_state.running + """:returns: `False` if working outside application context or if service is + halted for current application. + """ + try: + return self.app_state.running + except RuntimeError: + # current_app is None: working outside application context + return False
Service.running: returns False if working outside application context (instead of letting RuntimeError propagate)
py
diff --git a/keanu-python/keanu/algorithm/sampling.py b/keanu-python/keanu/algorithm/sampling.py index <HASH>..<HASH> 100644 --- a/keanu-python/keanu/algorithm/sampling.py +++ b/keanu-python/keanu/algorithm/sampling.py @@ -34,7 +34,7 @@ class PosteriorSamplingAlgorithm: class ForwardSampler(PosteriorSamplingAlgorithm): - def __init__(self): + def __init__(self) -> None: super().__init__(k.jvm_view().ForwardSampler())
add rogue None to init
py
diff --git a/tools/dbmaint.py b/tools/dbmaint.py index <HASH>..<HASH> 100755 --- a/tools/dbmaint.py +++ b/tools/dbmaint.py @@ -125,7 +125,7 @@ def version_key(string): """Returns a version representation useful for version comparison""" # remove the trailing '-<release>' number if any - string, _ = (string + '-').split('-', 1) + string = string.split('-', 1)[0] return version.StrictVersion(string)
Simplify stupid code (thanks to al-maisan). Former-commit-id: 3b<I>da<I>cce4e<I>a3e<I>a<I>dfcd8cadb1dba
py
diff --git a/great_expectations/cli/datasource.py b/great_expectations/cli/datasource.py index <HASH>..<HASH> 100644 --- a/great_expectations/cli/datasource.py +++ b/great_expectations/cli/datasource.py @@ -465,6 +465,13 @@ def create_sample_expectation_suite( msg_prompt_enter_data_asset_name = "\nWhich data would you like to use? (Choose one)\n" + msg_prompt_what_will_profiler_do = """ +The profiler will choose a couple of columns and generate expectations about them. +This will show you some examples of assertions you can make about your data using Great Expectations. + +Press any key to continue... + """ + msg_data_doc_intro = """ <cyan>========== Data Docs ==========</cyan>""" @@ -513,6 +520,8 @@ def create_sample_expectation_suite( if len(data_assets) > 0: data_asset_name = data_assets[0] + click.prompt(msg_prompt_what_will_profiler_do, default="Enter", hide_input=True) + cli_message("\nProfiling {0:s}...".format(data_assets[0])) # after getting the arguments from the user, let's try to run profiling again
Stop and explain what the profiler will do
py
diff --git a/pyxmpp/client.py b/pyxmpp/client.py index <HASH>..<HASH> 100644 --- a/pyxmpp/client.py +++ b/pyxmpp/client.py @@ -158,7 +158,7 @@ class Client: q=iq.get_query() item=self.roster.update(q) if item: - self.roster_updated(item.jid()) + self.roster_updated(item) resp=iq.make_result_response() self.stream.send(resp)
- pass roster item instead of JID to roster_updated()
py
diff --git a/smmap/buf.py b/smmap/buf.py index <HASH>..<HASH> 100644 --- a/smmap/buf.py +++ b/smmap/buf.py @@ -51,6 +51,8 @@ class SlidingWindowMapBuffer(object): return self._size def __getitem__(self, i): + if isinstance(i, slice): + return self.__getslice__(i.start or 0, i.stop or self._size) c = self._c assert c.is_valid() if i < 0:
Make __getitem__ handle slice for Python 3 Python 3 doesn't have __getslice__ instead it uses __getitem__ with a slice object.
py
diff --git a/salt/modules/ddns.py b/salt/modules/ddns.py index <HASH>..<HASH> 100644 --- a/salt/modules/ddns.py +++ b/salt/modules/ddns.py @@ -167,7 +167,7 @@ def update(zone, name, ttl, rdtype, data, nameserver='127.0.0.1', replace=False, for rrset in answer.answer: if rdata in rrset.items: if ttl == rrset.ttl: - if (len(answer.answer) >= 1 or len(rrset.items) >= 1): + if len(answer.answer) >= 1 or len(rrset.items) >= 1: is_exist = True break
match pylint rule
py
diff --git a/proto/src/Rammbock.py b/proto/src/Rammbock.py index <HASH>..<HASH> 100644 --- a/proto/src/Rammbock.py +++ b/proto/src/Rammbock.py @@ -69,10 +69,10 @@ class Rammbock(object): Parameters have to be pdu fields.""" def send_pdu(self, *params): - paramsdict = self._parse_parameters(params) - server = paramsdict.pop("_server", None) - client = paramsdict.pop("_client", None) - msg = self.create_binary_to_send(paramsdict) + params_dict = self._parse_parameters(params) + server = params_dict.pop("_server", None) + client = params_dict.pop("_client", None) + msg = self.create_binary_to_send(params_dict) self.send_binary(msg, server, client) def create_binary_to_send(self, paramsdict):
rename paramsdict to params_dict
py
diff --git a/cytomine/cytomine.py b/cytomine/cytomine.py index <HASH>..<HASH> 100644 --- a/cytomine/cytomine.py +++ b/cytomine/cytomine.py @@ -238,6 +238,9 @@ class Cytomine(object): protocol = provided_protocol host = host.replace("http://", "").replace("https://", "") + if host.endswith("/"): + host = host[:-1] + return host, protocol def _start(self):
Handle host values finishing by slash
py
diff --git a/rinohlib/stylesheets/matcher.py b/rinohlib/stylesheets/matcher.py index <HASH>..<HASH> 100644 --- a/rinohlib/stylesheets/matcher.py +++ b/rinohlib/stylesheets/matcher.py @@ -249,7 +249,8 @@ matcher('front matter section', FrontMatter > Section.like(level=1)) matcher('front matter section heading', 'front matter section' / Heading) matcher('table of contents section', Section.like('table of contents')) -matcher('table of contents title', 'table of contents section' / Heading) +matcher('table of contents title', 'table of contents section' + / Heading.like(level=1)) matcher('table of contents', TableOfContents) matcher('toc level 1', TableOfContentsEntry.like(depth=1)) matcher('toc level 2', TableOfContentsEntry.like(depth=2))
Make 'table of contents title' more specific It was less specific than 'unnumbered heading level 1'.
py
diff --git a/openpnm/algorithms/ReactiveTransport.py b/openpnm/algorithms/ReactiveTransport.py index <HASH>..<HASH> 100644 --- a/openpnm/algorithms/ReactiveTransport.py +++ b/openpnm/algorithms/ReactiveTransport.py @@ -240,7 +240,7 @@ class ReactiveTransport(GenericTransport): if self.settings['t_scheme'] == 'cranknicolson': f1 = 0.5 else: - f1 = 1 + f1 = 1.0 phase = self.project.phases()[self.settings['phase']] relax = self.settings['relaxation_source'] for item in self.settings['sources']:
Minor future-proofing: int -> float
py
diff --git a/salt/loader.py b/salt/loader.py index <HASH>..<HASH> 100644 --- a/salt/loader.py +++ b/salt/loader.py @@ -155,6 +155,10 @@ class Loader(object): self.grains = opts['grains'] else: self.grains = {} + if 'pillar' in opts: + self.pillar = opts['pillar'] + else: + self.pillar = {} self.opts = self.__prep_mod_opts(opts) def __prep_mod_opts(self, opts): @@ -340,6 +344,7 @@ class Loader(object): mod.__opts__ = self.opts mod.__grains__ = self.grains + mod.__pillar__ = self.pillar if pack: if isinstance(pack, list):
Add pillar data to the loader
py
diff --git a/djcelery/admin.py b/djcelery/admin.py index <HASH>..<HASH> 100644 --- a/djcelery/admin.py +++ b/djcelery/admin.py @@ -91,7 +91,7 @@ class ModelMonitor(admin.ModelAdmin): extra_context = extra_context or {} extra_context.setdefault('title', self.detail_title) return super(ModelMonitor, self).change_view(request, object_id, - extra_context) + extra_context=extra_context) def has_delete_permission(self, request, obj=None): if not self.can_delete:
Update admin.py django.contrib.admin.options.py:ModelAdmin.change_view has following signature(Django <I>&<I>): def change_view(self, request, object_id, form_url='', extra_context=None): Currently passing extra_context dict without explicit naming( extra_context=extra_context) actually works as implicit form_url=extra_context. This issue blocks submiting Worker and Task admin forms.
py
diff --git a/py/selenium/webdriver/firefox/firefox_binary.py b/py/selenium/webdriver/firefox/firefox_binary.py index <HASH>..<HASH> 100644 --- a/py/selenium/webdriver/firefox/firefox_binary.py +++ b/py/selenium/webdriver/firefox/firefox_binary.py @@ -132,6 +132,6 @@ class FirefoxBinary(object): """Returns the fully qualified path by searching Path of the given name""" for pe in os.environ['PATH'].split(os.pathsep): checkname = os.path.join(pe, fname) - if os.access(checkname, os.X_OK): + if os.access(checkname, os.X_OK) and not os.path.isdir(checkname): return checkname return None
DavidBurns, on behalf of AndiAlbrecht, fixing where which finds directories. Fixes issue <I> r<I>
py
diff --git a/doublethink/rethinker.py b/doublethink/rethinker.py index <HASH>..<HASH> 100644 --- a/doublethink/rethinker.py +++ b/doublethink/rethinker.py @@ -48,14 +48,31 @@ class RethinkerWrapper(object): result = self.wrapped.run(conn, db=db or self.rr.dbname) if hasattr(result, '__next__'): is_iter = True + def gen(): try: yield # empty yield, see comment below - for x in result: - yield x + while True: + try: + x = next(result) + yield x + except StopIteration: + break + except r.ReqlOpFailedError as e: + if e.args and re.match( + '^Cannot perform.*replica.*', + e.args[0]): + self.logger.error( + 'will keep trying after ' + 'potentially recoverable ' + 'error: %s', e) + time.sleep(0.5) + else: + raise finally: result.close() conn.close() + g = gen() # Start executing the generator, leaving off after the # empty yield. If we didn't do this, and the caller never
handle recoverable errors that happen while iterating over results!
py
diff --git a/twitter_ads/error.py b/twitter_ads/error.py index <HASH>..<HASH> 100644 --- a/twitter_ads/error.py +++ b/twitter_ads/error.py @@ -9,7 +9,11 @@ class Error(Exception): def __init__(self, response, **kwargs): self._response = response self._code = kwargs.get('code', response.code) - self._details = kwargs.get('details', response.body.get('errors', None)) + + if response.body and 'errors' in response.body: + self._details = kwargs.get('details', response.body.get('errors')) + else: + self._details = None @property def response(self): @@ -31,6 +35,9 @@ class Error(Exception): details=getattr(self, 'details') ) + def __str__(self): + return self.__repr__() + @staticmethod def from_response(response): """Returns the correct error type from a ::class::`Response` object."""
[minor] fixing errors for empty response bodys and adding str() implementation
py
diff --git a/socialregistration/views.py b/socialregistration/views.py index <HASH>..<HASH> 100644 --- a/socialregistration/views.py +++ b/socialregistration/views.py @@ -148,6 +148,7 @@ def facebook_login(request, template='socialregistration/facebook.html', return render_to_response(account_inactive_template, extra_context, context_instance=RequestContext(request)) + request.facebook.request = request _login(request, user, FacebookProfile.objects.get(user = user), request.facebook) return HttpResponseRedirect(_get_next(request))
Ensuring that the request is available in signal handlers.
py
diff --git a/satpy/readers/sar_c_safe.py b/satpy/readers/sar_c_safe.py index <HASH>..<HASH> 100644 --- a/satpy/readers/sar_c_safe.py +++ b/satpy/readers/sar_c_safe.py @@ -179,7 +179,7 @@ class SAFEXML(BaseFileHandler): data = self.interpolate_xml_array(data, low_res_coords, data.shape) - @lru_cache + @lru_cache(maxsize=10) def get_noise_correction(self, shape, chunks=None): """Get the noise correction array.""" data_items = self.root.findall(".//noiseVector") @@ -196,7 +196,7 @@ class SAFEXML(BaseFileHandler): noise = self.interpolate_xml_array(data, low_res_coords, shape, chunks=chunks) return noise - @lru_cache + @lru_cache(maxsize=10) def get_calibration(self, calibration, shape, chunks=None): """Get the calibration array.""" calibration_name = calibration.name or 'gamma'
Add maxsize to lru_cache
py
diff --git a/pandas/core/frame.py b/pandas/core/frame.py index <HASH>..<HASH> 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -4323,7 +4323,7 @@ class DataFrame(NDFrame): Traceback (most recent call last): KeyError: ['C'] not found in axis - Using axis-style parameters + Using axis-style parameters: >>> df.rename(str.lower, axis='columns') a b
DOC: make rename docs consistent (#<I>)
py
diff --git a/path.py b/path.py index <HASH>..<HASH> 100644 --- a/path.py +++ b/path.py @@ -1231,7 +1231,8 @@ class Path(text_type): self.rmdir() except OSError: _, e, _ = sys.exc_info() - if e.errno != errno.ENOTEMPTY and e.errno != errno.EEXIST and e.errno != errno.ENOENT: + bypass_codes = errno.ENOTEMPTY, errno.EEXIST, errno.ENOENT + if e.errno not in bypass_codes: raise return self
Extract bypass codes for brevity
py
diff --git a/src/toil/provisioners/aws/awsProvisioner.py b/src/toil/provisioners/aws/awsProvisioner.py index <HASH>..<HASH> 100644 --- a/src/toil/provisioners/aws/awsProvisioner.py +++ b/src/toil/provisioners/aws/awsProvisioner.py @@ -179,9 +179,14 @@ class AWSProvisioner(AbstractProvisioner): def getNodeShape(self, nodeType, preemptable=False): instanceType = ec2_instance_types[nodeType] - #EBS-backed instances are listed as having zero disk space in cgcloud.lib.ec2, - #but we'll estimate them at 2GB - disk = max(2 * 2**30, instanceType.disks * instanceType.disk_capacity * 2 ** 30) + + disk = instanceType.disks * instanceType.disk_capacity * 2 ** 30 + if disk == 0: + # This is an EBS-backed instance. We will use the root + # volume, so add the amount of EBS storage requested for + # the root volume + disk = self.nodeStorage * 2 ** 30 + #Underestimate memory by 100M to prevent autoscaler from disagreeing with #mesos about whether a job can run on a particular node type memory = (instanceType.memory - 0.1) * 2** 30
Add nodeStorage to the disk value for the nodeShape Previously the disk was always estimated to be 2GB, making instances with only EBS-backed storage like c4, r4, etc. useless.
py
diff --git a/saltcloud/cloud.py b/saltcloud/cloud.py index <HASH>..<HASH> 100644 --- a/saltcloud/cloud.py +++ b/saltcloud/cloud.py @@ -165,6 +165,7 @@ class Cloud(object): found = True if name in pmap.get(self.provider(vm_), []): # The specified vm already exists, don't make it anew + print("{0} already exists on {1}".format(name, self.provider(vm_))) continue vm_['name'] = name if self.opts['parallel']:
Notify user when a VM name already exists
py
diff --git a/examples/websocket_example.py b/examples/websocket_example.py index <HASH>..<HASH> 100644 --- a/examples/websocket_example.py +++ b/examples/websocket_example.py @@ -76,4 +76,18 @@ if __name__ == '__main__': if USE_POLYGON: conn.run(['trade_updates', 'AM.AAPL', 'Q.AA', 'T.*']) else: - conn.run(['trade_updates', 'alpacadatav1/AM.AAPL']) + # these won't work: + # conn.run(['T.*']) + # conn.run(['Q.*']) + # conn.run(['alpacadatav1/Q.*']) + # conn.run(['T.TSLA']) + # conn.run(['Q.TSLA']) + + # these are fine: + # conn.run(['AM.*']) + # conn.run(['alpacadatav1/AM.*']) + + # conn.run(['alpacadatav1/AM.TSLA']) + # conn.run(['alpacadatav1/Q.GOOG']) + conn.run(['alpacadatav1/T.TSLA']) +
added examples for the alpaca websocket
py
diff --git a/atomic_reactor/plugins/pre_fetch_sources.py b/atomic_reactor/plugins/pre_fetch_sources.py index <HASH>..<HASH> 100644 --- a/atomic_reactor/plugins/pre_fetch_sources.py +++ b/atomic_reactor/plugins/pre_fetch_sources.py @@ -193,7 +193,7 @@ class FetchSourcesPlugin(PreBuildPlugin): if missing_srpms: raise RuntimeError('Could not find files signed by any of {} for these SRPMS: {}' - .format(sigkeys, srpm_filename)) + .format(sigkeys, missing_srpms)) return srpm_urls
Fix missing SRPMs error message The wording suggests that the error message would show all the missing SRPM files, but currently, it only shows the last one.
py
diff --git a/setup.py b/setup.py index <HASH>..<HASH> 100644 --- a/setup.py +++ b/setup.py @@ -3,6 +3,24 @@ from setuptools import setup, find_packages import json import sys import datetime +from sys import version_info as vi + + +if vi.major != 3: + ver = '{}.{}.{}'.format(vi.major, vi.minor, vi.micro) + error = ( + 'INSTALLATION WARNING!\n' + 'BiblioPixelAnimations requires Python 3.4+ and you are using {}!\n' + 'All versions after v3.20170531.153148 are designed for BiblioPixel 3.x and Python 3.4+\n' + 'If you absolutely require using Python 2, ' + 'please install the older version using:\n' + '> pip install BiblioPixelAnimations==3.20170531.153148 --upgrade' + '\n' + 'However, we highly recommend using the latest BiblioPixel ' + '(v3+) and BiblioPixelAnimations with Python 3.4+\n' + '\n' + ) + print(error.format(ver)) def _get_version(): @@ -27,8 +45,7 @@ setup( classifiers=[ 'Development Status :: 5 - Production/Stable', 'License :: OSI Approved :: MIT License', - 'Programming Language :: Python :: 2', - 'Programming Language :: Python :: 2.6', - 'Programming Language :: Python :: 2.7', + 'Programming Language :: Python :: 3.4', + 'Programming Language :: Python :: 3.5', ], )
added python version warning
py
diff --git a/fireplace/player.py b/fireplace/player.py index <HASH>..<HASH> 100644 --- a/fireplace/player.py +++ b/fireplace/player.py @@ -77,7 +77,7 @@ class Player(Entity): for entity in self.secrets: ret += entity.entities # Note: Board receives TURN_BEGIN before player - return chain(list(self.hero.entities), ret, [self]) + return chain(list(self.hero.entities) if self.hero else [], ret, [self]) @property def liveEntities(self):
Fix Player.entities when the hero is unset
py
diff --git a/bika/lims/browser/analysisrequest/__init__.py b/bika/lims/browser/analysisrequest/__init__.py index <HASH>..<HASH> 100644 --- a/bika/lims/browser/analysisrequest/__init__.py +++ b/bika/lims/browser/analysisrequest/__init__.py @@ -370,8 +370,9 @@ class mailto_link_from_contacts: contacts = [contacts, ] ret = [] for contact in contacts: - mailto = "<a href='mailto:%s'>%s</a>" % ( - contact.getEmailAddress(), contact.getFullname()) + if contact: + mailto = "<a href='mailto:%s'>%s</a>" % ( + contact.getEmailAddress(), contact.getFullname()) ret.append(mailto) return ",".join(ret)
Fix error displaying AR with missing contact
py
diff --git a/setup.py b/setup.py index <HASH>..<HASH> 100644 --- a/setup.py +++ b/setup.py @@ -12,8 +12,6 @@ standard_exclude = ('*.py', '*.pyc', '*~', '.*', '*.bak') standard_exclude_directories = ('.*', 'CVS', '_darcs', './build', './dist', 'EGG-INFO', '*.egg-info') -try: - reqs = read('requirements.txt') # Copied from paste/util/finddata.py def find_package_data(where='.', package='', exclude=standard_exclude, exclude_directories=standard_exclude_directories,
Missed a partial requirements attempt. Need to test alternative methods of requirements installation
py
diff --git a/telethon_examples/print_updates.py b/telethon_examples/print_updates.py index <HASH>..<HASH> 100755 --- a/telethon_examples/print_updates.py +++ b/telethon_examples/print_updates.py @@ -10,7 +10,7 @@ from os import environ def main(): session_name = environ.get('TG_SESSION','session') - user_phone = environ['TG_PHONE'], + user_phone = environ['TG_PHONE'] client = TelegramClient(session_name, int(environ['TG_API_ID']), environ['TG_API_HASH'],
Remove comma (#<I>)
py
diff --git a/test/test_replica_set_client.py b/test/test_replica_set_client.py index <HASH>..<HASH> 100644 --- a/test/test_replica_set_client.py +++ b/test/test_replica_set_client.py @@ -860,28 +860,13 @@ class TestReplicaSetClient(TestReplicaSetClientBase, TestRequestMixin): old_signal_handler = None try: - # Platform-specific hacks for raising a KeyboardInterrupt on the main - # thread while find() is in-progress: On Windows, SIGALRM is unavailable - # so we use second thread. In our Bamboo setup on Linux, the thread - # technique causes an error in the test at sock.recv(): - # TypeError: 'int' object is not callable - # We don't know what causes this in Bamboo, so we hack around it. - if sys.platform == 'win32': - def interrupter(): - time.sleep(0.25) - - # Raises KeyboardInterrupt in the main thread - thread.interrupt_main() - - thread.start_new_thread(interrupter, ()) - else: - # Convert SIGALRM to SIGINT -- it's hard to schedule a SIGINT for one - # second in the future, but easy to schedule SIGALRM. - def sigalarm(num, frame): - raise KeyboardInterrupt - - old_signal_handler = signal.signal(signal.SIGALRM, sigalarm) - signal.alarm(1) + def interrupter(): + time.sleep(0.25) + + # Raises KeyboardInterrupt in the main thread + thread.interrupt_main() + + thread.start_new_thread(interrupter, ()) raised = False try:
Simplify and fix interrupt test.
py
diff --git a/qiskit/circuit/quantumcircuit.py b/qiskit/circuit/quantumcircuit.py index <HASH>..<HASH> 100644 --- a/qiskit/circuit/quantumcircuit.py +++ b/qiskit/circuit/quantumcircuit.py @@ -1805,18 +1805,14 @@ class QuantumCircuit: for instr, qargs, cargs in self._data: levels = [] reg_ints = [] - # If count then add one to stack heights - count = True - if instr._directive: - count = False for ind, reg in enumerate(qargs + cargs): # Add to the stacks of the qubits and # cbits used in the gate. reg_ints.append(bit_indices[reg]) - if count: - levels.append(op_stack[reg_ints[ind]] + 1) - else: + if instr._directive: levels.append(op_stack[reg_ints[ind]]) + else: + levels.append(op_stack[reg_ints[ind]] + 1) # Assuming here that there is no conditional # snapshots or barriers ever. if instr.condition:
Improve the readability of depth() method (#<I>) * Improve the readability of depth() method * Delete comment
py
diff --git a/tests/settings.py b/tests/settings.py index <HASH>..<HASH> 100644 --- a/tests/settings.py +++ b/tests/settings.py @@ -1,13 +1,12 @@ from __future__ import unicode_literals - - if DJANGO_VERSION >= (2, 0): + from django.utils.text import format_lazy from cmsplugin_cascade.extra_fields.config import PluginExtraFieldsConfig - +from django import VERSION as DJANGO_VERSION if DJANGO_VERSION < (2, 0): from django.core.urlresolvers import reverse_lazy - + MIDDLEWARE = [ 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', @@ -21,7 +20,7 @@ if DJANGO_VERSION < (2, 0): 'cms.middleware.toolbar.ToolbarMiddleware', 'cms.middleware.language.LanguageCookieMiddleware', ] - +] if DJANGO_VERSION >= (2, 0): from django.urls import reverse_lazy
update test/setings.py
py
diff --git a/foyer/forcefield.py b/foyer/forcefield.py index <HASH>..<HASH> 100644 --- a/foyer/forcefield.py +++ b/foyer/forcefield.py @@ -1,5 +1,6 @@ import itertools import os +from warnings import warn import networkx as nx import parmed.gromacs as gmx @@ -12,6 +13,8 @@ from foyer.atomtyper import find_atomtypes def apply_forcefield(structure, forcefield, debug=False): """Apply a forcefield to a Topology. """ + if not structure.bonds: + warn('Structure contains no bonds: \n{}\n'.format(structure)) if isinstance(forcefield, string_types): if forcefield.lower() in ['opls-aa', 'oplsaa', 'opls']: ff_path = os.path.join(gmx.GROMACS_TOPDIR, 'oplsaa.ff/forcefield.itp') @@ -25,7 +28,8 @@ def apply_forcefield(structure, forcefield, debug=False): find_atomtypes(structure.atoms, forcefield, debug=debug) - ff.box = structure.box + if structure.box.any(): + ff.box = structure.box ff.atoms = structure.atoms ff.bonds = structure.bonds create_bonded_forces(ff)
Warn if no bonds are found in structure
py
diff --git a/setup.py b/setup.py index <HASH>..<HASH> 100644 --- a/setup.py +++ b/setup.py @@ -71,16 +71,18 @@ for accessing Google's Cloud Platform services such as Google BigQuery. 'future==0.15.2', 'futures==3.0.5', 'google-cloud==0.19.0', + 'google-api-python-client==1.5.1', + 'seaborn==0.7.0', + 'plotly==1.12.5', 'httplib2==0.9.2', 'oauth2client==2.2.0', + 'psutil==4.3.0', 'pandas>=0.17.1', 'pandas-profiling>=1.0.0a2', 'python-dateutil==2.5.0', 'pytz>=2015.4', 'pyyaml==3.11', 'requests==2.9.1', - 'scipy==0.18.0', - 'scikit-learn==0.17.1', 'ipykernel==4.4.1', ], package_data={
Add some missing dependencies, remove some unused ones (#<I>) * Remove scikit-learn and scipy as dependencies * add more required packages * Add psutil as dependency * Update packages versions
py
diff --git a/indra/assemblers/pysb_assembler.py b/indra/assemblers/pysb_assembler.py index <HASH>..<HASH> 100644 --- a/indra/assemblers/pysb_assembler.py +++ b/indra/assemblers/pysb_assembler.py @@ -827,7 +827,7 @@ class PysbAssembler(object): set_base_initial_condition(self.model, m, init_round) monomers_found.append(m.name) else: - set_base_initial_condition(self.model, m, 100.0) + set_base_initial_condition(self.model, m, 1000.0) monomers_notfound.append(m.name) logger.info('Monomers set to %s context' % cell_type) logger.info('--------------------------------')
Fix increase default initial amount in set context
py
diff --git a/setup.py b/setup.py index <HASH>..<HASH> 100644 --- a/setup.py +++ b/setup.py @@ -12,7 +12,7 @@ instructions. setup( name="django-prometheus", - version="0.2.0", + version="0.2.1", author="Uriel Corfa", author_email="uriel@corfa.fr", description=(
Release <I>. <I> was cut at the wrong commit.
py
diff --git a/O365/account.py b/O365/account.py index <HASH>..<HASH> 100644 --- a/O365/account.py +++ b/O365/account.py @@ -1,12 +1,10 @@ from .connection import Connection, Protocol, MSGraphProtocol from .connection import oauth_authentication_flow -from .utils import ME_RESOURCE class Account(object): - def __init__(self, credentials, *, protocol=None, main_resource=ME_RESOURCE, - **kwargs): + def __init__(self, credentials, *, protocol=None, main_resource=None, **kwargs): """ Creates an object which is used to access resources related to the specified credentials @@ -14,7 +12,7 @@ class Account(object): and client_secret :param Protocol protocol: the protocol to be used in this account :param str main_resource: the resource to be used by this account - ('me' or 'users') + ('me' or 'users', etc.) :param kwargs: any extra args to be passed to the Connection instance :raises ValueError: if an invalid protocol is passed """ @@ -28,7 +26,7 @@ class Account(object): raise ValueError("'protocol' must be a subclass of Protocol") self.con = Connection(credentials, **kwargs) - self.main_resource = main_resource + self.main_resource = main_resource or self.protocol.default_resource def __repr__(self): if self.con.auth:
Account now uses the default protocol. Fixes #<I>. Other library objects are already using it by default.
py
diff --git a/docs/source/conf.py b/docs/source/conf.py index <HASH>..<HASH> 100644 --- a/docs/source/conf.py +++ b/docs/source/conf.py @@ -64,11 +64,12 @@ copyright = u'2017, Brendt Wohlberg' # built documents. # # The short X.Y version. -module = '../../../../jonga.py' if on_rtd else '../../jonga.py' +module = '../../jonga.py' if on_rtd else '../../jonga.py' with open(module) as f: - version = parse(next(filter( - lambda line: line.startswith('__version__'), - f))).body[0].value.s + modprs = parse(next(filter( + lambda line: line.startswith('__version__'), f))) + print(modprs) + version = modprs.body[0].value.s # The full version, including alpha/beta/rc tags. release = version
Debugging rtd build
py
diff --git a/i3pystatus/spotify.py b/i3pystatus/spotify.py index <HASH>..<HASH> 100644 --- a/i3pystatus/spotify.py +++ b/i3pystatus/spotify.py @@ -74,8 +74,9 @@ class Spotify(IntervalModule): "length": "", } - if player.props.status: - result["status"] = player.props.status.lower() + status = player.props.status + if status: + result["status"] = self.status.get(status.lower(), None) result["artist"] = player.get_artist() result["title"] = player.get_title() result["album"] = player.get_album()
Forget to get format from dict
py
diff --git a/luminoso_api/client.py b/luminoso_api/client.py index <HASH>..<HASH> 100644 --- a/luminoso_api/client.py +++ b/luminoso_api/client.py @@ -487,6 +487,16 @@ class LuminosoClient(object): url = ensure_trailing_slash(self.url + path.lstrip('/')) return self._request('get', url, params=params).text + def save_to_file(self, path, filename, **params): + """ + Saves binary content to file filename. Useful for downloading .xlsx + files. + """ + url = ensure_trailing_slash(self.url + path.lstrip('/')) + content = self._request('get', url, params=params).content + with open(filename, 'wb') as f: + f.write(content) + def get_token_filename(): """
save_to_file method for downloading and saving xlsx
py
diff --git a/odl/discr/discretization.py b/odl/discr/discretization.py index <HASH>..<HASH> 100644 --- a/odl/discr/discretization.py +++ b/odl/discr/discretization.py @@ -565,10 +565,6 @@ def dspace_type(space, impl, dtype=None): Space type selected after the space's field, the backend and the data type """ - spacetype_map = {RealNumbers: fn_impl, - ComplexNumbers: fn_impl, - type(None): ntuples_impl} - field_type = type(getattr(space, 'field', None)) if dtype is None: @@ -592,13 +588,16 @@ def dspace_type(space, impl, dtype=None): raise TypeError('non-scalar data type {!r} cannot be combined with ' 'a `LinearSpace`'.format(dtype)) - try: - stype = spacetype_map[field_type](impl) - except KeyError: + if field_type in (RealNumbers, ComplexNumbers): + spacetype = fn_impl + elif field_type == type(None): + spacetype = ntuples_impl + else: raise NotImplementedError('no corresponding data space available ' 'for space {!r} and implementation {!r}' ''.format(space, impl)) - return stype + + return spacetype(impl) if __name__ == '__main__':
MAINT: Improved dspace_type implementation
py
diff --git a/notifier/_notifier.py b/notifier/_notifier.py index <HASH>..<HASH> 100644 --- a/notifier/_notifier.py +++ b/notifier/_notifier.py @@ -284,9 +284,8 @@ class Notifier(object): All callbacks registered to receive notifications about given event type will be called. If the provided event type can not be used to emit notifications (this is checked via - the :meth:`.can_be_registered` method) then it will silently be - dropped (notification failures are not allowed to cause or - raise exceptions). + the :meth:`.can_be_registered` method) then a value error will be + raised. :param event_type: event type that occurred :param details: additional event details *dictionary* passed to
Fix docstring now that this raises a value error
py
diff --git a/setup.py b/setup.py index <HASH>..<HASH> 100644 --- a/setup.py +++ b/setup.py @@ -240,16 +240,16 @@ def gumath_extensions(): add_runtime_library_dirs = [] else: add_libraries = [":%s" % LIBNDTYPES, ":%s" % LIBXND, ":%s" % LIBSHARED] - if config_vars.get("HAVE_CUDA"): - if os.path.isdir("/usr/cuda/lib64"): - add_library_dirs += ["/usr/cuda/lib64"] - if os.path.isdir("/usr/local/cuda/lib64"): - add_library_dirs += ["/usr/local/cuda/lib64"] - add_libraries += ["cudart"] - add_extra_link_args = [] add_runtime_library_dirs = ["$ORIGIN"] + if config_vars.get("HAVE_CUDA"): + if os.path.isdir("/usr/cuda/lib64"): + add_library_dirs += ["/usr/cuda/lib64"] + if os.path.isdir("/usr/local/cuda/lib64"): + add_library_dirs += ["/usr/local/cuda/lib64"] + add_libraries += ["cudart"] + def gumath_ext(): sources = ["python/gumath/_gumath.c"]
Enable CUDA in setup.py for OS X.
py
diff --git a/shinken/modulesmanager.py b/shinken/modulesmanager.py index <HASH>..<HASH> 100644 --- a/shinken/modulesmanager.py +++ b/shinken/modulesmanager.py @@ -100,8 +100,14 @@ class ModulesManager(object): mod_dir = os.path.dirname(mod_file) # We add this dir to sys.path so the module can load local files too sys.path.append(mod_dir) - # important, equivalent to import fname from module.py - m = imp.load_source(fname, mod_file) + if not os.path.exists(mod_file): + mod_file = os.path.abspath(os.path.join(self.modules_path, fname,'module.pyc')) + m = None + if mod_file.endswith('.py'): + # important, equivalent to import fname from module.py + m = imp.load_source(fname, mod_file) + else: + m = imp.load_compiled(fname, mod_file) m_dir = os.path.abspath(os.path.dirname(m.__file__)) # Look if it's a valid module
Fix: allow to laod pyc file for modules
py
diff --git a/bytecode/tests/__init__.py b/bytecode/tests/__init__.py index <HASH>..<HASH> 100644 --- a/bytecode/tests/__init__.py +++ b/bytecode/tests/__init__.py @@ -36,7 +36,7 @@ def _format_instr_list(block, labels, lineno): instr_list.append(text) return '[%s]' % ',\n '.join(instr_list) -def dump_code(code, lineno=True): +def dump_bytecode(code, lineno=True): """ Use this function to write unit tests: copy/paste its output to write a self.assertBlocksEqual() check.
tests: rename dump_code to dump_bytecode
py
diff --git a/gcloud/datastore/dataset.py b/gcloud/datastore/dataset.py index <HASH>..<HASH> 100644 --- a/gcloud/datastore/dataset.py +++ b/gcloud/datastore/dataset.py @@ -23,7 +23,14 @@ from gcloud.datastore.transaction import Transaction class Dataset(object): - """Convenience wrapper for invoking APIs/factories w/ a dataset ID.""" + """Convenience wrapper for invoking APIs/factories w/ a dataset ID. + + :type dataset_id: string + :param dataset_id: (required) dataset ID to pass to proxied API methods. + + :type connection: :class:`gcloud.datastore.connection.Connection`, or None + :param connection: (optional) connection to pass to proxied API methods + """ def __init__(self, dataset_id, connection=None): if dataset_id is None:
Add ctor args to class docstring. [ci skip]
py
diff --git a/jaraco/windows/dpapi.py b/jaraco/windows/dpapi.py index <HASH>..<HASH> 100644 --- a/jaraco/windows/dpapi.py +++ b/jaraco/windows/dpapi.py @@ -19,11 +19,12 @@ class DATA_BLOB(ctypes.Structure): A data blob structure for use with MS DPAPI functions. Initialize with string of characters - >>> blob = DATA_BLOB(b'abc123\x00456') + >>> input = b'abc123\x00456' + >>> blob = DATA_BLOB(input) >>> len(blob) 10 - >>> blob.get_data() - b'abc123\x00456' + >>> blob.get_data() == input + True """ _fields_ = [ ('data_size', wintypes.DWORD),
Rewrite test that fails on Python 2.
py
diff --git a/command/build_py.py b/command/build_py.py index <HASH>..<HASH> 100644 --- a/command/build_py.py +++ b/command/build_py.py @@ -190,9 +190,9 @@ class build_py (Command): if not os.path.isfile(module_file): self.warn("file %s (for module %s) not found" % (module_file, module)) - return False + return 0 else: - return True + return 1 # check_module ()
Revert 0/1 -> False/True change; I didn't intend to muck w/ distutils.
py
diff --git a/src/sagemaker/session.py b/src/sagemaker/session.py index <HASH>..<HASH> 100644 --- a/src/sagemaker/session.py +++ b/src/sagemaker/session.py @@ -357,6 +357,8 @@ class Session(object): # pylint: disable=too-many-public-methods def default_bucket(self): """Return the name of the default bucket to use in relevant Amazon SageMaker interactions. + This function will create the s3 bucket if it does not exist. + Returns: str: The name of the default bucket, which is of the form: ``sagemaker-{region}-{AWS account ID}``.
documentation: clarify that default_bucket creates a bucket (#<I>)
py
diff --git a/openfisca_core/formulas.py b/openfisca_core/formulas.py index <HASH>..<HASH> 100644 --- a/openfisca_core/formulas.py +++ b/openfisca_core/formulas.py @@ -96,6 +96,11 @@ class AlternativeFormula(AbstractFormula): requested_formulas.remove(self) return array + def graph_parameters(self, edges, nodes, visited): + """Recursively build a graph of formulas.""" + for alternative_formula in self.alternative_formulas: + alternative_formula.graph_parameters(edges, nodes, visited) + @classmethod def set_dependencies(cls, column, tax_benefit_system): for alternative_formula_constructor in cls.alternative_formulas_constructor:
Add missing method graph_parameters to AlternativeFormula.
py
diff --git a/test/test_big_phi.py b/test/test_big_phi.py index <HASH>..<HASH> 100644 --- a/test/test_big_phi.py +++ b/test/test_big_phi.py @@ -590,9 +590,9 @@ def test_big_mip_bipartitions(): answer = [models.Cut((1,), (2, 3, 4)), models.Cut((2,), (1, 3, 4)), models.Cut((3,), (1, 2, 4)), - models.Cut((1, 2, 3), (4,)), models.Cut((4,), (1, 2, 3)), - models.Cut((1, 2, 4), (3,)), + models.Cut((2, 3, 4), (1,)), models.Cut((1, 3, 4), (2,)), - models.Cut((2, 3, 4), (1,))] + models.Cut((1, 2, 4), (3,)), + models.Cut((1, 2, 3), (4,))] assert big_mip_bipartitions((1, 2, 3, 4)) == answer
Update `test_big_phi` to new 'of one' part order
py
diff --git a/phy/scripts/phy_script.py b/phy/scripts/phy_script.py index <HASH>..<HASH> 100644 --- a/phy/scripts/phy_script.py +++ b/phy/scripts/phy_script.py @@ -120,7 +120,6 @@ class ParserCreator(object): epilog=_examples, formatter_class=CustomFormatter, ) - self._parser.set_defaults(func=None) self._parser.add_argument('--version', '-v', action='version', version=phy.__version_git__, @@ -427,7 +426,7 @@ def main(args=None): call_pdb=1, ) - func = args.func + func = getattr(args, 'func', None) if func is None: p.parser.print_help() return
Fix issue #<I> The main parser's defaults overwrite the subparser so `func` is None on some systems (why this doesn't happen everywhere, I have no idea).
py