buggy
stringlengths
35
5.03k
fixed
stringlengths
46
62.5k
def should_series_dispatch(left, right, op): # numpy integer dtypes as timedelta64 dtypes in this scenario return True if is_datetime64_dtype(ldtype) and is_object_dtype(rdtype): # in particular case where right is an array of DateOffsets return True return False
def should_series_dispatch(left, right, op): # numpy integer dtypes as timedelta64 dtypes in this scenario return True if (is_datetime64_dtype(ldtype) and is_object_dtype(rdtype)) or ( is_datetime64_dtype(rdtype) and is_object_dtype(ldtype) ): # in particular case where one is a...
def id_func(x): # ------------------------------------------------------------------ @pytest.fixture(params=[1, np.array(1, dtype=np.int64)])
def id_func(x): # ------------------------------------------------------------------ @pytest.fixture( params=[ ("foo", None, None), ("Egon", "Venkman", None), ("NCC1701D", "NCC1701D", "NCC1701D"), ] ) def names(request): """ A 3-tuple of names, the first two for operands, the l...
class TestDatetime64DateOffsetArithmetic: tm.assert_equal(result, exp) tm.assert_equal(result2, exp) # TODO: __sub__, __rsub__ def test_dt64arr_add_mixed_offset_array(self, box_with_array): # GH#10699 # array of offsets s = DatetimeIndex([Timestamp("2000-1-1"), Timestamp...
class TestDatetime64DateOffsetArithmetic: tm.assert_equal(result, exp) tm.assert_equal(result2, exp) @pytest.mark.parametrize( "other", [ np.array([pd.offsets.MonthEnd(), pd.offsets.Day(n=2)]), np.array([pd.offsets.DateOffset(years=1), pd.offsets.MonthEnd()])...
class TestTimestampSeriesArithmetic: # TODO: parametrize over box @pytest.mark.parametrize("op", ["__add__", "__radd__", "__sub__", "__rsub__"]) @pytest.mark.parametrize("tz", [None, "Asia/Tokyo"]) def test_dt64_series_add_intlike(self, tz, op): # GH#19123 dti = pd.DatetimeIndex(["2016-...
class TestTimestampSeriesArithmetic: # TODO: parametrize over box @pytest.mark.parametrize("op", ["__add__", "__radd__", "__sub__", "__rsub__"]) def test_dt64_series_add_intlike(self, tz_naive_fixture, op): # GH#19123 tz = tz_naive_fixture dti = pd.DatetimeIndex(["2016-01-02", "2016...
class TestDatetimeIndexArithmetic: tm.assert_index_equal(result, exp) assert result.freq == exp.freq @pytest.mark.parametrize( "names", [("foo", None, None), ("baz", "bar", None), ("bar", "bar", "bar")] ) @pytest.mark.parametrize("tz", [None, "America/Chicago"]) def test...
class TestDatetimeIndexArithmetic: tm.assert_index_equal(result, exp) assert result.freq == exp.freq def test_dti_add_series(self, tz_naive_fixture, names): # GH#13905 tz = tz_naive_fixture index = DatetimeIndex( ["2016-06-28 05:30", "2016-06-28 05:31"], ...
class TestDatetimeIndexArithmetic: tm.assert_index_equal(result4, expected) @pytest.mark.parametrize("op", [operator.add, roperator.radd, operator.sub]) @pytest.mark.parametrize( "names", [(None, None, None), ("foo", "bar", None), ("foo", "foo", "foo")] ) def test_dti_addsub_offset_arra...
class TestDatetimeIndexArithmetic: tm.assert_index_equal(result4, expected) @pytest.mark.parametrize("op", [operator.add, roperator.radd, operator.sub]) def test_dti_addsub_offset_arraylike( self, tz_naive_fixture, names, op, index_or_series ):
class TestTimedeltaArraylikeAddSubOps: result = tdarr - tdi tm.assert_equal(result, expected) @pytest.mark.parametrize( "names", [ (None, None, None), ("Egon", "Venkman", None), ("NCC1701D", "NCC1701D", "NCC1701D"), ], ) def test_t...
class TestTimedeltaArraylikeAddSubOps: result = tdarr - tdi tm.assert_equal(result, expected) def test_td64arr_add_sub_tdi(self, box, names): # GH#17250 make sure result dtype is correct # GH#19043 make sure names are propagated correctly if box is pd.DataFrame and names[1] ...
class TestTimedeltaArraylikeAddSubOps: # ------------------------------------------------------------------ # __add__/__sub__ with DateOffsets and arrays of DateOffsets @pytest.mark.parametrize( "names", [(None, None, None), ("foo", "bar", None), ("foo", "foo", "foo")] ) def test_td64arr_ad...
class TestTimedeltaArraylikeAddSubOps: # ------------------------------------------------------------------ # __add__/__sub__ with DateOffsets and arrays of DateOffsets def test_td64arr_add_offset_index(self, names, box): # GH#18849, GH#19744 if box is pd.DataFrame and names[1] != names[0]:...
class TestTimedeltaArraylikeMulDivOps: with pytest.raises(TypeError, match=pattern): vector.astype(object) / tdser @pytest.mark.parametrize( "names", [ (None, None, None), ("Egon", "Venkman", None), ("NCC1701D", "NCC1701D", "NCC1701D"), ...
class TestTimedeltaArraylikeMulDivOps: with pytest.raises(TypeError, match=pattern): vector.astype(object) / tdser def test_td64arr_mul_int_series(self, box_df_fail, names): # GH#19042 test for correct name attachment box = box_df_fail # broadcasts along wrong axis, but doesn't...
class TestTimedeltaArraylikeMulDivOps: tm.assert_equal(result, expected) # TODO: Should we be parametrizing over types for `ser` too? @pytest.mark.parametrize( "names", [ (None, None, None), ("Egon", "Venkman", None), ("NCC1701D", "NCC1701D", "NCC1701...
class TestTimedeltaArraylikeMulDivOps: tm.assert_equal(result, expected) # TODO: Should we be parametrizing over types for `ser` too? def test_float_series_rdiv_td64arr(self, box_with_array, names): # GH#19042 test for correct name attachment # TODO: the direct operation TimedeltaIndex ...
def format_file_in_place( with open(src, "w", encoding=src_buffer.encoding) as f: f.write(dst_contents) elif write_back == write_back.DIFF: src_name = f"{src.name} (original)" dst_name = f"{src.name} (formatted)" diff_contents = diff(src_contents, dst_contents, src_name...
def format_file_in_place( with open(src, "w", encoding=src_buffer.encoding) as f: f.write(dst_contents) elif write_back == write_back.DIFF: src_name = f"{src} (original)" dst_name = f"{src} (formatted)" diff_contents = diff(src_contents, dst_contents, src_name, dst_name...
class BlackTestCase(unittest.TestCase): self.assertTrue(ff(tmp_file, write_back=black.WriteBack.DIFF)) sys.stdout.seek(0) actual = sys.stdout.read() actual = actual.replace(tmp_file.name, "<stdin>") finally: sys.stdout = hold_stdout os.unli...
class BlackTestCase(unittest.TestCase): self.assertTrue(ff(tmp_file, write_back=black.WriteBack.DIFF)) sys.stdout.seek(0) actual = sys.stdout.read() actual = actual.replace(str(tmp_file), "<stdin>") finally: sys.stdout = hold_stdout os.unli...
if __name__ == "__main__": if os.path.exists('/tmp/bar'): shutil.rmtree('/tmp/bar') luigi.run(['--task', 'examples.Foo', '--workers', '2', '--local-scheduler'])
if __name__ == "__main__": if os.path.exists('/tmp/bar'): shutil.rmtree('/tmp/bar') luigi.run(['examples.Foo', '--workers', '2', '--local-scheduler'])
def run(cmdline_args=None, main_task_cls=None, :param use_dynamic_argparse: :param local_scheduler: """ if use_dynamic_argparse: interface = DynamicArgParseInterface() else:
def run(cmdline_args=None, main_task_cls=None, :param use_dynamic_argparse: :param local_scheduler: """ if cmdline_args is None: cmdline_args = sys.argv[1:] if use_dynamic_argparse: interface = DynamicArgParseInterface() else:
from helpers import unittest import luigi import luigi.date_interval import luigi.notifications from luigi.interface import core, Interface, WorkerSchedulerFactory from luigi.worker import Worker from mock import Mock luigi.notifications.DEBUG = True class InterfaceTest(unittest.TestCase): def setUp(self): ...
from helpers import unittest import luigi import luigi.date_interval import luigi.notifications import sys from luigi.interface import core, Interface, WorkerSchedulerFactory from luigi.worker import Worker from mock import Mock, patch from helpers import LuigiTestCase luigi.notifications.DEBUG = True class Interfac...
class InterfaceTest(unittest.TestCase): self.worker_scheduler_factory = WorkerSchedulerFactory() self.worker_scheduler_factory.create_worker = Mock(return_value=self.worker) self.worker_scheduler_factory.create_local_scheduler = Mock() class NoOpTask(luigi.Task): param = lui...
class InterfaceTest(unittest.TestCase): self.worker_scheduler_factory = WorkerSchedulerFactory() self.worker_scheduler_factory.create_worker = Mock(return_value=self.worker) self.worker_scheduler_factory.create_local_scheduler = Mock() super(InterfaceTest, self).setUp() class No...
class InterfaceTest(unittest.TestCase): self.assertFalse(self._run_interface()) def _run_interface(self): return Interface.run([self.task_a, self.task_b], self.worker_scheduler_factory, {'no_lock': True})
class InterfaceTest(unittest.TestCase): self.assertFalse(self._run_interface()) def test_just_run_main_task_cls(self): class MyTestTask(luigi.Task): pass class MyOtherTestTask(luigi.Task): my_param = luigi.Parameter() with patch.object(sys, 'argv', ['my_mo...
from typing import ( Sequence, Set, Tuple, Type, TypeVar, Union, cast,
from typing import ( Sequence, Set, Tuple, TypeVar, Union, cast,
class CannotSplit(Exception): """ class FormatError(Exception): """Base exception for `# fmt: on` and `# fmt: off` handling. It holds the number of bytes of the prefix consumed before the format control comment appeared. """ def __init__(self, consumed: int) -> None: super().__init__...
class CannotSplit(Exception): """ class WriteBack(Enum): NO = 0 YES = 1
class DebugVisitor(Visitor[T]): out(f" {node.value!r}", fg="blue", bold=False) @classmethod def show(cls, code: str) -> None: """Pretty-print the lib2to3 AST of a given string of `code`. Convenience method for debugging. """ v: DebugVisitor[None] = DebugVisitor() ...
class DebugVisitor(Visitor[T]): out(f" {node.value!r}", fg="blue", bold=False) @classmethod def show(cls, code: Union[str, Leaf, Node]) -> None: """Pretty-print the lib2to3 AST of a given string of `code`. Convenience method for debugging. """ v: DebugVisitor[None] ...
class Line: return bool(self.leaves or self.comments) class UnformattedLines(Line): """Just like :class:`Line` but stores lines which aren't reformatted.""" def append(self, leaf: Leaf, preformatted: bool = True) -> None: """Just add a new `leaf` to the end of the lines. The `preform...
class Line: return bool(self.leaves or self.comments) @dataclass class EmptyLineTracker: """Provides a stateful method that returns the number of potential extra
class EmptyLineTracker: This is for separating `def`, `async def` and `class` with extra empty lines (two on module-level). """ if isinstance(current_line, UnformattedLines): return 0, 0 before, after = self._maybe_empty_lines(current_line) before -= self.pre...
class EmptyLineTracker: This is for separating `def`, `async def` and `class` with extra empty lines (two on module-level). """ before, after = self._maybe_empty_lines(current_line) before -= self.previous_after self.previous_after = after
class LineGenerator(Visitor[Line]): current_line: Line = Factory(Line) remove_u_prefix: bool = False def line(self, indent: int = 0, type: Type[Line] = Line) -> Iterator[Line]: """Generate a line. If the line is empty, only emit if it makes sense.
class LineGenerator(Visitor[Line]): current_line: Line = Factory(Line) remove_u_prefix: bool = False def line(self, indent: int = 0) -> Iterator[Line]: """Generate a line. If the line is empty, only emit if it makes sense.
class LineGenerator(Visitor[Line]): If any lines were generated, set up a new current_line. """ if not self.current_line: if self.current_line.__class__ == type: self.current_line.depth += indent else: self.current_line = type(depth=self.cu...
class LineGenerator(Visitor[Line]): If any lines were generated, set up a new current_line. """ if not self.current_line: self.current_line.depth += indent return # Line is empty, don't emit. Creating a new one unnecessary. complete_line = self.current_line ...
class LineGenerator(Visitor[Line]): yield from self.visit_default(leaf) yield from self.line() def visit_unformatted(self, node: LN) -> Iterator[Line]: """Used when file contained a `# fmt: off`.""" if isinstance(node, Node): for child in node.children: y...
class LineGenerator(Visitor[Line]): yield from self.visit_default(leaf) yield from self.line() def visit_STANDALONE_COMMENT(self, leaf: Leaf) -> Iterator[Line]: if not self.current_line.bracket_tracker.any_open_brackets(): yield from self.line() yield from self.visit_def...
def container_of(leaf: Leaf) -> LN: if parent.children[0].prefix != same_prefix: break if parent.type in SURROUNDED_BY_BRACKETS: break
def container_of(leaf: Leaf) -> LN: if parent.children[0].prefix != same_prefix: break if parent.type == syms.file_input: break if parent.type in SURROUNDED_BY_BRACKETS: break
def generate_comments(leaf: LN) -> Iterator[Leaf]: """ for pc in list_comments(leaf.prefix, is_endmarker=leaf.type == token.ENDMARKER): yield Leaf(pc.type, pc.value, prefix="\n" * pc.newlines) if pc.value in FMT_ON: raise FormatOn(pc.consumed) if pc.value in FMT_OFF: ...
def generate_comments(leaf: LN) -> Iterator[Leaf]: """ for pc in list_comments(leaf.prefix, is_endmarker=leaf.type == token.ENDMARKER): yield Leaf(pc.type, pc.value, prefix="\n" * pc.newlines) @dataclass
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
def split_line( If `py36` is True, splitting may generate syntax that is only compatible with Python 3.6 and later. """ if line.is_comment: yield line return
def normalize_invisible_parens(node: Node, parens_after: Set[str]) -> None: def normalize_fmt_off(node: Node) -> None: """Allow `# fmt: off`/`# fmt: on` within bracket pairs. Ignores `# fmt: off` and `# fmt: on` outside of brackets. Raises :exc:`SyntaxError` if no matching `# fmt: on` is found for a `# ...
def normalize_invisible_parens(node: Node, parens_after: Set[str]) -> None: def normalize_fmt_off(node: Node) -> None: """Convert content between `# fmt: off`/`# fmt: on` into standalone comments.""" try_again = True while try_again: try_again = convert_one_fmt_off_pair(node) def convert_one_fmt...
def hide_fmt_off(node: Node) -> bool: hidden_value = ( comment.value + "\n" + "".join(str(n) for n in ignored_nodes) ) first_idx = None for ignored in ignored_nodes: index = ignored.remove()
def hide_fmt_off(node: Node) -> bool: hidden_value = ( comment.value + "\n" + "".join(str(n) for n in ignored_nodes) ) if hidden_value.endswith("\n"): # That happens when one of the `ignored_nodes` ended with a NEWLINE ...
def hide_fmt_off(node: Node) -> bool: def generate_ignored_nodes(leaf: Leaf) -> Iterator[LN]: container: Optional[LN] = container_of(leaf) while container is not None: for comment in list_comments(container.prefix, is_endmarker=False): if comment.value in FMT_ON: return
def hide_fmt_off(node: Node) -> bool: def generate_ignored_nodes(leaf: Leaf) -> Iterator[LN]: """Starting from the container of `leaf`, generate all leaves until `# fmt: on`. Stops at the end of the block. """ container: Optional[LN] = container_of(leaf) while container is not None and container....
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_remove_empty_parentheses_after_class(self) -> None: source, expected = read_data("class_blank_parenth...
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_fmtonoff2(self) -> None: source, expected = read_data("fmtonoff2") actual = fs(source) ...
def gendata4(): data = [gendata1(), gendata2(), gendata4()] class TestAudioop(unittest.TestCase):
def gendata4(): data = [gendata1(), gendata2(), gendata4()] INVALID_DATA = [ ('abc', 0), ('abc', 2), ('abc', 4), ] class TestAudioop(unittest.TestCase):
def test_negativelen(self): self.assertRaises(audioop.error, audioop.findmax, ''.join(chr(x) for x in range(256)), -2392392) def test_main(): run_unittest(TestAudioop)
def test_negativelen(self): self.assertRaises(audioop.error, audioop.findmax, ''.join(chr(x) for x in range(256)), -2392392) def test_issue7673(self): state = None for data, size in INVALID_DATA: size2 = size self.assertRaises(audioop.error, audioop.getsa...
def strip_tags(value): value = str(value) while '<' in value and '>' in value: new_value = _strip_once(value) if len(new_value) >= len(value): # _strip_once was not able to detect more tags break value = new_value return value
def strip_tags(value): value = str(value) while '<' in value and '>' in value: new_value = _strip_once(value) if value.count('<') == new_value.count('<'): # _strip_once wasn't able to detect more tags. break value = new_value return value
class TestUtilsHtml(SimpleTestCase): ('&gotcha&#;<>', '&gotcha&#;<>'), ('<sc<!-- -->ript>test<<!-- -->/script>', 'ript>test'), ('<script>alert()</script>&h', 'alert()h'), ) for value, output in items: with self.subTest(value=value, output=output):
class TestUtilsHtml(SimpleTestCase): ('&gotcha&#;<>', '&gotcha&#;<>'), ('<sc<!-- -->ript>test<<!-- -->/script>', 'ript>test'), ('<script>alert()</script>&h', 'alert()h'), ('><!' + ('&' * 16000) + 'D', '><!' + ('&' * 16000) + 'D'), ('X<<<<br>br>br>br>X', 'XX'),...
class RegexPattern(CheckURLMixin): self.converters = {} def match(self, path): match = self.regex.search(path) if match: # If there are any named groups, use those as kwargs, ignoring # non-named groups. Otherwise, pass all non-named arguments as
class RegexPattern(CheckURLMixin): self.converters = {} def match(self, path): match = ( self.regex.fullmatch(path) if self._is_endpoint and self.regex.pattern.endswith('$') else self.regex.search(path) ) if match: # If there are any n...
def _route_to_regex(route, is_endpoint=False): converters[parameter] = converter parts.append('(?P<' + parameter + '>' + converter.regex + ')') if is_endpoint: parts.append('$') return ''.join(parts), converters
def _route_to_regex(route, is_endpoint=False): converters[parameter] = converter parts.append('(?P<' + parameter + '>' + converter.regex + ')') if is_endpoint: parts.append(r'\Z') return ''.join(parts), converters
class SimplifiedURLTests(SimpleTestCase): with self.assertRaisesMessage(ImproperlyConfigured, msg): path('foo/<nonexistent:var>/', empty_view) @override_settings(ROOT_URLCONF='urlpatterns.converter_urls') class ConverterTests(SimpleTestCase):
class SimplifiedURLTests(SimpleTestCase): with self.assertRaisesMessage(ImproperlyConfigured, msg): path('foo/<nonexistent:var>/', empty_view) def test_path_trailing_newlines(self): tests = [ '/articles/2003/\n', '/articles/2010/\n', '/en/foo/\n', ...
class MWorker(salt.utils.process.SignalHandlingMultiprocessingProcess): ''' log.trace('Clear payload received with command %s', load['cmd']) cmd = load['cmd'] if cmd.startswith('__'): return False if self.opts['master_stats']: start = time.time() ...
class MWorker(salt.utils.process.SignalHandlingMultiprocessingProcess): ''' log.trace('Clear payload received with command %s', load['cmd']) cmd = load['cmd'] method = self.clear_funcs.get_method(cmd) if not method: return {}, {'fun': 'send_clear'} if self.opt...
class MWorker(salt.utils.process.SignalHandlingMultiprocessingProcess): return {} cmd = data['cmd'] log.trace('AES payload received with command %s', data['cmd']) if cmd.startswith('__'): return False if self.opts['master_stats']: start = time.time() ...
class MWorker(salt.utils.process.SignalHandlingMultiprocessingProcess): return {} cmd = data['cmd'] log.trace('AES payload received with command %s', data['cmd']) method = self.aes_funcs.get_method(cmd) if not method: return {}, {'fun': 'send'} if self.opt...
class MWorker(salt.utils.process.SignalHandlingMultiprocessingProcess): self.__bind() # TODO: rename? No longer tied to "AES", just "encrypted" or "private" requests class AESFuncs(object): ''' Set up functions that are available when the load is encrypted with AES ''' # The AES Functions: ...
class MWorker(salt.utils.process.SignalHandlingMultiprocessingProcess): self.__bind() class TransportMethods(object): ''' Expose methods to the transport layer, methods with their names found in the class attribute 'expose_methods' will be exposed to the transport layer via 'get_method'. '...
class AESFuncs(object): return ret, {'fun': 'send'} class ClearFuncs(object): ''' Set up functions that are safe to execute when commands sent to the master without encryption and authentication ''' # The ClearFuncs object encapsulates the functions that can be executed in # the clear:...
class AESFuncs(object): return ret, {'fun': 'send'} class ClearFuncs(TransportMethods): ''' Set up functions that are safe to execute when commands sent to the master without encryption and authentication ''' # These methods will be exposed to the transport layer by # MWorker._handle_...
from tests.support.mock import ( ) class ClearFuncsTestCase(TestCase): ''' TestCase for salt.master.ClearFuncs class
from tests.support.mock import ( ) class TransportMethodsTest(TestCase): def test_transport_methods(self): class Foo(salt.master.TransportMethods): expose_methods = ['bar'] def bar(self): pass def bang(self): pass foo = Foo()...
class ClearFuncsTestCase(TestCase): opts = salt.config.master_config(None) self.clear_funcs = salt.master.ClearFuncs(opts, {}) # runner tests def test_runner_token_not_authenticated(self):
class ClearFuncsTestCase(TestCase): opts = salt.config.master_config(None) self.clear_funcs = salt.master.ClearFuncs(opts, {}) def tearDown(self): del self.clear_funcs def test_get_method(self): assert getattr(self.clear_funcs, '_send_pub', None) is not None assert self...
class HTTPRequest(HTTPMessage): ) headers = dict(self._orig.headers) if 'Host' not in headers: headers['Host'] = url.netloc.split('@')[-1] headers = ['%s: %s' % (name, value)
class HTTPRequest(HTTPMessage): ) headers = dict(self._orig.headers) if 'Host' not in self._orig.headers: headers['Host'] = url.netloc.split('@')[-1] headers = ['%s: %s' % (name, value)
class APIRouter(routing.Router): assert not prefix.endswith( "/" ), "A path prefix must not end with '/', as the routes will start with '/'" for route in router.routes: if isinstance(route, APIRoute): if responses is None: r...
class APIRouter(routing.Router): assert not prefix.endswith( "/" ), "A path prefix must not end with '/', as the routes will start with '/'" if responses is None: responses = {} for route in router.routes: if isinstance(route, APIRoute): ...
class APIRouter(routing.Router): summary=route.summary, description=route.description, response_description=route.response_description, responses=responses, deprecated=route.deprecated, methods=route....
class APIRouter(routing.Router): summary=route.summary, description=route.description, response_description=route.response_description, responses=combined_responses, deprecated=route.deprecated, metho...
from django.utils.text import normalize_newlines from .html_parser import HTMLParseError, HTMLParser # Configuration for urlize() function. TRAILING_PUNCTUATION_RE = re.compile( '^' # Beginning of word '(.*?)' # The URL in word '([.,:;!]+)' # Allowed non-wrapping, trailing punctuation ...
from django.utils.text import normalize_newlines from .html_parser import HTMLParseError, HTMLParser # Configuration for urlize() function. TRAILING_PUNCTUATION_CHARS = '.,:;!' WRAPPING_PUNCTUATION = [('(', ')'), ('<', '>'), ('[', ']'), ('&lt;', '&gt;'), ('"', '"'), ('\'', '\'')] # List of possible strings used for b...
unencoded_ampersands_re = re.compile(r'&(?!(\w+|#\d+);)') word_split_re = re.compile(r'''([\s<>"']+)''') simple_url_re = re.compile(r'^https?://\[?\w', re.IGNORECASE) simple_url_2_re = re.compile(r'^www\.|^(?!http)\w[^@]+\.(com|edu|gov|int|mil|net|org)($|/.*)$', re.IGNORECASE) simple_email_re = re.compile(r'^\S+@\S+\.\...
unencoded_ampersands_re = re.compile(r'&(?!(\w+|#\d+);)') word_split_re = re.compile(r'''([\s<>"']+)''') simple_url_re = re.compile(r'^https?://\[?\w', re.IGNORECASE) simple_url_2_re = re.compile(r'^www\.|^(?!http)\w[^@]+\.(com|edu|gov|int|mil|net|org)($|/.*)$', re.IGNORECASE) @keep_lazy(str, SafeText)
def urlize(text, trim_url_limit=None, nofollow=False, autoescape=False): trimmed_something = False # Trim trailing punctuation. match = TRAILING_PUNCTUATION_RE.match(middle) if match: middle = match.group(1) trail = match.group(2) + trail ...
def urlize(text, trim_url_limit=None, nofollow=False, autoescape=False): trimmed_something = False # Trim trailing punctuation. stripped = middle.rstrip(TRAILING_PUNCTUATION_CHARS) if middle != stripped: trail = middle[len(stripped):] + trail ...
def urlize(text, trim_url_limit=None, nofollow=False, autoescape=False): trimmed_something = True return lead, middle, trail words = word_split_re.split(force_text(text)) for i, word in enumerate(words): if '.' in word or '@' in word or ':' in word:
def urlize(text, trim_url_limit=None, nofollow=False, autoescape=False): trimmed_something = True return lead, middle, trail def is_email_simple(value): """Return True if value looks like an email address.""" # An @ must be in the middle of the value. if '@' not ...
def urlize(text, trim_url_limit=None, nofollow=False, autoescape=False): elif simple_url_2_re.match(middle): middle, middle_unescaped, trail = unescape(middle, trail) url = smart_urlquote('http://%s' % middle_unescaped) elif ':' not in middle and simple_email_re.m...
def urlize(text, trim_url_limit=None, nofollow=False, autoescape=False): elif simple_url_2_re.match(middle): middle, middle_unescaped, trail = unescape(middle, trail) url = smart_urlquote('http://%s' % middle_unescaped) elif ':' not in middle and is_email_simple(m...
from django.test import SimpleTestCase from django.utils.functional import lazystr from django.utils.html import ( conditional_escape, escape, escapejs, format_html, html_safe, linebreaks, smart_urlquote, strip_spaces_between_tags, strip_tags, ) from django.utils.safestring import mark_safe
from django.test import SimpleTestCase from django.utils.functional import lazystr from django.utils.html import ( conditional_escape, escape, escapejs, format_html, html_safe, linebreaks, smart_urlquote, strip_spaces_between_tags, strip_tags, urlize, ) from django.utils.safestring import mark_safe
class TestUtilsHtml(SimpleTestCase): @html_safe class HtmlClass: pass
class TestUtilsHtml(SimpleTestCase): @html_safe class HtmlClass: pass def test_urlize_unchanged_inputs(self): tests = ( ('a' + '@a' * 50000) + 'a', # simple_email_re catastrophic test ('a' + '.' * 1000000) + 'a', # trailing_punctuation catas...
# if greater than this, the number is in ms, if less than or equal it's in seconds # (in seconds this is 11th October 2603, in ms it's 20th August 1970) MS_WATERSHED = int(2e10) StrBytesIntFloat = Union[str, bytes, int, float]
# if greater than this, the number is in ms, if less than or equal it's in seconds # (in seconds this is 11th October 2603, in ms it's 20th August 1970) MS_WATERSHED = int(2e10) # slightly more than datetime.max in ns - (datetime.max - EPOCH).total_seconds() * 1e9 MAX_NUMBER = int(3e20) StrBytesIntFloat = Union[str, by...
def get_numeric(value: StrBytesIntFloat, native_expected_type: str) -> Union[Non def from_unix_seconds(seconds: Union[int, float]) -> datetime: while abs(seconds) > MS_WATERSHED: seconds /= 1000 dt = EPOCH + timedelta(seconds=seconds)
def get_numeric(value: StrBytesIntFloat, native_expected_type: str) -> Union[Non def from_unix_seconds(seconds: Union[int, float]) -> datetime: if seconds > MAX_NUMBER: return datetime.max elif seconds < -MAX_NUMBER: return datetime.min while abs(seconds) > MS_WATERSHED: seconds /...
def create_tz(minutes): (1_549_316_052_104, date(2019, 2, 4)), # nowish in ms (1_549_316_052_104_324, date(2019, 2, 4)), # nowish in μs (1_549_316_052_104_324_096, date(2019, 2, 4)), # nowish in ns ], ) def test_date_parsing(value, result): if result == errors.DateError: with ...
def create_tz(minutes): (1_549_316_052_104, date(2019, 2, 4)), # nowish in ms (1_549_316_052_104_324, date(2019, 2, 4)), # nowish in μs (1_549_316_052_104_324_096, date(2019, 2, 4)), # nowish in ns ('infinity', date(9999, 12, 31)), ('inf', date(9999, 12, 31)), (float('...
def test_time_parsing(value, result): (1_549_316_052_104, datetime(2019, 2, 4, 21, 34, 12, 104_000, tzinfo=timezone.utc)), # nowish in ms (1_549_316_052_104_324, datetime(2019, 2, 4, 21, 34, 12, 104_324, tzinfo=timezone.utc)), # nowish in μs (1_549_316_052_104_324_096, datetime(2019, 2, 4, 21,...
def test_time_parsing(value, result): (1_549_316_052_104, datetime(2019, 2, 4, 21, 34, 12, 104_000, tzinfo=timezone.utc)), # nowish in ms (1_549_316_052_104_324, datetime(2019, 2, 4, 21, 34, 12, 104_324, tzinfo=timezone.utc)), # nowish in μs (1_549_316_052_104_324_096, datetime(2019, 2, 4, 21,...
class Model(BaseModel): 'type': 'value_error.unicodedecode', 'msg': "'utf-8' codec can't decode byte 0x81 in position 0: invalid start byte", }
class Model(BaseModel): 'type': 'value_error.unicodedecode', 'msg': "'utf-8' codec can't decode byte 0x81 in position 0: invalid start byte", } def test_nan(): class Model(BaseModel): dt: datetime d: date with pytest.raises(ValidationError) as exc_info: Model(dt='n...
import numpy as np import time import json import warnings from collections import deque from collections import OrderedDict
import numpy as np import time import json import warnings import io import sys from collections import deque from collections import OrderedDict
class CSVLogger(Callback): self.writer = None self.keys = None self.append_header = True self.file_flags = 'b' if six.PY2 and os.name == 'nt' else '' super(CSVLogger, self).__init__() def on_train_begin(self, logs=None):
class CSVLogger(Callback): self.writer = None self.keys = None self.append_header = True if six.PY2: self.file_flags = 'b' self._open_args = {} else: self.file_flags = '' self._open_args = {'newline': '\n'} super(CSVLogger, ...
class CSVLogger(Callback): if os.path.exists(self.filename): with open(self.filename, 'r' + self.file_flags) as f: self.append_header = not bool(len(f.readline())) self.csv_file = open(self.filename, 'a' + self.file_flags) else: self.csv_fi...
class CSVLogger(Callback): if os.path.exists(self.filename): with open(self.filename, 'r' + self.file_flags) as f: self.append_header = not bool(len(f.readline())) mode = 'a' else: mode = 'w' self.csv_file = io.open(self.filename, ...
class CSVLogger(Callback): if not self.writer: class CustomDialect(csv.excel): delimiter = self.sep self.writer = csv.DictWriter(self.csv_file, fieldnames=['epoch'] + self.keys, dialect=CustomDialect) if self.append_he...
class CSVLogger(Callback): if not self.writer: class CustomDialect(csv.excel): delimiter = self.sep fieldnames = ['epoch'] + self.keys if six.PY2: fieldnames = [unicode(x) for x in fieldnames] self.writer = csv.DictWriter(self.csv_f...
def test_CSVLogger(tmpdir): # case 3, reuse of CSVLogger object model.fit(X_train, y_train, batch_size=batch_size, validation_data=(X_test, y_test), callbacks=cbks, epochs=1) import re with open(filepath) as csvfile: output = " ".join(csvfile.readlines()) assert len(re.fi...
def test_CSVLogger(tmpdir): # case 3, reuse of CSVLogger object model.fit(X_train, y_train, batch_size=batch_size, validation_data=(X_test, y_test), callbacks=cbks, epochs=2) import re with open(filepath) as csvfile: list_lines = csvfile.readlines() for line in list_lines...
class HTTPConnection(_HTTPConnection, object): conn = connection.create_connection( (self._dns_host, self.port), self.timeout, **extra_kw) except SocketTimeout as e: raise ConnectTimeoutError( self, "Connection to %s timed out. (connect timeout=%s)" % ...
class HTTPConnection(_HTTPConnection, object): conn = connection.create_connection( (self._dns_host, self.port), self.timeout, **extra_kw) except SocketTimeout: raise ConnectTimeoutError( self, "Connection to %s timed out. (connect timeout=%s)" % ...
class HTTPConnectionPool(ConnectionPool, RequestMethods): # released back to the pool once the entire response is read response.read() except (TimeoutError, HTTPException, SocketError, ProtocolError, BaseSSLError, SSLError) as e: pass ...
class HTTPConnectionPool(ConnectionPool, RequestMethods): # released back to the pool once the entire response is read response.read() except (TimeoutError, HTTPException, SocketError, ProtocolError, BaseSSLError, SSLError): pass #...
class WrappedSocket(object): return b'' else: raise SocketError(str(e)) except OpenSSL.SSL.ZeroReturnError as e: if self.connection.get_shutdown() == OpenSSL.SSL.RECEIVED_SHUTDOWN: return b'' else:
class WrappedSocket(object): return b'' else: raise SocketError(str(e)) except OpenSSL.SSL.ZeroReturnError: if self.connection.get_shutdown() == OpenSSL.SSL.RECEIVED_SHUTDOWN: return b'' else:
class WrappedSocket(object): return 0 else: raise SocketError(str(e)) except OpenSSL.SSL.ZeroReturnError as e: if self.connection.get_shutdown() == OpenSSL.SSL.RECEIVED_SHUTDOWN: return 0 else:
class WrappedSocket(object): return 0 else: raise SocketError(str(e)) except OpenSSL.SSL.ZeroReturnError: if self.connection.get_shutdown() == OpenSSL.SSL.RECEIVED_SHUTDOWN: return 0 else:
class SOCKSConnection(HTTPConnection): **extra_kw ) except SocketTimeout as e: raise ConnectTimeoutError( self, "Connection to %s timed out. (connect timeout=%s)" % (self.host, self.timeout))
class SOCKSConnection(HTTPConnection): **extra_kw ) except SocketTimeout: raise ConnectTimeoutError( self, "Connection to %s timed out. (connect timeout=%s)" % (self.host, self.timeout))
_key_fields = ( 'key__socks_options', # dict 'key_assert_hostname', # bool or string 'key_assert_fingerprint', # str 'key_server_hostname', #str ) #: The namedtuple class used to construct keys for the connection pool.
_key_fields = ( 'key__socks_options', # dict 'key_assert_hostname', # bool or string 'key_assert_fingerprint', # str 'key_server_hostname', # str ) #: The namedtuple class used to construct keys for the connection pool.
class HTTPResponse(io.IOBase): if content_encoding in self.CONTENT_DECODERS: self._decoder = _get_decoder(content_encoding) elif ',' in content_encoding: encodings = [e.strip() for e in content_encoding.split(',') if e.strip() in self.CONTENT_DECODERS] ...
class HTTPResponse(io.IOBase): if content_encoding in self.CONTENT_DECODERS: self._decoder = _get_decoder(content_encoding) elif ',' in content_encoding: encodings = [ e.strip() for e in content_encoding.split(',') if e.stri...
DEFAULT_CIPHERS = ':'.join([ try: from ssl import SSLContext # Modern SSL? except ImportError: import sys class SSLContext(object): # Platform-specific: Python 2 def __init__(self, protocol_version): self.protocol = protocol_version
DEFAULT_CIPHERS = ':'.join([ try: from ssl import SSLContext # Modern SSL? except ImportError: class SSLContext(object): # Platform-specific: Python 2 def __init__(self, protocol_version): self.protocol = protocol_version
from __future__ import absolute_import from collections import namedtuple from ..exceptions import LocationParseError
from __future__ import absolute_import from collections import namedtuple import re from ..exceptions import LocationParseError
url_attrs = ['scheme', 'auth', 'host', 'port', 'path', 'query', 'fragment'] # urllib3 infers URLs without a scheme (None) to be http. NORMALIZABLE_SCHEMES = ('http', 'https', None) class Url(namedtuple('Url', url_attrs)): """
url_attrs = ['scheme', 'auth', 'host', 'port', 'path', 'query', 'fragment'] # urllib3 infers URLs without a scheme (None) to be http. NORMALIZABLE_SCHEMES = ('http', 'https', None) _contains_disallowed_url_pchar_re = re.compile('[\x00-\x20\x7f]') class Url(namedtuple('Url', url_attrs)): """
def parse_url(url): # Empty return Url() scheme = None auth = None host = None
def parse_url(url): # Empty return Url() # Prevent CVE-2019-9740. # adapted from https://github.com/python/cpython/pull/12755 if _contains_disallowed_url_pchar_re.search(url): raise LocationParseError("URL can't contain control characters. {!r}".format(url)) scheme = None a...
import errno import functools import logging import socket import pytest
import errno import functools import logging import socket import ssl import os import pytest
def notSecureTransport(test): return wrapper _requires_network_has_route = None
def notSecureTransport(test): return wrapper def notOpenSSL098(test): """Skips this test for Python 3.4 and 3.5 macOS python.org distributions""" @functools.wraps(test) def wrapper(*args, **kwargs): is_stdlib_ssl = not ssl_.IS_SECURETRANSPORT and not ssl_.IS_PYOPENSSL if is_stdlib_ssl...
def requires_network(test): return wrapper class _ListHandler(logging.Handler): def __init__(self): super(_ListHandler, self).__init__()
def requires_network(test): return wrapper def fails_on_travis_gce(test): """Expect the test to fail on Google Compute Engine instances for Travis. Travis uses GCE for its sudo: enabled builds. Reason for this decorator: https://github.com/urllib3/urllib3/pull/1475#issuecomment-440788064 """ ...
class TestUtil(object): with pytest.raises(ValueError): parse_url('[::1') def test_Url_str(self): U = Url('http', host='google.com') assert str(U) == U.url
class TestUtil(object): with pytest.raises(ValueError): parse_url('[::1') def test_parse_url_contains_control_characters(self): # see CVE-2019-9740 with pytest.raises(LocationParseError): parse_url('http://localhost:8000/ HTTP/1.1\r\nHEADER: INJECTED\r\nIgnore:') ...
from dummyserver.server import (DEFAULT_CA, DEFAULT_CA_BAD, DEFAULT_CERTS, from test import ( onlyPy279OrNewer, notSecureTransport, requires_network, TARPIT_HOST, ) from urllib3 import HTTPSConnectionPool
from dummyserver.server import (DEFAULT_CA, DEFAULT_CA_BAD, DEFAULT_CERTS, from test import ( onlyPy279OrNewer, notSecureTransport, notOpenSSL098, requires_network, fails_on_travis_gce, TARPIT_HOST, ) from urllib3 import HTTPSConnectionPool
class TestHTTPS(HTTPSDummyServerTestCase): r = self._pool.request('GET', '/') self.assertEqual(r.status, 200, r.data) def test_dotted_fqdn(self): pool = HTTPSConnectionPool(self.host + '.', self.port) r = pool.request('GET', '/')
class TestHTTPS(HTTPSDummyServerTestCase): r = self._pool.request('GET', '/') self.assertEqual(r.status, 200, r.data) @fails_on_travis_gce def test_dotted_fqdn(self): pool = HTTPSConnectionPool(self.host + '.', self.port) r = pool.request('GET', '/')
class TestHTTPS(HTTPSDummyServerTestCase): @onlyPy279OrNewer @notSecureTransport # SecureTransport does not support cert directories def test_ca_dir_verified(self): https_pool = HTTPSConnectionPool(self.host, self.port, cert_reqs='CERT_REQUIRED',
class TestHTTPS(HTTPSDummyServerTestCase): @onlyPy279OrNewer @notSecureTransport # SecureTransport does not support cert directories @notOpenSSL098 # OpenSSL 0.9.8 does not support cert directories def test_ca_dir_verified(self): https_pool = HTTPSConnectionPool(self.host, self.port, ...
from urllib3.util.timeout import Timeout from urllib3.util.retry import Retry from urllib3._collections import HTTPHeaderDict from dummyserver.testcase import SocketDummyServerTestCase, consume_socket from dummyserver.server import ( DEFAULT_CERTS, DEFAULT_CA, COMBINED_CERT_AND_KEY, get_unreachable_address)
from urllib3.util.timeout import Timeout from urllib3.util.retry import Retry from urllib3._collections import HTTPHeaderDict from test import fails_on_travis_gce from dummyserver.testcase import SocketDummyServerTestCase, consume_socket from dummyserver.server import ( DEFAULT_CERTS, DEFAULT_CA, COMBINED_CERT_AND...
class TestHeaders(SocketDummyServerTestCase): pool.request('GET', '/', headers=OrderedDict(expected_request_headers)) self.assertEqual(expected_request_headers, actual_request_headers) def test_request_host_header_ignores_fqdn_dot(self): received_headers = []
class TestHeaders(SocketDummyServerTestCase): pool.request('GET', '/', headers=OrderedDict(expected_request_headers)) self.assertEqual(expected_request_headers, actual_request_headers) @fails_on_travis_gce def test_request_host_header_ignores_fqdn_dot(self): received_headers = []
def repercent_broken_unicode(path): we need to re-percent-encode any octet produced that is not part of a strictly legal UTF-8 octet sequence. """ try: path.decode('utf-8') except UnicodeDecodeError as e: repercent = quote(path[e.start:e.end], safe=b"/#%[]=:;$&()+,!?*@'~") pa...
def repercent_broken_unicode(path): we need to re-percent-encode any octet produced that is not part of a strictly legal UTF-8 octet sequence. """ while True: try: path.decode('utf-8') except UnicodeDecodeError as e: # CVE-2019-14235: A recursion shouldn't be used...
from __future__ import unicode_literals import datetime import unittest from django.utils import six from django.utils.encoding import ( escape_uri_path, filepath_to_uri, force_bytes, force_text, iri_to_uri, smart_text, uri_to_iri, ) from django.utils.functional import SimpleLazyObject from django.utils.http ...
from __future__ import unicode_literals import datetime import sys import unittest from django.utils import six from django.utils.encoding import ( escape_uri_path, filepath_to_uri, force_bytes, force_text, iri_to_uri, repercent_broken_unicode, smart_text, uri_to_iri, ) from django.utils.functional import Sim...
class TestEncodingUtils(unittest.TestCase): self.assertEqual(smart_text(1), '1') self.assertEqual(smart_text('foo'), 'foo') class TestRFC3987IEncodingUtils(unittest.TestCase):
class TestEncodingUtils(unittest.TestCase): self.assertEqual(smart_text(1), '1') self.assertEqual(smart_text('foo'), 'foo') def test_repercent_broken_unicode_recursion_error(self): # Prepare a string long enough to force a recursion error if the tested # function uses recursion. ...
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'...
def capfirst(x): # Set up regular expressions re_words = re.compile(r'<[^>]+?>|([^<>\s]+)', re.S) re_chars = re.compile(r'<[^>]+?>|(.)', 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'(((?<=[a-z])[A-Z])|...
class FunctionTests(SimpleTestCase): def test_truncate2(self): self.assertEqual( truncatewords_html('<p>one <a href="#">two - three <br>four</a> five</p>', 4), '<p>one <a href="#">two - three <br>four ...</a></p>', ) def test_truncate3(self): self.assertEqual( ...
class FunctionTests(SimpleTestCase): def test_truncate2(self): self.assertEqual( truncatewords_html('<p>one <a href="#">two - three <br>four</a> five</p>', 4), '<p>one <a href="#">two - three ...</a></p>', ) def test_truncate3(self): self.assertEqual( ...
class TestUtilsText(SimpleTestCase): # lazy strings are handled correctly self.assertEqual(text.Truncator(lazystr('The quick brown fox')).chars(12), 'The quick...') def test_truncate_words(self): truncator = text.Truncator('The quick brown fox jumped over the lazy dog.') self.assert...
class TestUtilsText(SimpleTestCase): # lazy strings are handled correctly self.assertEqual(text.Truncator(lazystr('The quick brown fox')).chars(12), 'The quick...') def test_truncate_chars_html(self): perf_test_values = [ (('</a' + '\t' * 50000) + '//>', None), ('&' ...
class TestUtilsText(SimpleTestCase): truncator = text.Truncator('<i>Buenos d&iacute;as! &#x00bf;C&oacute;mo est&aacute;?</i>') self.assertEqual('<i>Buenos d&iacute;as! &#x00bf;C&oacute;mo...</i>', truncator.words(3, '...', html=True)) truncator = text.Truncator('<p>I &lt;3 python, what about you...
class TestUtilsText(SimpleTestCase): truncator = text.Truncator('<i>Buenos d&iacute;as! &#x00bf;C&oacute;mo est&aacute;?</i>') self.assertEqual('<i>Buenos d&iacute;as! &#x00bf;C&oacute;mo...</i>', truncator.words(3, '...', html=True)) truncator = text.Truncator('<p>I &lt;3 python, what about you...
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)