buggy
stringlengths
35
5.03k
fixed
stringlengths
46
62.5k
import subprocess import sys import tempfile import warnings from binascii import hexlify from binascii import unhexlify from binascii import Error as BinasciiError
import subprocess import sys import tempfile import warnings from binascii import hexlify from binascii import unhexlify from binascii import Error as BinasciiError
class VaultEditor: os.remove(tmp_path) def _edit_file_helper(self, filename, secret, existing_data=None, force_save=False, vault_id=None): # Create a tempfile root, ext = os.path.splitext(os.path.realpath(filename)) fd, tmp_path = tempfile.mkstemp(suffix=...
class VaultEditor: os.remove(tmp_path) def _edit_file_helper(self, filename, secret, existing_data=None, force_save=False, vault_id=None): # Create a tempfile root, ext = os.path.splitext(os.path.realpath(filename)) fd, tmp_path = tempfile.mkstemp(suffix=ext, dir=C.DEFAULT_LOCAL_T...
class VaultEditor: # Figure out the vault id from the file, to select the right secret to re-encrypt it # (duplicates parts of decrypt, but alas...) dummy, dummy, cipher_name, vault_id = parse_vaulttext_envelope(b_vaulttext, ...
class VaultEditor: # Figure out the vault id from the file, to select the right secret to re-encrypt it # (duplicates parts of decrypt, but alas...) dummy, dummy, cipher_name, vault_id = parse_vaulttext_envelope(b_vaulttext, filename=filename) # vault id here may not be the vault id ac...
class VaultEditor: return data # TODO: add docstrings for arg types since this code is picky about that def write_data(self, data, filename, shred=True): """Write the data bytes to given path This is used to write a byte string to a file or stdout. It is used for
class VaultEditor: return data def write_data(self, data, thefile, shred=True, mode=0o600): # TODO: add docstrings for arg types since this code is picky about that """Write the data bytes to given path This is used to write a byte string to a file or stdout. It is used for
class VaultEditor: should be a byte string and not a text type. :arg data: the byte string (bytes) data :arg filename: filename to save 'data' to. :arg shred: if shred==True, make sure that the original data is first shredded so that is cannot be recovered. :returns: None ...
class VaultEditor: should be a byte string and not a text type. :arg data: the byte string (bytes) data :arg thefile: file descriptor or filename to save 'data' to. :arg shred: if shred==True, make sure that the original data is first shredded so that is cannot be recovered. :re...
class TestImage: with pytest.warns(DeprecationWarning): assert test_module.PILLOW_VERSION > "7.0.0" def test_overrun(self): """For overrun completeness, test as: valgrind pytest -qq Tests/test_image.py::TestImage::test_overrun | grep decode.c """ for file in [ ...
class TestImage: with pytest.warns(DeprecationWarning): assert test_module.PILLOW_VERSION > "7.0.0" @pytest.mark.parametrize("path", [ "fli_overrun.bin", "sgi_overrun.bin", "sgi_overrun_expandrow.bin", "sgi_overrun_expandrow2.bin", "pc...
class PcxImageFile(ImageFile.ImageFile): version = s[1] bits = s[3] planes = s[65] stride = i16(s, 66) logger.debug( "PCX version %s, bits %s, planes %s, stride %s", version, bits, planes, stride, ) self...
class PcxImageFile(ImageFile.ImageFile): version = s[1] bits = s[3] planes = s[65] ignored_stride = i16(s, 66) logger.debug( "PCX version %s, bits %s, planes %s, stride %s", version, bits, planes, ignored_stride, ...
class PcxImageFile(ImageFile.ImageFile): self.mode = mode self._size = bbox[2] - bbox[0], bbox[3] - bbox[1] bbox = (0, 0) + self.size logger.debug("size: %sx%s", *self.size)
class PcxImageFile(ImageFile.ImageFile): self.mode = mode self._size = bbox[2] - bbox[0], bbox[3] - bbox[1] # don't trust the passed in stride. Calculate for ourselves. # CVE-2020-35655 stride = (self._size[0] * bits + 7) // 8 stride += stride % 2 bbox = (0, 0) ...
def test_seek(): im.seek(50) assert_image_equal_tofile(im, "Tests/images/a_fli.png")
def test_seek(): im.seek(50) assert_image_equal_tofile(im, "Tests/images/a_fli.png") @pytest.mark.parametrize( "test_file", [ "Tests/images/timeout-9139147ce93e20eb14088fe238e541443ffd64b3.fli", "Tests/images/timeout-bff0a9dc7243a8e6ede2408d2ffa6a9964698b87.fli", ], ) @pyt...
def __xml_scan(node, env, path, arg): styledoc = libxml2.parseFile(xsl_file) style = libxslt.parseStylesheetDoc(styledoc) doc = libxml2.parseFile(str(node)) result = style.applyStylesheet(doc, None) depfiles = []
def __xml_scan(node, env, path, arg): styledoc = libxml2.parseFile(xsl_file) style = libxslt.parseStylesheetDoc(styledoc) doc = libxml2.readFile(str(node), None, libxml2.XML_PARSE_NOENT) result = style.applyStylesheet(doc, None) depfiles = []
def __xinclude_libxml2(target, source, env): Resolving XIncludes, using the libxml2 module. """ doc = libxml2.readFile(str(source[0]), None, libxml2.XML_PARSE_NOENT) doc.xincludeProcess() doc.saveFile(str(target[0])) doc.freeDoc()
def __xinclude_libxml2(target, source, env): Resolving XIncludes, using the libxml2 module. """ doc = libxml2.readFile(str(source[0]), None, libxml2.XML_PARSE_NOENT) doc.xincludeProcessFlags(libxml2.XML_PARSE_NOENT) doc.saveFile(str(target[0])) doc.freeDoc()
class URLValidator(RegexValidator): ul = '\u00a1-\uffff' # Unicode letters range (must not be a raw string). # IP patterns ipv4_re = r'(?:25[0-5]|2[0-4]\d|[0-1]?\d?\d)(?:\.(?:25[0-5]|2[0-4]\d|[0-1]?\d?\d)){3}' ipv6_re = r'\[[0-9a-f:.]+\]' # (simple regex, validated later) # Host patterns
class URLValidator(RegexValidator): ul = '\u00a1-\uffff' # Unicode letters range (must not be a raw string). # IP patterns ipv4_re = r'(?:0|25[0-5]|2[0-4]\d|1\d?\d?|[1-9]\d?)(?:\.(?:0|25[0-5]|2[0-4]\d|1\d?\d?|[1-9]\d?)){3}' ipv6_re = r'\[[0-9a-f:.]+\]' # (simple regex, validated later) # Host pa...
def validate_ipv4_address(value): ipaddress.IPv4Address(value) except ValueError: raise ValidationError(_('Enter a valid IPv4 address.'), code='invalid') def validate_ipv6_address(value):
def validate_ipv4_address(value): ipaddress.IPv4Address(value) except ValueError: raise ValidationError(_('Enter a valid IPv4 address.'), code='invalid') else: # Leading zeros are forbidden to avoid ambiguity with the octal # notation. This restriction is included in Python 3.9.5...
TEST_DATA = [ (validate_ipv4_address, '1.1.1.1\n', ValidationError), (validate_ipv4_address, '٧.2٥.3٣.243', ValidationError), # validate_ipv6_address uses django.utils.ipv6, which # is tested in much greater detail in its own testcase (validate_ipv6_address, 'fe80::1', None),
TEST_DATA = [ (validate_ipv4_address, '1.1.1.1\n', ValidationError), (validate_ipv4_address, '٧.2٥.3٣.243', ValidationError), # Leading zeros are forbidden to avoid ambiguity with the octal notation. (validate_ipv4_address, '000.000.000.000', ValidationError), (validate_ipv4_address, '016.016.016.0...
TEST_DATA = [ (validate_ipv46_address, '::zzz', ValidationError), (validate_ipv46_address, '12345::', ValidationError), (validate_comma_separated_integer_list, '1', None), (validate_comma_separated_integer_list, '12', None), (validate_comma_separated_integer_list, '1,2', None),
TEST_DATA = [ (validate_ipv46_address, '::zzz', ValidationError), (validate_ipv46_address, '12345::', ValidationError), # Leading zeros are forbidden to avoid ambiguity with the octal notation. (validate_ipv46_address, '000.000.000.000', ValidationError), (validate_ipv46_address, '016.016.016.016',...
def _parse_octet(cls, octet_str): if len(octet_str) > 3: msg = "At most 3 characters permitted in %r" raise ValueError(msg % octet_str) # Convert to integer (we know digits are legal) octet_int = int(octet_str, 10) if octet_int > 255:
def _parse_octet(cls, octet_str): if len(octet_str) > 3: msg = "At most 3 characters permitted in %r" raise ValueError(msg % octet_str) # Handle leading zeros as strict as glibc's inet_pton() # See security bug bpo-36384 if octet_str != '0' and octet_str[0] == '0'...
def pickle_test(self, addr): 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", "192.168.0.1") self.assertInstancesEqual("016.016.016.016", "16.16.16.16") self....
def pickle_test(self, addr): class CommonTestMixin_v4(CommonTestMixin): def test_leading_zeros(self): # bpo-36384: no leading zeros to avoid ambiguity with octal notation msg = "Leading zeros are not permitted in '\d+'" addresses = [ "000.000.000.000", "192.168.000.0...
def finalize_with_tag(self, tag): "finalize_with_tag requires OpenSSL >= 1.0.2. To use this " "method please update OpenSSL" ) res = self._backend._lib.EVP_CIPHER_CTX_ctrl( self._ctx, self._backend._lib.EVP_CTRL_AEAD_SET_TAG, len(tag), tag
def finalize_with_tag(self, tag): "finalize_with_tag requires OpenSSL >= 1.0.2. To use this " "method please update OpenSSL" ) if len(tag) < self._mode._min_tag_length: raise ValueError( "Authentication tag must be {0} bytes or longer.".for...
def __init__(self, initialization_vector, tag=None, min_tag_length=16): min_tag_length) ) self._tag = tag tag = utils.read_only_property("_tag") initialization_vector = utils.read_only_property("_initialization_vector")
def __init__(self, initialization_vector, tag=None, min_tag_length=16): min_tag_length) ) self._tag = tag self._min_tag_length = min_tag_length tag = utils.read_only_property("_tag") initialization_vector = utils.read_only_property("_initialization_vector...
def test_gcm_tag_decrypt_finalize(self, backend): decryptor.finalize() else: decryptor.finalize_with_tag(tag)
def test_gcm_tag_decrypt_finalize(self, backend): decryptor.finalize() else: decryptor.finalize_with_tag(tag) @pytest.mark.supported( only_if=lambda backend: ( not backend._lib.CRYPTOGRAPHY_OPENSSL_LESS_THAN_102 or backend._lib.CRYPTOGRAPHY_IS_LIBRESS...
class BeamDataflowJobTask(MixinNaiveBulkComplete, luigi.Task): def __init__(self): if not isinstance(self.dataflow_params, DataflowParamKeys): raise ValueError("dataflow_params must be of type DataflowParamKeys") @abstractmethod def dataflow_executable(self):
class BeamDataflowJobTask(MixinNaiveBulkComplete, luigi.Task): def __init__(self): if not isinstance(self.dataflow_params, DataflowParamKeys): raise ValueError("dataflow_params must be of type DataflowParamKeys") super(BeamDataflowJobTask, self).__init__() @abstractmethod def da...
class BeamDataflowJobTask(MixinNaiveBulkComplete, luigi.Task): @staticmethod def get_target_path(target): if isinstance(target, luigi.LocalTarget) or isinstance(target, gcs.GCSTarget): return target.path elif isinstance(target, bigquery.BigQueryTarget): "{}:{}.{}".format...
class BeamDataflowJobTask(MixinNaiveBulkComplete, luigi.Task): @staticmethod def get_target_path(target): """ Given a luigi Target, determine a stringly typed path to pass as a Dataflow job argument. """ if isinstance(target, luigi.LocalTarget) or isinstance(targ...
import json import luigi from luigi.contrib import beam_dataflow from luigi import local_target import mock from mock import MagicMock, patch
import json import luigi from luigi.contrib import beam_dataflow, bigquery, gcs from luigi import local_target import mock from mock import MagicMock, patch
class BeamDataflowTest(unittest.TestCase): self.assertEqual(TestTaskDictOfMixedCompleteOutput().complete(), False) def test_dataflow_runner_resolution(self): task = SimpleTestTask() # Test that supported runners are passed through
class BeamDataflowTest(unittest.TestCase): self.assertEqual(TestTaskDictOfMixedCompleteOutput().complete(), False) def test_get_target_path(self): bq_target = bigquery.BigQueryTarget("p", "d", "t", client="fake_client") self.assertEqual( SimpleTestTask.get_target_path(bq_target...
import warnings import numpy as np from pandas._libs import NaT, algos as libalgos, lib, tslib, writers from pandas._libs.index import convert_scalar import pandas._libs.internals as libinternals from pandas._libs.tslibs import Timedelta, conversion
import warnings import numpy as np from pandas._libs import NaT, Timestamp, algos as libalgos, lib, tslib, writers from pandas._libs.index import convert_scalar import pandas._libs.internals as libinternals from pandas._libs.tslibs import Timedelta, conversion
class DatetimeLikeBlockMixin: # Override to return DatetimeArray and TimedeltaArray return self.array_values() class DatetimeBlock(DatetimeLikeBlockMixin, Block): __slots__ = ()
class DatetimeLikeBlockMixin: # Override to return DatetimeArray and TimedeltaArray return self.array_values() def iget(self, key): # GH#31649 we need to wrap scalars in Timestamp/Timedelta # TODO: this can be removed if we ever have 2D EA result = super().iget(key) ...
class TestDataFrameIndexingUInt64: df = result.set_index("foo") tm.assert_index_equal(df.index, idx)
class TestDataFrameIndexingUInt64: df = result.set_index("foo") tm.assert_index_equal(df.index, idx) def test_object_casting_indexing_wraps_datetimelike(): # GH#31649, check the indexing methods all the way down the stack df = pd.DataFrame( { "A": [1, 2], "B": ...
def capfirst(x): # Set up regular expressions re_words = re.compile(r'<.*?>|((?:\w[-\w]*|&.*?;)+)', re.U | re.S) re_chars = re.compile(r'<.*?>|(.)', re.U | re.S) re_tag = re.compile(r'<(/)?([^ ]+?)(?:(\s*/)| .*?)?>', re.S) re_newlines = re.compile(r'\r\n|\r') # Used in normalize_newlines re_camel_case = re.compile(r'(...
def capfirst(x): # Set up regular expressions re_words = re.compile(r'<.*?>|((?:\w[-\w]*|&.*?;)+)', re.U | re.S) re_chars = re.compile(r'<.*?>|(.)', re.U | re.S) re_tag = re.compile(r'<(/)?(\S+?)(?:(\s*/)|\s.*?)?>', re.S) re_newlines = re.compile(r'\r\n|\r') # Used in normalize_newlines re_camel_case = re.compile(r'((...
class TestUtilsText(SimpleTestCase): truncator = text.Truncator('<p>I &lt;3 python, what about you?</p>') self.assertEqual('<p>I &lt;3 python...</p>', truncator.words(3, '...', html=True)) def test_wrap(self): digits = '1234 67 9' self.assertEqual(text.wrap(digits, 100), '1234 67 9'...
class TestUtilsText(SimpleTestCase): truncator = text.Truncator('<p>I &lt;3 python, what about you?</p>') self.assertEqual('<p>I &lt;3 python...</p>', truncator.words(3, '...', html=True)) re_tag_catastrophic_test = ('</a' + '\t' * 50000) + '//>' truncator = text.Truncator(re_tag_catast...
class ObjectBlock(Block): if convert: block = [b.convert(numeric=False, copy=True) for b in block] return block return self
class ObjectBlock(Block): if convert: block = [b.convert(numeric=False, copy=True) for b in block] return block if convert: return [self.convert(numeric=False, copy=True)] return self
class BlockManager(PandasObject): convert=convert, regex=regex, ) if m.any(): new_rb = _extend_blocks(result, new_rb) else: new_rb.append(b)
class BlockManager(PandasObject): convert=convert, regex=regex, ) if m.any() or convert: new_rb = _extend_blocks(result, new_rb) else: new_rb.append(b)
class TestDataFrameReplace: expected = pd.DataFrame(exp) result = df.replace(to_replace) tm.assert_frame_equal(result, expected)
class TestDataFrameReplace: expected = pd.DataFrame(exp) result = df.replace(to_replace) tm.assert_frame_equal(result, expected) @pytest.mark.parametrize( "replacer", [ pd.Timestamp("20170827"), np.int8(1), np.int16(1), np.flo...
def reformat_many( if sys.platform == "win32": # Work around https://bugs.python.org/issue26903 worker_count = min(worker_count, 61) executor = ProcessPoolExecutor(max_workers=worker_count) try: loop.run_until_complete( schedule_formatting(
def reformat_many( if sys.platform == "win32": # Work around https://bugs.python.org/issue26903 worker_count = min(worker_count, 61) try: executor = ProcessPoolExecutor(max_workers=worker_count) except OSError: # we arrive here if the underlying system does not support multi-...
def reformat_many( ) finally: shutdown(loop) executor.shutdown() async def schedule_formatting(
def reformat_many( ) finally: shutdown(loop) if executor is not None: executor.shutdown() async def schedule_formatting(
async def schedule_formatting( mode: Mode, report: "Report", loop: asyncio.AbstractEventLoop, executor: Executor, ) -> None: """Run formatting of `sources` in parallel using the provided `executor`.
async def schedule_formatting( mode: Mode, report: "Report", loop: asyncio.AbstractEventLoop, executor: Optional[Executor], ) -> None: """Run formatting of `sources` in parallel using the provided `executor`.
class BlackTestCase(unittest.TestCase): self.assertIn(one, cache) self.assertIn(two, cache) def test_no_cache_when_writeback_diff(self) -> None: mode = black.FileMode() with cache_dir() as workspace:
class BlackTestCase(unittest.TestCase): self.assertIn(one, cache) self.assertIn(two, cache) @patch("black.ProcessPoolExecutor", autospec=True) def test_works_in_mono_process_only_environment(self, mock_executor) -> None: mock_executor.side_effect = OSError() mode = black...
class Axis(martist.Artist): self._minor_tick_kw.update(kwtrans) for tick in self.minorTicks: tick._apply_params(**kwtrans) # special-case label color to also apply to the offset text if 'labelcolor' in kwtrans: self.offsetText.s...
class Axis(martist.Artist): self._minor_tick_kw.update(kwtrans) for tick in self.minorTicks: tick._apply_params(**kwtrans) # labelOn and labelcolor also apply to the offset text. if 'label1On' in kwtrans or 'label2On' in kwtrans: ...
def test_offset_label_color(): assert ax.yaxis.get_offset_text().get_color() == 'red' def test_large_offset(): fig, ax = plt.subplots() ax.plot((1 + np.array([0, 1.e-12])) * 1.e27)
def test_offset_label_color(): assert ax.yaxis.get_offset_text().get_color() == 'red' def test_offset_text_visible(): fig = plt.figure() ax = fig.add_subplot(1, 1, 1) ax.plot([1.01e9, 1.02e9, 1.03e9]) ax.yaxis.set_tick_params(label1On=False, label2On=True) assert ax.yaxis.get_offset_text().get...
def get_grammars(target_versions: Set[TargetVersion]) -> List[Grammar]: if not target_versions: return GRAMMARS elif all(not version.is_python2() for version in target_versions): # Python 2-compatible code, so don't try Python 3 grammar. return [ pygram.python_grammar_no_prin...
def get_grammars(target_versions: Set[TargetVersion]) -> List[Grammar]: if not target_versions: return GRAMMARS elif all(not version.is_python2() for version in target_versions): # Python 3-compatible code, so don't try Python 2 grammar return [ pygram.python_grammar_no_print...
class BlackTestCase(unittest.TestCase): # black.assert_equivalent(source, actual) black.assert_stable(source, actual, black.FileMode()) @patch("black.dump_to_file", dump_to_stderr) def test_python2_unicode_literals(self) -> None: source, expected = read_data("python2_unicode_literals")
class BlackTestCase(unittest.TestCase): # black.assert_equivalent(source, actual) black.assert_stable(source, actual, black.FileMode()) @patch("black.dump_to_file", dump_to_stderr) def test_python2_print_function(self) -> None: source, expected = read_data("python2_print_function") ...
class PeriodicCallback(object): self._timeout = self.io_loop.add_timeout(self._next_timeout, self._run) def _update_next(self, current_time): if self._next_timeout <= current_time: callback_time_sec = self.callback_time / 1000.0 self._next_timeout += (math.floor((current...
class PeriodicCallback(object): self._timeout = self.io_loop.add_timeout(self._next_timeout, self._run) def _update_next(self, current_time): callback_time_sec = self.callback_time / 1000.0 if self._next_timeout <= current_time: # The period should be measured from the start...
class TestPeriodicCallbackMath(unittest.TestCase): def simulate_calls(self, pc, durations): """Simulate a series of calls to the PeriodicCallback. Pass a list of call durations in seconds. This method returns the times at which each call would be made. """ calls = [] ...
class TestPeriodicCallbackMath(unittest.TestCase): def simulate_calls(self, pc, durations): """Simulate a series of calls to the PeriodicCallback. Pass a list of call durations in seconds (negative values work to simulate clock adjustments during the call, or more or less equivalent...
class TestPeriodicCallbackMath(unittest.TestCase): self.assertEqual(self.simulate_calls(pc, call_durations), expected) class TestIOLoopConfiguration(unittest.TestCase): def run_python(self, *statements):
class TestPeriodicCallbackMath(unittest.TestCase): self.assertEqual(self.simulate_calls(pc, call_durations), expected) def test_clock_backwards(self): pc = PeriodicCallback(None, 10000) # Backwards jumps are ignored, potentially resulting in a # slightly slo...
def standardize_weights(y, """Performs sample weight validation and standardization. Everything gets normalized to a single sample-wise (or timestep-wise) weight array. # Arguments y: Numpy array of model targets to be weighted.
def standardize_weights(y, """Performs sample weight validation and standardization. Everything gets normalized to a single sample-wise (or timestep-wise) weight array. If both `sample_weights` and `class_weights` are provided, the weights are multiplied together. # Arguments y: Numpy arra...
def standardize_weights(y, 'sample-wise weights, make sure your ' 'sample_weight array is 1D.') if sample_weight is not None and class_weight is not None: warnings.warn('Found both `sample_weight` and `class_weight`: ' '`class_...
def standardize_weights(y, 'sample-wise weights, make sure your ' 'sample_weight array is 1D.') if sample_weight is not None: if len(sample_weight.shape) > len(y.shape): raise ValueError('Found a sample_weight with shape' +
def standardize_weights(y, ' for an input with shape ' + str(y.shape) + '. ' 'sample_weight cannot be broadcast.') return sample_weight elif isinstance(class_weight, dict): if len(y.shape) > 2: raise V...
def standardize_weights(y, ' for an input with shape ' + str(y.shape) + '. ' 'sample_weight cannot be broadcast.') class_sample_weight = None if isinstance(class_weight, dict): if len(y.shape) > 2: raise ...
def standardize_weights(y, ' The classes %s exist in the data but not in ' '`class_weight`.' % (existing_classes - existing_class_weight)) return weights else: if sample_weight_mode is None: return np....
def standardize_weights(y, ' The classes %s exist in the data but not in ' '`class_weight`.' % (existing_classes - existing_class_weight)) if sample_weight is not None and class_sample_weight is not None: return sample_w...
def test_dynamic_set_inputs(): assert preds4.shape == (1, 19) if __name__ == '__main__': pytest.main([__file__])
def test_dynamic_set_inputs(): assert preds4.shape == (1, 19) def test_sample_weights(): y = np.array([0, 1, 0, 0, 2]) sample_weights = np.array([0.5, 1., 1., 0., 2.]) class_weights = {0: 0.5, 1: 1., 2: 1.5} # Only `sample_weights`. weights = training_utils.standardize_weights(y, sample_weigh...
setup( name="waitress", version="1.4.0", author="Zope Foundation and Contributors", author_email="zope-dev@zope.org", maintainer="Pylons Project",
setup( name="waitress", version="1.4.1", author="Zope Foundation and Contributors", author_email="zope-dev@zope.org", maintainer="Pylons Project",
ServerNotImplemented, find_double_newline, ) class ParsingError(Exception):
ServerNotImplemented, find_double_newline, ) from .rfc7230 import HEADER_FIELD class ParsingError(Exception):
class ParsingError(Exception): class TransferEncodingNotImplemented(Exception): pass class HTTPRequestParser(object): """A structure that collects the HTTP request.
class ParsingError(Exception): class TransferEncodingNotImplemented(Exception): pass class HTTPRequestParser(object): """A structure that collects the HTTP request.
def parse_header(self, header_plus): headers = self.headers for line in lines: index = line.find(b":") if index > 0: key = line[:index] if key != key.strip(): raise ParsingError("Invalid whitespace after field-name") ...
def parse_header(self, header_plus): headers = self.headers for line in lines: header = HEADER_FIELD.match(line) if not header: raise ParsingError("Invalid header") key, value = header.group('name', 'value') if b"_" in key: ...
def get_header_lines(header): r = [] lines = header.split(b"\r\n") for line in lines: if b"\r" in line or b"\n" in line: raise ParsingError('Bare CR or LF found in header line "%s"' % tostr(line))
def get_header_lines(header): r = [] lines = header.split(b"\r\n") for line in lines: if not line: continue if b"\r" in line or b"\n" in line: raise ParsingError('Bare CR or LF found in header line "%s"' % tostr(line))
def test_parse_header_invalid_whitespace(self): try: self.parser.parse_header(data) except ParsingError as e: self.assertIn("Invalid whitespace after field-name", e.args[0]) else: # pragma: nocover self.assertTrue(False) class Test_split_uri(unittest.TestCa...
def test_parse_header_invalid_whitespace(self): try: self.parser.parse_header(data) except ParsingError as e: self.assertIn("Invalid header", e.args[0]) else: # pragma: nocover self.assertTrue(False) def test_parse_header_invalid_whitespace_vtab(self): ...
import stat import time logger = logging.getLogger("waitress") queue_logger = logging.getLogger("waitress.queue")
import stat import time from .rfc7230 import OBS_TEXT, VCHAR logger = logging.getLogger("waitress") queue_logger = logging.getLogger("waitress.queue")
def group(s): long_day_reg = group(join(long_days, "|")) daymap = {} for i in range(7): daymap[short_days[i]] = i daymap[long_days[i]] = i
def group(s): long_day_reg = group(join(long_days, "|")) daymap = {} for i in range(7): daymap[short_days[i]] = i daymap[long_days[i]] = i
def group(s): ] monmap = {} for i in range(12): monmap[months[i]] = i + 1
def group(s): ] monmap = {} for i in range(12): monmap[months[i]] = i + 1
def group(s): def unpack_rfc822(m): g = m.group return ( int(g(4)), # year monmap[g(3)], # month
def group(s): def unpack_rfc822(m): g = m.group return ( int(g(4)), # year monmap[g(3)], # month
def unpack_rfc822(m): def unpack_rfc850(m): g = m.group yr = g(4) if len(yr) == 2: yr = "19" + yr return ( int(yr), # year monmap[g(3)], # month
def unpack_rfc822(m): def unpack_rfc850(m): g = m.group yr = g(4) if len(yr) == 2: yr = "19" + yr return ( int(yr), # year monmap[g(3)], # month
def unpack_rfc850(m): def build_http_date(when): year, month, day, hh, mm, ss, wd, y, z = time.gmtime(when) return "%s, %02d %3s %4d %02d:%02d:%02d GMT" % ( weekdayname[wd], day,
def unpack_rfc850(m): def build_http_date(when): year, month, day, hh, mm, ss, wd, y, z = time.gmtime(when) return "%s, %02d %3s %4d %02d:%02d:%02d GMT" % ( weekdayname[wd], day,
def build_http_date(when): def parse_http_date(d): d = d.lower() m = rfc850_reg.match(d) if m and m.end() == len(d): retval = int(calendar.timegm(unpack_rfc850(m))) else: m = rfc822_reg.match(d) if m and m.end() == len(d): retval = int(calendar.timegm(unpack_rfc822(m)...
def build_http_date(when): def parse_http_date(d): d = d.lower() m = rfc850_reg.match(d) if m and m.end() == len(d): retval = int(calendar.timegm(unpack_rfc850(m))) else: m = rfc822_reg.match(d) if m and m.end() == len(d): retval = int(calendar.timegm(unpack_rfc822(...
Tests for L{twisted.web.twcgi}. """ import sys, os from twisted.trial import unittest from twisted.internet import reactor, interfaces, error from twisted.python import util, failure, log from twisted.web.http import NOT_FOUND, INTERNAL_SERVER_ERROR from twisted.web import client, twcgi, server, resource from twisted...
Tests for L{twisted.web.twcgi}. """ import sys import os import json from twisted.trial import unittest from twisted.internet import reactor, interfaces, error from twisted.python import util, failure, log from twisted.web.http import NOT_FOUND, INTERNAL_SERVER_ERROR from twisted.web import client, twcgi, server, res...
print print "cgi output" ''' class PythonScript(twcgi.FilteredScript): filter = sys.executable
print print "cgi output" ''' HEADER_OUTPUT_CGI = '''\ import json import os print("") print("") vals = {x:y for x,y in os.environ.items() if x.startswith("HTTP_")} print(json.dumps(vals)) ''' class PythonScript(twcgi.FilteredScript): filter = sys.executable
class CGITests(unittest.TestCase): return factory.deferred def test_duplicateHeaderCGI(self): """ If a CGI script emits two instances of the same header, both are sent in
class CGITests(unittest.TestCase): return factory.deferred def test_noProxyPassthrough(self): """ The CGI script is never called with the Proxy header passed through. """ cgiFilename = self.writeCGI(HEADER_OUTPUT_CGI) portnum = self.startServer(cgiFilename) ...
class CGIScript(resource.Resource): # Propagate HTTP headers for title, header in request.getAllHeaders().items(): envname = title.replace('-', '_').upper() if title not in ('content-type', 'content-length'): envname = "HTTP_" + envname env[envname] = ...
class CGIScript(resource.Resource): # Propagate HTTP headers for title, header in request.getAllHeaders().items(): envname = title.replace('-', '_').upper() if title not in ('content-type', 'content-length', 'proxy'): envname = "HTTP_" + envname env[en...
def verify_collections(collections, search_paths, apis, validate_certs, ignore_e for search_path in search_paths: b_search_path = to_bytes(os.path.join(search_path, namespace, name), errors='surrogate_or_strict') if os.path.isdir(b_search_path): ...
def verify_collections(collections, search_paths, apis, validate_certs, ignore_e for search_path in search_paths: b_search_path = to_bytes(os.path.join(search_path, namespace, name), errors='surrogate_or_strict') if os.path.isdir(b_search_path): ...
def test_verify_identical(monkeypatch, mock_collection, manifest_info, files_man assert mock_debug.call_args_list[-1][0][0] == success_msg @patch.object(collection.CollectionRequirement, 'verify') def test_verify_collections_not_installed(mock_verify, mock_collection, monkeypatch): namespace = 'ansibl...
def test_verify_identical(monkeypatch, mock_collection, manifest_info, files_man assert mock_debug.call_args_list[-1][0][0] == success_msg @patch.object(os.path, 'isdir', return_value=True) def test_verify_collections_no_version(mock_isdir, mock_collection, monkeypatch): namespace = 'ansible_namespace...
def test_verify_collections_not_installed_ignore_errors(mock_verify, mock_collec @patch.object(os.path, 'isdir', return_value=True) @patch.object(collection.CollectionRequirement, 'verify') def test_verify_collections_no_remote(mock_verify, mock_isdir, mock_collection): namespace = 'ansible_namespace' name = '...
def test_verify_collections_not_installed_ignore_errors(mock_verify, mock_collec @patch.object(os.path, 'isdir', return_value=True) @patch.object(collection.CollectionRequirement, 'verify') def test_verify_collections_no_remote(mock_verify, mock_isdir, mock_collection, monkeypatch): namespace = 'ansible_namespace'...
def test_verify_collections_no_remote(mock_verify, mock_isdir, mock_collection): @patch.object(os.path, 'isdir', return_value=True) @patch.object(collection.CollectionRequirement, 'verify') def test_verify_collections_no_remote_ignore_errors(mock_verify, mock_isdir, mock_collection): namespace = 'ansible_namespace...
def test_verify_collections_no_remote(mock_verify, mock_isdir, mock_collection): @patch.object(os.path, 'isdir', return_value=True) @patch.object(collection.CollectionRequirement, 'verify') def test_verify_collections_no_remote_ignore_errors(mock_verify, mock_isdir, mock_collection, monkeypatch): namespace = 'ansi...
def test_verify_collections_url(monkeypatch): assert err.value.message == msg @patch.object(os.path, 'isfile', return_value=False) @patch.object(os.path, 'isdir', return_value=True) @patch.object(collection.CollectionRequirement, 'verify') def test_verify_collections_name(mock_verify, mock_isdir, mock_isfile, moc...
def test_verify_collections_url(monkeypatch): assert err.value.message == msg @patch.object(os.path, 'isdir', return_value=True) @patch.object(collection.CollectionRequirement, 'verify') def test_verify_collections_name(mock_verify, mock_isdir, mock_collection, monkeypatch): local_collection = mock_collection...
class DatabaseFeatures(BaseDatabaseFeatures): supports_over_clause = True supports_aggregate_filter_clause = True supported_explain_formats = {'JSON', 'TEXT', 'XML', 'YAML'} validates_explain_options = False # A query will error on invalid options. @cached_property def is_postgresql_9_5(self):
class DatabaseFeatures(BaseDatabaseFeatures): supports_over_clause = True supports_aggregate_filter_clause = True supported_explain_formats = {'JSON', 'TEXT', 'XML', 'YAML'} @cached_property def is_postgresql_9_5(self):
from django.db.backends.base.operations import BaseDatabaseOperations class DatabaseOperations(BaseDatabaseOperations): cast_char_field_without_max_length = 'varchar' explain_prefix = 'EXPLAIN' cast_data_types = { 'AutoField': 'integer', 'BigAutoField': 'bigint',
from django.db.backends.base.operations import BaseDatabaseOperations class DatabaseOperations(BaseDatabaseOperations): cast_char_field_without_max_length = 'varchar' explain_prefix = 'EXPLAIN' explain_options = frozenset( [ "ANALYZE", "BUFFERS", "COSTS", ...
class DatabaseOperations(BaseDatabaseOperations): return start_, end_ def explain_query_prefix(self, format=None, **options): prefix = super().explain_query_prefix(format) extra = {} if format: extra['FORMAT'] = format if options: extra.update({ ...
class DatabaseOperations(BaseDatabaseOperations): return start_, end_ def explain_query_prefix(self, format=None, **options): extra = {} # Normalize options. if options: options = { name.upper(): 'true' if value else 'false' for name, valu...
__all__ = ['Query', 'RawQuery'] # SQL comments are forbidden in column aliases. FORBIDDEN_ALIAS_PATTERN = re.compile(r"['`\"\]\[;\s]|--|/\*|\*/") def get_field_names_from_opts(opts): return set(chain.from_iterable(
__all__ = ['Query', 'RawQuery'] # SQL comments are forbidden in column aliases. FORBIDDEN_ALIAS_PATTERN = re.compile(r"['`\"\]\[;\s]|--|/\*|\*/") # Inspired from # https://www.postgresql.org/docs/current/sql-syntax-lexical.html#SQL-SYNTAX-IDENTIFIERS EXPLAIN_OPTIONS_PATTERN = re.compile(r"[\w\-]+") def get_field_nam...
class Query: def explain(self, using, format=None, **options): q = self.clone() q.explain_query = True q.explain_format = format q.explain_options = options
class Query: def explain(self, using, format=None, **options): q = self.clone() for option_name in options: if ( not EXPLAIN_OPTIONS_PATTERN.fullmatch(option_name) or "--" in option_name ): raise ValueError("Invalid option name...
class ExplainTests(TestCase): @skipUnlessDBFeature('validates_explain_options') def test_unknown_options(self): with self.assertRaisesMessage(ValueError, 'Unknown options: test, test2'): Tag.objects.all().explain(test=1, test2=1) def test_unknown_format(self): msg = 'DOES NOT E...
class ExplainTests(TestCase): @skipUnlessDBFeature('validates_explain_options') def test_unknown_options(self): with self.assertRaisesMessage(ValueError, "Unknown options: TEST, TEST2"): Tag.objects.all().explain(**{"TEST": 1, "TEST2": 1}) def test_unknown_format(self): msg = '...
class ExplainTests(TestCase): option = '{} {}'.format(name.upper(), 'true' if value else 'false') self.assertIn(option, captured_queries[0]['sql']) @unittest.skipUnless(connection.vendor == 'mysql', 'MySQL specific') def test_mysql_text_to_traditional(self): # In...
class ExplainTests(TestCase): option = '{} {}'.format(name.upper(), 'true' if value else 'false') self.assertIn(option, captured_queries[0]['sql']) def test_option_sql_injection(self): qs = Tag.objects.filter(name="test") options = {"SUMMARY true) SELECT 1; -...
def categorical_accuracy(y_true, y_pred): def sparse_categorical_accuracy(y_true, y_pred): # flatten y_true in case it's in shape (num_samples, 1) instead of (num_samples,) return K.cast(K.equal(K.flatten(y_true), K.cast(K.argmax(y_pred, axis=-1), K.floatx())), K.fl...
def categorical_accuracy(y_true, y_pred): def sparse_categorical_accuracy(y_true, y_pred): # reshape in case it's in shape (num_samples, 1) instead of (num_samples,) if K.ndim(y_true) == K.ndim(y_pred): y_true = K.squeeze(y_true, -1) # convert dense predictions to labels y_pred_labels = K.argm...
def test_sparse_metrics(): assert K.eval(metric(y_a, y_b)).shape == (6,) def test_sparse_categorical_accuracy_correctness(): y_a = K.variable(np.random.randint(0, 7, (6,)), dtype=K.floatx()) y_b = K.variable(np.random.random((6, 7)), dtype=K.floatx()) # use one_hot embedding to convert sparse labe...
def test_sparse_metrics(): assert K.eval(metric(y_a, y_b)).shape == (6,) @pytest.mark.parametrize('shape', [(6,), (6, 3), (6, 3, 1)]) def test_sparse_categorical_accuracy_correctness(shape): y_a = K.variable(np.random.randint(0, 7, shape), dtype=K.floatx()) y_b_shape = shape + (7,) y_b = K.variabl...
def __virtual__(): return __virtualname__ def _check_cb(cb_): """ If the callback is None or is not callable, return a lambda that returns
def __virtual__(): return __virtualname__ def _log_cmd(cmd): if not isinstance(cmd, list): return cmd.split()[0].strip() return cmd[0].strip() def _check_cb(cb_): """ If the callback is None or is not callable, return a lambda that returns
def _run( ) env[bad_env_key] = "" def _get_stripped(cmd): # Return stripped command string copies to improve logging. if isinstance(cmd, list): return [x.strip() if isinstance(x, str) else x for x in cmd] elif isinstance(cmd, str): return cmd.strip() ...
def _run( ) env[bad_env_key] = "" if output_loglevel is not None: # Always log the shell commands at INFO unless quiet logging is # requested. The command output is what will be controlled by the # 'loglevel' parameter. msg = "Executing command {}{}{} {}{}in director...
def _run( log.error( "Failed to decode stdout from command %s, non-decodable " "characters have been replaced", cmd, ) try:
def _run( log.error( "Failed to decode stdout from command %s, non-decodable " "characters have been replaced", _log_cmd(cmd), ) try:
def _run( log.error( "Failed to decode stderr from command %s, non-decodable " "characters have been replaced", cmd, ) if rstrip:
def _run( log.error( "Failed to decode stderr from command %s, non-decodable " "characters have been replaced", _log_cmd(cmd), ) if rstrip:
def _run( if not ignore_retcode and ret["retcode"] != 0: if output_loglevel < LOG_LEVELS["error"]: output_loglevel = LOG_LEVELS["error"] msg = "Command '{}' failed with return code: {}".format(cmd, ret["retcode"]) log.error(log_callback(msg)) if ret["s...
def _run( if not ignore_retcode and ret["retcode"] != 0: if output_loglevel < LOG_LEVELS["error"]: output_loglevel = LOG_LEVELS["error"] msg = "Command '{}' failed with return code: {}".format(_log_cmd(cmd), ret["retcode"]) log.error(log_callback(msg)) ...
def run( if not ignore_retcode and ret["retcode"] != 0: if lvl < LOG_LEVELS["error"]: lvl = LOG_LEVELS["error"] msg = "Command '{}' failed with return code: {}".format(cmd, ret["retcode"]) log.error(log_callback(msg)) if raise_err: ...
def run( if not ignore_retcode and ret["retcode"] != 0: if lvl < LOG_LEVELS["error"]: lvl = LOG_LEVELS["error"] msg = "Command '{}' failed with return code: {}".format(_log_cmd(cmd), ret["retcode"]) log.error(log_callback(msg)) if raise_err: ...
class CMDMODTestCase(TestCase, LoaderModuleMockMixin): umask=None, use_vt=False, )
class CMDMODTestCase(TestCase, LoaderModuleMockMixin): umask=None, use_vt=False, ) def test_cve_2021_25284(self): proc = MagicMock( return_value=MockTimedProc( stdout=b"foo", stderr=b"wtf", returncode=2 ...
class NDFrame(PandasObject, SelectionMixin, indexing.IndexingMixin): res._is_copy = self._is_copy return res def _iget_item_cache(self, item): """Return the cached item, item represents a positional indexer.""" ax = self._info_axis if ax.is_unique: lower = se...
class NDFrame(PandasObject, SelectionMixin, indexing.IndexingMixin): res._is_copy = self._is_copy return res def _iget_item_cache(self, item: int): """Return the cached item, item represents a positional indexer.""" ax = self._info_axis if ax.is_unique: lower...
class _iLocIndexer(_LocationIndexer): if not is_integer(k): return False ax = self.obj.axes[i] if not ax.is_unique: return False return True def _validate_integer(self, key: int, axis: int) -> None:
class _iLocIndexer(_LocationIndexer): if not is_integer(k): return False return True def _validate_integer(self, key: int, axis: int) -> None:
class TestiLoc(Base): class TestiLoc2: # TODO: better name, just separating out things that dont rely on base class def test_iloc_exceeds_bounds(self): # GH6296
class TestiLoc(Base): class TestiLoc2: # TODO: better name, just separating out things that dont rely on base class def test_is_scalar_access(self): # GH#32085 index with duplicates doesnt matter for _is_scalar_access index = pd.Index([1, 2, 1]) ser = pd.Series(range(3), index=index) ...
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 str(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 TestHTTPS_TLSv1(HTTPSDummyServerTestCase): self._pool = HTTPSConnectionPool(self.host, self.port) def test_set_ssl_version_to_sslv3(self): self._pool.ssl_version = ssl.PROTOCOL_SSLv3 self.assertRaises(SSLError, self._pool.request, 'GET', '/') def test_ssl_version_as_string(self):...
class TestHTTPS_TLSv1(HTTPSDummyServerTestCase): self._pool = HTTPSConnectionPool(self.host, self.port) def test_set_ssl_version_to_sslv3(self): self.assertEqual( ssl.PROTOCOL_SSLv3, util.ssl_.resolve_ssl_version(ssl.PROTOCOL_SSLv3) ) def test_ssl_version_as_str...
try: except AttributeError: pass _openssl_verify = { ssl.CERT_NONE: OpenSSL.SSL.VERIFY_NONE, ssl.CERT_OPTIONAL: OpenSSL.SSL.VERIFY_PEER, ssl.CERT_REQUIRED: OpenSSL.SSL.VERIFY_PEER + OpenSSL.SSL.VERIFY_FAIL_IF_NO_PEER_CERT, } #: The list of supported SSL/TLS cipher suites. DEFAULT_SSL_CIPHER_LI...
try: except AttributeError: pass _stdlib_to_openssl_verify = { ssl.CERT_NONE: OpenSSL.SSL.VERIFY_NONE, ssl.CERT_OPTIONAL: OpenSSL.SSL.VERIFY_PEER, ssl.CERT_REQUIRED: OpenSSL.SSL.VERIFY_PEER + OpenSSL.SSL.VERIFY_FAIL_IF_NO_PEER_CERT, } _openssl_to_stdlib_verify = dict( (v, k) for k, v in _st...
class PyOpenSSLContext(object): @property def verify_mode(self): return self._ctx.get_verify_mode() @verify_mode.setter def verify_mode(self, value): self._ctx.set_verify(value, _verify_callback) def set_default_verify_paths(self): self._ctx.set_default_verify_paths()
class PyOpenSSLContext(object): @property def verify_mode(self): return _openssl_to_stdlib_verify[self._ctx.get_verify_mode()] @verify_mode.setter def verify_mode(self, value): self._ctx.set_verify( _stdlib_to_openssl_verify[value], _verify_callback ) ...
def ssl_wrap_socket(sock, keyfile=None, certfile=None, cert_reqs=None, if keyfile: ctx.use_privatekey_file(keyfile) if cert_reqs != ssl.CERT_NONE: ctx.set_verify(_openssl_verify[cert_reqs], _verify_callback) if ca_certs or ca_cert_dir: try: ctx.load_verify_locations(ca_ce...
def ssl_wrap_socket(sock, keyfile=None, certfile=None, cert_reqs=None, if keyfile: ctx.use_privatekey_file(keyfile) if cert_reqs != ssl.CERT_NONE: ctx.set_verify(_stdlib_to_openssl_verify[cert_reqs], _verify_callback) if ca_certs or ca_cert_dir: try: ctx.load_verify_locat...
class TestFormatSelection(unittest.TestCase): self.assertEqual(downloaded['format_id'], '137+141') self.assertEqual(downloaded['ext'], 'mp4') info_dict = _make_result(list(formats_order), extractor='youtube') ydl = YDL({'format': '(bestvideo[ext=mp4],bestvideo[ext=webm])+bestaudio'}) ...
class TestFormatSelection(unittest.TestCase): self.assertEqual(downloaded['format_id'], '137+141') self.assertEqual(downloaded['ext'], 'mp4') info_dict = _make_result(list(formats_order), extractor='youtube') ydl = YDL({'format': 'bestvideo[height>=999999]+bestaudio/best'}) yie ...