diff
stringlengths
139
3.65k
message
stringlengths
8
627
diff_languages
stringclasses
1 value
diff --git a/pdfwatermarker/utils/write.py b/pdfwatermarker/utils/write.py index <HASH>..<HASH> 100644 --- a/pdfwatermarker/utils/write.py +++ b/pdfwatermarker/utils/write.py @@ -10,7 +10,7 @@ def write_pdf(top_pdf, bottom_pdf, destination): :param destination: Desintation path """ drawing = PdfFileReader(top_pdf) # Create new PDF object - template = PdfFileReader(open(bottom_pdf, "rb")) # read your existing PDF + template = PdfFileReader(bottom_pdf) # read your existing PDF # add the "watermark" (which is the new pdf) on the existing page page = template.getPage(0)
Removed file opening from PdfFileReader and PdfFileWriter object args
py
diff --git a/paper/scripts/k2sc_cdpp.py b/paper/scripts/k2sc_cdpp.py index <HASH>..<HASH> 100755 --- a/paper/scripts/k2sc_cdpp.py +++ b/paper/scripts/k2sc_cdpp.py @@ -22,7 +22,7 @@ import warnings from urllib.error import HTTPError from scipy.signal import savgol_filter -for campaign in range(4,7): +for campaign in range(3,7): print("\nRunning campaign %02d..." % campaign)
add c3 to k2sc
py
diff --git a/tests/test_formatter.py b/tests/test_formatter.py index <HASH>..<HASH> 100644 --- a/tests/test_formatter.py +++ b/tests/test_formatter.py @@ -62,6 +62,11 @@ class CommandTestCase(unittest.TestCase): help='A sample option with numeric choices', type=click.Choice([1, 2, 3]), ) + @click.option( + '--flag', + is_flag=True, + help='A boolean flag', + ) @click.argument('ARG', envvar='ARG') def foobar(bar): """A sample command.""" @@ -102,6 +107,10 @@ class CommandTestCase(unittest.TestCase): :options: 1 | 2 | 3 + .. option:: --flag + + A boolean flag + .. rubric:: Arguments .. option:: ARG
tests: Add test for boolean options This was missing, weirdly. Make sure we don't regress.
py
diff --git a/contrib/buildgen/src/python/pants/contrib/buildgen/build_file_manipulator.py b/contrib/buildgen/src/python/pants/contrib/buildgen/build_file_manipulator.py index <HASH>..<HASH> 100644 --- a/contrib/buildgen/src/python/pants/contrib/buildgen/build_file_manipulator.py +++ b/contrib/buildgen/src/python/pants/contrib/buildgen/build_file_manipulator.py @@ -8,6 +8,7 @@ import ast import logging import re import sys +from builtins import object, str from difflib import unified_diff from pants.build_graph.address import Address, BuildFileAddress
Port buildgen to py3 (#<I>) ### Problem Porting buildgen to py3. Needs references to str and object. ### Solution added builtins import for str and object
py
diff --git a/profiling/remote/select.py b/profiling/remote/select.py index <HASH>..<HASH> 100644 --- a/profiling/remote/select.py +++ b/profiling/remote/select.py @@ -13,7 +13,7 @@ """ from __future__ import absolute_import -from errno import EINTR +from errno import ECONNRESET, EINTR import select import socket import time @@ -98,5 +98,9 @@ class SelectProfilingServer(ProfilingServer): sock, addr = listener.accept() self.connected(sock) else: - sock.recv(1) + try: + sock.recv(1) + except socket.error as exc: + if exc.errno != ECONNRESET: + raise self.disconnected(sock)
Ignore ECONNRESET when handling client disconnection
py
diff --git a/vcr/stubs/__init__.py b/vcr/stubs/__init__.py index <HASH>..<HASH> 100644 --- a/vcr/stubs/__init__.py +++ b/vcr/stubs/__init__.py @@ -6,6 +6,10 @@ from cStringIO import StringIO from vcr.request import Request +class CannotOverwriteExistingCassetteException(Exception): + pass + + def parse_headers(header_list): headers = "".join(header_list) + "\r\n" msg = HTTPMessage(StringIO(headers)) @@ -172,9 +176,10 @@ class VCRConnectionMixin: return VCRHTTPResponse(response) else: if self.cassette.write_protected: - raise Exception( - "Can't overwrite existing cassette in \ - your current record mode." + raise CannotOverwriteExistingCassetteException( + "Can't overwrite existing cassette (%r) in " + "your current record mode (%r)." + % (self.cassette._path, self.cassette.record_mode) ) # Otherwise, we should send the request, then get the response
Nicer error for can't overwrite existing cassette Raise CannotOverwriteExistingCassetteException rather than Exception. Include cassette filename and record mode in error message.
py
diff --git a/setup.py b/setup.py index <HASH>..<HASH> 100644 --- a/setup.py +++ b/setup.py @@ -2,7 +2,7 @@ import os import sys from setuptools import setup, find_packages -version = '0.3.0' +version = '0.4.0' if sys.argv[-1] == 'tag': print("Tagging the version on github:")
Bump to version '<I>'
py
diff --git a/pmagpy/new_builder.py b/pmagpy/new_builder.py index <HASH>..<HASH> 100644 --- a/pmagpy/new_builder.py +++ b/pmagpy/new_builder.py @@ -129,15 +129,20 @@ class Contribution(object): names_list = ['specimen', 'sample', 'site', 'location'] # add in any tables that you can for num, name in enumerate(names_list): - if name in meas_df.columns: + # don't replace tables that already exist + if (name + "s") in self.tables: + continue + elif name in meas_df.columns: + print "making new {} file".format(name) items = meas_df[name].unique() df = pd.DataFrame(columns=[name], index=items) df[name] = df.index - # add in parent name + # add in parent name if possible # (i.e., sample name to specimens table) if num < (len(names_list) - 1): parent = names_list[num+1] - df[parent] = meas_df.drop_duplicates(subset=[name])[parent].values + if parent in meas_df.columns: + df[parent] = meas_df.drop_duplicates(subset=[name])[parent].values self.tables[name + "s"] = MagicDataFrame(dtype=name + "s", df=df)
fix up propagate_measurement_info
py
diff --git a/paypal/standard/models.py b/paypal/standard/models.py index <HASH>..<HASH> 100644 --- a/paypal/standard/models.py +++ b/paypal/standard/models.py @@ -266,6 +266,12 @@ class PayPalStandardBase(Model): def is_recurring_failed(self): return self.txn_type == "recurring_payment_failed" + def is_recurring_suspended(self): + return self.txn_type == "recurring_payment_suspended" + + def is_recurring_suspended_due_to_max_failed_payment(self): + return self.txn_type == "recurring_payment_suspended_due_to_max_failed_payment" + def is_billing_agreement(self): return len(self.mp_id) > 0
Improved support for suspended transaction types. From henriquebastos, thank you!
py
diff --git a/tornado/gen.py b/tornado/gen.py index <HASH>..<HASH> 100644 --- a/tornado/gen.py +++ b/tornado/gen.py @@ -91,7 +91,7 @@ from tornado.log import app_log from tornado.util import TimeoutError import typing -from typing import Union, Any, Callable, List, Type, Tuple, Awaitable, Dict +from typing import Union, Any, Callable, List, Type, Tuple, Awaitable, Dict, overload if typing.TYPE_CHECKING: from typing import Sequence, Deque, Optional, Set, Iterable # noqa: F401 @@ -153,9 +153,21 @@ def _create_future() -> Future: return future +@overload def coroutine( func: Callable[..., "Generator[Any, Any, _T]"] ) -> Callable[..., "Future[_T]"]: + ... + + +@overload +def coroutine(func: Callable[..., _T]) -> Callable[..., "Future[_T]"]: + ... + + +def coroutine( + func: Union[Callable[..., "Generator[Any, Any, _T]"], Callable[..., _T]] +) -> Callable[..., "Future[_T]"]: """Decorator for asynchronous generators. For compatibility with older versions of Python, coroutines may
Allow non-yielding functions in `tornado.gen.coroutine`'s type hint (#<I>) `@gen.coroutine` deco allows non-yielding functions, so I reflected that in the type hint. Requires usage of `@typing.overload` due to python/mypy#<I>
py
diff --git a/photonpump/connection.py b/photonpump/connection.py index <HASH>..<HASH> 100644 --- a/photonpump/connection.py +++ b/photonpump/connection.py @@ -943,8 +943,11 @@ class PhotonPumpProtocol(asyncio.streams.FlowControlMixin): async def dispatch(self): while True: - next_msg = await self.input_queue.get() - await self.dispatcher.dispatch(next_msg, self.output_queue) + try: + next_msg = await self.input_queue.get() + await self.dispatcher.dispatch(next_msg, self.output_queue) + except: + logging.exception("Dispatch loop failed") def connection_lost(self, exn): self._log.debug("Connection lost")
Add try/except around dispatch loop.
py
diff --git a/uber_rides/utils/handlers.py b/uber_rides/utils/handlers.py index <HASH>..<HASH> 100644 --- a/uber_rides/utils/handlers.py +++ b/uber_rides/utils/handlers.py @@ -26,8 +26,6 @@ from __future__ import unicode_literals from uber_rides.errors import ClientError from uber_rides.errors import ServerError -from json import JSONDecodeError - def error_handler(response, **kwargs): """Error Handler to surface 4XX and 5XX errors. @@ -52,7 +50,7 @@ def error_handler(response, **kwargs): """ try: body = response.json() - except JSONDecodeError: + except ValueError: body = {} status_code = response.status_code message = body.get('message', '')
Added better support for python 2/3 to support simplejson/json
py
diff --git a/openid/extensions/pape.py b/openid/extensions/pape.py index <HASH>..<HASH> 100644 --- a/openid/extensions/pape.py +++ b/openid/extensions/pape.py @@ -254,4 +254,4 @@ class Response(Extension): return ns_args -Response.ns_uri = ns_uri +Request.ns_uri = ns_uri
[project @ Fix the ns_uri assignment to the PAPE response]
py
diff --git a/parsl/providers/provider_base.py b/parsl/providers/provider_base.py index <HASH>..<HASH> 100644 --- a/parsl/providers/provider_base.py +++ b/parsl/providers/provider_base.py @@ -29,7 +29,15 @@ class JobState(bytes, Enum): class JobStatus(object): - """Encapsulates a job state together with other details, presently a (error) message""" + """Encapsulates a job state together with other details: + + Args: + state: The machine-reachable state of the job this status refers to + message: Optional human readable message + exit_code: Optional exit code + stdout_path: Optional path to a file containing the job's stdout + stderr_path: Optional path to a file containing the job's stderr + """ SUMMARY_TRUNCATION_THRESHOLD = 2048 def __init__(self, state: JobState, message: Optional[str] = None, exit_code: Optional[int] = None,
Elaborate JobStatus docstring to include stdout/err/state info (#<I>)
py
diff --git a/allauth/account/views.py b/allauth/account/views.py index <HASH>..<HASH> 100644 --- a/allauth/account/views.py +++ b/allauth/account/views.py @@ -94,10 +94,10 @@ class ConfirmEmailView(TemplateResponseMixin, View): } def get_template_names(self): - return { - "GET": ["account/email_confirm.html"], - "POST": ["account/email_confirmed.html"], - }[self.request.method] + if self.request.method == 'POST': + return ["account/email_confirmed.html"] + else: + return [ "account/email_confirm.html" ] def get(self, *args, **kwargs): try:
Confirm e-mail crashes on HEAD request, fixed (closes #<I>)
py
diff --git a/angr/sim_options.py b/angr/sim_options.py index <HASH>..<HASH> 100644 --- a/angr/sim_options.py +++ b/angr/sim_options.py @@ -217,8 +217,8 @@ BEST_EFFORT_MEMORY_STORING = 'BEST_EFFORT_MEMORY_STORING' # Approximation options (to optimize symbolic execution) APPROXIMATE_GUARDS = "APPROXIMATE_GUARDS" APPROXIMATE_SATISFIABILITY = "APPROXIMATE_SATISFIABILITY" # does GUARDS and the rest of the constraints -APPROXIMATE_MEMORY_SIZES = "APPROXIMAGE_MEMORY_SIZES" -APPROXIMATE_MEMORY_INDICES = "APPROXIMAGE_MEMORY_INDICES" +APPROXIMATE_MEMORY_SIZES = "APPROXIMATE_MEMORY_SIZES" +APPROXIMATE_MEMORY_INDICES = "APPROXIMATE_MEMORY_INDICES" VALIDATE_APPROXIMATIONS = "VALIDATE_APPROXIMATIONS" # use an experimental replacement solver
Typo fix in sim_options.py. (#<I>)
py
diff --git a/openhtf/util/measurements.py b/openhtf/util/measurements.py index <HASH>..<HASH> 100644 --- a/openhtf/util/measurements.py +++ b/openhtf/util/measurements.py @@ -63,7 +63,6 @@ Examples: import collections -import itertools import logging from enum import Enum @@ -350,10 +349,8 @@ class Collection(mutablerecords.Record('Collection', ['_measurements'], raise NotAMeasurementError('Not a measurement', name, self._measurements) def __iter__(self): # pylint: disable=invalid-name - def _GetMeasurementValue(item): # pylint: disable=invalid-name - """Extract a single MeasurementValue's value.""" - return item[0], item[1].value - return itertools.imap(_GetMeasurementValue, self._values.iteritems()) + """Extract each MeasurementValue's value.""" + return ((key, val.value) for key, val in self._values.iteritems()) def __setattr__(self, name, value): # pylint: disable=invalid-name self[name] = value
Cleanup measurements.Collection.__iter__ Replaced a function and itertools.imap() call with a simpler generator expression
py
diff --git a/examples/plotting/file/custom_datetime_axis.py b/examples/plotting/file/custom_datetime_axis.py index <HASH>..<HASH> 100644 --- a/examples/plotting/file/custom_datetime_axis.py +++ b/examples/plotting/file/custom_datetime_axis.py @@ -1,4 +1,3 @@ -from pdb import set_trace as bp from math import pi import pandas as pd @@ -10,8 +9,9 @@ from bokeh.models.formatters import TickFormatter, String, List # In this custom TickFormatter, xaxis labels are taken from an array of date # Strings (e.g. ['Sep 01', 'Sep 02', ...]) passed to the date_labels property. class DateGapTickFormatter(TickFormatter): - date_labels = List(item_type=String) - __implementation__ = """ + date_labels = List(String) + + __implementation__ = """ _ = require "underscore" HasProperties = require "common/has_properties" @@ -20,15 +20,11 @@ class DateGapTickFormatter extends HasProperties format: (ticks) -> date_labels = @get("date_labels") - labels = ( - for tick, i in ticks - date_labels[tick] ? "" - ) - return labels + return (date_labels[tick] ? "" for tick in ticks) module.exports = Model: DateGapTickFormatter - """ +""" df = pd.DataFrame(MSFT)[:50]
Stylistic improvements Fixed indentation and improved coffeescript for loop using one-liner syntax
py
diff --git a/packages/vaex-core/vaex/core/_version.py b/packages/vaex-core/vaex/core/_version.py index <HASH>..<HASH> 100644 --- a/packages/vaex-core/vaex/core/_version.py +++ b/packages/vaex-core/vaex/core/_version.py @@ -1,2 +1,2 @@ -__version_tuple__ = (0, 5, 0) -__version__ = '0.5.0' +__version_tuple__ = (0, 5, 1) +__version__ = '0.5.1'
Release <I> of vaex-core
py
diff --git a/quart/serving.py b/quart/serving.py index <HASH>..<HASH> 100644 --- a/quart/serving.py +++ b/quart/serving.py @@ -140,7 +140,8 @@ class HTTPProtocol: ) finally: del self.streams[stream_id] - self._timeout_handle = self.loop.call_later(self._timeout, self._handle_timeout) + if not self.streams: + self._timeout_handle = self.loop.call_later(self._timeout, self._handle_timeout) async def send_response(self, stream_id: int, response: Response) -> None: raise NotImplemented()
Don't trigger an idle timeout, if not idle If there are streams in existance, they are being processed and hence the connection is not idle.
py
diff --git a/aiostream/manager.py b/aiostream/manager.py index <HASH>..<HASH> 100644 --- a/aiostream/manager.py +++ b/aiostream/manager.py @@ -48,6 +48,8 @@ class TaskGroup: # This makes sense since we don't know in which context the exception # was meant to be processed. For instance, a `StopAsyncIteration` # might be raised to notify that the end of a streamer has been reached. + if not task.cancelled(): + task.exception() self._pending.discard(task)
Consume all exceptions for non-cancelled tasks Calling `.exception()` makes sure we do not get `Task exception was never retrieved` if two tasks fail in the same tick. This fixes vxgmichel/aiostream#<I>
py
diff --git a/singularity/hub/registry/utils/recipes.py b/singularity/hub/registry/utils/recipes.py index <HASH>..<HASH> 100644 --- a/singularity/hub/registry/utils/recipes.py +++ b/singularity/hub/registry/utils/recipes.py @@ -37,8 +37,7 @@ def find_recipes(folders,pattern=None, base=None): (indicated by Starting with Singularity :param base: if defined, consider collection folders below this level. - ''' - + ''' if folders is None: folders = os.getcwd() @@ -86,7 +85,10 @@ def find_folder_recipes(base_folder,pattern=None, manifest=None, base=None): container_path = os.path.join(root, filename) if base is not None: - container_uri = container_path.replace(base,'').strip('/').replace('/','-') + container_base = container_path.replace(base,'').strip('/') + collection = container_base.split('/')[0] + recipe = os.path.basename(container_base) + container_uri = "%s/%s" %(collection,recipe) else: container_uri = '/'.join(container_path.strip('/').split('/')[-2:])
modified: singularity/hub/registry/utils/recipes.py
py
diff --git a/gwpy/timeseries/io/losc.py b/gwpy/timeseries/io/losc.py index <HASH>..<HASH> 100644 --- a/gwpy/timeseries/io/losc.py +++ b/gwpy/timeseries/io/losc.py @@ -200,7 +200,7 @@ def read_losc_hdf5(h5f, path='strain/Strain', """ dataset = io_hdf5.find_dataset(h5f, path) # read data - nddata = dataset.value + nddata = dataset[()] # read metadata xunit = parse_unit(dataset.attrs['Xunits']) epoch = dataset.attrs['Xstart']
gwpy.timeseries: fixed HDF5 DeprecationWarning
py
diff --git a/billy/models/events.py b/billy/models/events.py index <HASH>..<HASH> 100644 --- a/billy/models/events.py +++ b/billy/models/events.py @@ -25,8 +25,8 @@ class Event(Document): ''' bills = [] for bill in self['related_bills']: - if 'bill_id' in bill: - bills.append(bill['bill_id']) + if 'id' in bill: + bills.append(bill['id']) return db.bills.find({"_id": {"$in": bills}}) def bills(self):
Use the new correct key for mongo ids
py
diff --git a/pyout.py b/pyout.py index <HASH>..<HASH> 100644 --- a/pyout.py +++ b/pyout.py @@ -459,7 +459,7 @@ class Tabular(object): self._fields[column] = field - _preformat_method = lambda self, x: x + _transform_method = lambda self, x: x def _seq_to_dict(self, row): return dict(zip(self._columns, row)) @@ -501,21 +501,21 @@ class Tabular(object): else: proc_key = "default" - row = self._preformat_method(row) + row = self._transform_method(row) try: proc_fields = [fields[c](row[c], proc_key) for c in self._columns] except TypeError: - if self._preformat_method == self._seq_to_dict: + if self._transform_method == self._seq_to_dict: raise - self._preformat_method = self._seq_to_dict + self._transform_method = self._seq_to_dict self._writerow(row, style, adopt=False) else: self.term.stream.write(self._sep.join(proc_fields) + "\n") def _maybe_write_header(self): if self._header_style is not None: - if self._preformat_method == self._seq_to_dict: + if self._transform_method == self._seq_to_dict: row = self._columns else: if isinstance(self._columns, OrderedDict):
Rename Tabular._{preformat => transform}_method This name better reflects the purpose of this method: it transforms the row into the expected {column: value} form, whereas "preformat" comes from the fact that the original code used this method to prepare the data for a format call.
py
diff --git a/tests/test_pytumblr.py b/tests/test_pytumblr.py index <HASH>..<HASH> 100644 --- a/tests/test_pytumblr.py +++ b/tests/test_pytumblr.py @@ -126,7 +126,7 @@ class TumblrRestClientTest(unittest.TestCase): HTTPretty.register_uri(HTTPretty.POST, 'http://api.tumblr.com/v2/blog/seejohnrun.tumblr.com/post/reblog', body='{"meta": {"status": 200, "msg": "OK"}, "response": []}') - response = self.client.reblog('seejohnrun', id='123', reblog_key="adsfsadf", state='coolguy') + response = self.client.reblog('seejohnrun', id='123', reblog_key="adsfsadf", state='coolguy', tags=['hello', 'world']) assert response == [] experimental_body = parse_qs(HTTPretty.last_request.body) @@ -134,6 +134,7 @@ class TumblrRestClientTest(unittest.TestCase): assert experimental_body['id'][0] == '123' assert experimental_body['reblog_key'][0] == 'adsfsadf' assert experimental_body['state'][0] == 'coolguy' + assert experimental_body['tags'][0] == 'hello,world' @httprettified def test_like(self):
Added a test for #<I>
py
diff --git a/nodeconductor/sugarcrm/backend.py b/nodeconductor/sugarcrm/backend.py index <HASH>..<HASH> 100644 --- a/nodeconductor/sugarcrm/backend.py +++ b/nodeconductor/sugarcrm/backend.py @@ -23,8 +23,6 @@ class SugarCRMBackend(object): def __getattr__(self, name): return getattr(self.backend, name) -# TODO: figure out how SPL sync actually works and why it is not working if sync is not necessary - class SugarCRMBaseBackend(ServiceBackend):
Remove TODO (leftover) - nc-<I>
py
diff --git a/linguist/helpers.py b/linguist/helpers.py index <HASH>..<HASH> 100644 --- a/linguist/helpers.py +++ b/linguist/helpers.py @@ -12,6 +12,9 @@ def prefetch_translations(instances, **kwargs): """ from .mixins import ModelMixin + if not isinstance(instances, collections.Iterable): + instances = [instances] + populate_missing = kwargs.get('populate_missing', True) grouped_translations = utils.get_grouped_translations(instances, **kwargs)
Fix prefetch_translations() -- be sure we only deal with iteratables.
py
diff --git a/sdcclient/_scanning.py b/sdcclient/_scanning.py index <HASH>..<HASH> 100644 --- a/sdcclient/_scanning.py +++ b/sdcclient/_scanning.py @@ -448,9 +448,15 @@ class SdScanningClient(_SdcCommon): **Success Return Value** A JSON object containing the policy description. ''' - url = self.url + '/api/scanning/v1/policies/' + policyid - if bundleid: - url += '?bundleId=' + bundleid + ok, policies = self.list_policies(bundleid) + if not ok: + return [ok, policies] + + for policy in policies: + if policy["id"] == policyid: + return [True, policy] + + return [False, "Policy not found"] def update_policy(self, policyid, policy_description): '''**Description**
Fix error while getting scanning policy (#<I>)
py
diff --git a/src/guake.py b/src/guake.py index <HASH>..<HASH> 100644 --- a/src/guake.py +++ b/src/guake.py @@ -1124,7 +1124,7 @@ def main(): remote_object.quit() called_with_param = True - if not called_with_param: + if not called_with_param and already_running: # here we know that guake was called without any parameter and # it is already running, so, lets toggle its visibility. remote_object.show_hide()
Making guake not be shown when running on first time.
py
diff --git a/ci/lib/opsmgr.py b/ci/lib/opsmgr.py index <HASH>..<HASH> 100644 --- a/ci/lib/opsmgr.py +++ b/ci/lib/opsmgr.py @@ -77,8 +77,8 @@ def delete(url, check_response=True): check_response(response, check_response=check_response) return response -def check_response(response, check_response=True): - if check_response and response.status_code != requests.codes.ok: +def check_response(response, check=True): + if check and response.status_code != requests.codes.ok: print >> sys.stderr, '-', response.status_code try: errors = response.json()["errors"]
New method name collided with argument name
py
diff --git a/src/validate.py b/src/validate.py index <HASH>..<HASH> 100644 --- a/src/validate.py +++ b/src/validate.py @@ -139,8 +139,9 @@ def assert_xl_consistency(xl, mc): def assert_xd_consistency(xd, mr, mc): - assert len(xd) == len(mr["name_to_idx"]) - # is it rectangular? + # is number of row labels in xd's first view equal to number of row names? + assert len(xd[0]) == len(mr["name_to_idx"]) + # do all views have the same number of row labels? assert len(set(map(len, xd))) == 1 def assert_t_consistency(T, mr, mc): @@ -158,7 +159,8 @@ def assert_t_consistency(T, mr, mc): assert T["dimensions"][0] == len(mc["name_to_idx"]) def assert_other(mr, mc, xl, xd, T): - assert len(xl["column_partition"]["counts"]) == len(xd[0]) + # is the number of views in xd equal to their cached counts in xl? + assert len(xl["column_partition"]["counts"]) == len(xd) if __name__ == '__main__': import argparse
fix logic when using xd: was using xd as if transposed
py
diff --git a/tcex/services/services.py b/tcex/services/services.py index <HASH>..<HASH> 100644 --- a/tcex/services/services.py +++ b/tcex/services/services.py @@ -558,7 +558,7 @@ class Services(object): status_code, status = args[0].split(' ', 1) response = { 'bodyVariable': 'response.body', - 'command': 'Acknowledge', + 'command': 'Acknowledged', 'headers': self.format_response_headers(args[1]), 'requestKey': kwargs.get('request_key'), # pylint: disable=cell-var-from-loop 'status': status,
Update commond type for run service to Acknowledged
py
diff --git a/src/SALib/util/__init__.py b/src/SALib/util/__init__.py index <HASH>..<HASH> 100755 --- a/src/SALib/util/__init__.py +++ b/src/SALib/util/__init__.py @@ -348,4 +348,4 @@ def _compute_delta(num_levels: int) -> float: ------- float """ - return num_levels / (2.0 * (num_levels - 1)) \ No newline at end of file + return num_levels / (2.0 * (num_levels - 1))
Small change to conform to PEP8
py
diff --git a/lib/svtplay/hds.py b/lib/svtplay/hds.py index <HASH>..<HASH> 100644 --- a/lib/svtplay/hds.py +++ b/lib/svtplay/hds.py @@ -253,9 +253,8 @@ def readasrtbox(data, pos): def decode_f4f(fragID, fragData): start = fragData.find("mdat") + 4 if (fragID > 1): - for dummy in range(2): - tagLen, = struct.unpack_from(">L", fragData, start) - tagLen &= 0x00ffffff - start += tagLen + 11 + 4 + tagLen, = struct.unpack_from(">L", fragData, start) + tagLen &= 0x00ffffff + start += tagLen + 11 + 4 return start
download_hds: fix some decoding problems Saw some issues while downloading streams from urplay.
py
diff --git a/pdfconduit/__init__.py b/pdfconduit/__init__.py index <HASH>..<HASH> 100644 --- a/pdfconduit/__init__.py +++ b/pdfconduit/__init__.py @@ -1,5 +1,5 @@ __all__ = ["upscale", "rotate", "Encrypt", "Merge", "Watermark", "Label", "WatermarkAdd", "slicer", - "GUI"] + "GUI", "Info"] __version__ = '1.1.4' __author__ = 'Stephen Neal'
Added Info class to __all__
py
diff --git a/ravel.py b/ravel.py index <HASH>..<HASH> 100644 --- a/ravel.py +++ b/ravel.py @@ -731,7 +731,7 @@ class Connection : if reply != None : result = reply.expect_return_objects(call_info["out_signature"]) else : - result = None + raise dbus.DBusError(DBUS.ERROR_TIMEOUT, "server took too long to return reply") #end if return \ result @@ -778,7 +778,7 @@ class Connection : if reply != None : result = reply.expect_return_objects(call_info["out_signature"]) else : - result = None + raise dbus.DBusError(DBUS.ERROR_TIMEOUT, "server took too long to return reply") #end if return \ result
raise timeout exception rather than return None method response
py
diff --git a/forms_builder/forms/migrations/0003_auto__add_field_field_slug.py b/forms_builder/forms/migrations/0003_auto__add_field_field_slug.py index <HASH>..<HASH> 100644 --- a/forms_builder/forms/migrations/0003_auto__add_field_field_slug.py +++ b/forms_builder/forms/migrations/0003_auto__add_field_field_slug.py @@ -12,10 +12,12 @@ class Migration(SchemaMigration): db.add_column('forms_field', 'slug', self.gf('django.db.models.fields.SlugField')(default='', max_length=100, blank=True), keep_default=False) + db.create_unique('forms_field', ['slug', 'form_id']) def backwards(self, orm): # Deleting field 'Field.slug' db.delete_column('forms_field', 'slug') + db.delete_unique('forms_field', ['slug', 'form_id']) models = { 'forms.field': { @@ -74,4 +76,4 @@ class Migration(SchemaMigration): } } - complete_apps = ['forms'] \ No newline at end of file + complete_apps = ['forms']
Add unique_together constract for form, field.slug
py
diff --git a/src/dependencies/_package.py b/src/dependencies/_package.py index <HASH>..<HASH> 100644 --- a/src/dependencies/_package.py +++ b/src/dependencies/_package.py @@ -5,15 +5,15 @@ from ._this import random_string class Package(object): def __init__(self, name): - self.__name = name + self.__name__ = name def __getattr__(self, attrname): - return Package(self.__name + "." + attrname) + return Package(self.__name__ + "." + attrname) def resolve_package_link(package, injector): - names = package._Package__name.split(".") + names = package.__name__.split(".") modulename, attributes = names[0], names[1:] result = importlib.import_module(modulename) do_import = True
Dependencies package is using dunder names.
py
diff --git a/docs/conf.py b/docs/conf.py index <HASH>..<HASH> 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -17,7 +17,7 @@ import os # If your extensions are in another directory, add it here. If the directory # is relative to the documentation root, use os.path.abspath to make it # absolute, like shown here. -sys.path.insert(0, "../carrot") +sys.path.insert(0, "../") import carrot # General configuration
"../" not "../carrot"
py
diff --git a/pykeyboard/base.py b/pykeyboard/base.py index <HASH>..<HASH> 100644 --- a/pykeyboard/base.py +++ b/pykeyboard/base.py @@ -103,7 +103,7 @@ class PyKeyboardEventMeta(Thread): #simpler, without digging a bunch of traps for incompatibilities between #platforms. - #Keeping track of the keyboard's state is not only generally necessary to + #Keeping track of the keyboard's state is not only necessary at times to #correctly interpret character identities in keyboard events, but should #also enable a user to easily query modifier states without worrying about #chaining event triggers for mod-combinations
Changed comment about state trackig being generally necessary for conversion, this may only be true for x<I>
py
diff --git a/SpiffWorkflow/bpmn/specs/EndEvent.py b/SpiffWorkflow/bpmn/specs/EndEvent.py index <HASH>..<HASH> 100644 --- a/SpiffWorkflow/bpmn/specs/EndEvent.py +++ b/SpiffWorkflow/bpmn/specs/EndEvent.py @@ -15,10 +15,9 @@ # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA from SpiffWorkflow.bpmn.specs.BpmnSpecMixin import BpmnSpecMixin -from SpiffWorkflow.bpmn.specs.ParallelGateway import ParallelGateway from SpiffWorkflow.Task import Task -class EndEvent(ParallelGateway, BpmnSpecMixin): +class EndEvent(BpmnSpecMixin): """ Task Spec for a bpmn:endEvent node. """
The EndEvent shouldn't be a subclass of ParallelGateway. In fact it doesn't need to be a Join at all.
py
diff --git a/openquake/commands/plot.py b/openquake/commands/plot.py index <HASH>..<HASH> 100644 --- a/openquake/commands/plot.py +++ b/openquake/commands/plot.py @@ -111,7 +111,9 @@ def make_figure_hmaps(extractors, what): itime = oq1.investigation_time assert oq2.investigation_time == itime sitecol = ex1.get('sitecol') - assert (ex2.get('sitecol').array == sitecol.array).all() + array2 = ex2.get('sitecol').array + for name in ('lon', 'lat'): + numpy.testing.assert_equal(array2[name], sitecol.array[name]) hmaps1 = ex1.get(what) hmaps2 = ex2.get(what) [imt] = hmaps1.imt
Fixed oq plot hmaps
py
diff --git a/salt/utils/slack.py b/salt/utils/slack.py index <HASH>..<HASH> 100644 --- a/salt/utils/slack.py +++ b/salt/utils/slack.py @@ -123,4 +123,3 @@ def query(function, return ret ret['message'] = _result.get(response) return ret -
Fixing empty line at the end of salt.utils.slack.
py
diff --git a/menuinst/win32.py b/menuinst/win32.py index <HASH>..<HASH> 100644 --- a/menuinst/win32.py +++ b/menuinst/win32.py @@ -74,12 +74,17 @@ class ShortCut(object): cmd = join(self.prefix, 'pythonw.exe') args = ['-m', 'webbrowser', '-t', self.shortcut['webbrowser']] + elif "script" in self.shortcut: + cmd = join(self.prefix, self.shortcut["script"].replace('/', '\\')) + args = [self.shortcut['scriptargument']] + else: raise Exception("Nothing to do: %r" % self.shortcut) workdir = self.shortcut.get('workdir', '') icon = self.shortcut.get('icon', '') for a, b in [ + ('${PREFIX}', self.prefix), ('${PYTHON_SCRIPTS}', join(self.prefix, 'Scripts')), ('${MENU_DIR}', join(self.prefix, 'Menu')), ('${PERSONALDIR}', get_folder_path('CSIDL_PERSONAL')),
Support 'script' key to shortcut to arbitrary executable
py
diff --git a/salt/runners/manage.py b/salt/runners/manage.py index <HASH>..<HASH> 100644 --- a/salt/runners/manage.py +++ b/salt/runners/manage.py @@ -5,7 +5,6 @@ and what hosts are down # Import python libs import os -import shutil # Import salt libs import salt.key
runners.manage: rm unused import of shutil
py
diff --git a/dddp/api.py b/dddp/api.py index <HASH>..<HASH> 100644 --- a/dddp/api.py +++ b/dddp/api.py @@ -498,7 +498,10 @@ class DDP(APIMixin): return try: result = handler(*params) - this.send_msg({'msg': 'result', 'id': id_, 'result': result}) + msg = {'msg': 'result', 'id': id_} + if result is not None: + msg['result'] = result + this.send_msg(msg) except Exception, err: # log error+stack trace -> pylint: disable=W0703 details = traceback.format_exc() this.ws.logger.error(err, exc_info=True)
Don't include null/None reply from method calls in message.
py
diff --git a/setup.py b/setup.py index <HASH>..<HASH> 100644 --- a/setup.py +++ b/setup.py @@ -563,15 +563,14 @@ hds = Extension('starlink.hds', setup(name='starlink-hds', version='0.1', - description='Python interface to the Starlink HDS library' - packages =['starlink'], + description='Python interface to the Starlink HDS library', + packages=['starlink'], ext_modules=[hds], test_suite='test', # metadata author='SF Graves', author_email='[email protected]', - description='Python interface to Starlink hds library', url='https://github.com/sfgraves/starlink-pyhds', license="GNU GPL v3", classifiers=[ @@ -580,9 +579,8 @@ setup(name='starlink-hds', 'Programming Language :: Python', 'Programming Language :: C', 'Topic :: Scientific/Engineering :: Astrononomy', - ] - + ], install_requires = [ 'numpy', - ] + ], )
Fix typos in setup.py
py
diff --git a/src/sos/step_executor.py b/src/sos/step_executor.py index <HASH>..<HASH> 100755 --- a/src/sos/step_executor.py +++ b/src/sos/step_executor.py @@ -409,6 +409,7 @@ class Base_Step_Executor: env.sos_dict.set('step_depends', sos_targets([])) env.sos_dict.set('_depends', sos_targets([])) + # # Common functions # @@ -632,6 +633,11 @@ class Base_Step_Executor: raise ValueError( f'An integer value is expected for runtime option trunk_workers, {env.sos_dict["_runtime"]["trunk_workers"]} provided' ) + if 'nodes' in env.sos_dict['_runtime']: + raise ValueError( + 'Option "trunk_workers" that specifies number of nodes and processes for the execution ' + 'of single-node jobs and option "nodes" that specifies number of nodes for single multi-node ' + 'jobs cannot be used at the same time.') trunk_workers = env.sos_dict['_runtime']['trunk_workers'] else: trunk_workers = 0
Disallow the concurrent use options trunk_workers and nodes #<I>
py
diff --git a/bypy.py b/bypy.py index <HASH>..<HASH> 100755 --- a/bypy.py +++ b/bypy.py @@ -1500,13 +1500,15 @@ class ByPy(object): return EFileWrite def __store_json(self, r): + j = {} try: - r.json() + j = r.json() except Exception: perr("Failed to decode JSON:\n" \ "Exception:\n{}".format(traceback.format_exc())) + perr("Error response:\n{}".format(r.text)); return EInvalidJson - return self.__store_json_only(r.json()) + return self.__store_json_only(j) def __load_local_bduss(self): try:
Print auth/refresh web response on error
py
diff --git a/setup.py b/setup.py index <HASH>..<HASH> 100644 --- a/setup.py +++ b/setup.py @@ -20,6 +20,7 @@ setup(name='universe', 'twisted', 'ujson', ], + package_data={'universe': 'runtimes.yml'}, tests_require=['pytest'], extras_require={ 'atari': 'gym[atari]',
include runtimes.yml in pip package
py
diff --git a/salt/modules/wordpress.py b/salt/modules/wordpress.py index <HASH>..<HASH> 100644 --- a/salt/modules/wordpress.py +++ b/salt/modules/wordpress.py @@ -10,8 +10,8 @@ from __future__ import absolute_import import collections # Import Salt Modules -from salt.ext.six.moves import map import salt.utils.path +from salt.ext.six.moves import map Plugin = collections.namedtuple('Plugin', 'name status update versino')
Update reference to old salt.utils.which function
py
diff --git a/salt/monitor.py b/salt/monitor.py index <HASH>..<HASH> 100644 --- a/salt/monitor.py +++ b/salt/monitor.py @@ -149,21 +149,21 @@ class MonitorCommand(object): ''' A single monitor command. ''' - def __init__(self, name, src, context, sleeper=None): - self.name = name + def __init__(self, cmdid, src, context, sleeper=None): + self.cmdid = cmdid self.code = compile(src, '<monitor-config>', 'exec') self.sleeper = sleeper self.context = context def run(self): - log.trace('start thread for %s', self.name) + log.trace('start thread for %s', self.cmdid) if self.sleeper is None: exec self.code in self.context else: while True: exec self.code in self.context duration = self.sleeper.next() - log.trace('sleep %s seconds', duration) + log.trace('%s: sleep %s seconds', self.cmdid, duration) time.sleep(duration) class Monitor(object):
Include the command id when trace logging each command's sleep
py
diff --git a/payflowpro/classes.py b/payflowpro/classes.py index <HASH>..<HASH> 100644 --- a/payflowpro/classes.py +++ b/payflowpro/classes.py @@ -50,7 +50,7 @@ class Field(object): class CreditCardField(Field): def clean(self, value): if isinstance(value, basestring): - return re.sub(r'\s', '', value) + return re.sub(r'-', '', re.sub(r'\s', '', value)) else: return value
Remove '-' from credit card numbers
py
diff --git a/src/reap/commands/reports.py b/src/reap/commands/reports.py index <HASH>..<HASH> 100644 --- a/src/reap/commands/reports.py +++ b/src/reap/commands/reports.py @@ -112,8 +112,10 @@ def hours(args): else: unbillable += proj_total total += proj_total - ratio = billable / unbillable if unbillable > 0.0 else 'Undef.' - percent = billable / total if total > 0.0 else 'Undef.' + # Divide by zero is undefined, but fudge it a little bit + # for easier output. + ratio = billable / unbillable if unbillable > 0.0 else 0.0 + percent = billable / total if total > 0.0 else 0.0 print str.format( HOURS_REPORT_FORMAT, total = total,
Fixed a problem with the hours report.
py
diff --git a/src/pycrunchbase/pycrunchbase.py b/src/pycrunchbase/pycrunchbase.py index <HASH>..<HASH> 100755 --- a/src/pycrunchbase/pycrunchbase.py +++ b/src/pycrunchbase/pycrunchbase.py @@ -69,7 +69,7 @@ class CrunchBase(object): Returns FundingRound or None """ - node_data = self.get_node('funding-round', uuid) + node_data = self.get_node('funding-rounds', uuid) return FundingRound(node_data) if node_data else None def acquisition(self, uuid):
Update funding-round to funding-rounds
py
diff --git a/source/rafcon/gui/mygaphas/items/state.py b/source/rafcon/gui/mygaphas/items/state.py index <HASH>..<HASH> 100644 --- a/source/rafcon/gui/mygaphas/items/state.py +++ b/source/rafcon/gui/mygaphas/items/state.py @@ -371,7 +371,7 @@ class StateView(Element): self.update_minimum_size_of_children() def update_port_position(port_v, meta_data): - if contains_geometric_info(meta_data['rel_pos']) == 2: + if contains_geometric_info(meta_data['rel_pos']): port_v.handle.pos = meta_data['rel_pos'] self.port_constraints[port_v].update_position(meta_data['rel_pos'])
fix(state): Properly check for geometric info in outcome meta data Issue was introduced in old commit <I>e0d<I>
py
diff --git a/testing/test_looponfail.py b/testing/test_looponfail.py index <HASH>..<HASH> 100644 --- a/testing/test_looponfail.py +++ b/testing/test_looponfail.py @@ -193,6 +193,8 @@ class TestLooponFailing: assert 'test_one' not in remotecontrol.failures[0] assert 'test_two' in remotecontrol.failures[0] + @py.test.mark.xfail(py.test.__version__ >= "3.1", + reason="broken by pytest 3.1+") def test_looponfail_removed_test(self, testdir): modcol = testdir.getmodulecol(""" def test_one():
mark looponfail tests broken by <I>+ as xfail
py
diff --git a/jsonklog/lib.py b/jsonklog/lib.py index <HASH>..<HASH> 100644 --- a/jsonklog/lib.py +++ b/jsonklog/lib.py @@ -14,7 +14,10 @@ # limitations under the License. # -# Originally borrowed from @Openstack/Nova +# Originally borrowed from @Openstack/Nova (All licenses apply to below code as per openstack.org + Apache) +# will be heavily modified before it makes it to being released, currently just for testing as an example... +# +# https://github.com/openstack/nova/blob/master/nova/log.py - JSONFormatter originally from there import logging import traceback
Updated lib.py, and added some more notes about OpenStack
py
diff --git a/pyani/pyani_graphics.py b/pyani/pyani_graphics.py index <HASH>..<HASH> 100644 --- a/pyani/pyani_graphics.py +++ b/pyani/pyani_graphics.py @@ -10,9 +10,9 @@ # Leighton Pritchard, # Strathclyde Institute of Pharmaceutical and Biomedical Sciences # The University of Strathclyde -#  Cathedral Street +# Cathedral Street # Glasgow -#  G1 1XQ +# G1 1XQ # Scotland, # UK # @@ -242,7 +242,7 @@ def distribution_seaborn(dfr, outfilename, matname, title=None): elif matname in ["hadamard", "coverage"]: ax.set_xlim(0, 1.01) elif matname == "identity": - ax.set_xlim(ax.get_xlim()[0], 1.01) + ax.set_xlim(0.75, 1.01) # Tidy figure fig.tight_layout(rect=[0, 0.03, 1, 0.95])
set lower bound on identity distribution graph x axis to <I>
py
diff --git a/ftfy/__init__.py b/ftfy/__init__.py index <HASH>..<HASH> 100644 --- a/ftfy/__init__.py +++ b/ftfy/__init__.py @@ -340,10 +340,8 @@ def guess_bytes(bstring): return bstring.decode('utf-16'), 'utf-16' byteset = set(bytes(bstring)) - byte_ed, byte_c0, byte_CR, byte_LF = b'\xed\xc0\r\n' - try: - if byte_ed in byteset or byte_c0 in byteset: + if 0xed in byteset or 0xc0 in byteset: # Byte 0xed can be used to encode a range of codepoints that # are UTF-16 surrogates. UTF-8 does not use UTF-16 surrogates, # so when we see 0xed, it's very likely we're being asked to @@ -370,7 +368,8 @@ def guess_bytes(bstring): except UnicodeDecodeError: pass - if byte_CR in bstring and byte_LF not in bstring: + if 0x0d in byteset and 0x0a not in byteset: + # Files that contain CR and not LF are likely to be MacRoman. return bstring.decode('macroman'), 'macroman' else: return bstring.decode('sloppy-windows-1252'), 'sloppy-windows-1252'
simplify how bytes are identified in guess_bytes
py
diff --git a/lib/python/vdm/server/HTTPListener.py b/lib/python/vdm/server/HTTPListener.py index <HASH>..<HASH> 100644 --- a/lib/python/vdm/server/HTTPListener.py +++ b/lib/python/vdm/server/HTTPListener.py @@ -1970,6 +1970,30 @@ class StopDatabaseAPI(MethodView): 500) +class StopServerAPI(MethodView): + """Class to handle request to stop a server.""" + + @staticmethod + def put(database_id, server_id): + """ + Stops VoltDB database server on the specified server + Args: + database_id (int): The id of the database that should be stopped + server_id (int): The id of the server node that is to be stopped + Returns: + Status string indicating if the stop request was sent successfully + """ + + try: + server = voltdbserver.VoltDatabase(database_id) + response = server.kill_server(server_id) + return response + except Exception, err: + print traceback.format_exc() + return make_response(jsonify({'statusstring': str(err)}), + 500) + + class StartServerAPI(MethodView): """Class to handle request to start a server for this database."""
VDM-<I>: Accidently removed StopServerAPI fixed
py
diff --git a/mtools/mplotqueries/plottypes/scatter_type.py b/mtools/mplotqueries/plottypes/scatter_type.py index <HASH>..<HASH> 100644 --- a/mtools/mplotqueries/plottypes/scatter_type.py +++ b/mtools/mplotqueries/plottypes/scatter_type.py @@ -7,6 +7,7 @@ import argparse try: import matplotlib.pyplot as plt + from matplotlib import __version__ as mpl_version from matplotlib.dates import date2num from matplotlib.lines import Line2D from matplotlib.patches import Polygon @@ -71,7 +72,9 @@ class ScatterPlotType(BasePlotType): group = event.artist._mt_group indices = event.ind - if not event.mouseevent.dblclick: + # double click only supported on 1.2 or later + major, minor, _ = mpl_version.split('.') + if (int(major), int(minor)) < (1, 2) or not event.mouseevent.dblclick: for i in indices: print self.groups[group][i].line_str
checking for version before accessing dblclick event in matplotlib.
py
diff --git a/simuvex/s_state.py b/simuvex/s_state.py index <HASH>..<HASH> 100644 --- a/simuvex/s_state.py +++ b/simuvex/s_state.py @@ -282,7 +282,10 @@ class SimState(object): # pylint: disable=R0904 # Returns a concretized value of the content in a register def reg_concrete(self, *args, **kwargs): - return self.se.utils.concretize_constant(self.reg_expr(*args, **kwargs)) + e = self.reg_expr(*args, **kwargs) + if self.se.symbolic(e): + raise SimValueError("target of reg_concrete is symbolic!") + return self.se.any_int(e) # Stores a bitvector expression in a register def store_reg(self, offset, content, length=None, endness=None): @@ -485,6 +488,6 @@ class SimState(object): # pylint: disable=R0904 from .s_memory import SimMemory from .s_arch import Architectures -from .s_errors import SimMergeError +from .s_errors import SimMergeError, SimValueError from .s_inspect import BP_AFTER, BP_BEFORE import simuvex.s_options as o
fixed reg_concrete for Fish
py
diff --git a/salt/modules/serverdensity_device.py b/salt/modules/serverdensity_device.py index <HASH>..<HASH> 100644 --- a/salt/modules/serverdensity_device.py +++ b/salt/modules/serverdensity_device.py @@ -11,7 +11,7 @@ import requests import json import logging -from six.moves import map +from salt.utils.six.moves import map from salt.exceptions import CommandExecutionError
Replaced module six in file /salt/modules/serverdensity_device.py
py
diff --git a/scripts/build-property-graph.py b/scripts/build-property-graph.py index <HASH>..<HASH> 100644 --- a/scripts/build-property-graph.py +++ b/scripts/build-property-graph.py @@ -17,7 +17,7 @@ def make_property_graph(): ] for ontology in ontologies: - print(ontology) + print("parsing: " + ontology) graph.parse(ontology, format='xml') # Get object properties @@ -57,9 +57,9 @@ def make_property_graph(): return -def add_property_to_graph(results, graph, property): +def add_property_to_graph(results, graph, property_type): for row in results: - graph.add((row[0], RDF['type'], property)) + graph.add((row[0], RDF['type'], property_type)) return graph
remove python reserved name (property)
py
diff --git a/pyqode/core/widgets/errors_table.py b/pyqode/core/widgets/errors_table.py index <HASH>..<HASH> 100644 --- a/pyqode/core/widgets/errors_table.py +++ b/pyqode/core/widgets/errors_table.py @@ -157,6 +157,6 @@ class ErrorsTable(QtWidgets.QTableWidget): QtWidgets.QMessageBox.information( self, 'Message details', """<p><b>Description:</b><br/>%s</p> - <i><p><b>File:</b><br/>%s</p> - <p><b>Line: </b>%d</p></i> +<p><b>File:</b><br/>%s</p> +<p><b>Line:</b><br/>%d</p> """ % (msg.description, msg.path, msg.line + 1, ))
Fix strange formatting of errors details Remove indentation and italic markup Indentation was not made on purpose and italic marks were wrongly placed. See OpenCobolIDE/OpenCobolIDE#<I>
py
diff --git a/skyfield/chaining.py b/skyfield/chaining.py index <HASH>..<HASH> 100644 --- a/skyfield/chaining.py +++ b/skyfield/chaining.py @@ -23,7 +23,7 @@ class Body(object): def observe(self, body): every = self.segments + body.segments - segment_dict = {segment.target: segment for segment in every} + segment_dict = dict((segment.target, segment) for segment in every) center_chain = list(_center(self.code, segment_dict))[::-1] target_chain = list(_center(body.code, segment_dict))[::-1] if not center_chain[0].center == target_chain[0].center == 0: @@ -35,7 +35,7 @@ class Body(object): def _connect(body1, body2): """Return ``(sign, segment)`` tuple list leading from body1 to body2.""" every = body1.segments + body2.segments - segment_dict = {segment.target: segment for segment in every} + segment_dict = dict((segment.target, segment) for segment in every) segments1 = list(_center(body1.code, segment_dict))[::-1] segments2 = list(_center(body2.code, segment_dict))[::-1] if segments1[0].center != segments2[0].center:
Repent of dict comprehensions for sake of <I>
py
diff --git a/wandb/meta.py b/wandb/meta.py index <HASH>..<HASH> 100644 --- a/wandb/meta.py +++ b/wandb/meta.py @@ -153,8 +153,8 @@ class Meta(object): pass # TODO: we should use the cuda library to collect this if os.path.exists("/usr/local/cuda/version.txt"): - self.data["cuda"] = open( - "/usr/local/cuda/version.txt").read().split(" ")[-1].strip() + with open("/usr/local/cuda/version.txt") as f: + self.data["cuda"] = f.read().split(" ")[-1].strip() self.data["args"] = sys.argv[1:] self.data["state"] = "running"
Remove ResourceWarning (#<I>)
py
diff --git a/google/gax/__init__.py b/google/gax/__init__.py index <HASH>..<HASH> 100644 --- a/google/gax/__init__.py +++ b/google/gax/__init__.py @@ -41,7 +41,7 @@ from google.gax.errors import GaxError from google.gax.retry import retryable -__version__ = '0.15.0' +__version__ = '0.15.1' _LOG = logging.getLogger(__name__)
Bump the version (#<I>)
py
diff --git a/visidata/_types.py b/visidata/_types.py index <HASH>..<HASH> 100644 --- a/visidata/_types.py +++ b/visidata/_types.py @@ -34,7 +34,7 @@ def currency(s=''): class vlen(int): def __new__(cls, v): - if isinstance(v, vlen): + if isinstance(v, (vlen, int)): return super(vlen, cls).__new__(cls, v) else: return super(vlen, cls).__new__(cls, len(v))
[vlen] allow constructor to take int also
py
diff --git a/visidata/join.py b/visidata/join.py index <HASH>..<HASH> 100644 --- a/visidata/join.py +++ b/visidata/join.py @@ -17,7 +17,7 @@ def createJoinedSheet(sheets, jointype=''): elif jointype == 'extend': vs = copy(sheets[0]) vs.name = '+'.join(vs.name for vs in sheets) - vs.reload = functools.partial(ExtendedSheet_reload, vs, sources=sheets) + vs.reload = functools.partial(ExtendedSheet_reload, vs, sheets) vs.rows = tuple() # to induce reload on first push, see vdtui return vs else:
[join bugfix] extend passes source sheets as positional arg
py
diff --git a/pyemma/coordinates/io/data_in_memory.py b/pyemma/coordinates/io/data_in_memory.py index <HASH>..<HASH> 100644 --- a/pyemma/coordinates/io/data_in_memory.py +++ b/pyemma/coordinates/io/data_in_memory.py @@ -6,9 +6,6 @@ from scipy.spatial.distance import cdist from pyemma.coordinates.transform.transformer import Transformer from pyemma.util.log import getLogger -logger = getLogger('DataInMemory') - - class DataInMemory(Transformer): r""" @@ -26,7 +23,7 @@ class DataInMemory(Transformer): def __init__(self, _data, **kwargs): Transformer.__init__(self) - + self.logger = getLogger('DataInMemory[%i]' % id(self)) self.data_producer = self if isinstance(_data, np.ndarray): @@ -169,6 +166,7 @@ class DataInMemory(Transformer): if lag == 0: if self.t >= traj_len: self.itraj += 1 + self.t = 0 return X else: # its okay to return empty chunks @@ -177,6 +175,7 @@ class DataInMemory(Transformer): Y = traj[self.t + lag: upper_bound] if self.t + lag >= traj_len: self.itraj += 1 + self.t = 0 return X, Y @staticmethod
[DataInMemory] reset time if itraj is incremented.
py
diff --git a/cleanerversion/__init__.py b/cleanerversion/__init__.py index <HASH>..<HASH> 100644 --- a/cleanerversion/__init__.py +++ b/cleanerversion/__init__.py @@ -1,4 +1,4 @@ -VERSION = (2, 0, 1) +VERSION = (2, 1, 0) def get_version(positions=None):
Bumped version number to <I>
py
diff --git a/setup.py b/setup.py index <HASH>..<HASH> 100644 --- a/setup.py +++ b/setup.py @@ -1,5 +1,3 @@ -#!/usr/bin/env python3 -# -*- coding: utf-8 -*- try: from setuptools import setup except ImportError:
Remove shebang and encoding from setup.py
py
diff --git a/wfdb/processing/basic.py b/wfdb/processing/basic.py index <HASH>..<HASH> 100644 --- a/wfdb/processing/basic.py +++ b/wfdb/processing/basic.py @@ -122,7 +122,7 @@ def resample_singlechan(x, ann, fs, fs_target): assert ann.sample.shape == new_sample.shape resampled_ann = Annotation(ann.record_name, ann.extension, new_sample, - ann.symbol, ann.num, ann.subtype, ann.chan, ann.aux_note, ann.fs) + ann.symbol, ann.num, ann.subtype, ann.chan, ann.aux_note, fs_target) return resampled_x, resampled_ann @@ -166,7 +166,7 @@ def resample_multichan(xs, ann, fs, fs_target, resamp_ann_chan=0): assert ann.sample.shape == new_sample.shape resampled_ann = Annotation(ann.record_name, ann.extension, new_sample, ann.symbol, - ann.num, ann.subtype, ann.chan, ann.aux_note, ann.fs) + ann.num, ann.subtype, ann.chan, ann.aux_note, fs_target) return numpy.column_stack(lx), resampled_ann
resampling: ann.fs -> fs_target New Annotation object should be setting the frequency to fs_target instead of the previous fs
py
diff --git a/git/test/test_git.py b/git/test/test_git.py index <HASH>..<HASH> 100644 --- a/git/test/test_git.py +++ b/git/test/test_git.py @@ -210,7 +210,6 @@ class TestGit(TestBase): assert err.status == 128 else: assert 'FOO' in str(err) - assert err.status == 2 # end # end # end if select.poll exists
fix(cmd): allow any kind of status message I see no need in verifying the status code. It's enough to just get the error.
py
diff --git a/fabfile.py b/fabfile.py index <HASH>..<HASH> 100644 --- a/fabfile.py +++ b/fabfile.py @@ -204,7 +204,7 @@ def uname(): @task -def reset(): +def reset(withPasswordReset=False): check_config() print green('Resetting '+ settings['name'] + "@" + current_config) @@ -212,7 +212,8 @@ def reset(): with cd(env.config['siteFolder']): with shell_env(COLUMNS='72'): if env.config['useForDevelopment'] == True: - run('drush user-password admin --password="admin"') + if withPasswordReset in [True, 'True', '1']: + run('drush user-password admin --password="admin"') run('chmod -R 777 ' + env.config['filesFolder']) if 'deploymentModule' in settings: run('drush en -y ' + settings['deploymentModule']) @@ -376,7 +377,7 @@ def copyDbFrom(config_name): def copyFrom(config_name = False): copyFilesFrom(config_name) copyDbFrom(config_name) - reset() + reset(withPasswordReset=True) @task def drush(drush_command):
reset password only when requested (reset:withPasswordReset=True) or after copyFrom
py
diff --git a/seleniumbase/masterqa/master_qa.py b/seleniumbase/masterqa/master_qa.py index <HASH>..<HASH> 100755 --- a/seleniumbase/masterqa/master_qa.py +++ b/seleniumbase/masterqa/master_qa.py @@ -77,6 +77,11 @@ class __MasterQATestCase__(BaseCase): text = self.execute_script( '''if(confirm("%s")){return "Success!"} else{return "Failure!"}''' % question) + elif self.browser == 'chrome': + self.execute_script('''if(confirm("%s")) + {window.master_qa_result="Success!"} + else{window.master_qa_result="Failure!"}''' % question) + text = self.execute_script('''return window.master_qa_result''') else: self.execute_script('''if(confirm("%s")){window.alert("Success!")} else{window.alert("Failure!")}''' % question)
Fix a bug that prevented masterqa tests from working in chrome
py
diff --git a/pyregion/core.py b/pyregion/core.py index <HASH>..<HASH> 100644 --- a/pyregion/core.py +++ b/pyregion/core.py @@ -255,7 +255,8 @@ def open(fname): shapes : `ShapeList` List of `~pyregion.Shape` """ - region_string = _builtin_open(fname).read() + with _builtin_open(fname) as fh: + region_string = fh.read() return parse(region_string)
Use with open to avoid keeping filehandles open indefinitely
py
diff --git a/setup.py b/setup.py index <HASH>..<HASH> 100644 --- a/setup.py +++ b/setup.py @@ -1,8 +1,10 @@ -from distutils.core import setup +from setuptools import setup, find_packages setup( name='pydirectory', - packages=['pydirectory'], # this must be the same as the name above + packages=find_packages(exclude=['contrib', 'docs', 'tests']), # this + # must be the same as the name + # above version='0.1.0', description='A class representing a file system directory, that deletes on ' 'garbage collect.',
Uploaded the package to PyPI Test
py
diff --git a/examples/commandline/sonoshell.py b/examples/commandline/sonoshell.py index <HASH>..<HASH> 100644 --- a/examples/commandline/sonoshell.py +++ b/examples/commandline/sonoshell.py @@ -57,9 +57,17 @@ def print_current_track_info(): def print_queue(): queue = sonos.get_queue() + current = int(sonos.get_current_track_info()['playlist_position']) + for idx, track in enumerate(queue, 1): + if (idx == current): + color = '\033[1m' + else: + color = '\033[0m' + print( - "%d: %s - %s. From album %s." % ( + "%s%d: %s - %s. From album %s." % ( + color, idx, track['artist'], track['title'],
Color highlight the current track in the queue.
py
diff --git a/openquake/hazardlib/probability_map.py b/openquake/hazardlib/probability_map.py index <HASH>..<HASH> 100644 --- a/openquake/hazardlib/probability_map.py +++ b/openquake/hazardlib/probability_map.py @@ -16,6 +16,7 @@ # You should have received a copy of the GNU Affero General Public License # along with OpenQuake. If not, see <http://www.gnu.org/licenses/>. from openquake.baselib.python3compat import zip +from openquake.baselib.general import block_splitter from openquake.hazardlib.stats import compute_stats import numpy @@ -210,6 +211,18 @@ class ProbabilityMap(dict): pass return dic + def split(self, max_weight=10000): + """ + Split the probability map depending on the weight + """ + def weight(sid, w=self.shape_y * self.shape_z): + return w + for sids in block_splitter(self, max_weight, weight): + dic = self.__class__(self.shape_y, self.shape_z) + for sid in sids: + dic[sid] = self[sid] + yield dic + def extract(self, inner_idx): """ Extracts a component of the underlying ProbabilityCurves,
Added ProbabilityMap.split
py
diff --git a/tests/testmagics.py b/tests/testmagics.py index <HASH>..<HASH> 100644 --- a/tests/testmagics.py +++ b/tests/testmagics.py @@ -131,6 +131,7 @@ class TestCompositorMagic(ExtensionTestCase): assert len(Compositor.definitions) == 1, "Compositor definition not created" self.assertEqual(Compositor.definitions[0].value, 'RGBTEST') + self.assertEqual(Compositor.definitions[0].mode, 'display') def test_HCS_compositor_definition(self): @@ -140,10 +141,11 @@ class TestCompositorMagic(ExtensionTestCase): self.cell("overlay = H * C * S") - definition = " display toHCS(Matrix * Matrix * Matrix) HCSTEST" + definition = " data toHCS(Matrix * Matrix * Matrix) HCSTEST" self.line_magic('compositor', definition) assert len(Compositor.definitions) == 1, "Compositor definition not created" self.assertEqual(Compositor.definitions[0].value, 'HCSTEST') + self.assertEqual(Compositor.definitions[0].mode, 'data') if __name__ == "__main__":
Improved unit tests of %compositor line magic
py
diff --git a/payu/models/mom6.py b/payu/models/mom6.py index <HASH>..<HASH> 100644 --- a/payu/models/mom6.py +++ b/payu/models/mom6.py @@ -67,7 +67,10 @@ class Mom6(Fms): input_nml = f90nml.read(input_fpath) - input_type = 'n' if self.expt.counter == 0 else 'r' + if self.expt.counter == 0 or self.expt.repeat_run: + input_type = 'n' + else: + input_type = 'r' input_nml['MOM_input_nml']['input_filename'] = input_type f90nml.write(input_nml, input_fpath, force=True)
MOM6 repeat run support THis patch correctly patches the namelist for MOM6 repeat runs.
py
diff --git a/ajax/endpoints.py b/ajax/endpoints.py index <HASH>..<HASH> 100644 --- a/ajax/endpoints.py +++ b/ajax/endpoints.py @@ -37,7 +37,7 @@ class BaseEndpoint(object): data = self._encode_data([record])[0] for field, val in data.iteritems(): try: - f = self.model._meta.get_field(field) + f = record.__class__._meta.get_field(field) if isinstance(f, models.ForeignKey): try: row = f.rel.to.objects.get(pk=val)
Use the record's __class__ rather than self.model, which isn't set in BaseEndpoint.
py
diff --git a/odl/tomo/geometry/conebeam.py b/odl/tomo/geometry/conebeam.py index <HASH>..<HASH> 100644 --- a/odl/tomo/geometry/conebeam.py +++ b/odl/tomo/geometry/conebeam.py @@ -184,7 +184,6 @@ class ConeBeamGeometry(with_metaclass(ABCMeta, Geometry)): return cos_ang * id_mat + (1. - cos_ang) * dy_mat + sin_ang * cross_mat - def __repr__(self): """Return ``repr(self)``""" inner_fstr = '{!r}, {!r}, src_radius={}, det_radius={}' @@ -210,8 +209,8 @@ class ConeFlatGeometry(ConeBeamGeometry): detector positions. """ - def __init__(self, angle_intvl, dparams, src_radius, det_radius, agrid=None, - dgrid=None, axis=None): + def __init__(self, angle_intvl, dparams, src_radius, det_radius, + agrid=None, dgrid=None, axis=None): """Initialize a new instance. Parameters
MAINT: fix pep8 fails in conebeam
py
diff --git a/gen_markdown.py b/gen_markdown.py index <HASH>..<HASH> 100644 --- a/gen_markdown.py +++ b/gen_markdown.py @@ -38,7 +38,7 @@ Register Map for f in sorted(reg.field, key=lambda x: x.bitOffset): description = f.description if f.enumeratedValues: - description += "".join(["<br>{} = {}".format( + description += "".join(["<br/>{} = {}".format( e.value, e.name) for e in f.enumeratedValues.enumeratedValue]) if f.bitWidth == 1:
replace <br> by <br/>
py
diff --git a/angr/analyses/cfg/cfg_base.py b/angr/analyses/cfg/cfg_base.py index <HASH>..<HASH> 100644 --- a/angr/analyses/cfg/cfg_base.py +++ b/angr/analyses/cfg/cfg_base.py @@ -1663,9 +1663,10 @@ class CFGBase(Analysis): :return: True if it is a tail-call optimization. False otherwise. :rtype: bool """ - def _has_more_than_one_exit(node_): - return len(g.out_edges(node_)) > 1 + # Do not consider FakeRets as counting as multiple exits here. + out_edges = list(filter(lambda x: g.get_edge_data(*x)['jumpkind'] != 'Ijk_FakeRet', g.out_edges(node_))) + return len(out_edges) > 1 if len(all_edges) == 1 and dst_addr != src_addr: the_edge = next(iter(all_edges))
Don't consider FakeRets during tail call optimization detection (#<I>)
py
diff --git a/maintain/config.py b/maintain/config.py index <HASH>..<HASH> 100644 --- a/maintain/config.py +++ b/maintain/config.py @@ -54,7 +54,7 @@ class Configuration(object): def fromfile(cls, path): with open(path) as fp: content = fp.read() - content = yaml.load(content) + content = yaml.safe_load(content) cls.validate(content) return cls(**content)
fix: use yaml.safe_load
py
diff --git a/sharepoint/lists/types.py b/sharepoint/lists/types.py index <HASH>..<HASH> 100644 --- a/sharepoint/lists/types.py +++ b/sharepoint/lists/types.py @@ -1,4 +1,5 @@ import datetime +import warnings from lxml.builder import E @@ -52,7 +53,10 @@ class Field(object): values.append(value[start:pos].replace(';;', ';')) start = pos = pos + 2 else: - raise ValueError("Unexpected character after ';': {0}".format(value[pos+1])) + pos += 2 + warnings.warn("Upexpected character after ';': {0}".format(value[pos+1])) + #raise ValueError("Unexpected character after ';': {0}".format(value[pos+1])) + continue if self.group_multi is not None: values = [values[i:i+self.group_multi] for i in xrange(0, len(values), self.group_multi)]
Be a bit more forgiving of weird lists in fields
py
diff --git a/mapboxcli/scripts/uploads.py b/mapboxcli/scripts/uploads.py index <HASH>..<HASH> 100644 --- a/mapboxcli/scripts/uploads.py +++ b/mapboxcli/scripts/uploads.py @@ -43,7 +43,7 @@ def upload(ctx, args, name): infile = click.File("rb")(args[0]) except click.ClickException: raise click.UsageError( - "Could not open file: {} " + "Could not open file: {0} " "(check order of command arguments: INFILE TILESET)".format(args[0])) tileset = args[1]
appease python <I>
py
diff --git a/tests/runtests.py b/tests/runtests.py index <HASH>..<HASH> 100755 --- a/tests/runtests.py +++ b/tests/runtests.py @@ -135,7 +135,6 @@ class SaltTestsuiteParser(SaltCoverageTestingParser): self.start_coverage( branch=True, source=[os.path.join(SALT_ROOT, 'salt')], - track_processes=True ) def run_integration_suite(self, suite_folder, display_name):
`track_processes` is no longer a valid `kwarg'.
py
diff --git a/django_webpack/settings.py b/django_webpack/settings.py index <HASH>..<HASH> 100644 --- a/django_webpack/settings.py +++ b/django_webpack/settings.py @@ -35,7 +35,8 @@ DEBUG = setting_overrides.get( CACHE = setting_overrides.get( 'CACHE', - not settings.DEBUG, + not DEBUG, +) DEVTOOL = setting_overrides.get( 'DEVTOOL',
The default value for the `DJANGO_WEBPACK['CACHE']` setting is now toggled by `DJANGO_WEBPACK['DEBUG']`, rather than `django.conf.settings.DEBUG`.
py
diff --git a/simuvex/s_run.py b/simuvex/s_run.py index <HASH>..<HASH> 100644 --- a/simuvex/s_run.py +++ b/simuvex/s_run.py @@ -76,7 +76,7 @@ class SimRun(object): self.all_successors.append(state) # categorize the state - if o.APPROXIMATE_GUARDS and state.se.is_false(state.scratch.guard): + if o.APPROXIMATE_GUARDS in self.state.options and state.se.is_false(state.scratch.guard): self.unsat_successors.append(state) elif not state.scratch.guard.symbolic and state.se.is_false(state.scratch.guard): self.unsat_successors.append(state)
*actually* check for APPROXIMATE_GUARDS in the state
py
diff --git a/spacy/about.py b/spacy/about.py index <HASH>..<HASH> 100644 --- a/spacy/about.py +++ b/spacy/about.py @@ -4,7 +4,7 @@ # fmt: off __title__ = "spacy-nightly" -__version__ = "2.1.0a9.dev1" +__version__ = "2.1.0a9.dev2" __summary__ = "Industrial-strength Natural Language Processing (NLP) with Python and Cython" __uri__ = "https://spacy.io" __author__ = "Explosion AI"
Set version to <I>a9.dev2
py
diff --git a/tornado/gen.py b/tornado/gen.py index <HASH>..<HASH> 100644 --- a/tornado/gen.py +++ b/tornado/gen.py @@ -1215,7 +1215,9 @@ def convert_yielded(yielded): .. versionadded:: 4.1 """ # Lists and dicts containing YieldPoints were handled earlier. - if isinstance(yielded, (list, dict)): + if yielded is None: + return moment + elif isinstance(yielded, (list, dict)): return multi(yielded) elif is_future(yielded): return yielded
gen: handle None in convert_yielded
py
diff --git a/openquake/engine/calculators/risk/event_based_risk/core.py b/openquake/engine/calculators/risk/event_based_risk/core.py index <HASH>..<HASH> 100644 --- a/openquake/engine/calculators/risk/event_based_risk/core.py +++ b/openquake/engine/calculators/risk/event_based_risk/core.py @@ -86,7 +86,7 @@ def event_based(workflow, getter, outputdict, params, monitor): if specific_assets: loss_matrix, assets = _filter_loss_matrix_assets( out.output.loss_matrix, out.output.assets, specific_assets) - if assets: + if len(assets): # compute the loss per rupture per asset event_loss = models.EventLoss.objects.get( output__oq_job=monitor.job_id,
Fixed a bug found by Chris Schneider
py
diff --git a/peewee.py b/peewee.py index <HASH>..<HASH> 100644 --- a/peewee.py +++ b/peewee.py @@ -4540,8 +4540,8 @@ class SchemaManager(object): self.create_table(safe, **table_options) self.create_indexes(safe=safe) - def drop_all(self, safe=True): - self.drop_table(safe) + def drop_all(self, safe=True, **options): + self.drop_table(safe, **options) class Metadata(object): @@ -5242,11 +5242,11 @@ class Model(with_metaclass(ModelBase, Node)): cls._schema.create_all(safe, **options) @classmethod - def drop_table(cls, safe=True): + def drop_table(cls, safe=True, **options): if safe and not cls._meta.database.safe_drop_index \ and not cls.table_exists(): return - cls._schema.drop_all(safe) + cls._schema.drop_all(safe, **options) @classmethod def index(cls, *fields, **kwargs):
Fix signature to support cascade parameter. Fixes #<I>.
py
diff --git a/salt/modules/aptpkg.py b/salt/modules/aptpkg.py index <HASH>..<HASH> 100644 --- a/salt/modules/aptpkg.py +++ b/salt/modules/aptpkg.py @@ -704,7 +704,7 @@ def purge(name=None, pkgs=None, **kwargs): return _uninstall(action='purge', name=name, pkgs=pkgs, **kwargs) -def upgrade(refresh=True, dist_upgrade=True): +def upgrade(refresh=True, dist_upgrade=False): ''' Upgrades all packages via ``apt-get dist-upgrade`` @@ -715,7 +715,7 @@ def upgrade(refresh=True, dist_upgrade=True): dist_upgrade Whether to perform the upgrade using dist-upgrade vs upgrade. Default - is to use dist-upgrade. + is to use upgrade. .. versionadded:: 2014.7.0
aptpkg.upgrade should default to upgrade instead of dist_upgrade.
py