buggy stringlengths 35 5.03k | fixed stringlengths 46 62.5k |
|---|---|
def is_safe_url(url, host=None):
return _is_safe_url(url, host) and _is_safe_url(url.replace('\\', '/'), host)
def _is_safe_url(url, host):
# Chrome considers any URL with more than two slashes to be absolute, but
# urlparse is not so flexible. Treat any url with three slashes as unsafe.
if url.starts... | def is_safe_url(url, host=None):
return _is_safe_url(url, host) and _is_safe_url(url.replace('\\', '/'), host)
# Copied from urllib.parse.urlparse() but uses fixed urlsplit() function.
def _urlparse(url, scheme='', allow_fragments=True):
"""Parse a URL into 6 components:
<scheme>://<netloc>/<path>;<params... |
class TestUtilsHttp(unittest.TestCase):
r'http://testserver\me:pass@example.com',
r'http://testserver\@example.com',
r'http:\\testserver\confirm\me@example.com',
'\n'):
self.assertFalse(http.is_safe_url(bad_url, ... | class TestUtilsHttp(unittest.TestCase):
r'http://testserver\me:pass@example.com',
r'http://testserver\@example.com',
r'http:\\testserver\confirm\me@example.com',
'http:999999999',
'ftp:9999999999',
... |
class TestUtilsHttp(unittest.TestCase):
'HTTPS://testserver/',
'//testserver/',
'http://testserver/confirm?email=me@example.com',
'/url%20with%20spaces/'):
self.assertTrue(http.is_safe_url(good_url, host='testserver'), "%s s... | class TestUtilsHttp(unittest.TestCase):
'HTTPS://testserver/',
'//testserver/',
'http://testserver/confirm?email=me@example.com',
'/url%20with%20spaces/',
'path/http:2222222222'):
self.assertTrue(http.is... |
class TestDecompressionBomb:
with Image.open(TEST_FILE):
pass
def test_exception_ico(self):
with pytest.raises(Image.DecompressionBombError):
with Image.open("Tests/images/decompression_bomb.ico"): | class TestDecompressionBomb:
with Image.open(TEST_FILE):
pass
@pytest.mark.xfail(reason="different exception")
def test_exception_ico(self):
with pytest.raises(Image.DecompressionBombError):
with Image.open("Tests/images/decompression_bomb.ico"): |
def test_apng_syntax_errors():
exception = e
assert exception is None
with pytest.raises(SyntaxError):
with Image.open("Tests/images/apng/syntax_num_frames_high.png") as im:
im.seek(im.n_frames - 1)
im.load() | def test_apng_syntax_errors():
exception = e
assert exception is None
with pytest.raises(OSError):
with Image.open("Tests/images/apng/syntax_num_frames_high.png") as im:
im.seek(im.n_frames - 1)
im.load() |
from PIL import Image
from .helper import assert_image_equal_tofile
| from PIL import Image
import pytest
from .helper import assert_image_equal_tofile
|
def test_combined_larger_than_size():
with pytest.raises(OSError):
with Image.open("Tests/images/combined_larger_than_size.psd"):
pass | def test_combined_larger_than_size():
with pytest.raises(OSError):
with Image.open("Tests/images/combined_larger_than_size.psd"):
pass
@pytest.mark.parametrize(
"test_file,raises",
[
("Tests/images/timeout-1ee28a249896e05b83840ae8140622de8e648ba9.psd", Image.UnidentifiedImageErr... |
class TestFileTiff:
)
def test_string_dimension(self):
# Assert that an error is raised if one of the dimensions is a string
with pytest.raises(ValueError):
with Image.open("Tests/images/string_dimension.tiff"):
pass
@pytest.mark.skipif(not is_win32(), reason="Windo... | class TestFileTiff:
)
def test_string_dimension(self):
# Assert that an error is raised if one of the dimensions is a string
with pytest.raises(OSError):
with Image.open("Tests/images/string_dimension.tiff") as im:
im.load()
@pytest.mark.skipif(not is_win32(), reas... |
def _safe_read(fp, size):
:param fp: File handle. Must implement a <b>read</b> method.
:param size: Number of bytes to read.
:returns: A string containing up to <i>size</i> bytes of data.
"""
if size <= 0:
return b""
if size <= SAFEBLOCK:
return fp.read(size)
data = []
... | def _safe_read(fp, size):
:param fp: File handle. Must implement a <b>read</b> method.
:param size: Number of bytes to read.
:returns: A string containing <i>size</i> bytes of data.
Raises an OSError if the file is truncated and the read can not be completed
"""
if size <= 0:
return ... |
def _safe_read(fp, size):
break
data.append(block)
size -= len(block)
return b"".join(data)
class PyCodecState:
def __init__(self):
self.xsize = 0 | def _safe_read(fp, size):
break
data.append(block)
size -= len(block)
if sum(len(d) for d in data) < size:
raise OSError("Truncated File Read")
return b"".join(data)
class PyCodecState:
def __init__(self):
self.xsize = 0 |
class PsdImageFile(ImageFile.ImageFile):
end = self.fp.tell() + size
size = i32(read(4))
if size:
self.layers = _layerinfo(self.fp)
self.fp.seek(end)
self.n_frames = len(self.layers)
self.is_animated = self.n_frames > 1 | class PsdImageFile(ImageFile.ImageFile):
end = self.fp.tell() + size
size = i32(read(4))
if size:
_layer_data = io.BytesIO(ImageFile._safe_read(self.fp, size))
self.layers = _layerinfo(_layer_data, size)
self.fp.seek(end)
self.n_fra... |
class PsdImageFile(ImageFile.ImageFile):
finally:
self.__fp = None
def _layerinfo(file):
# read layerinfo block
layers = []
read = file.read
for i in range(abs(i16(read(2)))):
# bounding box
y0 = i32(read(4)) | class PsdImageFile(ImageFile.ImageFile):
finally:
self.__fp = None
def _layerinfo(fp, ct_bytes):
# read layerinfo block
layers = []
def read(size):
return ImageFile._safe_read(fp, size)
ct = i16(read(2))
# sanity check
if ct_bytes < (abs(ct) * 20):
raise S... |
def _layerinfo(file):
# image info
info = []
mode = []
types = list(range(i16(read(2))))
if len(types) > 4:
continue
| def _layerinfo(file):
# image info
info = []
mode = []
ct_types = i16(read(2))
types = list(range(ct_types))
if len(types) > 4:
continue
|
def _layerinfo(file):
size = i32(read(4)) # length of the extra data field
combined = 0
if size:
data_end = file.tell() + size
length = i32(read(4))
if length:
file.seek(length - 16, io.SEEK_CUR)
combined += length + 4
... | def _layerinfo(file):
size = i32(read(4)) # length of the extra data field
combined = 0
if size:
data_end = fp.tell() + size
length = i32(read(4))
if length:
fp.seek(length - 16, io.SEEK_CUR)
combined += length + 4
le... |
def _layerinfo(file):
name = read(length).decode("latin-1", "replace")
combined += length + 1
file.seek(data_end)
layers.append((name, mode, (x0, y0, x1, y1)))
# get tiles | def _layerinfo(file):
name = read(length).decode("latin-1", "replace")
combined += length + 1
fp.seek(data_end)
layers.append((name, mode, (x0, y0, x1, y1)))
# get tiles |
def _layerinfo(file):
for name, mode, bbox in layers:
tile = []
for m in mode:
t = _maketile(file, m, bbox, 1)
if t:
tile.extend(t)
layers[i] = name, mode, bbox, tile | def _layerinfo(file):
for name, mode, bbox in layers:
tile = []
for m in mode:
t = _maketile(fp, m, bbox, 1)
if t:
tile.extend(t)
layers[i] = name, mode, bbox, tile |
from django.conf import settings
from django.contrib import messages
from django.contrib.auth import REDIRECT_FIELD_NAME
from django.utils.translation import ugettext as _
from keystoneclient import exceptions as keystone_exceptions
| from django.conf import settings
from django.contrib import messages
from django.contrib.auth import REDIRECT_FIELD_NAME
from django.utils.http import same_origin
from django.utils.translation import ugettext as _
from keystoneclient import exceptions as keystone_exceptions
|
def handle(self, request, data):
request.session['region_endpoint'] = endpoint
request.session['region_name'] = region_name
redirect_to = request.REQUEST.get(REDIRECT_FIELD_NAME, "")
if data.get('tenant', None):
try: | def handle(self, request, data):
request.session['region_endpoint'] = endpoint
request.session['region_name'] = region_name
redirect_to = request.REQUEST.get(REDIRECT_FIELD_NAME, None)
# Make sure the requested redirect matches the protocol,
# domain, and port of this request
... |
class SchemaBase(BaseModel):
not_: Optional[List[Any]] = PSchema(None, alias="not") # type: ignore
items: Optional[Any] = None
properties: Optional[Dict[str, Any]] = None
additionalProperties: Optional[Union[bool, Any]] = None
description: Optional[str] = None
format: Optional[str] = None
d... | class SchemaBase(BaseModel):
not_: Optional[List[Any]] = PSchema(None, alias="not") # type: ignore
items: Optional[Any] = None
properties: Optional[Dict[str, Any]] = None
additionalProperties: Optional[Union[Dict[str, Any], bool]] = None
description: Optional[str] = None
format: Optional[str] =... |
class Schema(SchemaBase):
not_: Optional[List[SchemaBase]] = PSchema(None, alias="not") # type: ignore
items: Optional[SchemaBase] = None
properties: Optional[Dict[str, SchemaBase]] = None
additionalProperties: Optional[Union[bool, SchemaBase]] = None
class Example(BaseModel): | class Schema(SchemaBase):
not_: Optional[List[SchemaBase]] = PSchema(None, alias="not") # type: ignore
items: Optional[SchemaBase] = None
properties: Optional[Dict[str, SchemaBase]] = None
additionalProperties: Optional[Union[SchemaBase, bool]] = None
class Example(BaseModel): |
class Operation(BaseModel):
operationId: Optional[str] = None
parameters: Optional[List[Union[Parameter, Reference]]] = None
requestBody: Optional[Union[RequestBody, Reference]] = None
responses: Union[Responses, Dict[Union[str], Response]]
# Workaround OpenAPI recursive reference
callbacks: Opt... | class Operation(BaseModel):
operationId: Optional[str] = None
parameters: Optional[List[Union[Parameter, Reference]]] = None
requestBody: Optional[Union[RequestBody, Reference]] = None
responses: Union[Responses, Dict[str, Response]]
# Workaround OpenAPI recursive reference
callbacks: Optional[D... |
class PythonItemExporter(BaseItemExporter):
return dict(self._serialize_dict(value))
if is_listlike(value):
return [self._serialize_value(v) for v in value]
if self.binary:
return to_bytes(value, encoding=self.encoding)
else:
return to_unicode(valu... | class PythonItemExporter(BaseItemExporter):
return dict(self._serialize_dict(value))
if is_listlike(value):
return [self._serialize_value(v) for v in value]
encode_func = to_bytes if self.binary else to_unicode
if isinstance(value, (six.text_type, bytes)):
ret... |
class PythonItemExporterTest(BaseItemExporterTest):
expected = {b'name': b'John\xc2\xa3', b'age': b'22'}
self.assertEqual(expected, exporter.export_item(value))
class PprintItemExporterTest(BaseItemExporterTest):
| class PythonItemExporterTest(BaseItemExporterTest):
expected = {b'name': b'John\xc2\xa3', b'age': b'22'}
self.assertEqual(expected, exporter.export_item(value))
def test_other_python_types_item(self):
from datetime import datetime
now = datetime.now()
item = {
'b... |
class EmptyLineTracker:
# Don't insert empty lines between decorators.
return 0, 0
newlines = 2
if current_line.depth:
newlines -= 1 | class EmptyLineTracker:
# Don't insert empty lines between decorators.
return 0, 0
if is_decorator and self.previous_line and self.previous_line.is_comment:
# Don't insert empty lines between decorator comments.
return 0, 0
newlin... |
class BlackTestCase(unittest.TestCase):
)
self.assertEqual(result.exit_code, 1)
if __name__ == "__main__":
unittest.main() | class BlackTestCase(unittest.TestCase):
)
self.assertEqual(result.exit_code, 1)
@patch("black.dump_to_file", dump_to_stderr)
def test_comment_in_decorator(self) -> None:
source, expected = read_data("comments6")
actual = fs(source)
self.assertFormatEqual(expected... |
class URLValidator(RegexValidator):
r'\Z', re.IGNORECASE)
message = _('Enter a valid URL.')
schemes = ['http', 'https', 'ftp', 'ftps']
def __init__(self, schemes=None, **kwargs):
super().__init__(**kwargs) | class URLValidator(RegexValidator):
r'\Z', re.IGNORECASE)
message = _('Enter a valid URL.')
schemes = ['http', 'https', 'ftp', 'ftps']
unsafe_chars = frozenset('\t\r\n')
def __init__(self, schemes=None, **kwargs):
super().__init__(**kwargs) |
class URLValidator(RegexValidator):
self.schemes = schemes
def __call__(self, value):
# Check first if the scheme is valid
scheme = value.split('://')[0].lower()
if scheme not in self.schemes:
raise ValidationError(self.message, code=self.code) | class URLValidator(RegexValidator):
self.schemes = schemes
def __call__(self, value):
if isinstance(value, str) and self.unsafe_chars.intersection(value):
raise ValidationError(self.message, code=self.code)
# Check if the scheme is valid.
scheme = value.split('://')[... |
TEST_DATA = [
(URLValidator(EXTENDED_SCHEMES), 'git+ssh://git@github.com/example/hg-git.git', None),
(URLValidator(EXTENDED_SCHEMES), 'git://-invalid.com', ValidationError),
# Trailing newlines not accepted
(URLValidator(), 'http://www.djangoproject.com/\n', ValidationError),
(URLValidator(), 'http... | TEST_DATA = [
(URLValidator(EXTENDED_SCHEMES), 'git+ssh://git@github.com/example/hg-git.git', None),
(URLValidator(EXTENDED_SCHEMES), 'git://-invalid.com', ValidationError),
# Newlines and tabs are not accepted.
(URLValidator(), 'http://www.djangoproject.com/\n', ValidationError),
(URLValidator(), ... |
import logging
import salt.utils.files
import salt.utils.path
import salt.payload
from salt.ext import six | import logging
import salt.utils.files
import salt.utils.path
import salt.utils.verify
import salt.payload
from salt.ext import six |
def get_token(opts, tok):
:returns: Token data if successful. Empty dict if failed.
'''
t_path = os.path.join(opts['token_dir'], tok)
if not os.path.isfile(t_path):
return {}
serial = salt.payload.Serial(opts) | def get_token(opts, tok):
:returns: Token data if successful. Empty dict if failed.
'''
t_path = os.path.join(opts['token_dir'], tok)
if not salt.utils.verify.clean_path(opts['token_dir'], t_path):
return {}
if not os.path.isfile(t_path):
return {}
serial = salt.payload.Serial(op... |
import salt.utils.files
import salt.utils.path
import salt.utils.platform
import salt.utils.user
log = logging.getLogger(__name__)
| import salt.utils.files
import salt.utils.path
import salt.utils.platform
import salt.utils.user
import salt.ext.six
log = logging.getLogger(__name__)
|
def check_max_open_files(opts):
log.log(level=level, msg=msg)
def clean_path(root, path, subdir=False):
'''
Accepts the root the path needs to be under and verifies that the path is
under said root. Pass in subdir=True if the path can result in a
subdirectory of the root instead of having to resid... | def check_max_open_files(opts):
log.log(level=level, msg=msg)
def _realpath_darwin(path):
base = ''
for part in path.split(os.path.sep)[1:]:
if base != '':
if os.path.islink(os.path.sep.join([base, part])):
base = os.readlink(os.path.sep.join([base, part]))
... |
def update_config(file_name, yaml_contents):
dir_path = os.path.join(__opts__['config_dir'],
os.path.dirname(__opts__['default_include']))
try:
yaml_out = salt.utils.yaml.safe_dump(yaml_contents, default_flow_style=False)
if not os.path.exists(dir_path):
... | def update_config(file_name, yaml_contents):
dir_path = os.path.join(__opts__['config_dir'],
os.path.dirname(__opts__['default_include']))
try:
yaml_out = salt.utils.yaml.safe_dump(
yaml_contents,
default_flow_style=False,
)
if not os.... |
def find(path, saltenv='base'):
return ret
for root in __opts__['file_roots'][saltenv]:
full = os.path.join(root, path)
if os.path.isfile(full):
# Add it to the dict
with salt.utils.files.fopen(full, 'rb') as fp_: | def find(path, saltenv='base'):
return ret
for root in __opts__['file_roots'][saltenv]:
full = os.path.join(root, path)
if not salt.utils.verify.clean_path(root, full):
continue
if os.path.isfile(full):
# Add it to the dict
with salt.utils.files.fo... |
def write(data, path, saltenv='base', index=0):
if os.path.isabs(path):
return ('The path passed in {0} is not relative to the environment '
'{1}').format(path, saltenv)
dest = os.path.join(__opts__['file_roots'][saltenv][index], path)
dest_dir = os.path.dirname(dest)
if not os.p... | def write(data, path, saltenv='base', index=0):
if os.path.isabs(path):
return ('The path passed in {0} is not relative to the environment '
'{1}').format(path, saltenv)
root = __opts__['file_roots'][saltenv][index]
dest = os.path.join(root, path)
if not salt.utils.verify.clean_p... |
class ClearFuncsPubTestCase(TestCase):
ret_evt = raw
break
assert not os.path.exists(self.tmpfile), 'Evil file created' | class ClearFuncsPubTestCase(TestCase):
ret_evt = raw
break
assert not os.path.exists(self.tmpfile), 'Evil file created'
class ClearFuncsConfigTest(TestCase):
def setUp(self):
master_opts = AdaptedConfigurationTestCaseMixin.get_config('master')
self.conf_dir... |
class BadTestModuleNamesTestCase(TestCase):
'integration.logging.test_jid_logging',
'integration.logging.handlers.test_logstash_mod',
'integration.master.test_event_return',
'integration.minion.test_blackout',
'integration.minion.test_executor',
'i... | class BadTestModuleNamesTestCase(TestCase):
'integration.logging.test_jid_logging',
'integration.logging.handlers.test_logstash_mod',
'integration.master.test_event_return',
'integration.master.test_clear_funcs',
'integration.minion.test_blackout',
... |
import stat
import shutil
import tempfile
import socket
# Import third party libs
if sys.platform.startswith('win'): | import stat
import shutil
import tempfile
import socket
import ctypes
# Import third party libs
if sys.platform.startswith('win'): |
from salt.utils.verify import (
verify_log,
verify_logs_filter,
verify_log_files,
)
# Import 3rd-party libs | from salt.utils.verify import (
verify_log,
verify_logs_filter,
verify_log_files,
clean_path
)
# Import 3rd-party libs |
class TestVerifyLog(TestCase):
self.assertFalse(os.path.exists(path))
verify_log_files([path], getpass.getuser())
self.assertTrue(os.path.exists(path)) | class TestVerifyLog(TestCase):
self.assertFalse(os.path.exists(path))
verify_log_files([path], getpass.getuser())
self.assertTrue(os.path.exists(path))
class TestCleanPath(TestCase):
'''
salt.utils.clean_path works as expected
'''
def setUp(self):
self.tmpdir = tempfile... |
def _enc_dec_rsa_pkey_ctx(backend, key, data, padding_enum, padding):
outlen = backend._ffi.new("size_t *", buf_size)
buf = backend._ffi.new("unsigned char[]", buf_size)
res = crypt(pkey_ctx, buf, outlen, data, len(data))
if res <= 0:
_handle_rsa_enc_dec_error(backend, key)
return backend.... | def _enc_dec_rsa_pkey_ctx(backend, key, data, padding_enum, padding):
outlen = backend._ffi.new("size_t *", buf_size)
buf = backend._ffi.new("unsigned char[]", buf_size)
# Everything from this line onwards is written with the goal of being as
# constant-time as is practical given the constraints of Pyt... |
import unittest
import urllib.parse
| import sys
import unicodedata
import unittest
import urllib.parse
|
def test_all(self):
expected.append(name)
self.assertCountEqual(urllib.parse.__all__, expected)
class Utility_Tests(unittest.TestCase):
"""Testcase to test the various utility functions in the urllib.""" | def test_all(self):
expected.append(name)
self.assertCountEqual(urllib.parse.__all__, expected)
def test_urlsplit_normalization(self):
# Certain characters should never occur in the netloc,
# including under normalization.
# Ensure that ALL of them are detected and c... |
def _splitnetloc(url, start=0):
delim = min(delim, wdelim) # use earliest delim position
return url[start:delim], url[delim:] # return (domain, rest)
def urlsplit(url, scheme='', allow_fragments=True):
"""Parse a URL into 5 components:
<scheme>://<netloc>/<path>?<query>#<fragment> | def _splitnetloc(url, start=0):
delim = min(delim, wdelim) # use earliest delim position
return url[start:delim], url[delim:] # return (domain, rest)
def _checknetloc(netloc):
if not netloc or netloc.isascii():
return
# looking for characters like \u2100 that expand to 'a/c'
#... |
def urlsplit(url, scheme='', allow_fragments=True):
url, fragment = url.split('#', 1)
if '?' in url:
url, query = url.split('?', 1)
v = SplitResult('http', netloc, url, query, fragment)
_parse_cache[key] = v
return _coerce_result(v) | def urlsplit(url, scheme='', allow_fragments=True):
url, fragment = url.split('#', 1)
if '?' in url:
url, query = url.split('?', 1)
_checknetloc(netloc)
v = SplitResult('http', netloc, url, query, fragment)
_parse_cache[key] = v
... |
def urlsplit(url, scheme='', allow_fragments=True):
url, fragment = url.split('#', 1)
if '?' in url:
url, query = url.split('?', 1)
v = SplitResult(scheme, netloc, url, query, fragment)
_parse_cache[key] = v
return _coerce_result(v) | def urlsplit(url, scheme='', allow_fragments=True):
url, fragment = url.split('#', 1)
if '?' in url:
url, query = url.split('?', 1)
_checknetloc(netloc)
v = SplitResult(scheme, netloc, url, query, fragment)
_parse_cache[key] = v
return _coerce_result(v) |
def _decryptRecord(self, recordType, b):
if self.version >= (3,2): #For TLS 1.1, remove explicit IV
b = b[self._readState.encContext.block_size : ]
#Check padding
paddingGood = True
paddingLength = b[-1] | def _decryptRecord(self, recordType, b):
if self.version >= (3,2): #For TLS 1.1, remove explicit IV
b = b[self._readState.encContext.block_size : ]
if len(b) == 0:
for result in self._sendError(\
AlertDescription.decryp... |
class NDFrame(PandasObject, SelectionMixin, indexing.IndexingMixin):
if not is_list:
start = self.index[0]
if isinstance(self.index, PeriodIndex):
where = Period(where, freq=self.index.freq).ordinal
start = start.ordinal
if where < start:
... | class NDFrame(PandasObject, SelectionMixin, indexing.IndexingMixin):
if not is_list:
start = self.index[0]
if isinstance(self.index, PeriodIndex):
where = Period(where, freq=self.index.freq)
if where < start:
if not is_series: |
class PeriodIndex(DatetimeIndexOpsMixin, Int64Index, PeriodDelegateMixin):
@Substitution(klass="PeriodIndex")
@Appender(_shared_docs["searchsorted"])
def searchsorted(self, value, side="left", sorter=None):
if isinstance(value, Period):
if value.freq != self.freq:
raise r... | class PeriodIndex(DatetimeIndexOpsMixin, Int64Index, PeriodDelegateMixin):
@Substitution(klass="PeriodIndex")
@Appender(_shared_docs["searchsorted"])
def searchsorted(self, value, side="left", sorter=None):
if isinstance(value, Period) or value is NaT:
self._data._check_compatible_with(v... |
class PeriodIndex(DatetimeIndexOpsMixin, Int64Index, PeriodDelegateMixin):
t1, t2 = self._parsed_string_to_bounds(reso, parsed)
return slice(
self.searchsorted(t1.ordinal, side="left"),
self.searchsorted(t2.ordinal, side="right"),
)
def _convert_tolerance(self, tole... | class PeriodIndex(DatetimeIndexOpsMixin, Int64Index, PeriodDelegateMixin):
t1, t2 = self._parsed_string_to_bounds(reso, parsed)
return slice(
self.searchsorted(t1, side="left"), self.searchsorted(t2, side="right")
)
def _convert_tolerance(self, tolerance, target): |
class TimeGrouper(Grouper):
rng += freq_mult
# adjust bin edge indexes to account for base
rng -= bin_shift
bins = memb.searchsorted(rng, side="left")
if nat_count > 0:
# NaT handling as in pandas._lib.lib.generate_bins_dt64() | class TimeGrouper(Grouper):
rng += freq_mult
# adjust bin edge indexes to account for base
rng -= bin_shift
# Wrap in PeriodArray for PeriodArray.searchsorted
prng = type(memb._data)(rng, dtype=memb.dtype)
bins = memb.searchsorted(prng, side="left")
if nat_count... |
import numpy as np
import pytest
from pandas import DataFrame, Series, Timestamp, date_range, to_datetime
import pandas._testing as tm
| import numpy as np
import pytest
from pandas import DataFrame, Period, Series, Timestamp, date_range, to_datetime
import pandas._testing as tm
|
class TestFrameAsof:
)
tm.assert_frame_equal(result, expected)
def test_all_nans(self, date_range_frame):
# GH 15713
# DataFrame is all nans | class TestFrameAsof:
)
tm.assert_frame_equal(result, expected)
# Check that we handle PeriodIndex correctly, dont end up with
# period.ordinal for series name
df = df.to_period("D")
result = df.asof("1989-12-31")
assert isinstance(result.name, Period)
def t... |
class TestPeriodIndex(DatetimeLike):
idx = PeriodIndex([2000, 2007, 2007, 2009, 2009], freq="A-JUN")
ts = Series(np.random.randn(len(idx)), index=idx)
result = ts[2007]
expected = ts[1:3]
tm.assert_series_equal(result, expected)
result[:] = 1 | class TestPeriodIndex(DatetimeLike):
idx = PeriodIndex([2000, 2007, 2007, 2009, 2009], freq="A-JUN")
ts = Series(np.random.randn(len(idx)), index=idx)
result = ts["2007"]
expected = ts[1:3]
tm.assert_series_equal(result, expected)
result[:] = 1 |
class TestPeriodIndex(DatetimeLike):
idx = PeriodIndex([2000, 2007, 2007, 2009, 2007], freq="A-JUN")
ts = Series(np.random.randn(len(idx)), index=idx)
result = ts[2007]
expected = ts[idx == "2007"]
tm.assert_series_equal(result, expected)
| class TestPeriodIndex(DatetimeLike):
idx = PeriodIndex([2000, 2007, 2007, 2009, 2007], freq="A-JUN")
ts = Series(np.random.randn(len(idx)), index=idx)
result = ts["2007"]
expected = ts[idx == "2007"]
tm.assert_series_equal(result, expected)
|
class TestPeriodIndex:
p2 = pd.Period("2014-01-04", freq=freq)
assert pidx.searchsorted(p2) == 3
msg = "Input has different freq=H from PeriodIndex"
with pytest.raises(IncompatibleFrequency, match=msg):
pidx.searchsorted(pd.Period("2014-01-01", freq="H"))
msg = "Inp... | class TestPeriodIndex:
p2 = pd.Period("2014-01-04", freq=freq)
assert pidx.searchsorted(p2) == 3
assert pidx.searchsorted(pd.NaT) == 0
msg = "Input has different freq=H from PeriodArray"
with pytest.raises(IncompatibleFrequency, match=msg):
pidx.searchsorted(pd.Peri... |
class XmlItemExporter(BaseItemExporter):
elif is_listlike(serialized_value):
for value in serialized_value:
self._export_xml_field('value', value)
else:
self._xg_characters(serialized_value)
self.xg.endElement(name)
# Workaround for http://bugs.python... | class XmlItemExporter(BaseItemExporter):
elif is_listlike(serialized_value):
for value in serialized_value:
self._export_xml_field('value', value)
elif isinstance(serialized_value, six.text_type):
self._xg_characters(serialized_value)
else:
sel... |
class XmlItemExporterTest(BaseItemExporterTest):
b'</items>'
)
class JsonLinesItemExporterTest(BaseItemExporterTest):
| class XmlItemExporterTest(BaseItemExporterTest):
b'</items>'
)
def test_nonstring_types_item(self):
item = self._get_nonstring_types_item()
self.assertExportResult(item,
b'<?xml version="1.0" encoding="utf-8"?>\n'
b'<items>'
b'<item>'
... |
class UrlParseTestCase(unittest.TestCase):
p = urllib.parse.urlsplit(url)
self.assertEqual(p.port, None)
def test_attributes_bad_port(self):
"""Check handling of non-integer ports."""
p = urllib.parse.urlsplit("http://www.example.net:foo") | class UrlParseTestCase(unittest.TestCase):
p = urllib.parse.urlsplit(url)
self.assertEqual(p.port, None)
def test_urlsplit_remove_unsafe_bytes(self):
# Remove ASCII tabs and newlines from input, for http common case scenario.
url = "h\nttp://www.python\n.org\t/java\nscript:\talert('... |
scheme_chars = ('abcdefghijklmnopqrstuvwxyz'
'0123456789'
'+-.')
# XXX: Consider replacing with functools.lru_cache
MAX_CACHE_SIZE = 20
_parse_cache = {} | scheme_chars = ('abcdefghijklmnopqrstuvwxyz'
'0123456789'
'+-.')
# Unsafe bytes to be removed per WHATWG spec
_UNSAFE_URL_BYTES_TO_REMOVE = ['\t', '\r', '\n']
# XXX: Consider replacing with functools.lru_cache
MAX_CACHE_SIZE = 20
_parse_cache = {} |
def _checknetloc(netloc):
raise ValueError("netloc '" + netloc2 + "' contains invalid " +
"characters under NFKC normalization")
def urlsplit(url, scheme='', allow_fragments=True):
"""Parse a URL into 5 components:
<scheme>://<netloc>/<path>?<query>#<fragment> | def _checknetloc(netloc):
raise ValueError("netloc '" + netloc2 + "' contains invalid " +
"characters under NFKC normalization")
def _remove_unsafe_bytes_from_url(url):
for b in _UNSAFE_URL_BYTES_TO_REMOVE:
url = url.replace(b, "")
return url
def urlsplit(url, ... |
def urlsplit(url, scheme='', allow_fragments=True):
Note that we don't break the components up in smaller bits
(e.g. netloc is a single string) and we don't expand % escapes."""
url, scheme, _coerce_result = _coerce_args(url, scheme)
allow_fragments = bool(allow_fragments)
key = url, scheme, allow_f... | def urlsplit(url, scheme='', allow_fragments=True):
Note that we don't break the components up in smaller bits
(e.g. netloc is a single string) and we don't expand % escapes."""
url, scheme, _coerce_result = _coerce_args(url, scheme)
url = _remove_unsafe_bytes_from_url(url)
scheme = _remove_unsafe_b... |
class DictTest(IronPythonTestCase):
x = str(d)
self.assertTrue(x.find("'abc'") != -1)
if is_cli:
self.assertTrue(x.find("'abc': <mappingproxy") != -1)
else:
self.assertTrue(x.find("'abc': mappingproxy") != -1)
del C.abc
keys, values = d.keys(), d... | class DictTest(IronPythonTestCase):
x = str(d)
self.assertTrue(x.find("'abc'") != -1)
self.assertTrue(x.find("'abc': mappingproxy") != -1)
del C.abc
keys, values = d.keys(), d.values() |
options:
name:
description:
- Zone name.
required: true
path:
description: | options:
name:
description:
- Zone name.
- A zone name must be unique name.
- A zone name must begin with an alpha-numeric character.
- The name can contain alpha-numeric characters, underbars I(_), hyphens I(-), and periods I(.).
- The name cannot be longer than 64 characters.
t... |
EXAMPLES = '''
import os
import platform
import tempfile
import time
| EXAMPLES = '''
import os
import platform
import re
import tempfile
import time
|
class Zone(object):
if int(self.os_minor) < 10:
self.module.fail_json(msg='This module requires Solaris 10 or later')
def configure(self):
if not self.path:
self.module.fail_json(msg='Missing required argument: path') | class Zone(object):
if int(self.os_minor) < 10:
self.module.fail_json(msg='This module requires Solaris 10 or later')
match = re.match('^[a-zA-Z0-9][-_.a-zA-Z0-9]{0,62}$', self.name)
if not match:
self.module.fail_json(msg="Provided zone name is not a valid zone name. "
... |
"""
Constants specific to the SQL storage portion of the ORM.
"""
# Size of each "chunk" for get_iterator calls.
# Larger values are slightly faster at the expense of more storage space. | """
Constants specific to the SQL storage portion of the ORM.
"""
from django.utils.regex_helper import _lazy_re_compile
# Size of each "chunk" for get_iterator calls.
# Larger values are slightly faster at the expense of more storage space. |
ORDER_DIR = {
'ASC': ('ASC', 'DESC'),
'DESC': ('DESC', 'ASC'),
}
# SQL join types.
INNER = 'INNER JOIN' | ORDER_DIR = {
'ASC': ('ASC', 'DESC'),
'DESC': ('DESC', 'ASC'),
}
ORDER_PATTERN = _lazy_re_compile(r'[-+]?[.\w]+$')
# SQL join types.
INNER = 'INNER JOIN' |
from django.db.models.lookups import Lookup
from django.db.models.query_utils import (
Q, check_rel_lookup_compatibility, refs_expression,
)
from django.db.models.sql.constants import INNER, LOUTER, ORDER_DIR, SINGLE
from django.db.models.sql.datastructures import (
BaseTable, Empty, Join, MultiJoin,
) | from django.db.models.lookups import Lookup
from django.db.models.query_utils import (
Q, check_rel_lookup_compatibility, refs_expression,
)
from django.db.models.sql.constants import (
INNER, LOUTER, ORDER_DIR, ORDER_PATTERN, SINGLE,
)
from django.db.models.sql.datastructures import (
BaseTable, Empty, Joi... |
class Query(BaseExpression):
errors = []
for item in ordering:
if isinstance(item, str):
if '.' in item:
warnings.warn(
'Passing column raw column aliases to order_by() is '
'deprecated. Wrap %r in a RawSQL e... | class Query(BaseExpression):
errors = []
for item in ordering:
if isinstance(item, str):
if '.' in item and ORDER_PATTERN.match(item):
warnings.warn(
'Passing column raw column aliases to order_by() is '
'dep... |
class QuerySetExceptionTests(SimpleTestCase):
with self.assertRaisesMessage(FieldError, msg):
Article.objects.order_by('*')
def test_invalid_queryset_model(self):
msg = 'Cannot use QuerySet for "Article": Use a QuerySet for "ExtraInfo".'
with self.assertRaisesMessage(ValueError,... | class QuerySetExceptionTests(SimpleTestCase):
with self.assertRaisesMessage(FieldError, msg):
Article.objects.order_by('*')
def test_order_by_escape_prevention(self):
msg = (
"Cannot resolve keyword 'queries.name);' into field. Choices are: "
"created, id, name"
... |
from tensorflow.python.ops import functional_ops
from tensorflow.python.ops import ctc_ops as ctc
from .common import floatx, epsilon, image_data_format
import functools
import threading
| from tensorflow.python.ops import functional_ops
from tensorflow.python.ops import ctc_ops as ctc
from .common import floatx, epsilon, image_data_format
import sys
import functools
import threading
|
def update(x, new_x):
# Returns
The variable `x` updated.
"""
return tf_state_ops.assign(x, new_x)
@symbolic | def update(x, new_x):
# Returns
The variable `x` updated.
"""
op = tf_state_ops.assign(x, new_x)
with tf.control_dependencies([op]):
return tf.identity(x)
@symbolic |
def update_add(x, increment):
# Returns
The variable `x` updated.
"""
return tf_state_ops.assign_add(x, increment)
@symbolic | def update_add(x, increment):
# Returns
The variable `x` updated.
"""
op = tf_state_ops.assign_add(x, increment)
with tf.control_dependencies([op]):
return tf.identity(x)
@symbolic |
def update_sub(x, decrement):
# Returns
The variable `x` updated.
"""
return tf_state_ops.assign_sub(x, decrement)
@symbolic | def update_sub(x, decrement):
# Returns
The variable `x` updated.
"""
op = tf_state_ops.assign_sub(x, decrement)
with tf.control_dependencies([op]):
return tf.identity(x)
@symbolic |
def get_variable_shape(x):
return int_shape(x)
def print_tensor(x, message=''):
"""Prints `message` and the tensor value when evaluated.
| def get_variable_shape(x):
return int_shape(x)
@symbolic
def print_tensor(x, message=''):
"""Prints `message` and the tensor value when evaluated.
|
def print_tensor(x, message=''):
# Returns
The same tensor `x`, unchanged.
"""
# TODO
return tf.Print(x, [x], message)
# GRAPH MANIPULATION | def print_tensor(x, message=''):
# Returns
The same tensor `x`, unchanged.
"""
op = tf.print(message, x, output_stream=sys.stdout)
with tf.control_dependencies([op]):
return tf.identity(x)
# GRAPH MANIPULATION |
def get_variable_shape(x):
def print_tensor(x, message=''):
"""Print the message and the tensor when evaluated and return the same
tensor.
"""
p_op = Print(message)
return p_op(x) | def get_variable_shape(x):
def print_tensor(x, message=''):
"""Print the message & the tensor when evaluated & return the same tensor.
"""
p_op = Print(message)
return p_op(x) |
class RandomNormal(Initializer):
self.seed = seed
def __call__(self, shape, dtype=None):
return K.random_normal(shape, self.mean, self.stddev,
dtype=dtype, seed=self.seed)
def get_config(self):
return { | class RandomNormal(Initializer):
self.seed = seed
def __call__(self, shape, dtype=None):
x = K.random_normal(shape, self.mean, self.stddev,
dtype=dtype, seed=self.seed)
if self.seed is not None:
self.seed += 1
return x
def get_config(self... |
class RandomUniform(Initializer):
self.seed = seed
def __call__(self, shape, dtype=None):
return K.random_uniform(shape, self.minval, self.maxval,
dtype=dtype, seed=self.seed)
def get_config(self):
return { | class RandomUniform(Initializer):
self.seed = seed
def __call__(self, shape, dtype=None):
x = K.random_uniform(shape, self.minval, self.maxval,
dtype=dtype, seed=self.seed)
if self.seed is not None:
self.seed += 1
return x
def get_config... |
class TruncatedNormal(Initializer):
self.seed = seed
def __call__(self, shape, dtype=None):
return K.truncated_normal(shape, self.mean, self.stddev,
dtype=dtype, seed=self.seed)
def get_config(self):
return { | class TruncatedNormal(Initializer):
self.seed = seed
def __call__(self, shape, dtype=None):
x = K.truncated_normal(shape, self.mean, self.stddev,
dtype=dtype, seed=self.seed)
if self.seed is not None:
self.seed += 1
return x
def get_co... |
class VarianceScaling(Initializer):
if self.distribution == 'normal':
# 0.879... = scipy.stats.truncnorm.std(a=-2, b=2, loc=0., scale=1.)
stddev = np.sqrt(scale) / .87962566103423978
return K.truncated_normal(shape, 0., stddev,
dtype=dtyp... | class VarianceScaling(Initializer):
if self.distribution == 'normal':
# 0.879... = scipy.stats.truncnorm.std(a=-2, b=2, loc=0., scale=1.)
stddev = np.sqrt(scale) / .87962566103423978
x = K.truncated_normal(shape, 0., stddev,
dtype=dtype, see... |
class Orthogonal(Initializer):
rng = np.random
if self.seed is not None:
rng = np.random.RandomState(self.seed)
a = rng.normal(0.0, 1.0, flat_shape)
u, _, v = np.linalg.svd(a, full_matrices=False)
# Pick the one with the correct shape. | class Orthogonal(Initializer):
rng = np.random
if self.seed is not None:
rng = np.random.RandomState(self.seed)
self.seed += 1
a = rng.normal(0.0, 1.0, flat_shape)
u, _, v = np.linalg.svd(a, full_matrices=False)
# Pick the one with the correct shape. |
class TestBackend(object):
else:
assert_list_pairwise(v_list, shape=False, allclose=False, itself=True)
def test_print_tensor(self):
check_single_tensor_operation('print_tensor', (), WITH_NP)
check_single_tensor_operation('print_tensor', (2,), WITH_NP)
check_single_tenso... | class TestBackend(object):
else:
assert_list_pairwise(v_list, shape=False, allclose=False, itself=True)
def test_print_tensor(self, capsys):
for k in [KTH, KTF]:
x = k.placeholder((1, 1))
y = k.print_tensor(x, 'msg')
fn = k.function([x], [y])
... |
class TestBackend(object):
def test_log(self):
check_single_tensor_operation('log', (4, 2), WITH_NP)
@pytest.mark.skipif(K.backend() == 'theano',
reason='theano returns tuples for update ops')
def test_update_add(self):
x = np.random.randn(3, 4)
x_var = K.var... | class TestBackend(object):
def test_log(self):
check_single_tensor_operation('log', (4, 2), WITH_NP)
@pytest.mark.skipif(K.backend() == 'theano',
reason='theano returns tuples for update ops')
def test_update(self):
x = np.ones((3, 4))
x_var = K.variable(x)
... |
class TestBackend(object):
assert output == [21.]
assert K.get_session().run(fetches=[x, y]) == [30., 40.]
@pytest.mark.skipif(K.backend() != 'tensorflow',
reason='Uses the `options` and `run_metadata` arguments.')
def test_function_tf_run_options_with_run_metadata(self)... | class TestBackend(object):
assert output == [21.]
assert K.get_session().run(fetches=[x, y]) == [30., 40.]
@pytest.mark.skipif(K.backend() != 'tensorflow' or not KTF._is_tf_1(),
reason='Uses the `options` and `run_metadata` arguments.')
def test_function_tf_run_options_w... |
class TestBackend(object):
assert_allclose(y1, y2, atol=1e-05)
def test_random_normal(self):
# test standard normal as well as a normal with a different set of parameters
for mean, std in [(0., 1.), (-10., 5.)]:
rand = K.eval(K.random_normal((300, 200),
... | class TestBackend(object):
assert_allclose(y1, y2, atol=1e-05)
def test_random_normal(self):
# TODO: make this a parameterized test
for mean, std in [(0., 1.), (-10., 5.)]:
rand = K.eval(K.random_normal((200, 200),
mean=mean,
... |
class TestBackend(object):
np.asarray([-5., -4., 0., 4., 9.],
dtype=np.float32))
@pytest.mark.skipif(K.backend() != 'tensorflow' or KTF._is_tf_1(),
reason='This test is for tensorflow parallelism.')
def test_tensorflow_ses... | class TestBackend(object):
np.asarray([-5., -4., 0., 4., 9.],
dtype=np.float32))
if __name__ == '__main__':
pytest.main([__file__]) |
def test_one(tensor_shape):
target_mean=1., target_max=1.)
if __name__ == '__main__':
pytest.main([__file__]) | def test_one(tensor_shape):
target_mean=1., target_max=1.)
@pytest.mark.parametrize('initializer',
[initializers.orthogonal,
initializers.uniform,
initializers.normal,
initializers.truncated_normal,
... |
class TestUtil(unittest.TestCase):
def test_str_to_int(self):
self.assertEqual(str_to_int('123,456'), 123456)
self.assertEqual(str_to_int('123.456'), 123456)
def test_url_basename(self):
self.assertEqual(url_basename('http://foo.de/'), '') | class TestUtil(unittest.TestCase):
def test_str_to_int(self):
self.assertEqual(str_to_int('123,456'), 123456)
self.assertEqual(str_to_int('123.456'), 123456)
self.assertEqual(str_to_int(523), 523)
def test_url_basename(self):
self.assertEqual(url_basename('http://foo.de/'), '') |
def str_or_none(v, default=None):
def str_to_int(int_str):
""" A more relaxed version of int_or_none """
if int_str is None:
return None
int_str = re.sub(r'[,\.\+]', '', int_str)
return int(int_str)
| def str_or_none(v, default=None):
def str_to_int(int_str):
""" A more relaxed version of int_or_none """
if not isinstance(int_str, compat_str):
return int_str
int_str = re.sub(r'[,\.\+]', '', int_str)
return int(int_str)
|
def normalize_invisible_parens(node: Node, parens_after: Set[str]) -> None:
check_lpar = False
for index, child in enumerate(list(node.children)):
if check_lpar:
if child.type == syms.atom:
if maybe_make_parens_invisible_in_atom(child, parent=node): | def normalize_invisible_parens(node: Node, parens_after: Set[str]) -> None:
check_lpar = False
for index, child in enumerate(list(node.children)):
# Add parentheses around long tuple unpacking in assignments.
if (
index == 0
and isinstance(child, Node)
and ch... |
def normalize_invisible_parens(node: Node, parens_after: Set[str]) -> None:
lpar = Leaf(token.LPAR, "")
rpar = Leaf(token.RPAR, "")
index = child.remove() or 0
node.insert_child(index, Node(syms.atom, [lpar, child, rpar]))
check_lpar = isinstance(... | def normalize_invisible_parens(node: Node, parens_after: Set[str]) -> None:
lpar = Leaf(token.LPAR, "")
rpar = Leaf(token.RPAR, "")
index = child.remove() or 0
prefix = child.prefix
child.prefix = ""
new_child = Node(syms.at... |
class BlackTestCase(unittest.TestCase):
black.assert_equivalent(source, actual)
black.assert_stable(source, actual, black.FileMode())
def test_tab_comment_indentation(self) -> None:
contents_tab = "if 1:\n\tif 2:\n\t\tpass\n\t# comment\n\tpass\n"
contents_spc = "if 1:\n if 2:\n ... | 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_tuple_assign(self) -> None:
source, expected = read_data("tupleassign")
actual = fs(source)... |
def shortDescription(self):
return """%s .decrypt() output of .encrypt() should not be garbled""" % (self.module_name,)
def runTest(self):
for mode in (self.module.MODE_ECB, self.module.MODE_CBC, self.module.MODE_CFB, self.module.MODE_OFB, self.module.MODE_OPENPGP):
encryption_cipher = ... | def shortDescription(self):
return """%s .decrypt() output of .encrypt() should not be garbled""" % (self.module_name,)
def runTest(self):
## ECB mode
mode = self.module.MODE_ECB
encryption_cipher = self.module.new(a2b_hex(self.key), mode)
ciphertext = encryption_cipher.enc... |
class _Alpha:
raise ValueError
def __gt__(self, other):
return not self.__lt__(other)
def __le__(self, other):
return self.__lt__(other) or self.__eq__(other)
def __ge__(self, other):
return self.__gt__(other) or self.__eq__(other)
class _Numeric: | class _Alpha:
raise ValueError
def __le__(self, other):
return self.__lt__(other) or self.__eq__(other)
def __gt__(self, other):
return not self.__le__(other)
def __ge__(self, other):
return not self.__lt__(other)
class _Numeric: |
class _Numeric:
raise ValueError
def __gt__(self, other):
return not self.__lt__(other)
def __le__(self, other):
return self.__lt__(other) or self.__eq__(other)
def __ge__(self, other):
return self.__gt__(other) or self.__eq__(other)
class SemanticVersion(Version): | class _Numeric:
raise ValueError
def __le__(self, other):
return self.__lt__(other) or self.__eq__(other)
def __gt__(self, other):
return not self.__le__(other)
def __ge__(self, other):
return not self.__lt__(other)
class SemanticVersion(Version): |
def test_alpha():
assert _Alpha('b') >= _Alpha('a')
assert _Alpha('b') >= _Alpha('b')
def test_numeric():
assert _Numeric(1) == _Numeric(1) | def test_alpha():
assert _Alpha('b') >= _Alpha('a')
assert _Alpha('b') >= _Alpha('b')
# The following 3*6 tests check that all comparison operators perform
# as expected. DO NOT remove any of them, or reformulate them (to remove
# the explicit `not`)!
assert _Alpha('a') == _Alpha('a')
asse... |
def test_numeric():
assert _Numeric(1) <= _Numeric(2)
assert _Numeric(2) >= _Numeric(1)
assert _Numeric(2) >= _Numeric(2) | def test_numeric():
assert _Numeric(1) <= _Numeric(2)
assert _Numeric(2) >= _Numeric(1)
assert _Numeric(2) >= _Numeric(2)
# The following 3*6 tests check that all comparison operators perform
# as expected. DO NOT remove any of them, or reformulate them (to remove
# the explicit `not`)!
as... |
class Language(object):
kwargs = component_cfg.get(name, {})
kwargs.setdefault("batch_size", batch_size)
if not hasattr(pipe, "pipe"):
docs = _pipe(pipe, docs, kwargs)
else:
docs = pipe.pipe(docs, **kwargs)
for doc, gold in zip(docs... | class Language(object):
kwargs = component_cfg.get(name, {})
kwargs.setdefault("batch_size", batch_size)
if not hasattr(pipe, "pipe"):
docs = _pipe(docs, pipe, kwargs)
else:
docs = pipe.pipe(docs, **kwargs)
for doc, gold in zip(docs... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.