buggy stringlengths 35 5.03k | fixed stringlengths 46 62.5k |
|---|---|
class GroupSelfAcceptInviteServlet(RestServlet):
PATTERNS = client_patterns("/groups/(?P<group_id>[^/]*)/self/accept_invite$")
def __init__(self, hs):
super().__init__()
self.auth = hs.get_auth()
self.clock = hs.get_clock()
self.groups_handler = hs.get_groups_local_handler()
... | class GroupSelfAcceptInviteServlet(RestServlet):
PATTERNS = client_patterns("/groups/(?P<group_id>[^/]*)/self/accept_invite$")
def __init__(self, hs: "HomeServer"):
super().__init__()
self.auth = hs.get_auth()
self.clock = hs.get_clock()
self.groups_handler = hs.get_groups_loca... |
class GroupSelfUpdatePublicityServlet(RestServlet):
PATTERNS = client_patterns("/groups/(?P<group_id>[^/]*)/self/update_publicity$")
def __init__(self, hs):
super().__init__()
self.auth = hs.get_auth()
self.clock = hs.get_clock()
self.store = hs.get_datastore()
@_validate_... | class GroupSelfUpdatePublicityServlet(RestServlet):
PATTERNS = client_patterns("/groups/(?P<group_id>[^/]*)/self/update_publicity$")
def __init__(self, hs: "HomeServer"):
super().__init__()
self.auth = hs.get_auth()
self.clock = hs.get_clock()
self.store = hs.get_datastore()
... |
class PublicisedGroupsForUserServlet(RestServlet):
PATTERNS = client_patterns("/publicised_groups/(?P<user_id>[^/]*)$")
def __init__(self, hs):
super().__init__()
self.auth = hs.get_auth()
self.clock = hs.get_clock()
self.store = hs.get_datastore()
self.groups_handler =... | class PublicisedGroupsForUserServlet(RestServlet):
PATTERNS = client_patterns("/publicised_groups/(?P<user_id>[^/]*)$")
def __init__(self, hs: "HomeServer"):
super().__init__()
self.auth = hs.get_auth()
self.clock = hs.get_clock()
self.store = hs.get_datastore()
self.gr... |
class PublicisedGroupsForUsersServlet(RestServlet):
PATTERNS = client_patterns("/publicised_groups$")
def __init__(self, hs):
super().__init__()
self.auth = hs.get_auth()
self.clock = hs.get_clock()
self.store = hs.get_datastore()
self.groups_handler = hs.get_groups_loc... | class PublicisedGroupsForUsersServlet(RestServlet):
PATTERNS = client_patterns("/publicised_groups$")
def __init__(self, hs: "HomeServer"):
super().__init__()
self.auth = hs.get_auth()
self.clock = hs.get_clock()
self.store = hs.get_datastore()
self.groups_handler = hs.... |
class GroupsForUserServlet(RestServlet):
PATTERNS = client_patterns("/joined_groups$")
def __init__(self, hs):
super().__init__()
self.auth = hs.get_auth()
self.clock = hs.get_clock()
self.groups_handler = hs.get_groups_local_handler()
async def on_GET(self, request):
... | class GroupsForUserServlet(RestServlet):
PATTERNS = client_patterns("/joined_groups$")
def __init__(self, hs: "HomeServer"):
super().__init__()
self.auth = hs.get_auth()
self.clock = hs.get_clock()
self.groups_handler = hs.get_groups_local_handler()
async def on_GET(self, ... |
async def on_GET(self, request):
return 200, result
def register_servlets(hs, http_server):
GroupServlet(hs).register(http_server)
GroupSummaryServlet(hs).register(http_server)
GroupInvitedUsersServlet(hs).register(http_server) | async def on_GET(self, request):
return 200, result
def register_servlets(hs: "HomeServer", http_server):
GroupServlet(hs).register(http_server)
GroupSummaryServlet(hs).register(http_server)
GroupInvitedUsersServlet(hs).register(http_server) |
async def on_POST(self, request):
body, ["client_secret", "country", "phone_number", "send_attempt"]
)
client_secret = body["client_secret"]
country = body["country"]
phone_number = body["phone_number"]
send_attempt = body["send_attempt"] | async def on_POST(self, request):
body, ["client_secret", "country", "phone_number", "send_attempt"]
)
client_secret = body["client_secret"]
assert_valid_client_secret(client_secret)
country = body["country"]
phone_number = body["phone_number"]
send_attempt = ... |
async def on_GET(self, request, medium):
sid = parse_string(request, "sid", required=True)
client_secret = parse_string(request, "client_secret", required=True)
token = parse_string(request, "token", required=True)
# Attempt to validate a 3PID session | async def on_GET(self, request, medium):
sid = parse_string(request, "sid", required=True)
client_secret = parse_string(request, "client_secret", required=True)
assert_valid_client_secret(client_secret)
token = parse_string(request, "token", required=True)
# Attempt to validate... |
import functools
import logging
import os
from typing import TYPE_CHECKING, Any, Callable, Dict, List, Optional, TypeVar, cast
import twisted.internet.base
import twisted.internet.tcp | import functools
import logging
import os
from typing import (
TYPE_CHECKING,
Any,
Callable,
Dict,
List,
Optional,
TypeVar,
Union,
cast,
)
import twisted.internet.base
import twisted.internet.tcp |
def get_user_directory_handler(self) -> UserDirectoryHandler:
return UserDirectoryHandler(self)
@cache_in_self
def get_groups_local_handler(self):
if self.config.worker_app:
return GroupsLocalWorkerHandler(self)
else: | def get_user_directory_handler(self) -> UserDirectoryHandler:
return UserDirectoryHandler(self)
@cache_in_self
def get_groups_local_handler(
self,
) -> Union[GroupsLocalWorkerHandler, GroupsLocalHandler]:
if self.config.worker_app:
return GroupsLocalWorkerHandler(self)
... |
_string_with_symbols = string.digits + string.ascii_letters + ".,;:^&*-_+=#~@"
# https://matrix.org/docs/spec/client_server/r0.6.0#post-matrix-client-r0-register-email-requesttoken
client_secret_regex = re.compile(r"^[0-9a-zA-Z\.\=\_\-]+$")
# https://matrix.org/docs/spec/client_server/r0.6.1#matrix-content-mxc-uris,
... | _string_with_symbols = string.digits + string.ascii_letters + ".,;:^&*-_+=#~@"
# https://matrix.org/docs/spec/client_server/r0.6.0#post-matrix-client-r0-register-email-requesttoken
CLIENT_SECRET_REGEX = re.compile(r"^[0-9a-zA-Z\.=_\-]+$")
# https://matrix.org/docs/spec/client_server/r0.6.1#matrix-content-mxc-uris,
# ... |
rand = random.SystemRandom()
def random_string(length):
return "".join(rand.choice(string.ascii_letters) for _ in range(length))
def random_string_with_symbols(length):
return "".join(rand.choice(_string_with_symbols) for _ in range(length))
def is_ascii(s):
if isinstance(s, bytes):
try:
... | rand = random.SystemRandom()
def random_string(length: int) -> str:
return "".join(rand.choice(string.ascii_letters) for _ in range(length))
def random_string_with_symbols(length: int) -> str:
return "".join(rand.choice(_string_with_symbols) for _ in range(length))
def is_ascii(s: bytes) -> bool:
try:... |
def from_bytes(
Raises:
ValueError: The provided byte string is not an ``openssh-key-v1``
key list or the declared key count is negative.
UserWarning: The check numbers in the decrypted private byte string
do not match (likely due to an incorrect passphra... | def from_bytes(
Raises:
ValueError: The provided byte string is not an ``openssh-key-v1``
key list, when the declared key count is negative, or when an
EOF is found while parsing the key.
UserWarning: The check numbers in the decrypted private byte strin... |
def from_bytes(
at the end of the decrypted private byte string are not as
expected.
"""
byte_stream = PascalStyleByteStream(byte_string)
header = byte_stream.read_from_format_instructions_dict(
cls.HEADER_FORMAT_INSTRUCTIONS_DICT
)
i... | def from_bytes(
at the end of the decrypted private byte string are not as
expected.
"""
try:
byte_stream = PascalStyleByteStream(byte_string)
header = byte_stream.read_from_format_instructions_dict(
cls.HEADER_FORMAT_INSTRUCTIONS_... |
Various other classes in this module support this usage:
from __future__ import division, absolute_import
__metaclass__ = type
from zope.interface import implementer
from twisted.python.compat import networkString | Various other classes in this module support this usage:
from __future__ import division, absolute_import
__metaclass__ = type
import re
from zope.interface import implementer
from twisted.python.compat import networkString |
class HTTPClientParser(HTTPParser):
@implementer(IClientRequest)
class Request:
""" | class HTTPClientParser(HTTPParser):
_VALID_METHOD = re.compile(
br"\A[%s]+\Z" % (
bytes().join(
(
b"!", b"#", b"$", b"%", b"&", b"'", b"*",
b"+", b"-", b".", b"^", b"_", b"`", b"|", b"~",
b"\x30-\x39",
b"\x41-\x5a",
... |
class Request:
connection, defaults to C{False}.
@type persistent: L{bool}
"""
self.method = method
self.uri = uri
self.headers = headers
self.bodyProducer = bodyProducer
self.persistent = persistent | class Request:
connection, defaults to C{False}.
@type persistent: L{bool}
"""
self.method = _ensureValidMethod(method)
self.uri = _ensureValidURI(uri)
self.headers = headers
self.bodyProducer = bodyProducer
self.persistent = persistent |
class Request:
# method would probably be good. It would be nice if this method
# weren't limited to issuing HTTP/1.1 requests.
requestLines = []
requestLines.append(b' '.join([self.method, self.uri,
b'HTTP/1.1\r\n']))
if not self.persistent:
requestLines... | class Request:
# method would probably be good. It would be nice if this method
# weren't limited to issuing HTTP/1.1 requests.
requestLines = []
requestLines.append(
b' '.join(
[
_ensureValidMethod(self.method),
_ensur... |
from twisted.web.iweb import UNKNOWN_LENGTH, IAgent, IBodyProducer, IResponse
from twisted.web.http_headers import Headers
from twisted.logger import Logger
class PartialDownloadError(error.Error):
""" | from twisted.web.iweb import UNKNOWN_LENGTH, IAgent, IBodyProducer, IResponse
from twisted.web.http_headers import Headers
from twisted.logger import Logger
from twisted.web._newclient import _ensureValidURI, _ensureValidMethod
class PartialDownloadError(error.Error):
""" |
class HTTPPageGetter(http.HTTPClient):
_completelyDone = True
_specialHeaders = set((b'host', b'user-agent', b'cookie', b'content-length'))
def connectionMade(self):
method = getattr(self.factory, 'method', b'GET')
self.sendCommand(method, self.factory.path)
if self.factory.scheme... | class HTTPPageGetter(http.HTTPClient):
_completelyDone = True
_specialHeaders = set(
(b'host', b'user-agent', b'cookie', b'content-length'),
)
def connectionMade(self):
method = _ensureValidMethod(getattr(self.factory, 'method', b'GET'))
self.sendCommand(method, _ensureValidUR... |
class HTTPClientFactory(protocol.ClientFactory):
# just in case a broken http/1.1 decides to keep connection alive
self.headers.setdefault(b"connection", b"close")
self.postdata = postdata
self.method = method
self.setURL(url)
| class HTTPClientFactory(protocol.ClientFactory):
# just in case a broken http/1.1 decides to keep connection alive
self.headers.setdefault(b"connection", b"close")
self.postdata = postdata
self.method = _ensureValidMethod(method)
self.setURL(url)
|
class HTTPClientFactory(protocol.ClientFactory):
return "<%s: %s>" % (self.__class__.__name__, self.url)
def setURL(self, url):
self.url = url
uri = URI.fromBytes(url)
if uri.scheme and uri.host: | class HTTPClientFactory(protocol.ClientFactory):
return "<%s: %s>" % (self.__class__.__name__, self.url)
def setURL(self, url):
_ensureValidURI(url.strip())
self.url = url
uri = URI.fromBytes(url)
if uri.scheme and uri.host: |
def _makeGetterFactory(url, factoryFactory, contextFactory=None,
@return: The factory created by C{factoryFactory}
"""
uri = URI.fromBytes(url)
factory = factoryFactory(url, *args, **kwargs)
if uri.scheme == b'https':
from twisted.internet import ssl | def _makeGetterFactory(url, factoryFactory, contextFactory=None,
@return: The factory created by C{factoryFactory}
"""
uri = URI.fromBytes(_ensureValidURI(url.strip()))
factory = factoryFactory(url, *args, **kwargs)
if uri.scheme == b'https':
from twisted.internet import ssl |
class _AgentBase(object):
Issue a new request, given the endpoint and the path sent as part of
the request.
"""
# Create minimal headers, if necessary:
if headers is None:
headers = Headers() | class _AgentBase(object):
Issue a new request, given the endpoint and the path sent as part of
the request.
"""
method = _ensureValidMethod(method)
# Create minimal headers, if necessary:
if headers is None:
headers = Headers() |
class Agent(_AgentBase):
@see: L{twisted.web.iweb.IAgent.request}
"""
parsedURI = URI.fromBytes(uri)
try:
endpoint = self._getEndpoint(parsedURI) | class Agent(_AgentBase):
@see: L{twisted.web.iweb.IAgent.request}
"""
uri = _ensureValidURI(uri.strip())
parsedURI = URI.fromBytes(uri)
try:
endpoint = self._getEndpoint(parsedURI) |
class ProxyAgent(_AgentBase):
"""
Issue a new request via the configured proxy.
"""
# Cache *all* connections under the same key, since we are only
# connecting to a single destination, the proxy:
key = ("http-proxy", self._proxyEndpoint) | class ProxyAgent(_AgentBase):
"""
Issue a new request via the configured proxy.
"""
uri = _ensureValidURI(uri.strip())
# Cache *all* connections under the same key, since we are only
# connecting to a single destination, the proxy:
key = ("http-proxy", self._prox... |
from io import BytesIO
from zope.interface.verify import verifyObject
from twisted.trial.unittest import TestCase
from twisted.web import client, error, http_headers
from twisted.web._newclient import RequestNotSent, RequestTransmissionFailed
from twisted.web._newclient import ResponseNeverReceived, ResponseFailed | from io import BytesIO
from zope.interface.verify import verifyObject
from twisted.trial.unittest import TestCase, SynchronousTestCase
from twisted.web import client, error, http_headers
from twisted.web._newclient import RequestNotSent, RequestTransmissionFailed
from twisted.web._newclient import ResponseNeverReceiv... |
from twisted.internet.endpoints import HostnameEndpoint
from twisted.test.proto_helpers import AccumulatingProtocol
from twisted.test.iosim import IOPump, FakeTransport
from twisted.test.test_sslverify import certificatesForAuthorityAndServer
from twisted.web.error import SchemeNotSupported
from twisted.logger import g... | from twisted.internet.endpoints import HostnameEndpoint
from twisted.test.proto_helpers import AccumulatingProtocol
from twisted.test.iosim import IOPump, FakeTransport
from twisted.test.test_sslverify import certificatesForAuthorityAndServer
from twisted.web.test.injectionhelpers import (
MethodInjectionTestsMixin... |
class AgentTests(TestCase, FakeReactorAndConnectMixin, AgentTestsMixin,
"""
Tests for the new HTTP client API provided by L{Agent}.
"""
def makeAgent(self):
"""
@return: a new L{twisted.web.client.Agent} instance | class AgentTests(TestCase, FakeReactorAndConnectMixin, AgentTestsMixin,
"""
Tests for the new HTTP client API provided by L{Agent}.
"""
def makeAgent(self):
"""
@return: a new L{twisted.web.client.Agent} instance |
class AgentTests(TestCase, FakeReactorAndConnectMixin, AgentTestsMixin,
class AgentHTTPSTests(TestCase, FakeReactorAndConnectMixin,
IntegrationTestingMixin):
""" | class AgentTests(TestCase, FakeReactorAndConnectMixin, AgentTestsMixin,
class AgentMethodInjectionTests(
FakeReactorAndConnectMixin,
MethodInjectionTestsMixin,
SynchronousTestCase,
):
"""
Test L{client.Agent} against HTTP method injections.
"""
def attemptRequestWithMalicious... |
class HostnameCachingHTTPSPolicyTests(TestCase):
self.assertEquals(5, len(policy._cache))
self.assertIn(hostn, policy._cache) | class HostnameCachingHTTPSPolicyTests(TestCase):
self.assertEquals(5, len(policy._cache))
self.assertIn(hostn, policy._cache)
class RequestMethodInjectionTests(
MethodInjectionTestsMixin,
SynchronousTestCase,
):
"""
Test L{client.Request} against HTTP method injections.
"... |
Tests for the old L{twisted.web.client} APIs, C{getPage} and friends.
from __future__ import division, absolute_import
import os
from errno import ENOSPC
| Tests for the old L{twisted.web.client} APIs, C{getPage} and friends.
from __future__ import division, absolute_import
import io
import os
from errno import ENOSPC
|
from twisted.trial import unittest, util
from twisted.web import server, client, error, resource
from twisted.web.static import Data
from twisted.web.util import Redirect
from twisted.internet import reactor, defer, interfaces
from twisted.python.filepath import FilePath
from twisted.protocols.policies import WrappingF... | from twisted.trial import unittest, util
from twisted.web import server, client, error, resource
from twisted.web.static import Data
from twisted.web.util import Redirect
from twisted.internet import address, reactor, defer, interfaces
from twisted.internet.protocol import ClientFactory
from twisted.python.filepath imp... |
from twisted import test
from twisted.logger import (globalLogPublisher, FilteringLogObserver,
LogLevelFilterPredicate, LogLevel, Logger)
serverPEM = FilePath(test.__file__).sibling('server.pem')
serverPEMPath = serverPEM.asBytesMode().path | from twisted import test
from twisted.logger import (globalLogPublisher, FilteringLogObserver,
LogLevelFilterPredicate, LogLevel, Logger)
from twisted.web.test.injectionhelpers import (
MethodInjectionTestsMixin,
URIInjectionTestsMixin,
)
serverPEM = FilePath(test.__file__).sibli... |
class DeprecationTests(unittest.TestCase):
L{client.HTTPDownloader} is deprecated.
"""
self._testDeprecatedClass("HTTPDownloader") | class DeprecationTests(unittest.TestCase):
L{client.HTTPDownloader} is deprecated.
"""
self._testDeprecatedClass("HTTPDownloader")
class GetPageMethodInjectionTests(
MethodInjectionTestsMixin,
unittest.SynchronousTestCase,
):
"""
Test L{client.getPage} against HTTP met... |
class TimedeltaIndex(
this, other = self, other
if this._can_fast_union(other):
return this._fast_union(other)
else:
result = Index._union(this, other, sort=sort)
if isinstance(result, TimedeltaIndex): | class TimedeltaIndex(
this, other = self, other
if this._can_fast_union(other):
return this._fast_union(other, sort=sort)
else:
result = Index._union(this, other, sort=sort)
if isinstance(result, TimedeltaIndex): |
class TimedeltaIndex(
result._set_freq("infer")
return result
def _fast_union(self, other):
if len(other) == 0:
return self.view(type(self))
| class TimedeltaIndex(
result._set_freq("infer")
return result
def _fast_union(self, other, sort=None):
if len(other) == 0:
return self.view(type(self))
|
class TimedeltaIndex(
# to make our life easier, "sort" the two ranges
if self[0] <= other[0]:
left, right = self, other
else:
left, right = other, self
| class TimedeltaIndex(
# to make our life easier, "sort" the two ranges
if self[0] <= other[0]:
left, right = self, other
elif sort is False:
# TDIs are not in the "correct" order and we don't want
# to sort but want to remove overlaps
left, right ... |
class TestTimedeltaIndex:
i1.union(i2) # Works
i2.union(i1) # Fails with "AttributeError: can't set attribute"
def test_union_coverage(self):
idx = TimedeltaIndex(["3d", "1d", "2d"]) | class TestTimedeltaIndex:
i1.union(i2) # Works
i2.union(i1) # Fails with "AttributeError: can't set attribute"
def test_union_sort_false(self):
tdi = timedelta_range("1day", periods=5)
left = tdi[3:]
right = tdi[:3]
# Check that we are testing the desired code pa... |
def _clone_functional_model(model, input_tensors=None):
kwargs['mask'] = computed_mask
output_tensors = to_list(
layer(computed_tensor, **kwargs))
output_masks = to_list(
layer.compute_mask(computed_tenso... | def _clone_functional_model(model, input_tensors=None):
kwargs['mask'] = computed_mask
output_tensors = to_list(
layer(computed_tensor, **kwargs))
if layer.supports_masking:
output_masks = to_list(
... |
def _clone_functional_model(model, input_tensors=None):
kwargs['mask'] = computed_masks
output_tensors = to_list(
layer(computed_tensors, **kwargs))
output_masks = to_list(
layer.compute_mask(computed_ten... | def _clone_functional_model(model, input_tensors=None):
kwargs['mask'] = computed_masks
output_tensors = to_list(
layer(computed_tensors, **kwargs))
if layer.supports_masking:
output_masks = to_list(
... |
def test_clone_functional_model():
new_model.train_on_batch(None, val_out)
def test_clone_sequential_model():
val_a = np.random.random((10, 4))
val_out = np.random.random((10, 4)) | def test_clone_functional_model():
new_model.train_on_batch(None, val_out)
def test_clone_functional_model_with_multi_outputs():
input_layer = keras.Input(shape=(4,))
# Layer with single input and multiple outputs
layer1 = keras.layers.Lambda(lambda x: [x + 1, x],
lam... |
def load_model_from_path(model_path, meta=False, **overrides):
for name in pipeline:
if name not in disable:
config = meta.get("pipeline_args", {}).get(name, {})
factory = factories.get(name, name)
component = nlp.create_pipe(factory, config=config)
nlp.add_pi... | def load_model_from_path(model_path, meta=False, **overrides):
for name in pipeline:
if name not in disable:
config = meta.get("pipeline_args", {}).get(name, {})
config.update(overrides)
factory = factories.get(name, name)
component = nlp.create_pipe(factory, ... |
def generate_commands(vlan_id, to_set, to_remove):
if "vlan_id" in to_remove:
return ["no vlan {0}".format(vlan_id)]
for key, value in to_set.items():
if key == "vlan_id" or value is None:
continue
commands.append("{0} {1}".format(key, value))
for key in to_remove:
... | def generate_commands(vlan_id, to_set, to_remove):
if "vlan_id" in to_remove:
return ["no vlan {0}".format(vlan_id)]
for key in to_remove:
if key in to_set.keys():
continue
commands.append("no {0}".format(key))
for key, value in to_set.items():
if key == "vlan_i... |
class TestEosVlansModule(TestEosModule):
self.execute_show_command.return_value = []
set_module_args(dict(
config=[dict(
vlan_id=30,
name="thirty",
state="suspend"
)], state="replaced"
))
commands = ['vlan 30', 'name... | class TestEosVlansModule(TestEosModule):
self.execute_show_command.return_value = []
set_module_args(dict(
config=[dict(
vlan_id=10,
name="tenreplaced",
state="suspend"
)], state="replaced"
))
commands = ['vlan 10', ... |
class _AxesBase(martist.Artist):
if right is None:
right = old_right
if self.get_xscale() == 'log':
if left <= 0:
cbook._warn_external(
'Attempted to set non-positive left xlim on a ' | class _AxesBase(martist.Artist):
if right is None:
right = old_right
if self.get_xscale() == 'log' and (left <= 0 or right <= 0):
# Axes init calls set_xlim(0, 1) before get_xlim() can be called,
# so only grab the limits if we really need them.
o... |
def test_log_scales():
ax.set_xscale('log', basex=9.0)
@image_comparison(['stackplot_test_image', 'stackplot_test_image'])
def test_stackplot():
fig = plt.figure() | def test_log_scales():
ax.set_xscale('log', basex=9.0)
def test_log_scales_invalid():
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
ax.set_xscale('log')
with pytest.warns(UserWarning, match='Attempted to set non-positive'):
ax.set_xlim(-1, 10)
@image_comparison(['stackplot_test_image'... |
class NDFrame(PandasObject, SelectionMixin):
data = self.fillna(method=fill_method, limit=limit, axis=axis)
rs = data.div(data.shift(periods=periods, freq=freq, axis=axis, **kwargs)) - 1
rs = rs.loc[~rs.index.duplicated()]
rs = rs.reindex_like(data)
if freq is None:
... | class NDFrame(PandasObject, SelectionMixin):
data = self.fillna(method=fill_method, limit=limit, axis=axis)
rs = data.div(data.shift(periods=periods, freq=freq, axis=axis, **kwargs)) - 1
if freq is not None:
# Shift method is implemented differently when freq is not None
... |
class TestDataFramePctChange:
rs_freq = empty_ts.pct_change(freq=freq, fill_method=fill_method, limit=limit)
rs_periods = empty_ts.pct_change(periods, fill_method=fill_method, limit=limit)
tm.assert_frame_equal(rs_freq, rs_periods) | class TestDataFramePctChange:
rs_freq = empty_ts.pct_change(freq=freq, fill_method=fill_method, limit=limit)
rs_periods = empty_ts.pct_change(periods, fill_method=fill_method, limit=limit)
tm.assert_frame_equal(rs_freq, rs_periods)
@pytest.mark.parametrize("fill_method", ["pad", "ffill", None]... |
class TestSeriesPctChange:
rs_freq = empty_ts.pct_change(freq=freq, fill_method=fill_method, limit=limit)
rs_periods = empty_ts.pct_change(periods, fill_method=fill_method, limit=limit)
tm.assert_series_equal(rs_freq, rs_periods) | class TestSeriesPctChange:
rs_freq = empty_ts.pct_change(freq=freq, fill_method=fill_method, limit=limit)
rs_periods = empty_ts.pct_change(periods, fill_method=fill_method, limit=limit)
tm.assert_series_equal(rs_freq, rs_periods)
@pytest.mark.parametrize("fill_method", ["pad", "ffill", None])
... |
r"""{% if request %} at {{ request.path_info|escape }}{% endif %}</title>
<h2>Traceback <span class="commands">{% if not is_email %}<a href="#" onclick="return switchPastebinFriendly(this);">
Switch to copy-and-paste view</a></span>{% endif %}
</h2>
{% autoescape off %}
<div id="browserTraceback">
<ul c... | r"""{% if request %} at {{ request.path_info|escape }}{% endif %}</title>
<h2>Traceback <span class="commands">{% if not is_email %}<a href="#" onclick="return switchPastebinFriendly(this);">
Switch to copy-and-paste view</a></span>{% endif %}
</h2>
<div id="browserTraceback">
<ul class="traceback">
... |
r"""{% if request %} at {{ request.path_info|escape }}{% endif %}</title>
<tbody>
{% for var in frame.vars|dictsort:0 %}
<tr>
<td>{{ var.0|force_escape }}</td>
<td class="code"><pre>{{ var.1 }}</pre></td>
</tr>
... | r"""{% if request %} at {{ request.path_info|escape }}{% endif %}</title>
<tbody>
{% for var in frame.vars|dictsort:0 %}
<tr>
<td>{{ var.0 }}</td>
<td class="code"><pre>{{ var.1 }}</pre></td>
</tr>
... |
r"""{% if request %} at {{ request.path_info|escape }}{% endif %}</title>
{% endfor %}
</ul>
</div>
{% endautoescape %}
<form action="http://dpaste.com/" name="pasteform" id="pasteform" method="post">
{% if not is_email %}
<div id="pastebinTraceback" class="pastebin"> | r"""{% if request %} at {{ request.path_info|escape }}{% endif %}</title>
{% endfor %}
</ul>
</div>
<form action="http://dpaste.com/" name="pasteform" id="pasteform" method="post">
{% if not is_email %}
<div id="pastebinTraceback" class="pastebin"> |
In template {{ template_info.name }}, error at line {{ template_info.line }}
Traceback:{% for frame in frames %}
{% ifchanged frame.exc_cause %}{% if frame.exc_cause %}{% if frame.exc_cause_explicit %}
The above exception ({{ frame.exc_cause }}) was the direct cause of the following exception:
{% else %}
During handli... | In template {{ template_info.name }}, error at line {{ template_info.line }}
Traceback:{% for frame in frames %}
{% ifchanged frame.exc_cause %}{% if frame.exc_cause %}{% if frame.exc_cause_explicit %}
The above exception ({{ frame.exc_cause|force_escape }}) was the direct cause of the following exception:
{% else %}
... |
error (raise ... from ...) can't be silenced using NOQA.
import sys
from django.test import RequestFactory, TestCase
from django.views.debug import ExceptionReporter
| error (raise ... from ...) can't be silenced using NOQA.
import sys
from django.test import RequestFactory, TestCase
from django.utils.safestring import mark_safe
from django.views.debug import ExceptionReporter
|
class Py3ExceptionReporterTests(TestCase):
request = self.rf.get('/test_view/')
try:
try:
raise AttributeError('Top level')
except AttributeError as explicit:
try:
raise ValueError('Second exception') from explicit
... | class Py3ExceptionReporterTests(TestCase):
request = self.rf.get('/test_view/')
try:
try:
raise AttributeError(mark_safe('<p>Top level</p>'))
except AttributeError as explicit:
try:
raise ValueError('<p>Second exception</p>') fr... |
class Py3ExceptionReporterTests(TestCase):
html = reporter.get_traceback_html()
# Both messages are twice on page -- one rendered as html,
# one as plain text (for pastebin)
self.assertEqual(2, html.count(explicit_exc.format("Top level")))
self.assertEqual(2, html.count(implicit_... | class Py3ExceptionReporterTests(TestCase):
html = reporter.get_traceback_html()
# Both messages are twice on page -- one rendered as html,
# one as plain text (for pastebin)
self.assertEqual(2, html.count(explicit_exc.format('<p>Top level</p>')))
self.assertEqual(2, h... |
def __init__(self,
ValueError: if `input_signature` is not None and the `python_function`'s
argspec has keyword arguments.
"""
self._lock = threading.Lock()
self._python_function = python_function
self._function_spec = function_lib.FunctionSpec.from_function_and_signature(
python_f... | def __init__(self,
ValueError: if `input_signature` is not None and the `python_function`'s
argspec has keyword arguments.
"""
self._lock = threading.RLock()
self._python_function = python_function
self._function_spec = function_lib.FunctionSpec.from_function_and_signature(
python_... |
def __getstate__(self):
def __setstate__(self, state):
"""Restore from pickled state."""
self.__dict__ = state
self._lock = threading.Lock()
self._descriptor_cache = weakref.WeakKeyDictionary()
self._key_for_call_stats = self._get_key_for_call_stats()
| def __getstate__(self):
def __setstate__(self, state):
"""Restore from pickled state."""
self.__dict__ = state
self._lock = threading.RLock()
self._descriptor_cache = weakref.WeakKeyDictionary()
self._key_for_call_stats = self._get_key_for_call_stats()
|
from six.moves import range
from tensorflow.python.autograph.core import converter
from tensorflow.python.eager import def_function
from tensorflow.python.eager import lift_to_graph
from tensorflow.python.framework import constant_op | from six.moves import range
from tensorflow.python.autograph.core import converter
from tensorflow.python.eager import backprop
from tensorflow.python.eager import def_function
from tensorflow.python.eager import lift_to_graph
from tensorflow.python.framework import constant_op |
from tensorflow.python.framework import test_util
from tensorflow.python.module import module
from tensorflow.python.ops import array_ops
from tensorflow.python.ops import control_flow_ops
from tensorflow.python.ops import math_ops
from tensorflow.python.ops import random_ops | from tensorflow.python.framework import test_util
from tensorflow.python.module import module
from tensorflow.python.ops import array_ops
from tensorflow.python.ops import cond_v2
from tensorflow.python.ops import control_flow_ops
from tensorflow.python.ops import math_ops
from tensorflow.python.ops import random_ops |
def testDouble(self, a):
self.assertAllEqual(obj2.testDouble.experimental_get_tracing_count(), 3)
self.assertAllEqual(obj1.testDouble.experimental_get_tracing_count(), 2)
if __name__ == '__main__':
ops.enable_eager_execution() | def testDouble(self, a):
self.assertAllEqual(obj2.testDouble.experimental_get_tracing_count(), 3)
self.assertAllEqual(obj1.testDouble.experimental_get_tracing_count(), 2)
def test_recursive_tf_function(self):
@def_function.function
def recursive_fn(n):
if n > 0:
return recursive_fn(n -... |
def __init__(self,
if self.input_signature is not None:
self._hashable_input_signature = hash(self.flat_input_signature)
self._lock = threading.Lock()
# _descriptor_cache is a of instance of a class to an instance-specific
# `Function`, used to make sure defun-decorated methods create different
... | def __init__(self,
if self.input_signature is not None:
self._hashable_input_signature = hash(self.flat_input_signature)
self._lock = threading.RLock()
# _descriptor_cache is a of instance of a class to an instance-specific
# `Function`, used to make sure defun-decorated methods create different
... |
import asyncio
import enum
import inspect
import json | import asyncio
import email.message
import enum
import inspect
import json |
)
from pydantic import BaseModel
from pydantic.error_wrappers import ErrorWrapper, ValidationError
from pydantic.fields import ModelField
from starlette import routing
from starlette.concurrency import run_in_threadpool
from starlette.exceptions import HTTPException | )
from pydantic import BaseModel
from pydantic.error_wrappers import ErrorWrapper, ValidationError
from pydantic.fields import ModelField, Undefined
from starlette import routing
from starlette.concurrency import run_in_threadpool
from starlette.exceptions import HTTPException |
def get_request_handler(
async def app(request: Request) -> Response:
try:
body = None
if body_field:
if is_body_form:
body = await request.form()
else:
body_bytes = await request.body()
if b... | def get_request_handler(
async def app(request: Request) -> Response:
try:
body: Any = None
if body_field:
if is_body_form:
body = await request.form()
else:
body_bytes = await request.body()
... |
def test_post_body(path, body, expected_status, expected_response):
def test_post_broken_body():
response = client.post("/items/", data={"name": "Foo", "price": 50.5})
assert response.status_code == 422, response.text
assert response.json() == {
"detail": [
{
"ctx": {
... | def test_post_body(path, body, expected_status, expected_response):
def test_post_broken_body():
response = client.post(
"/items/",
headers={"content-type": "application/json"},
data="{some broken json}",
)
assert response.status_code == 422, response.text
assert response.json(... |
def test_gzip_request(compress):
if compress:
data = gzip.compress(data)
headers["Content-Encoding"] = "gzip"
response = client.post("/sum", data=data, headers=headers)
assert response.json() == {"sum": n}
| def test_gzip_request(compress):
if compress:
data = gzip.compress(data)
headers["Content-Encoding"] = "gzip"
headers["Content-Type"] = "application/json"
response = client.post("/sum", data=data, headers=headers)
assert response.json() == {"sum": n}
|
def _read_file(filename):
package_dir={'': 'src'},
python_requires='>= 3.6',
install_requires=[
'AccessControl >= 4.2',
'Acquisition',
'BTrees',
'Chameleon >= 3.7.0', | def _read_file(filename):
package_dir={'': 'src'},
python_requires='>= 3.6',
install_requires=[
'AccessControl >= 5.2',
'Acquisition',
'BTrees',
'Chameleon >= 3.7.0', |
from blib2to3 import pygram, pytree
from blib2to3.pgen2 import driver, token
from blib2to3.pgen2.grammar import Grammar
from blib2to3.pgen2.parse import ParseError
__version__ = "19.3b0" | from blib2to3 import pygram, pytree
from blib2to3.pgen2 import driver, token
from blib2to3.pgen2.grammar import Grammar
from blib2to3.pgen2.parse import ParseError
from blib2to3.pgen2.tokenize import TokenizerConfig
__version__ = "19.3b0" |
class Feature(Enum):
NUMERIC_UNDERSCORES = 3
TRAILING_COMMA_IN_CALL = 4
TRAILING_COMMA_IN_DEF = 5
VERSION_TO_FEATURES: Dict[TargetVersion, Set[Feature]] = {
TargetVersion.PY27: set(),
TargetVersion.PY33: {Feature.UNICODE_LITERALS},
TargetVersion.PY34: {Feature.UNICODE_LITERALS},
TargetVers... | class Feature(Enum):
NUMERIC_UNDERSCORES = 3
TRAILING_COMMA_IN_CALL = 4
TRAILING_COMMA_IN_DEF = 5
# The following two feature-flags are mutually exclusive, and exactly one should be
# set for every version of python.
ASYNC_IS_VALID_IDENTIFIER = 6
ASYNC_IS_RESERVED_KEYWORD = 7
VERSION_TO_FE... |
VERSION_TO_FEATURES: Dict[TargetVersion, Set[Feature]] = {
Feature.NUMERIC_UNDERSCORES,
Feature.TRAILING_COMMA_IN_CALL,
Feature.TRAILING_COMMA_IN_DEF,
},
TargetVersion.PY38: {
Feature.UNICODE_LITERALS, | VERSION_TO_FEATURES: Dict[TargetVersion, Set[Feature]] = {
Feature.NUMERIC_UNDERSCORES,
Feature.TRAILING_COMMA_IN_CALL,
Feature.TRAILING_COMMA_IN_DEF,
Feature.ASYNC_IS_RESERVED_KEYWORD,
},
TargetVersion.PY38: {
Feature.UNICODE_LITERALS, |
VERSION_TO_FEATURES: Dict[TargetVersion, Set[Feature]] = {
Feature.NUMERIC_UNDERSCORES,
Feature.TRAILING_COMMA_IN_CALL,
Feature.TRAILING_COMMA_IN_DEF,
},
}
| VERSION_TO_FEATURES: Dict[TargetVersion, Set[Feature]] = {
Feature.NUMERIC_UNDERSCORES,
Feature.TRAILING_COMMA_IN_CALL,
Feature.TRAILING_COMMA_IN_DEF,
Feature.ASYNC_IS_RESERVED_KEYWORD,
},
}
|
def decode_bytes(src: bytes) -> Tuple[FileContent, Encoding, NewLine]:
return tiow.read(), encoding, newline
def get_grammars(target_versions: Set[TargetVersion]) -> List[Grammar]:
if not target_versions:
# No target_version specified, so try all grammars.
return [
pygram.pytho... | def decode_bytes(src: bytes) -> Tuple[FileContent, Encoding, NewLine]:
return tiow.read(), encoding, newline
@dataclass(frozen=True)
class ParserConfig:
grammar: Grammar
tokenizer_config: TokenizerConfig = TokenizerConfig()
def get_parser_configs(target_versions: Set[TargetVersion]) -> List[ParserCo... |
def lib2to3_parse(src_txt: str, target_versions: Iterable[TargetVersion] = ()) -
if src_txt[-1:] != "\n":
src_txt += "\n"
for grammar in get_grammars(set(target_versions)):
drv = driver.Driver(grammar, pytree.convert)
try:
result = drv.parse_string(src_txt, True)
... | def lib2to3_parse(src_txt: str, target_versions: Iterable[TargetVersion] = ()) -
if src_txt[-1:] != "\n":
src_txt += "\n"
for parser_config in get_parser_configs(set(target_versions)):
drv = driver.Driver(
parser_config.grammar,
pytree.convert,
tokenizer_conf... |
from . import grammar, parse, token, tokenize, pgen
class Driver(object):
def __init__(self, grammar, convert=None, logger=None):
self.grammar = grammar
if logger is None:
logger = logging.getLogger(__name__)
self.logger = logger
self.convert = convert
def parse_to... | from . import grammar, parse, token, tokenize, pgen
class Driver(object):
def __init__(
self,
grammar,
convert=None,
logger=None,
tokenizer_config=tokenize.TokenizerConfig(),
):
self.grammar = grammar
if logger is None:
logger = logging.getLo... |
class Driver(object):
def parse_stream_raw(self, stream, debug=False):
"""Parse a stream and return the syntax tree."""
tokens = tokenize.generate_tokens(stream.readline)
return self.parse_tokens(tokens, debug)
def parse_stream(self, stream, debug=False): | class Driver(object):
def parse_stream_raw(self, stream, debug=False):
"""Parse a stream and return the syntax tree."""
tokens = tokenize.generate_tokens(stream.readline, config=self.tokenizer_config)
return self.parse_tokens(tokens, debug)
def parse_stream(self, stream, debug=False): |
class Driver(object):
def parse_string(self, text, debug=False):
"""Parse a string and return the syntax tree."""
tokens = tokenize.generate_tokens(io.StringIO(text).readline)
return self.parse_tokens(tokens, debug)
def _partially_consume_prefix(self, prefix, column): | class Driver(object):
def parse_string(self, text, debug=False):
"""Parse a string and return the syntax tree."""
tokens = tokenize.generate_tokens(
io.StringIO(text).readline,
config=self.tokenizer_config,
)
return self.parse_tokens(tokens, debug)
def _... |
__credits__ = \
import re
from codecs import BOM_UTF8, lookup
from blib2to3.pgen2.token import *
from . import token | __credits__ = \
import re
from codecs import BOM_UTF8, lookup
from attr import dataclass
from blib2to3.pgen2.token import *
from . import token |
single_quoted = (
tabsize = 8
class TokenError(Exception): pass
class StopTokenizing(Exception): pass | single_quoted = (
tabsize = 8
@dataclass(frozen=True)
class TokenizerConfig:
async_is_reserved_keyword: bool = False
class TokenError(Exception): pass
class StopTokenizing(Exception): pass |
def untokenize(iterable):
ut = Untokenizer()
return ut.untokenize(iterable)
def generate_tokens(readline):
"""
The generate_tokens() generator requires one argument, readline, which
must be a callable object which provides the same interface as the | def untokenize(iterable):
ut = Untokenizer()
return ut.untokenize(iterable)
def generate_tokens(readline, config: TokenizerConfig = TokenizerConfig()):
"""
The generate_tokens() generator requires one argument, readline, which
must be a callable object which provides the same interface as the |
def generate_tokens(readline):
contline = None
indents = [0]
# 'stashed' and 'async_*' are used for async/await parsing
stashed = None
async_def = False | def generate_tokens(readline):
contline = None
indents = [0]
# If we know we're parsing 3.7+, we can unconditionally parse `async` and
# `await` as keywords.
async_is_reserved_keyword = config.async_is_reserved_keyword
# 'stashed' and 'async_*' are used for async/await parsing
stashed = Non... |
def generate_tokens(readline):
yield (STRING, token, spos, epos, line)
elif initial.isidentifier(): # ordinary name
if token in ('async', 'await'):
if async_def:
yield (ASYNC if token == 'async'... | def generate_tokens(readline):
yield (STRING, token, spos, epos, line)
elif initial.isidentifier(): # ordinary name
if token in ('async', 'await'):
if async_is_reserved_keyword or async_def:
yie... |
async def func():
self.async_inc, arange(8), batch_size=3
)
]
# output
| async def func():
self.async_inc, arange(8), batch_size=3
)
]
def awaited_generator_value(n):
return (await awaitable for awaitable in awaitable_list)
def make_arange(n):
return (i * 2 for i in range(n) if await wrap(i))
# output
|
async def func():
self.async_inc, arange(8), batch_size=3
)
] | async def func():
self.async_inc, arange(8), batch_size=3
)
]
def awaited_generator_value(n):
return (await awaitable for awaitable in awaitable_list)
def make_arange(n):
return (i * 2 for i in range(n) if await wrap(i)) |
class BlackTestCase(unittest.TestCase):
self.assertFormatEqual(expected, actual)
black.assert_stable(source, actual, mode)
@patch("black.dump_to_file", dump_to_stderr)
def test_python37(self) -> None:
source, expected = read_data("python37")
actual = fs(source)
self.asse... | class BlackTestCase(unittest.TestCase):
self.assertFormatEqual(expected, actual)
black.assert_stable(source, actual, mode)
@patch("black.dump_to_file", dump_to_stderr)
def test_async_as_identifier(self) -> None:
source_path = (THIS_DIR / "data" / "async_as_identifier.py").resolve()
... |
class BlackTestCase(unittest.TestCase):
if major > 3 or (major == 3 and minor >= 7):
black.assert_equivalent(source, actual)
black.assert_stable(source, actual, black.FileMode())
@patch("black.dump_to_file", dump_to_stderr)
def test_fmtonoff(self) -> None: | class BlackTestCase(unittest.TestCase):
if major > 3 or (major == 3 and minor >= 7):
black.assert_equivalent(source, actual)
black.assert_stable(source, actual, black.FileMode())
# ensure black can parse this when the target is 3.7
self.invokeBlack([str(source_path), "--targe... |
def __xml_scan(node, env, path, arg):
styledoc = libxml2.parseFile(xsl_file)
style = libxslt.parseStylesheetDoc(styledoc)
doc = libxml2.parseFile(str(node))
result = style.applyStylesheet(doc, None)
depfiles = [] | def __xml_scan(node, env, path, arg):
styledoc = libxml2.parseFile(xsl_file)
style = libxslt.parseStylesheetDoc(styledoc)
doc = libxml2.readFile(str(node), None, libxml2.XML_PARSE_NOENT)
result = style.applyStylesheet(doc, None)
depfiles = [] |
def __xinclude_libxml2(target, source, env):
Resolving XIncludes, using the libxml2 module.
"""
doc = libxml2.readFile(str(source[0]), None, libxml2.XML_PARSE_NOENT)
doc.xincludeProcess()
doc.saveFile(str(target[0]))
doc.freeDoc()
| def __xinclude_libxml2(target, source, env):
Resolving XIncludes, using the libxml2 module.
"""
doc = libxml2.readFile(str(source[0]), None, libxml2.XML_PARSE_NOENT)
doc.xincludeProcessFlags(libxml2.XML_PARSE_NOENT)
doc.saveFile(str(target[0]))
doc.freeDoc()
|
from pandas.core.dtypes.common import (
is_unsigned_integer_dtype,
pandas_dtype,
)
from pandas.core.dtypes.generic import ABCIndexClass, ABCPeriodArray, ABCSeries
from pandas.core.dtypes.inference import is_array_like
from pandas.core.dtypes.missing import is_valid_nat_for_dtype, isna
| from pandas.core.dtypes.common import (
is_unsigned_integer_dtype,
pandas_dtype,
)
from pandas.core.dtypes.generic import ABCSeries
from pandas.core.dtypes.inference import is_array_like
from pandas.core.dtypes.missing import is_valid_nat_for_dtype, isna
|
default 'raise'
def _round(self, freq, mode, ambiguous, nonexistent):
# round the local times
values = _ensure_datetimelike_to_i8(self)
result = round_nsint64(values, mode, freq)
result = self._maybe_mask_results(result, fill_value=NaT)
dtype = self.dtype
if is_date... | default 'raise'
def _round(self, freq, mode, ambiguous, nonexistent):
# round the local times
if is_datetime64tz_dtype(self):
# operate on naive timestamps, then convert back to aware
naive = self.tz_localize(None)
result = naive._round(freq, mode, ambiguous, non... |
class DatetimeLikeArrayMixin(ExtensionOpsMixin, AttributesMixin, ExtensionArray)
self._freq = result._freq
return self
# --------------------------------------------------------------
# Comparison Methods
def _ensure_localized(
self, arg, ambiguous="raise", nonexistent="raise",... | class DatetimeLikeArrayMixin(ExtensionOpsMixin, AttributesMixin, ExtensionArray)
self._freq = result._freq
return self
# --------------------------------------------------------------
# Reductions
|
def maybe_infer_freq(freq):
freq_infer = True
freq = None
return freq, freq_infer
def _ensure_datetimelike_to_i8(other, to_utc=False):
"""
Helper for coercing an input scalar or array to i8.
Parameters
----------
other : 1d array
to_utc : bool, default False
... | def maybe_infer_freq(freq):
freq_infer = True
freq = None
return freq, freq_infer |
from pandas.util._decorators import Appender, cache_readonly
from pandas.core.dtypes.common import (
ensure_int64,
is_bool_dtype,
is_dtype_equal,
is_float,
is_integer,
is_list_like,
is_period_dtype,
is_scalar,
)
from pandas.core.dtypes.concat import concat_compat
from pandas.core.dtypes.... | from pandas.util._decorators import Appender, cache_readonly
from pandas.core.dtypes.common import (
ensure_int64,
is_bool_dtype,
is_categorical_dtype,
is_dtype_equal,
is_float,
is_integer,
is_list_like,
is_period_dtype,
is_scalar,
needs_i8_conversion,
)
from pandas.core.dtypes.c... |
from pandas.core.arrays import (
ExtensionOpsMixin,
TimedeltaArray,
)
from pandas.core.arrays.datetimelike import (
DatetimeLikeArrayMixin,
_ensure_datetimelike_to_i8,
)
import pandas.core.indexes.base as ibase
from pandas.core.indexes.base import Index, _index_shared_docs
from pandas.core.indexes.numer... | from pandas.core.arrays import (
ExtensionOpsMixin,
TimedeltaArray,
)
from pandas.core.arrays.datetimelike import DatetimeLikeArrayMixin
import pandas.core.indexes.base as ibase
from pandas.core.indexes.base import Index, _index_shared_docs
from pandas.core.indexes.numeric import Int64Index |
class DatetimeIndexOpsMixin(ExtensionIndex, ExtensionOpsMixin):
return np.array_equal(self.asi8, other.asi8)
def _ensure_localized(
self, arg, ambiguous="raise", nonexistent="raise", from_utc=False
):
# See DatetimeLikeArrayMixin._ensure_localized.__doc__
if getattr(self, "tz",... | class DatetimeIndexOpsMixin(ExtensionIndex, ExtensionOpsMixin):
return np.array_equal(self.asi8, other.asi8)
@Appender(_index_shared_docs["contains"] % _index_doc_kwargs)
def __contains__(self, key):
try: |
class DatetimeIndexOpsMixin(ExtensionIndex, ExtensionOpsMixin):
@Appender(_index_shared_docs["where"] % _index_doc_kwargs)
def where(self, cond, other=None):
other = _ensure_datetimelike_to_i8(other, to_utc=True)
values = _ensure_datetimelike_to_i8(self, to_utc=True)
result = np.where(c... | class DatetimeIndexOpsMixin(ExtensionIndex, ExtensionOpsMixin):
@Appender(_index_shared_docs["where"] % _index_doc_kwargs)
def where(self, cond, other=None):
values = self.view("i8")
if is_scalar(other) and isna(other):
other = NaT.value
else:
# Do type inferen... |
class TestWhere:
i2 = i.copy()
i2 = Index([pd.NaT, pd.NaT] + i[2:].tolist())
result = i.where(notna(i2), i2.values)
tm.assert_index_equal(result, i2)
def test_where_tz(self):
i = pd.date_range("20130101", periods=3, tz="US/Eastern")
result = i.where(notna(i)) | class TestWhere:
i2 = i.copy()
i2 = Index([pd.NaT, pd.NaT] + i[2:].tolist())
result = i.where(notna(i2), i2._values)
tm.assert_index_equal(result, i2)
def test_where_invalid_dtypes(self):
dti = pd.date_range("20130101", periods=3, tz="US/Eastern")
i2 = dti.copy()
... |
class TestWhere:
result = i.where(notna(i2), i2.values)
tm.assert_index_equal(result, i2)
class TestTake:
def test_take(self): | class TestWhere:
result = i.where(notna(i2), i2.values)
tm.assert_index_equal(result, i2)
def test_where_invalid_dtypes(self):
pi = period_range("20130101", periods=5, freq="D")
i2 = pi.copy()
i2 = pd.PeriodIndex([pd.NaT, pd.NaT] + pi[2:].tolist(), freq="D")
with p... |
import numpy as np
import pytest
import pandas as pd
from pandas import Index, Timedelta, TimedeltaIndex, timedelta_range
import pandas._testing as tm
| import numpy as np
import pytest
import pandas as pd
from pandas import Index, Timedelta, TimedeltaIndex, notna, timedelta_range
import pandas._testing as tm
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.