buggy
stringlengths
35
5.03k
fixed
stringlengths
46
62.5k
class Model(Container): str(generator_output)) # build batch logs batch_logs = {} if isinstance(x, list): batch_size = x[0].shape[0] elif isinstance(x, dict): ...
class Model(Container): str(generator_output)) # build batch logs batch_logs = {} if x is None or len(x) == 0: # Handle data tensors support when no input given # step-siz...
class Model(Container): outs = [outs] outs_per_batch.append(outs) if isinstance(x, list): batch_size = x[0].shape[0] elif isinstance(x, dict): batch_size = list(x.values())[0].shape[0]
class Model(Container): outs = [outs] outs_per_batch.append(outs) if x is None or len(x) == 0: # Handle data tensors support when no input given # step-size = 1 for data tensors batch_size = 1 ...
def test_model_with_external_loss(): out = model.fit(None, None, epochs=1, batch_size=10) out = model.fit(None, None, epochs=1, steps_per_epoch=1) # test fit with validation data with pytest.raises(ValueError): out = model.fit(None, None,
def test_model_with_external_loss(): out = model.fit(None, None, epochs=1, batch_size=10) out = model.fit(None, None, epochs=1, steps_per_epoch=1) # define a generator to produce x=None and y=None def data_tensors_generator(): while True: yield (None, Non...
""" Constants specific to the SQL storage portion of the ORM. """ # Size of each "chunk" for get_iterator calls. # Larger values are slightly faster at the expense of more storage space.
""" Constants specific to the SQL storage portion of the ORM. """ from django.utils.regex_helper import _lazy_re_compile # Size of each "chunk" for get_iterator calls. # Larger values are slightly faster at the expense of more storage space.
ORDER_DIR = { 'ASC': ('ASC', 'DESC'), 'DESC': ('DESC', 'ASC'), } # SQL join types. INNER = 'INNER JOIN'
ORDER_DIR = { 'ASC': ('ASC', 'DESC'), 'DESC': ('DESC', 'ASC'), } ORDER_PATTERN = _lazy_re_compile(r'[-+]?[.\w]+$') # SQL join types. INNER = 'INNER JOIN'
from django.db.models.lookups import Lookup from django.db.models.query_utils import ( Q, check_rel_lookup_compatibility, refs_expression, ) from django.db.models.sql.constants import INNER, LOUTER, ORDER_DIR, SINGLE from django.db.models.sql.datastructures import ( BaseTable, Empty, Join, MultiJoin, )
from django.db.models.lookups import Lookup from django.db.models.query_utils import ( Q, check_rel_lookup_compatibility, refs_expression, ) from django.db.models.sql.constants import ( INNER, LOUTER, ORDER_DIR, ORDER_PATTERN, SINGLE, ) from django.db.models.sql.datastructures import ( BaseTable, Empty, Joi...
class Query(BaseExpression): errors = [] for item in ordering: if isinstance(item, str): if '.' in item: warnings.warn( 'Passing column raw column aliases to order_by() is ' 'deprecated. Wrap %r in a RawSQL e...
class Query(BaseExpression): errors = [] for item in ordering: if isinstance(item, str): if '.' in item and ORDER_PATTERN.match(item): warnings.warn( 'Passing column raw column aliases to order_by() is ' 'dep...
class QuerySetExceptionTests(SimpleTestCase): with self.assertRaisesMessage(FieldError, msg): Article.objects.order_by('*') def test_invalid_queryset_model(self): msg = 'Cannot use QuerySet for "Article": Use a QuerySet for "ExtraInfo".' with self.assertRaisesMessage(ValueError,...
class QuerySetExceptionTests(SimpleTestCase): with self.assertRaisesMessage(FieldError, msg): Article.objects.order_by('*') def test_order_by_escape_prevention(self): msg = ( "Cannot resolve keyword 'queries.name);' into field. Choices are: " "created, id, name" ...
class AnsibleModule(object): if k not in self.argument_spec: self.argument_spec[k] = v self._load_params() self._set_fallbacks()
class AnsibleModule(object): if k not in self.argument_spec: self.argument_spec[k] = v # Save parameter values that should never be logged self.no_log_values = set() self._load_params() self._set_fallbacks()
class AnsibleModule(object): print('\n{"failed": true, "msg": "Module alias error: %s"}' % to_native(e)) sys.exit(1) # Save parameter values that should never be logged self.no_log_values = set() self._handle_no_log_values() # check the locale as set by the curr...
class AnsibleModule(object): print('\n{"failed": true, "msg": "Module alias error: %s"}' % to_native(e)) sys.exit(1) self._handle_no_log_values() # check the locale as set by the current environment, and reset to
class AnsibleModule(object): param = self.params for (k, v) in spec.items(): default = v.get('default', None) if pre is True: # this prevents setting defaults on required items if default is not None and k not in param: para...
class AnsibleModule(object): param = self.params for (k, v) in spec.items(): default = v.get('default', None) # This prevents setting defaults on required items on the 1st run, # otherwise will set things without a default to None on the 2nd. if k not...
class AnsibleModule(object): else: fallback_args = item try: param[k] = fallback_strategy(*fallback_args, **fallback_kwargs) except AnsibleFallbackNotFound: continue def _load_params(self): '...
class AnsibleModule(object): else: fallback_args = item try: fallback_value = fallback_strategy(*fallback_args, **fallback_kwargs) except AnsibleFallbackNotFound: continue else: ...
async def impl(request: Request, handler: _Handler) -> StreamResponse: paths_to_check.append(merged_slashes[:-1]) for path in paths_to_check: resolves, request = await _check_request_resolves(request, path) if resolves: raise redirect_clas...
async def impl(request: Request, handler: _Handler) -> StreamResponse: paths_to_check.append(merged_slashes[:-1]) for path in paths_to_check: path = re.sub("^//+", "/", path) # SECURITY: GHSA-v6wp-4m6f-gcjg resolves, request = await _check_request_resolves(r...
async def test_cannot_remove_and_add_slash(self) -> None: with pytest.raises(AssertionError): web.normalize_path_middleware(append_slash=True, remove_slash=True) async def test_bug_3669(aiohttp_client: Any): async def paymethod(request):
async def test_cannot_remove_and_add_slash(self) -> None: with pytest.raises(AssertionError): web.normalize_path_middleware(append_slash=True, remove_slash=True) @pytest.mark.parametrize( ["append_slash", "remove_slash"], [ (True, False), (False, True), ...
def authenticate(self, context, auth=None): self.token_api.create_token( context, token_id, dict(key=token_id, id=token_id, user=user_ref, tenant=tenant_ref, ...
def authenticate(self, context, auth=None): self.token_api.create_token( context, token_id, dict(key=token_id, id=token_id, expires=auth_token_data['expires'], user=user_re...
from django.utils.text import ( from django.utils.timesince import timesince, timeuntil from django.utils.translation import gettext, ngettext from .base import Variable, VariableDoesNotExist from .library import Library register = Library()
from django.utils.text import ( from django.utils.timesince import timesince, timeuntil from django.utils.translation import gettext, ngettext from .base import VARIABLE_ATTRIBUTE_SEPARATOR from .library import Library register = Library()
def striptags(value): def _property_resolver(arg): """ When arg is convertible to float, behave like operator.itemgetter(arg) Otherwise, behave like Variable(arg).resolve >>> _property_resolver(1)('abc') 'b'
def striptags(value): def _property_resolver(arg): """ When arg is convertible to float, behave like operator.itemgetter(arg) Otherwise, chain __getitem__() and getattr(). >>> _property_resolver(1)('abc') 'b'
def _property_resolver(arg): try: float(arg) except ValueError: return Variable(arg).resolve else: return itemgetter(arg)
def _property_resolver(arg): try: float(arg) except ValueError: if VARIABLE_ATTRIBUTE_SEPARATOR + '_' in arg or arg[0] == '_': raise AttributeError('Access to private variables is forbidden.') parts = arg.split(VARIABLE_ATTRIBUTE_SEPARATOR) def resolve(value): ...
def dictsort(value, arg): """ try: return sorted(value, key=_property_resolver(arg)) except (TypeError, VariableDoesNotExist): return ''
def dictsort(value, arg): """ try: return sorted(value, key=_property_resolver(arg)) except (AttributeError, TypeError): return ''
def dictsortreversed(value, arg): """ try: return sorted(value, key=_property_resolver(arg), reverse=True) except (TypeError, VariableDoesNotExist): return ''
def dictsortreversed(value, arg): """ try: return sorted(value, key=_property_resolver(arg), reverse=True) except (AttributeError, TypeError): return ''
from django.template.defaultfilters import dictsort from django.test import SimpleTestCase class FunctionTests(SimpleTestCase): def test_sort(self): sorted_dicts = dictsort( [{'age': 23, 'name': 'Barbara-Ann'},
from django.template.defaultfilters import _property_resolver, dictsort from django.test import SimpleTestCase class User: password = 'abc' _private = 'private' @property def test_property(self): return 'cde' def test_method(self): """This is just a test method.""" class Funct...
class FunctionTests(SimpleTestCase): def test_dictsort_complex_sorting_key(self): """ Since dictsort uses template.Variable under the hood, it can sort on keys like 'foo.bar'. """ data = [
class FunctionTests(SimpleTestCase): def test_dictsort_complex_sorting_key(self): """ Since dictsort uses dict.get()/getattr() under the hood, it can sort on keys like 'foo.bar'. """ data = [
class FunctionTests(SimpleTestCase): self.assertEqual(dictsort('Hello!', 'age'), '') self.assertEqual(dictsort({'a': 1}, 'age'), '') self.assertEqual(dictsort(1, 'age'), '')
class FunctionTests(SimpleTestCase): self.assertEqual(dictsort('Hello!', 'age'), '') self.assertEqual(dictsort({'a': 1}, 'age'), '') self.assertEqual(dictsort(1, 'age'), '') def test_invalid_args(self): """Fail silently if invalid lookups are passed.""" self.assertEqual(dict...
class FunctionTests(SimpleTestCase): self.assertEqual(dictsortreversed('Hello!', 'age'), '') self.assertEqual(dictsortreversed({'a': 1}, 'age'), '') self.assertEqual(dictsortreversed(1, 'age'), '')
class FunctionTests(SimpleTestCase): self.assertEqual(dictsortreversed('Hello!', 'age'), '') self.assertEqual(dictsortreversed({'a': 1}, 'age'), '') self.assertEqual(dictsortreversed(1, 'age'), '') def test_invalid_args(self): """Fail silently if invalid lookups are passed.""" ...
def test_overrun(self): for file in [ "fli_overrun.bin", "sgi_overrun.bin", "pcx_overrun.bin", "pcx_overrun2.bin", ]:
def test_overrun(self): for file in [ "fli_overrun.bin", "sgi_overrun.bin", "sgi_overrun_expandrow.bin", "sgi_overrun_expandrow2.bin", "pcx_overrun.bin", "pcx_overrun2.bin", ]:
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=...
class APIRouter(routing.Router): include_in_schema=route.include_in_schema, name=route.name, ) def get( self,
class APIRouter(routing.Router): include_in_schema=route.include_in_schema, name=route.name, ) elif isinstance(route, routing.WebSocketRoute): self.add_websocket_route( prefix + route.path, route.endpoint, name=route...
class LinuxHardware(Hardware): # regex used against mtab content to find entries that are bind mounts MTAB_BIND_MOUNT_RE = re.compile(r'.*bind.*"') def populate(self, collected_facts=None): hardware_facts = {} self.module.run_command_environ_update = {'LANG': 'C', 'LC_ALL': 'C', 'LC_NUMERIC...
class LinuxHardware(Hardware): # regex used against mtab content to find entries that are bind mounts MTAB_BIND_MOUNT_RE = re.compile(r'.*bind.*"') # regex used for replacing octal escape sequences OCTAL_ESCAPE_RE = re.compile(r'\\[0-9]{3}') def populate(self, collected_facts=None): hardwa...
class LinuxHardware(Hardware): mtab_entries.append(fields) return mtab_entries def get_mount_info(self, mount, device, uuids): mount_size = get_mount_size(mount)
class LinuxHardware(Hardware): mtab_entries.append(fields) return mtab_entries @staticmethod def _replace_octal_escapes_helper(match): # Convert to integer using base8 and then convert to character return chr(int(match.group()[1:], 8)) def _replace_octal_escapes(self, v...
class LinuxHardware(Hardware): pool = ThreadPool(processes=min(len(mtab_entries), cpu_count())) maxtime = globals().get('GATHER_TIMEOUT') or timeout.DEFAULT_GATHER_TIMEOUT for fields in mtab_entries: device, mount, fstype, options = fields[0], fields[1], fields[2], fields[3]
class LinuxHardware(Hardware): pool = ThreadPool(processes=min(len(mtab_entries), cpu_count())) maxtime = globals().get('GATHER_TIMEOUT') or timeout.DEFAULT_GATHER_TIMEOUT for fields in mtab_entries: # Transform octal escape sequences fields = [self._replace_octal_escapes...
MTAB_ENTRIES = [ '0', '0' ], ['fusectl', '/sys/fs/fuse/connections', 'fusectl', 'rw,relatime', '0', '0']] BIND_MOUNTS = ['/not/a/real/bind_mount']
MTAB_ENTRIES = [ '0', '0' ], ['fusectl', '/sys/fs/fuse/connections', 'fusectl', 'rw,relatime', '0', '0'], # Mount path with space in the name # The space is encoded as \040 since the fields in /etc/mtab are space-delimeted ['/dev/sdz9', r'/mnt/foo\040bar', 'ext4', 'rw,relatime', '0',...
class TestFactsLinuxHardwareGetMountFacts(unittest.TestCase): self.assertIsInstance(mount_facts['mounts'], list) self.assertIsInstance(mount_facts['mounts'][0], dict) @patch('ansible.module_utils.facts.hardware.linux.get_file_content', return_value=MTAB) def test_get_mtab_entries(self, mock_get...
class TestFactsLinuxHardwareGetMountFacts(unittest.TestCase): self.assertIsInstance(mount_facts['mounts'], list) self.assertIsInstance(mount_facts['mounts'][0], dict) # Find mounts with space in the mountpoint path mounts_with_space = [x for x in mount_facts['mounts'] if ' ' in x['mount...
class HiveCommandClient(HiveClient): if partition is None: stdout = run_hive_cmd('use {0}; show tables like "{1}";'.format(database, table)) return stdout and table in stdout else: stdout = run_hive_cmd("""use %s; show partitions %s partition ...
class HiveCommandClient(HiveClient): if partition is None: stdout = run_hive_cmd('use {0}; show tables like "{1}";'.format(database, table)) return stdout and table.lower() in stdout else: stdout = run_hive_cmd("""use %s; show partitions %s partition ...
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 = ...
DEFAULT_FORCE_HANDLERS = get_config(p, DEFAULTS, 'force_handlers', 'ANSIBLE_F DEFAULT_INVENTORY_IGNORE = get_config(p, DEFAULTS, 'inventory_ignore_extensions', 'ANSIBLE_INVENTORY_IGNORE', ["~", ".orig", ".bak", ".ini", ".cfg", ".retry", ".pyc", ".pyo"], value_type='list') DEFAULT_VAR_COMPRESSION_LEVEL = get_config(...
DEFAULT_FORCE_HANDLERS = get_config(p, DEFAULTS, 'force_handlers', 'ANSIBLE_F DEFAULT_INVENTORY_IGNORE = get_config(p, DEFAULTS, 'inventory_ignore_extensions', 'ANSIBLE_INVENTORY_IGNORE', ["~", ".orig", ".bak", ".ini", ".cfg", ".retry", ".pyc", ".pyo"], value_type='list') DEFAULT_VAR_COMPRESSION_LEVEL = get_config(...
class Templar: loader=FileSystemLoader(self._basedir), ) self.SINGLE_VAR = re.compile(r"^%s\s*(\w*)\s*%s$" % (self.environment.variable_start_string, self.environment.variable_end_string)) self.block_start = self.environment.block_start_string
class Templar: loader=FileSystemLoader(self._basedir), ) # the current rendering context under which the templar class is working self.cur_context = None self.SINGLE_VAR = re.compile(r"^%s\s*(\w*)\s*%s$" % (self.environment.variable_start_string, self.environment.variable_e...
class Templar: if instance is not None: wantlist = kwargs.pop('wantlist', False) from ansible.utils.listify import listify_lookup_plugin_terms loop_terms = listify_lookup_plugin_terms(terms=args, templar=self, loader=self._loader, fail_on_undefined=True, convert_bare=False)
class Templar: if instance is not None: wantlist = kwargs.pop('wantlist', False) allow_unsafe = kwargs.pop('allow_unsafe', C.DEFAULT_ALLOW_UNSAFE_LOOKUPS) from ansible.utils.listify import listify_lookup_plugin_terms loop_terms = listify_lookup_plugin_terms(term...
class Templar: raise AnsibleError("An unhandled exception occurred while running the lookup plugin '%s'. Error was a %s, original message: %s" % (name, type(e), e)) ran = None if ran: if wantlist: ran = wrap_var(ran) el...
class Templar: raise AnsibleError("An unhandled exception occurred while running the lookup plugin '%s'. Error was a %s, original message: %s" % (name, type(e), e)) ran = None if ran and not allow_unsafe: from ansible.vars.unsafe_proxy import UnsafeProxy,...
class Templar: else: ran = wrap_var(ran) return ran else: raise AnsibleError("lookup plugin (%s) not found" % name)
class Templar: else: ran = wrap_var(ran) if self.cur_context: self.cur_context.unsafe = True return ran else: raise AnsibleError("lookup plugin (%s) not found" % name)
class Templar: jvars = AnsibleJ2Vars(self, t.globals) new_context = t.new_context(jvars, shared=True) rf = t.root_render_func(new_context) try:
class Templar: jvars = AnsibleJ2Vars(self, t.globals) self.cur_context = new_context = t.new_context(jvars, shared=True) rf = t.root_render_func(new_context) try:
class PlayBook(object): basedir = self.inventory.basedir() filename = "%s.retry" % os.path.basename(self.filename) filename = filename.replace(".yml","") if not os.path.exists('/var/tmp/ansible'): try: os.makedirs('/var/tmp/ansible') except: ...
class PlayBook(object): basedir = self.inventory.basedir() filename = "%s.retry" % os.path.basename(self.filename) filename = filename.replace(".yml","") filename = os.path.join(os.path.expandvars('$HOME/'), filename) try: fd = open(filename, 'w')
import stat from django.http import ( FileResponse, Http404, HttpResponse, HttpResponseNotModified, HttpResponseRedirect, ) from django.template import Context, Engine, TemplateDoesNotExist, loader from django.utils.http import http_date, parse_http_date from django.utils.translation import gettext as _, gette...
import stat from django.http import ( FileResponse, Http404, HttpResponse, HttpResponseNotModified, ) from django.template import Context, Engine, TemplateDoesNotExist, loader from django.utils._os import safe_join from django.utils.http import http_date, parse_http_date from django.utils.translation import gettex...
def serve(request, path, document_root=None, show_indexes=False): but if you'd like to override it, you can create a template called ``static/directory_index.html``. """ path = posixpath.normpath(path) path = path.lstrip('/') newpath = '' for part in path.split('/'): if not part: ...
def serve(request, path, document_root=None, show_indexes=False): but if you'd like to override it, you can create a template called ``static/directory_index.html``. """ path = posixpath.normpath(path).lstrip('/') fullpath = safe_join(document_root, path) if os.path.isdir(fullpath): if s...
class StaticTests(SimpleTestCase): def test_index(self): response = self.client.get('/%s/' % self.prefix) self.assertContains(response, 'Index of /') class StaticHelperTest(StaticTests):
class StaticTests(SimpleTestCase): def test_index(self): response = self.client.get('/%s/' % self.prefix) self.assertContains(response, 'Index of ./') class StaticHelperTest(StaticTests):
def validate_baseindexer_support(func_name: Optional[str]) -> None: "median", "std", "var", "kurt", "quantile", }
def validate_baseindexer_support(func_name: Optional[str]) -> None: "median", "std", "var", "skew", "kurt", "quantile", }
class _Window(PandasObject, ShallowMixin, SelectionMixin): def calc(x): x = np.concatenate((x, additional_nans)) if not isinstance(window, BaseIndexer): min_periods = calculate_min_periods( window, self.min_peri...
class _Window(PandasObject, ShallowMixin, SelectionMixin): def calc(x): x = np.concatenate((x, additional_nans)) if not isinstance(self.window, BaseIndexer): min_periods = calculate_min_periods( window, self.min...
def test_win_type_not_implemented(): df.rolling(indexer, win_type="boxcar") @pytest.mark.parametrize("func", ["skew", "cov", "corr"]) def test_notimplemented_functions(func): # GH 32865 class CustomIndexer(BaseIndexer):
def test_win_type_not_implemented(): df.rolling(indexer, win_type="boxcar") @pytest.mark.parametrize("func", ["cov", "corr"]) def test_notimplemented_functions(func): # GH 32865 class CustomIndexer(BaseIndexer):
def test_rolling_forward_window(constructor, func, np_func, expected, np_kwargs) result3 = getattr(rolling3, func)() expected3 = constructor(rolling3.apply(lambda x: np_func(x, **np_kwargs))) tm.assert_equal(result3, expected3)
def test_rolling_forward_window(constructor, func, np_func, expected, np_kwargs) result3 = getattr(rolling3, func)() expected3 = constructor(rolling3.apply(lambda x: np_func(x, **np_kwargs))) tm.assert_equal(result3, expected3) @pytest.mark.parametrize("constructor", [Series, DataFrame]) def test_rolling_...
def test_pdf_append_to_bytesio(): f = io.BytesIO(f.getvalue()) im.save(f, format="PDF", append=True) assert len(f.getvalue()) > initial_size
def test_pdf_append_to_bytesio(): f = io.BytesIO(f.getvalue()) im.save(f, format="PDF", append=True) assert len(f.getvalue()) > initial_size @pytest.mark.timeout(1) def test_redos(): malicious = b" trailer<<>>" + b"\n" * 3456 # This particular exception isn't relevant here. # The important th...
class MultiPartParser: remaining = len(stripped_chunk) % 4 while remaining != 0: over_chunk = field_stream.read(4 - remaining) stripped_chunk += b"".join(over_chunk.split()) ...
class MultiPartParser: remaining = len(stripped_chunk) % 4 while remaining != 0: over_chunk = field_stream.read(4 - remaining) if not over_chunk: ...
class FileUploadTests(TestCase): def test_big_base64_newlines_upload(self): self._test_base64_upload("Big data" * 68000, encode=base64.encodebytes) def test_unicode_file_name(self): with sys_tempfile.TemporaryDirectory() as temp_dir: # This file contains Chinese symbols and an accen...
class FileUploadTests(TestCase): def test_big_base64_newlines_upload(self): self._test_base64_upload("Big data" * 68000, encode=base64.encodebytes) def test_base64_invalid_upload(self): payload = client.FakePayload('\r\n'.join([ '--' + client.BOUNDARY, 'Content-Dispositi...
def request_httprepr(request): parsed = urlparse_cached(request) path = urlunparse(('', '', parsed.path or '/', parsed.params, parsed.query, '')) s = to_bytes(request.method) + b" " + to_bytes(path) + b" HTTP/1.1\r\n" s += b"Host: " + to_bytes(parsed.hostname) + b"\r\n" if request.headers: s...
def request_httprepr(request): parsed = urlparse_cached(request) path = urlunparse(('', '', parsed.path or '/', parsed.params, parsed.query, '')) s = to_bytes(request.method) + b" " + to_bytes(path) + b" HTTP/1.1\r\n" s += b"Host: " + to_bytes(parsed.hostname or b'') + b"\r\n" if request.headers: ...
class UtilsRequestTest(unittest.TestCase): r1 = Request("http://www.example.com", method='POST', headers={"Content-type": b"text/html"}, body=b"Some body") self.assertEqual(request_httprepr(r1), b'POST / HTTP/1.1\r\nHost: www.example.com\r\nContent-Type: text/html\r\n\r\nSome body') if __name__ == "__m...
class UtilsRequestTest(unittest.TestCase): r1 = Request("http://www.example.com", method='POST', headers={"Content-type": b"text/html"}, body=b"Some body") self.assertEqual(request_httprepr(r1), b'POST / HTTP/1.1\r\nHost: www.example.com\r\nContent-Type: text/html\r\n\r\nSome body') def test_reques...
class AsyncioServer: task = asyncio.ensure_future(coro, loop=self.loop) return task def __await__(self): """Starts the asyncio server, returns AsyncServerCoro""" task = asyncio.ensure_future(self.serve_coro)
class AsyncioServer: task = asyncio.ensure_future(coro, loop=self.loop) return task def start_serving(self): if self.server: try: return self.server.start_serving() except AttributeError: raise NotImplementedError( ...
def test_create_asyncio_server(app): @pytest.mark.skipif( sys.version_info < (3, 7), reason="requires python3.7 or higher" ) def test_asyncio_server_start_serving(app): if not uvloop_installed(): loop = asyncio.get_event_loop() asyncio_srv_coro = app.create_server(
def test_create_asyncio_server(app): @pytest.mark.skipif( sys.version_info < (3, 7), reason="requires python3.7 or higher" ) def test_asyncio_server_no_start_serving(app): if not uvloop_installed(): loop = asyncio.get_event_loop() asyncio_srv_coro = app.create_server(
def test_asyncio_server_start_serving(app): srv = loop.run_until_complete(asyncio_srv_coro) assert srv.is_serving() is False def test_app_loop_not_running(app): with pytest.raises(SanicException) as excinfo:
def test_asyncio_server_start_serving(app): srv = loop.run_until_complete(asyncio_srv_coro) assert srv.is_serving() is False @pytest.mark.skipif( sys.version_info < (3, 7), reason="requires python3.7 or higher" ) def test_asyncio_server_start_serving(app): if not uvloop_installed(): loo...
def test_overflowing_header_limit_after_100(self): 'r\n' * 32768 ) resp = client.HTTPResponse(FakeSocket(body)) self.assertRaises(client.HTTPException, resp.begin) def test_overflowing_chunked_line(self): body = (
def test_overflowing_header_limit_after_100(self): 'r\n' * 32768 ) resp = client.HTTPResponse(FakeSocket(body)) with self.assertRaises(client.HTTPException) as cm: resp.begin() # We must assert more because other reasonable errors that we # do not want can...
def nanstd(values, axis=None, skipna=True, ddof=1, mask=None): >>> nanops.nanstd(s) 1.0 """ result = np.sqrt(nanvar(values, axis=axis, skipna=skipna, ddof=ddof, mask=mask)) return _wrap_results(result, values.dtype) @disallow("M8") @bottleneck_switch(ddof=1) def nanvar(values, axis=None, skipna=Tr...
def nanstd(values, axis=None, skipna=True, ddof=1, mask=None): >>> nanops.nanstd(s) 1.0 """ orig_dtype = values.dtype values, mask, dtype, dtype_max, fill_value = _get_values(values, skipna, mask=mask) result = np.sqrt(nanvar(values, axis=axis, skipna=skipna, ddof=ddof, mask=mask)) return _...
class Series(base.IndexOpsMixin, generic.NDFrame): If we have an ndarray as a value, then simply perform the operation, otherwise delegate to the object. """ delegate = self._values if axis is not None:
class Series(base.IndexOpsMixin, generic.NDFrame): If we have an ndarray as a value, then simply perform the operation, otherwise delegate to the object. """ delegate = self._values if axis is not None:
class TestIndexReductions: assert result[0] == expected # invalid ops for op in ["skew", "kurt", "sem", "prod"]: msg = "reduction operation '{}' not allowed for this dtype" with pytest.raises(TypeError, match=msg.format(op)): getattr(td, op)() # ...
class TestIndexReductions: assert result[0] == expected # invalid ops for op in ["skew", "kurt", "sem", "prod", "var"]: msg = "reduction operation '{}' not allowed for this dtype" with pytest.raises(TypeError, match=msg.format(op)): getattr(td, op)() ...
class TestSeriesReductions: assert pd.isna(result) # timedelta64[ns] result = getattr(Series(dtype="m8[ns]"), method)() assert result is pd.NaT def test_nansum_buglet(self): ser = Series([1.0, np.nan], index=[0, 1])
class TestSeriesReductions: assert pd.isna(result) # timedelta64[ns] tdser = Series([], dtype="m8[ns]") if method == "var": with pytest.raises(TypeError, match="operation 'var' not allowed"): getattr(tdser, method)() else: result = getattr...
class WorkerProcess(multiprocessing.Process): # set to /dev/null self._new_stdin = os.devnull def run(self): ''' Called when the process is started. Pushes the result onto the
class WorkerProcess(multiprocessing.Process): # set to /dev/null self._new_stdin = os.devnull # NOTE: this works due to fork, if switching to threads this should change to per thread storage of temp files # clear var to ensure we only delete files for this child self._lo...
class WorkerProcess(multiprocessing.Process): except: display.debug(u"WORKER EXCEPTION: %s" % to_text(e)) display.debug(u"WORKER TRACEBACK: %s" % to_text(traceback.format_exc())) display.debug("WORKER PROCESS EXITING")
class WorkerProcess(multiprocessing.Process): except: display.debug(u"WORKER EXCEPTION: %s" % to_text(e)) display.debug(u"WORKER TRACEBACK: %s" % to_text(traceback.format_exc())) finally: self._clean_up() display.debug(...
class WorkerProcess(multiprocessing.Process): # ps.print_stats() # with open('worker_%06d.stats' % os.getpid(), 'w') as f: # f.write(s.getvalue())
class WorkerProcess(multiprocessing.Process): # ps.print_stats() # with open('worker_%06d.stats' % os.getpid(), 'w') as f: # f.write(s.getvalue()) def _clean_up(self): # NOTE: see note in init about forks # ensure we cleanup all temp files for this worker self._l...
class DataLoader: ''' def __init__(self): self._basedir = '.' self._FILE_CACHE = dict() self._tempfiles = set() # initialize the vault stuff with an empty password
class DataLoader: ''' def __init__(self): self._basedir = '.' # NOTE: not effective with forks as the main copy does not get updated. # avoids rereading files self._FILE_CACHE = dict() # NOTE: not thread safe, also issues with forks not returning data to main proc ...
class DataLoader: def _create_content_tempfile(self, content): ''' Create a tempfile containing defined content ''' fd, content_tempfile = tempfile.mkstemp() f = os.fdopen(fd, 'wb') content = to_bytes(content) try:
class DataLoader: def _create_content_tempfile(self, content): ''' Create a tempfile containing defined content ''' fd, content_tempfile = tempfile.mkstemp(dir=C.DEFAULT_LOCAL_TMP) f = os.fdopen(fd, 'wb') content = to_bytes(content) try:
class DataLoader: self._tempfiles.remove(file_path) def cleanup_all_tmp_files(self): for f in self._tempfiles: try: self.cleanup_tmp_file(f)
class DataLoader: self._tempfiles.remove(file_path) def cleanup_all_tmp_files(self): """ Removes all temporary files that DataLoader has created NOTE: not thread safe, forks also need special handling see __init__ for details. """ for f in self._tempfiles: ...
class VaultEditor: # Create a tempfile root, ext = os.path.splitext(os.path.realpath(filename)) fd, tmp_path = tempfile.mkstemp(suffix=ext) os.close(fd) cmd = self._editor_shell_command(tmp_path)
class VaultEditor: # Create a tempfile root, ext = os.path.splitext(os.path.realpath(filename)) fd, tmp_path = tempfile.mkstemp(suffix=ext, dir=C.DEFAULT_LOCAL_TMP) os.close(fd) cmd = self._editor_shell_command(tmp_path)
from pandas.core.dtypes.common import ( from pandas.core.dtypes.generic import ABCSeries from pandas.core.accessor import PandasDelegate, delegate_names from pandas.core.algorithms import take_1d from pandas.core.arrays import DatetimeArray, PeriodArray, TimedeltaArray from pandas.core.base import NoNewAttributesMixin...
from pandas.core.dtypes.common import ( from pandas.core.dtypes.generic import ABCSeries from pandas.core.accessor import PandasDelegate, delegate_names from pandas.core.arrays import DatetimeArray, PeriodArray, TimedeltaArray from pandas.core.base import NoNewAttributesMixin, PandasObject from pandas.core.indexes.dat...
class Properties(PandasDelegate, PandasObject, NoNewAttributesMixin): result = np.asarray(result) # blow up if we operate on categories if self.orig is not None: result = take_1d(result, self.orig.cat.codes) index = self.orig.index else: index = self...
class Properties(PandasDelegate, PandasObject, NoNewAttributesMixin): result = np.asarray(result) if self.orig is not None: index = self.orig.index else: index = self._parent.index
class CombinedDatetimelikeProperties( orig = data if is_categorical_dtype(data) else None if orig is not None: data = Series(orig.values.categories, name=orig.name, copy=False) if is_datetime64_dtype(data.dtype): return DatetimeProperties(data, orig)
class CombinedDatetimelikeProperties( orig = data if is_categorical_dtype(data) else None if orig is not None: data = Series( orig.array, name=orig.name, copy=False, dtype=orig.values.categories.dtype, ) if...
class TestSeriesDatetimeValues: expected = Series([2017, 2017, 2018, 2018], name="foo") tm.assert_series_equal(result, expected) def test_dt_accessor_no_new_attributes(self): # https://github.com/pandas-dev/pandas/issues/10673 s = Series(date_range("20130101", periods=5, freq="D"))
class TestSeriesDatetimeValues: expected = Series([2017, 2017, 2018, 2018], name="foo") tm.assert_series_equal(result, expected) def test_dt_tz_localize_categorical(self, tz_aware_fixture): # GH 27952 tz = tz_aware_fixture datetimes = pd.Series( ["2019-01-01", "2...
def _junos_interfaces_ifconfig(out): pmac = re.compile("curr media .*? ([0-9a-f:]+)") pip = re.compile( r".*?inet\s*(primary)*\s+mtu (\d+)\s+local=[^\d]*(.*?)\s+dest=[^\d]*(.*?)\/([\d]*)\s+bcast=((?:[0-9]{1,3}\.){3}[0-9]{1,3})" ) pip6 = re.compile( r".*?inet6 mtu [^\d]+\s+local=([0-9a-f...
def _junos_interfaces_ifconfig(out): pmac = re.compile("curr media .*? ([0-9a-f:]+)") pip = re.compile( r".*?inet\s*(primary)*\s+mtu" r" (\d+)\s+local=[^\d]*(.*?)\s{0,40}dest=[^\d]*(.*?)\/([\d]*)\s{0,40}bcast=((?:[0-9]{1,3}\.){3}[0-9]{1,3})" ) pip6 = re.compile( r".*?inet6 mtu [...
import warnings import numpy as np from pandas._libs import NaT, Timestamp, lib, tslib import pandas._libs.internals as libinternals from pandas._libs.tslibs import Timedelta, conversion from pandas._libs.tslibs.timezones import tz_compare
import warnings import numpy as np from pandas._libs import NaT, Timestamp, lib, tslib, writers import pandas._libs.internals as libinternals from pandas._libs.tslibs import Timedelta, conversion from pandas._libs.tslibs.timezones import tz_compare
class Block(PandasObject): mask = isna(values) if not self.is_object and not quoting: values = values.astype(str) else: values = np.array(values, dtype="object")
class Block(PandasObject): mask = isna(values) if not self.is_object and not quoting: itemsize = writers.word_len(na_rep) values = values.astype("<U{size}".format(size=itemsize)) else: values = np.array(values, dtype="object")
z assert len(zp.filelist) == 1 archived_file = os.path.basename(zp.filelist[0].filename) assert archived_file == expected_arcname
z assert len(zp.filelist) == 1 archived_file = os.path.basename(zp.filelist[0].filename) assert archived_file == expected_arcname @pytest.mark.parametrize("df_new_type", ["Int64"]) def test_to_csv_na_rep_long_string(self, df_new_type): # see gh-25099 df = pd....
from pandas.core.dtypes.common import ( is_list_like, is_object_dtype, is_scalar, ) from pandas.core.dtypes.dtypes import register_extension_dtype from pandas.core.dtypes.missing import isna
from pandas.core.dtypes.common import ( is_list_like, is_object_dtype, is_scalar, pandas_dtype, ) from pandas.core.dtypes.dtypes import register_extension_dtype from pandas.core.dtypes.missing import isna
class IntegerArray(BaseMaskedArray): if incompatible type with an IntegerDtype, equivalent of same_kind casting """ # if we are astyping to an existing IntegerDtype we can fastpath if isinstance(dtype, _IntegerDtype): result = self._data.astype(dtype.numpy_dt...
class IntegerArray(BaseMaskedArray): if incompatible type with an IntegerDtype, equivalent of same_kind casting """ from pandas.core.arrays.boolean import BooleanArray, BooleanDtype dtype = pandas_dtype(dtype) # if we are astyping to an existing IntegerDtype we ...
class TestCasting: tm.assert_numpy_array_equal(a.astype(str), expected) tm.assert_numpy_array_equal(a.astype("str"), expected) def test_frame_repr(data_missing):
class TestCasting: tm.assert_numpy_array_equal(a.astype(str), expected) tm.assert_numpy_array_equal(a.astype("str"), expected) def test_astype_boolean(self): # https://github.com/pandas-dev/pandas/issues/31102 a = pd.array([1, 0, -1, 2, None], dtype="Int64") result = a.astyp...
class Storage: content = File(content, name) name = self.get_available_name(name, max_length=max_length) return self._save(name, content) # These methods are part of the public API, with default implementations.
class Storage: content = File(content, name) name = self.get_available_name(name, max_length=max_length) name = self._save(name, content) # Ensure that the name returned from the storage system is still valid. validate_file_name(name, allow_relative_path=True) return...
class Storage: Return a filename that's free on the target storage system and available for new content to be written to. """ dir_name, file_name = os.path.split(name) if '..' in pathlib.PurePath(dir_name).parts: raise SuspiciousFileOperation("Detected path traversal ...
class Storage: Return a filename that's free on the target storage system and available for new content to be written to. """ name = str(name).replace('\\', '/') dir_name, file_name = os.path.split(name) if '..' in pathlib.PurePath(dir_name).parts: raise Suspi...
class Storage: Validate the filename by calling get_valid_name() and return a filename to be passed to the save() method. """ # `filename` may include a path as returned by FileField.upload_to. dirname, filename = os.path.split(filename) if '..' in pathlib.PurePath(dirnam...
class Storage: Validate the filename by calling get_valid_name() and return a filename to be passed to the save() method. """ filename = str(filename).replace('\\', '/') # `filename` may include a path as returned by FileField.upload_to. dirname, filename = os.path.split(...
class FileSystemStorage(Storage): if self.file_permissions_mode is not None: os.chmod(full_path, self.file_permissions_mode) # Store filenames with forward slashes, even on Windows. return name.replace('\\', '/')
class FileSystemStorage(Storage): if self.file_permissions_mode is not None: os.chmod(full_path, self.file_permissions_mode) # Ensure the saved path is always relative to the storage root. name = os.path.relpath(full_path, self.location) # Store filenames with forward slashe...
class GenerateFilenameStorageTests(SimpleTestCase): s.generate_filename(file_name) def test_storage_dangerous_paths_dir_name(self): file_name = '/tmp/../path' s = FileSystemStorage() msg = "Detected path traversal attempt in '/tmp/..'" with self.assertRaisesMessa...
class GenerateFilenameStorageTests(SimpleTestCase): s.generate_filename(file_name) def test_storage_dangerous_paths_dir_name(self): candidates = [ ('tmp/../path', 'tmp/..'), ('tmp\\..\\path', 'tmp/..'), ('/tmp/../path', '/tmp/..'), ('\\tmp...
class FileStorageTests(SimpleTestCase): self.storage.delete('path/to/test.file') def test_save_doesnt_close(self): with TemporaryUploadedFile('test', 'text/plain', 1, 'utf8') as file: file.write(b'1')
class FileStorageTests(SimpleTestCase): self.storage.delete('path/to/test.file') def test_file_save_abs_path(self): test_name = 'path/to/test.file' f = ContentFile('file saved with path') f_name = self.storage.save(os.path.join(self.temp_dir, test_name), f) self.assertEqual...
class HMACKey(Key): invalid_strings = [ b'-----BEGIN PUBLIC KEY-----', b'-----BEGIN CERTIFICATE-----', b'ssh-rsa' ]
class HMACKey(Key): invalid_strings = [ b'-----BEGIN PUBLIC KEY-----', b'-----BEGIN RSA PUBLIC KEY-----', b'-----BEGIN CERTIFICATE-----', b'ssh-rsa' ]
class TestHMACAlgorithm: with pytest.raises(JOSEError): HMACKey(key, ALGORITHMS.HS256) key = "-----BEGIN CERTIFICATE-----" with pytest.raises(JOSEError): HMACKey(key, ALGORITHMS.HS256)
class TestHMACAlgorithm: with pytest.raises(JOSEError): HMACKey(key, ALGORITHMS.HS256) key = "-----BEGIN RSA PUBLIC KEY-----" with pytest.raises(JOSEError): HMACKey(key, ALGORITHMS.HS256) key = "-----BEGIN CERTIFICATE-----" with pytest.raises(JOSEError):...
from __future__ import (absolute_import, division, print_function) __metaclass__ = type import os import random import shlex
from __future__ import (absolute_import, division, print_function) __metaclass__ = type import errno import fcntl import os import random import shlex