buggy
stringlengths
35
5.03k
fixed
stringlengths
46
62.5k
class HiveCommandClientTest(unittest.TestCase): returned = self.client.table_exists("mytable") self.assertTrue(returned) run_command.return_value = "day=2013-06-28/hour=3\n" \ "day=2013-06-28/hour=4\n" \ "day=2013-07-07/hour=...
class HiveCommandClientTest(unittest.TestCase): returned = self.client.table_exists("mytable") self.assertTrue(returned) # Issue #896 test case insensitivity returned = self.client.table_exists("MyTable") self.assertTrue(returned) run_command.return_value = "day=2013-06...
class HiveCommandClientTest(unittest.TestCase): returned = self.apacheclient.table_exists("mytable") self.assertTrue(returned) run_command.return_value = "day=2013-06-28/hour=3\n" \ "day=2013-06-28/hour=4\n" \ "day=2013-07-07...
class HiveCommandClientTest(unittest.TestCase): returned = self.apacheclient.table_exists("mytable") self.assertTrue(returned) # Issue #896 test case insensitivity returned = self.apacheclient.table_exists("MyTable") self.assertTrue(returned) run_command.return_value = ...
def get_openapi_path( operation_parameters = get_openapi_operation_parameters(all_route_params) parameters.extend(operation_parameters) if parameters: operation["parameters"] = parameters if method in METHODS_WITH_BODY: request_body_oai = g...
def get_openapi_path( operation_parameters = get_openapi_operation_parameters(all_route_params) parameters.extend(operation_parameters) if parameters: operation["parameters"] = list( {param["name"]: param for param in parameters}.values() ...
def _get_clickable(clickdata, form): """ clickables = [ el for el in form.xpath( 'descendant::*[(self::input or self::button)' ' and re:test(@type, "^submit$", "i")]' '|descendant::button[not(@type)]', namespaces={"re": "http://exslt.org/regular-expression...
def _get_clickable(clickdata, form): """ clickables = [ el for el in form.xpath( 'descendant::input[re:test(@type, "^(submit|image)$", "i")]' '|descendant::button[not(@type) or re:test(@type, "^submit$", "i")]', namespaces={"re": "http://exslt.org/regular-expressions"...
class FormRequestTest(RequestTest): req = self.request_class.from_response(response, dont_click=True) fs = _qs(req) self.assertEqual(fs, {b'i1': [b'i1v'], b'i2': [b'i2v']}) def test_from_response_multiple_clickdata(self): response = _buildresponse(
class FormRequestTest(RequestTest): req = self.request_class.from_response(response, dont_click=True) fs = _qs(req) self.assertEqual(fs, {b'i1': [b'i1v'], b'i2': [b'i2v']}) def test_from_response_clickdata_does_not_ignore_image(self): response = _buildresponse( """<f...
from django import http from django.template import Context, Engine, TemplateDoesNotExist, loader from django.utils import six from django.utils.encoding import force_text from django.views.decorators.csrf import requires_csrf_token ERROR_404_TEMPLATE_NAME = '404.html'
from django import http from django.template import Context, Engine, TemplateDoesNotExist, loader from django.utils import six from django.utils.encoding import force_text from django.utils.http import urlquote from django.views.decorators.csrf import requires_csrf_token ERROR_404_TEMPLATE_NAME = '404.html'
def page_not_found(request, exception, template_name=ERROR_404_TEMPLATE_NAME): Templates: :template:`404.html` Context: request_path The path of the requested URL (e.g., '/app/pages/bad_page/') exception The message from the exception which triggered the 404 (if one was ...
def page_not_found(request, exception, template_name=ERROR_404_TEMPLATE_NAME): Templates: :template:`404.html` Context: request_path The path of the requested URL (e.g., '/app/pages/bad_page/'). It's quoted to prevent a content injection attack. exception The ...
def page_not_found(request, exception, template_name=ERROR_404_TEMPLATE_NAME): if isinstance(message, six.text_type): exception_repr = message context = { 'request_path': request.path, 'exception': exception_repr, } try:
def page_not_found(request, exception, template_name=ERROR_404_TEMPLATE_NAME): if isinstance(message, six.text_type): exception_repr = message context = { 'request_path': urlquote(request.path), 'exception': exception_repr, } try:
def page_not_found(request, exception, template_name=ERROR_404_TEMPLATE_NAME): raise template = Engine().from_string( '<h1>Not Found</h1>' '<p>The requested URL {{ request_path }} was not found on this server.</p>') body = template.render(Context(context)) con...
def page_not_found(request, exception, template_name=ERROR_404_TEMPLATE_NAME): raise template = Engine().from_string( '<h1>Not Found</h1>' '<p>The requested resource was not found on this server.</p>') body = template.render(Context(context)) content_type = 't...
from __future__ import unicode_literals import unittest from django.core.exceptions import ImproperlyConfigured
from __future__ import unicode_literals import sys import unittest from django.core.exceptions import ImproperlyConfigured
try: except ImportError: # Python < 3.5 HTTPStatus = None class HandlerTests(SimpleTestCase):
try: except ImportError: # Python < 3.5 HTTPStatus = None PY37 = sys.version_info >= (3, 7, 0) class HandlerTests(SimpleTestCase):
class HandlerRequestTests(SimpleTestCase): def test_invalid_urls(self): response = self.client.get('~%A9helloworld') self.assertContains(response, '~%A9helloworld', status_code=404) response = self.client.get('d%aao%aaw%aan%aal%aao%aaa%aad%aa/') self.assertContains(response, 'd%AAo...
class HandlerRequestTests(SimpleTestCase): def test_invalid_urls(self): response = self.client.get('~%A9helloworld') self.assertEqual(response.status_code, 404) self.assertEqual(response.context['request_path'], '/~%25A9helloworld' if PY37 else '/%7E%25A9helloworld') response = sel...
import sys import tarfile import threading import time import zipfile from abc import abstractmethod from multiprocessing.pool import ThreadPool
import sys import tarfile import threading import time import traceback import zipfile from abc import abstractmethod from multiprocessing.pool import ThreadPool
class OrderedEnqueuer(SequenceEnqueuer): yield inputs except Exception as e: self.stop() raise StopIteration(e) def _send_sequence(self): """Send current Sequence to all workers."""
class OrderedEnqueuer(SequenceEnqueuer): yield inputs except Exception as e: self.stop() six.raise_from(StopIteration(e), e) def _send_sequence(self): """Send current Sequence to all workers."""
class GeneratorEnqueuer(SequenceEnqueuer): self._use_multiprocessing = use_multiprocessing self._threads = [] self._stop_event = None self.queue = None self.seed = seed
class GeneratorEnqueuer(SequenceEnqueuer): self._use_multiprocessing = use_multiprocessing self._threads = [] self._stop_event = None self._manager = None self.queue = None self.seed = seed
class GeneratorEnqueuer(SequenceEnqueuer): try: if self._use_multiprocessing or self.queue.qsize() < max_queue_size: generator_output = next(self._generator) self.queue.put(generator_output) else: ...
class GeneratorEnqueuer(SequenceEnqueuer): try: if self._use_multiprocessing or self.queue.qsize() < max_queue_size: generator_output = next(self._generator) self.queue.put((True, generator_output)) else: ...
class GeneratorEnqueuer(SequenceEnqueuer): else: thread.join(timeout) if self._use_multiprocessing: if self.queue is not None: self.queue.close() self._threads = [] self._stop_event = None
class GeneratorEnqueuer(SequenceEnqueuer): else: thread.join(timeout) if self._manager: self._manager.shutdown() self._threads = [] self._stop_event = None
class GeneratorEnqueuer(SequenceEnqueuer): """ while self.is_running(): if not self.queue.empty(): inputs = self.queue.get() if inputs is not None: yield inputs else: all_finished = all([not thread.is_alive() for...
class GeneratorEnqueuer(SequenceEnqueuer): """ while self.is_running(): if not self.queue.empty(): success, value = self.queue.get() # Rethrow any exceptions found in the queue if not success: six.reraise(value.__class__, va...
def test_generator_enqueuer_fail_threads(): FaultSequence()), use_multiprocessing=False) enqueuer.start(3, 10) gen_output = enqueuer.get() with pytest.raises(StopIteration): next(gen_output)
def test_generator_enqueuer_fail_threads(): FaultSequence()), use_multiprocessing=False) enqueuer.start(3, 10) gen_output = enqueuer.get() with pytest.raises(IndexError): next(gen_output)
def test_generator_enqueuer_fail_processes(): FaultSequence()), use_multiprocessing=True) enqueuer.start(3, 10) gen_output = enqueuer.get() with pytest.raises(StopIteration): next(gen_output)
def test_generator_enqueuer_fail_processes(): FaultSequence()), use_multiprocessing=True) enqueuer.start(3, 10) gen_output = enqueuer.get() with pytest.raises(IndexError): next(gen_output)
def test_multiprocessing_fit_error(): """Raises an exception after a few good batches""" for i in range(good_batches): yield (np.random.randint(batch_size, 256, (50, 2)), np.random.randint(batch_size, 2, 50)) raise RuntimeError model = Sequential()
def test_multiprocessing_fit_error(): """Raises an exception after a few good batches""" for i in range(good_batches): yield (np.random.randint(batch_size, 256, (50, 2)), np.random.randint(batch_size, 12, 50)) raise RuntimeError model = Sequential()
def test_multiprocessing_fit_error(): samples = batch_size * (good_batches + 1) with pytest.raises(StopIteration): model.fit_generator( custom_generator(), samples, 1, workers=4, use_multiprocessing=True, ) with pytest.raises(StopIteration): model.fit_gener...
def test_multiprocessing_fit_error(): samples = batch_size * (good_batches + 1) with pytest.raises(RuntimeError): model.fit_generator( custom_generator(), samples, 1, workers=4, use_multiprocessing=True, ) with pytest.raises(RuntimeError): model.fit_generat...
def test_multiprocessing_fit_error(): def test_multiprocessing_evaluate_error(): batch_size = 10 good_batches = 3 def custom_generator(): """Raises an exception after a few good batches""" for i in range(good_batches): yield (np.random.randint(batch_size, 256, (50, 2)), ...
def test_multiprocessing_fit_error(): def test_multiprocessing_evaluate_error(): batch_size = 10 good_batches = 3 workers = 4 def custom_generator(): """Raises an exception after a few good batches""" for i in range(good_batches): yield (np.random.randint(batch_size, 256, (5...
def test_multiprocessing_predict_error(): model.add(Dense(1, input_shape=(5,))) model.compile(loss='mse', optimizer='adadelta') with pytest.raises(StopIteration): model.predict_generator( custom_generator(), good_batches * workers + 1, 1, workers=workers, use_multiprocessing...
def test_multiprocessing_predict_error(): model.add(Dense(1, input_shape=(5,))) model.compile(loss='mse', optimizer='adadelta') with pytest.raises(RuntimeError): model.predict_generator( custom_generator(), good_batches * workers + 1, 1, workers=workers, use_multiprocessing=...
notes: rules. This should work out in most cases, but it is theoretically possible to see spurious changes when target and actual values are semantically identical but lexically distinct. version_added: '2.3' author: - Jiri Tyr (@jtyr)
notes: rules. This should work out in most cases, but it is theoretically possible to see spurious changes when target and actual values are semantically identical but lexically distinct. - "The I(params) parameter is deprecated in Ansible-2.7 due to circumventing Ansible's parameter handling. The I(...
options: a list of strings (see examples). type: raw required: true params: description: - Additional module parameters. type: dict extends_documentation_fragment: - ldap.documentation '''
options: a list of strings (see examples). type: raw required: true extends_documentation_fragment: - ldap.documentation '''
EXAMPLES = r''' # server_uri: ldap://localhost/ # bind_dn: cn=admin,dc=example,dc=com # bind_pw: password - name: Get rid of an unneeded attribute ldap_attr: dn: uid=jdoe,ou=people,dc=example,dc=com name: shadowExpire values: [] state: exact params: "{{ ldap_auth }}" ''' RETURN = r'''
EXAMPLES = r''' # server_uri: ldap://localhost/ # bind_dn: cn=admin,dc=example,dc=com # bind_pw: password # # In the example below, 'args' is a task keyword, passed at the same level as the module - name: Get rid of an unneeded attribute ldap_attr: dn: uid=jdoe,ou=people,dc=example,dc=com name: shadowEx...
modlist: ''' import traceback from ansible.module_utils.basic import AnsibleModule, missing_required_lib from ansible.module_utils._text import to_native, to_bytes
modlist: ''' import traceback from distutils.version import LooseVersion from ansible.module_utils.basic import AnsibleModule, missing_required_lib from ansible.module_utils._text import to_native, to_bytes
def main(): module.fail_json(msg=missing_required_lib('python-ldap'), exception=LDAP_IMP_ERR) # Update module parameters with user's parameters if defined if 'params' in module.params and isinstance(module.params['params'], dict): module.params.update(module.params['par...
def main(): module.fail_json(msg=missing_required_lib('python-ldap'), exception=LDAP_IMP_ERR) # For Ansible-2.9.x and below, allow the params module parameter with a warning if LooseVersion(module.ansible_version) < LooseVersion('2.10'): if module.params['params']: ...
notes: rule allowing root to modify the server configuration. If you need to use a simple bind to access your server, pass the credentials in I(bind_dn) and I(bind_pw). version_added: '2.3' author: - Jiri Tyr (@jtyr)
notes: rule allowing root to modify the server configuration. If you need to use a simple bind to access your server, pass the credentials in I(bind_dn) and I(bind_pw). - "The I(params) parameter is deprecated in Ansible-2.7 due to circumventing Ansible's parameter handling. The I(params) parameter s...
options: - If I(state=present), value or list of values to use when creating the entry. It can either be a string or an actual list of strings. params: description: - List of options which allows to overwrite any of the task or the I(attributes) options. To remove an option, se...
options: - If I(state=present), value or list of values to use when creating the entry. It can either be a string or an actual list of strings. state: description: - The target state of the entry.
EXAMPLES = """ # server_uri: ldap://localhost/ # bind_dn: cn=admin,dc=example,dc=com # bind_pw: password - name: Get rid of an old entry ldap_entry: dn: ou=stuff,dc=example,dc=com state: absent params: "{{ ldap_auth }}" """
EXAMPLES = """ # server_uri: ldap://localhost/ # bind_dn: cn=admin,dc=example,dc=com # bind_pw: password # # In the example below, 'args' is a task keyword, passed at the same level as the module - name: Get rid of an old entry ldap_entry: dn: ou=stuff,dc=example,dc=com state: absent args: "{{ ldap_au...
RETURN = """ """ import traceback from ansible.module_utils.basic import AnsibleModule, missing_required_lib from ansible.module_utils.six import string_types
RETURN = """ """ import traceback from distutils.version import LooseVersion from ansible.module_utils.basic import AnsibleModule, missing_required_lib from ansible.module_utils.six import string_types
def main(): module.fail_json(msg=missing_required_lib('python-ldap'), exception=LDAP_IMP_ERR) state = module.params['state'] # Check if objectClass is present when needed
def main(): module.fail_json(msg=missing_required_lib('python-ldap'), exception=LDAP_IMP_ERR) # For Ansible-2.9.x and below, allow the params module parameter with a warning if LooseVersion(module.ansible_version) < LooseVersion('2.10'): if module.params['params']: ...
def main(): isinstance(module.params['objectClass'], list))): module.fail_json(msg="objectClass must be either a string or a list.") # Update module parameters with user's parameters if defined if 'params' in module.params and isinstance(module.params['params'], dict): for key, ...
def main(): isinstance(module.params['objectClass'], list))): module.fail_json(msg="objectClass must be either a string or a list.") # Instantiate the LdapEntry object ldap = LdapEntry(module)
from bisect import bisect from hashlib import md5 DEFAULT_MEMCACHED_PORT = 11211 CONN_TIMEOUT = 0.3 IO_TIMEOUT = 2.0 PICKLE_FLAG = 1 NODE_WEIGHT = 50 PICKLE_PROTOCOL = 2 TRY_COUNT = 3
from bisect import bisect from hashlib import md5 try: import simplejson as json except ImportError: import json DEFAULT_MEMCACHED_PORT = 11211 CONN_TIMEOUT = 0.3 IO_TIMEOUT = 2.0 PICKLE_FLAG = 1 JSON_FLAG = 2 NODE_WEIGHT = 50 PICKLE_PROTOCOL = 2 TRY_COUNT = 3
class MemcacheRing(object): """ def __init__(self, servers, connect_timeout=CONN_TIMEOUT, io_timeout=IO_TIMEOUT, tries=TRY_COUNT): self._ring = {} self._errors = dict(((serv, []) for serv in servers)) self._error_limited = dict(((serv, 0) for serv in servers))
class MemcacheRing(object): """ def __init__(self, servers, connect_timeout=CONN_TIMEOUT, io_timeout=IO_TIMEOUT, tries=TRY_COUNT, allow_pickle=False, allow_unpickle=False): self._ring = {} self._errors = dict(((serv, []) for serv in servers)) self._erro...
def __init__(self, servers, connect_timeout=CONN_TIMEOUT, self._client_cache = dict(((server, []) for server in servers)) self._connect_timeout = connect_timeout self._io_timeout = io_timeout def _exception_occurred(self, server, e, action='talking'): if isinstance(e, socket.timeout...
def __init__(self, servers, connect_timeout=CONN_TIMEOUT, self._client_cache = dict(((server, []) for server in servers)) self._connect_timeout = connect_timeout self._io_timeout = io_timeout self._allow_pickle = allow_pickle self._allow_unpickle = allow_unpickle or allow_pickle ...
def set(self, key, value, serialize=True, timeout=0): :param key: key :param value: value :param serialize: if True, value is pickled before sending to memcache :param timeout: ttl in memcache """ key = md5hash(key) if timeout > 0: timeout += time.tim...
def set(self, key, value, serialize=True, timeout=0): :param key: key :param value: value :param serialize: if True, value is serialized with JSON before sending to memcache, or with pickle if configured to use pickle instead of JSON (to avoid...
def set(self, key, value, serialize=True, timeout=0): def get(self, key): """ Gets the object specified by key. It will also unpickle the object before returning if it is pickled in memcache. :param key: key :returns: value of the key in memcache
def set(self, key, value, serialize=True, timeout=0): def get(self, key): """ Gets the object specified by key. It will also unserialize the object before returning if it is serialized in memcache with JSON, or if it is pickled and unpickling is allowed. :param key: key ...
def get(self, key): size = int(line[3]) value = fp.read(size) if int(line[2]) & PICKLE_FLAG: value = pickle.loads(value) fp.readline() line = fp.readline().strip().split() ...
def get(self, key): size = int(line[3]) value = fp.read(size) if int(line[2]) & PICKLE_FLAG: if self._allow_unpickle: value = pickle.loads(value) else: ...
def set_multi(self, mapping, server_key, serialize=True, timeout=0): :param mapping: dictonary of keys and values to be set in memcache :param servery_key: key to use in determining which server in the ring is used :param serialize: if True, value is pickled before se...
def set_multi(self, mapping, server_key, serialize=True, timeout=0): :param mapping: dictonary of keys and values to be set in memcache :param servery_key: key to use in determining which server in the ring is used :param serialize: if True, value is serialized with J...
def set_multi(self, mapping, server_key, serialize=True, timeout=0): for key, value in mapping.iteritems(): key = md5hash(key) flags = 0 if serialize: value = pickle.dumps(value, PICKLE_PROTOCOL) flags |= PICKLE_FLAG msg += ('set %s...
def set_multi(self, mapping, server_key, serialize=True, timeout=0): for key, value in mapping.iteritems(): key = md5hash(key) flags = 0 if serialize and self._allow_pickle: value = pickle.dumps(value, PICKLE_PROTOCOL) flags |= PICKLE_FLAG ...
def get_multi(self, keys, server_key): size = int(line[3]) value = fp.read(size) if int(line[2]) & PICKLE_FLAG: value = pickle.loads(value) responses[line[1]] = value fp.re...
def get_multi(self, keys, server_key): size = int(line[3]) value = fp.read(size) if int(line[2]) & PICKLE_FLAG: if self._allow_unpickle: value = pickle.loads(value) ...
class MemcacheMiddleware(object): def __init__(self, app, conf): self.app = app self.memcache_servers = conf.get('memcache_servers') if not self.memcache_servers: path = os.path.join(conf.get('swift_dir', '/etc/swift'), 'memcache.conf') ...
class MemcacheMiddleware(object): def __init__(self, app, conf): self.app = app self.memcache_servers = conf.get('memcache_servers') serialization_format = conf.get('memcache_serialization_support') if not self.memcache_servers or serialization_format is None: path = os....
def get(self, section, option): if section == 'memcache': if option == 'memcache_servers': return '1.2.3.4:5' else: raise NoOptionError(option) else:
def get(self, section, option): if section == 'memcache': if option == 'memcache_servers': return '1.2.3.4:5' elif option == 'memcache_serialization_support': return '2' else: raise NoOptionError(option) else:
def test_conf_set_no_read(self): exc = None try: app = memcache.MemcacheMiddleware( FakeApp(), {'memcache_servers': '1.2.3.4:5'}) except Exception, err: exc = err finally:
def test_conf_set_no_read(self): exc = None try: app = memcache.MemcacheMiddleware( FakeApp(), {'memcache_servers': '1.2.3.4:5', 'memcache_serialization_support': '2'}) except Exception, err: exc = err finally:
# Copyright (c) 2010-2012 OpenStack, LLC. # # Licensed under the Apache License, Version 2.0 (the "License");
# -*- coding: utf8 -*- # Copyright (c) 2010-2012 OpenStack, LLC. # # Licensed under the Apache License, Version 2.0 (the "License");
def test_set_get(self): self.assertEquals(memcache_client.get('some_key'), [1, 2, 3]) memcache_client.set('some_key', [4, 5, 6]) self.assertEquals(memcache_client.get('some_key'), [4, 5, 6]) self.assert_(float(mock.cache.values()[0][1]) == 0) esttimeout = time.time() + 10 ...
def test_set_get(self): self.assertEquals(memcache_client.get('some_key'), [1, 2, 3]) memcache_client.set('some_key', [4, 5, 6]) self.assertEquals(memcache_client.get('some_key'), [4, 5, 6]) memcache_client.set('some_key', ['simple str', 'utf8 str éà']) # As per http://wiki.opens...
def test_multi(self): self.assertEquals(memcache_client.get_multi(('some_key2', 'some_key1', 'not_exists'), 'multi_key'), [[4, 5, 6], [1, 2, 3], None]) if __name__ == '__main__': unittest.main()
def test_multi(self): self.assertEquals(memcache_client.get_multi(('some_key2', 'some_key1', 'not_exists'), 'multi_key'), [[4, 5, 6], [1, 2, 3], None]) def test_serialization(self): memcache_client = memcached.MemcacheRing(['1.2.3.4:11211'], ...
from keystone import exception from keystone import policy from keystone import token from keystone.common import manager from keystone.common import wsgi CONF = config.CONF class Manager(manager.Manager): """Default pivot point for the Identity backend.
from keystone import exception from keystone import policy from keystone import token from keystone.common import logging from keystone.common import manager from keystone.common import wsgi CONF = config.CONF LOG = logging.getLogger(__name__) class Manager(manager.Manager): """Default pivot point for the Iden...
def set_user_enabled(self, context, user_id, user): return self.update_user(context, user_id, user) def set_user_password(self, context, user_id, user): return self.update_user(context, user_id, user) def update_user_tenant(self, context, user_id, user): """Update the default tenant.""...
def set_user_enabled(self, context, user_id, user): return self.update_user(context, user_id, user) def set_user_password(self, context, user_id, user): user_ref = self.update_user(context, user_id, user) try: for token_id in self.token_api.list_tokens(context, user_id): ...
def delete_token(self, token_id): return self.db.delete('token-%s' % token_id) except KeyError: raise exception.TokenNotFound(token_id=token_id)
def delete_token(self, token_id): return self.db.delete('token-%s' % token_id) except KeyError: raise exception.TokenNotFound(token_id=token_id) def list_tokens(self, user_id): tokens = [] now = datetime.datetime.utcnow() for token, user_ref in self.db.items(...
def delete_token(self, token_id): with session.begin(): session.delete(token_ref) session.flush()
def delete_token(self, token_id): with session.begin(): session.delete(token_ref) session.flush() def list_tokens(self, user_id): session = self.get_session() tokens = [] now = datetime.datetime.utcnow() for token_ref in session.query(TokenModel)\ ...
def delete_token(self, token_id): """ raise exception.NotImplemented() def _get_default_expire_time(self): """Determine when a token should expire based on the config.
def delete_token(self, token_id): """ raise exception.NotImplemented() def list_tokens(self, user_id): """Returns a list of current token_id's for a user :param user_id: identity of the user :type user_id: string :returns: list of token_id's """ rai...
def test_invalid_user_password(self): username='blah', password='blah') def test_user_create_update_delete(self): from keystoneclient import exceptions as client_exceptions
def test_invalid_user_password(self): username='blah', password='blah') def test_change_password_invalidates_token(self): from keystoneclient import exceptions as client_exceptions client = self.get_client(admin=True) username = uuid.uui...
from pandas._libs import NaT, Timestamp, algos as libalgos, lib, tslib, writers import pandas._libs.internals as libinternals from pandas._libs.tslibs import Timedelta, conversion from pandas._libs.tslibs.timezones import tz_compare from pandas.util._validators import validate_bool_kwarg from pandas.core.dtypes.cast i...
from pandas._libs import NaT, Timestamp, algos as libalgos, lib, tslib, writers import pandas._libs.internals as libinternals from pandas._libs.tslibs import Timedelta, conversion from pandas._libs.tslibs.timezones import tz_compare from pandas._typing import ArrayLike from pandas.util._validators import validate_bool_...
class Block(PandasObject): def set(self, locs, values): """ Modify Block in-place with new item value Returns ------- None """ self.values[locs] = values
class Block(PandasObject): def set(self, locs, values): """ Modify block values in-place with new item value. Notes ----- `set` never creates a new array or new Block, whereas `setitem` _may_ create a new array and always creates a new Block. """ sel...
class Block(PandasObject): def setitem(self, indexer, value): """ Set the value inplace, returning a a maybe different typed block. Parameters ----------
class Block(PandasObject): def setitem(self, indexer, value): """ Attempt self.values[indexer] = value, possibly creating a new array. Parameters ----------
class ExtensionBlock(Block): raise IndexError(f"{self} only contains one item") return self.values def should_store(self, value): return isinstance(value, self._holder) def set(self, locs, values, check=False): assert locs.tolist() == [0] self.values = value...
class ExtensionBlock(Block): raise IndexError(f"{self} only contains one item") return self.values def should_store(self, value: ArrayLike) -> bool: """ Can we set the given array-like value inplace? """ return isinstance(value, self._holder) def set...
class ExtensionBlock(Block): def setitem(self, indexer, value): """ Set the value inplace, returning a same-typed block. This differs from Block.setitem by not allowing setitem to change the dtype of the Block.
class ExtensionBlock(Block): def setitem(self, indexer, value): """ Attempt self.values[indexer] = value, possibly creating a new array. This differs from Block.setitem by not allowing setitem to change the dtype of the Block.
class FloatBlock(FloatOrComplexBlock): ) return formatter.get_result_as_array() def should_store(self, value) -> bool: # when inserting a column should not coerce integers to floats # unnecessarily return issubclass(value.dtype.type, np.floating) and value.dtype == self.dtyp...
class FloatBlock(FloatOrComplexBlock): ) return formatter.get_result_as_array() def should_store(self, value: ArrayLike) -> bool: # when inserting a column should not coerce integers to floats # unnecessarily return issubclass(value.dtype.type, np.floating) and value.dtype =...
class ComplexBlock(FloatOrComplexBlock): element, (float, int, complex, np.float_, np.int_) ) and not isinstance(element, (bool, np.bool_)) def should_store(self, value) -> bool: return issubclass(value.dtype.type, np.complexfloating)
class ComplexBlock(FloatOrComplexBlock): element, (float, int, complex, np.float_, np.int_) ) and not isinstance(element, (bool, np.bool_)) def should_store(self, value: ArrayLike) -> bool: return issubclass(value.dtype.type, np.complexfloating)
class IntBlock(NumericBlock): ) return is_integer(element) def should_store(self, value) -> bool: return is_integer_dtype(value) and value.dtype == self.dtype
class IntBlock(NumericBlock): ) return is_integer(element) def should_store(self, value: ArrayLike) -> bool: return is_integer_dtype(value) and value.dtype == self.dtype
class DatetimeLikeBlockMixin: def _holder(self): return DatetimeArray @property def fill_value(self): return np.datetime64("NaT", "ns")
class DatetimeLikeBlockMixin: def _holder(self): return DatetimeArray def should_store(self, value): return is_dtype_equal(self.dtype, value.dtype) @property def fill_value(self): return np.datetime64("NaT", "ns")
class DatetimeBlock(DatetimeLikeBlockMixin, Block): ).reshape(i8values.shape) return np.atleast_2d(result) def should_store(self, value) -> bool: return is_datetime64_dtype(value.dtype) def set(self, locs, values): """ Modify Block in-place with new item value ...
class DatetimeBlock(DatetimeLikeBlockMixin, Block): ).reshape(i8values.shape) return np.atleast_2d(result) def set(self, locs, values): """ See Block.set.__doc__ """ values = conversion.ensure_datetime64ns(values, copy=False)
class DatetimeTZBlock(ExtensionBlock, DatetimeBlock): _can_hold_element = DatetimeBlock._can_hold_element to_native_types = DatetimeBlock.to_native_types fill_value = np.datetime64("NaT", "ns") @property def _holder(self):
class DatetimeTZBlock(ExtensionBlock, DatetimeBlock): _can_hold_element = DatetimeBlock._can_hold_element to_native_types = DatetimeBlock.to_native_types fill_value = np.datetime64("NaT", "ns") should_store = DatetimeBlock.should_store @property def _holder(self):
class TimeDeltaBlock(DatetimeLikeBlockMixin, IntBlock): ) return super().fillna(value, **kwargs) def should_store(self, value) -> bool: return is_timedelta64_dtype(value.dtype) def to_native_types(self, slicer=None, na_rep=None, quoting=None, **kwargs): """ convert to our n...
class TimeDeltaBlock(DatetimeLikeBlockMixin, IntBlock): ) return super().fillna(value, **kwargs) def to_native_types(self, slicer=None, na_rep=None, quoting=None, **kwargs): """ convert to our native types format, slicing if desired """ values = self.values
class BoolBlock(NumericBlock): return issubclass(tipo.type, np.bool_) return isinstance(element, (bool, np.bool_)) def should_store(self, value) -> bool: return issubclass(value.dtype.type, np.bool_) and not is_extension_array_dtype( value )
class BoolBlock(NumericBlock): return issubclass(tipo.type, np.bool_) return isinstance(element, (bool, np.bool_)) def should_store(self, value: ArrayLike) -> bool: return issubclass(value.dtype.type, np.bool_) and not is_extension_array_dtype( value )
class ObjectBlock(Block): def _can_hold_element(self, element: Any) -> bool: return True def should_store(self, value) -> bool: return not ( issubclass( value.dtype.type,
class ObjectBlock(Block): def _can_hold_element(self, element: Any) -> bool: return True def should_store(self, value: ArrayLike) -> bool: return not ( issubclass( value.dtype.type,
class CategoricalBlock(ExtensionBlock): def _holder(self): return Categorical def to_native_types(self, slicer=None, na_rep="", quoting=None, **kwargs): """ convert to our native types format, slicing if desired """ values = self.values
class CategoricalBlock(ExtensionBlock): def _holder(self): return Categorical def should_store(self, arr: ArrayLike): return isinstance(arr, self._holder) and is_dtype_equal(self.dtype, arr.dtype) def to_native_types(self, slicer=None, na_rep="", quoting=None, **kwargs): """ conver...
class TestiLoc2: result = s.iloc[np.array(0)] assert result == 1 class TestILocSetItemDuplicateColumns: def test_iloc_setitem_scalar_duplicate_columns(self):
class TestiLoc2: result = s.iloc[np.array(0)] assert result == 1 def test_iloc_setitem_categorical_updates_inplace(self): # Mixed dtype ensures we go through take_split_path in setitem_with_indexer cat = pd.Categorical(["A", "B", "C"]) df = pd.DataFrame({1: cat, 2: [1, 2, 3]...
class TestCanHoldElement: tm.assert_series_equal(result, expected) @pytest.mark.parametrize( "typestr, holder", [
class TestCanHoldElement: tm.assert_series_equal(result, expected) class TestShouldStore: def test_should_store_categorical(self): cat = pd.Categorical(["A", "B", "C"]) df = pd.DataFrame(cat) blk = df._data.blocks[0] # matching dtype assert blk.should_store(cat...
MSG_USERAUTH_INFO_REQUEST, MSG_USERAUTH_INFO_RESPONSE = range(60, 62) MSG_USERAUTH_GSSAPI_RESPONSE, MSG_USERAUTH_GSSAPI_TOKEN = range(60, 62) MSG_USERAUTH_GSSAPI_EXCHANGE_COMPLETE, MSG_USERAUTH_GSSAPI_ERROR,\ MSG_USERAUTH_GSSAPI_ERRTOK, MSG_USERAUTH_GSSAPI_MIC = range(63, 67) MSG_GLOBAL_REQUEST, MSG_REQUEST_SUCCESS...
MSG_USERAUTH_INFO_REQUEST, MSG_USERAUTH_INFO_RESPONSE = range(60, 62) MSG_USERAUTH_GSSAPI_RESPONSE, MSG_USERAUTH_GSSAPI_TOKEN = range(60, 62) MSG_USERAUTH_GSSAPI_EXCHANGE_COMPLETE, MSG_USERAUTH_GSSAPI_ERROR,\ MSG_USERAUTH_GSSAPI_ERRTOK, MSG_USERAUTH_GSSAPI_MIC = range(63, 67) HIGHEST_USERAUTH_MESSAGE_ID = 79 MSG_GL...
from paramiko.common import ( MSG_CHANNEL_FAILURE, MSG_CHANNEL_DATA, MSG_CHANNEL_EXTENDED_DATA, MSG_CHANNEL_WINDOW_ADJUST, MSG_CHANNEL_REQUEST, MSG_CHANNEL_EOF, MSG_CHANNEL_CLOSE, MIN_WINDOW_SIZE, MIN_PACKET_SIZE, MAX_WINDOW_SIZE, DEFAULT_WINDOW_SIZE, DEFAULT_MAX_PACKET_SIZE, ) from paramiko.compress im...
from paramiko.common import ( MSG_CHANNEL_FAILURE, MSG_CHANNEL_DATA, MSG_CHANNEL_EXTENDED_DATA, MSG_CHANNEL_WINDOW_ADJUST, MSG_CHANNEL_REQUEST, MSG_CHANNEL_EOF, MSG_CHANNEL_CLOSE, MIN_WINDOW_SIZE, MIN_PACKET_SIZE, MAX_WINDOW_SIZE, DEFAULT_WINDOW_SIZE, DEFAULT_MAX_PACKET_SIZE, HIGHEST_USERAUTH_MESSAGE_ID...
class Transport(threading.Thread, ClosingContextManager): max_packet_size = self.default_max_packet_size return clamp_value(MIN_PACKET_SIZE, max_packet_size, MAX_WINDOW_SIZE) def run(self): # (use the exposed "run" method, because if we specify a thread target
class Transport(threading.Thread, ClosingContextManager): max_packet_size = self.default_max_packet_size return clamp_value(MIN_PACKET_SIZE, max_packet_size, MAX_WINDOW_SIZE) def _ensure_authed(self, ptype, message): """ Checks message type against current auth state. I...
class Transport(threading.Thread, ClosingContextManager): continue if ptype in self._handler_table: self._handler_table[ptype](self, m) elif ptype in self._channel_handler_table: chanid = m.get_int() ...
class Transport(threading.Thread, ClosingContextManager): continue if ptype in self._handler_table: error_msg = self._ensure_authed(ptype, m) if error_msg: self._send_message(error_msg) ...
class SeriesGroupBy(GroupBy): res, out = np.zeros(len(ri), dtype=out.dtype), res res[ids[idx]] = out return Series(res, index=ri, name=self._selection_name) @Appender(Series.describe.__doc__) def describe(self, **kwargs):
class SeriesGroupBy(GroupBy): res, out = np.zeros(len(ri), dtype=out.dtype), res res[ids[idx]] = out result = Series(res, index=ri, name=self._selection_name) return self._reindex_output(result, fill_value=0) @Appender(Series.describe.__doc__) def describe(self, **kwarg...
class SeriesGroupBy(GroupBy): minlength = ngroups or 0 out = np.bincount(ids[mask], minlength=minlength) return Series( out, index=self.grouper.result_index, name=self._selection_name, dtype="int64", ) def _apply_to_column_groupbys(se...
class SeriesGroupBy(GroupBy): minlength = ngroups or 0 out = np.bincount(ids[mask], minlength=minlength) result = Series( out, index=self.grouper.result_index, name=self._selection_name, dtype="int64", ) return self._reindex_output...
from pandas.core.dtypes.common import ( ) from pandas.core.dtypes.missing import isna, notna from pandas.core import nanops import pandas.core.algorithms as algorithms from pandas.core.arrays import Categorical, try_cast_to_ea
from pandas.core.dtypes.common import ( ) from pandas.core.dtypes.missing import isna, notna from pandas._typing import FrameOrSeries, Scalar from pandas.core import nanops import pandas.core.algorithms as algorithms from pandas.core.arrays import Categorical, try_cast_to_ea
class GroupBy(_GroupBy): if isinstance(self.obj, Series): result.name = self.obj.name return result @classmethod def _add_numeric_operations(cls):
class GroupBy(_GroupBy): if isinstance(self.obj, Series): result.name = self.obj.name return self._reindex_output(result, fill_value=0) @classmethod def _add_numeric_operations(cls):
class GroupBy(_GroupBy): if not self.observed and isinstance(result_index, CategoricalIndex): out = out.reindex(result_index) return out.sort_index() if self.sort else out # dropna is truthy
class GroupBy(_GroupBy): if not self.observed and isinstance(result_index, CategoricalIndex): out = out.reindex(result_index) out = self._reindex_output(out) return out.sort_index() if self.sort else out # dropna is truthy
class GroupBy(_GroupBy): mask = self._cumcount_array(ascending=False) < n return self._selected_obj[mask] def _reindex_output(self, output): """ If we have categorical groupers, then we might want to make sure that we have a fully re-indexed output to the levels. This means ...
class GroupBy(_GroupBy): mask = self._cumcount_array(ascending=False) < n return self._selected_obj[mask] def _reindex_output( self, output: FrameOrSeries, fill_value: Scalar = np.NaN ) -> FrameOrSeries: """ If we have categorical groupers, then we might want to make sur...
class GroupBy(_GroupBy): Parameters ---------- output: Series or DataFrame Object resulting from grouping and applying an operation. Returns -------
class GroupBy(_GroupBy): Parameters ---------- output : Series or DataFrame Object resulting from grouping and applying an operation. fill_value : scalar, default np.NaN Value to use for unobserved categories if self.observed is False. Returns --...
class GroupBy(_GroupBy): ).sortlevel() if self.as_index: d = {self.obj._get_axis_name(self.axis): index, "copy": False} return output.reindex(**d) # GH 13204
class GroupBy(_GroupBy): ).sortlevel() if self.as_index: d = { self.obj._get_axis_name(self.axis): index, "copy": False, "fill_value": fill_value, } return output.reindex(**d) # GH 13204
class GroupBy(_GroupBy): output = output.drop(labels=list(g_names), axis=1) # Set a temp index and reindex (possibly expanding) output = output.set_index(self.grouper.result_index).reindex(index, copy=False) # Reset in-axis grouper columns # (using level numbers `g_nums` becaus...
class GroupBy(_GroupBy): output = output.drop(labels=list(g_names), axis=1) # Set a temp index and reindex (possibly expanding) output = output.set_index(self.grouper.result_index).reindex( index, copy=False, fill_value=fill_value ) # Reset in-axis grouper columns ...
def test_get_nonexistent_category(): {"var": [rows.iloc[-1]["var"]], "val": [rows.iloc[-1]["vau"]]} ) )
def test_get_nonexistent_category(): {"var": [rows.iloc[-1]["var"]], "val": [rows.iloc[-1]["vau"]]} ) ) def test_series_groupby_on_2_categoricals_unobserved( reduction_func: str, observed: bool ): # GH 17605 if reduction_func == "ngroup": pytest.skip("ngroup is...
def bracket_split_build_line( if leaves: # Since body is a new indent level, remove spurious leading whitespace. normalize_prefix(leaves[0], inside_brackets=True) # Ensure a trailing comma when expected. if original.is_import: if leaves[-1].type !=...
def bracket_split_build_line( if leaves: # Since body is a new indent level, remove spurious leading whitespace. normalize_prefix(leaves[0], inside_brackets=True) # Ensure a trailing comma for imports, but be careful not to add one after # any comments. ...
class BlackTestCase(unittest.TestCase): black.assert_equivalent(source, actual) black.assert_stable(source, actual, black.FileMode()) @patch("black.dump_to_file", dump_to_stderr) def test_cantfit(self) -> None: source, expected = read_data("cantfit")
class BlackTestCase(unittest.TestCase): black.assert_equivalent(source, actual) black.assert_stable(source, actual, black.FileMode()) @patch("black.dump_to_file", dump_to_stderr) def test_comments7(self) -> None: source, expected = read_data("comments7") actual = fs(source) ...
from tests.utils import Command @pytest.fixture def did_not_match(target, did_you_forget=True): error = ("error: pathspec '{}' did not match any " "file(s) known to git.".format(target)) if did_you_forget: error = ("{}\nDid you forget to 'git add'?'".format(error)) return error @pyt...
from tests.utils import Command @pytest.fixture def stderr(target): return ("error: pathspec '{}' did not match any " 'file(s) known to git.'.format(target)) @pytest.mark.parametrize('script, target', [ ('git submodule update unknown', 'unknown'), ('git commit unknown', 'unknown')]) def test...
from thefuck.specific.git import git_support @git_support def match(command): return ('did not match any file(s) known to git.' in command.stderr and "Did you forget to 'git add'?" in command.stderr) @git_support def get_new_command(command): missing_file = re.findall( r"error: pathsp...
from thefuck.specific.git import git_support @git_support def match(command): return 'did not match any file(s) known to git.' in command.stderr @git_support def get_new_command(command): missing_file = re.findall( r"error: pathspec '([^']*)' " r'did not match any file\(s\) known to git.', co...
class ExcelFormatter: # Deprecated in GH#17295, enforced in 1.0.0 raise KeyError("Not all names specified in 'columns' are found") self.df = df self.columns = self.df.columns self.float_format = float_format
class ExcelFormatter: # Deprecated in GH#17295, enforced in 1.0.0 raise KeyError("Not all names specified in 'columns' are found") self.df = df.reindex(columns=cols) self.columns = self.df.columns self.float_format = float_format
class TestExcelWriter: ): write_frame.to_excel(path, "test1", columns=["C", "D"]) def test_comment_arg(self, path): # see gh-18735 #
class TestExcelWriter: ): write_frame.to_excel(path, "test1", columns=["C", "D"]) @pytest.mark.parametrize( "to_excel_index,read_excel_index_col", [ (True, 0), # Include index in write to file (False, None), # Dont include index in write to file ...
from __future__ import print_function import warnings import numpy as np from .training_utils import iter_sequence_infinite from .. import backend as K from ..utils.data_utils import Sequence
from __future__ import print_function import warnings import numpy as np from .training_utils import is_sequence from .training_utils import iter_sequence_infinite from .. import backend as K from ..utils.data_utils import Sequence
def fit_generator(model, if do_validation: model._make_test_function() is_sequence = isinstance(generator, Sequence) if not is_sequence and use_multiprocessing and workers > 1: warnings.warn( UserWarning('Using a generator with `use_multiprocessing=True`' ...
def fit_generator(model, if do_validation: model._make_test_function() use_sequence_api = is_sequence(generator) if not use_sequence_api and use_multiprocessing and workers > 1: warnings.warn( UserWarning('Using a generator with `use_multiprocessing=True`' ...
def fit_generator(model, # python 2 has 'next', 3 has '__next__' # avoid any explicit version checks val_gen = (hasattr(validation_data, 'next') or hasattr(validation_data, '__next__') or isinstance(validation_data, Sequence)) if (val_gen and not isinstance(validation_data...
def fit_generator(model, # python 2 has 'next', 3 has '__next__' # avoid any explicit version checks val_use_sequence_api = is_sequence(validation_data) val_gen = (hasattr(validation_data, 'next') or hasattr(validation_data, '__next__') or val_use_sequence_api) if (val...
def fit_generator(model, if val_gen and workers > 0: # Create an Enqueuer that can be reused val_data = validation_data if isinstance(val_data, Sequence): val_enqueuer = OrderedEnqueuer( val_data, ...
def fit_generator(model, if val_gen and workers > 0: # Create an Enqueuer that can be reused val_data = validation_data if is_sequence(val_data): val_enqueuer = OrderedEnqueuer( val_data, use_...
def fit_generator(model, val_enqueuer_gen = val_enqueuer.get() elif val_gen: val_data = validation_data if isinstance(val_data, Sequence): val_enqueuer_gen = iter_sequence_infinite(val_data) validation_steps = validation...
def fit_generator(model, val_enqueuer_gen = val_enqueuer.get() elif val_gen: val_data = validation_data if is_sequence(val_data): val_enqueuer_gen = iter_sequence_infinite(val_data) validation_steps = validation_steps or...
def fit_generator(model, cbk.validation_data = val_data if workers > 0: if is_sequence: enqueuer = OrderedEnqueuer( generator, use_multiprocessing=use_multiprocessing,
def fit_generator(model, cbk.validation_data = val_data if workers > 0: if use_sequence_api: enqueuer = OrderedEnqueuer( generator, use_multiprocessing=use_multiprocessing,
def fit_generator(model, enqueuer.start(workers=workers, max_queue_size=max_queue_size) output_generator = enqueuer.get() else: if is_sequence: output_generator = iter_sequence_infinite(generator) else: output_generator = generator
def fit_generator(model, enqueuer.start(workers=workers, max_queue_size=max_queue_size) output_generator = enqueuer.get() else: if use_sequence_api: output_generator = iter_sequence_infinite(generator) else: output_generator = gener...