buggy
stringlengths
35
5.03k
fixed
stringlengths
46
62.5k
class Queries5Tests(TestCase): Note.objects.extra(select={"foo": "'bar %%s'"})[0].foo, "bar %s" ) def test_queryset_reuse(self): # Using querysets doesn't mutate aliases. authors = Author.objects.filter(Q(name="a1") | Q(name="nonexistent"))
class Queries5Tests(TestCase): Note.objects.extra(select={"foo": "'bar %%s'"})[0].foo, "bar %s" ) def test_extra_select_alias_sql_injection(self): crafted_alias = """injected_name" from "queries_note"; --""" msg = ( "Column aliases cannot contain whitespace character...
from pathlib import Path from django.conf import settings from django.http import HttpResponse, HttpResponseNotFound from django.template import Context, Engine, TemplateDoesNotExist from django.template.defaultfilters import force_escape, pprint from django.urls import Resolver404, resolve from django.utils import tim...
from pathlib import Path from django.conf import settings from django.http import HttpResponse, HttpResponseNotFound from django.template import Context, Engine, TemplateDoesNotExist from django.template.defaultfilters import pprint from django.urls import Resolver404, resolve from django.utils import timezone from dja...
class ExceptionReporter: # Trim large blobs of data if len(v) > 4096: v = '%s... <trimmed %d bytes string>' % (v[0:4096], len(v)) frame_vars.append((k, force_escape(v))) frame['vars'] = frame_vars frames[i] =...
class ExceptionReporter: # Trim large blobs of data if len(v) > 4096: v = '%s... <trimmed %d bytes string>' % (v[0:4096], len(v)) frame_vars.append((k, v)) frame['vars'] = frame_vars frames[i] = frame
class ExceptionReporterTests(SimpleTestCase): request = self.rf.get('/test_view/') try: try: raise AttributeError('Top level') except AttributeError as explicit: try: raise ValueError('Second exception') from explicit ...
class ExceptionReporterTests(SimpleTestCase): request = self.rf.get('/test_view/') try: try: raise AttributeError(mark_safe('<p>Top level</p>')) except AttributeError as explicit: try: raise ValueError(mark_safe('<p>Second excep...
class ExceptionReporterTests(SimpleTestCase): html = reporter.get_traceback_html() # Both messages are twice on page -- one rendered as html, # one as plain text (for pastebin) self.assertEqual(2, html.count(explicit_exc.format("Top level"))) self.assertEqual(2, html.count(implic...
class ExceptionReporterTests(SimpleTestCase): html = reporter.get_traceback_html() # Both messages are twice on page -- one rendered as html, # one as plain text (for pastebin) self.assertEqual(2, html.count(explicit_exc.format('&lt;p&gt;Top level&lt;/p&gt;'))) self.assertEqual(2...
class AnsibleModule(object): (k, v) = x.split("=",1) except Exception, e: self.fail_json(msg="this module requires key=value arguments (%s)" % (items)) params[k] = v params2 = json.loads(MODULE_COMPLEX_ARGS) params2.update(params)
class AnsibleModule(object): (k, v) = x.split("=",1) except Exception, e: self.fail_json(msg="this module requires key=value arguments (%s)" % (items)) if k in params: self.fail_json(msg="duplicate parameter: %s (value=%s)" % (k, v)) pa...
import sys import pipes import jinja2 import subprocess import getpass import ansible.constants as C
import sys import pipes import jinja2 import subprocess import shlex import getpass import ansible.constants as C
class Runner(object): return actual_user # *****************************************************
class Runner(object): return actual_user def _count_module_args(self, args): ''' Count the number of k=v pairs in the supplied module args. This is basically a specialized version of parse_kv() from utils with a few minor changes. ''' options = {} if...
class Runner(object): items_terms = self.module_vars.get('items_lookup_terms', '') items_terms = template.template(basedir, items_terms, inject) items = utils.plugins.lookup_loader.get(items_plugin, runner=self, basedir=basedir).run(items_terms, inject=inject) if type(ite...
class Runner(object): items_terms = self.module_vars.get('items_lookup_terms', '') items_terms = template.template(basedir, items_terms, inject) items = utils.plugins.lookup_loader.get(items_plugin, runner=self, basedir=basedir).run(items_terms, inject=inject) # strip out...
class Runner(object): # render module_args and complex_args templates try: module_args = template.template(self.basedir, module_args, inject, fail_on_undefined=self.error_on_undefined_vars) complex_args = template.template(self.basedir, complex_args, inject, fail_on_undefined=se...
class Runner(object): # render module_args and complex_args templates try: # When templating module_args, we need to be careful to ensure # that no variables inadvertantly (or maliciously) add params # to the list of args. We do this by counting the number of k=v ...
class ActionModule(object): self.runner._remote_chmod(conn, 'a+r', xfered, tmp) # run the copy module module_args = "%s src=%s dest=%s original_basename=%s" % (module_args, pipes.quote(xfered), pipes.quote(dest), pipes.quote(os.path.basename(src))) if self.runner.no...
class ActionModule(object): self.runner._remote_chmod(conn, 'a+r', xfered, tmp) # run the copy module new_module_args = dict( src=xfered, dest=dest, original_basename=os.path.basename(src), ) module_args_tmp...
class ActionModule(object): # src and dest here come after original and override them # we pass dest only to make sure it includes trailing slash in case of recursive copy module_args_tmp = "%s src=%s dest=%s original_basename=%s" % (module_args, ...
class ActionModule(object): # src and dest here come after original and override them # we pass dest only to make sure it includes trailing slash in case of recursive copy new_module_args = dict( src=tmp_src, dest=dest, ...
class ActionModule(object): tmp_src = tmp_path + source_rel # Build temporary module_args. module_args_tmp = "%s src=%s original_basename=%s" % (module_args, pipes.quote(tmp_src), pipes.quote(source_rel)) if self.runner.n...
class ActionModule(object): tmp_src = tmp_path + source_rel # Build temporary module_args. new_module_args = dict( src=tmp_src, dest=dest, ) if self.runner.noop_on_check(inject): ...
class ActionModule(object): self.runner._remote_chmod(conn, 'a+r', xfered, tmp) # run the copy module module_args = "%s src=%s dest=%s original_basename=%s" % (module_args, pipes.quote(xfered), pipes.quote(dest), pipes.quote(os.path.basename(source))) if self.runner...
class ActionModule(object): self.runner._remote_chmod(conn, 'a+r', xfered, tmp) # run the copy module new_module_args = dict( src=xfered, dest=dest, original_basename=os.path.basename(source), ) module_args_tmp...
VERBOSITY=0 MAX_FILE_SIZE_FOR_DIFF=1*1024*1024 try: import json except ImportError:
VERBOSITY=0 MAX_FILE_SIZE_FOR_DIFF=1*1024*1024 # caching the compilation of the regex used # to check for lookup calls within data LOOKUP_REGEX=re.compile(r'lookup\s*\(') try: import json except ImportError:
def json_loads(data): return json.loads(data) def _clean_data(orig_data): ''' remove template tags from a string ''' data = orig_data if isinstance(orig_data, basestring): for pattern,replacement in (('{{','{#'), ('}}','#}'), ('{%','{#'), ('%}','#}')): data = data.replace(pattern, ...
def json_loads(data): return json.loads(data) def _clean_data(orig_data, from_remote=False, from_inventory=False): ''' remove template tags from a string ''' data = orig_data if isinstance(orig_data, basestring): sub_list = [('{%','{#'), ('%}','#}')] if from_remote or (from_inventory a...
def parse_json(raw_data, from_remote=False): return { "failed" : True, "parsed" : False, "msg" : orig_data } if from_remote: results = _clean_data_struct(results) return results def smush_braces(data): ''' smush Jinaj2 braces so unresolved templates like {{ foo }} don't get parsed wei...
def parse_json(raw_data, from_remote=False): return { "failed" : True, "parsed" : False, "msg" : orig_data } if from_remote: results = _clean_data_struct(results, from_remote, from_inventory) return results def merge_module_args(current_args, new_args): ''' merges either a diction...
def parse_kv(args): for x in vargs: if "=" in x: k, v = x.split("=",1) options[k]=v return options def merge_hash(a, b):
def parse_kv(args): for x in vargs: if "=" in x: k, v = x.split("=",1) options[k] = v return options def merge_hash(a, b):
def list_intersection(a, b): def safe_eval(expr, locals={}, include_exceptions=False): ''' this is intended for allowing things like: with_items: a_list_variable where Jinja2 would return a string but we do not want to allow it to call functions (outside of Jinja2, where the env is constrained)...
def list_intersection(a, b): def safe_eval(expr, locals={}, include_exceptions=False): ''' This is intended for allowing things like: with_items: a_list_variable Where Jinja2 would return a string but we do not want to allow it to call functions (outside of Jinja2, where the env is constrained). I...
from pandas.core.dtypes.common import ( is_unsigned_integer_dtype, pandas_dtype, ) from pandas.core.dtypes.generic import ABCIndexClass, ABCPeriodArray, ABCSeries from pandas.core.dtypes.inference import is_array_like from pandas.core.dtypes.missing import is_valid_nat_for_dtype, isna
from pandas.core.dtypes.common import ( is_unsigned_integer_dtype, pandas_dtype, ) from pandas.core.dtypes.generic import ABCSeries from pandas.core.dtypes.inference import is_array_like from pandas.core.dtypes.missing import is_valid_nat_for_dtype, isna
default 'raise' def _round(self, freq, mode, ambiguous, nonexistent): # round the local times values = _ensure_datetimelike_to_i8(self) result = round_nsint64(values, mode, freq) result = self._maybe_mask_results(result, fill_value=NaT) dtype = self.dtype if is_date...
default 'raise' def _round(self, freq, mode, ambiguous, nonexistent): # round the local times if is_datetime64tz_dtype(self): # operate on naive timestamps, then convert back to aware naive = self.tz_localize(None) result = naive._round(freq, mode, ambiguous, non...
class DatetimeLikeArrayMixin(ExtensionOpsMixin, AttributesMixin, ExtensionArray) self._freq = result._freq return self # -------------------------------------------------------------- # Comparison Methods def _ensure_localized( self, arg, ambiguous="raise", nonexistent="raise",...
class DatetimeLikeArrayMixin(ExtensionOpsMixin, AttributesMixin, ExtensionArray) self._freq = result._freq return self # -------------------------------------------------------------- # Reductions
def maybe_infer_freq(freq): freq_infer = True freq = None return freq, freq_infer def _ensure_datetimelike_to_i8(other, to_utc=False): """ Helper for coercing an input scalar or array to i8. Parameters ---------- other : 1d array to_utc : bool, default False ...
def maybe_infer_freq(freq): freq_infer = True freq = None return freq, freq_infer
from pandas.util._decorators import Appender, cache_readonly from pandas.core.dtypes.common import ( ensure_int64, is_bool_dtype, is_dtype_equal, is_float, is_integer, is_list_like, is_period_dtype, is_scalar, ) from pandas.core.dtypes.concat import concat_compat from pandas.core.dtypes....
from pandas.util._decorators import Appender, cache_readonly from pandas.core.dtypes.common import ( ensure_int64, is_bool_dtype, is_categorical_dtype, is_dtype_equal, is_float, is_integer, is_list_like, is_period_dtype, is_scalar, needs_i8_conversion, ) from pandas.core.dtypes.c...
from pandas.core.arrays import ( ExtensionOpsMixin, TimedeltaArray, ) from pandas.core.arrays.datetimelike import ( DatetimeLikeArrayMixin, _ensure_datetimelike_to_i8, ) import pandas.core.indexes.base as ibase from pandas.core.indexes.base import Index, _index_shared_docs from pandas.core.indexes.numer...
from pandas.core.arrays import ( ExtensionOpsMixin, TimedeltaArray, ) from pandas.core.arrays.datetimelike import DatetimeLikeArrayMixin import pandas.core.indexes.base as ibase from pandas.core.indexes.base import Index, _index_shared_docs from pandas.core.indexes.numeric import Int64Index
class DatetimeIndexOpsMixin(ExtensionIndex, ExtensionOpsMixin): return np.array_equal(self.asi8, other.asi8) def _ensure_localized( self, arg, ambiguous="raise", nonexistent="raise", from_utc=False ): # See DatetimeLikeArrayMixin._ensure_localized.__doc__ if getattr(self, "tz",...
class DatetimeIndexOpsMixin(ExtensionIndex, ExtensionOpsMixin): return np.array_equal(self.asi8, other.asi8) @Appender(_index_shared_docs["contains"] % _index_doc_kwargs) def __contains__(self, key): try:
class DatetimeIndexOpsMixin(ExtensionIndex, ExtensionOpsMixin): @Appender(_index_shared_docs["where"] % _index_doc_kwargs) def where(self, cond, other=None): other = _ensure_datetimelike_to_i8(other, to_utc=True) values = _ensure_datetimelike_to_i8(self, to_utc=True) result = np.where(c...
class DatetimeIndexOpsMixin(ExtensionIndex, ExtensionOpsMixin): @Appender(_index_shared_docs["where"] % _index_doc_kwargs) def where(self, cond, other=None): values = self.view("i8") if is_scalar(other) and isna(other): other = NaT.value else: # Do type inferen...
class TestWhere: i2 = i.copy() i2 = Index([pd.NaT, pd.NaT] + i[2:].tolist()) result = i.where(notna(i2), i2.values) tm.assert_index_equal(result, i2) def test_where_tz(self): i = pd.date_range("20130101", periods=3, tz="US/Eastern") result = i.where(notna(i))
class TestWhere: i2 = i.copy() i2 = Index([pd.NaT, pd.NaT] + i[2:].tolist()) result = i.where(notna(i2), i2._values) tm.assert_index_equal(result, i2) def test_where_invalid_dtypes(self): dti = pd.date_range("20130101", periods=3, tz="US/Eastern") i2 = dti.copy() ...
class TestWhere: result = i.where(notna(i2), i2.values) tm.assert_index_equal(result, i2) class TestTake: def test_take(self):
class TestWhere: result = i.where(notna(i2), i2.values) tm.assert_index_equal(result, i2) def test_where_invalid_dtypes(self): pi = period_range("20130101", periods=5, freq="D") i2 = pi.copy() i2 = pd.PeriodIndex([pd.NaT, pd.NaT] + pi[2:].tolist(), freq="D") with p...
import numpy as np import pytest import pandas as pd from pandas import Index, Timedelta, TimedeltaIndex, timedelta_range import pandas._testing as tm
import numpy as np import pytest import pandas as pd from pandas import Index, Timedelta, TimedeltaIndex, notna, timedelta_range import pandas._testing as tm
class TestGetItem: class TestWhere: # placeholder for symmetry with DatetimeIndex and PeriodIndex tests pass class TestTake:
class TestGetItem: class TestWhere: def test_where_invalid_dtypes(self): tdi = timedelta_range("1 day", periods=3, freq="D", name="idx") i2 = tdi.copy() i2 = Index([pd.NaT, pd.NaT] + tdi[2:].tolist()) with pytest.raises(TypeError, match="Where requires matching dtype"): ...
class TestFormatSelection(unittest.TestCase): def test_format_selection_string_ops(self): formats = [ {'format_id': 'abc-cba', 'ext': 'mp4', 'url': TEST_URL}, ] info_dict = _make_result(formats)
class TestFormatSelection(unittest.TestCase): def test_format_selection_string_ops(self): formats = [ {'format_id': 'abc-cba', 'ext': 'mp4', 'url': TEST_URL}, {'format_id': 'zxc-cxz', 'ext': 'webm', 'url': TEST_URL}, ] info_dict = _make_result(formats)
class TestFormatSelection(unittest.TestCase): # does not equal (!=) ydl = YDL({'format': '[format_id!=abc-cba]'}) self.assertRaises(ExtractorError, ydl.process_ie_result, info_dict.copy()) # starts with (^=)
class TestFormatSelection(unittest.TestCase): # does not equal (!=) ydl = YDL({'format': '[format_id!=abc-cba]'}) ydl.process_ie_result(info_dict.copy()) downloaded = ydl.downloaded_info_dicts[0] self.assertEqual(downloaded['format_id'], 'zxc-cxz') ydl = YDL({'format': ...
class TestFormatSelection(unittest.TestCase): self.assertEqual(downloaded['format_id'], 'abc-cba') # does not start with (!^=) ydl = YDL({'format': '[format_id!^=abc-cba]'}) self.assertRaises(ExtractorError, ydl.process_ie_result, info_dict.copy()) # ends with ($=)
class TestFormatSelection(unittest.TestCase): self.assertEqual(downloaded['format_id'], 'abc-cba') # does not start with (!^=) ydl = YDL({'format': '[format_id!^=abc]'}) ydl.process_ie_result(info_dict.copy()) downloaded = ydl.downloaded_info_dicts[0] self.assertEqual(do...
class TestFormatSelection(unittest.TestCase): self.assertEqual(downloaded['format_id'], 'abc-cba') # does not end with (!$=) ydl = YDL({'format': '[format_id!$=abc-cba]'}) self.assertRaises(ExtractorError, ydl.process_ie_result, info_dict.copy()) # contains (*=) ydl = Y...
class TestFormatSelection(unittest.TestCase): self.assertEqual(downloaded['format_id'], 'abc-cba') # does not end with (!$=) ydl = YDL({'format': '[format_id!$=cba]'}) ydl.process_ie_result(info_dict.copy()) downloaded = ydl.downloaded_info_dicts[0] self.assertEqual(down...
class YoutubeDL(object): comparison_value = m.group('value') str_op = STR_OPERATORS[m.group('op')] if m.group('negation'): op = lambda attr, value: not str_op else: op = str_op
class YoutubeDL(object): comparison_value = m.group('value') str_op = STR_OPERATORS[m.group('op')] if m.group('negation'): op = lambda attr, value: not str_op(attr, value) else: op = str_op
class TimedeltaIndex( @Appender(_shared_docs["searchsorted"]) def searchsorted(self, value, side="left", sorter=None): if isinstance(value, (np.ndarray, Index)): value = np.array(value, dtype=_TD_DTYPE, copy=False) else: value = Timedelta(value).asm8.view(_TD_DTYPE) ...
class TimedeltaIndex( @Appender(_shared_docs["searchsorted"]) def searchsorted(self, value, side="left", sorter=None): if isinstance(value, (np.ndarray, Index)): if not type(self._data)._is_recognized_dtype(value): raise TypeError( "searchsorted requires c...
class TestTimedeltaArray: arr[0] = obj assert arr[0] == pd.Timedelta(seconds=1) class TestReductions: @pytest.mark.parametrize("name", ["sum", "std", "min", "max", "median"])
class TestTimedeltaArray: arr[0] = obj assert arr[0] == pd.Timedelta(seconds=1) @pytest.mark.parametrize( "other", [ 1, np.int64(1), 1.0, np.datetime64("NaT"), pd.Timestamp.now(), "invalid", np.arang...
class CategoricalDtype(PandasExtensionDtype, ExtensionDtype): raise ValueError( "Cannot specify `categories` or `ordered` together with `dtype`." ) elif is_categorical(values): # If no "dtype" was passed, use the one from "values", but honor ...
class CategoricalDtype(PandasExtensionDtype, ExtensionDtype): raise ValueError( "Cannot specify `categories` or `ordered` together with `dtype`." ) elif not isinstance(dtype, CategoricalDtype): raise ValueError(f"Cannot not construct Catego...
class TestCategoricalDtype(Base): with pytest.raises(ValueError, match=msg): CategoricalDtype._from_values_or_dtype(values, categories, ordered, dtype) def test_is_dtype(self, dtype): assert CategoricalDtype.is_dtype(dtype) assert CategoricalDtype.is_dtype("category")
class TestCategoricalDtype(Base): with pytest.raises(ValueError, match=msg): CategoricalDtype._from_values_or_dtype(values, categories, ordered, dtype) def test_from_values_or_dtype_invalid_dtype(self): msg = "Cannot not construct CategoricalDtype from <class 'object'>" with pyt...
class Base: assert not indices.equals(np.array(indices)) # Cannot pass in non-int64 dtype to RangeIndex if not isinstance(indices, RangeIndex): same_values = Index(indices, dtype=object) assert indices.equals(same_values) assert same_values.equals(indices)
class Base: assert not indices.equals(np.array(indices)) # Cannot pass in non-int64 dtype to RangeIndex if not isinstance(indices, (RangeIndex, CategoricalIndex)): # TODO: CategoricalIndex can be re-allowed following GH#32167 same_values = Index(indices, dtype=object) ...
def _parse_octet(cls, octet_str): raise ValueError(msg % octet_str) # Convert to integer (we know digits are legal) octet_int = int(octet_str, 10) # Any octets that look like they *might* be written in octal, # and which don't look exactly the same in both octal and #...
def _parse_octet(cls, octet_str): raise ValueError(msg % octet_str) # Convert to integer (we know digits are legal) octet_int = int(octet_str, 10) if octet_int > 255: raise ValueError("Octet %d (> 255) not permitted" % octet_int) return octet_int
def pickle_test(self, addr): y = pickle.loads(pickle.dumps(x, proto)) self.assertEqual(y, x) class CommonTestMixin_v4(CommonTestMixin): def test_leading_zeros(self): self.assertInstancesEqual("000.000.000.000", "0.0.0.0") self.assertInstancesEqual("192.168.000.001",...
def pickle_test(self, addr): y = pickle.loads(pickle.dumps(x, proto)) self.assertEqual(y, x) class CommonTestMixin_v4(CommonTestMixin): def test_leading_zeros(self): self.assertInstancesEqual("000.000.000.000", "0.0.0.0") self.assertInstancesEqual("192.168.000.001"...
def assertBadOctet(addr, octet): assertBadOctet("1.2.3.4::", "4::") assertBadOctet("1.a.2.3", "a") def test_octal_decimal_ambiguity(self): def assertBadOctet(addr, octet): msg = "Ambiguous (octal/decimal) value in %r not permitted in %r" with self.assertAddressError(...
def assertBadOctet(addr, octet): assertBadOctet("1.2.3.4::", "4::") assertBadOctet("1.a.2.3", "a") def test_octet_length(self): def assertBadOctet(addr, octet): msg = "At most 3 characters permitted in %r in %r"
class Model(Container): @interfaces.legacy_generator_methods_support def fit_generator(self, generator, steps_per_epoch, epochs=1, verbose=1, callbacks=None,
class Model(Container): @interfaces.legacy_generator_methods_support def fit_generator(self, generator, steps_per_epoch=None, epochs=1, verbose=1, callbacks=None,
class Model(Container): to yield from `generator` before declaring one epoch finished and starting the next epoch. It should typically be equal to the number of samples of your dataset divided by the batch size. Not used if using `Sequence`. ep...
class Model(Container): to yield from `generator` before declaring one epoch finished and starting the next epoch. It should typically be equal to the number of samples of your dataset divided by the batch size. Optional for `Sequence`: if ...
class Model(Container): validation_steps: Only relevant if `validation_data` is a generator. Total number of steps (batches of samples) to yield from `generator` before stopping. class_weight: Dictionary mapping class indices to a weight for the cl...
class Model(Container): validation_steps: Only relevant if `validation_data` is a generator. Total number of steps (batches of samples) to yield from `generator` before stopping. Optional for `Sequence`: if unspecified, will use the `len(valida...
class Model(Container): if do_validation: self._make_test_function() # python 2 has 'next', 3 has '__next__' # avoid any explicit version checks val_gen = (hasattr(validation_data, 'next') or hasattr(validation_data, '__next__') or isins...
class Model(Container): if do_validation: self._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`' ...
class Model(Container): val_data += [0.] for cbk in callbacks: cbk.validation_data = val_data is_sequence = isinstance(generator, Sequence) if not is_sequence and use_multiprocessing and workers > 1: warnings.warn( UserWarning('Usin...
class Model(Container): val_data += [0.] for cbk in callbacks: cbk.validation_data = val_data enqueuer = None try:
class Model(Container): return self.history @interfaces.legacy_generator_methods_support def evaluate_generator(self, generator, steps, max_queue_size=10, workers=1, use_multiprocessing=False):
class Model(Container): return self.history @interfaces.legacy_generator_methods_support def evaluate_generator(self, generator, steps=None, max_queue_size=10, workers=1, use_multiprocessing=False):
class Model(Container): when using multiprocessing. steps: Total number of steps (batches of samples) to yield from `generator` before stopping. Not used if using Sequence. max_queue_size: maximum size for the generator queue worker...
class Model(Container): when using multiprocessing. steps: Total number of steps (batches of samples) to yield from `generator` before stopping. Optional for `Sequence`: if unspecified, will use the `len(generator)` as a number of steps. ...
class Model(Container): ' and multiple workers may duplicate your data.' ' Please consider using the`keras.utils.Sequence' ' class.')) if is_sequence: steps = len(generator) enqueuer = None try:
class Model(Container): ' and multiple workers may duplicate your data.' ' Please consider using the`keras.utils.Sequence' ' class.')) if steps is None: if is_sequence: steps = len(generator) ...
class Model(Container): return averages @interfaces.legacy_generator_methods_support def predict_generator(self, generator, steps, max_queue_size=10, workers=1, use_multiprocessing=False,
class Model(Container): return averages @interfaces.legacy_generator_methods_support def predict_generator(self, generator, steps=None, max_queue_size=10, workers=1, use_multiprocessing=False,
class Model(Container): when using multiprocessing. steps: Total number of steps (batches of samples) to yield from `generator` before stopping. Not used if using Sequence. max_queue_size: Maximum size for the generator queue. worke...
class Model(Container): when using multiprocessing. steps: Total number of steps (batches of samples) to yield from `generator` before stopping. Optional for `Sequence`: if unspecified, will use the `len(generator)` as a number of steps. ...
class Model(Container): ' and multiple workers may duplicate your data.' ' Please consider using the`keras.utils.Sequence' ' class.')) if is_sequence: steps = len(generator) enqueuer = None try:
class Model(Container): ' and multiple workers may duplicate your data.' ' Please consider using the`keras.utils.Sequence' ' class.')) if steps is None: if is_sequence: steps = len(generator) ...
class Sequential(Model): @interfaces.legacy_generator_methods_support def fit_generator(self, generator, steps_per_epoch, epochs=1, verbose=1, callbacks=None,
class Sequential(Model): @interfaces.legacy_generator_methods_support def fit_generator(self, generator, steps_per_epoch=None, epochs=1, verbose=1, callbacks=None,
class Sequential(Model): finished and starting the next epoch. It should typically be equal to the number of samples of your dataset divided by the batch size. epochs: Integer, total number of iterations on the data. Note that in conjunction wi...
class Sequential(Model): finished and starting the next epoch. It should typically be equal to the number of samples of your dataset divided by the batch size. Optional for `Sequence`: if unspecified, will use the `len(generator)` as a numb...
class Sequential(Model): at the end of every epoch. It should typically be equal to the number of samples of your validation dataset divided by the batch size. class_weight: Dictionary mapping class indices to a weight for the class. ...
class Sequential(Model): at the end of every epoch. It should typically be equal to the number of samples of your validation dataset divided by the batch size. Optional for `Sequence`: if unspecified, will use the `len(validation_data)` as ...
class Sequential(Model): initial_epoch=initial_epoch) @interfaces.legacy_generator_methods_support def evaluate_generator(self, generator, steps, max_queue_size=10, workers=1, use_multiprocessing=False): """Ev...
class Sequential(Model): initial_epoch=initial_epoch) @interfaces.legacy_generator_methods_support def evaluate_generator(self, generator, steps=None, max_queue_size=10, workers=1, use_multiprocessing=False): ...
class Sequential(Model): or (inputs, targets, sample_weights) steps: Total number of steps (batches of samples) to yield from `generator` before stopping. max_queue_size: maximum size for the generator queue workers: maximum number of processes to spin...
class Sequential(Model): or (inputs, targets, sample_weights) steps: Total number of steps (batches of samples) to yield from `generator` before stopping. Optional for `Sequence`: if unspecified, will use the `len(generator)` as a number of ste...
class Sequential(Model): use_multiprocessing=use_multiprocessing) @interfaces.legacy_generator_methods_support def predict_generator(self, generator, steps, max_queue_size=10, workers=1, use_multiprocessing=False, ...
class Sequential(Model): use_multiprocessing=use_multiprocessing) @interfaces.legacy_generator_methods_support def predict_generator(self, generator, steps=None, max_queue_size=10, workers=1, use_multiprocessing=Fa...
class Sequential(Model): generator: generator yielding batches of input samples. steps: Total number of steps (batches of samples) to yield from `generator` before stopping. max_queue_size: maximum size for the generator queue workers: maximum number of pr...
class Sequential(Model): generator: generator yielding batches of input samples. steps: Total number of steps (batches of samples) to yield from `generator` before stopping. Optional for `Sequence`: if unspecified, will use the `len(generator)` as ...
def test_model_methods(): # test starting from non-zero initial epoch trained_epochs = [] # define tracer callback def on_epoch_begin(epoch, logs): trained_epochs.append(epoch) tracker_cb = LambdaCallback(on_epoch_begin=on_epoch_begin) out = model.fit([input_a_np, input_b_np], ...
def test_model_methods(): # test starting from non-zero initial epoch trained_epochs = [] trained_batches = [] # define tracer callback def on_epoch_begin(epoch, logs): trained_epochs.append(epoch) def on_batch_begin(batch, logs): trained_batches.append(batch) tracker_cb ...
def test_model_methods(): model.compile(optimizer, loss, metrics=[], loss_weights=loss_weights, sample_weight_mode=None) trained_epochs = [] out = model.fit_generator(generator=RandomSequence(3), steps_per_epoch=12, epochs=5, initial_epoch=0, validation_data=R...
def test_model_methods(): model.compile(optimizer, loss, metrics=[], loss_weights=loss_weights, sample_weight_mode=None) trained_epochs = [] trained_batches = [] out = model.fit_generator(generator=RandomSequence(3), steps_per_epoch=3, epochs=5, initial_ep...
class TestUtil(unittest.TestCase): self.assertEqual(url_basename(u'http://foo.de/bar/baz?x=y'), u'baz') self.assertEqual(url_basename(u'http://foo.de/bar/baz#x=y'), u'baz') self.assertEqual(url_basename(u'http://foo.de/bar/baz/'), u'baz') if __name__ == '__main__': unittest.main()
class TestUtil(unittest.TestCase): self.assertEqual(url_basename(u'http://foo.de/bar/baz?x=y'), u'baz') self.assertEqual(url_basename(u'http://foo.de/bar/baz#x=y'), u'baz') self.assertEqual(url_basename(u'http://foo.de/bar/baz/'), u'baz') self.assertEqual( url_basename(u'http...
def remove_start(s, start): def url_basename(url): m = re.match(r'(?:https?:|)//[^/]+/(?:[^/?#]+/)?([^/?#]+)/?(?:[?#]|$)', url) if not m: return u'' return m.group(1)
def remove_start(s, start): def url_basename(url): m = re.match(r'(?:https?:|)//[^/]+/(?:[^?#]+/)?([^/?#]+)/?(?:[?#]|$)', url) if not m: return u'' return m.group(1)
def _create_instance(self, context, instance_type, security_group, block_device_mapping) instances.append(instance) instance_uuids.append(instance['uuid']) # In the case of any exceptions, attempt DB cleanup and rollback the # quota reservations.
def _create_instance(self, context, instance_type, security_group, block_device_mapping) instances.append(instance) instance_uuids.append(instance['uuid']) self._validate_bdm(context, instance) # send a state update notification for...
def _update_block_device_mapping(self, elevated_context, self.db.block_device_mapping_update_or_create(elevated_context, values) def _populate_instance_for_bdm(self, context, instance, instance_type, image, block_device_mapping): ...
def _update_block_device_mapping(self, elevated_context, self.db.block_device_mapping_update_or_create(elevated_context, values) def _validate_bdm(self, context, instance): for bdm in self.db.block_device_mapping_get_all_by_instance( ...
def create_db_entry_for_new_instance(self, context, instance_type, image, self._populate_instance_for_bdm(context, instance, instance_type, image, block_device_mapping) # send a state update notification for the initial create to # show it going from non-existent to BUILDING ...
def create_db_entry_for_new_instance(self, context, instance_type, image, self._populate_instance_for_bdm(context, instance, instance_type, image, block_device_mapping) return instance def _check_create_policies(self, context, availability_zone,
class InvalidSnapshot(Invalid): message = _("Invalid snapshot") + ": %(reason)s" class VolumeUnattached(Invalid): message = _("Volume %(volume_id)s is not attached to anything")
class InvalidSnapshot(Invalid): message = _("Invalid snapshot") + ": %(reason)s" class InvalidBDM(Invalid): message = _("Block Device Mapping is Invalid.") class InvalidBDMSnapshot(InvalidBDM): message = _("Block Device Mapping is Invalid: " "failed to get snapshot %(id)s.") class Inva...
class TestUtil(unittest.TestCase): self.assertEqual(parse_duration('0s'), 0) self.assertEqual(parse_duration('01:02:03.05'), 3723.05) self.assertEqual(parse_duration('T30M38S'), 1838) def test_fix_xml_ampersands(self): self.assertEqual(
class TestUtil(unittest.TestCase): self.assertEqual(parse_duration('0s'), 0) self.assertEqual(parse_duration('01:02:03.05'), 3723.05) self.assertEqual(parse_duration('T30M38S'), 1838) self.assertEqual(parse_duration('5 s'), 5) self.assertEqual(parse_duration('3 min'), 180) ...
from ..compat import ( ) from ..utils import ( int_or_none, parse_filesize, )
from ..compat import ( ) from ..utils import ( int_or_none, parse_duration, parse_filesize, )
class MinhatecaIE(InfoExtractor): filesize_approx = parse_filesize(self._html_search_regex( r'<p class="fileSize">(.*?)</p>', webpage, 'file size approximation', fatal=False)) duration = int_or_none(self._html_search_regex( r'(?s)<p class="fileLeng[ht][th]">.*?([0-9]+...
class MinhatecaIE(InfoExtractor): filesize_approx = parse_filesize(self._html_search_regex( r'<p class="fileSize">(.*?)</p>', webpage, 'file size approximation', fatal=False)) duration = parse_duration(self._html_search_regex( r'(?s)<p class="fileLeng[ht][th]">.*?clas...
def parse_duration(s): m = re.match( r'''(?ix)T? (?: (?:(?P<hours>[0-9]+)\s*(?:[:h]|hours?)\s*)? (?P<mins>[0-9]+)\s*(?:[:m]|mins?|minutes?)\s* )? (?P<secs>[0-9]+)(?P<ms>\.[0-9]+)?\s*(?:s|secs?|seconds?)?$''', s) if not m: retur...
def parse_duration(s): m = re.match( r'''(?ix)T? (?: (?P<only_mins>[0-9.]+)\s*(?:mins?|minutes?)\s*| (?P<only_hours>[0-9.]+)\s*(?:hours?)| (?: (?:(?P<hours>[0-9]+)\s*(?:[:h]|hours?)\s*)? (?P<mins>[0-9]+)\s*(?:[:m]|mins?|minutes?)\...
import asyncio from asyncio.base_events import BaseEventLoop from concurrent.futures import Executor, ProcessPoolExecutor from functools import partial import keyword import os from pathlib import Path import tokenize import sys from typing import ( Dict, Generic, Iterable, Iterator, List, Optional, Set, Tuple, Typ...
import asyncio from asyncio.base_events import BaseEventLoop from concurrent.futures import Executor, ProcessPoolExecutor from functools import partial, wraps import keyword import os from pathlib import Path import tokenize import sys from typing import ( Callable, Dict, Generic, Iterable, Iterator...
Depth = int NodeType = int LeafID = int Priority = int LN = Union[Leaf, Node] out = partial(click.secho, bold=True, err=True) err = partial(click.secho, fg='red', err=True)
Depth = int NodeType = int LeafID = int Priority = int Index = int LN = Union[Leaf, Node] SplitFunc = Callable[['Line', bool], Iterator['Line']] out = partial(click.secho, bold=True, err=True) err = partial(click.secho, fg='red', err=True)
class Line: depth: int = 0 leaves: List[Leaf] = Factory(list) comments: Dict[LeafID, Leaf] = Factory(dict) bracket_tracker: BracketTracker = Factory(BracketTracker) inside_brackets: bool = False has_for: bool = False
class Line: depth: int = 0 leaves: List[Leaf] = Factory(list) comments: List[Tuple[Index, Leaf]] = Factory(list) bracket_tracker: BracketTracker = Factory(BracketTracker) inside_brackets: bool = False has_for: bool = False
class Line: self.bracket_tracker.mark(leaf) self.maybe_remove_trailing_comma(leaf) self.maybe_increment_for_loop_variable(leaf) if self.maybe_adapt_standalone_comment(leaf): return if not self.append_comment(leaf): self.leaves.append(l...
class Line: self.bracket_tracker.mark(leaf) self.maybe_remove_trailing_comma(leaf) self.maybe_increment_for_loop_variable(leaf) if not self.append_comment(leaf): self.leaves.append(leaf) def append_safe(self, leaf: Leaf, preformatted: bool = False) -> None: ...
class Line: and self.leaves[0].value == 'yield' ) def maybe_remove_trailing_comma(self, closing: Leaf) -> bool: """Remove trailing comma if there is one and it's safe.""" if not (
class Line: and self.leaves[0].value == 'yield' ) @property def contains_standalone_comments(self) -> bool: """If so, needs to be split before emitting.""" for leaf in self.leaves: if leaf.type == STANDALONE_COMMENT: return True return Fa...
class Line: return False if closing.type == token.RBRACE: self.leaves.pop() return True if closing.type == token.RSQB: comma = self.leaves[-1] if comma.parent and comma.parent.type == syms.listmaker: self.leaves.pop() ...
class Line: return False if closing.type == token.RBRACE: self.remove_trailing_comma() return True if closing.type == token.RSQB: comma = self.leaves[-1] if comma.parent and comma.parent.type == syms.listmaker: self.remove_tra...
class Line: break if commas > 1: self.leaves.pop() return True return False
class Line: break if commas > 1: self.remove_trailing_comma() return True return False
class Line: return False def maybe_adapt_standalone_comment(self, comment: Leaf) -> bool: """Hack a standalone comment to act as a trailing comment for line splitting. If this line has brackets and a standalone `comment`, we need to adapt it to be able to still reformat the line. ...
class Line: return False def append_comment(self, comment: Leaf) -> bool: """Add an inline or standalone comment to the line.""" if ( comment.type == STANDALONE_COMMENT and self.bracket_tracker.any_open_brackets() ): comment.prefix = '' ...
class Line: res = f'{first.prefix}{indent}{first.value}' for leaf in leaves: res += str(leaf) for comment in self.comments.values(): res += str(comment) return res + '\n'
class Line: res = f'{first.prefix}{indent}{first.value}' for leaf in leaves: res += str(leaf) for _, comment in self.comments: res += str(comment) return res + '\n'
class UnformattedLines(Line): """Does nothing and returns False.""" return False def maybe_adapt_standalone_comment(self, comment: Leaf) -> bool: """Does nothing and returns False.""" return False @dataclass class EmptyLineTracker:
class UnformattedLines(Line): """Does nothing and returns False.""" return False @dataclass class EmptyLineTracker:
def split_line( If `py36` is True, splitting may generate syntax that is only compatible with Python 3.6 and later. """ if isinstance(line, UnformattedLines): yield line return line_str = str(line).strip('\n') if len(line_str) <= line_length and '\n' not in line_str: yie...
def split_line( If `py36` is True, splitting may generate syntax that is only compatible with Python 3.6 and later. """ if isinstance(line, UnformattedLines) or line.is_comment: yield line return line_str = str(line).strip('\n') if ( len(line_str) <= line_length ...
def split_line( # split altogether. result: List[Line] = [] try: for l in split_func(line, py36=py36): if str(l).strip('\n') == line_str: raise CannotSplit("Split function returned an unchanged result")
def split_line( # split altogether. result: List[Line] = [] try: for l in split_func(line, py36): if str(l).strip('\n') == line_str: raise CannotSplit("Split function returned an unchanged result")
def left_hand_split(line: Line, py36: bool = False) -> Iterator[Line]: ): for leaf in leaves: result.append(leaf, preformatted=True) comment_after = line.comments.get(id(leaf)) if comment_after: result.append(comment_after, preformatted=True) bracket_s...
def left_hand_split(line: Line, py36: bool = False) -> Iterator[Line]: ): for leaf in leaves: result.append(leaf, preformatted=True) for comment_after in line.comments_after(leaf): result.append(comment_after, preformatted=True) bracket_split_succeeded_or_raise(he...
def right_hand_split(line: Line, py36: bool = False) -> Iterator[Line]: ): for leaf in leaves: result.append(leaf, preformatted=True) comment_after = line.comments.get(id(leaf)) if comment_after: result.append(comment_after, preformatted=True) bracket_...
def right_hand_split(line: Line, py36: bool = False) -> Iterator[Line]: ): for leaf in leaves: result.append(leaf, preformatted=True) for comment_after in line.comments_after(leaf): result.append(comment_after, preformatted=True) bracket_split_succeeded_or_raise(h...
def bracket_split_succeeded_or_raise(head: Line, body: Line, tail: Line) -> None ) def delimiter_split(line: Line, py36: bool = False) -> Iterator[Line]: """Split according to delimiters of the highest priority. This kind of split doesn't increase indentation. If `py36` is True, the split wil...
def bracket_split_succeeded_or_raise(head: Line, body: Line, tail: Line) -> None ) def dont_increase_indentation(split_func: SplitFunc) -> SplitFunc: """Normalize prefix of the first leaf in every line returned by `split_func`. This is a decorator over relevant split functions. """ @wrap...
def delimiter_split(line: Line, py36: bool = False) -> Iterator[Line]: current_line = Line(depth=line.depth, inside_brackets=line.inside_brackets) lowest_depth = sys.maxsize trailing_comma_safe = True for leaf in line.leaves: current_line.append(leaf, preformatted=True) comment_after = l...
def delimiter_split(line: Line, py36: bool = False) -> Iterator[Line]: current_line = Line(depth=line.depth, inside_brackets=line.inside_brackets) lowest_depth = sys.maxsize trailing_comma_safe = True def append_to_line(leaf: Leaf) -> Iterator[Line]: """Append `leaf` to current line or to new l...
def delimiter_split(line: Line, py36: bool = False) -> Iterator[Line]: trailing_comma_safe = trailing_comma_safe and py36 leaf_priority = delimiters.get(id(leaf)) if leaf_priority == delimiter_priority: normalize_prefix(current_line.leaves[0], inside_brackets=True) yi...
def delimiter_split(line: Line, py36: bool = False) -> Iterator[Line]: trailing_comma_safe = trailing_comma_safe and py36 leaf_priority = delimiters.get(id(leaf)) if leaf_priority == delimiter_priority: yield current_line current_line = Line(depth=line.depth, inside_...
def delimiter_split(line: Line, py36: bool = False) -> Iterator[Line]: and trailing_comma_safe ): current_line.append(Leaf(token.COMMA, ',')) normalize_prefix(current_line.leaves[0], inside_brackets=True) yield current_line
def delimiter_split(line: Line, py36: bool = False) -> Iterator[Line]: and trailing_comma_safe ): current_line.append(Leaf(token.COMMA, ',')) yield current_line @dont_increase_indentation def standalone_comment_split(line: Line, py36: bool = False) -> Iterator[Line]: """Spl...
class BlackTestCase(unittest.TestCase): black.assert_equivalent(source, actual) black.assert_stable(source, actual, line_length=ll) @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, line_length=ll) @patch("black.dump_to_file", dump_to_stderr) def test_comments3(self) -> None: source, expected = read_data('comments3') actual = fs(source) ...
def fit_generator(model, elif val_gen: val_data = validation_data if isinstance(val_data, Sequence): val_enqueuer_gen = iter_sequence_infinite(generator) else: val_enqueuer_gen = val_data else:
def fit_generator(model, elif val_gen: val_data = validation_data if isinstance(val_data, Sequence): val_enqueuer_gen = iter_sequence_infinite(val_data) validation_steps = validation_steps or len(val_data) else: ...
def test_model_methods(): assert trained_batches == list(range(12)) * 5 assert len(val_seq.logs) == 12 * 5 # fit_generator will throw an exception # if steps is unspecified for regular generator with pytest.raises(ValueError):
def test_model_methods(): assert trained_batches == list(range(12)) * 5 assert len(val_seq.logs) == 12 * 5 # test for workers = 0 trained_epochs = [] trained_batches = [] val_seq = RandomSequence(4) out = model.fit_generator(generator=RandomSequence(3), epochs=...
else: def parse_cookie(cookie): if cookie == '': return {} if not isinstance(cookie, http_cookies.BaseCookie): try: c = SimpleCookie() c.load(cookie) except http_cookies.CookieError: # Invalid cookie return {} else: c = cookie...
else: def parse_cookie(cookie): """ Return a dictionary parsed from a `Cookie:` header string. """ cookiedict = {} if six.PY2: cookie = force_str(cookie) for chunk in cookie.split(str(';')): if str('=') in chunk: key, val = chunk.split(str('='), 1) else: ...
from django.http import ( from django.test import TestCase from django.utils import six from django.utils._os import upath from django.utils.encoding import force_text, smart_str from django.utils.functional import lazy lazystr = lazy(force_text, six.text_type)
from django.http import ( from django.test import TestCase from django.utils import six from django.utils._os import upath from django.utils.encoding import force_str, force_text, smart_str from django.utils.functional import lazy lazystr = lazy(force_text, six.text_type)
class CookieTests(unittest.TestCase): c2 = SimpleCookie() c2.load(c.output()[12:]) self.assertEqual(c['test'].value, c2['test'].value) def test_decode_2(self): """
class CookieTests(unittest.TestCase): c2 = SimpleCookie() c2.load(c.output()[12:]) self.assertEqual(c['test'].value, c2['test'].value) c3 = parse_cookie(c.output()[12:]) self.assertEqual(c['test'].value, c3['test']) def test_decode_2(self): """
class CookieTests(unittest.TestCase): c2 = SimpleCookie() c2.load(c.output()[12:]) self.assertEqual(c['test'].value, c2['test'].value) def test_nonstandard_keys(self): """
class CookieTests(unittest.TestCase): c2 = SimpleCookie() c2.load(c.output()[12:]) self.assertEqual(c['test'].value, c2['test'].value) c3 = parse_cookie(c.output()[12:]) self.assertEqual(c['test'].value, c3['test']) def test_nonstandard_keys(self): """
class CookieTests(unittest.TestCase): """ self.assertIn('good_cookie', parse_cookie('a:=b; a:=c; good_cookie=yes').keys()) def test_httponly_after_load(self): """ Test that we can use httponly attribute on cookies that we load
class CookieTests(unittest.TestCase): """ self.assertIn('good_cookie', parse_cookie('a:=b; a:=c; good_cookie=yes').keys()) def test_python_cookies(self): """ Test cases copied from Python's Lib/test/test_http_cookies.py """ self.assertEqual(parse_cookie('chips=ahoy; ...