diff
stringlengths
139
3.65k
message
stringlengths
8
627
diff_languages
stringclasses
1 value
diff --git a/phonopy/api_phonopy.py b/phonopy/api_phonopy.py index <HASH>..<HASH> 100644 --- a/phonopy/api_phonopy.py +++ b/phonopy/api_phonopy.py @@ -487,6 +487,7 @@ class Phonopy(object): if 'first_atoms' in dataset: self._displacement_dataset = dataset elif 'displacements' in dataset: + self._displacement_dataset = {} self.displacements = dataset['displacements'] if 'forces' in dataset: self.forces = dataset['forces']
Minor fix to accept type1 dataset at Phonopy.dataset.setter
py
diff --git a/kettle.py b/kettle.py index <HASH>..<HASH> 100755 --- a/kettle.py +++ b/kettle.py @@ -50,14 +50,20 @@ class KettleManager: } } + def player_entity(self, player): + return { + "Type": "Player", + "Player": { + "EntityID": player.manager.id, + "Tags": Kettle._serialize_tags(player.tags), + } + } + def full_entity(self, entity): - if isinstance(entity, Player): - type = "Player" - else: - type = "FullEntity" return { - "Type": type, - type: { + "Type": "FullEntity", + "FullEntity": { + "CardID": entity.id, "EntityID": entity.manager.id, "Tags": Kettle._serialize_tags(entity.tags), }
Kettle: Add a CardID to full_entity packets
py
diff --git a/setup.py b/setup.py index <HASH>..<HASH> 100644 --- a/setup.py +++ b/setup.py @@ -1,18 +1,17 @@ from setuptools import find_packages from distutils.core import setup -import django_object_actions as app setup( - name=app.__name__, - version=app.__version__, + name='django-object-actions', + version='0.0.1', author="Chris Chang", author_email="c@crccheck.com", # url packages=find_packages('.', exclude=('example_project*',)), include_package_data=True, # automatically include things from MANIFEST license='Apache License, Version 2.0', - description=app.__doc__.strip(), + description='A Django app for adding object tools to models', long_description=open('README.md').read(), classifiers=[ "Development Status :: 3 - Alpha",
Don't pull metadata from the application It imports Django modules that require the settings module, which breaks installation.
py
diff --git a/oidc_auth/authentication.py b/oidc_auth/authentication.py index <HASH>..<HASH> 100644 --- a/oidc_auth/authentication.py +++ b/oidc_auth/authentication.py @@ -170,15 +170,15 @@ class JSONWebTokenAuthentication(BaseOidcAuthentication): return auth[1] + def jwks(self): + return JsonWebKey.import_key_set(self.jwks_data()) + @cache(ttl=api_settings.OIDC_JWKS_EXPIRATION_TIME) def jwks_data(self): r = request("GET", self.oidc_config['jwks_uri'], allow_redirects=True) r.raise_for_status() return r.json() - def jwks(self): - return JsonWebKey.import_key_set(self.jwks_data()) - @cached_property def issuer(self): return self.oidc_config['issuer']
Put it on the same spot to not confuse git.
py
diff --git a/hebel/layers/linear_regression_layer.py b/hebel/layers/linear_regression_layer.py index <HASH>..<HASH> 100644 --- a/hebel/layers/linear_regression_layer.py +++ b/hebel/layers/linear_regression_layer.py @@ -189,5 +189,5 @@ class LinearRegressionLayer(SoftmaxLayer): matrix_sum_out_axis((targets - activations) ** 2, 1)) if average: loss = loss.mean() - return float(loss.get()) + return loss train_error = squared_loss
Linear regression layer returns loss as GPUArray, not float, to be consistent with SoftmaxLayer
py
diff --git a/dateparser/timezones.py b/dateparser/timezones.py index <HASH>..<HASH> 100644 --- a/dateparser/timezones.py +++ b/dateparser/timezones.py @@ -1,6 +1,7 @@ # Based on http://stackoverflow.com/q/1703546 # As well as http://en.wikipedia.org/wiki/List_of_time_zone_abbreviations # As well as https://github.com/scrapinghub/dateparser/pull/4 +# As well as http://en.wikipedia.org/wiki/List_of_UTC_time_offsets timezone_info_list = [ {
Added source for the list of utc offsets
py
diff --git a/pydivert/__init__.py b/pydivert/__init__.py index <HASH>..<HASH> 100644 --- a/pydivert/__init__.py +++ b/pydivert/__init__.py @@ -20,7 +20,7 @@ from .packet import Packet from .windivert import WinDivert __author__ = 'fabio' -__version__ = '2.0.0' +__version__ = '2.0.1' if _sys.version_info < (3, 4): # add socket.inet_pton on Python < 3.4
Bump to version <I> to reinvent the wheel...
py
diff --git a/tests/eventlisten.py b/tests/eventlisten.py index <HASH>..<HASH> 100644 --- a/tests/eventlisten.py +++ b/tests/eventlisten.py @@ -51,8 +51,8 @@ def listen(sock_dir, node): Attach to the pub socket and grab messages ''' event = salt.utils.event.SaltEvent( + node, sock_dir, - node ) while True: ret = event.get_event(full=True)
Args got flipped in eventlisten
py
diff --git a/pygccxml/parser/directory_cache.py b/pygccxml/parser/directory_cache.py index <HASH>..<HASH> 100644 --- a/pygccxml/parser/directory_cache.py +++ b/pygccxml/parser/directory_cache.py @@ -379,13 +379,13 @@ class directory_cache_t (declarations_cache.cache_base_t): m = hashlib.sha1() m.update(config.working_directory.encode("utf-8")) for p in config.include_paths: - m.update(p) + m.update(p.encode("utf-8")) for p in config.define_symbols: - m.update(p) + m.update(p.encode("utf-8")) for p in config.undefine_symbols: - m.update(p) + m.update(p.encode("utf-8")) for p in config.cflags: - m.update(p) + m.update(p.encode("utf-8")) return m.digest()
Add more fixes for directory cache and python3
py
diff --git a/gitlab/__init__.py b/gitlab/__init__.py index <HASH>..<HASH> 100644 --- a/gitlab/__init__.py +++ b/gitlab/__init__.py @@ -1102,6 +1102,24 @@ class Gitlab(object): return False + def getmergerequestcomments(self, project_id, mergerequest_id): + """ + Get comments of a merge request. + :type project_id: int + :param project_id: ID of the project + :param mergerequest_id: ID of the merge request + """ + url_str = '{0}/{1}/merge_request/{2}/comments'.format(self.projects_url, + project_id, + mergerequest_id) + request = requests.get(url_str, headers=self.headers, verify=self.verify_ssl) + + if request.status_code == 200: + return json.loads(request.content.decode("utf-8")) + else: + + return False + def createmergerequest(self, project_id, sourcebranch, targetbranch, title, assignee_id=None, sudo=""): """
Mergerequest: add get comments
py
diff --git a/mistletoe/span_token.py b/mistletoe/span_token.py index <HASH>..<HASH> 100644 --- a/mistletoe/span_token.py +++ b/mistletoe/span_token.py @@ -259,7 +259,7 @@ class XWikiBlockMacroStart(SpanToken): We want to keep it on a separate line instead of "soft" merging it with the *following* line. """ - pattern = re.compile('(((?<!~)\{\{)(\w+)(.*?)((?<![~/])\}\}))(?:\s*\n)') + pattern = re.compile(r'(?<!\\)(\{\{\w+.*?(?<![\\/])\}\})\s*\n') parse_inner = False parse_group = 1 @@ -269,7 +269,7 @@ class XWikiBlockMacroEnd(SpanToken): We want to keep it on a separate line instead of "soft" merging it with the *preceding* line. """ - pattern = re.compile('^(?:\s*)((\{\{/)(\w+)(\}\}))', re.MULTILINE) + pattern = re.compile(r'^(?:\s*)(\{\{/\w+\}\})', re.MULTILINE) parse_inner = False parse_group = 1
fix(xwiki-renderer): fix regex for macro tokens * check for `\\`, not `~` (`~` will be correctly escaped to `~~` on render) * cleanup: remove unused capturing groups
py
diff --git a/asammdf/blocks/utils.py b/asammdf/blocks/utils.py index <HASH>..<HASH> 100644 --- a/asammdf/blocks/utils.py +++ b/asammdf/blocks/utils.py @@ -989,7 +989,7 @@ def is_file_like(obj: object) -> bool: class UniqueDB(object): - def __init__(self): + def __init__(self) -> None: self._db = {} def get_unique_name(self, name: str) -> str: @@ -1136,7 +1136,7 @@ class Group: def __getitem__(self, item: str) -> Any: return self.__getattribute__(item) - def __setitem__(self, item: str, value: Any) -> str: + def __setitem__(self, item: str, value: Any) -> None: self.__setattr__(item, value) def set_blocks_info(self, info: list[DataBlockInfo]) -> None:
fix(blocks.utils): wrong type annotations
py
diff --git a/nornir/plugins/inventory/simple.py b/nornir/plugins/inventory/simple.py index <HASH>..<HASH> 100644 --- a/nornir/plugins/inventory/simple.py +++ b/nornir/plugins/inventory/simple.py @@ -28,12 +28,13 @@ class SimpleInventory(Inventory): ) -> None: if hosts is None: yml = ruamel.yaml.YAML(typ="safe") - with open(host_file, "r") as f: + with open(os.path.expanduser(host_file), "r") as f: hosts = yml.load(f) if groups is None: groups = {} if group_file: + group_file = os.path.expanduser(group_file) if os.path.exists(group_file): with open(group_file, "r") as f: groups = yml.load(f) or {} @@ -44,6 +45,7 @@ class SimpleInventory(Inventory): if defaults is None: defaults = {} if defaults_file: + defaults_file = os.path.expanduser(defaults_file) if os.path.exists(defaults_file): with open(defaults_file, "r") as f: defaults = yml.load(f) or {}
Allow simple inventory files to use ~ in paths (#<I>)
py
diff --git a/src/tea/decorators/__init__.py b/src/tea/decorators/__init__.py index <HASH>..<HASH> 100644 --- a/src/tea/decorators/__init__.py +++ b/src/tea/decorators/__init__.py @@ -3,6 +3,9 @@ __date__ = '06 October 2013' __copyright__ = 'Copyright (c) 2013 Viktor Kerkez' +import contextlib + + def docstring(doc, prepend=False, join='\n'): """Decorator that will prepend or append a string to the current documentation of the target function. @@ -30,3 +33,18 @@ def docstring(doc, prepend=False, join='\n'): func.__doc__ = new.strip() + '\n' return func return decorator + + +@contextlib.contextmanager +def ignore(*exceptions): + """Ignores an exception or exception list + + Usage:: + + with ignore(OSError): + os.remove('filename.txt') + """ + try: + yield + except exceptions: + pass
NFT: Ignore exception context manager added
py
diff --git a/setup.py b/setup.py index <HASH>..<HASH> 100644 --- a/setup.py +++ b/setup.py @@ -31,7 +31,7 @@ setup( ], }, test_suite='green.test', - description = 'Green is a clean, colorful test runner for Python unit tests. Compare it to trial or nose.', + description = 'Green is a clean, colorful test runner for Python unit tests.', long_description = long_description, author = 'Nathan Stocks', author_email = 'nathan.stocks@gmail.com',
Removed another unnecessary reference to trial and nose.
py
diff --git a/docs/conf.py b/docs/conf.py index <HASH>..<HASH> 100755 --- a/docs/conf.py +++ b/docs/conf.py @@ -41,7 +41,7 @@ import pronouncing # Add any Sphinx extension module names here, as strings. They can be # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom ones. extensions = ['sphinx.ext.autodoc', 'sphinx.ext.viewcode', - 'sphinx.ext.doctest'] + 'sphinx.ext.doctest'] # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates']
reindent to appease flake8
py
diff --git a/tests/models.py b/tests/models.py index <HASH>..<HASH> 100644 --- a/tests/models.py +++ b/tests/models.py @@ -557,7 +557,7 @@ class TaskInstanceTest(unittest.TestCase): ti.xcom_push(key=key, value=value) self.assertEqual(ti.xcom_pull(task_ids='test_xcom', key=key), value) ti.run() - exec_date = exec_date.replace(day=exec_date.day + 1) + exec_date += datetime.timedelta(days=1) ti = TI( task=task, execution_date=exec_date) ti.run()
[AIRFLOW-<I>] Fix broken unit test This unit tests always fails on the last day of the month, since it tries to access a nonexistent day (like June <I>st).
py
diff --git a/dyndnsc/daemon.py b/dyndnsc/daemon.py index <HASH>..<HASH> 100644 --- a/dyndnsc/daemon.py +++ b/dyndnsc/daemon.py @@ -59,7 +59,7 @@ def daemonize(stdout=os.devnull, stderr=None, stdin=os.devnull, sys.stderr.write("%s%s" % (startmsg, os.linesep) % pid) sys.stderr.flush() if pidfile: - open(pidfile, 'w+b').write("%s%s" % (pid, os.linesep)) + open(pidfile, 'w+').write("%s%s" % (pid, os.linesep)) # Redirect standard file descriptors. os.dup2(si.fileno(), sys.stdin.fileno())
pidfile: w+b expects bytes, but on py3 it got unicode str but as it is a text file, binary mode is wrong anyway, so just use text mode.
py
diff --git a/secedgar/filings/daily.py b/secedgar/filings/daily.py index <HASH>..<HASH> 100644 --- a/secedgar/filings/daily.py +++ b/secedgar/filings/daily.py @@ -193,7 +193,7 @@ class DailyFilings(AbstractFiling): self.get_filings_dict() for filings in self._filings_dict.values(): # take the company name from the first filing and make that the subdirectory name - subdirectory = os.path.join(directory, filings[0].company_name) + subdirectory = os.path.join(str(directory), filings[0].company_name) make_path(subdirectory) for filing in filings: filename = filing.file_name.split('/')[-1]
FIX: Ensure directory is string for <I> compatability
py
diff --git a/urbansim/urbanchoice/interaction.py b/urbansim/urbanchoice/interaction.py index <HASH>..<HASH> 100644 --- a/urbansim/urbanchoice/interaction.py +++ b/urbansim/urbanchoice/interaction.py @@ -80,13 +80,7 @@ def mnl_interaction_dataset(choosers, alternatives, SAMPLE_SIZE, alts_sample = alternatives.loc[sample] assert len(alts_sample.index) == SAMPLE_SIZE * len(choosers.index) - try: - alts_sample['join_index'] = np.repeat(choosers.index, SAMPLE_SIZE) - except: - # TODO: log the error here and re-raise the original exception - raise Exception( - "ERROR: An exception here means agents and " - "alternatives aren't merging correctly") + alts_sample['join_index'] = np.repeat(choosers.index.values, SAMPLE_SIZE) alts_sample = pd.merge( alts_sample, choosers, left_on='join_index', right_index=True,
Use index.values with numpy.repeat The interaction code was calling np.repeat with a Pandas Index, which was causing an error further in. Passing the Index values seems to fix things. There was a try/except block wrapping this call. I took it out because it prevented diagnosing the problem.
py
diff --git a/setup.py b/setup.py index <HASH>..<HASH> 100644 --- a/setup.py +++ b/setup.py @@ -19,7 +19,7 @@ setup(name='grs', include_package_data=True, license=grs.__license__, keywords="stock taiwan taipei twse 台灣 股市 台北 即時", - install_requires=[], + install_requires=['python-dateutil'], classifiers=[ 'Development Status :: 5 - Production/Stable', 'Environment :: Console',
Add python-dateutil in setup.
py
diff --git a/raiden/network/proxies/token_network.py b/raiden/network/proxies/token_network.py index <HASH>..<HASH> 100644 --- a/raiden/network/proxies/token_network.py +++ b/raiden/network/proxies/token_network.py @@ -997,8 +997,7 @@ class TokenNetwork: # # Exception is raised if the public key recovery failed. except Exception: # pylint: disable=broad-except - msg = "Couldn't verify the balance proof signature" - return RaidenUnrecoverableError, msg + raise RaidenUnrecoverableError("Couldn't verify the balance proof signature") if signer_address != partner: raise RaidenUnrecoverableError('Invalid balance proof signature')
bugfix: Exception was not thrown The return values from _update_preconditions are discarded
py
diff --git a/mintapi/api.py b/mintapi/api.py index <HASH>..<HASH> 100644 --- a/mintapi/api.py +++ b/mintapi/api.py @@ -12,7 +12,10 @@ from datetime import date, datetime, timedelta import requests from requests.adapters import HTTPAdapter -from requests.packages.urllib3.poolmanager import PoolManager +try: + from requests.packages.urllib3.poolmanager import PoolManager +except: + from urllib3.poolmanager import PoolManager import xmltodict
Exception urllib3 lib Ubuntu <I>+ and other Debian distros do not have urllib3 in the request library
py
diff --git a/bcloud/App.py b/bcloud/App.py index <HASH>..<HASH> 100644 --- a/bcloud/App.py +++ b/bcloud/App.py @@ -110,6 +110,7 @@ class App: paned.child_set_property(left_box, 'resize', False) nav_window = Gtk.ScrolledWindow() + nav_window.get_style_context().add_class(Gtk.STYLE_CLASS_SIDEBAR) nav_window.props.hscrollbar_policy = Gtk.PolicyType.NEVER left_box.pack_start(nav_window, True, True, 0)
Add SIDEBAR class to nav_window
py
diff --git a/mygeotab/ext/entitylist.py b/mygeotab/ext/entitylist.py index <HASH>..<HASH> 100644 --- a/mygeotab/ext/entitylist.py +++ b/mygeotab/ext/entitylist.py @@ -11,6 +11,17 @@ class API(api.API): """ def get(self, type_name, **parameters): + """Gets entities using the API. Shortcut for using call() with the 'Get' method. This returns an EntityList + with added convience methods. + + :param type_name: The type of entity. + :type type_name: str + :param parameters: Additional parameters to send. + :raise MyGeotabException: Raises when an exception occurs on the MyGeotab server. + :raise TimeoutException: Raises when the request does not respond after some time. + :return: The results from the server. + :rtype: EntityList + """ return EntityList(super().get(type_name, **parameters), type_name=type_name)
Added docs for entitylist.API.get()
py
diff --git a/setup.py b/setup.py index <HASH>..<HASH> 100644 --- a/setup.py +++ b/setup.py @@ -38,11 +38,11 @@ required_packages = [ "flask==1.1.1", "gunicorn", "typing", - "retrying==1.3.3", + "retrying>=1.3.3", "gevent", "inotify_simple==1.2.1", - "werkzeug==0.15.5", - "paramiko==2.4.2", + "werkzeug>=0.15.5", + "paramiko>=2.4.2", "psutil>=5.6.7", "protobuf>=3.1", "scipy>=1.2.2",
fix: relax dependencies version requirements. (#<I>)
py
diff --git a/oauthlib/oauth1/rfc5849/__init__.py b/oauthlib/oauth1/rfc5849/__init__.py index <HASH>..<HASH> 100644 --- a/oauthlib/oauth1/rfc5849/__init__.py +++ b/oauthlib/oauth1/rfc5849/__init__.py @@ -177,11 +177,11 @@ class Client(object): # as described in http://oauth.googlecode.com/svn/spec/ext/body_hash/1.0/oauth-bodyhash.html # 4.1.1. When to include the body hash # * [...] MUST NOT include an oauth_body_hash parameter on requests with form-encoded request bodies - # * [...] SHOULD include the oauth_body_hash parameter on all other requests. + # * [...] SHOULD include the oauth_body_hash parameter on all other requests. content_type = request.headers.get('Content-Type', None) content_type_eligible = content_type and content_type.find('application/x-www-form-urlencoded') < 0 if request.body is not None and content_type_eligible: - params.append(('oauth_body_hash', base64.b64encode(hashlib.sha1(request.body).digest()).decode('utf-8'))) + params.append(('oauth_body_hash', base64.b64encode(hashlib.sha1(request.body.encode('utf-8')).digest()).decode('utf-8'))) return params
Python3 fix: encodes request body before hashing In python 3 hashlib works on bytestrings, so we need to encode arguments to most, if not all, hashing functions.
py
diff --git a/pytest/test_std.py b/pytest/test_std.py index <HASH>..<HASH> 100644 --- a/pytest/test_std.py +++ b/pytest/test_std.py @@ -28,7 +28,7 @@ EXPECTED_CODE_INFO = ("""\ # Filename: <disassembly> # Argument count: 0 """ -+ ("# Kw-only arguments: 0" if PYTHON3 else "") + ++ ("# Kw-only arguments: 0\n" if PYTHON3 else "") + """# Number of locals: 0 # Stack size: 1 # Flags: {flags} @@ -84,7 +84,8 @@ def test_bytecode_dis(bytecode_fixture): def test_bytecode_info(bytecode_fixture): - assert bytecode_fixture.info() == EXPECTED_CODE_INFO + actual = bytecode_fixture.info() + assert actual == EXPECTED_CODE_INFO def test_bytecode__iter__(bytecode_fixture):
fixed failing test_std due to missing newline
py
diff --git a/dispatch/default_settings.py b/dispatch/default_settings.py index <HASH>..<HASH> 100644 --- a/dispatch/default_settings.py +++ b/dispatch/default_settings.py @@ -90,5 +90,4 @@ STATICFILES_DIRS = ( PHONENUMBER_DB_FORMAT = 'NATIONAL' PHONENUMBER_DEFAULT_REGION = 'CA' -NOTIFICATION_KEY = "Mp2OSApC5ZQ11iHtKfTfAWycrr-YYl9yphpkeqKIy9E" PASSWORD_RESET_TIMEOUT_DAYS = 1
move notification key to ubyssey settings
py
diff --git a/tests/test_baseapi.py b/tests/test_baseapi.py index <HASH>..<HASH> 100644 --- a/tests/test_baseapi.py +++ b/tests/test_baseapi.py @@ -105,19 +105,19 @@ class TestBaseAPIURL(object): class TesteAPIQuery(object): - @mock.patch.object(requests, 'get') + @mock.patch.object(requests.Session, 'request') def test_timeout(self, get, baseapi): get.side_effect = requests.exceptions.Timeout with pytest.raises(requests.exceptions.Timeout): baseapi._query('nodes') - @mock.patch.object(requests, 'get') + @mock.patch.object(requests.Session, 'request') def test_connectionerror(self, get, baseapi): get.side_effect = requests.exceptions.ConnectionError with pytest.raises(requests.exceptions.ConnectionError): baseapi._query('nodes') - @mock.patch.object(requests, 'get') + @mock.patch.object(requests.Session, 'request') def test_httperror(self, get, baseapi): get.side_effect = requests.exceptions.HTTPError( response=requests.Response())
patch requests.Session.request instead of the global API The global API is implemented in terms of Session, so we don't break anything. This is a preparation for using the session API.
py
diff --git a/openquake/engine/export/hazard.py b/openquake/engine/export/hazard.py index <HASH>..<HASH> 100644 --- a/openquake/engine/export/hazard.py +++ b/openquake/engine/export/hazard.py @@ -203,7 +203,7 @@ def export_hazard_curve_multi(output, target_dir): metadata_set = [] path = None for hc in hcs: - metadata, path = _curve_metadata(output, target_dir) + metadata, path = _curve_metadata(hc.output, target_dir) metadata_set.append(metadata) assert(path)
export/hazard: Fixed the retrieval of `hazard_curve_multi` metadata. IML/IMT information wasn't being collected from the correct `Output`. Former-commit-id: <I>d<I>b<I>a<I>a<I>fa<I>aeb4a4a<I>f<I>f1d<I>
py
diff --git a/docx2html/core.py b/docx2html/core.py index <HASH>..<HASH> 100644 --- a/docx2html/core.py +++ b/docx2html/core.py @@ -1266,26 +1266,8 @@ def _strip_tag(tree, tag): """ Remove all tags that have the tag name ``tag`` """ - w_namespace = get_namespace(tree, 'w') - - check_text = True - # There are some tags that even if they have text we want to ignore - # (tags related to headers and footers) - black_list = ( - '%ssectPr' % w_namespace, - ) - if tag in black_list: - # We do not care if these tags have text in them or not, remove them - # anyway. - check_text = False for el in tree: - remove_el = False if el.tag == tag: - # We can remove the element if we don't want to check the element - # for text, or if the tag in question does not have text. - if not check_text or not has_text(el): - remove_el = True - if remove_el: tree.remove(el)
refs #<I>: removed all the balck list stuff, will re-add later if its needed
py
diff --git a/fsoopify/extras/yaml.py b/fsoopify/extras/yaml.py index <HASH>..<HASH> 100644 --- a/fsoopify/extras/yaml.py +++ b/fsoopify/extras/yaml.py @@ -21,7 +21,7 @@ from ..nodes import FileInfo class YamlSerializer: def load(self, src: FileInfo, kwargs): - return yaml.load(src.read_text(), **kwargs) + return yaml.safe_load(src.read_text(), **kwargs) def dump(self, src: FileInfo, obj, kwargs): return src.write_text(yaml.dump(obj, **kwargs), append=False)
fixed: use safe yaml load
py
diff --git a/tests/test_systematic.py b/tests/test_systematic.py index <HASH>..<HASH> 100644 --- a/tests/test_systematic.py +++ b/tests/test_systematic.py @@ -71,7 +71,7 @@ def test_op_add(): binary_ufunc_check(op.add) def test_op_sub(): binary_ufunc_check(op.sub) def test_op_mod(): binary_ufunc_check_no_same_args(op.mod, lims_B=[0.3, 2.0], test_complex=False) def test_op_mod_neg(): binary_ufunc_check_no_same_args(op.mod, lims_B=[-0.3, -2.0], test_complex=False) -def test_op_div(): binary_ufunc_check(op.div, lims_B=[0.5, 2.0]) +def test_op_div(): binary_ufunc_check(op.truediv, lims_B=[0.5, 2.0]) def test_op_pow(): binary_ufunc_check(op.pow, lims_A=[0.7, 2.0])
Use truediv operatator, which is present in both Py<I> and Py3
py
diff --git a/src/toil/test/jobStores/jobStoreTest.py b/src/toil/test/jobStores/jobStoreTest.py index <HASH>..<HASH> 100644 --- a/src/toil/test/jobStores/jobStoreTest.py +++ b/src/toil/test/jobStores/jobStoreTest.py @@ -1253,9 +1253,16 @@ class AWSJobStoreTest(AbstractJobStoreTest.Test): else: self.fail() finally: - for attempt in retry_s3(): - with attempt: - s3.delete_bucket(bucket=bucket) + try: + for attempt in retry_s3(): + with attempt: + s3.delete_bucket(bucket=bucket) + except boto.exception.S3ResponseError as e: + if e.error_code == 404: + # The bucket doesn't exist; maybe a failed delete actually succeeded. + pass + else: + raise @slow def testInlinedFiles(self):
Tolerate unnecessary bucket cleanup (#<I>)
py
diff --git a/winpty/tests/test_ptyprocess.py b/winpty/tests/test_ptyprocess.py index <HASH>..<HASH> 100644 --- a/winpty/tests/test_ptyprocess.py +++ b/winpty/tests/test_ptyprocess.py @@ -90,6 +90,7 @@ def test_isalive(pty_fixture): pty.terminate() +@pytest.mark.xfail(reason="It fails sometimes due to long strings") @flaky(max_runs=40, min_passes=1) def test_readline(pty_fixture): env = os.environ.copy()
Mark test_readline as xfail
py
diff --git a/fitsio/fitslib.py b/fitsio/fitslib.py index <HASH>..<HASH> 100644 --- a/fitsio/fitslib.py +++ b/fitsio/fitslib.py @@ -3442,7 +3442,7 @@ class FITSHDR: card += vstr if 'comment' in record: - f += ' / %s' % record['comment'] + card += ' / %s' % record['comment'] return card[0:80]
fix minor typo in adding comments to header cards
py
diff --git a/linkcheck/checker/urlbase.py b/linkcheck/checker/urlbase.py index <HASH>..<HASH> 100644 --- a/linkcheck/checker/urlbase.py +++ b/linkcheck/checker/urlbase.py @@ -508,13 +508,9 @@ class UrlBase (object): Return True iff we can recurse into the url's content. """ log.debug(LOG_CHECK, "checking recursion of %r ...", self.url) - # Test self.valid before self.is_parseable(). if not self.valid: log.debug(LOG_CHECK, "... no, invalid.") return False - if not self.is_parseable(): - log.debug(LOG_CHECK, "... no, not parseable.") - return False if not self.can_get_content(): log.debug(LOG_CHECK, "... no, cannot get content.") return False @@ -528,6 +524,9 @@ class UrlBase (object): if self.size > self.aggregate.config["maxfilesizeparse"]: log.debug(LOG_CHECK, "... no, maximum parse size.") return False + if not self.is_parseable(): + log.debug(LOG_CHECK, "... no, not parseable.") + return False if not self.content_allows_robots(): log.debug(LOG_CHECK, "... no, robots.") return False
Move parseable check down since it might get the content.
py
diff --git a/glue/ligolw/metaio.py b/glue/ligolw/metaio.py index <HASH>..<HASH> 100644 --- a/glue/ligolw/metaio.py +++ b/glue/ligolw/metaio.py @@ -214,7 +214,15 @@ class Column(ligolw.Column): """ if self.getAttribute("Type") in StringTypes: raise TypeError, "Column does not have numeric type" - return numarray.asarray(self, type = ToNumArrayType[self.getAttribute("Type")]) + # hack to work around bug in numarray: numarray tests that + # an object can be turned into an array, that is it is + # "list like", by trying to retrieve element 0. This fails + # if the list like object has 0 length, causing numarray to + # barf. If the object is, in fact, a real Python list then + # numarray is made happy. + if not len(self): + return numarray.array([], type = ToNumArrayType[self.getAttribute("Type")], shape = (len(self),)) + return numarray.array(self, type = ToNumArrayType[self.getAttribute("Type")], shape = (len(self),)) # FIXME: This function is for the metaio library: metaio cares # what order the attributes of XML tags come in. This function
Add work-around for gotcha when building numarray.array objects from zero-length non-list objects.
py
diff --git a/setup.py b/setup.py index <HASH>..<HASH> 100644 --- a/setup.py +++ b/setup.py @@ -41,7 +41,7 @@ setup( 'flake8>=2.5.4', 'hacking>=0.11.0', 'nose>=1.3.4', - 'coverage>=4.0.3', + 'coverage>=4.1b2', 'requests>=2.9.1', 'websocket-client>=0.35.0', ],
upgrade to coverage <I>b2
py
diff --git a/examples/robots.py b/examples/robots.py index <HASH>..<HASH> 100755 --- a/examples/robots.py +++ b/examples/robots.py @@ -54,8 +54,8 @@ class Vector(tuple): other, potentially diagonally.''' return self + Vector(( - (self[0] > other[0]) - (self[0] < other[0]), - (self[1] > other[1]) - (self[1] < other[1]), + (self[0] < other[0]) - (self[0] > other[0]), + (self[1] < other[1]) - (self[1] > other[1]), ))
fixed bug in example just introduced by swapping arguments
py
diff --git a/salt/modules/riak.py b/salt/modules/riak.py index <HASH>..<HASH> 100644 --- a/salt/modules/riak.py +++ b/salt/modules/riak.py @@ -84,4 +84,28 @@ def member_status(): salt '*' riak.member_status ''' - return __salt__['cmd.run']('riak-admin member-status') + ret = {'membership': {}, + 'summary': {'Valid': 0, + 'Leaving': 0, + 'Exiting': 0, + 'Joining': 0, + 'Down': 0, + } + } + cmd = 'riak-admin member-status' + out = __salt__['cmd.run'](cmd).splitlines() + for line in out: + if line.startswith(('=', '-', 'Status')): + continue + if '/' in line: + comps = line.split('/') + for item in comps: + key, val = item.split(':') + ret['summary'][key.strip()] = val.strip() + vals = line.split() + if len(vals) == 4: + ret['membership'][vals[3]] = {'Status': vals[0], + 'Ring': vals[1], + 'Pending': vals[2], + } + return ret
Return proper data structure from member_status
py
diff --git a/deimos/containerizer.py b/deimos/containerizer.py index <HASH>..<HASH> 100644 --- a/deimos/containerizer.py +++ b/deimos/containerizer.py @@ -115,10 +115,10 @@ class Docker(Containerizer, _Struct): # start an executor. observer_argv = None if needs_executor_wrapper(task): - options = ["--mesos-executor", "--executor"] + options = ["--mesos-executor", "--observer"] if not(len(args) > 1 and args[0] in options): - raise Err("Task %s needs --executor to be set!" % state.tid()) - observer_argv = [ args[1], deimos.path.me(), "wait", "--docker" ] + raise Err("Task %s needs --observer to be set!" % state.eid()) + observer_argv = args[1:] + [ deimos.path.me(), "wait", "--docker" ] else: env += mesos_env() + [("MESOS_DIRECTORY", self.workdir)]
More flexible specification of "observer" executor.
py
diff --git a/tests/unit/test_pillar.py b/tests/unit/test_pillar.py index <HASH>..<HASH> 100644 --- a/tests/unit/test_pillar.py +++ b/tests/unit/test_pillar.py @@ -439,8 +439,8 @@ class PillarTestCase(TestCase): 'renderer_blacklist': [], 'renderer_whitelist': [], 'state_top': '', - 'pillar_roots': [], - 'file_roots': [], + 'pillar_roots': {}, + 'file_roots': {}, 'extension_modules': '' } grains = {
mocked file_roots and pillar_roots should be dicts
py
diff --git a/docs/examples/rt-stuck-trackers.py b/docs/examples/rt-stuck-trackers.py index <HASH>..<HASH> 100755 --- a/docs/examples/rt-stuck-trackers.py +++ b/docs/examples/rt-stuck-trackers.py @@ -60,6 +60,7 @@ class StuckTrackers(base.ScriptBaseWithConfig): if self.options.stuck_only: continue if self.options.to_tagged: + proxy.d.views.push_back_unique(infohash, view) proxy.view.set_visible(infohash, view) domain = 'ALL TRACKERS DISABLED' if trackers else 'NO TRACKERS' stuck[domain] += 1 @@ -74,6 +75,7 @@ class StuckTrackers(base.ScriptBaseWithConfig): delta = now - t.activity_time_last if self.options.all or delta > t.normal_interval: if self.options.to_tagged: + proxy.d.views.push_back_unique(infohash, view) proxy.view.set_visible(infohash, view) domain = urlparse(t.url).netloc.split(':')[0] stuck[domain] += 1
rt-stuck-trackers: fix for --to-tagged
py
diff --git a/tests/test_cli.py b/tests/test_cli.py index <HASH>..<HASH> 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -1,6 +1,6 @@ import subprocess import os -from nose.tools import eq_ +from nose.tools import eq_, assert_raises # Get the filename of 'halibote.txt', which contains some mojibake about @@ -42,11 +42,10 @@ def test_alternate_encoding(): def test_wrong_encoding(): # It's more of a problem when the file doesn't actually decode. - try: + with assert_raises(subprocess.CalledProcessError) as context: get_command_output(['ftfy', '-e', 'windows-1252', TEST_FILENAME]) - assert False, "Should have raised a CalledProcessError" - except subprocess.CalledProcessError as e: - eq_(e.output.decode('utf-8'), FAILED_OUTPUT) + e = context.exception + eq_(e.output.decode('utf-8'), FAILED_OUTPUT) def test_stdin():
Use assert_raises in test_cli
py
diff --git a/assertpy/assertpy.py b/assertpy/assertpy.py index <HASH>..<HASH> 100644 --- a/assertpy/assertpy.py +++ b/assertpy/assertpy.py @@ -485,10 +485,9 @@ class AssertionBuilder(object): elif isinstance(self.val, collections.Iterable): if len(self.val) == 0: raise ValueError('val must not be empty') - for i in self.val: - if i != prefix: - self._err('Expected %s to start with <%s>, but did not.' % (self.val, prefix)) - break + first = next(i for i in self.val) + if first != prefix: + self._err('Expected %s to start with <%s>, but did not.' % (self.val, prefix)) else: raise TypeError('val is not a string or iterable') return self
use next() built-in to get first item of iterable
py
diff --git a/elasticsearch/compat.py b/elasticsearch/compat.py index <HASH>..<HASH> 100644 --- a/elasticsearch/compat.py +++ b/elasticsearch/compat.py @@ -33,7 +33,7 @@ else: from queue import Queue try: - from collections.abs import Mapping + from collections.abc import Mapping except ImportError: from collections import Mapping
Fix typo (collections.abs -> collections.abc) to restore Python <I> support
py
diff --git a/holoviews/plotting/plot.py b/holoviews/plotting/plot.py index <HASH>..<HASH> 100644 --- a/holoviews/plotting/plot.py +++ b/holoviews/plotting/plot.py @@ -943,7 +943,7 @@ class GenericCompositePlot(DimensionedPlot): if not isinstance(key, tuple): key = (key,) nthkey_fn = lambda x: zip(tuple(x.name for x in x.kdims), list(x.data.keys())[min([key[0], len(x)-1])]) - if key == self.current_key: + if key == self.current_key and not self._force: return self.current_frame else: self.current_key = key
Fixed GenericCompositePlot.get_frame for DynamicMaps with streams
py
diff --git a/python_modules/dagster-celery/dagster_celery/version.py b/python_modules/dagster-celery/dagster_celery/version.py index <HASH>..<HASH> 100644 --- a/python_modules/dagster-celery/dagster_celery/version.py +++ b/python_modules/dagster-celery/dagster_celery/version.py @@ -1,3 +1,3 @@ -__version__ = '0.6.5' +__version__ = '0.6.6' -__nightly__ = 'nightly-2019.11.28' +__nightly__ = 'nightly-2019.12.12'
Bring versions into lockstep Summary: Blocking nightlies. Test Plan: Nightly Reviewers: nate Reviewed By: nate Differential Revision: <URL>
py
diff --git a/fusionbox/middleware.py b/fusionbox/middleware.py index <HASH>..<HASH> 100644 --- a/fusionbox/middleware.py +++ b/fusionbox/middleware.py @@ -34,7 +34,10 @@ class GenericTemplateFinderMiddleware(object): """ def process_response(self, request, response): if response.status_code == 404: - return generic_template_finder_view(request) + try: + return generic_template_finder_view(request) + except Http404: + return response else: return response
Don't trash original response in GenericTemplateFinderMiddleware When GenericTemplateFinderMiddleware catches a <I> but can not find a suitable template, it should return the original response, not its Http<I> exception.
py
diff --git a/src/ossos-pipeline/setup.py b/src/ossos-pipeline/setup.py index <HASH>..<HASH> 100644 --- a/src/ossos-pipeline/setup.py +++ b/src/ossos-pipeline/setup.py @@ -17,7 +17,7 @@ for script in os.listdir(script_dir): scripts.append(os.path.join(script_dir,script)) scripts.append('validate.py') -version = "0.2.1" +version = "0.3.2" setup(name='ossos', version=version,
Bumped the version number, new flow and new CR-reject code
py
diff --git a/examples/py/kucoin-fetch-closed-orders-pagination.py b/examples/py/kucoin-fetch-closed-orders-pagination.py index <HASH>..<HASH> 100644 --- a/examples/py/kucoin-fetch-closed-orders-pagination.py +++ b/examples/py/kucoin-fetch-closed-orders-pagination.py @@ -23,11 +23,11 @@ limit = 20 while since < now: - end = max(since + week, now) + end = min(since + week, now) params = {'endAt': end} orders = exchange.fetch_closed_orders(symbol, since, limit, params) print(exchange.iso8601(since), '-', exchange.iso8601(end), len(orders), 'orders') if len(orders) == limit: since = orders[-1]['timestamp'] else: - since += week \ No newline at end of file + since += week
Update kucoin fetch closed orders example As mentioned [here](<URL>) the example needs to be update to use `min` instead of max for the end date, since if the difference between `startAt` and `endAt` is greater than 1 week the kucoin server responds with an error.
py
diff --git a/tests/integration_server.py b/tests/integration_server.py index <HASH>..<HASH> 100644 --- a/tests/integration_server.py +++ b/tests/integration_server.py @@ -67,8 +67,10 @@ class BaseIntegrationServer(object): continue match = self.protocol_re.match(line) - protocol = match.group('protocol') + if not match: + raise Exception('unexpected line: %r' % line) + protocol = match.group('protocol') if protocol not in self.protocols: continue
Show unexpected lines from nsq servers.
py
diff --git a/html5lib/tests/test_tokenizer.py b/html5lib/tests/test_tokenizer.py index <HASH>..<HASH> 100644 --- a/html5lib/tests/test_tokenizer.py +++ b/html5lib/tests/test_tokenizer.py @@ -144,10 +144,6 @@ def unescape(test): def runTokenizerTest(test): warnings.resetwarnings() warnings.simplefilter("error") - #XXX - move this out into the setup function - #concatenate all consecutive character tokens into a single token - if 'doubleEscaped' in test: - test = unescape(test) expected = concatenateCharacterTokens(test['output']) if 'lastStartTag' not in test: @@ -183,10 +179,10 @@ def testTokenizer(): testName = os.path.basename(filename).replace(".test","") if 'tests' in tests: for index,test in enumerate(tests['tests']): - #Skip tests with a self closing flag - skip = False if 'initialStates' not in test: test["initialStates"] = ["Data state"] + if 'doubleEscaped' in test: + test = unescape(test) for initialState in test["initialStates"]: test["initialState"] = capitalize(initialState) yield runTokenizerTest, test
Fix tokenizer test harness to not decode tests multiple times. Given a double escaped test, if it had multiple initial states, the same test object would be decoded multiple times: this led to bogus results on every run except the first.
py
diff --git a/nolds/__init__.py b/nolds/__init__.py index <HASH>..<HASH> 100644 --- a/nolds/__init__.py +++ b/nolds/__init__.py @@ -1 +1 @@ -from measures import lyap_r, layp_e, sampen, hurs_rs, corr_dim, dfa, fbm, binary_n, logarithmic_n, logarithmic_r +from nolds.measures import lyap_r, lyap_e, sampen, hurst_rs, corr_dim, dfa, fbm, binary_n, logarithmic_n, logarithmic_r
bugfix: we need to use nolds.measures instead of just measures when importing in package structure (+ some typos)
py
diff --git a/auth0/v2/device_credentials.py b/auth0/v2/device_credentials.py index <HASH>..<HASH> 100644 --- a/auth0/v2/device_credentials.py +++ b/auth0/v2/device_credentials.py @@ -18,3 +18,9 @@ class DeviceCredentials(object): 'type': type, } return self.client.get(params=params) + + def create(self, body): + return self.client.post(data=body) + + def delete(self, id): + return self.client.delete(id=id)
Implement create and delete methods for DeviceCredentials
py
diff --git a/commands.py b/commands.py index <HASH>..<HASH> 100755 --- a/commands.py +++ b/commands.py @@ -41,7 +41,12 @@ def virtualenv(where='.venv', python='python', overwrite=False): def install(where='.venv', python='python', upgrade=False, overwrite=False): virtualenv(where=where, python=python, overwrite=overwrite) pip = '{where}/bin/pip'.format(where=where) - local((pip, 'install', '--upgrade' if upgrade else '', '-e', '.[dev,tox]')) + local(( + pip, 'install', + ('--upgrade', '--upgrade-strategy', 'eager') if upgrade else None, + '--editable', '.[dev,tox]', + ('pip', 'setuptools') if upgrade else None, + ), echo=True) @command
Upgrade pip & setuptools when running install with --upgrade In addition, use the `--upgrade-strategy eager` option.
py
diff --git a/sos/plugins/memory.py b/sos/plugins/memory.py index <HASH>..<HASH> 100644 --- a/sos/plugins/memory.py +++ b/sos/plugins/memory.py @@ -27,9 +27,6 @@ class Memory(Plugin, RedHatPlugin, DebianPlugin, UbuntuPlugin): "/proc/vmstat", "/proc/slabinfo", "/proc/pagetypeinfo"]) - - self.add_cmd_output("dmesg | grep -e 'e820.' -e 'aperature.'", - suggest_filename="dmesg.e820-map") self.add_cmd_output("free", root_symlink = "free") self.add_cmd_output("free -m")
Remove dmesg|grep use from memory plugin This is redundant since the whole boottime dmesg (and current dmesg buffer) are captured elsewhere. Also removes shell syntax from the plugin. Related: Issue #<I>.
py
diff --git a/pdb.py b/pdb.py index <HASH>..<HASH> 100644 --- a/pdb.py +++ b/pdb.py @@ -1334,13 +1334,16 @@ except for when using the function decorator. filename = os.path.abspath(frame.f_code.co_filename) return filename, lineno - def _format_editcmd(self, editor, filename, lineno): + def _quote_filename(self, filename): try: - from shutil import quote + from shlex import quote except ImportError: from pipes import quote - filename = quote(filename) + return quote(filename) + + def _format_editcmd(self, editor, filename, lineno): + filename = self._quote_filename(filename) if "{filename}" in editor: return editor.format(filename=filename, lineno=lineno)
Factor out _quote_filename, fix preferred import (#<I>)
py
diff --git a/salt/states/pkg.py b/salt/states/pkg.py index <HASH>..<HASH> 100644 --- a/salt/states/pkg.py +++ b/salt/states/pkg.py @@ -666,7 +666,7 @@ def installed( hold_ret = __salt__['pkg.unhold']( name=name, pkgs=pkgs, sources=sources ) - except SaltInvocationError as exc: + except (CommandExecutionError, SaltInvocationError) as exc: return {'name': name, 'changes': {}, 'result': False, @@ -793,7 +793,7 @@ def installed( hold_ret = __salt__['pkg.unhold']( name=name, pkgs=pkgs, sources=sources ) - except SaltInvocationError as exc: + except (CommandExecutionError, SaltInvocationError) as exc: comment.append(exc.message) return {'name': name, 'changes': changes,
Add CommandExecutionError to exception handling aptpkg's set_selections (called by hold/unhold) could potentially raise this exception, so catch it as well.
py
diff --git a/greg/aux_functions.py b/greg/aux_functions.py index <HASH>..<HASH> 100755 --- a/greg/aux_functions.py +++ b/greg/aux_functions.py @@ -208,18 +208,6 @@ def get_date(line): return date -def transition(args, feed, feeds): - # A function to ease the transition to individual feed files - if "downloadfrom" in feeds[feed]: - edit({"downloadfrom": eval(feeds[feed]["downloadfrom"]), "name": feed}) - # edit() is usually called from the outside - DATA_DIR = retrieve_data_directory(args) - DATA_FILENAME = os.path.join(DATA_DIR, "data") - feeds.remove_option(feed, "downloadfrom") - with open(DATA_FILENAME, 'w') as configfile: - feeds.write(configfile) - - def download_handler(feed, placeholders): import shlex """
Deleting the prehistoric transition function
py
diff --git a/datascience/tables.py b/datascience/tables.py index <HASH>..<HASH> 100644 --- a/datascience/tables.py +++ b/datascience/tables.py @@ -774,7 +774,7 @@ class Table(collections.abc.MutableMapping): names = [op.__name__ for op in ops] ops = [_zero_on_type_error(op) for op in ops] columns = [[op(column) for op in ops] for column in self.columns] - table = Table(columns, self.labels) + table = Table().with_columns(zip(self.labels, columns)) stats = table._unused_label('statistic') table[stats] = names table.move_to_start(stats)
fix deprecation creation of table in stats
py
diff --git a/rest_framework_simplejwt/token_blacklist/models.py b/rest_framework_simplejwt/token_blacklist/models.py index <HASH>..<HASH> 100644 --- a/rest_framework_simplejwt/token_blacklist/models.py +++ b/rest_framework_simplejwt/token_blacklist/models.py @@ -1,14 +1,11 @@ -from django.contrib.auth import get_user_model +from django.conf import settings from django.db import models from django.utils.six import python_2_unicode_compatible -User = get_user_model() - - @python_2_unicode_compatible class OutstandingToken(models.Model): - user = models.ForeignKey(User, on_delete=models.CASCADE) + user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) jti = models.UUIDField(unique=True) token = models.TextField()
Fix broken tests in <I>-<I>
py
diff --git a/setuptools/tests/test_easy_install.py b/setuptools/tests/test_easy_install.py index <HASH>..<HASH> 100644 --- a/setuptools/tests/test_easy_install.py +++ b/setuptools/tests/test_easy_install.py @@ -170,6 +170,8 @@ class TestEasyInstallTest: sdist_zip.close() return str(sdist) + @pytest.mark.xfail(os.environ.get('LANG') == 'C', + reason="https://github.com/pypa/setuptools/issues/706") def test_unicode_filename_in_sdist(self, sdist_unicode, tmpdir, monkeypatch): """ The install command should execute correctly even if
Mark test as xfail. Ref #<I>.
py
diff --git a/salt/states/pyrax_queues.py b/salt/states/pyrax_queues.py index <HASH>..<HASH> 100644 --- a/salt/states/pyrax_queues.py +++ b/salt/states/pyrax_queues.py @@ -41,7 +41,6 @@ def present(name, provider): provider Salt Cloud Provider - ''' ret = {'name': name, 'result': True, 'comment': '', 'changes': {}}
missed one pylint
py
diff --git a/WrightTools/data/_data.py b/WrightTools/data/_data.py index <HASH>..<HASH> 100644 --- a/WrightTools/data/_data.py +++ b/WrightTools/data/_data.py @@ -1239,7 +1239,7 @@ class Data: ai = Ai(axi.points) Mi = mi(ai) # apply Mi to channel - self.channels[i].values /= Mi + self.channels[channel].values /= Mi # invert back out of the transpose t_inv = [t_order.index(j) for j in range(len(t_order))] if verbose:
M-factor fix data.m now normalizes the correct channel. resolves #<I>
py
diff --git a/tests/unit/modules/ddns_test.py b/tests/unit/modules/ddns_test.py index <HASH>..<HASH> 100644 --- a/tests/unit/modules/ddns_test.py +++ b/tests/unit/modules/ddns_test.py @@ -29,6 +29,9 @@ ddns.__grains__ = {} ddns.__salt__ = {} +@skipif(True, 'mocking dnspython without depending on it being installed' + 'requires more effort than unit testing the ddns module may be worth' + 'at this point. An integration test would be easy though.') @skipIf(NO_MOCK, NO_MOCK_REASON) class DDNSTestCase(TestCase): '''
fix ddns tests These tests will only work if dnspython is installed. Mocking away dnspython is a great amount of work, so we'll just disable these tests for now.
py
diff --git a/lib/meta/list.py b/lib/meta/list.py index <HASH>..<HASH> 100644 --- a/lib/meta/list.py +++ b/lib/meta/list.py @@ -417,7 +417,13 @@ class List(memory_region.MemoryRegion): bitlist = list() for i in xrange(len(self.declarations)): - instance = self.instantiate(i) + decl_hash = hash(self.declarations[i]) + + if self.instance_map.has_key(decl_hash): + instance = self.instance_map[decl_hash] + else: + instance = self.instantiate(decl_hash) + bitlist += instance.read_bits(instance.bitspan) return ''.join(map(chr, bitlist_to_bytelist(bitlist)))
read_memory culls from instance_map
py
diff --git a/setup.py b/setup.py index <HASH>..<HASH> 100755 --- a/setup.py +++ b/setup.py @@ -8,7 +8,7 @@ from pathlib import Path from setuptools import setup, find_packages ##################################### -VERSION = "0.7.3" +VERSION = "0.7.4" ISRELEASED = True if ISRELEASED: __version__ = VERSION
Bump to version <I>
py
diff --git a/vent/api/tools.py b/vent/api/tools.py index <HASH>..<HASH> 100644 --- a/vent/api/tools.py +++ b/vent/api/tools.py @@ -312,12 +312,6 @@ class Tools: # check and update links, volumes_from for container in list(tool_d.keys()): - for section in s: - if not 'groups' in s[section] or 'syslog' not in s[section]['groups']: - if not 'links' in tool_d[container]: - tool_d[container]['links'] = {'Syslog': 'syslog'} - else: - tool_d[container]['links']['Syslog'] = 'syslog' if 'links' in tool_d[container]: for link in list(tool_d[container]['links'].keys()): # add links to external services already running if @@ -563,7 +557,7 @@ class Tools: externally_configured = False if not externally_configured: log_config = {'type': 'syslog', - 'config': {'syslog-address': 'tcp://syslog:514', + 'config': {'syslog-address': 'tcp://0.0.0.0:514', 'syslog-facility': 'daemon', 'tag': '{{.Name}}'}} if 'groups' in s[section]:
move syslog back to host
py
diff --git a/representatives/templatetags/representatives_tags.py b/representatives/templatetags/representatives_tags.py index <HASH>..<HASH> 100644 --- a/representatives/templatetags/representatives_tags.py +++ b/representatives/templatetags/representatives_tags.py @@ -24,7 +24,7 @@ def chamber_icon(chamber): @register.filter def mandate_date(date, arg=None): - if date.year == 9999: + if date is None or date.year == 9999: return 'present' else: return naturalday(date, arg)
Mandate with no end date = present
py
diff --git a/ceph_deploy/cli.py b/ceph_deploy/cli.py index <HASH>..<HASH> 100644 --- a/ceph_deploy/cli.py +++ b/ceph_deploy/cli.py @@ -149,7 +149,7 @@ def _main(args=None, namespace=None): # File Logger fh = logging.FileHandler('{cluster}.log'.format(cluster=args.cluster)) fh.setLevel(logging.DEBUG) - fh.setFormatter(logging.Formatter(log.BASE_FORMAT)) + fh.setFormatter(logging.Formatter(log.FILE_FORMAT)) root_logger.addHandler(fh)
[RM-<I>] Use different log format for file logger
py
diff --git a/mtools/util/logfile.py b/mtools/util/logfile.py index <HASH>..<HASH> 100644 --- a/mtools/util/logfile.py +++ b/mtools/util/logfile.py @@ -310,7 +310,7 @@ class LogFile(InputSource): def _check_for_restart(self, logevent): - if logevent.thread == 'mongosMain': + if logevent.thread == 'mongosMain' and 'MongoS' in logevent.line_str: self._binary = 'mongos' elif logevent.thread == 'initandlisten' and "db version v" in logevent.line_str:
made version detection more stable, including enterprise builds (with ssl). Closes #<I>.
py
diff --git a/setup.py b/setup.py index <HASH>..<HASH> 100644 --- a/setup.py +++ b/setup.py @@ -8,7 +8,7 @@ try: except ImportError: from distutils.core import setup -__version__ = "1.2.2" +__version__ = "1.3.0" setup( name='django-tenants',
Update version number ready for pypi
py
diff --git a/salt/states/supervisord.py b/salt/states/supervisord.py index <HASH>..<HASH> 100644 --- a/salt/states/supervisord.py +++ b/salt/states/supervisord.py @@ -17,7 +17,7 @@ from __future__ import absolute_import # Import python libs import logging -import six +import salt.utils.six as six log = logging.getLogger(__name__)
Replaced import six in file /salt/states/supervisord.py
py
diff --git a/autoflake.py b/autoflake.py index <HASH>..<HASH> 100644 --- a/autoflake.py +++ b/autoflake.py @@ -6,7 +6,7 @@ import io import os -__version__ = '0.1' +__version__ = '0.1.1' PYFLAKES_BIN = 'pyflakes'
Increment patch version to <I>
py
diff --git a/salt/netapi/rest_cherrypy/app.py b/salt/netapi/rest_cherrypy/app.py index <HASH>..<HASH> 100644 --- a/salt/netapi/rest_cherrypy/app.py +++ b/salt/netapi/rest_cherrypy/app.py @@ -1432,19 +1432,18 @@ class Login(LowDataAdapter): try: eauth = self.opts.get('external_auth', {}).get(token['eauth'], {}) + # Get sum of '*' perms, user-specific perms, and group-specific perms + perms = eauth.get(token['name'], []) + perms.extend(eauth.get('*', [])) + if 'groups' in token: user_groups = set(token['groups']) eauth_groups = set([i.rstrip('%') for i in eauth.keys() if i.endswith('%')]) - perms = [] for group in user_groups & eauth_groups: perms.extend(eauth['{0}%'.format(group)]) - perms = perms or None - else: - perms = eauth.get(token['name'], eauth.get('*')) - - if perms is None: + if not perms: raise ValueError("Eauth permission list not found.") except (AttributeError, IndexError, KeyError, ValueError): logger.debug("Configuration for external_auth malformed for "
Return all relevant perms on login If the requesting user was in a group specified in the eauth config, then the return would only have the permissions allowed by their group memberships, even if there were specific permissions for that user or permissions for '*'. A user without any group permissions, but with user-specific permissions would also not get permissions for '*'. Now, the return should contain all relevant permissions for the requesting user.
py
diff --git a/src/scs_core/aws/config/project.py b/src/scs_core/aws/config/project.py index <HASH>..<HASH> 100644 --- a/src/scs_core/aws/config/project.py +++ b/src/scs_core/aws/config/project.py @@ -21,7 +21,7 @@ class Project(PersistentJSONable): # ---------------------------------------------------------------------------------------------------------------- - __FILENAME = "aws_project.json" + __FILENAME = "aws_project.json" @classmethod def persistence_location(cls):
Added text standardisation to aws_project.py
py
diff --git a/tableone.py b/tableone.py index <HASH>..<HASH> 100644 --- a/tableone.py +++ b/tableone.py @@ -212,8 +212,9 @@ class TableOne(object): grouped_data.append(data[v][data[self.strata_col]==s][data[v][data[self.strata_col]==s].notnull()].values) # minimum n across groups df.loc[v]['min_n'] = len(min(grouped_data,key=len)) - # compute p value - df.loc[v]['pval'],df.loc[v]['testname'] = self.__p_test(df,v,grouped_data,data) + if self.pval: + # compute p value + df.loc[v]['pval'],df.loc[v]['testname'] = self.__p_test(df,v,grouped_data,data) return df
don't compute pval if false. fixes #4
py
diff --git a/llvmlite/tests/test_refprune.py b/llvmlite/tests/test_refprune.py index <HASH>..<HASH> 100644 --- a/llvmlite/tests/test_refprune.py +++ b/llvmlite/tests/test_refprune.py @@ -206,6 +206,8 @@ define void @main(i8* %ptr) { def test_per_bb_2(self): mod, stats = self.check(self.per_bb_ir_2) self.assertEqual(stats.basicblock, 4) + # not pruned + self.assertIn("call void @NRT_incref(i8* %ptr)", str(mod)) per_bb_ir_3 = r""" define void @main(i8* %ptr, i8* %other) {
Add check in test as requested from code review
py
diff --git a/openquake/calculators/base.py b/openquake/calculators/base.py index <HASH>..<HASH> 100644 --- a/openquake/calculators/base.py +++ b/openquake/calculators/base.py @@ -607,7 +607,8 @@ class HazardCalculator(BaseCalculator): logging.info('Extracted %d/%d assets', len(self.assetcol), len(assetcol)) nsites = len(self.sitecol) - if nsites > MAXSITES: # hard-coded, heuristic + if (oq.spatial_correlation != 'no correlation' and + nsites > MAXSITES): # hard-coded, heuristic raise ValueError(CORRELATION_MATRIX_TOO_LARGE % nsites) elif hasattr(self, 'sitecol') and general.not_equal( self.sitecol.sids, haz_sitecol.sids):
Small fix [skip CI]
py
diff --git a/qiniustorage/backends.py b/qiniustorage/backends.py index <HASH>..<HASH> 100644 --- a/qiniustorage/backends.py +++ b/qiniustorage/backends.py @@ -91,7 +91,8 @@ class QiniuStorage(Storage): return name def _put_file(self, name, content): - ret, err = qiniu.io.put(self.put_policy.token(), name, content) + token = self.put_policy.token() + ret, err = qiniu.io.put(token, name, content) if err: raise IOError( "Failed to put file '%s'. "
Generate the put in a separeted line. Could be helpful for debugging.
py
diff --git a/tornado/template.py b/tornado/template.py index <HASH>..<HASH> 100644 --- a/tornado/template.py +++ b/tornado/template.py @@ -367,10 +367,9 @@ class Loader(BaseLoader): def _create_template(self, name): path = os.path.join(self.root, name) - f = open(path, "rb") - template = Template(f.read(), name=name, loader=self) - f.close() - return template + with open(path, "rb") as f: + template = Template(f.read(), name=name, loader=self) + return template class DictLoader(BaseLoader):
update Template Loader with 'with' statment
py
diff --git a/great_expectations/render/renderer/content_block/bullet_list_content_block.py b/great_expectations/render/renderer/content_block/bullet_list_content_block.py index <HASH>..<HASH> 100644 --- a/great_expectations/render/renderer/content_block/bullet_list_content_block.py +++ b/great_expectations/render/renderer/content_block/bullet_list_content_block.py @@ -1202,7 +1202,8 @@ class PrescriptiveBulletListContentBlockRenderer(ContentBlockRenderer): ["column", "partition_object", "threshold"] ) - styling.update({ + hist_styling = copy.deepcopy(styling) + hist_styling.update({ "params": { "sparklines_histogram": { "styles": { @@ -1226,7 +1227,7 @@ class PrescriptiveBulletListContentBlockRenderer(ContentBlockRenderer): return [{ "template": template_str, "params": params, - "styling": styling, + "styling": hist_styling, }] @classmethod
Fix styling present in every bullet list element
py
diff --git a/src/pyipmi/event.py b/src/pyipmi/event.py index <HASH>..<HASH> 100644 --- a/src/pyipmi/event.py +++ b/src/pyipmi/event.py @@ -4,9 +4,5 @@ # author: Heiko Thiery <heiko.thiery@kontron.com> # author: Michael Walle <michael.walle@kontron.com> # - -class Event: - DIR_ASSERTION = 0 - DIR_DEASSERTION = 1 - - +EVENT_ASSERTION = 0 +EVENT_DEASSERTION = 1
event: changed ASSERTION, DEASSERTION constants
py
diff --git a/setup.py b/setup.py index <HASH>..<HASH> 100644 --- a/setup.py +++ b/setup.py @@ -43,12 +43,12 @@ class PyTest(Command): requires = ["pymongo"] setup(name="minimongo", - version="0.2.6", + version="0.2.8b1", packages=find_packages(), cmdclass={"test": PyTest}, platforms=["any"], - install_requires = ["pymongo>=1.9"], + install_requires = ["pymongo>=2.4"], zip_safe=False, include_package_data=True,
Update setup.py Updated version and pymongo required version
py
diff --git a/paystackapi/tests/test_invoice.py b/paystackapi/tests/test_invoice.py index <HASH>..<HASH> 100644 --- a/paystackapi/tests/test_invoice.py +++ b/paystackapi/tests/test_invoice.py @@ -121,3 +121,20 @@ class TestInvoice(BaseTestCase): id_or_code="PRQ_kp4lleqc7g8xckk", ) self.assertTrue(response['status']) + + @httpretty.activate + def test_update(self): + """Method defined to test Invoice update.""" + httpretty.register_uri( + httpretty.PUT, + self.endpoint_url("/paymentrequest/PRQ_kp4lleqc7g8xckk"), + content_type='text/json', + body='{"status": true, "message": "Payment request updated"}', + status=201, + ) + + response = Invoice.update( + id_or_code="PRQ_kp4lleqc7g8xckk", + amount=450000 + ) + self.assertTrue(response['status'])
Add test case for finalize_draft invoice
py
diff --git a/tests/test_api.py b/tests/test_api.py index <HASH>..<HASH> 100644 --- a/tests/test_api.py +++ b/tests/test_api.py @@ -350,3 +350,21 @@ def test_formats(): assert '<' in str(data.xml) assert '<title>' in str(data.html) assert '\n' in str(data.as_list()) + + +@vcr.use_cassette +def test_phisheye(): + with api.phisheye('google') as data: + assert data['term'] == 'google' + for result in data: + assert result['domain'] + assert result['tld'] + + +@vcr.use_cassette +def test_phisheye_term_list(): + with api.phisheye_term_list() as data: + assert data + for term in data: + assert 'term' in term + assert type(term['active']) == bool
Add tests for new phisheye API endpoints
py
diff --git a/bedup/__main__.py b/bedup/__main__.py index <HASH>..<HASH> 100644 --- a/bedup/__main__.py +++ b/bedup/__main__.py @@ -113,6 +113,7 @@ def vol_cmd(args): sys.stderr.write( "The dedup-vol command is deprecated, please use dedup.\n") args.command = 'dedup' + args.defrag = False elif args.command == 'reset' and not args.filter: sys.stderr.write("You need to list volumes explicitly.\n") return 1 @@ -399,6 +400,7 @@ which displays the extent map of files. sp_dedup_files.add_argument('source', metavar='SRC', help='Source file') sp_dedup_files.add_argument( 'dests', metavar='DEST', nargs='+', help='Dest files') + # Don't forget to also set new options in the dedup-vol test in vol_cmd sp_dedup_files.add_argument( '--defrag', action='store_true', help='Defragment the source file first')
Fix the dedup-vol compat alias, which broke when --defrag was introduced.
py
diff --git a/setup.py b/setup.py index <HASH>..<HASH> 100644 --- a/setup.py +++ b/setup.py @@ -29,7 +29,7 @@ import subprocess import sys import sysconfig from contextlib import contextmanager -from setuptools import Extension, setup +from setuptools import setup from cy_build import CyExtension as Extension, cy_build_ext as build_ext try: import cython
Removal of unused import Import is overwritten in the next line with cy_build
py
diff --git a/cisco_aci/datadog_checks/cisco_aci/tenant.py b/cisco_aci/datadog_checks/cisco_aci/tenant.py index <HASH>..<HASH> 100644 --- a/cisco_aci/datadog_checks/cisco_aci/tenant.py +++ b/cisco_aci/datadog_checks/cisco_aci/tenant.py @@ -99,10 +99,12 @@ class Tenant: name = list(s.keys())[0] # we only want to collect the 15 minutes metrics. if '15min' not in name: + self.log.debug("Skipping metric: %s because it does not contain 15min in its name", name) continue attrs = s.get(name, {}).get("attributes", {}) if 'index' in attrs: + self.log.debug("Skipping metric: %s because it contains index in its attributes", name) continue self.log.debug("submitting metrics for: %s", name)
Add debug lines for support (#<I>) * Add debug lines for support * Add debug lines for support * Update cisco_aci/datadog_checks/cisco_aci/tenant.py
py
diff --git a/setup.py b/setup.py index <HASH>..<HASH> 100644 --- a/setup.py +++ b/setup.py @@ -1,10 +1,8 @@ -import os from setuptools import setup setup( name='turrentine', version = '0.0.1', description = 'A very simple CMS for Django', - long_description = open(os.path.join(os.path.dirname(__file__), 'README.rst')).read(), url = 'https://github/af/turrentine', author = 'Aaron Franks',
Remove setup.py long_description trickery.
py
diff --git a/neopixel.py b/neopixel.py index <HASH>..<HASH> 100644 --- a/neopixel.py +++ b/neopixel.py @@ -93,6 +93,18 @@ class NeoPixel(_pixelbuf.PixelBuf): with neopixel.NeoPixel(NEOPIXEL, 10) as pixels: pixels[::2] = [RED] * (len(pixels) // 2) time.sleep(2) + + .. py:method:: NeoPixel.show() + + Shows the new colors on the pixels themselves if they haven't already + been autowritten. + + The colors may or may not be showing after this function returns because + it may be done asynchronously. + + .. py:method:: NeoPixel.fill(color) + + Colors all pixels the given ***color***. """ bpp = None n = 0
add docs for methods on parent class
py
diff --git a/ftfy/fixes.py b/ftfy/fixes.py index <HASH>..<HASH> 100644 --- a/ftfy/fixes.py +++ b/ftfy/fixes.py @@ -636,10 +636,10 @@ def decode_escapes(text): # Other instances in Portuguese, such as "àfrica", seem to be typos (intended # to be "África" with the accent in the other direction). # -# Unfortunately, Catalan has many words beginning with "à" that will end up -# with a space inserted in them in this case. We can't do the right thing with -# all of them. The cost is that the mojibake text "à udio" will be interpreted -# as "à udio", not the Catalan word "àudio". +# Unfortunately, "à" is a common letter in Catalan, and mojibake of words that +# contain it will end up with inserted spaces. We can't do the right thing with +# every word. The cost is that the mojibake text "fà cil" will be interpreted as +# "fà cil", not "fàcil". A_GRAVE_WORD_RE = re.compile(b'\xc3 (?! |quele|quela|quilo|s )') def restore_byte_a0(byts):
clarify the problem with à in the middle of a word
py
diff --git a/salt/modules/win_file.py b/salt/modules/win_file.py index <HASH>..<HASH> 100644 --- a/salt/modules/win_file.py +++ b/salt/modules/win_file.py @@ -818,8 +818,10 @@ def stats(path, hash_type='sha256', follow_symlinks=True): salt '*' file.stats /etc/passwd ''' + # This is to mirror the behavior of file.py. `check_file_meta` expects an + # empty dictionary when the file does not exist if not os.path.exists(path): - raise CommandExecutionError('Path not found: {0}'.format(path)) + return {} if follow_symlinks and sys.getwindowsversion().major >= 6: path = _resolve_symlink(path) @@ -1556,6 +1558,13 @@ def check_perms(path, # Specify advanced attributes with a list salt '*' file.check_perms C:\\Temp\\ Administrators "{'jsnuffy': {'perms': ['read_attributes', 'read_ea'], 'applies_to': 'files_only'}}" ''' + # This is to work with the state module. + if not os.path.exists(path): + if ret: + return ret + else: + raise CommandExecutionError('The directory does not exist.') + path = os.path.expanduser(path) if not ret:
Return empty or unmodified dict on file not found Fixes issue with file.managed with test=True when the directory structure for the file is not there and makedirs=True
py
diff --git a/tests/unit/modules/blockdev_test.py b/tests/unit/modules/blockdev_test.py index <HASH>..<HASH> 100644 --- a/tests/unit/modules/blockdev_test.py +++ b/tests/unit/modules/blockdev_test.py @@ -57,16 +57,6 @@ class TestBlockdevModule(TestCase): with patch.dict(blockdev.__salt__, {'cmd.run': mock}): self.assertEqual(blockdev.fstype(device), fs_type) - def test_resize2fs(self): - ''' - unit tests for blockdev.resize2fs - ''' - device = '/dev/sdX1' - mock = MagicMock() - with patch.dict(blockdev.__salt__, {'cmd.run_all': mock}): - blockdev.resize2fs(device) - mock.assert_called_once_with('resize2fs {0}'.format(device), python_shell=False) - if __name__ == '__main__': from integration import run_tests
Remove test failing because of mocks -- it's deprecated anyway
py
diff --git a/furious/context.py b/furious/context.py index <HASH>..<HASH> 100644 --- a/furious/context.py +++ b/furious/context.py @@ -57,6 +57,18 @@ def new(): return new_context +def init_context_with_async(async): + """Instantiate a new JobContext and store a reference to it in the global + async context to make later retrieval easier.""" + if not _local_context._executing_async_context: + raise ContextExistsError + + _init() + job_context = JobContext(async) + _local_context._executing_async_context = job_context + return job_context + + def get_current_async(): """Return a reference to the currently executing Async job object or None if not in an Async job. @@ -178,7 +190,14 @@ def _init(): if hasattr(_local_context, '_initialized'): return + # Used to track the context object stack. _local_context.registry = [] + + # Used to provide easy access to the currently running Async job. + _local_context._executing_async_context = None + _local_context._executing_async = None + + # So that we do not inadvertently reinitialize the local context. _local_context._initialized = True return _local_context
Add setup and helper to initialize the eniviron with a job context.
py
diff --git a/tests/test_proxies.py b/tests/test_proxies.py index <HASH>..<HASH> 100644 --- a/tests/test_proxies.py +++ b/tests/test_proxies.py @@ -379,15 +379,33 @@ def test_this_deny_non_integers(): assert str(exc_info.value) == 'Positive integer argument is required' -def test_this_deny_negative_integers(): +negative_integers = CodeCollector() + + +@negative_integers.parametrize +def test_this_deny_negative_integers(code): """We can't shift `this` with negative integer.""" with pytest.raises(ValueError) as exc_info: - this << -1 + code() assert str(exc_info.value) == 'Positive integer argument is required' +@negative_integers +def xsJWb2lx6EMs(): + """Minus one.""" + + this << -1 + + +@negative_integers +def nvm3ybp98vGm(): + """Zero.""" + + this << 0 + + too_many = CodeCollector()
Test this left shift against zero and negative integers.
py
diff --git a/docx2html/tests/test_xml.py b/docx2html/tests/test_xml.py index <HASH>..<HASH> 100644 --- a/docx2html/tests/test_xml.py +++ b/docx2html/tests/test_xml.py @@ -42,7 +42,7 @@ def _create_p_tag(text, bold=False): t_tag = _create_t_tag(text) return DOCUMENT_P_TEMPLATE % { 'text': t_tag, - 'bold': _bold(bold), + 'bold': _bold(is_bold=bold), } @@ -52,7 +52,7 @@ def _create_li(text, ilvl, numId, bold=False): 'text': text, 'ilvl': ilvl, 'numId': numId, - 'bold': _bold(bold), + 'bold': _bold(is_bold=bold), } @@ -395,7 +395,7 @@ class ListWithContinuationTestCase(_TranslationTestCase): _create_li(text='AAA', ilvl=0, numId=1), DOCUMENT_P_TEMPLATE % { 'text': _create_t_tag('BBB'), - 'bold': _bold(False), + 'bold': _bold(is_bold=False), }, _create_li(text='CCC', ilvl=0, numId=1), table,
refs #5: used named kwargs
py