diff
stringlengths
139
3.65k
message
stringlengths
8
627
diff_languages
stringclasses
1 value
diff --git a/geomdl/abstract.py b/geomdl/abstract.py index <HASH>..<HASH> 100644 --- a/geomdl/abstract.py +++ b/geomdl/abstract.py @@ -797,10 +797,10 @@ class Curve(SplineGeometry): def reverse(self): """ Reverses the curve """ - self._control_points = reversed(self._control_points) + self._control_points = list(reversed(self._control_points)) max_k = self.knotvector[-1] new_kv = [max_k - k for k in self.knotvector] - self._knot_vector[0] = reversed(new_kv) + self._knot_vector[0] = list(reversed(new_kv)) def set_ctrlpts(self, ctrlpts, *args, **kwargs): """ Sets control points and checks if the data is consistent.
Fix a bug in curve reverse method
py
diff --git a/ELiDE/ELiDE/board/board.py b/ELiDE/ELiDE/board/board.py index <HASH>..<HASH> 100644 --- a/ELiDE/ELiDE/board/board.py +++ b/ELiDE/ELiDE/board/board.py @@ -582,9 +582,12 @@ class Board(RelativeLayout): else: patch['_image_paths'] = Spot.default_image_paths zeroes = [0] - patch['_offxs'] = place.get('_offxs', zeroes) - patch['_offys'] = place.get('_offys', zeroes) - nodes_patch[place_name] = patch + if '_offxs' not in place: + patch['_offxs'] = zeroes + if '_offys' not in place: + patch['_offys'] = zeroes + if patch: + nodes_patch[place_name] = patch if nodes_patch: self.character.node.patch(nodes_patch) for place in places2add:
Avoid needlessly patching nodes at ELiDE startup
py
diff --git a/test/test_client.py b/test/test_client.py index <HASH>..<HASH> 100644 --- a/test/test_client.py +++ b/test/test_client.py @@ -59,7 +59,9 @@ from test.utils import (assertRaisesExactly, one) -class TestClient(unittest.TestCase, TestRequestMixin): +class ClientUnitTest(unittest.TestCase, TestRequestMixin): + """MongoClient tests that don't require a server.""" + @classmethod def setUpClass(cls): cls.client = MongoClient(host, port, _connect=False)
Enable MongoClient unittests that were disabled by mistake.
py
diff --git a/holoviews/core/util.py b/holoviews/core/util.py index <HASH>..<HASH> 100644 --- a/holoviews/core/util.py +++ b/holoviews/core/util.py @@ -17,9 +17,9 @@ def find_minmax(lims, olims): def int_to_roman(input): if type(input) != type(1): - raise TypeError, "expected integer, got %s" % type(input) + raise TypeError("expected integer, got %s" % type(input)) if not 0 < input < 4000: - raise ValueError, "Argument must be between 1 and 3999" + raise ValueError("Argument must be between 1 and 3999") ints = (1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1) nums = ('M', 'CM', 'D', 'CD','C', 'XC','L','XL','X','IX','V','IV','I') result = ""
Fixed Py3 incompatibility in core/util.py
py
diff --git a/soco/core.py b/soco/core.py index <HASH>..<HASH> 100755 --- a/soco/core.py +++ b/soco/core.py @@ -878,7 +878,7 @@ class SoCo(object): def get_music_library_information(self, search_type, start=0, max_items=100): """ Retrieve information about the music library - + Arguments: search The kind of information to retrieve. Can be one of: 'folders', 'artists', 'album_artists', 'albums', 'genres', @@ -893,6 +893,11 @@ class SoCo(object): the search results. Raises SoCoException (or a subclass) upon errors. + + The information about the which searches can be performed and the form + of the query has been gathered from the Janos project: + http://sourceforge.net/projects/janos/ Probs to the authors of that + project. """ search_translation = {'folders': 'A:', 'artists': 'A:ARTIST', 'album_artists': 'A:ALBUMARTIST',
Added credit for the information on the searches to the Janos project
py
diff --git a/setup.py b/setup.py index <HASH>..<HASH> 100755 --- a/setup.py +++ b/setup.py @@ -10,7 +10,7 @@ def unique_flatten_dict(d): core_requires = ['numpy', 'pandas >= 0.17.0', 'pyarrow >= 0.15.0', 'requests', 'protobuf >= 2.6.0'] stubs = [ - 'pandas-stubs' + 'pandas-stubs', 'types-requests' ] dev_extras = {
fix(mypi): add missing requests type stub
py
diff --git a/setup.py b/setup.py index <HASH>..<HASH> 100644 --- a/setup.py +++ b/setup.py @@ -31,9 +31,9 @@ setup(name = "pychal", 'Programming Language :: Python :: 3.6' ], install_requires = [ - 'iso8601', - 'tzlocal', - 'pytz', - 'requests', + 'iso8601==0.1.12', + 'tzlocal==2.0.0', + 'pytz==2019.3', + 'requests==2.23.0', ], )
pin the dependencies in setup.py
py
diff --git a/salt/utils/templates.py b/salt/utils/templates.py index <HASH>..<HASH> 100644 --- a/salt/utils/templates.py +++ b/salt/utils/templates.py @@ -13,7 +13,6 @@ import logging import tempfile import traceback import sys -import collections # Import third party libs import jinja2 @@ -27,6 +26,7 @@ from salt.exceptions import ( from salt.utils.jinja import ensure_sequence_filter from salt.utils.jinja import SaltCacheLoader as JinjaSaltCacheLoader from salt.utils.jinja import SerializerExtension as JinjaSerializerExtension +from salt.utils.odict import OrderedDict from salt import __path__ as saltpath from salt._compat import string_types @@ -253,7 +253,7 @@ def render_jinja_tmpl(tmplstr, context, tmplpath=None): jinja_env.filters['strftime'] = salt.utils.date_format jinja_env.filters['sequence'] = ensure_sequence_filter - jinja_env.globals['OrderedDict'] = collections.OrderedDict + jinja_env.globals['odict'] = OrderedDict unicode_context = {} for key, value in context.iteritems():
Changed OrderedDict provider to salt.utils.odict for backwards compat with py<I>
py
diff --git a/tensorboard/backend/http_util.py b/tensorboard/backend/http_util.py index <HASH>..<HASH> 100644 --- a/tensorboard/backend/http_util.py +++ b/tensorboard/backend/http_util.py @@ -147,6 +147,7 @@ def Respond(request, headers = [] headers.append(('Content-Length', str(content_length))) + headers.append(('X-Content-Type-Options', 'nosniff')) if content_encoding: headers.append(('Content-Encoding', content_encoding)) if expires > 0:
core: add x-content-type-options: nosniff (#<I>) This prevents browsers from guessing correct mimetype and make it follow the content-type given by the server. There was no functional regression from the change.
py
diff --git a/backtrader/cerebro.py b/backtrader/cerebro.py index <HASH>..<HASH> 100644 --- a/backtrader/cerebro.py +++ b/backtrader/cerebro.py @@ -63,6 +63,7 @@ class Cerebro(six.with_metaclass(MetaParams, object)): ('maxcpus', None), ('stdstats', True), ('lookahead', 0), + ('jit', False), ) def __init__(self): @@ -258,6 +259,10 @@ class Cerebro(six.with_metaclass(MetaParams, object)): if key in pkeys: setattr(self.params, key, val) + if self.p.jit: + self.p.runonce = False + self.p.preload = False + self.runstrats = list() iterstrats = itertools.product(*self.strats) if not self._dooptimize or self.p.maxcpus == 1: @@ -347,8 +352,9 @@ class Cerebro(six.with_metaclass(MetaParams, object)): Actual implementation of run in full next mode. All objects have its ``next`` method invoke on each data arrival ''' - for strat in runstrats: - strat.ringbuffer() + if self.p.jit: + for strat in runstrats: + strat.ringbuffer() data0 = self.datas[0] while data0.next():
Initial support in Cerebro for the "jit" mode to only use the minimum number of needed bars.
py
diff --git a/discord/ui/view.py b/discord/ui/view.py index <HASH>..<HASH> 100644 --- a/discord/ui/view.py +++ b/discord/ui/view.py @@ -118,6 +118,7 @@ class View: self.id = os.urandom(16).hex() self._cancel_callback: Optional[Callable[[View], None]] = None + self._stopped = asyncio.Event() def to_components(self) -> List[Dict[str, Any]]: def key(item: Item) -> int: @@ -212,9 +213,17 @@ class View: This operation cannot be undone. """ + self._stopped.set() if self._cancel_callback: self._cancel_callback(self) + async def wait(self) -> None: + """Waits until the view has finished interacting. + + A view is considered finished when :meth:`stop` is called. + """ + await self._stopped.wait() + class ViewStore: def __init__(self, state):
Add a way to wait for a view to finish its interactions
py
diff --git a/openshift/dynamic/client.py b/openshift/dynamic/client.py index <HASH>..<HASH> 100644 --- a/openshift/dynamic/client.py +++ b/openshift/dynamic/client.py @@ -179,11 +179,12 @@ class DynamicClient(object): def apply(self, resource, body=None, name=None, namespace=None): body = self.serialize_body(body) - name = name or body.get('metadata', {}).get('name') + body['metadata'] = body.get('metadata', dict()) + name = name or body['metadata'].get('name') if not name: raise ValueError("name is required to apply {}.{}".format(resource.group_version, resource.kind)) if resource.namespaced: - namespace = self.ensure_namespace(resource, namespace, body) + body['metadata']['namespace'] = self.ensure_namespace(resource, namespace, body) return apply(resource, body) def watch(self, resource, namespace=None, name=None, label_selector=None, field_selector=None, resource_version=None, timeout=None):
Ensure that namespace and name parameters are used for apply (#<I>) resource definitions that are accompanied separately by names and namespaces should be updated and the name and namespace used Fixes #<I>
py
diff --git a/indra/assemblers/pysb/sites.py b/indra/assemblers/pysb/sites.py index <HASH>..<HASH> 100644 --- a/indra/assemblers/pysb/sites.py +++ b/indra/assemblers/pysb/sites.py @@ -68,7 +68,11 @@ def get_binding_site_name(agent): """Return a binding site name from a given agent.""" # Try to construct a binding site name based on parent grounding = agent.get_grounding() - if grounding != (None, None): + # We don't want to accidentally deal with very deep ontological + # cases here such as CHEBI (e.g., GTP) which requires thousands + # of lookups to resolve + if grounding != (None, None) and grounding[0] in {'HGNC', 'FPLX'}: + print('Getting parents for %s' % str(grounding)) top_parents = bio_ontology.get_top_level_parents(*grounding) if top_parents: parent_name = bio_ontology.get_name(*top_parents[0])
Avoid looking up parents for CHEBI terms
py
diff --git a/discord/abc.py b/discord/abc.py index <HASH>..<HASH> 100644 --- a/discord/abc.py +++ b/discord/abc.py @@ -440,7 +440,7 @@ class GuildChannel: .. versionadded:: 1.3 """ category = self.guild.get_channel(self.category_id) - return bool(category and category._overwrites == self._overwrites) + return bool(category and category.overwrites == self.overwrites) def permissions_for(self, member): """Handles permission resolution for the current :class:`~discord.Member`.
Fix comparison for overwrites when checking if a channel is synced
py
diff --git a/tests/tests.py b/tests/tests.py index <HASH>..<HASH> 100755 --- a/tests/tests.py +++ b/tests/tests.py @@ -24,6 +24,10 @@ logging.basicConfig(level=logging.DEBUG,format="[%(asctime)s %(levelname)s] [%(n logging.getLogger('Test-mYQL') +logging.getLogger('mYQL').disabled = True +logging.getLogger('yahoo_oauth').disabled = True +logging.getLogger('requests').disabled = True + def json_write_data(json_data, filename): with open(filename, 'w') as fp: json.dump(json_data, fp, indent=4, sort_keys=True, ensure_ascii=False)
yahoo_oauth and requests logger disabled
py
diff --git a/openquake/engine/engine.py b/openquake/engine/engine.py index <HASH>..<HASH> 100644 --- a/openquake/engine/engine.py +++ b/openquake/engine/engine.py @@ -335,8 +335,9 @@ def run_calc(job_id, oqparam, exports, hazard_calculation_id=None, **kw): return try: if OQ_DISTRIBUTE.endswith('pool'): + # Report the number of "visible" cores, not the total system cores logs.LOG.warning('Using %d cores on %s', - parallel.Starmap.num_cores, platform.node()) + len(os.sched_getaffinity(0)), platform.node()) if OQ_DISTRIBUTE == 'zmq' and config.zworkers['host_cores']: logs.dbcmd('zmq_start') # start the zworkers logs.dbcmd('zmq_wait') # wait for them to go up
Report the number of visible cores, not total system cores In a cgroups limited environment, like a SLURM cluster, the number of processors available is different from the number of procs available in the whole system.
py
diff --git a/sigal/__init__.py b/sigal/__init__.py index <HASH>..<HASH> 100644 --- a/sigal/__init__.py +++ b/sigal/__init__.py @@ -117,11 +117,14 @@ def build(source, destination, debug, verbose, force, config, theme, title, logger.error("Input directory not found: %s", settings['source']) sys.exit(1) + # on windows os.path.relpath raises a ValueError if the two paths are on + # different drives, in that case we just ignore the exception as the two + # paths are anyway not relative relative_check = True try: relative_check = os.path.relpath(settings['destination'], settings['source']).startswith('..') - except: + except ValueError: pass if not relative_check:
Windows fix added comments and specified the concrete exception (ValueError)
py
diff --git a/src/toil/job.py b/src/toil/job.py index <HASH>..<HASH> 100644 --- a/src/toil/job.py +++ b/src/toil/job.py @@ -1642,6 +1642,8 @@ class Promise(object): """ Caches the job store instance used during unpickling to prevent it from being instantiated for each promise + + :type: toil.jobStores.abstractJobStore.AbstractJobStore """ filesToDelete = set() @@ -1682,7 +1684,9 @@ class Promise(object): @classmethod def _resolve(cls, jobStoreString, jobStoreFileID): - if cls._jobstore is None: + # Initialize the cached job store if it was never initialized in the current process or + # if it belongs to a different workflow that was run earlier in the current process. + if cls._jobstore is None or cls._jobstore.config.jobStore != jobStoreString: cls._jobstore = Toil.loadOrCreateJobStore(jobStoreString) cls.filesToDelete.add(jobStoreFileID) with cls._jobstore.readFileStream(jobStoreFileID) as fileHandle:
Avoid reusing a cached promise job store from a different workflow (resolves #<I>)
py
diff --git a/vtki/utilities.py b/vtki/utilities.py index <HASH>..<HASH> 100755 --- a/vtki/utilities.py +++ b/vtki/utilities.py @@ -267,7 +267,7 @@ def numpy_to_texture(image): if image.ndim != 3 or image.shape[2] != 3: raise AssertionError('Input image must be nn by nm by RGB') grid = vtki.UniformGrid((image.shape[1], image.shape[0], 1)) - grid.point_arrays['Image'] = image.swapaxes(0,1).reshape((-1, 3), order='F') + grid.point_arrays['Image'] = np.flip(image.swapaxes(0,1), axis=1).reshape((-1, 3), order='F') grid.set_active_scalar('Image') vtex = vtk.vtkTexture() vtex.SetInputDataObject(grid)
Fix numpy to texture converter to be consistent with VTK image readers
py
diff --git a/pylint/test/functional/namedtuple_member_inference.py b/pylint/test/functional/namedtuple_member_inference.py index <HASH>..<HASH> 100644 --- a/pylint/test/functional/namedtuple_member_inference.py +++ b/pylint/test/functional/namedtuple_member_inference.py @@ -19,5 +19,4 @@ def test(): print(fan.foo) # Should not raise protected-access. fan2 = fan._replace(foo=2) - # This is a bug. - print(fan2.foo) # [no-member] + print(fan2.foo)
We understand namedtuple._replace properly (in a static analysis sense of course), so remove wrong assumption.
py
diff --git a/pyinfra_cli/main.py b/pyinfra_cli/main.py index <HASH>..<HASH> 100644 --- a/pyinfra_cli/main.py +++ b/pyinfra_cli/main.py @@ -205,13 +205,17 @@ def cli(*args, **kwargs): pyinfra INVENTORY server.user pyinfra home=/home/pyinfra \b - # Execute an arbitrary command on the inventory + # Execute an arbitrary command against the inventory pyinfra INVENTORY exec -- echo "hello world" \b - # Run one or more facts on the inventory + # Run one or more facts against the inventory pyinfra INVENTORY fact server.LinuxName [server.Users]... pyinfra INVENTORY fact files.File path=/path/to/file... + + \b + # Debug the inventory hosts and data + pyinfra INVENTORY debug-inventory ''' try:
Add debug-inventory example to the help doc.
py
diff --git a/caravel/config.py b/caravel/config.py index <HASH>..<HASH> 100644 --- a/caravel/config.py +++ b/caravel/config.py @@ -213,7 +213,7 @@ WARNING_MSG = None # Example: class CeleryConfig(object): BROKER_URL = 'sqla+sqlite:///celerydb.sqlite' - CELERY_IMPORTS = ('caravel.tasks', ) + CELERY_IMPORTS = ('caravel.sql_lab', ) CELERY_RESULT_BACKEND = 'db+sqlite:///celery_results.sqlite' CELERY_ANNOTATIONS = {'tasks.add': {'rate_limit': '10/s'}} CELERY_CONFIG = CeleryConfig
Fix celery module import in comments. (#<I>)
py
diff --git a/killer.py b/killer.py index <HASH>..<HASH> 100644 --- a/killer.py +++ b/killer.py @@ -29,7 +29,7 @@ or the disk tray is tampered with, shut the computer down! # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <https://www.gnu.org/licenses/agpl.html>. -__version__ = "0.3.1" +__version__ = "0.3.2" __author__ = "Lvl4Sword" import argparse @@ -303,8 +303,8 @@ class Killer(object): conn.esmtp_features['auth'] = login_auth conn.login(sender, sender_password) try: - for each in destination: - conn.sendmail(sender, each, msg.as_string()) + for each in self.config['email']['DESTINATION'].split(','): + conn.sendmail(sender, each.strip(), msg.as_string()) finally: conn.quit() @@ -320,7 +320,7 @@ if __name__ == "__main__": execute.detect_power() elif sys.platform.startswith("linux"): execute.detect_bt() -# execute.detect_ac() + execute.detect_ac() execute.detect_battery() execute.detect_tray(execute.config['linux']['CDROM_DRIVE']) execute.detect_usb()
<I> - smtplib.SMTPRecipientsRefused fixed - execute.detect_ac() is actually running now. Should learn to get rid of comments when I'm done testing..
py
diff --git a/smtplibaio.py b/smtplibaio.py index <HASH>..<HASH> 100644 --- a/smtplibaio.py +++ b/smtplibaio.py @@ -417,8 +417,10 @@ class SMTP: future.set_result(True) self._loop.add_reader(self.file, callback) - yield from future - self._loop.remove_reader(self.file) + try: + yield from future + finally: + self._loop.remove_reader(self.file) while 1: try:
Also remove_reader() when the future throws.
py
diff --git a/openpnm/io/PerGeos.py b/openpnm/io/PerGeos.py index <HASH>..<HASH> 100644 --- a/openpnm/io/PerGeos.py +++ b/openpnm/io/PerGeos.py @@ -1,6 +1,5 @@ import numpy import numpy as np -import scipy as sp from openpnm.utils import logging from openpnm.io import GenericIO from openpnm.network import GenericNetwork @@ -9,6 +8,8 @@ logger = logging.getLogger(__name__) class PerGeos(GenericIO): r""" + PerGeos is the format used by the Avizo software. See `here for more + details <https://cases.pergeos.com/>`_. """ @classmethod
Adding a bit of text to pergeos docstring [ci min]
py
diff --git a/xapian_backend.py b/xapian_backend.py index <HASH>..<HASH> 100644 --- a/xapian_backend.py +++ b/xapian_backend.py @@ -320,9 +320,6 @@ class SearchBackend(BaseSearchBackend): 'hits': 0, } - if query_facets is not None: - warnings.warn("Query faceting has not been implemented yet.", Warning, stacklevel=2) - database = self._database() query, spelling_suggestion = self._query( database, query_string, narrow_queries, spelling_query, boost
Removed outdated warning regarding query facets
py
diff --git a/openquake/calculators/export/__init__.py b/openquake/calculators/export/__init__.py index <HASH>..<HASH> 100644 --- a/openquake/calculators/export/__init__.py +++ b/openquake/calculators/export/__init__.py @@ -15,7 +15,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.general import import_all, CallableDict +from openquake.baselib.general import CallableDict from openquake.commonlib.writers import write_csv @@ -63,8 +63,6 @@ export = CallableDict(keyfunc) export.from_db = False # overridden when exporting from db -import_all('openquake.calculators.export') - @export.add(('input_zip', 'zip')) def export_input_zip(ekey, dstore):
Try to override a race condition during imports [demos] Former-commit-id: 8e<I>fa2f<I>d<I>b7be<I>af<I>dbb<I>dd<I>
py
diff --git a/runtests.py b/runtests.py index <HASH>..<HASH> 100644 --- a/runtests.py +++ b/runtests.py @@ -3,6 +3,7 @@ import sys TESTS_ROOT = os.path.abspath(os.path.dirname(os.path.dirname(__file__))) +import django from django.conf import settings settings.configure( @@ -44,6 +45,12 @@ settings.configure( ] ) +# Avoid AppRegistryNotReady exception +# http://stackoverflow.com/questions/24793351/django-appregistrynotready +if hasattr(django, "setup"): + django.setup() + + from django_nose import NoseTestSuiteRunner test_runner = NoseTestSuiteRunner(verbosity=1)
Manually call django.setup() to populate apps registry.
py
diff --git a/src/wormhole/test/test_cli.py b/src/wormhole/test/test_cli.py index <HASH>..<HASH> 100644 --- a/src/wormhole/test/test_cli.py +++ b/src/wormhole/test/test_cli.py @@ -1172,6 +1172,14 @@ class Dispatch(unittest.TestCase): self.assertEqual(cfg.stderr.getvalue(), expected) +class FakeConfig(object): + no_daemon = True + blur_usage = True + advertise_version = u"fake.version.1" + transit = str('tcp:4321') + rendezvous = str('tcp:1234') + signal_error = True + allow_list = False class Server(unittest.TestCase): def setUp(self): @@ -1183,15 +1191,6 @@ class Server(unittest.TestCase): self.assertEqual(0, result.exit_code) def test_server_plugin(self): - class FakeConfig(object): - no_daemon = True - blur_usage = True - advertise_version = u"fake.version.1" - transit = str('tcp:4321') - rendezvous = str('tcp:1234') - signal_error = True - allow_list = False - cfg = FakeConfig() plugin = MyPlugin(cfg) relay = plugin.makeService(None)
Let me use FakeConfig in another test method
py
diff --git a/src/sunhead/serializers/json.py b/src/sunhead/serializers/json.py index <HASH>..<HASH> 100644 --- a/src/sunhead/serializers/json.py +++ b/src/sunhead/serializers/json.py @@ -32,6 +32,9 @@ def json_serial(obj): elif isinstance(obj, timedelta): serial = str(obj) + elif isinstance(obj, set): + serial = list(x for x in obj) + elif isinstance(obj, uuid.UUID): serial = str(obj)
Added set to JSON serializer
py
diff --git a/dimod/binary_quadratic_model.py b/dimod/binary_quadratic_model.py index <HASH>..<HASH> 100644 --- a/dimod/binary_quadratic_model.py +++ b/dimod/binary_quadratic_model.py @@ -1661,7 +1661,7 @@ class BinaryQuadraticModel(Sized, Container, Iterable): Args: obj: bytes: Byte string that represents linear and quadratic biases using - the encoding used in `.to_bson`. + the encoding used in :meth: `.to_bson`. Returns: :class:`.BinaryQuadraticModel`: The corresponding binary quadratic model. @@ -1676,7 +1676,7 @@ class BinaryQuadraticModel(Sized, Container, Iterable): num_variables = len(lin) vals = np.frombuffer(doc["quadratic_vals"], dtype=np.float32) if doc["as_complete"]: - i, j = list(zip(*itertools.combinations(range(num_variables), 2))) + i, j = zip(*itertools.combinations(range(num_variables), 2)) else: i = np.frombuffer(doc["quadratic_head"], dtype=np.uint16) j = np.frombuffer(doc["quadratic_tail"], dtype=np.uint16)
Add :meth: link in from_bson doc and remove superfluous `list` call
py
diff --git a/tests/conftest.py b/tests/conftest.py index <HASH>..<HASH> 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -453,8 +453,7 @@ def invalid_epub_file(): @pytest.fixture def html_file(): - source_url = "https://web.archive.org/web/20191122220303/" \ - "https://studio.learningequality.org/content/storage/" \ + source_url = "https://studio.learningequality.org/content/storage/" \ "e/d/ed494d6547b603b8ff22095cf5f5b624.zip" local_path = os.path.join("tests", "testcontent", "downloaded", "testhtml.zip") download_fixture_file(source_url, local_path)
Fix test: Do not use archive.org to fetch test zip data
py
diff --git a/revolver/contextmanager.py b/revolver/contextmanager.py index <HASH>..<HASH> 100644 --- a/revolver/contextmanager.py +++ b/revolver/contextmanager.py @@ -29,3 +29,20 @@ def sudo(username=None, login=False): env.sudo_forced = old_forced env.sudo_user = old_user env.shell = old_shell + + +@contextmanager +def unpatched_state(): + old_shell = env.shell + old_sudo_forced = env.sudo_forced + old_sudo_user = env.sudo_user + + env.shell = "/bin/bash -l -c" + env.sudo_forced = False + env.sudo_user = None + + yield + + env.shell = old_shell + env.sudo_forced = old_sudo_forced + env.sudo_user = old_sudo_user
New context unpatched_state added
py
diff --git a/test/test_ad2.py b/test/test_ad2.py index <HASH>..<HASH> 100644 --- a/test/test_ad2.py +++ b/test/test_ad2.py @@ -43,7 +43,7 @@ class TestAlarmDecoder(TestCase): self._device.on_read = EventHandler(Event(), self._device) self._device.on_write = EventHandler(Event(), self._device) - self._decoder = AlarmDecoder(self._device) + self._decoder = AlarmDecoder(self._device, ignore_lrr_states=False) self._decoder.on_panic += self.on_panic self._decoder.on_relay_changed += self.on_relay_changed self._decoder.on_power_changed += self.on_power_changed @@ -305,7 +305,7 @@ class TestAlarmDecoder(TestCase): def test_fire_alarm_event(self): msg = self._decoder._handle_message(b'[0000000000000000----],000,[f707000600e5800c0c020000]," "') - self.assertTrue(self._fire) # Not set the first time we hit it. + self.assertFalse(self._fire) # Not set the first time we hit it. msg = self._decoder._handle_message(b'[0000000000000100----],000,[f707000600e5800c0c020000]," "') self.assertTrue(self._fire)
ok need to test locally.. how?
py
diff --git a/rtcclient/template.py b/rtcclient/template.py index <HASH>..<HASH> 100644 --- a/rtcclient/template.py +++ b/rtcclient/template.py @@ -361,7 +361,8 @@ class Templater(RTCBase): match_str_list = ["rtc_cm:com.ibm.", "calm:"] - for key in list(wk_raw_data.keys()): + keys = list(wk_raw_data.keys()) + for key in keys: for match_str in match_str_list: if key.startswith(match_str): try:
fix #<I>: OrderedDict mutated during iteration
py
diff --git a/doctr/tests/test_local.py b/doctr/tests/test_local.py index <HASH>..<HASH> 100644 --- a/doctr/tests/test_local.py +++ b/doctr/tests/test_local.py @@ -67,7 +67,7 @@ def test_GIT_URL(): def test_guess_github_repo(): """ Only works if run in this repo, and if cloned from origin. For safety, - only run on Travis + only run on Travis and not run on fork builds. """ - if on_travis(): + if on_travis() and os.environ.get('TRAVIS_SECURE_ENV_VARS', 'false') == 'true': assert guess_github_repo() == 'drdoctr/doctr'
Don't run test_guess_github_repo() on fork builds
py
diff --git a/bcbio/variation/recalibrate.py b/bcbio/variation/recalibrate.py index <HASH>..<HASH> 100644 --- a/bcbio/variation/recalibrate.py +++ b/bcbio/variation/recalibrate.py @@ -39,6 +39,7 @@ def prep_recal(data): def apply_recal(data): """Apply recalibration tables to the sorted aligned BAM, producing recalibrated BAM. """ + orig_bam = dd.get_work_bam(data) if dd.get_recalibrate(data) in [True, "gatk"]: logger.info("Applying BQSR recalibration with GATK: %s " % str(dd.get_sample_name(data))) data["work_bam"] = _gatk_apply_bqsr(data) @@ -47,6 +48,8 @@ def apply_recal(data): data["work_bam"] = sentieon.apply_bqsr(data) elif dd.get_recalibrate(data): raise NotImplementedError("Unsupported recalibration type: %s" % (dd.get_recalibrate(data))) + if orig_bam != dd.get_work_bam(data) and orig_bam != dd.get_align_bam(data): + utils.save_diskspace(orig_bam, "BAM recalibrated to %s" % dd.get_work_bam(data), data["config"]) return data def _get_ref_twobit(data):
BQSR: add save diskspace stub for recal BAMs
py
diff --git a/setup.py b/setup.py index <HASH>..<HASH> 100644 --- a/setup.py +++ b/setup.py @@ -9,7 +9,7 @@ NEWS = open(os.path.join(here, 'NEWS.txt')).read() version = '0.1.0' install_requires = [ - "neo4jrestclient>=2.1.1", + 'neo4jrestclient>=2.1.0', 'prettytable', 'ipython>=1.0', ]
Downgrading neo4jrestclient dependency
py
diff --git a/billy/web/admin/urls.py b/billy/web/admin/urls.py index <HASH>..<HASH> 100644 --- a/billy/web/admin/urls.py +++ b/billy/web/admin/urls.py @@ -11,7 +11,7 @@ urlpatterns = patterns('billy.web.admin.views', name='admin_legislators'), url(r'^(?P<abbr>[a-z]{2})/committees/$', 'committees', name='admin_committees'), - url(r'^/delete_committees/$', 'delete_committees', + url(r'^delete_committees/$', 'delete_committees', name='delete_committees'), url(r'^legislators/(?P<id>\w+)/$', 'legislator', name='legislator'), url(r'^legislators/(?P<id>\w+)/retire/$', 'retire_legislator',
fix delete_committees url
py
diff --git a/accounts/views.py b/accounts/views.py index <HASH>..<HASH> 100644 --- a/accounts/views.py +++ b/accounts/views.py @@ -23,8 +23,7 @@ class Login(TemplateView): def get(self, request, *args, **kwargs): if request.user.is_authenticated(): - #return HttpResponseRedirect(reverse('index')) - pass + return HttpResponseRedirect(reverse('index')) context = self.get_context_data(**kwargs) return self.render_to_response(context)
Put index redirect back into the login view if user is logged in.
py
diff --git a/python/ray/rllib/agent.py b/python/ray/rllib/agent.py index <HASH>..<HASH> 100644 --- a/python/ray/rllib/agent.py +++ b/python/ray/rllib/agent.py @@ -56,6 +56,7 @@ class Agent(object): agent_id (str): Optional unique identifier for this agent, used to determine where to store results in the local dir. """ + self._initialize_ok = False self._experiment_id = uuid.uuid4().hex if type(env_creator) is str: import gym @@ -115,6 +116,8 @@ class Agent(object): with tf.Graph().as_default(): self._init() + self._initialize_ok = True + def _init(self, config, env_creator): """Subclasses should override this for custom initialization.""" @@ -127,6 +130,10 @@ class Agent(object): A TrainingResult that describes training progress. """ + if not self._initialize_ok: + raise ValueError( + "Agent initialization failed, see previous errors") + start = time.time() result = self._train() self._iteration += 1
warn if agent failed (#<I>)
py
diff --git a/pyicloud/base.py b/pyicloud/base.py index <HASH>..<HASH> 100644 --- a/pyicloud/base.py +++ b/pyicloud/base.py @@ -1,9 +1,11 @@ import uuid import hashlib import json +import logging +import pickle import requests import sys -import pickle +import tempfile import os from re import match @@ -16,6 +18,9 @@ from pyicloud.services import ( ) +logger = logging.getLogger(__name__) + + class PyiCloudService(object): """ A base authentication class for the iCloud service. Handles the @@ -40,7 +45,10 @@ class PyiCloudService(object): self._base_system_url = '%s/system/version.json' % self._home_endpoint self._base_webauth_url = '%s/refreshWebAuth' % self._push_endpoint - self._cookie_directory = 'cookies' + self._cookie_directory = os.path.join( + tempfile.gettempdir(), + 'pyicloud', + ) self.session = requests.Session() self.session.verify = False
Cleaning up cookie handling to use a system-level temporary directory. Adding logger.
py
diff --git a/mixbox/typedlist.py b/mixbox/typedlist.py index <HASH>..<HASH> 100644 --- a/mixbox/typedlist.py +++ b/mixbox/typedlist.py @@ -69,6 +69,9 @@ class TypedList(collections.MutableSequence): ) six.reraise(TypeError, TypeError(error), sys.exc_info()[-1]) + def _is_type_castable(self): + return getattr(self._type, "_try_cast", False) + def __nonzero__(self): return bool(self._inner) @@ -98,9 +101,14 @@ class TypedList(collections.MutableSequence): def insert(self, idx, value): if value is None and self._ignore_none: return - elif not self._is_valid(value): + elif self._is_valid(value): + self._inner.insert(idx, value) + elif self._is_type_castable(): value = self._fix_value(value) - self._inner.insert(idx, value) + self._inner.insert(idx, value) + else: + err = "Cannot insert type (%s) into %s" % (type(value), type(self)) + raise TypeError(err) def __repr__(self): return self._inner.__repr__()
Added _is_type_castable() method to TypedList. This makes input validation the same between TypedField and TypedList.
py
diff --git a/pythran/dist.py b/pythran/dist.py index <HASH>..<HASH> 100644 --- a/pythran/dist.py +++ b/pythran/dist.py @@ -147,7 +147,7 @@ class PythranExtension(Extension): output_file = base + '.cpp' # target name if os.path.exists(source) and (not os.path.exists(output_file) - or os.stat(output_file) < os.stat(source)): + or os.path.getmtime(output_file) < os.path.getmtime(source)): # get the last name in the path if '.' in self.name: module_name = os.path.splitext(self.name)[-1][1:]
Fix time comparison for cpp file creation
py
diff --git a/glue/ligolw/lsctables.py b/glue/ligolw/lsctables.py index <HASH>..<HASH> 100644 --- a/glue/ligolw/lsctables.py +++ b/glue/ligolw/lsctables.py @@ -741,6 +741,21 @@ class SnglInspiralTable(table.Table): keep.append(row) return keep + def vetoed(self, seglist): + """ + Return the inverse of what veto returns, i.e., return the triggers + that lie within a given seglist. + """ + vetoed = table.new_from_template(self) + keep = table.new_from_template(self) + for row in self: + time = row.get_end() + if time in seglist: + vetoed.append(row) + else: + keep.append(row) + return vetoed + def getslide(self,slide_num): """ Return the triggers with a specific slide number.
Added vetoed() method to SnglInspiralTable, which is the complement of veto()
py
diff --git a/lib/creds/constants.py b/lib/creds/constants.py index <HASH>..<HASH> 100644 --- a/lib/creds/constants.py +++ b/lib/creds/constants.py @@ -28,15 +28,14 @@ def login_defs(): line = str(line) if PY2: line = line.encode(text_type('utf8')) - if line[:6] == text_type('UID_MIN'): + if line[:7] == text_type('UID_MIN'): uid_min = int(line.split()[1].strip()) - if line[:6] == text_type('UID_MAX'): + if line[:7] == text_type('UID_MAX'): uid_max = int(line.split()[1].strip()) if not uid_min: uid_min = DEFAULT_UID_MIN if not uid_max: uid_max = DEFAULT_UID_MAX - print(uid_min, uid_max) return uid_min, uid_max
fix max uid and gid checks.
py
diff --git a/billy/importers/events.py b/billy/importers/events.py index <HASH>..<HASH> 100644 --- a/billy/importers/events.py +++ b/billy/importers/events.py @@ -63,9 +63,26 @@ def import_events(abbr, data_dir, import_actions=False): bill_id = bill['bill_id'] bill_id = fix_bill_id(bill_id) bill['bill_id'] = "" - db_bill = db.bills.find_one({"state": abbr, - 'session': data['session'], - 'bill_id': bill_id}) + db_bill = db.bills.find_one({ + "$or": [ + { + "state": abbr, + 'session': data['session'], + 'bill_id': bill_id + }, + { + "state": abbr, + 'session': data['session'], + 'alternate_bill_ids': bill_id + } + ] + }) + + if not db_bill: + logger.warning("Error: Can't find %s" % bill_id) + db_bill = {} + db_bill['_id'] = None + # Events are really hard to pin to a chamber. Some of these are # also a committee considering a bill from the other chamber, or # something like that.
adding in a bit of logic for matching bills
py
diff --git a/src/feat/agencies/net/agency.py b/src/feat/agencies/net/agency.py index <HASH>..<HASH> 100644 --- a/src/feat/agencies/net/agency.py +++ b/src/feat/agencies/net/agency.py @@ -280,8 +280,6 @@ class Agency(agency.Agency): if hasattr(options, attr): new_value = getattr(options, attr) old_value = conf_group[conf_key] - if old_value is not None: - continue if new_value is not None and (old_value != new_value): if old_value is None: self.log("Setting %s.%s to %r",
Bring the options parsing logic back to its original form.
py
diff --git a/limbo/plugins/urban.py b/limbo/plugins/urban.py index <HASH>..<HASH> 100644 --- a/limbo/plugins/urban.py +++ b/limbo/plugins/urban.py @@ -1,3 +1,4 @@ +# -*- coding: UTF-8 -*- """!urban <term> returns the urban dictionary definition and example of a term""" import requests import re @@ -15,7 +16,7 @@ def reply_quote(string): def urban(term): # slack likes to replace the quote character with a smart quote. # Undo that. - term = term.replace(u'’', "'") + term = term.replace(u'’', "'").encode("utf8") baseurl = u"http://api.urbandictionary.com/v0/define?term={0}" data = requests.get(baseurl.format(quote(term))).json()
re-fix unicode in urban plugin
py
diff --git a/source/rafcon/statemachine/storage/storage.py b/source/rafcon/statemachine/storage/storage.py index <HASH>..<HASH> 100644 --- a/source/rafcon/statemachine/storage/storage.py +++ b/source/rafcon/statemachine/storage/storage.py @@ -14,8 +14,6 @@ import glob import copy import yaml -from gtkmvc import Observable - from rafcon.statemachine.state_machine import StateMachine from rafcon.statemachine.custom_exceptions import LibraryNotFoundException @@ -37,7 +35,7 @@ if os.path.exists(DEFAULT_SCRIPT_PATH): shutil.rmtree(f) -class StateMachineStorage(Observable): +class StateMachineStorage(): """This class implements the Storage interface by using a file system on the disk. @@ -58,8 +56,6 @@ class StateMachineStorage(Observable): STATEMACHINE_FILE_OLD = 'statemachine.yaml' def __init__(self, base_path=RAFCON_TEMP_PATH_STORAGE): - Observable.__init__(self) - self._base_path = None self.base_path = os.path.abspath(base_path) logger.debug("Storage class initialized!") @@ -377,7 +373,6 @@ class StateMachineStorage(Observable): return self._base_path @base_path.setter - @Observable.observed def base_path(self, base_path): if not isinstance(base_path, basestring): raise TypeError("base_path must be of type str")
StateMachineStorage no longer inherits from Observable This wasn't used at any instance
py
diff --git a/lib/search_engine.py b/lib/search_engine.py index <HASH>..<HASH> 100644 --- a/lib/search_engine.py +++ b/lib/search_engine.py @@ -3291,7 +3291,12 @@ def sort_records(req, recIDs, sort_field='', sort_order='d', sort_pattern='', ve val = "" # will hold value for recID according to which sort vals = [] # will hold all values found in sorting tag for recID for tag in tags: - vals.extend(get_fieldvalues(recID, tag)) + if CFG_CERN_SITE and tag == '773__c': + # CERN hack: journal sorting + # 773__c contains page numbers, e.g. 3-13, and we want to sort by 3, and numerically: + vals.extend(["%050s" % x.split("-",1)[0] for x in get_fieldvalues(recID, tag)]) + else: + vals.extend(get_fieldvalues(recID, tag)) if sort_pattern: # try to pick that tag value that corresponds to sort pattern bingo = 0
WebSearch: CERN-specific hack for journal sorting * CERN-specific hack for journal sorting to transform page numbers of the form 3-<I> to 3 before applying numerical sorting. (addresses #<I>) * Cherry-picked from af<I>ef4ac<I>e<I>fe<I>a8a<I>fbf1d<I>e.
py
diff --git a/tests/test_substrate.py b/tests/test_substrate.py index <HASH>..<HASH> 100644 --- a/tests/test_substrate.py +++ b/tests/test_substrate.py @@ -828,7 +828,7 @@ class TestMAASAccountFromConfig(TestCase): config = get_maas_env().config with patch('subprocess.check_call', autospec=True) as cc_mock: with maas_account_from_config(config) as maas: - self.assertIsInstance(maas, MAASAccount) + self.assertIs(type(maas), MAASAccount) self.assertEqual(maas.profile, 'mas') self.assertEqual(maas.url, 'http://10.0.10.10/MAAS/api/2.0/') self.assertEqual(maas.oauth, 'a:password:string') @@ -846,7 +846,7 @@ class TestMAASAccountFromConfig(TestCase): with patch('subprocess.check_call', autospec=True, side_effect=[login_error, None, None]) as cc_mock: with maas_account_from_config(config) as maas: - self.assertIsInstance(maas, MAASAccount) + self.assertIs(type(maas), MAAS1Account) self.assertEqual(maas.profile, 'mas') self.assertEqual(maas.url, 'http://10.0.10.10/MAAS/api/1.0/') self.assertEqual(maas.oauth, 'a:password:string')
Correct check on MAASAccount types in test
py
diff --git a/setup.py b/setup.py index <HASH>..<HASH> 100644 --- a/setup.py +++ b/setup.py @@ -27,11 +27,11 @@ with open('README.md') as fp: setup( name="docker_interface", - version="0.2.11", + version="0.2.12", packages=find_packages(), install_requires=[ - 'jsonschema==2.6.0', - 'PyYAML==3.12', + 'jsonschema>=2.6.0', + 'PyYAML>=3.12', ], entry_points={ 'console_scripts': [
Relax requirements to support python <I>
py
diff --git a/fedmsg/commands/tweet.py b/fedmsg/commands/tweet.py index <HASH>..<HASH> 100644 --- a/fedmsg/commands/tweet.py +++ b/fedmsg/commands/tweet.py @@ -106,9 +106,9 @@ class TweetCommand(BaseCommand): self.log.warn("Bad URI for bitly %r" %link) link = "" - message = message[:138 - len(link)] + " " + link + message = message[:137 - len(link)] + " " + link else: - message = message[:140] + message = message[:139] if not message: self.log.info("Not tweeting blank message.")
Stop fedmsg-tweet from falling over.
py
diff --git a/kiner/producer.py b/kiner/producer.py index <HASH>..<HASH> 100644 --- a/kiner/producer.py +++ b/kiner/producer.py @@ -65,7 +65,7 @@ class KinesisProducer: if not self.queue.empty(): logger.info("Queue Flush: time without flush exceeded") self.flush_queue() - time.sleep(self.batch_time) + time.sleep(self.batch_time) def put_records(self, records, partition_key=None): """Add a list of data records to the record queue in the proper format.
Avoid continuously checking if it's time to flush the queue
py
diff --git a/vivarium/test_util.py b/vivarium/test_util.py index <HASH>..<HASH> 100644 --- a/vivarium/test_util.py +++ b/vivarium/test_util.py @@ -20,7 +20,6 @@ def setup_simulation(components, population_size=100, start=None): else: year_start = config.simulation_parameters.year_start simulation.current_time = pd.Timestamp(year_start, 1, 1) - simulation.step_size = pd.Timedelta(config.simulation_parameters.time_step, unit='D') if 'initial_age' in config.simulation_parameters: simulation.population._create_simulants(population_size, @@ -29,6 +28,8 @@ def setup_simulation(components, population_size=100, start=None): else: simulation.population._create_simulants(population_size) + simulation.step_size = pd.Timedelta(config.simulation_parameters.time_step, unit='D') + return simulation
Messed up the ordering in the test_util
py
diff --git a/spyder/plugins/editor/panels/codefolding.py b/spyder/plugins/editor/panels/codefolding.py index <HASH>..<HASH> 100644 --- a/spyder/plugins/editor/panels/codefolding.py +++ b/spyder/plugins/editor/panels/codefolding.py @@ -479,8 +479,8 @@ class FoldingPanel(Panel): # mouse enter fold scope QApplication.setOverrideCursor( QCursor(Qt.PointingHandCursor)) - if self._mouse_over_line != block.blockNumber() and \ - self._mouse_over_line is not None: + if (self._mouse_over_line != block.blockNumber() and + self._mouse_over_line is not None): # fold scope changed, a previous block was highlighter so # we quickly update our highlighting self._mouse_over_line = block.blockNumber() @@ -488,8 +488,13 @@ class FoldingPanel(Panel): else: # same fold scope, request highlight self._mouse_over_line = block.blockNumber() - self._highlight_runner.request_job( - self._highlight_block, block) + try: + self._highlight_runner.request_job( + self._highlight_block, block) + except KeyError: + # Catching the KeyError above is necessary to avoid + # issue spyder-ide/spyder#11291. + pass self._highight_block = block else: # no fold scope to highlight, cancel any pending requests
Folding: Catch KeyError when trying to highlight folding region
py
diff --git a/setup.py b/setup.py index <HASH>..<HASH> 100644 --- a/setup.py +++ b/setup.py @@ -91,7 +91,7 @@ setup( setup_requires=['numpy>=1.14.3', 'setuptools>=18.0'], python_requires='>=3.6', install_requires=["numpy>=1.14.3", "requests", "ruamel.yaml>=0.15.6", - "monty>=1.0.6", "scipy>=1.0.1", "pydispatcher>=2.0.5", + "monty>=2.0.6", "scipy>=1.0.1", "pydispatcher>=2.0.5", "tabulate", "spglib>=1.9.9.44", "networkx>=2.2", "matplotlib>=1.5", "palettable>=3.1.1", "sympy", "pandas"], extras_require={ @@ -168,4 +168,4 @@ setup( 'get_environment = pymatgen.cli.get_environment:main', ] } -) \ No newline at end of file +)
Upgade monty version in setup.py
py
diff --git a/atx/__init__.py b/atx/__init__.py index <HASH>..<HASH> 100644 --- a/atx/__init__.py +++ b/atx/__init__.py @@ -19,6 +19,11 @@ except pkg_resources.DistributionNotFound: from atx.consts import * from atx.errors import * from atx.drivers import Pattern, Bounds, ImageCrop +import atx.adbkit.client + + +# make a global var for easily use +adb_client = atx.adbkit.client.Client() def _connect_url(*args):
add atx.adb_client for easily adb operator
py
diff --git a/setup.py b/setup.py index <HASH>..<HASH> 100644 --- a/setup.py +++ b/setup.py @@ -51,6 +51,7 @@ setup( 'Framework :: Django', 'Framework :: Django :: 1.11', 'Framework :: Django :: 2.0', + 'Framework :: Django :: 2.1', ], zip_safe=False, tests_require=[
Added Django <I> to setup
py
diff --git a/hwt/synthesizer/utils.py b/hwt/synthesizer/utils.py index <HASH>..<HASH> 100644 --- a/hwt/synthesizer/utils.py +++ b/hwt/synthesizer/utils.py @@ -102,15 +102,15 @@ def toRtl(unitOrCls: Unit, name: str=None, if sc: if createFiles: - if fileMode == 'w': - fp = os.path.join(saveTo, fName) - files.append(fp) - with open(fp, fileMode) as f: - if fileMode == 'a': - f.write("\n") - f.write( - serializer.formater(sc) - ) + fp = os.path.join(saveTo, fName) + files.append(fp) + with open(fp, fileMode) as f: + if fileMode == 'a': + f.write("\n") + + f.write( + serializer.formater(sc) + ) else: codeBuff.append(sc)
toRtl fix wrong append to file
py
diff --git a/axes/decorators.py b/axes/decorators.py index <HASH>..<HASH> 100644 --- a/axes/decorators.py +++ b/axes/decorators.py @@ -1,7 +1,9 @@ import logging import socket +import json from datetime import timedelta +from babel.dates import format_timedelta from django.conf import settings from django.contrib.auth import logout @@ -350,12 +352,17 @@ def watch_login(func): def lockout_response(request): + context = { + 'cooloff_time': COOLOFF_TIME, + 'failure_limit': FAILURE_LIMIT, + 'username': request.POST.get(USERNAME_FORM_FIELD, '') + } + if request.is_ajax(): + return HttpResponse(json.dumps(context), + content_type='application/json', + status=403) + if LOCKOUT_TEMPLATE: - context = { - 'cooloff_time': COOLOFF_TIME, - 'failure_limit': FAILURE_LIMIT, - 'username': request.POST.get(USERNAME_FORM_FIELD, '') - } template = get_template(LOCKOUT_TEMPLATE) content = template.render(context, request) return HttpResponse(content, status=403)
Add json response on ajax request.
py
diff --git a/librosa/core/audio.py b/librosa/core/audio.py index <HASH>..<HASH> 100644 --- a/librosa/core/audio.py +++ b/librosa/core/audio.py @@ -139,7 +139,7 @@ def load(path, sr=22050, mono=True, offset=0.0, duration=None, # Load the target number of frames, and transpose to match librosa form y = sf_desc.read(frames=frame_duration, dtype=dtype, always_2d=False).T - except RuntimeError as exc: + except (RuntimeError, OSError) as exc: # If soundfile failed, try audioread instead if isinstance(path, six.string_types):
Compat fix: Fix core.load fallback Property fallback to audioread when OSError is raised in soundfile due to missing libsndfile binary dependency.
py
diff --git a/decode/plot/functions.py b/decode/plot/functions.py index <HASH>..<HASH> 100644 --- a/decode/plot/functions.py +++ b/decode/plot/functions.py @@ -206,20 +206,17 @@ def plot_chmap(cube, kidid, ax=None, **kwargs): """ if ax is None: ax = plt.gca() - fig = plt.gcf() index = np.where(cube.kidid == kidid)[0] if len(index) == 0: raise KeyError('Such a kidid does not exist.') index = int(index) - im = ax.imshow(cube[:, :, index].T, **kwargs) - divider = make_axes_locatable(ax) - cax = divider.append_axes('right', '5%', pad='3%') - fig.colorbar(im, cax=cax) + im = ax.pcolormesh(cube.x, cube.y, cube[:, :, index].T, **kwargs) ax.set_xlabel('x') ax.set_ylabel('y') ax.set_title('intensity map ch #{}'.format(kidid)) + return im def plotpsd(data, dt, ndivide=1, window=hanning, overlap_half=False, ax=None, **kwargs):
:<I>: plot_chmap returns mappable and does not plot colorbar inside it
py
diff --git a/fmn/lib/defaults.py b/fmn/lib/defaults.py index <HASH>..<HASH> 100644 --- a/fmn/lib/defaults.py +++ b/fmn/lib/defaults.py @@ -244,15 +244,6 @@ def create_defaults_for(session, user, only_for=None, detail_values=None): pref = fmn.lib.models.Preference.create( session, user, context, detail_value=value) - # Add a special filter that looks for mentions like @ralph - filt = fmn.lib.models.Filter.create( - session, "Mentions of my @username") - pattern = '[!-~ ]*[^\w@]@%s[^\w@][!-~ ]*' % nick - filt.add_rule(session, valid_paths, - "fmn.rules:regex_filter", pattern=pattern) - pref.add_filter(session, filt, notify=True) - # END @username filter - # Add a filter that looks for packages of this user filt = fmn.lib.models.Filter.create( session, "Events on packages that I own")
Remove regex usage from the defaults.
py
diff --git a/synapse/lib/layer.py b/synapse/lib/layer.py index <HASH>..<HASH> 100644 --- a/synapse/lib/layer.py +++ b/synapse/lib/layer.py @@ -14,7 +14,7 @@ import synapse.lib.msgpack as s_msgpack logger = logging.getLogger(__name__) -FAIR_ITERS = 5000 # every this many rows, yield CPU to other tasks +FAIR_ITERS = 10 # every this many rows, yield CPU to other tasks class Encoder(collections.defaultdict): def __missing__(self, name):
Make regex lookups more fair (#<I>)
py
diff --git a/netpyne/sim/run.py b/netpyne/sim/run.py index <HASH>..<HASH> 100644 --- a/netpyne/sim/run.py +++ b/netpyne/sim/run.py @@ -100,7 +100,7 @@ def preRun (): #------------------------------------------------------------------------------ # Run Simulation #------------------------------------------------------------------------------ -def runSim (reRun=False): +def runSim (skipPreRun=False): from .. import sim sim.pc.barrier() @@ -113,7 +113,7 @@ def runSim (reRun=False): sim.pc.barrier() sim.timing('start', 'runTime') - if not reRun: + if not skipPreRun: preRun() h.finitialize(float(sim.cfg.hParams['v_init']))
renamed reRun with skipPreRun
py
diff --git a/scripts/generate_rpc_templates.py b/scripts/generate_rpc_templates.py index <HASH>..<HASH> 100755 --- a/scripts/generate_rpc_templates.py +++ b/scripts/generate_rpc_templates.py @@ -72,8 +72,10 @@ def generate_async_message_template(nargs): print " boost::function< void(" + csep("arg#_t") + ") > callback;" print "};" print - if nargs == 0: print "inline" - else: print "template<" + csep("class arg#_t") + ">" + if nargs == 0: + print "inline" + else: + print "template<" + csep("class arg#_t") + ">" print "void send(mailbox_cluster_t *src, " + ("typename " if nargs > 0 else "") + "async_mailbox_t< void(" + csep("arg#_t") + ") >::address_t dest" + cpre("const arg#_t &arg#") + ") {" print " send(src, dest.addr," print " boost::bind(&async_mailbox_t< void(" + csep("arg#_t") + ") >::write, _1" + cpre("arg#") + "));"
Got rid of some one-line ifs in generate_rpc_templates.py.
py
diff --git a/grimoire_elk/elk/stackexchange.py b/grimoire_elk/elk/stackexchange.py index <HASH>..<HASH> 100644 --- a/grimoire_elk/elk/stackexchange.py +++ b/grimoire_elk/elk/stackexchange.py @@ -43,22 +43,15 @@ class StackExchangeEnrich(Enrich): def get_elastic_mappings(self): - from grimoire_elk.utils import kibiter_version - - fielddata = '' - if kibiter_version == '5': - fielddata = ', "fielddata": true' - mapping = """ { "properties": { "title_analyzed": { "type": "string", "index":"analyzed" - %s } } - } """ % fielddata + } """ return {"items":mapping}
[enrich][stackexchange] Remove agg flag from title_analyzed field
py
diff --git a/setup.py b/setup.py index <HASH>..<HASH> 100644 --- a/setup.py +++ b/setup.py @@ -25,7 +25,7 @@ if __name__ == '__main__': 'the Cole-Cole model', author='Maximilian Weigand', author_email='mweigand@geo.uni-bonn.de', - url='http://www.geo.uni-bonn.de/~mweigand', + url='https://github.com/m-weigand/sip_models', # find_packages() somehow does not work under Win7 when creating a # msi # installer # packages=find_packages(),
update homepage to github url
py
diff --git a/build.py b/build.py index <HASH>..<HASH> 100755 --- a/build.py +++ b/build.py @@ -625,7 +625,7 @@ virtual('apidoc', 'build/jsdoc-%(BRANCH)s-timestamp' % vars(variables)) 'build/src/external/src/exports.js', SRC, SHADER_SRC, ifind('apidoc/template')) def jsdoc_BRANCH_timestamp(t): - t.run('%(JSDOC)s', '-c', 'apidoc/conf.json', 'src', 'apidoc/index.md', + t.run('%(JSDOC)s', 'apidoc/index.md', '-c', 'apidoc/conf.json', '-d', 'build/hosted/%(BRANCH)s/apidoc') t.touch()
Adjust parameters of jsdoc-call in build.py. The `src`-directory is no longer defined on the commmandline and the `index.md` as explicit source file is now the first argument.
py
diff --git a/exporters/export_managers/base_exporter.py b/exporters/export_managers/base_exporter.py index <HASH>..<HASH> 100644 --- a/exporters/export_managers/base_exporter.py +++ b/exporters/export_managers/base_exporter.py @@ -126,6 +126,7 @@ class BaseExporter(object): 'items_count', self.writer.get_metadata('items_count') + bypass.total_items) self.logger.info( 'Finished executing bypass {}.'.format(bypass_class.__name__)) + self._final_stats_report() self.notifiers.notify_complete_dump(receivers=[CLIENTS, TEAM]) def bypass(self):
Generate stats report also when bypass is done
py
diff --git a/gglsbl/utils.py b/gglsbl/utils.py index <HASH>..<HASH> 100644 --- a/gglsbl/utils.py +++ b/gglsbl/utils.py @@ -1,11 +1,12 @@ +import binascii import sys def to_hex_2(v): return v.encode("hex") def to_hex_3(v): - return v.hex() + return binascii.hexlify(v) global to_hex
Fixes bug with converting bytes to hex with Python3 (#<I>)
py
diff --git a/tests/cases/py_client/cli_test.py b/tests/cases/py_client/cli_test.py index <HASH>..<HASH> 100644 --- a/tests/cases/py_client/cli_test.py +++ b/tests/cases/py_client/cli_test.py @@ -119,16 +119,10 @@ class PythonCliTestCase(base.TestCase): def testUploadDownload(self): localDir = os.path.join(os.path.dirname(__file__), 'testdata') args = ['-c', 'upload', str(self.publicFolder['_id']), localDir] - flag = False - try: + with self.assertRaises(girder_client.HttpError): invokeCli(args) - except girder_client.AuthenticationError: - flag = True - - self.assertTrue(flag) # Test dry-run and blacklist options - ret = invokeCli(args + ['--dryrun', '--blacklist=hello.txt'], username='mylogin', password='password') self.assertEqual(ret['exitVal'], 0)
Fix failing test based on bad assumption We changed the behavior that authentication is always required in the girder python client, so this test must be changed to reflect that.
py
diff --git a/_functions.py b/_functions.py index <HASH>..<HASH> 100644 --- a/_functions.py +++ b/_functions.py @@ -1,29 +1,10 @@ #import wx as _wx import numpy as _n import os as _os -import sys as _sys import shutil as _shutil import spinmob as _s import pickle as _cPickle -# Import our local visa library -def import_path(path): - """ - Imports a python module and returns it (adds path to sys.path). - - Parameters - ---------- - path - Full path to python module, e.g., "/my/full/path/module.py" - """ - include_path, filename = _os.path.split(path) - module = filename[0:len(filename)-3] - - # Insert the path - if include_path not in _sys.path: _sys.path.insert(0, include_path) - - exec("import "+module+" as _x") - return _x def coarsen_array(a, level=2, method='mean'):
Removed it. Recommend just sys.path.insert(0, path) then a normal import.
py
diff --git a/intern/service/boss/v1/volume.py b/intern/service/boss/v1/volume.py index <HASH>..<HASH> 100644 --- a/intern/service/boss/v1/volume.py +++ b/intern/service/boss/v1/volume.py @@ -1,4 +1,4 @@ -# Copyright 2016 The Johns Hopkins University Applied Physics Laboratory +# Copyright 2020 The Johns Hopkins University Applied Physics Laboratory # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -65,6 +65,8 @@ class VolumeService_1(BaseVersion): session (requests.Session): HTTP session to use for request. send_opts (dictionary): Additional arguments to pass to session.send(). """ + if np.sum(numpyVolume) == 0: + return if numpyVolume.ndim == 3: # Can't have time
Return quickly from empty create_cutout (#<I>) Fixes #<I>
py
diff --git a/metal/mmtl/trainer.py b/metal/mmtl/trainer.py index <HASH>..<HASH> 100644 --- a/metal/mmtl/trainer.py +++ b/metal/mmtl/trainer.py @@ -154,12 +154,7 @@ class MultitaskTrainer(object): self.metrics_hist = {} self._reset_losses() for epoch in range(self.config["n_epochs"]): - progress_bar = ( - self.config["progress_bar"] - and self.config["verbose"] - and self.logger.log_unit == "epochs" - ) - + progress_bar = self.config["progress_bar"] and self.config["verbose"] t = tqdm( enumerate(self._get_train_batches(tasks)), total=batches_per_epoch,
use progress bar regardless of how often you log
py
diff --git a/astroplan/constraints.py b/astroplan/constraints.py index <HASH>..<HASH> 100644 --- a/astroplan/constraints.py +++ b/astroplan/constraints.py @@ -65,10 +65,10 @@ def _get_altaz(times, observer, targets, force_zero_pressure=False): # convert times, targets to tuple for hashing try: - aakey = (tuple(times.jd), targets) + aakey = (tuple(times.jd), tuple(targets.ra.deg.ravel())) hash(aakey) except: - aakey = (times.jd, targets) + aakey = (times.jd, tuple(targets.ra.deg.ravel())) if aakey not in observer._altaz_cache: try: @@ -165,10 +165,10 @@ def _get_meridian_transit_times(times, observer, targets): # convert times to tuple for hashing try: - aakey = (tuple(times.jd), targets) + aakey = (tuple(times.jd), tuple(targets.ra.deg.ravel())) hash(aakey) except: - aakey = (times.jd, targets) + aakey = (times.jd, tuple(targets.ra.deg.ravel())) if aakey not in observer._meridian_transit_cache: meridian_transit_times = observer.target_meridian_transit_time(times, targets)
don't rely on target ID for hashing use the ra of targets as a dictionary key, since the conversion of targets prior to calculation means that the same underlying targets can have dfferent object IDs
py
diff --git a/src/edeposit/amqp/aleph/export.py b/src/edeposit/amqp/aleph/export.py index <HASH>..<HASH> 100755 --- a/src/edeposit/amqp/aleph/export.py +++ b/src/edeposit/amqp/aleph/export.py @@ -30,8 +30,9 @@ import isbn_validator from httpkie import Downloader import settings +from datastructures import Author from datastructures import FormatEnum -from datastructures import EPublication, Author +from datastructures import EPublication # Functions & objects =========================================================
export.py: Imports splitted to own lines.
py
diff --git a/sporco/linalg.py b/sporco/linalg.py index <HASH>..<HASH> 100644 --- a/sporco/linalg.py +++ b/sporco/linalg.py @@ -461,8 +461,6 @@ def solvemdbi_cg(ah, rho, b, axisM, axisK, tol=1e-5, mit=1000, isn=None): Number of CG iterations """ - K = ah.shape[axisK] - M = ah.shape[axisM] a = np.conj(ah) if isn is not None: isn = isn.ravel() @@ -722,7 +720,6 @@ def rfl2norm2(xf, xs, axis=(0,1)): array :math:`\mathbf{x}` """ - xfs = xf.shape scl = 1.0 / np.prod(np.array([xs[k] for k in axis])) slc0 = (slice(None),)*axis[-1] nrm0 = linalg.norm(xf[slc0 + (0,)])
Addressed some more code quality issues.
py
diff --git a/tests/test_util.py b/tests/test_util.py index <HASH>..<HASH> 100644 --- a/tests/test_util.py +++ b/tests/test_util.py @@ -43,6 +43,7 @@ from pythainlp.util import ( time_to_thaiword, thai_to_eng, thaiword_to_num, + thai_keyboard_dist, ) @@ -155,7 +156,15 @@ class TestUtilPackage(unittest.TestCase): self.assertIsNotNone( rank(["แมว", "คน", "แมว"], exclude_stopwords=True) ) - + + # ### pythainlp.util.keyboard + + def test_thai_keyboard_dist(self): + self.assertEqual(thai_keyboard_dist("ฟ", "ฤ"), 0.0) + self.assertEqual(thai_keyboard_dist("ฟ", "ห"), 1.0) + self.assertEqual(thai_keyboard_dist("ฟ", "ก"), 2.0) + self.assertEqual(thai_keyboard_dist("ฟ", "ฤ", 0.5), 0.5) + # ### pythainlp.util.date def test_date(self):
Add test for thai keyboard distance
py
diff --git a/oembed/providers.py b/oembed/providers.py index <HASH>..<HASH> 100644 --- a/oembed/providers.py +++ b/oembed/providers.py @@ -529,7 +529,7 @@ class DjangoProvider(BaseProvider): # resize image if we have a photo, otherwise use the given maximums if self.resource_type == 'photo' and self.get_image(obj): self.resize_photo(obj, mapping, maxwidth, maxheight) - elif self.resource_type in ('html', 'rich', 'photo'): + elif self.resource_type in ('video', 'rich', 'photo'): width, height = size_to_nearest( maxwidth, maxheight,
Fixing a reference to an invalid resource type
py
diff --git a/constance/admin.py b/constance/admin.py index <HASH>..<HASH> 100644 --- a/constance/admin.py +++ b/constance/admin.py @@ -166,7 +166,7 @@ class ConstanceForm(forms.Form): for fieldset_title, fields_list in settings.CONFIG_FIELDSETS.items(): for field_name in fields_list: field_name_list.append(field_name) - if set(set(settings.CONFIG.keys()) - set(field_name_list)): + if field_name_list and set(set(settings.CONFIG.keys()) - set(field_name_list)): raise forms.ValidationError(_('CONSTANCE_CONFIG_FIELDSETS does not contain ' 'fields that exist in CONSTANCE_CONFIG.'))
Fix ConstanceForm validation Account for cases where CONSTANCE_CONFIG_FIELDSETS is not set at all in ConstanceForm validation.
py
diff --git a/microraiden/microraiden/proxy/resources/expensive.py b/microraiden/microraiden/proxy/resources/expensive.py index <HASH>..<HASH> 100644 --- a/microraiden/microraiden/proxy/resources/expensive.py +++ b/microraiden/microraiden/proxy/resources/expensive.py @@ -141,6 +141,9 @@ class Expensive(Resource): return self.reply_payment_required(content, proxy_handle, headers={header.NONEXISTING_CHANNEL: 1}, gen_ui=accepts_html) + except InvalidBalanceAmount as e: + # balance sent to the proxy is less than in the previous proof + return self.reply_payment_required(content, proxy_handle, headers, gen_ui=accepts_html) except InvalidBalanceProof as e: return self.reply_payment_required(content, proxy_handle, headers={header.INVALID_PROOF: 1},
proxy: catch exception raised on wrong balance
py
diff --git a/menuconfig.py b/menuconfig.py index <HASH>..<HASH> 100755 --- a/menuconfig.py +++ b/menuconfig.py @@ -658,7 +658,17 @@ def menuconfig(kconf): if _CONVERT_C_LC_CTYPE_TO_UTF8: _convert_c_lc_ctype_to_utf8() - # Get rid of the delay between pressing ESC and jumping to the parent menu + # Get rid of the delay between pressing ESC and jumping to the parent menu, + # unless the user has set ESCDELAY (see ncurses(3)). This makes the UI much + # smoother to work with. + # + # Note: This is strictly pretty iffy, since escape codes for e.g. cursor + # keys start with ESC, but I've never seen it cause problems in practice + # (probably because it's unlikely that the escape code for a key would get + # split up across read()s, at least with a terminal emulator). Please + # report if you run into issues. Some suitable small default value could be + # used here instead in that case. Maybe it's silly to not put in the + # smallest imperceptible delay here already, though I don't like guessing. os.environ.setdefault("ESCDELAY", "0") # Enter curses mode. _menuconfig() returns a string to print on exit, after
menuconfig: Mention some potential (though never seen) ESCDELAY iffiness
py
diff --git a/jcvi/formats/gff.py b/jcvi/formats/gff.py index <HASH>..<HASH> 100644 --- a/jcvi/formats/gff.py +++ b/jcvi/formats/gff.py @@ -2767,7 +2767,7 @@ def load(args): continue if desc_attr in g_fparent.attributes: desc = ",".join(g_fparent.attributes[desc_attr]) - elif desc_attr in feat.attributes: + if not desc and desc_attr in feat.attributes: desc = ",".join(feat.attributes[desc_attr]) if opts.full_header:
[formats] Update desc when desc_attribute is in feature
py
diff --git a/test/testing/test_waiting.py b/test/testing/test_waiting.py index <HASH>..<HASH> 100644 --- a/test/testing/test_waiting.py +++ b/test/testing/test_waiting.py @@ -36,7 +36,6 @@ class TestPatchWaitUseCases(object): def cb(args, kwargs, res, exc_info): if res == 10: return True - return False with wait_for_call(counter, 'count', callback=cb) as result: Thread(target=count_forever).start() @@ -66,7 +65,6 @@ class TestPatchWaitUseCases(object): def cb(args, kwargs, res, exc_info): if args == (10,): return True - return False with wait_for_call(counter, 'skip_to', callback=cb) as result: Thread(target=increment_forever).start() @@ -100,7 +98,6 @@ class TestPatchWaitUseCases(object): def cb(args, kwargs, res, exc_info): if exc_info is not None: return True - return False with wait_for_call(counter, 'count', callback=cb) as result: Thread(target=count_forever).start() @@ -139,7 +136,6 @@ class TestPatchWaitUseCases(object): def cb(args, kwargs, res, exc_info): if exc_info is not None: return False - return True with wait_for_call(counter, 'count', callback=cb) as result: Thread(target=count_forever).start()
don't need these lines, implicit return is falsy
py
diff --git a/octodns/provider/yaml.py b/octodns/provider/yaml.py index <HASH>..<HASH> 100644 --- a/octodns/provider/yaml.py +++ b/octodns/provider/yaml.py @@ -104,6 +104,7 @@ class YamlProvider(BaseProvider): ''' SUPPORTS_GEO = True SUPPORTS_DYNAMIC = True + SUPPORTS_MUTLIVALUE_PTR = True SUPPORTS = set(('A', 'AAAA', 'ALIAS', 'CAA', 'CNAME', 'DNAME', 'LOC', 'MX', 'NAPTR', 'NS', 'PTR', 'SSHFP', 'SPF', 'SRV', 'TXT', 'URLFWD'))
yaml supports multi value PTR
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,7 +64,7 @@ copyright = '2013, {}'.format(setup_pkg.kwargs['author']) # built documents. # # The short X.Y version. -version = setup_pkg.kwargs['version'] +version = '.'.join(setup_pkg.kwargs['version'].split('.')[0:2]) # The full version, including alpha/beta/rc tags. release = setup_pkg.kwargs['version']
Make short version string digested from potentially longer version string... in sphinx docs conf.py
py
diff --git a/test_nameko_sentry.py b/test_nameko_sentry.py index <HASH>..<HASH> 100644 --- a/test_nameko_sentry.py +++ b/test_nameko_sentry.py @@ -155,8 +155,8 @@ def test_worker_exception( with pytest.raises(RemoteError): rpc_proxy.broken() - with pytest.raises(exception_cls) as raised: - result.get() + with pytest.raises(exception_cls) as raised: + result.get() sentry = get_extension(container, SentryReporter) @@ -205,8 +205,8 @@ def test_expected_exception_not_reported( with pytest.raises(RemoteError): rpc_proxy.broken() - with pytest.raises(exception_cls): - result.get() + with pytest.raises(exception_cls): + result.get() sentry = get_extension(container, SentryReporter)
indentation fix: must exit the entrypoint waiter context before trying to get the result
py
diff --git a/grimoire/ocean/elastic.py b/grimoire/ocean/elastic.py index <HASH>..<HASH> 100644 --- a/grimoire/ocean/elastic.py +++ b/grimoire/ocean/elastic.py @@ -115,7 +115,13 @@ class ElasticOcean(object): # Forced from backend command line. last_update = from_date - logging.info("Incremental from: %s" % (last_update)) + logging.info("Incremental from: %s", last_update) + + # Check if backend supports from_date + try: + self.perceval_backend.from_date + except AttributeError: + last_update = None task_init = datetime.now()
[ocean] Support backends without from_date param
py
diff --git a/fabfile.py b/fabfile.py index <HASH>..<HASH> 100644 --- a/fabfile.py +++ b/fabfile.py @@ -10,13 +10,14 @@ from pathlib import Path PWD = path.dirname(__file__) -VENV_DIR = path.join(PWD, '.env') +ENV = os.environ["VENV_DIR"] if 'VENV_DIR' in os.environ else '.env' +VENV_DIR = path.join(PWD, ENV) def env(lang="python2.7"): - if file_exists('.env'): - local('rm -rf .env') - local('virtualenv -p %s .env' % lang) + if file_exists(VENV_DIR): + local('rm -rf {env}'.format(env=VENV_DIR)) + local('virtualenv -p {lang} {env}'.format(lang=lang, env=VENV_DIR)) def install():
Allow control of virtualenv in fabfile via environment variable
py
diff --git a/charmhelpers/contrib/openstack/context.py b/charmhelpers/contrib/openstack/context.py index <HASH>..<HASH> 100644 --- a/charmhelpers/contrib/openstack/context.py +++ b/charmhelpers/contrib/openstack/context.py @@ -244,7 +244,7 @@ class IdentityServiceContext(OSContextGenerator): class AMQPContext(OSContextGenerator): - def __init__(self, rel_name='amqp', relation_prefix=None, ssl_dir=None): + def __init__(self, ssl_dir=None, rel_name='amqp', relation_prefix=None): self.ssl_dir = ssl_dir self.rel_name = rel_name self.relation_prefix = relation_prefix
Reordered params for AMQPContext after last change broke backwards compatability
py
diff --git a/tests.py b/tests.py index <HASH>..<HASH> 100644 --- a/tests.py +++ b/tests.py @@ -303,8 +303,8 @@ def test_load_ui_mainwindow(): app = QtWidgets.QApplication(sys.argv) win = QtWidgets.QMainWindow() - with ignoreQtMessageHandler(['QMainWindowLayout::count: ?']): - QtCompat.loadUi(self.ui_qmainwindow, win) + #with ignoreQtMessageHandler(['QMainWindowLayout::count: ?']): + QtCompat.loadUi(self.ui_qmainwindow, win) assert hasattr(win, 'lineEdit'), \ "loadUi could not load instance to main window"
Verify original reason for RuntimeError being raised.
py
diff --git a/tests/test_future/test_utils.py b/tests/test_future/test_utils.py index <HASH>..<HASH> 100644 --- a/tests/test_future/test_utils.py +++ b/tests/test_future/test_utils.py @@ -18,6 +18,11 @@ from future.tests.base import unittest, skip26 TEST_UNICODE_STR = u'ℝεα∂@ßʟ℮ ☂ℯṧт υηḯ¢☺ḓ℮' +class MyExceptionIssue235(Exception): + def __init__(self, a, b): + super(MyExceptionIssue235, self).__init__('{0}: {1}'.format(a, b)) + + class TestUtils(unittest.TestCase): def setUp(self): self.s = TEST_UNICODE_STR @@ -153,12 +158,8 @@ class TestUtils(unittest.TestCase): self.assertIsNone(e.__cause__) def test_issue_235(self): - class MyException(Exception): - def __init__(self, a, b): - super(MyException, self).__init__('{0}: {1}'.format(a, 7)) - def foo(): - raise MyException(3, 7) + raise MyExceptionIssue235(3, 7) def bar(): try: @@ -288,7 +289,6 @@ class TestCause(unittest.TestCase): else: self.fail("No exception raised") - @expectedFailurePY3 def test_instance_cause(self): cause = KeyError('blah') try:
Fix tests for issue #<I>
py
diff --git a/aiida_codtools/parsers/ciffilter.py b/aiida_codtools/parsers/ciffilter.py index <HASH>..<HASH> 100644 --- a/aiida_codtools/parsers/ciffilter.py +++ b/aiida_codtools/parsers/ciffilter.py @@ -1,6 +1,7 @@ # -*- coding: utf-8 -*- -from aiida.parsers.plugins.codtools.baseclass import BaseCodtoolsParser -from aiida.orm.calculation.job.codtools.ciffilter import CiffilterCalculation +from aiida.orm import CalculationFactory +from aiida_codtools.parsers.baseclass import BaseCodtoolsParser + class CiffilterParser(BaseCodtoolsParser): """ @@ -11,5 +12,5 @@ class CiffilterParser(BaseCodtoolsParser): """ Initialize the instance of CiffilterParser """ - self._supported_calculation_class = CiffilterCalculation + self._supported_calculation_class = CalculationFactory('codtools.ciffilter') super(CiffilterParser, self).__init__(calc)
Fixing imports in ciffilter parser for #2
py
diff --git a/bxml/xml.py b/bxml/xml.py index <HASH>..<HASH> 100644 --- a/bxml/xml.py +++ b/bxml/xml.py @@ -145,6 +145,21 @@ class XML(File): d.root = deepcopy(self.root) return d + def element(self, tag_path, **attributes): + """given a tag in xpath form and optional attributes, find the element in self.root or return a new one.""" + xpath = tag_path + if len(attributes) > 0: + xpath += "[%s]" % ' '.join(["@%s='%s'" % (k, attributes[k]) for k in attributes]) + e = self.find(self.root, xpath) + if e is None: + tag = tag_path.split('/')[-1].split('[')[0] + tagname = tag.split(':')[-1] + if ':' in tag: + nstag = tag.split(':')[0] + tag = "{%s}%s" % (self.NS[nstag], tagname) + e = etree.Element(tag, **attributes) + return e + @classmethod def Element(cls, s, *args): """given a string s and string *args, return an Element."""
XML.element() will find the element with the given tag_path and **attributes, or else create a new one, and returns it.
py
diff --git a/c7n/resources/rdscluster.py b/c7n/resources/rdscluster.py index <HASH>..<HASH> 100644 --- a/c7n/resources/rdscluster.py +++ b/c7n/resources/rdscluster.py @@ -13,6 +13,7 @@ # limitations under the License. import logging +from botocore.exceptions import ClientError from concurrent.futures import as_completed from c7n.actions import ActionRegistry, BaseAction
Added a missing ClientError import
py
diff --git a/pygubu/__init__.py b/pygubu/__init__.py index <HASH>..<HASH> 100644 --- a/pygubu/__init__.py +++ b/pygubu/__init__.py @@ -10,7 +10,7 @@ from pygubu.builder.builderobject import BuilderObject, register_widget from pygubu.binding import remove_binding, ApplicationLevelBindManager -__version__ = '0.12' +__version__ = '0.13' def register_property(name, description):
Increase version number to sync with pypi.
py
diff --git a/pyrogram/client/client.py b/pyrogram/client/client.py index <HASH>..<HASH> 100644 --- a/pyrogram/client/client.py +++ b/pyrogram/client/client.py @@ -370,7 +370,7 @@ class Client: self.phone_code = ( input("Enter phone code: ") if self.phone_code is None else self.phone_code if type(self.phone_code) is str - else self.phone_code() + else str(self.phone_code()) ) try:
Allow returning sms codes as int from the callback function
py