language stringclasses 1 value | repo stringclasses 346 values | path stringlengths 6 201 | class_span dict | source stringlengths 21 2.38M | target stringlengths 1 96 |
|---|---|---|---|---|---|
python | python__mypy | mypy/types.py | {
"start": 145047,
"end": 145643
} | class ____(TypeTranslator, SyntheticTypeVisitor[Type]):
"""A base class for type translators that need to be run during semantic analysis."""
def visit_placeholder_type(self, t: PlaceholderType, /) -> Type:
return t
def visit_callable_argument(self, t: CallableArgument, /) -> Type:
return t
def visit_ellipsis_type(self, t: EllipsisType, /) -> Type:
return t
def visit_raw_expression_type(self, t: RawExpressionType, /) -> Type:
return t
def visit_type_list(self, t: TypeList, /) -> Type:
return t
| TrivialSyntheticTypeTranslator |
python | cython__cython | Cython/Compiler/Tests/TestFlowControl.py | {
"start": 397,
"end": 1783
} | class ____(TestCase):
def test_deepcopy(self):
lhs, rhs = FakeNode(), FakeNode()
entry = FakeEntry()
entry.pos = lhs.pos
name_ass = NameAssignment(lhs, rhs, entry)
ass = deepcopy(name_ass)
self.assertTrue(ass.lhs)
self.assertTrue(ass.rhs)
self.assertTrue(ass.entry)
self.assertEqual(ass.pos, name_ass.pos)
self.assertFalse(ass.is_arg)
self.assertFalse(ass.is_deletion)
static_ass = StaticAssignment(entry)
ass = deepcopy(static_ass)
self.assertTrue(ass.lhs)
self.assertTrue(ass.rhs)
self.assertTrue(ass.entry)
self.assertEqual(ass.pos, static_ass.pos)
self.assertFalse(ass.is_arg)
self.assertFalse(ass.is_deletion)
arg_ass = Argument(lhs, rhs, entry)
ass = deepcopy(arg_ass)
self.assertTrue(ass.lhs)
self.assertTrue(ass.rhs)
self.assertTrue(ass.entry)
self.assertEqual(ass.pos, arg_ass.pos)
self.assertTrue(ass.is_arg)
self.assertFalse(ass.is_deletion)
name_del = NameDeletion(lhs, entry)
ass = deepcopy(name_del)
self.assertTrue(ass.lhs)
self.assertTrue(ass.rhs)
self.assertTrue(ass.entry)
self.assertEqual(ass.pos, name_del.pos)
self.assertFalse(ass.is_arg)
self.assertTrue(ass.is_deletion)
| TestGraph |
python | django__django | tests/middleware_exceptions/middleware.py | {
"start": 2749,
"end": 2952
} | class ____(BaseMiddleware):
def __call__(self, request):
response = self.get_response(request)
log.append((response.status_code, response.content))
return response
| LogMiddleware |
python | automl__auto-sklearn | autosklearn/util/logging_.py | {
"start": 8116,
"end": 10759
} | class ____(socketserver.StreamRequestHandler):
"""Handler for a streaming logging request.
This basically logs the record using whatever logging policy is
configured locally.
"""
def handle(self) -> None:
"""
Handle multiple requests - each expected to be a 4-byte length,
followed by the LogRecord in pickle format. Logs the record
according to whatever policy is configured locally.
"""
while True:
chunk = self.connection.recv(4) # type: ignore[attr-defined]
if len(chunk) < 4:
break
slen = struct.unpack(">L", chunk)[0]
chunk = self.connection.recv(slen) # type: ignore[attr-defined]
while len(chunk) < slen:
chunk = chunk + self.connection.recv(slen - len(chunk)) # type: ignore[attr-defined] # noqa: E501
obj = self.unPickle(chunk)
record = logging.makeLogRecord(obj)
self.handleLogRecord(record)
def unPickle(self, data: Any) -> Any:
return pickle.loads(data)
def handleLogRecord(self, record: logging.LogRecord) -> None:
# logname is define in LogRecordSocketReceiver
# Yet Mypy Cannot see this. This is needed so that we can
# re-use the logging setup for autosklearn into the recieved
# records
if self.server.logname is not None: # type: ignore # noqa
name = self.server.logname # type: ignore # noqa
else:
name = record.name
logger = logging.getLogger(name)
# N.B. EVERY record gets logged. This is because Logger.handle
# is normally called AFTER logger-level filtering. If you want
# to do filtering, do it at the client end to save wasting
# cycles and network bandwidth!
logger.handle(record)
def start_log_server(
host: str,
logname: str,
event: threading.Event,
port: multiprocessing.Value,
filename: str,
logging_config: Dict,
output_dir: str,
) -> None:
setup_logger(
filename=filename, logging_config=logging_config, output_dir=output_dir
)
while True:
# Loop until we find a valid port
_port = random.randint(10000, 65535)
try:
receiver = LogRecordSocketReceiver(
host=host,
port=_port,
logname=logname,
event=event,
)
with port.get_lock():
port.value = _port
receiver.serve_until_stopped()
break
except OSError:
continue
| LogRecordStreamHandler |
python | django-import-export__django-import-export | tests/core/tests/test_tmp_storages.py | {
"start": 3990,
"end": 5191
} | class ____(TestCase):
@override_settings(
STORAGES={
"import_export": {
"BACKEND": "tests.core.tests.test_tmp_storages.CustomizedStorage"
}
}
)
def test_MediaStorage_uses_custom_storage_implementation(self):
tmp_storage = TestMediaStorage()
tmp_storage.save(b"a")
self.assertEqual(1, tmp_storage._storage.save_count)
tmp_storage.read()
self.assertEqual(1, tmp_storage._storage.open_count)
tmp_storage.remove()
self.assertEqual(1, tmp_storage._storage.delete_count)
@override_settings(
STORAGES={
"import_export": {
"BACKEND": "tests.core.tests.test_tmp_storages.CustomizedStorage"
}
}
)
def test_disable_media_folder(self):
tmp_storage = MediaStorage(MEDIA_FOLDER=None)
tmp_storage.name = "TESTNAME"
self.assertIsNone(tmp_storage.MEDIA_FOLDER)
self.assertEqual("TESTNAME", tmp_storage.get_full_path())
def test_media_folder(self):
tmp_storage = MediaStorage()
self.assertEqual("django-import-export", tmp_storage.MEDIA_FOLDER)
| CustomizedMediaStorageTestDjango |
python | vyperlang__vyper | vyper/venom/passes/sccp/sccp.py | {
"start": 627,
"end": 692
} | class ____(Enum):
TOP = 1
BOTTOM = 2
@dataclass
| LatticeEnum |
python | spyder-ide__spyder | spyder/plugins/remoteclient/api/ssh.py | {
"start": 388,
"end": 6972
} | class ____(SSHClient):
def __init__(self, client):
self.client = client
def connection_made(self, conn: SSHClientConnection) -> None:
"""Called when a connection is made
This method is called as soon as the TCP connection completes.
The `conn` parameter should be stored if needed for later use.
:param conn:
The connection which was successfully opened
:type conn: :class:`SSHClientConnection`
"""
def connection_lost(self, exc: Optional[Exception]) -> None:
"""Called when a connection is lost or closed
This method is called when a connection is closed. If the
connection is shut down cleanly, *exc* will be `None`.
Otherwise, it will be an exception explaining the reason for
the disconnect.
:param exc:
The exception which caused the connection to close, or
`None` if the connection closed cleanly
:type exc: :class:`Exception`
"""
if self.client._plugin:
self.client._plugin.sig_connection_lost.emit(self.client.config_id)
self.client._handle_connection_lost(exc)
def debug_msg_received(
self, msg: str, lang: str, always_display: bool
) -> None:
"""A debug message was received on this connection
This method is called when the other end of the connection sends
a debug message. Applications should implement this method if
they wish to process these debug messages.
:param msg:
The debug message sent
:param lang:
The language the message is in
:param always_display:
Whether or not to display the message
:type msg: `str`
:type lang: `str`
:type always_display: `bool`
"""
_logger.debug(f"Debug message received: {msg}")
def auth_completed(self) -> None:
"""Authentication was completed successfully
This method is called when authentication has completed
successfully. Applications may use this method to create
whatever client sessions and direct TCP/IP or UNIX domain
connections are needed and/or set up listeners for incoming
TCP/IP or UNIX domain connections coming from the server.
However, :func:`create_connection` now blocks until
authentication is complete, so any code which wishes to
use the SSH connection can simply follow that call and
doesn't need to be performed in a callback.
"""
def public_key_auth_requested(self) -> Optional[KeyPairListArg]:
"""Public key authentication has been requested
This method should return a private key corresponding to
the user that authentication is being attempted for.
This method may be called multiple times and can return a
different key to try each time it is called. When there are
no keys left to try, it should return `None` to indicate
that some other authentication method should be tried.
If client keys were provided when the connection was opened,
they will be tried before this method is called.
If blocking operations need to be performed to determine the
key to authenticate with, this method may be defined as a
coroutine.
:returns: A key as described in :ref:`SpecifyingPrivateKeys`
or `None` to move on to another authentication
method
"""
return None # pragma: no cover
def password_auth_requested(self) -> Optional[str]:
"""Password authentication has been requested
This method should return a string containing the password
corresponding to the user that authentication is being
attempted for. It may be called multiple times and can
return a different password to try each time, but most
servers have a limit on the number of attempts allowed.
When there's no password left to try, this method should
return `None` to indicate that some other authentication
method should be tried.
If a password was provided when the connection was opened,
it will be tried before this method is called.
If blocking operations need to be performed to determine the
password to authenticate with, this method may be defined as
a coroutine.
:returns: A string containing the password to authenticate
with or `None` to move on to another authentication
method
"""
return None # pragma: no cover
def password_change_requested(
self, prompt: str, lang: str
) -> PasswordChangeResponse:
"""A password change has been requested
This method is called when password authentication was
attempted and the user's password was expired on the
server. To request a password change, this method should
return a tuple or two strings containing the old and new
passwords. Otherwise, it should return `NotImplemented`.
If blocking operations need to be performed to determine the
passwords to authenticate with, this method may be defined
as a coroutine.
By default, this method returns `NotImplemented`.
:param prompt:
The prompt requesting that the user enter a new password
:param lang:
The language that the prompt is in
:type prompt: `str`
:type lang: `str`
:returns: A tuple of two strings containing the old and new
passwords or `NotImplemented` if password changes
aren't supported
"""
return NotImplemented # pragma: no cover
def password_changed(self) -> None:
"""The requested password change was successful
This method is called to indicate that a requested password
change was successful. It is generally followed by a call to
:meth:`auth_completed` since this means authentication was
also successful.
"""
def password_change_failed(self) -> None:
"""The requested password change has failed
This method is called to indicate that a requested password
change failed, generally because the requested new password
doesn't meet the password criteria on the remote system.
After this method is called, other forms of authentication
will automatically be attempted.
"""
| SpyderSSHClient |
python | run-llama__llama_index | llama-index-packs/llama-index-packs-code-hierarchy/tests/test_code_hierarchy_no_skeleton.py | {
"start": 19679,
"end": 21597
} | class ____ { // The class
public: // Access specifier
int myNum; // Attribute (int variable)
string myString; // Attribute (string variable)
void myMethod() { // Method/function defined inside the class
cout << "Hello World!";
}
}"""
)
assert chunks[1].metadata["inclusive_scopes"] == [
{"name": "MyClass", "type": "class_specifier", "signature": "class MyClass"}
]
assert (
cast(RelatedNodeInfo, chunks[1].relationships[NodeRelationship.PARENT]).node_id
== chunks[0].id_
)
assert [c.node_id for c in chunks[1].relationships[NodeRelationship.CHILD]] == [
chunks[2].id_
]
# Test the third chunk (myMethod in class MyClass)
assert (
chunks[2].text
== """\
void myMethod() { // Method/function defined inside the class
cout << "Hello World!";
}"""
)
assert chunks[2].metadata["inclusive_scopes"] == [
{"name": "MyClass", "type": "class_specifier", "signature": "class MyClass"},
{
"name": "myMethod()",
"type": "function_definition",
"signature": "void myMethod()",
},
]
assert (
cast(RelatedNodeInfo, chunks[2].relationships[NodeRelationship.PARENT]).node_id
== chunks[1].id_
)
assert chunks[2].relationships[NodeRelationship.CHILD] == []
# Test the fourth chunk (main function)
assert (
chunks[3].text
== """\
int main() {
std::cout << "Hello, World!" << std::endl;
return 0;
}"""
)
assert chunks[3].metadata["inclusive_scopes"] == [
{"name": "main()", "type": "function_definition", "signature": "int main()"}
]
assert (
cast(RelatedNodeInfo, chunks[3].relationships[NodeRelationship.PARENT]).node_id
== chunks[0].id_
)
assert chunks[3].relationships[NodeRelationship.CHILD] == []
| MyClass |
python | pandas-dev__pandas | pandas/tests/io/formats/test_printing.py | {
"start": 2674,
"end": 5558
} | class ____:
def test_adjoin(self):
data = [["a", "b", "c"], ["dd", "ee", "ff"], ["ggg", "hhh", "iii"]]
expected = "a dd ggg\nb ee hhh\nc ff iii"
adjoined = printing.adjoin(2, *data)
assert adjoined == expected
def test_adjoin_unicode(self):
data = [["あ", "b", "c"], ["dd", "ええ", "ff"], ["ggg", "hhh", "いいい"]]
expected = "あ dd ggg\nb ええ hhh\nc ff いいい"
adjoined = printing.adjoin(2, *data)
assert adjoined == expected
adj = printing._EastAsianTextAdjustment()
expected = """あ dd ggg
b ええ hhh
c ff いいい"""
adjoined = adj.adjoin(2, *data)
assert adjoined == expected
cols = adjoined.split("\n")
assert adj.len(cols[0]) == 13
assert adj.len(cols[1]) == 13
assert adj.len(cols[2]) == 16
expected = """あ dd ggg
b ええ hhh
c ff いいい"""
adjoined = adj.adjoin(7, *data)
assert adjoined == expected
cols = adjoined.split("\n")
assert adj.len(cols[0]) == 23
assert adj.len(cols[1]) == 23
assert adj.len(cols[2]) == 26
def test_justify(self):
adj = printing._EastAsianTextAdjustment()
def just(x, *args, **kwargs):
# wrapper to test single str
return adj.justify([x], *args, **kwargs)[0]
assert just("abc", 5, mode="left") == "abc "
assert just("abc", 5, mode="center") == " abc "
assert just("abc", 5, mode="right") == " abc"
assert just("abc", 5, mode="left") == "abc "
assert just("abc", 5, mode="center") == " abc "
assert just("abc", 5, mode="right") == " abc"
assert just("パンダ", 5, mode="left") == "パンダ"
assert just("パンダ", 5, mode="center") == "パンダ"
assert just("パンダ", 5, mode="right") == "パンダ"
assert just("パンダ", 10, mode="left") == "パンダ "
assert just("パンダ", 10, mode="center") == " パンダ "
assert just("パンダ", 10, mode="right") == " パンダ"
def test_east_asian_len(self):
adj = printing._EastAsianTextAdjustment()
assert adj.len("abc") == 3
assert adj.len("abc") == 3
assert adj.len("パンダ") == 6
assert adj.len("パンダ") == 5
assert adj.len("パンダpanda") == 11
assert adj.len("パンダpanda") == 10
def test_ambiguous_width(self):
adj = printing._EastAsianTextAdjustment()
assert adj.len("¡¡ab") == 4
with cf.option_context("display.unicode.ambiguous_as_wide", True):
adj = printing._EastAsianTextAdjustment()
assert adj.len("¡¡ab") == 6
data = [["あ", "b", "c"], ["dd", "ええ", "ff"], ["ggg", "¡¡ab", "いいい"]]
expected = "あ dd ggg \nb ええ ¡¡ab\nc ff いいい"
adjoined = adj.adjoin(2, *data)
assert adjoined == expected
| TestFormatBase |
python | Pylons__pyramid | tests/test_config/test_views.py | {
"start": 109257,
"end": 120343
} | class ____(unittest.TestCase):
def _getTargetClass(self):
from pyramid.config.views import MultiView
return MultiView
def _makeOne(self, name='name'):
return self._getTargetClass()(name)
def test_class_implements_ISecuredView(self):
from zope.interface.verify import verifyClass
from pyramid.interfaces import ISecuredView
verifyClass(ISecuredView, self._getTargetClass())
def test_instance_implements_ISecuredView(self):
from zope.interface.verify import verifyObject
from pyramid.interfaces import ISecuredView
verifyObject(ISecuredView, self._makeOne())
def test_add(self):
mv = self._makeOne()
mv.add('view', 100)
self.assertEqual(mv.views, [(100, 'view', None)])
mv.add('view2', 99)
self.assertEqual(mv.views, [(99, 'view2', None), (100, 'view', None)])
mv.add('view3', 100, accept='text/html')
self.assertEqual(mv.media_views['text/html'], [(100, 'view3', None)])
mv.add('view4', 99, 'abc', accept='text/html')
self.assertEqual(
mv.media_views['text/html'],
[(99, 'view4', 'abc'), (100, 'view3', None)],
)
mv.add('view5', 100, accept='text/xml')
self.assertEqual(mv.media_views['text/xml'], [(100, 'view5', None)])
self.assertEqual(set(mv.accepts), {'text/xml', 'text/html'})
self.assertEqual(mv.views, [(99, 'view2', None), (100, 'view', None)])
def test_add_with_phash(self):
mv = self._makeOne()
mv.add('view', 100, phash='abc')
self.assertEqual(mv.views, [(100, 'view', 'abc')])
mv.add('view', 100, phash='abc')
self.assertEqual(mv.views, [(100, 'view', 'abc')])
mv.add('view', 100, phash='def')
self.assertEqual(
mv.views, [(100, 'view', 'abc'), (100, 'view', 'def')]
)
mv.add('view', 100, phash='abc')
self.assertEqual(
mv.views, [(100, 'view', 'abc'), (100, 'view', 'def')]
)
def test_add_with_phash_override_accept(self):
mv = self._makeOne()
def view1(): # pragma: no cover
pass
def view2(): # pragma: no cover
pass
def view3(): # pragma: no cover
pass
mv.add(view1, 100, accept='text/html', phash='abc')
mv.add(view2, 100, accept='text/html', phash='abc')
mv.add(view3, 99, accept='text/html', phash='def')
self.assertEqual(
mv.media_views['text/html'],
[(99, view3, 'def'), (100, view2, 'abc')],
)
def test_add_with_phash_override_accept2(self):
mv = self._makeOne()
def view1(): # pragma: no cover
pass
def view2(): # pragma: no cover
pass
def view3(): # pragma: no cover
pass
mv.add(view1, 100, accept='text/html', phash='abc')
mv.add(view2, 100, accept='text/html', phash='def')
mv.add(view3, 99, accept='text/html', phash='ghi')
self.assertEqual(
mv.media_views['text/html'],
[(99, view3, 'ghi'), (100, view1, 'abc'), (100, view2, 'def')],
)
def test_multiple_with_functions_as_views(self):
# this failed on py3 at one point, because functions aren't orderable
# and we were sorting the views via a plain sort() rather than
# sort(key=itemgetter(0)).
def view1(request): # pragma: no cover
pass
def view2(request): # pragma: no cover
pass
mv = self._makeOne()
mv.add(view1, 100, None)
self.assertEqual(mv.views, [(100, view1, None)])
mv.add(view2, 100, None)
self.assertEqual(mv.views, [(100, view1, None), (100, view2, None)])
def test_get_views_request_has_no_accept(self):
request = DummyRequest()
mv = self._makeOne()
mv.views = [(99, lambda *arg: None)]
self.assertEqual(mv.get_views(request), mv.views)
def test_get_views_no_self_accepts(self):
request = DummyRequest()
request.accept = True
mv = self._makeOne()
mv.accepts = []
mv.views = [(99, lambda *arg: None)]
self.assertEqual(mv.get_views(request), mv.views)
def test_get_views(self):
request = DummyRequest()
request.accept = DummyAccept('text/html')
mv = self._makeOne()
mv.accepts = ['text/html']
mv.views = [(99, lambda *arg: None)]
html_views = [(98, lambda *arg: None)]
mv.media_views['text/html'] = html_views
self.assertEqual(mv.get_views(request), html_views + mv.views)
def test_get_views_best_match_returns_None(self):
request = DummyRequest()
request.accept = DummyAccept(None)
mv = self._makeOne()
mv.accepts = ['text/html']
mv.views = [(99, lambda *arg: None)]
self.assertEqual(mv.get_views(request), mv.views)
def test_match_not_found(self):
from pyramid.httpexceptions import HTTPNotFound
mv = self._makeOne()
context = DummyContext()
request = DummyRequest()
self.assertRaises(HTTPNotFound, mv.match, context, request)
def test_match_predicate_fails(self):
from pyramid.httpexceptions import HTTPNotFound
mv = self._makeOne()
def view(context, request):
""" """
view.__predicated__ = lambda *arg: False
mv.views = [(100, view, None)]
context = DummyContext()
request = DummyRequest()
self.assertRaises(HTTPNotFound, mv.match, context, request)
def test_match_predicate_succeeds(self):
mv = self._makeOne()
def view(context, request):
""" """
view.__predicated__ = lambda *arg: True
mv.views = [(100, view, None)]
context = DummyContext()
request = DummyRequest()
result = mv.match(context, request)
self.assertEqual(result, view)
def test_permitted_no_views(self):
from pyramid.httpexceptions import HTTPNotFound
mv = self._makeOne()
context = DummyContext()
request = DummyRequest()
self.assertRaises(HTTPNotFound, mv.__permitted__, context, request)
def test_permitted_no_match_with__permitted__(self):
mv = self._makeOne()
def view(context, request):
""" """
mv.views = [(100, view, None)]
self.assertEqual(mv.__permitted__(None, None), True)
def test_permitted(self):
mv = self._makeOne()
def view(context, request):
""" """
def permitted(context, request):
return False
view.__permitted__ = permitted
mv.views = [(100, view, None)]
context = DummyContext()
request = DummyRequest()
result = mv.__permitted__(context, request)
self.assertEqual(result, False)
def test__call__not_found(self):
from pyramid.httpexceptions import HTTPNotFound
mv = self._makeOne()
context = DummyContext()
request = DummyRequest()
self.assertRaises(HTTPNotFound, mv, context, request)
def test___call__intermediate_not_found(self):
from pyramid.exceptions import PredicateMismatch
mv = self._makeOne()
context = DummyContext()
request = DummyRequest()
request.view_name = ''
expected_response = DummyResponse()
def view1(context, request):
raise PredicateMismatch
def view2(context, request):
return expected_response
mv.views = [(100, view1, None), (99, view2, None)]
response = mv(context, request)
self.assertEqual(response, expected_response)
def test___call__raise_not_found_isnt_interpreted_as_pred_mismatch(self):
from pyramid.httpexceptions import HTTPNotFound
mv = self._makeOne()
context = DummyContext()
request = DummyRequest()
request.view_name = ''
def view1(context, request):
raise HTTPNotFound
def view2(context, request):
""" """
mv.views = [(100, view1, None), (99, view2, None)]
self.assertRaises(HTTPNotFound, mv, context, request)
def test___call__(self):
mv = self._makeOne()
context = DummyContext()
request = DummyRequest()
request.view_name = ''
expected_response = DummyResponse()
def view(context, request):
return expected_response
mv.views = [(100, view, None)]
response = mv(context, request)
self.assertEqual(response, expected_response)
def test__call_permissive__not_found(self):
from pyramid.httpexceptions import HTTPNotFound
mv = self._makeOne()
context = DummyContext()
request = DummyRequest()
self.assertRaises(HTTPNotFound, mv, context, request)
def test___call_permissive_has_call_permissive(self):
mv = self._makeOne()
context = DummyContext()
request = DummyRequest()
request.view_name = ''
expected_response = DummyResponse()
def view(context, request):
""" """
def permissive(context, request):
return expected_response
view.__call_permissive__ = permissive
mv.views = [(100, view, None)]
response = mv.__call_permissive__(context, request)
self.assertEqual(response, expected_response)
def test___call_permissive_has_no_call_permissive(self):
mv = self._makeOne()
context = DummyContext()
request = DummyRequest()
request.view_name = ''
expected_response = DummyResponse()
def view(context, request):
return expected_response
mv.views = [(100, view, None)]
response = mv.__call_permissive__(context, request)
self.assertEqual(response, expected_response)
def test__call__with_accept_match(self):
mv = self._makeOne()
context = DummyContext()
request = DummyRequest()
request.accept = DummyAccept('text/html', 'text/xml')
expected_response = DummyResponse()
def view(context, request):
return expected_response
mv.views = [(100, None)]
mv.media_views['text/xml'] = [(100, view, None)]
mv.accepts = ['text/xml']
response = mv(context, request)
self.assertEqual(response, expected_response)
def test__call__with_accept_miss(self):
mv = self._makeOne()
context = DummyContext()
request = DummyRequest()
request.accept = DummyAccept('text/plain', 'text/html')
expected_response = DummyResponse()
def view(context, request):
return expected_response
mv.views = [(100, view, None)]
mv.media_views['text/xml'] = [(100, None, None)]
mv.accepts = ['text/xml']
response = mv(context, request)
self.assertEqual(response, expected_response)
| TestMultiView |
python | donnemartin__interactive-coding-challenges | bit_manipulation/draw_line/test_draw_line.py | {
"start": 18,
"end": 863
} | class ____(unittest.TestCase):
def test_draw_line(self):
bits_screen = BitsScreen()
screen = []
for _ in range(20):
screen.append(int('00000000', base=2))
bits_screen.draw_line(screen, width=32, x1=68, x2=80)
self.assertEqual(screen[8], int('00001111', base=2))
self.assertEqual(screen[9], int('11111111', base=2))
self.assertEqual(screen[10], int('10000000', base=2))
bits_screen.draw_line(screen, width=32, x1=2, x2=6)
self.assertEqual(screen[0], int('00111110', base=2))
bits_screen.draw_line(screen, width=32, x1=10, x2=13)
self.assertEqual(screen[1], int('00111100', base=2))
print('Success: test_draw_line')
def main():
test = TestBitsScreen()
test.test_draw_line()
if __name__ == '__main__':
main()
| TestBitsScreen |
python | kamyu104__LeetCode-Solutions | Python/count-the-number-of-vowel-strings-in-range.py | {
"start": 38,
"end": 377
} | class ____(object):
def vowelStrings(self, words, left, right):
"""
:type words: List[str]
:type left: int
:type right: int
:rtype: int
"""
VOWELS = {'a', 'e', 'i', 'o', 'u'}
return sum(words[i][0] in VOWELS and words[i][-1] in VOWELS for i in xrange(left, right+1))
| Solution |
python | Textualize__textual | src/textual/binding.py | {
"start": 1294,
"end": 5594
} | class ____:
"""The configuration of a key binding."""
key: str
"""Key to bind. This can also be a comma-separated list of keys to map multiple keys to a single action."""
action: str
"""Action to bind to."""
description: str = ""
"""Description of action."""
show: bool = True
"""Show the action in Footer, or False to hide."""
key_display: str | None = None
"""How the key should be shown in footer.
If `None`, the display of the key will use the result of `App.get_key_display`.
If overridden in a keymap then this value is ignored.
"""
priority: bool = False
"""Enable priority binding for this key."""
tooltip: str = ""
"""Optional tooltip to show in footer."""
id: str | None = None
"""ID of the binding. Intended to be globally unique, but uniqueness is not enforced.
If specified in the App's keymap then Textual will use this ID to lookup the binding,
and substitute the `key` property of the Binding with the key specified in the keymap.
"""
system: bool = False
"""Make this binding a system binding, which removes it from the key panel."""
@dataclass(frozen=True)
class Group:
"""A binding group causes the keys to be grouped under a single description."""
description: str = ""
"""Description of the group."""
compact: bool = False
"""Show keys in compact form (no spaces)."""
group: Group | None = None
"""Optional binding group (used to group related bindings in the footer)."""
def parse_key(self) -> tuple[list[str], str]:
"""Parse a key into a list of modifiers, and the actual key.
Returns:
A tuple of (MODIFIER LIST, KEY).
"""
*modifiers, key = self.key.split("+")
return modifiers, key
def with_key(self, key: str, key_display: str | None = None) -> Binding:
"""Return a new binding with the key and key_display set to the specified values.
Args:
key: The new key to set.
key_display: The new key display to set.
Returns:
A new binding with the key set to the specified value.
"""
return dataclasses.replace(self, key=key, key_display=key_display)
@classmethod
def make_bindings(cls, bindings: Iterable[BindingType]) -> Iterable[Binding]:
"""Convert a list of BindingType (the types that can be specified in BINDINGS)
into an Iterable[Binding].
Compound bindings like "j,down" will be expanded into 2 Binding instances.
Args:
bindings: An iterable of BindingType.
Returns:
An iterable of Binding.
"""
bindings = list(bindings)
for binding in bindings:
# If it's a tuple of length 3, convert into a Binding first
if isinstance(binding, tuple):
if len(binding) not in (2, 3):
raise BindingError(
f"BINDINGS must contain a tuple of two or three strings, not {binding!r}"
)
# `binding` is a tuple of 2 or 3 values at this point
binding = Binding(*binding) # type: ignore[reportArgumentType]
# At this point we have a Binding instance, but the key may
# be a list of keys, so now we unroll that single Binding
# into a (potential) collection of Binding instances.
for key in binding.key.split(","):
key = key.strip()
if not key:
raise InvalidBinding(
f"Can not bind empty string in {binding.key!r}"
)
if len(key) == 1:
key = _character_to_key(key)
yield Binding(
key=key,
action=binding.action,
description=binding.description,
show=bool(binding.description and binding.show),
key_display=binding.key_display,
priority=binding.priority,
tooltip=binding.tooltip,
id=binding.id,
system=binding.system,
group=binding.group,
)
| Binding |
python | langchain-ai__langchain | libs/partners/ollama/tests/unit_tests/test_auth.py | {
"start": 5881,
"end": 6852
} | class ____:
"""Test URL authentication integration with OllamaLLM."""
@patch("langchain_ollama.llms.Client")
@patch("langchain_ollama.llms.AsyncClient")
def test_ollama_llm_url_auth_integration(
self, mock_async_client: MagicMock, mock_client: MagicMock
) -> None:
"""Test that OllamaLLM properly handles URL authentication."""
url_with_auth = "https://user:password@ollama.example.com:11434"
OllamaLLM(
model=MODEL_NAME,
base_url=url_with_auth,
)
expected_url = "https://ollama.example.com:11434"
expected_credentials = base64.b64encode(b"user:password").decode()
expected_headers = {"Authorization": f"Basic {expected_credentials}"}
mock_client.assert_called_once_with(host=expected_url, headers=expected_headers)
mock_async_client.assert_called_once_with(
host=expected_url, headers=expected_headers
)
| TestOllamaLLMUrlAuth |
python | rapidsai__cudf | python/cudf/cudf/tests/test_doctests.py | {
"start": 2064,
"end": 3958
} | class ____:
@pytest.fixture(autouse=True)
def printoptions(cls):
# TODO: NumPy now prints scalars as `np.int8(1)`, etc. this should
# be adapted evantually.
if version.parse(np.__version__) >= version.parse("2.0"):
with np.printoptions(legacy="1.25"):
yield
else:
yield
@pytest.mark.parametrize(
"docstring",
itertools.chain.from_iterable(
_find_doctests_in_obj(mod) for mod in tests
),
ids=lambda docstring: docstring.name,
)
@pytest.mark.skipif(
PANDAS_VERSION < PANDAS_CURRENT_SUPPORTED_VERSION,
reason="Doctests not expected to pass on older versions of pandas",
)
def test_docstring(self, docstring, monkeypatch, tmp_path):
# We ignore differences in whitespace in the doctest output, and enable
# the use of an ellipsis "..." to match any string in the doctest
# output. An ellipsis is useful for, e.g., memory addresses or
# imprecise floating point values.
monkeypatch.chdir(tmp_path)
optionflags = doctest.ELLIPSIS | doctest.NORMALIZE_WHITESPACE
runner = doctest.DocTestRunner(optionflags=optionflags)
# These global names are pre-defined and can be used in doctests
# without first importing them.
globals = dict(
cudf=cudf,
np=np,
)
docstring.globs = globals
# Capture stdout and include failing outputs in the traceback.
doctest_stdout = io.StringIO()
with contextlib.redirect_stdout(doctest_stdout):
runner.run(docstring)
results = runner.summarize()
assert not results.failed, (
f"{results.failed} of {results.attempted} doctests failed for "
f"{docstring.name}:\n{doctest_stdout.getvalue()}"
)
| TestDoctests |
python | jazzband__django-model-utils | tests/test_fields/test_monitor_field.py | {
"start": 3323,
"end": 4089
} | class ____(TestCase):
"""
Monitor should never be updated id when is an empty list.
"""
def setUp(self) -> None:
self.instance = MonitorWhenEmpty(name='Charlie')
self.created = self.instance.name_changed
def test_save_no_change(self) -> None:
self.instance.save()
self.assertEqual(self.instance.name_changed, self.created)
def test_save_changed_to_Jose(self) -> None:
self.instance.name = 'Jose'
self.instance.save()
self.assertEqual(self.instance.name_changed, self.created)
def test_save_changed_to_Maria(self) -> None:
self.instance.name = 'Maria'
self.instance.save()
self.assertEqual(self.instance.name_changed, self.created)
| MonitorWhenEmptyFieldTests |
python | kubernetes-client__python | kubernetes/client/models/v1beta2_device_class_configuration.py | {
"start": 383,
"end": 3547
} | class ____(object):
"""NOTE: This class is auto generated by OpenAPI Generator.
Ref: https://openapi-generator.tech
Do not edit the class manually.
"""
"""
Attributes:
openapi_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The key is attribute name
and the value is json key in definition.
"""
openapi_types = {
'opaque': 'V1beta2OpaqueDeviceConfiguration'
}
attribute_map = {
'opaque': 'opaque'
}
def __init__(self, opaque=None, local_vars_configuration=None): # noqa: E501
"""V1beta2DeviceClassConfiguration - a model defined in OpenAPI""" # noqa: E501
if local_vars_configuration is None:
local_vars_configuration = Configuration()
self.local_vars_configuration = local_vars_configuration
self._opaque = None
self.discriminator = None
if opaque is not None:
self.opaque = opaque
@property
def opaque(self):
"""Gets the opaque of this V1beta2DeviceClassConfiguration. # noqa: E501
:return: The opaque of this V1beta2DeviceClassConfiguration. # noqa: E501
:rtype: V1beta2OpaqueDeviceConfiguration
"""
return self._opaque
@opaque.setter
def opaque(self, opaque):
"""Sets the opaque of this V1beta2DeviceClassConfiguration.
:param opaque: The opaque of this V1beta2DeviceClassConfiguration. # noqa: E501
:type: V1beta2OpaqueDeviceConfiguration
"""
self._opaque = opaque
def to_dict(self):
"""Returns the model properties as a dict"""
result = {}
for attr, _ in six.iteritems(self.openapi_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value
))
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict") else item,
value.items()
))
else:
result[attr] = value
return result
def to_str(self):
"""Returns the string representation of the model"""
return pprint.pformat(self.to_dict())
def __repr__(self):
"""For `print` and `pprint`"""
return self.to_str()
def __eq__(self, other):
"""Returns true if both objects are equal"""
if not isinstance(other, V1beta2DeviceClassConfiguration):
return False
return self.to_dict() == other.to_dict()
def __ne__(self, other):
"""Returns true if both objects are not equal"""
if not isinstance(other, V1beta2DeviceClassConfiguration):
return True
return self.to_dict() != other.to_dict()
| V1beta2DeviceClassConfiguration |
python | doocs__leetcode | solution/0500-0599/0547.Number of Provinces/Solution2.py | {
"start": 0,
"end": 541
} | class ____:
def findCircleNum(self, isConnected: List[List[int]]) -> int:
def find(x: int) -> int:
if p[x] != x:
p[x] = find(p[x])
return p[x]
n = len(isConnected)
p = list(range(n))
ans = n
for i in range(n):
for j in range(i + 1, n):
if isConnected[i][j]:
pa, pb = find(i), find(j)
if pa != pb:
p[pa] = pb
ans -= 1
return ans
| Solution |
python | joke2k__faker | faker/providers/ssn/sl_SI/__init__.py | {
"start": 42,
"end": 408
} | class ____(BaseProvider):
"""
A Faker provider for the Slovenian VAT IDs
"""
vat_id_formats = ("SI########",)
def vat_id(self) -> str:
"""
http://ec.europa.eu/taxation_customs/vies/faq.html#item_11
:return: a random Slovenian VAT ID
"""
return self.bothify(self.random_element(self.vat_id_formats))
| Provider |
python | django-guardian__django-guardian | example_project/posts/migrations/0003_alter_post_id.py | {
"start": 93,
"end": 439
} | class ____(migrations.Migration):
dependencies = [
("posts", "0002_auto_20190629_0848"),
]
operations = [
migrations.AlterField(
model_name="post",
name="id",
field=models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name="ID"),
),
]
| Migration |
python | django__django | django/contrib/postgres/apps.py | {
"start": 1989,
"end": 4062
} | class ____(AppConfig):
name = "django.contrib.postgres"
verbose_name = _("PostgreSQL extensions")
def ready(self):
setting_changed.connect(uninstall_if_needed)
# Connections may already exist before we are called.
for conn in connections.all(initialized_only=True):
if conn.vendor == "postgresql":
conn.introspection.data_types_reverse.update(
{
3904: "django.contrib.postgres.fields.IntegerRangeField",
3906: "django.contrib.postgres.fields.DecimalRangeField",
3910: "django.contrib.postgres.fields.DateTimeRangeField",
3912: "django.contrib.postgres.fields.DateRangeField",
3926: "django.contrib.postgres.fields.BigIntegerRangeField",
# PostgreSQL OIDs may vary depending on the
# installation, especially for datatypes from
# extensions, e.g. "hstore". In such cases, the
# type_display attribute (psycopg 3.2+) should be used.
"hstore": "django.contrib.postgres.fields.HStoreField",
}
)
if conn.connection is not None:
register_type_handlers(conn)
connection_created.connect(register_type_handlers)
CharField.register_lookup(Unaccent)
TextField.register_lookup(Unaccent)
CharField.register_lookup(SearchLookup)
TextField.register_lookup(SearchLookup)
CharField.register_lookup(TrigramSimilar)
TextField.register_lookup(TrigramSimilar)
CharField.register_lookup(TrigramWordSimilar)
TextField.register_lookup(TrigramWordSimilar)
CharField.register_lookup(TrigramStrictWordSimilar)
TextField.register_lookup(TrigramStrictWordSimilar)
MigrationWriter.register_serializer(RANGE_TYPES, RangeSerializer)
IndexExpression.register_wrappers(OrderBy, OpClass, Collate)
| PostgresConfig |
python | apache__airflow | providers/google/src/airflow/providers/google/cloud/hooks/dataproc.py | {
"start": 2310,
"end": 2441
} | class ____(AirflowException):
"""Raise when resource is not ready for create Dataproc cluster."""
| DataprocResourceIsNotReadyError |
python | ijl__orjson | test/test_dataclass.py | {
"start": 665,
"end": 786
} | class ____:
a: str = field()
b: int = field(metadata={"unrelated": False})
c: float = 1.1
@dataclass
| Dataclass4 |
python | getsentry__sentry | fixtures/safe_migrations_apps/good_flow_delete_field_pending_with_not_null_m2m_app/migrations/0002_delete_without_pending.py | {
"start": 190,
"end": 530
} | class ____(CheckedMigration):
dependencies = [
("good_flow_delete_field_pending_with_not_null_m2m_app", "0001_initial"),
]
operations = [
SafeRemoveField(
model_name="testtable",
name="excluded_projects",
deletion_action=DeletionAction.MOVE_TO_PENDING,
),
]
| Migration |
python | apache__airflow | providers/keycloak/src/airflow/providers/keycloak/auth_manager/datamodels/token.py | {
"start": 1025,
"end": 1160
} | class ____(StrictBaseModel):
"""Token serializer for post bodies."""
username: str = Field()
password: str = Field()
| TokenBody |
python | HIPS__autograd | examples/rkhs.py | {
"start": 1069,
"end": 2460
} | class ____(VSpace):
def __init__(self, value):
self.kernel = value.kernel
def zeros(self):
return RKHSFun(self.kernel)
def randn(self):
# These arbitrary vectors are not analogous to randn in any meaningful way
N = npr.randint(1, 3)
return RKHSFun(self.kernel, dict(zip(npr.randn(N), npr.randn(N))))
def _add(self, f, g):
assert f.kernel is g.kernel
return RKHSFun(f.kernel, add_dicts(f.alphas, g.alphas))
def _scalar_mul(self, f, a):
return RKHSFun(f.kernel, {x: a * a_cur for x, a_cur in f.alphas.items()})
def _inner_prod(self, f, g):
assert f.kernel is g.kernel
return sum(
[a1 * a2 * f.kernel(x1, x2) for x1, a1 in f.alphas.items() for x2, a2 in g.alphas.items()], 0.0
)
RKHSFunVSpace.register(RKHSFun)
def add_dicts(d1, d2):
d = {}
for k, v in chain(d1.items(), d2.items()):
d[k] = d[k] + v if k in d else v
return d
if __name__ == "__main__":
def sq_exp_kernel(x1, x2):
return np.exp(-((x1 - x2) ** 2))
xs = range(5)
ys = [1, 2, 3, 2, 1]
def logprob(f, xs, ys):
return -sum((f(x) - y) ** 2 for x, y in zip(xs, ys))
f = RKHSFun(sq_exp_kernel)
for i in range(100):
f = f + grad(logprob)(f, xs, ys) * 0.01
for x, y in zip(xs, ys):
print(f"{x}\t{y}\t{f(x)}")
| RKHSFunVSpace |
python | huggingface__transformers | src/transformers/models/roberta_prelayernorm/modeling_roberta_prelayernorm.py | {
"start": 8080,
"end": 11322
} | class ____(nn.Module):
def __init__(self, config, is_causal=False, layer_idx=None):
super().__init__()
if config.hidden_size % config.num_attention_heads != 0 and not hasattr(config, "embedding_size"):
raise ValueError(
f"The hidden size ({config.hidden_size}) is not a multiple of the number of attention "
f"heads ({config.num_attention_heads})"
)
self.config = config
self.num_attention_heads = config.num_attention_heads
self.attention_head_size = int(config.hidden_size / config.num_attention_heads)
self.all_head_size = self.num_attention_heads * self.attention_head_size
self.scaling = self.attention_head_size**-0.5
self.query = nn.Linear(config.hidden_size, self.all_head_size)
self.key = nn.Linear(config.hidden_size, self.all_head_size)
self.value = nn.Linear(config.hidden_size, self.all_head_size)
self.dropout = nn.Dropout(config.attention_probs_dropout_prob)
self.is_decoder = config.is_decoder
self.is_causal = is_causal
self.layer_idx = layer_idx
def forward(
self,
hidden_states: torch.Tensor,
attention_mask: Optional[torch.FloatTensor] = None,
past_key_values: Optional[Cache] = None,
cache_position: Optional[torch.Tensor] = None,
**kwargs: Unpack[TransformersKwargs],
) -> tuple[torch.Tensor]:
input_shape = hidden_states.shape[:-1]
hidden_shape = (*input_shape, -1, self.attention_head_size)
# get all proj
query_layer = self.query(hidden_states).view(*hidden_shape).transpose(1, 2)
key_layer = self.key(hidden_states).view(*hidden_shape).transpose(1, 2)
value_layer = self.value(hidden_states).view(*hidden_shape).transpose(1, 2)
if past_key_values is not None:
# decoder-only bert can have a simple dynamic cache for example
current_past_key_values = past_key_values
if isinstance(past_key_values, EncoderDecoderCache):
current_past_key_values = past_key_values.self_attention_cache
# save all key/value_layer to cache to be re-used for fast auto-regressive generation
key_layer, value_layer = current_past_key_values.update(
key_layer,
value_layer,
self.layer_idx,
{"cache_position": cache_position},
)
attention_interface: Callable = eager_attention_forward
if self.config._attn_implementation != "eager":
attention_interface = ALL_ATTENTION_FUNCTIONS[self.config._attn_implementation]
attn_output, attn_weights = attention_interface(
self,
query_layer,
key_layer,
value_layer,
attention_mask,
dropout=0.0 if not self.training else self.dropout.p,
scaling=self.scaling,
**kwargs,
)
attn_output = attn_output.reshape(*input_shape, -1).contiguous()
return attn_output, attn_weights
# Copied from transformers.models.bert.modeling_bert.BertCrossAttention with Bert->RobertaPreLayerNorm
| RobertaPreLayerNormSelfAttention |
python | getsentry__sentry | tests/snuba/api/endpoints/test_organization_events.py | {
"start": 239152,
"end": 246309
} | class ____(
OrganizationEventsEndpointTestBase, ProfilesSnubaTestCase
):
def test_functions_dataset_simple(self) -> None:
one_hour_ago = before_now(hours=1)
three_hours_ago = before_now(hours=3)
stored_1 = self.store_functions(
[
{
"self_times_ns": [100_000_000 for _ in range(100)],
"package": "foo",
"function": "foo",
"in_app": True,
},
],
project=self.project,
timestamp=three_hours_ago,
)
stored_2 = self.store_functions(
[
{
"self_times_ns": [150_000_000 for _ in range(100)],
"package": "foo",
"function": "foo",
"in_app": True,
},
],
project=self.project,
timestamp=one_hour_ago,
)
stored_3 = self.store_functions_chunk(
[
{
"self_times_ns": [200_000_000 for _ in range(100)],
"package": "bar",
"function": "bar",
"thread_id": "1",
"in_app": True,
},
],
project=self.project,
timestamp=three_hours_ago,
)
stored_4 = self.store_functions_chunk(
[
{
"self_times_ns": [250_000_000 for _ in range(100)],
"package": "bar",
"function": "bar",
"thread_id": "1",
"in_app": True,
},
],
project=self.project,
timestamp=one_hour_ago,
)
mid = before_now(hours=2)
fields = [
"transaction",
"project",
"function",
"package",
"is_application",
"platform.name",
"environment",
"release",
"count()",
"examples()",
"all_examples()",
"p50()",
"p75()",
"p95()",
"p99()",
"avg()",
"sum()",
f"regression_score(function.duration, 0.95, {int(mid.timestamp())})",
]
response = self.do_request(
{
"field": fields,
"statsPeriod": "4h",
"project": [self.project.id],
"dataset": "profileFunctions",
"orderby": "transaction",
},
features={"organizations:profiling": True},
)
assert response.status_code == 200, response.content
# making sure the response keys are in the form we expect and not aliased
data_keys = {key for row in response.data["data"] for key in row}
field_keys = {key for key in response.data["meta"]["fields"]}
unit_keys = {key for key in response.data["meta"]["units"]}
assert set(fields) == data_keys
assert set(fields) == field_keys
assert set(fields) == unit_keys
assert response.data["meta"]["units"] == {
"transaction": None,
"project": None,
"function": None,
"package": None,
"is_application": None,
"platform.name": None,
"environment": None,
"release": None,
"count()": None,
"examples()": None,
"all_examples()": None,
"p50()": "nanosecond",
"p75()": "nanosecond",
"p95()": "nanosecond",
"p99()": "nanosecond",
"avg()": "nanosecond",
"sum()": "nanosecond",
f"regression_score(function.duration, 0.95, {int(mid.timestamp())})": None,
}
def all_examples_sort_key(example):
return example.get("profile_id") or example.get("profiler_id")
for row in response.data["data"]:
row["examples()"].sort()
row["all_examples()"].sort(key=all_examples_sort_key)
transaction_examples = [
stored_1["transaction"]["contexts"]["profile"]["profile_id"],
stored_2["transaction"]["contexts"]["profile"]["profile_id"],
]
transaction_examples.sort()
transaction_all_examples = [
{"profile_id": stored_1["transaction"]["contexts"]["profile"]["profile_id"]},
{"profile_id": stored_2["transaction"]["contexts"]["profile"]["profile_id"]},
]
transaction_all_examples.sort(key=all_examples_sort_key)
continuous_examples = [stored_3["profiler_id"], stored_4["profiler_id"]]
continuous_examples.sort()
continuous_all_examples = [
{
"profiler_id": stored_3["profiler_id"],
"thread_id": "1",
"start": three_hours_ago.timestamp(),
"end": (three_hours_ago + timedelta(microseconds=200_000)).timestamp(),
},
{
"profiler_id": stored_4["profiler_id"],
"thread_id": "1",
"start": one_hour_ago.timestamp(),
"end": (one_hour_ago + timedelta(microseconds=250_000)).timestamp(),
},
]
continuous_all_examples.sort(key=all_examples_sort_key)
assert response.data["data"] == [
{
"transaction": "",
"project": self.project.slug,
"function": "bar",
"package": "bar",
"is_application": 1,
"platform.name": "",
"environment": None,
"release": None,
"count()": 200,
"examples()": continuous_examples,
"all_examples()": continuous_all_examples,
"p50()": 225_000_000.0,
"p75()": 250_000_000.0,
"p95()": 250_000_000.0,
"p99()": 250_000_000.0,
"avg()": 225_000_000.0,
"sum()": 45_000_000_000.0,
f"regression_score(function.duration, 0.95, {int(mid.timestamp())})": mock.ANY,
},
{
"transaction": "/country_by_code/",
"project": self.project.slug,
"function": "foo",
"package": "foo",
"is_application": 1,
"platform.name": "transaction",
"environment": None,
"release": None,
"count()": 200,
"examples()": transaction_examples,
"all_examples()": transaction_all_examples,
"p50()": 125_000_000.0,
"p75()": 150_000_000.0,
"p95()": 150_000_000.0,
"p99()": 150_000_000.0,
"avg()": 125_000_000.0,
"sum()": 25_000_000_000.0,
f"regression_score(function.duration, 0.95, {int(mid.timestamp())})": mock.ANY,
},
]
| OrganizationEventsProfileFunctionsDatasetEndpointTest |
python | google__jax | jax/experimental/jax2tf/tests/flax_models/vae.py | {
"start": 1231,
"end": 1741
} | class ____(nn.Module):
latents: int = 20
def setup(self):
self.encoder = Encoder(self.latents)
self.decoder = Decoder()
def __call__(self, x, z_rng):
mean, logvar = self.encoder(x)
z = reparameterize(z_rng, mean, logvar)
recon_x = self.decoder(z)
return recon_x, mean, logvar
def generate(self, z):
return nn.sigmoid(self.decoder(z))
def reparameterize(rng, mean, logvar):
std = jnp.exp(0.5 * logvar)
eps = random.normal(rng, logvar.shape)
return mean + eps * std
| VAE |
python | tornadoweb__tornado | tornado/test/web_test.py | {
"start": 69237,
"end": 69926
} | class ____(WebTestCase):
def get_handlers(self):
# note that if the handlers list is empty we get the default_host
# redirect fallback instead of a 404, so test with both an
# explicitly defined error handler and an implicit 404.
return [("/error", ErrorHandler, dict(status_code=417))]
def get_app_kwargs(self):
return dict(xsrf_cookies=True)
def test_error_xsrf(self):
response = self.fetch("/error", method="POST", body="")
self.assertEqual(response.code, 417)
def test_404_xsrf(self):
response = self.fetch("/404", method="POST", body="")
self.assertEqual(response.code, 404)
| ErrorHandlerXSRFTest |
python | getsentry__sentry | tests/sentry/hybridcloud/test_organizationmapping.py | {
"start": 8829,
"end": 9477
} | class ____(TransactionTestCase):
def test_replicates_all_flags(self) -> None:
self.organization = self.create_organization(slug="santry", region="us")
self.organization.flags = 255 # all flags set
organization_mapping_service.upsert(
organization_id=self.organization.id,
update=update_organization_mapping_from_instance(
organization=self.organization, region=get_local_region()
),
)
with assume_test_silo_mode(SiloMode.CONTROL):
assert_matching_organization_mapping(self.organization, validate_flags=True)
| OrganizationMappingReplicationTest |
python | tornadoweb__tornado | demos/google_auth/main.py | {
"start": 1977,
"end": 3151
} | class ____(BaseHandler, tornado.auth.GoogleOAuth2Mixin):
async def get(self):
redirect_uri = urllib.parse.urljoin(
self.application.settings["redirect_base_uri"],
self.reverse_url("google_oauth"),
)
if self.get_argument("code", False):
access = await self.get_authenticated_user(
redirect_uri=redirect_uri, code=self.get_argument("code")
)
user = await self.oauth2_request(
"https://www.googleapis.com/oauth2/v1/userinfo",
access_token=access["access_token"],
)
# Save the user and access token.
user_cookie = dict(id=user["id"], access_token=access["access_token"])
self.set_signed_cookie("googledemo_user", json.dumps(user_cookie))
self.redirect("/")
else:
self.authorize_redirect(
redirect_uri=redirect_uri,
client_id=self.get_google_oauth_settings()["key"],
scope=["profile", "email"],
response_type="code",
extra_params={"approval_prompt": "auto"},
)
| LoginHandler |
python | plotly__plotly.py | plotly/graph_objs/barpolar/legendgrouptitle/_font.py | {
"start": 233,
"end": 9932
} | class ____(_BaseTraceHierarchyType):
_parent_path_str = "barpolar.legendgrouptitle"
_path_str = "barpolar.legendgrouptitle.font"
_valid_props = {
"color",
"family",
"lineposition",
"shadow",
"size",
"style",
"textcase",
"variant",
"weight",
}
@property
def color(self):
"""
The 'color' property is a color and may be specified as:
- A hex string (e.g. '#ff0000')
- An rgb/rgba string (e.g. 'rgb(255,0,0)')
- An hsl/hsla string (e.g. 'hsl(0,100%,50%)')
- An hsv/hsva string (e.g. 'hsv(0,100%,100%)')
- A named CSS color: see https://plotly.com/python/css-colors/ for a list
Returns
-------
str
"""
return self["color"]
@color.setter
def color(self, val):
self["color"] = val
@property
def family(self):
"""
HTML font family - the typeface that will be applied by the web
browser. The web browser can only apply a font if it is
available on the system where it runs. Provide multiple font
families, separated by commas, to indicate the order in which
to apply fonts if they aren't available.
The 'family' property is a string and must be specified as:
- A non-empty string
Returns
-------
str
"""
return self["family"]
@family.setter
def family(self, val):
self["family"] = val
@property
def lineposition(self):
"""
Sets the kind of decoration line(s) with text, such as an
"under", "over" or "through" as well as combinations e.g.
"under+over", etc.
The 'lineposition' property is a flaglist and may be specified
as a string containing:
- Any combination of ['under', 'over', 'through'] joined with '+' characters
(e.g. 'under+over')
OR exactly one of ['none'] (e.g. 'none')
Returns
-------
Any
"""
return self["lineposition"]
@lineposition.setter
def lineposition(self, val):
self["lineposition"] = val
@property
def shadow(self):
"""
Sets the shape and color of the shadow behind text. "auto"
places minimal shadow and applies contrast text font color. See
https://developer.mozilla.org/en-US/docs/Web/CSS/text-shadow
for additional options.
The 'shadow' property is a string and must be specified as:
- A string
- A number that will be converted to a string
Returns
-------
str
"""
return self["shadow"]
@shadow.setter
def shadow(self, val):
self["shadow"] = val
@property
def size(self):
"""
The 'size' property is a number and may be specified as:
- An int or float in the interval [1, inf]
Returns
-------
int|float
"""
return self["size"]
@size.setter
def size(self, val):
self["size"] = val
@property
def style(self):
"""
Sets whether a font should be styled with a normal or italic
face from its family.
The 'style' property is an enumeration that may be specified as:
- One of the following enumeration values:
['normal', 'italic']
Returns
-------
Any
"""
return self["style"]
@style.setter
def style(self, val):
self["style"] = val
@property
def textcase(self):
"""
Sets capitalization of text. It can be used to make text appear
in all-uppercase or all-lowercase, or with each word
capitalized.
The 'textcase' property is an enumeration that may be specified as:
- One of the following enumeration values:
['normal', 'word caps', 'upper', 'lower']
Returns
-------
Any
"""
return self["textcase"]
@textcase.setter
def textcase(self, val):
self["textcase"] = val
@property
def variant(self):
"""
Sets the variant of the font.
The 'variant' property is an enumeration that may be specified as:
- One of the following enumeration values:
['normal', 'small-caps', 'all-small-caps',
'all-petite-caps', 'petite-caps', 'unicase']
Returns
-------
Any
"""
return self["variant"]
@variant.setter
def variant(self, val):
self["variant"] = val
@property
def weight(self):
"""
Sets the weight (or boldness) of the font.
The 'weight' property is a integer and may be specified as:
- An int (or float that will be cast to an int)
in the interval [1, 1000]
OR exactly one of ['normal', 'bold'] (e.g. 'bold')
Returns
-------
int
"""
return self["weight"]
@weight.setter
def weight(self, val):
self["weight"] = val
@property
def _prop_descriptions(self):
return """\
color
family
HTML font family - the typeface that will be applied by
the web browser. The web browser can only apply a font
if it is available on the system where it runs. Provide
multiple font families, separated by commas, to
indicate the order in which to apply fonts if they
aren't available.
lineposition
Sets the kind of decoration line(s) with text, such as
an "under", "over" or "through" as well as combinations
e.g. "under+over", etc.
shadow
Sets the shape and color of the shadow behind text.
"auto" places minimal shadow and applies contrast text
font color. See https://developer.mozilla.org/en-
US/docs/Web/CSS/text-shadow for additional options.
size
style
Sets whether a font should be styled with a normal or
italic face from its family.
textcase
Sets capitalization of text. It can be used to make
text appear in all-uppercase or all-lowercase, or with
each word capitalized.
variant
Sets the variant of the font.
weight
Sets the weight (or boldness) of the font.
"""
def __init__(
self,
arg=None,
color=None,
family=None,
lineposition=None,
shadow=None,
size=None,
style=None,
textcase=None,
variant=None,
weight=None,
**kwargs,
):
"""
Construct a new Font object
Sets this legend group's title font.
Parameters
----------
arg
dict of properties compatible with this constructor or
an instance of :class:`plotly.graph_objs.barpolar.legen
dgrouptitle.Font`
color
family
HTML font family - the typeface that will be applied by
the web browser. The web browser can only apply a font
if it is available on the system where it runs. Provide
multiple font families, separated by commas, to
indicate the order in which to apply fonts if they
aren't available.
lineposition
Sets the kind of decoration line(s) with text, such as
an "under", "over" or "through" as well as combinations
e.g. "under+over", etc.
shadow
Sets the shape and color of the shadow behind text.
"auto" places minimal shadow and applies contrast text
font color. See https://developer.mozilla.org/en-
US/docs/Web/CSS/text-shadow for additional options.
size
style
Sets whether a font should be styled with a normal or
italic face from its family.
textcase
Sets capitalization of text. It can be used to make
text appear in all-uppercase or all-lowercase, or with
each word capitalized.
variant
Sets the variant of the font.
weight
Sets the weight (or boldness) of the font.
Returns
-------
Font
"""
super().__init__("font")
if "_parent" in kwargs:
self._parent = kwargs["_parent"]
return
if arg is None:
arg = {}
elif isinstance(arg, self.__class__):
arg = arg.to_plotly_json()
elif isinstance(arg, dict):
arg = _copy.copy(arg)
else:
raise ValueError("""\
The first argument to the plotly.graph_objs.barpolar.legendgrouptitle.Font
constructor must be a dict or
an instance of :class:`plotly.graph_objs.barpolar.legendgrouptitle.Font`""")
self._skip_invalid = kwargs.pop("skip_invalid", False)
self._validate = kwargs.pop("_validate", True)
self._set_property("color", arg, color)
self._set_property("family", arg, family)
self._set_property("lineposition", arg, lineposition)
self._set_property("shadow", arg, shadow)
self._set_property("size", arg, size)
self._set_property("style", arg, style)
self._set_property("textcase", arg, textcase)
self._set_property("variant", arg, variant)
self._set_property("weight", arg, weight)
self._process_kwargs(**dict(arg, **kwargs))
self._skip_invalid = False
| Font |
python | pytorch__pytorch | tools/linter/adapters/no_workflows_on_fork.py | {
"start": 1174,
"end": 7054
} | class ____(NamedTuple):
path: str | None
line: int | None
char: int | None
code: str
severity: LintSeverity
name: str
original: str | None
replacement: str | None
description: str | None
def load_yaml(path: Path) -> Any:
with open(path) as f:
return load(f, Loader)
def gen_lint_message(
filename: str | None = None,
original: str | None = None,
replacement: str | None = None,
description: str | None = None,
) -> LintMessage:
return LintMessage(
path=filename,
line=None,
char=None,
code="NO_WORKFLOWS_ON_FORK",
severity=LintSeverity.ERROR,
name="format",
original=original,
replacement=replacement,
description=description,
)
def check_file(filename: str) -> list[LintMessage]:
logging.debug("Checking file %s", filename)
workflow = load_yaml(Path(filename))
bad_jobs: dict[str, str | None] = {}
if type(workflow) is not dict:
return []
# yaml parses "on" as True
triggers = workflow.get(True, {})
triggers_to_check = ["push", "schedule", "pull_request", "pull_request_target"]
if not any(trigger in triggers_to_check for trigger in triggers):
return []
jobs = workflow.get("jobs", {})
for job, definition in jobs.items():
if definition.get("needs"):
# The parent job will have the if statement
continue
if_statement = definition.get("if")
if if_statement is None:
bad_jobs[job] = None
elif type(if_statement) is bool and not if_statement:
# if: false
pass
else:
if_statement = str(if_statement)
valid_checks: list[Callable[[str], bool]] = [
lambda x: "github.repository == 'pytorch/pytorch'" in x
and "github.event_name != 'schedule' || github.repository == 'pytorch/pytorch'"
not in x,
lambda x: "github.repository_owner == 'pytorch'" in x,
]
if not any(f(if_statement) for f in valid_checks):
bad_jobs[job] = if_statement
with open(filename) as f:
lines = f.readlines()
smart_enough = True
original = "".join(lines)
iterator = iter(range(len(lines)))
replacement = ""
for i in iterator:
line = lines[i]
# Search for job name
re_match = re.match(r"( +)([-_\w]*):", line)
if not re_match or re_match.group(2) not in bad_jobs:
replacement += line
continue
job_name = re_match.group(2)
failure_type = bad_jobs[job_name]
if failure_type is None:
# Just need to add an if statement
replacement += (
f"{line}{re_match.group(1)} if: github.repository_owner == 'pytorch'\n"
)
continue
# Search for if statement
while re.match(r"^ +if:", line) is None:
replacement += line
i = next(iterator)
line = lines[i]
if i + 1 < len(lines) and not re.match(r"^ +(.*):", lines[i + 1]):
# This is a multi line if statement
smart_enough = False
break
if_statement_match = re.match(r"^ +if: ([^#]*)(#.*)?$", line)
# Get ... in if: ... # comments
if not if_statement_match:
return [
gen_lint_message(
description=f"Something went wrong when looking at {job_name}.",
)
]
if_statement = if_statement_match.group(1).strip()
# Handle comment in if: ... # comments
comments = if_statement_match.group(2) or ""
if comments:
comments = " " + comments
# Too broad of a check, but should catch everything
needs_parens = "||" in if_statement
# Handle ${{ ... }}
has_brackets = re.match(r"\$\{\{(.*)\}\}", if_statement)
internal_statement = (
has_brackets.group(1).strip() if has_brackets else if_statement
)
if needs_parens:
internal_statement = f"({internal_statement})"
new_line = f"{internal_statement} && github.repository_owner == 'pytorch'"
# I don't actually know if we need the ${{ }} but do it just in case
new_line = "${{ " + new_line + " }}" + comments
replacement += f"{re_match.group(1)} if: {new_line}\n"
description = (
"Please add checks for if: github.repository_owner == 'pytorch' in the following jobs in this file: "
+ ", ".join(job for job in bad_jobs)
)
if not smart_enough:
return [
gen_lint_message(
filename=filename,
description=description,
)
]
if replacement == original:
return []
return [
gen_lint_message(
filename=filename,
original=original,
replacement=replacement,
description=description,
)
]
if __name__ == "__main__":
parser = argparse.ArgumentParser(
description="workflow consistency linter.",
fromfile_prefix_chars="@",
)
parser.add_argument(
"filenames",
nargs="+",
help="paths to lint",
)
args = parser.parse_args()
with concurrent.futures.ProcessPoolExecutor(
max_workers=os.cpu_count(),
) as executor:
futures = {executor.submit(check_file, x): x for x in args.filenames}
for future in concurrent.futures.as_completed(futures):
try:
for lint_message in future.result():
print(json.dumps(lint_message._asdict()), flush=True)
except Exception:
logging.critical('Failed at "%s".', futures[future])
raise
| LintMessage |
python | joke2k__faker | faker/providers/job/ar_AA/__init__.py | {
"start": 42,
"end": 2725
} | class ____(BaseProvider):
# Source: https://learnenglish100.com/grammar/career-job/
jobs = (
"أحيائي",
"احصائي",
"اطفائي",
"بائع",
"بائع خضار وفاكهة",
"بائع زهور",
"بائعة",
"بواب",
"تاجر",
"جزار",
"جوھري",
"جيولوجي",
"حداد",
"حلاق",
"خادمة",
"خباز",
"خبير اقتصادي",
"خبير في التراث الشعبي",
"خبير في عالم الحيوان",
"خراط",
"خياط",
"خياطة",
"داية",
"رئيس طهاه",
"راقصة",
"راقصة باليه",
"رجل مباحث",
"رسام",
"روائي",
"سائق",
"سائق تاكسي",
"سائق شاحنة",
"ساعاتي",
"ساعي بريد",
"سكرتير",
"سكرتيرة",
"سمكري",
"سياسي",
"شاعر",
"شرطي",
"صائغ",
"صاحب متجر",
"صاحب مطبعة",
"صاحب مكتبة",
"صانع أدوات بصرية",
"صباغ",
"صباغ أحذية",
"صحافي",
"صحفي",
"صراف",
"صيدلي",
"ضابط شرطة",
"ضارب على الآلة الكاتبة",
"طباخ",
"طبيب",
"طبيب أسنان",
"طبيب جراح",
"طبيب عيون",
"طبيب نفساني",
"طيار",
"عارضة أزياء",
"عالم",
"عالم أرصاد جوية",
"عالم اثار",
"عالم رياضيات",
"عالم فيزياء",
"عامل",
"عامل أحذية",
"عامل بمتجر",
"عامل بناء",
"غسالة",
"فنان",
"فيلسوف",
"قائد شرطة",
"قاضي",
"كاتب",
"كاتب مسرحي",
"لغوي",
"مؤلف",
"ماسح احذية",
"مبرمج",
"مترجم",
"مجلد كتب",
"محاسب",
"محاضر",
"محام",
"محرر",
"محرر جريدة",
"مدير",
"مدير او مخرج",
"مدير بنك",
"مدير تسويق",
"مدير متجر",
"مدير موظفين",
"مذيع",
"مساعد مبيعات",
"مشتري",
"مصحح قانوني",
"مصصم",
"مصفف شعر",
"مصمم جرافيك",
"مصمم ديكور",
"مصور",
"مضيفة جوية",
"مضيفة في الطائرة",
"مطرب",
"معالج طبيعي",
"معلم",
"مغني",
"مكوى",
"ملحن",
"ممثل",
"ممثلة",
"ممرضة",
"منتج",
"منجد",
"منسق ازياء",
"موزع جرائد",
"موسيقار",
"موصل طلبيات",
"موظف استقبال",
"موظف بدالة",
"موظف حكومي",
"ميكانيكي",
"مھندس",
"نادلة",
"ناشر",
"نباتي",
"نجار",
"نحات",
"وسيط تأمين",
"وكيل سفر",
"وكيل عقارات",
)
| Provider |
python | huggingface__transformers | src/transformers/models/mask2former/modeling_mask2former.py | {
"start": 106228,
"end": 117183
} | class ____(Mask2FormerPreTrainedModel):
main_input_name = "pixel_values"
def __init__(self, config: Mask2FormerConfig):
super().__init__(config)
self.model = Mask2FormerModel(config)
self.weight_dict: dict[str, float] = {
"loss_cross_entropy": config.class_weight,
"loss_mask": config.mask_weight,
"loss_dice": config.dice_weight,
}
self.class_predictor = nn.Linear(config.hidden_dim, config.num_labels + 1)
self.criterion = Mask2FormerLoss(config=config, weight_dict=self.weight_dict)
self.post_init()
def get_loss_dict(
self,
masks_queries_logits: Tensor,
class_queries_logits: Tensor,
mask_labels: Tensor,
class_labels: Tensor,
auxiliary_predictions: dict[str, Tensor],
) -> dict[str, Tensor]:
loss_dict: dict[str, Tensor] = self.criterion(
masks_queries_logits=masks_queries_logits,
class_queries_logits=class_queries_logits,
mask_labels=mask_labels,
class_labels=class_labels,
auxiliary_predictions=auxiliary_predictions,
)
# weight each loss by `self.weight_dict[<LOSS_NAME>]` including auxiliary losses
for key, weight in self.weight_dict.items():
for loss_key, loss in loss_dict.items():
if key in loss_key:
loss *= weight
return loss_dict
def get_loss(self, loss_dict: dict[str, Tensor]) -> Tensor:
return sum(loss_dict.values())
def get_auxiliary_logits(self, classes: torch.Tensor, output_masks: torch.Tensor):
auxiliary_logits: list[dict[str, Tensor]] = []
for aux_binary_masks, aux_classes in zip(output_masks[:-1], classes[:-1]):
auxiliary_logits.append({"masks_queries_logits": aux_binary_masks, "class_queries_logits": aux_classes})
return auxiliary_logits
@auto_docstring
def forward(
self,
pixel_values: Tensor,
mask_labels: Optional[list[Tensor]] = None,
class_labels: Optional[list[Tensor]] = None,
pixel_mask: Optional[Tensor] = None,
output_hidden_states: Optional[bool] = None,
output_auxiliary_logits: Optional[bool] = None,
output_attentions: Optional[bool] = None,
return_dict: Optional[bool] = None,
) -> Mask2FormerForUniversalSegmentationOutput:
r"""
mask_labels (`list[torch.Tensor]`, *optional*):
List of mask labels of shape `(num_labels, height, width)` to be fed to a model
class_labels (`list[torch.LongTensor]`, *optional*):
list of target class labels of shape `(num_labels, height, width)` to be fed to a model. They identify the
labels of `mask_labels`, e.g. the label of `mask_labels[i][j]` if `class_labels[i][j]`.
output_auxiliary_logits (`bool`, *optional*):
Whether or not to output auxiliary logits.
Examples:
Instance segmentation example:
```python
>>> from transformers import AutoImageProcessor, Mask2FormerForUniversalSegmentation
>>> from PIL import Image
>>> import requests
>>> import torch
>>> # Load Mask2Former trained on COCO instance segmentation dataset
>>> image_processor = AutoImageProcessor.from_pretrained("facebook/mask2former-swin-small-coco-instance")
>>> model = Mask2FormerForUniversalSegmentation.from_pretrained(
... "facebook/mask2former-swin-small-coco-instance"
... )
>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
>>> image = Image.open(requests.get(url, stream=True).raw)
>>> inputs = image_processor(image, return_tensors="pt")
>>> with torch.no_grad():
... outputs = model(**inputs)
>>> # Model predicts class_queries_logits of shape `(batch_size, num_queries)`
>>> # and masks_queries_logits of shape `(batch_size, num_queries, height, width)`
>>> class_queries_logits = outputs.class_queries_logits
>>> masks_queries_logits = outputs.masks_queries_logits
>>> # Perform post-processing to get instance segmentation map
>>> pred_instance_map = image_processor.post_process_instance_segmentation(
... outputs, target_sizes=[(image.height, image.width)]
... )[0]
>>> print(pred_instance_map.shape)
torch.Size([480, 640])
```
Semantic segmentation example:
```python
>>> from transformers import AutoImageProcessor, Mask2FormerForUniversalSegmentation
>>> from PIL import Image
>>> import requests
>>> import torch
>>> # Load Mask2Former trained on ADE20k semantic segmentation dataset
>>> image_processor = AutoImageProcessor.from_pretrained("facebook/mask2former-swin-small-ade-semantic")
>>> model = Mask2FormerForUniversalSegmentation.from_pretrained("facebook/mask2former-swin-small-ade-semantic")
>>> url = (
... "https://huggingface.co/datasets/hf-internal-testing/fixtures_ade20k/resolve/main/ADE_val_00000001.jpg"
... )
>>> image = Image.open(requests.get(url, stream=True).raw)
>>> inputs = image_processor(image, return_tensors="pt")
>>> with torch.no_grad():
... outputs = model(**inputs)
>>> # Model predicts class_queries_logits of shape `(batch_size, num_queries)`
>>> # and masks_queries_logits of shape `(batch_size, num_queries, height, width)`
>>> class_queries_logits = outputs.class_queries_logits
>>> masks_queries_logits = outputs.masks_queries_logits
>>> # Perform post-processing to get semantic segmentation map
>>> pred_semantic_map = image_processor.post_process_semantic_segmentation(
... outputs, target_sizes=[(image.height, image.width)]
... )[0]
>>> print(pred_semantic_map.shape)
torch.Size([512, 683])
```
Panoptic segmentation example:
```python
>>> from transformers import AutoImageProcessor, Mask2FormerForUniversalSegmentation
>>> from PIL import Image
>>> import requests
>>> import torch
>>> # Load Mask2Former trained on CityScapes panoptic segmentation dataset
>>> image_processor = AutoImageProcessor.from_pretrained("facebook/mask2former-swin-small-cityscapes-panoptic")
>>> model = Mask2FormerForUniversalSegmentation.from_pretrained(
... "facebook/mask2former-swin-small-cityscapes-panoptic"
... )
>>> url = "https://cdn-media.huggingface.co/Inference-API/Sample-results-on-the-Cityscapes-dataset-The-above-images-show-how-our-method-can-handle.png"
>>> image = Image.open(requests.get(url, stream=True).raw)
>>> inputs = image_processor(image, return_tensors="pt")
>>> with torch.no_grad():
... outputs = model(**inputs)
>>> # Model predicts class_queries_logits of shape `(batch_size, num_queries)`
>>> # and masks_queries_logits of shape `(batch_size, num_queries, height, width)`
>>> class_queries_logits = outputs.class_queries_logits
>>> masks_queries_logits = outputs.masks_queries_logits
>>> # Perform post-processing to get panoptic segmentation map
>>> pred_panoptic_map = image_processor.post_process_panoptic_segmentation(
... outputs, target_sizes=[(image.height, image.width)]
... )[0]["segmentation"]
>>> print(pred_panoptic_map.shape)
torch.Size([338, 676])
```
"""
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
output_hidden_states = (
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
)
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
outputs = self.model(
pixel_values=pixel_values,
pixel_mask=pixel_mask,
output_hidden_states=output_hidden_states or self.config.use_auxiliary_loss,
output_attentions=output_attentions,
return_dict=True,
)
loss, loss_dict, auxiliary_logits = None, None, None
class_queries_logits = ()
for decoder_output in outputs.transformer_decoder_intermediate_states:
class_prediction = self.class_predictor(decoder_output.transpose(0, 1))
class_queries_logits += (class_prediction,)
masks_queries_logits = outputs.masks_queries_logits
auxiliary_logits = self.get_auxiliary_logits(class_queries_logits, masks_queries_logits)
if mask_labels is not None and class_labels is not None:
loss_dict = self.get_loss_dict(
masks_queries_logits=masks_queries_logits[-1],
class_queries_logits=class_queries_logits[-1],
mask_labels=mask_labels,
class_labels=class_labels,
auxiliary_predictions=auxiliary_logits,
)
loss = self.get_loss(loss_dict)
encoder_hidden_states = None
pixel_decoder_hidden_states = None
transformer_decoder_hidden_states = None
if output_hidden_states:
encoder_hidden_states = outputs.encoder_hidden_states
pixel_decoder_hidden_states = outputs.pixel_decoder_hidden_states
transformer_decoder_hidden_states = outputs.transformer_decoder_hidden_states
output_auxiliary_logits = (
self.config.output_auxiliary_logits if output_auxiliary_logits is None else output_auxiliary_logits
)
if not output_auxiliary_logits:
auxiliary_logits = None
output = Mask2FormerForUniversalSegmentationOutput(
loss=loss,
class_queries_logits=class_queries_logits[-1],
masks_queries_logits=masks_queries_logits[-1],
auxiliary_logits=auxiliary_logits,
encoder_last_hidden_state=outputs.encoder_last_hidden_state,
pixel_decoder_last_hidden_state=outputs.pixel_decoder_last_hidden_state,
transformer_decoder_last_hidden_state=outputs.transformer_decoder_last_hidden_state,
encoder_hidden_states=encoder_hidden_states,
pixel_decoder_hidden_states=pixel_decoder_hidden_states,
transformer_decoder_hidden_states=transformer_decoder_hidden_states,
attentions=outputs.attentions,
)
if not return_dict:
output = tuple(v for v in output.values() if v is not None)
if loss is not None:
output = (loss) + output
return output
__all__ = ["Mask2FormerForUniversalSegmentation", "Mask2FormerModel", "Mask2FormerPreTrainedModel"]
| Mask2FormerForUniversalSegmentation |
python | FactoryBoy__factory_boy | factory/alchemy.py | {
"start": 1601,
"end": 4679
} | class ____(base.Factory):
"""Factory for SQLAlchemy models. """
_options_class = SQLAlchemyOptions
_original_params = None
class Meta:
abstract = True
@classmethod
def _generate(cls, strategy, params):
# Original params are used in _get_or_create if it cannot build an
# object initially due to an IntegrityError being raised
cls._original_params = params
return super()._generate(strategy, params)
@classmethod
def _get_or_create(cls, model_class, session, args, kwargs):
key_fields = {}
for field in cls._meta.sqlalchemy_get_or_create:
if field not in kwargs:
raise errors.FactoryError(
"sqlalchemy_get_or_create - "
"Unable to find initialization value for '%s' in factory %s" %
(field, cls.__name__))
key_fields[field] = kwargs.pop(field)
obj = session.query(model_class).filter_by(
*args, **key_fields).one_or_none()
if not obj:
try:
obj = cls._save(model_class, session, args, {**key_fields, **kwargs})
except IntegrityError as e:
session.rollback()
if cls._original_params is None:
raise e
get_or_create_params = {
lookup: value
for lookup, value in cls._original_params.items()
if lookup in cls._meta.sqlalchemy_get_or_create
}
if get_or_create_params:
try:
obj = session.query(model_class).filter_by(
**get_or_create_params).one()
except NoResultFound:
# Original params are not a valid lookup and triggered a create(),
# that resulted in an IntegrityError.
raise e
else:
raise e
return obj
@classmethod
def _create(cls, model_class, *args, **kwargs):
"""Create an instance of the model, and save it to the database."""
session_factory = cls._meta.sqlalchemy_session_factory
if session_factory:
cls._meta.sqlalchemy_session = session_factory()
session = cls._meta.sqlalchemy_session
if session is None:
raise RuntimeError("No session provided.")
if cls._meta.sqlalchemy_get_or_create:
return cls._get_or_create(model_class, session, args, kwargs)
return cls._save(model_class, session, args, kwargs)
@classmethod
def _save(cls, model_class, session, args, kwargs):
session_persistence = cls._meta.sqlalchemy_session_persistence
obj = model_class(*args, **kwargs)
session.add(obj)
if session_persistence == SESSION_PERSISTENCE_FLUSH:
session.flush()
elif session_persistence == SESSION_PERSISTENCE_COMMIT:
session.commit()
return obj
| SQLAlchemyModelFactory |
python | getsentry__sentry | src/sentry/toolbar/views/login_success_view.py | {
"start": 275,
"end": 840
} | class ____(OrganizationView):
def get(self, request: HttpRequest, organization, project_id_or_slug):
delay_ms = int(request.GET.get("delay") or 3000)
return self.respond(
TEMPLATE,
status=200,
context={
"organization_slug": organization.slug,
"delay_sec": int(delay_ms / 1000),
"delay_ms": delay_ms,
"cookie": f"{session_cookie_name}={request.COOKIES.get(session_cookie_name)}",
"token": "",
},
)
| LoginSuccessView |
python | scrapy__scrapy | scrapy/signalmanager.py | {
"start": 240,
"end": 3665
} | class ____:
def __init__(self, sender: Any = dispatcher.Anonymous):
self.sender: Any = sender
def connect(self, receiver: Any, signal: Any, **kwargs: Any) -> None:
"""
Connect a receiver function to a signal.
The signal can be any object, although Scrapy comes with some
predefined signals that are documented in the :ref:`topics-signals`
section.
:param receiver: the function to be connected
:type receiver: collections.abc.Callable
:param signal: the signal to connect to
:type signal: object
"""
kwargs.setdefault("sender", self.sender)
dispatcher.connect(receiver, signal, **kwargs)
def disconnect(self, receiver: Any, signal: Any, **kwargs: Any) -> None:
"""
Disconnect a receiver function from a signal. This has the
opposite effect of the :meth:`connect` method, and the arguments
are the same.
"""
kwargs.setdefault("sender", self.sender)
dispatcher.disconnect(receiver, signal, **kwargs)
def send_catch_log(self, signal: Any, **kwargs: Any) -> list[tuple[Any, Any]]:
"""
Send a signal, catch exceptions and log them.
The keyword arguments are passed to the signal handlers (connected
through the :meth:`connect` method).
"""
kwargs.setdefault("sender", self.sender)
return _signal.send_catch_log(signal, **kwargs)
def send_catch_log_deferred(
self, signal: Any, **kwargs: Any
) -> Deferred[list[tuple[Any, Any]]]:
"""
Like :meth:`send_catch_log` but supports :ref:`asynchronous signal
handlers <signal-deferred>`.
Returns a Deferred that gets fired once all signal handlers
have finished. Send a signal, catch exceptions and log them.
The keyword arguments are passed to the signal handlers (connected
through the :meth:`connect` method).
"""
kwargs.setdefault("sender", self.sender)
return _signal.send_catch_log_deferred(signal, **kwargs)
async def send_catch_log_async(
self, signal: Any, **kwargs: Any
) -> list[tuple[Any, Any]]:
"""
Like :meth:`send_catch_log` but supports :ref:`asynchronous signal
handlers <signal-deferred>`.
Returns a coroutine that completes once all signal handlers
have finished. Send a signal, catch exceptions and log them.
The keyword arguments are passed to the signal handlers (connected
through the :meth:`connect` method).
.. versionadded:: VERSION
"""
kwargs.setdefault("sender", self.sender)
return await _signal.send_catch_log_async(signal, **kwargs)
def disconnect_all(self, signal: Any, **kwargs: Any) -> None:
"""
Disconnect all receivers from the given signal.
:param signal: the signal to disconnect from
:type signal: object
"""
kwargs.setdefault("sender", self.sender)
_signal.disconnect_all(signal, **kwargs)
async def wait_for(self, signal):
"""Await the next *signal*.
See :ref:`start-requests-lazy` for an example.
"""
d = Deferred()
def handle():
self.disconnect(handle, signal)
d.callback(None)
self.connect(handle, signal)
await maybe_deferred_to_future(d)
| SignalManager |
python | plotly__plotly.py | plotly/graph_objs/scattergl/marker/colorbar/_tickformatstop.py | {
"start": 233,
"end": 8559
} | class ____(_BaseTraceHierarchyType):
_parent_path_str = "scattergl.marker.colorbar"
_path_str = "scattergl.marker.colorbar.tickformatstop"
_valid_props = {"dtickrange", "enabled", "name", "templateitemname", "value"}
@property
def dtickrange(self):
"""
range [*min*, *max*], where "min", "max" - dtick values which
describe some zoom level, it is possible to omit "min" or "max"
value by passing "null"
The 'dtickrange' property is an info array that may be specified as:
* a list or tuple of 2 elements where:
(0) The 'dtickrange[0]' property accepts values of any type
(1) The 'dtickrange[1]' property accepts values of any type
Returns
-------
list
"""
return self["dtickrange"]
@dtickrange.setter
def dtickrange(self, val):
self["dtickrange"] = val
@property
def enabled(self):
"""
Determines whether or not this stop is used. If `false`, this
stop is ignored even within its `dtickrange`.
The 'enabled' property must be specified as a bool
(either True, or False)
Returns
-------
bool
"""
return self["enabled"]
@enabled.setter
def enabled(self, val):
self["enabled"] = val
@property
def name(self):
"""
When used in a template, named items are created in the output
figure in addition to any items the figure already has in this
array. You can modify these items in the output figure by
making your own item with `templateitemname` matching this
`name` alongside your modifications (including `visible: false`
or `enabled: false` to hide it). Has no effect outside of a
template.
The 'name' property is a string and must be specified as:
- A string
- A number that will be converted to a string
Returns
-------
str
"""
return self["name"]
@name.setter
def name(self, val):
self["name"] = val
@property
def templateitemname(self):
"""
Used to refer to a named item in this array in the template.
Named items from the template will be created even without a
matching item in the input figure, but you can modify one by
making an item with `templateitemname` matching its `name`,
alongside your modifications (including `visible: false` or
`enabled: false` to hide it). If there is no template or no
matching item, this item will be hidden unless you explicitly
show it with `visible: true`.
The 'templateitemname' property is a string and must be specified as:
- A string
- A number that will be converted to a string
Returns
-------
str
"""
return self["templateitemname"]
@templateitemname.setter
def templateitemname(self, val):
self["templateitemname"] = val
@property
def value(self):
"""
string - dtickformat for described zoom level, the same as
"tickformat"
The 'value' property is a string and must be specified as:
- A string
- A number that will be converted to a string
Returns
-------
str
"""
return self["value"]
@value.setter
def value(self, val):
self["value"] = val
@property
def _prop_descriptions(self):
return """\
dtickrange
range [*min*, *max*], where "min", "max" - dtick values
which describe some zoom level, it is possible to omit
"min" or "max" value by passing "null"
enabled
Determines whether or not this stop is used. If
`false`, this stop is ignored even within its
`dtickrange`.
name
When used in a template, named items are created in the
output figure in addition to any items the figure
already has in this array. You can modify these items
in the output figure by making your own item with
`templateitemname` matching this `name` alongside your
modifications (including `visible: false` or `enabled:
false` to hide it). Has no effect outside of a
template.
templateitemname
Used to refer to a named item in this array in the
template. Named items from the template will be created
even without a matching item in the input figure, but
you can modify one by making an item with
`templateitemname` matching its `name`, alongside your
modifications (including `visible: false` or `enabled:
false` to hide it). If there is no template or no
matching item, this item will be hidden unless you
explicitly show it with `visible: true`.
value
string - dtickformat for described zoom level, the same
as "tickformat"
"""
def __init__(
self,
arg=None,
dtickrange=None,
enabled=None,
name=None,
templateitemname=None,
value=None,
**kwargs,
):
"""
Construct a new Tickformatstop object
Parameters
----------
arg
dict of properties compatible with this constructor or
an instance of :class:`plotly.graph_objs.scattergl.mark
er.colorbar.Tickformatstop`
dtickrange
range [*min*, *max*], where "min", "max" - dtick values
which describe some zoom level, it is possible to omit
"min" or "max" value by passing "null"
enabled
Determines whether or not this stop is used. If
`false`, this stop is ignored even within its
`dtickrange`.
name
When used in a template, named items are created in the
output figure in addition to any items the figure
already has in this array. You can modify these items
in the output figure by making your own item with
`templateitemname` matching this `name` alongside your
modifications (including `visible: false` or `enabled:
false` to hide it). Has no effect outside of a
template.
templateitemname
Used to refer to a named item in this array in the
template. Named items from the template will be created
even without a matching item in the input figure, but
you can modify one by making an item with
`templateitemname` matching its `name`, alongside your
modifications (including `visible: false` or `enabled:
false` to hide it). If there is no template or no
matching item, this item will be hidden unless you
explicitly show it with `visible: true`.
value
string - dtickformat for described zoom level, the same
as "tickformat"
Returns
-------
Tickformatstop
"""
super().__init__("tickformatstops")
if "_parent" in kwargs:
self._parent = kwargs["_parent"]
return
if arg is None:
arg = {}
elif isinstance(arg, self.__class__):
arg = arg.to_plotly_json()
elif isinstance(arg, dict):
arg = _copy.copy(arg)
else:
raise ValueError("""\
The first argument to the plotly.graph_objs.scattergl.marker.colorbar.Tickformatstop
constructor must be a dict or
an instance of :class:`plotly.graph_objs.scattergl.marker.colorbar.Tickformatstop`""")
self._skip_invalid = kwargs.pop("skip_invalid", False)
self._validate = kwargs.pop("_validate", True)
self._set_property("dtickrange", arg, dtickrange)
self._set_property("enabled", arg, enabled)
self._set_property("name", arg, name)
self._set_property("templateitemname", arg, templateitemname)
self._set_property("value", arg, value)
self._process_kwargs(**dict(arg, **kwargs))
self._skip_invalid = False
| Tickformatstop |
python | pypa__pipenv | pipenv/vendor/packaging/_manylinux.py | {
"start": 2316,
"end": 9586
} | class ____(NamedTuple):
major: int
minor: int
def _glibc_version_string_confstr() -> str | None:
"""
Primary implementation of glibc_version_string using os.confstr.
"""
# os.confstr is quite a bit faster than ctypes.DLL. It's also less likely
# to be broken or missing. This strategy is used in the standard library
# platform module.
# https://github.com/python/cpython/blob/fcf1d003bf4f0100c/Lib/platform.py#L175-L183
try:
# Should be a string like "glibc 2.17".
version_string: str | None = os.confstr("CS_GNU_LIBC_VERSION")
assert version_string is not None
_, version = version_string.rsplit()
except (AssertionError, AttributeError, OSError, ValueError):
# os.confstr() or CS_GNU_LIBC_VERSION not available (or a bad value)...
return None
return version
def _glibc_version_string_ctypes() -> str | None:
"""
Fallback implementation of glibc_version_string using ctypes.
"""
try:
import ctypes
except ImportError:
return None
# ctypes.CDLL(None) internally calls dlopen(NULL), and as the dlopen
# manpage says, "If filename is NULL, then the returned handle is for the
# main program". This way we can let the linker do the work to figure out
# which libc our process is actually using.
#
# We must also handle the special case where the executable is not a
# dynamically linked executable. This can occur when using musl libc,
# for example. In this situation, dlopen() will error, leading to an
# OSError. Interestingly, at least in the case of musl, there is no
# errno set on the OSError. The single string argument used to construct
# OSError comes from libc itself and is therefore not portable to
# hard code here. In any case, failure to call dlopen() means we
# can proceed, so we bail on our attempt.
try:
process_namespace = ctypes.CDLL(None)
except OSError:
return None
try:
gnu_get_libc_version = process_namespace.gnu_get_libc_version
except AttributeError:
# Symbol doesn't exist -> therefore, we are not linked to
# glibc.
return None
# Call gnu_get_libc_version, which returns a string like "2.5"
gnu_get_libc_version.restype = ctypes.c_char_p
version_str: str = gnu_get_libc_version()
# py2 / py3 compatibility:
if not isinstance(version_str, str):
version_str = version_str.decode("ascii")
return version_str
def _glibc_version_string() -> str | None:
"""Returns glibc version string, or None if not using glibc."""
return _glibc_version_string_confstr() or _glibc_version_string_ctypes()
def _parse_glibc_version(version_str: str) -> tuple[int, int]:
"""Parse glibc version.
We use a regexp instead of str.split because we want to discard any
random junk that might come after the minor version -- this might happen
in patched/forked versions of glibc (e.g. Linaro's version of glibc
uses version strings like "2.20-2014.11"). See gh-3588.
"""
m = re.match(r"(?P<major>[0-9]+)\.(?P<minor>[0-9]+)", version_str)
if not m:
warnings.warn(
f"Expected glibc version with 2 components major.minor,"
f" got: {version_str}",
RuntimeWarning,
)
return -1, -1
return int(m.group("major")), int(m.group("minor"))
@functools.lru_cache
def _get_glibc_version() -> tuple[int, int]:
version_str = _glibc_version_string()
if version_str is None:
return (-1, -1)
return _parse_glibc_version(version_str)
# From PEP 513, PEP 600
def _is_compatible(arch: str, version: _GLibCVersion) -> bool:
sys_glibc = _get_glibc_version()
if sys_glibc < version:
return False
# Check for presence of _manylinux module.
try:
import _manylinux
except ImportError:
return True
if hasattr(_manylinux, "manylinux_compatible"):
result = _manylinux.manylinux_compatible(version[0], version[1], arch)
if result is not None:
return bool(result)
return True
if version == _GLibCVersion(2, 5):
if hasattr(_manylinux, "manylinux1_compatible"):
return bool(_manylinux.manylinux1_compatible)
if version == _GLibCVersion(2, 12):
if hasattr(_manylinux, "manylinux2010_compatible"):
return bool(_manylinux.manylinux2010_compatible)
if version == _GLibCVersion(2, 17):
if hasattr(_manylinux, "manylinux2014_compatible"):
return bool(_manylinux.manylinux2014_compatible)
return True
_LEGACY_MANYLINUX_MAP = {
# CentOS 7 w/ glibc 2.17 (PEP 599)
(2, 17): "manylinux2014",
# CentOS 6 w/ glibc 2.12 (PEP 571)
(2, 12): "manylinux2010",
# CentOS 5 w/ glibc 2.5 (PEP 513)
(2, 5): "manylinux1",
}
def platform_tags(archs: Sequence[str]) -> Iterator[str]:
"""Generate manylinux tags compatible to the current platform.
:param archs: Sequence of compatible architectures.
The first one shall be the closest to the actual architecture and be the part of
platform tag after the ``linux_`` prefix, e.g. ``x86_64``.
The ``linux_`` prefix is assumed as a prerequisite for the current platform to
be manylinux-compatible.
:returns: An iterator of compatible manylinux tags.
"""
if not _have_compatible_abi(sys.executable, archs):
return
# Oldest glibc to be supported regardless of architecture is (2, 17).
too_old_glibc2 = _GLibCVersion(2, 16)
if set(archs) & {"x86_64", "i686"}:
# On x86/i686 also oldest glibc to be supported is (2, 5).
too_old_glibc2 = _GLibCVersion(2, 4)
current_glibc = _GLibCVersion(*_get_glibc_version())
glibc_max_list = [current_glibc]
# We can assume compatibility across glibc major versions.
# https://sourceware.org/bugzilla/show_bug.cgi?id=24636
#
# Build a list of maximum glibc versions so that we can
# output the canonical list of all glibc from current_glibc
# down to too_old_glibc2, including all intermediary versions.
for glibc_major in range(current_glibc.major - 1, 1, -1):
glibc_minor = _LAST_GLIBC_MINOR[glibc_major]
glibc_max_list.append(_GLibCVersion(glibc_major, glibc_minor))
for arch in archs:
for glibc_max in glibc_max_list:
if glibc_max.major == too_old_glibc2.major:
min_minor = too_old_glibc2.minor
else:
# For other glibc major versions oldest supported is (x, 0).
min_minor = -1
for glibc_minor in range(glibc_max.minor, min_minor, -1):
glibc_version = _GLibCVersion(glibc_max.major, glibc_minor)
tag = "manylinux_{}_{}".format(*glibc_version)
if _is_compatible(arch, glibc_version):
yield f"{tag}_{arch}"
# Handle the legacy manylinux1, manylinux2010, manylinux2014 tags.
if glibc_version in _LEGACY_MANYLINUX_MAP:
legacy_tag = _LEGACY_MANYLINUX_MAP[glibc_version]
if _is_compatible(arch, glibc_version):
yield f"{legacy_tag}_{arch}"
| _GLibCVersion |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/typedDict1.py | {
"start": 1254,
"end": 1623
} | class ____(NotATD, TypedDict):
pass
# This should generate an error because TypedDict can't
# be used in a type annotation.
v1: TypedDict | int
# This should generate an error because TypedDict can't
# be used in a TypeVar bound.
T = TypeVar("T", bound=TypedDict | int)
# This should generate an error because TypedDict doesn't support
# a metaclass parameter.
| TD7 |
python | huggingface__transformers | src/transformers/models/minimax/modeling_minimax.py | {
"start": 21977,
"end": 23895
} | class ____(nn.Module):
"""Collection of expert weights stored as 3D tensors."""
def __init__(self, config: MiniMaxConfig):
super().__init__()
self.num_experts = config.num_local_experts
self.hidden_dim = config.hidden_size
self.intermediate_dim = config.intermediate_size
self.gate_up_proj = nn.Parameter(torch.empty(self.num_experts, 2 * self.intermediate_dim, self.hidden_dim))
self.down_proj = nn.Parameter(torch.empty(self.num_experts, self.hidden_dim, self.intermediate_dim))
self.act_fn = ACT2FN[config.hidden_act]
def forward(
self,
hidden_states: torch.Tensor,
top_k_index: torch.Tensor,
top_k_weights: torch.Tensor,
) -> torch.Tensor:
final_hidden_states = torch.zeros_like(hidden_states)
num_experts = top_k_weights.shape[1]
with torch.no_grad():
expert_mask = torch.nn.functional.one_hot(top_k_index, num_classes=num_experts + 1)
expert_mask = expert_mask.permute(2, 1, 0)
expert_hit = torch.greater(expert_mask.sum(dim=(-1, -2)), 0).nonzero()
for expert_idx in expert_hit:
expert_idx = expert_idx[0]
if expert_idx == num_experts:
continue
_, token_idx = torch.where(expert_mask[expert_idx])
current_state = hidden_states[token_idx]
gate, up = nn.functional.linear(current_state, self.gate_up_proj[expert_idx]).chunk(2, dim=-1)
current_hidden_states = self.act_fn(gate) * up
current_hidden_states = nn.functional.linear(current_hidden_states, self.down_proj[expert_idx])
current_hidden_states = current_hidden_states * top_k_weights[token_idx, expert_idx, None]
final_hidden_states.index_add_(0, token_idx, current_hidden_states.to(final_hidden_states.dtype))
return final_hidden_states
| MiniMaxExperts |
python | langchain-ai__langchain | libs/standard-tests/langchain_tests/integration_tests/base_store.py | {
"start": 5620,
"end": 11225
} | class ____(BaseStandardTests, Generic[V]):
"""Test suite for checking the key-value API of a `BaseStore`.
This test suite verifies the basic key-value API of a `BaseStore`.
The test suite is designed for synchronous key-value stores.
Implementers should subclass this test suite and provide a fixture
that returns an empty key-value store for each test.
"""
@abstractmethod
@pytest.fixture
async def kv_store(self) -> BaseStore[str, V]:
"""Get the key-value store class to test.
The returned key-value store should be EMPTY.
"""
@abstractmethod
@pytest.fixture
def three_values(self) -> tuple[V, V, V]:
"""Three example values that will be used in the tests."""
async def test_three_values(self, three_values: tuple[V, V, V]) -> None:
"""Test that the fixture provides three values."""
assert isinstance(three_values, tuple)
assert len(three_values) == 3
async def test_kv_store_is_empty(self, kv_store: BaseStore[str, V]) -> None:
"""Test that the key-value store is empty."""
keys = ["foo", "bar", "buzz"]
assert await kv_store.amget(keys) == [None, None, None]
async def test_set_and_get_values(
self,
kv_store: BaseStore[str, V],
three_values: tuple[V, V, V],
) -> None:
"""Test setting and getting values in the key-value store."""
foo = three_values[0]
bar = three_values[1]
key_value_pairs = [("foo", foo), ("bar", bar)]
await kv_store.amset(key_value_pairs)
assert await kv_store.amget(["foo", "bar"]) == [foo, bar]
async def test_store_still_empty(self, kv_store: BaseStore[str, V]) -> None:
"""Test that the store is still empty.
This test should follow a test that sets values.
This just verifies that the fixture is set up properly to be empty
after each test.
"""
keys = ["foo"]
assert await kv_store.amget(keys) == [None]
async def test_delete_values(
self,
kv_store: BaseStore[str, V],
three_values: tuple[V, V, V],
) -> None:
"""Test deleting values from the key-value store."""
foo = three_values[0]
bar = three_values[1]
key_value_pairs = [("foo", foo), ("bar", bar)]
await kv_store.amset(key_value_pairs)
await kv_store.amdelete(["foo"])
assert await kv_store.amget(["foo", "bar"]) == [None, bar]
async def test_delete_bulk_values(
self,
kv_store: BaseStore[str, V],
three_values: tuple[V, V, V],
) -> None:
"""Test that we can delete several values at once."""
foo, bar, buz = three_values
key_values = [("foo", foo), ("bar", bar), ("buz", buz)]
await kv_store.amset(key_values)
await kv_store.amdelete(["foo", "buz"])
assert await kv_store.amget(["foo", "bar", "buz"]) == [None, bar, None]
async def test_delete_missing_keys(self, kv_store: BaseStore[str, V]) -> None:
"""Deleting missing keys should not raise an exception."""
await kv_store.amdelete(["foo"])
await kv_store.amdelete(["foo", "bar", "baz"])
async def test_set_values_is_idempotent(
self,
kv_store: BaseStore[str, V],
three_values: tuple[V, V, V],
) -> None:
"""Setting values by key should be idempotent."""
foo, bar, _ = three_values
key_value_pairs = [("foo", foo), ("bar", bar)]
await kv_store.amset(key_value_pairs)
await kv_store.amset(key_value_pairs)
assert await kv_store.amget(["foo", "bar"]) == [foo, bar]
assert sorted([key async for key in kv_store.ayield_keys()]) == ["bar", "foo"]
async def test_get_can_get_same_value(
self,
kv_store: BaseStore[str, V],
three_values: tuple[V, V, V],
) -> None:
"""Test that the same value can be retrieved multiple times."""
foo, bar, _ = three_values
key_value_pairs = [("foo", foo), ("bar", bar)]
await kv_store.amset(key_value_pairs)
# This test assumes kv_store does not handle duplicates by async default
assert await kv_store.amget(["foo", "bar", "foo", "bar"]) == [
foo,
bar,
foo,
bar,
]
async def test_overwrite_values_by_key(
self,
kv_store: BaseStore[str, V],
three_values: tuple[V, V, V],
) -> None:
"""Test that we can overwrite values by key using mset."""
foo, bar, buzz = three_values
key_value_pairs = [("foo", foo), ("bar", bar)]
await kv_store.amset(key_value_pairs)
# Now overwrite value of key "foo"
new_key_value_pairs = [("foo", buzz)]
await kv_store.amset(new_key_value_pairs)
# Check that the value has been updated
assert await kv_store.amget(["foo", "bar"]) == [buzz, bar]
async def test_yield_keys(
self,
kv_store: BaseStore[str, V],
three_values: tuple[V, V, V],
) -> None:
"""Test that we can yield keys from the store."""
foo, bar, _buzz = three_values
key_value_pairs = [("foo", foo), ("bar", bar)]
await kv_store.amset(key_value_pairs)
generator = kv_store.ayield_keys()
assert isinstance(generator, AsyncGenerator)
assert sorted([key async for key in kv_store.ayield_keys()]) == ["bar", "foo"]
assert sorted([key async for key in kv_store.ayield_keys(prefix="foo")]) == [
"foo",
]
| BaseStoreAsyncTests |
python | getsentry__sentry | src/sentry/identity/vsts/provider.py | {
"start": 9197,
"end": 9679
} | class ____(OAuth2CallbackView):
def get_access_token(self, pipeline: IdentityPipeline, code: str) -> Response:
data = self.get_token_params(
code=code, redirect_uri=absolute_uri(pipeline.config.get("redirect_url"))
)
headers = {
"Content-Type": "application/x-www-form-urlencoded",
"Content-Length": "1322",
}
return safe_urlopen(self.access_token_url, data=data, headers=headers)
| VSTSNewOAuth2CallbackView |
python | dask__distributed | distributed/deploy/ssh.py | {
"start": 984,
"end": 5779
} | class ____(Process):
"""A Remote Dask Worker controlled by SSH
Parameters
----------
scheduler: str
The address of the scheduler
address: str
The hostname where we should run this worker
worker_class: str
The python class to use to create the worker.
connect_options: dict
kwargs to be passed to asyncssh connections
remote_python: str
Path to Python on remote node to run this worker.
kwargs: dict
These will be passed through the dask worker CLI to the
dask.distributed.Worker class
"""
def __init__( # type: ignore[no-untyped-def]
self,
scheduler: str,
address: str,
connect_options: dict,
kwargs: dict,
worker_module="deprecated",
worker_class="distributed.Nanny",
remote_python=None,
loop=None,
name=None,
):
super().__init__()
if worker_module != "deprecated":
raise ValueError(
"worker_module has been deprecated in favor of worker_class. "
"Please specify a Python class rather than a CLI module."
)
self.address = address
self.scheduler = scheduler
self.worker_class = worker_class
self.connect_options = connect_options
self.kwargs = copy.copy(kwargs)
self.name = name
self.remote_python = remote_python
if kwargs.get("nprocs") is not None and kwargs.get("n_workers") is not None:
raise ValueError(
"Both nprocs and n_workers were specified. Use n_workers only."
)
elif kwargs.get("nprocs") is not None:
warnings.warn(
"The nprocs argument will be removed in a future release. It has been "
"renamed to n_workers.",
FutureWarning,
)
self.n_workers = self.kwargs.pop("nprocs", 1)
else:
self.n_workers = self.kwargs.pop("n_workers", 1)
@property
def nprocs(self):
warnings.warn(
"The nprocs attribute will be removed in a future release. It has been "
"renamed to n_workers.",
FutureWarning,
)
return self.n_workers
@nprocs.setter
def nprocs(self, value):
warnings.warn(
"The nprocs attribute will be removed in a future release. It has been "
"renamed to n_workers.",
FutureWarning,
)
self.n_workers = value
async def start(self):
try:
import asyncssh # import now to avoid adding to module startup time
except ImportError:
raise ImportError(
"Dask's SSHCluster requires the `asyncssh` package to be installed. "
"Please install it using pip or conda."
)
self.connection = await asyncssh.connect(self.address, **self.connect_options)
result = await self.connection.run("uname")
if result.exit_status == 0:
set_env = f'env DASK_INTERNAL_INHERIT_CONFIG="{dask.config.serialize(dask.config.global_config)}"'
else:
result = await self.connection.run("cmd /c ver")
if result.exit_status == 0:
set_env = f"set DASK_INTERNAL_INHERIT_CONFIG={dask.config.serialize(dask.config.global_config)} &&"
else:
raise Exception(
"Worker failed to set DASK_INTERNAL_INHERIT_CONFIG variable "
)
if not self.remote_python:
self.remote_python = sys.executable
cmd = " ".join(
[
set_env,
self.remote_python,
"-m",
"distributed.cli.dask_spec",
self.scheduler,
"--spec",
"'%s'"
% dumps(
{
i: {
"cls": self.worker_class,
"opts": {
**self.kwargs,
},
}
for i in range(self.n_workers)
}
),
]
)
self.proc = await self.connection.create_process(cmd)
# We watch stderr in order to get the address, then we return
started_workers = 0
while started_workers < self.n_workers:
line = await self.proc.stderr.readline()
if not line.strip():
raise Exception("Worker failed to start")
logger.info(line.strip())
if "worker at" in line:
started_workers += 1
logger.debug("%s", line)
await super().start()
| Worker |
python | walkccc__LeetCode | solutions/1170. Compare Strings by Frequency of the Smallest Character/1170.py | {
"start": 0,
"end": 356
} | class ____:
def numSmallerByFrequency(
self,
queries: list[str],
words: list[str],
) -> list[int]:
ans = []
wordsFreq = sorted([word.count(min(word)) for word in words])
for q in queries:
count = q.count(min(q))
index = bisect.bisect(wordsFreq, count)
ans.append(len(words) - index)
return ans
| Solution |
python | pydantic__pydantic | tests/mypy/modules/plugin_fail_baseConfig.py | {
"start": 788,
"end": 892
} | class ____(BaseModel):
class Config:
extra = 'forbid'
ForbidExtraModel(x=1)
| ForbidExtraModel |
python | getsentry__sentry | src/sentry/rules/age.py | {
"start": 79,
"end": 243
} | class ____(StrEnum):
OLDEST = "oldest"
NEWEST = "newest"
model_age_choices = [(ModelAgeType.OLDEST, "oldest"), (ModelAgeType.NEWEST, "newest")]
| ModelAgeType |
python | numba__numba | numba/tests/test_parfors.py | {
"start": 93312,
"end": 109736
} | class ____(TestParforsBase):
"""
Tests miscellaneous parts of ParallelAccelerator use.
"""
def test_no_warn_if_cache_set(self):
def pyfunc():
arr = np.ones(100)
for i in prange(arr.size):
arr[i] += i
return arr
cfunc = njit(parallel=True, cache=True)(pyfunc)
with warnings.catch_warnings(record=True) as raised_warnings:
warnings.simplefilter('always')
warnings.filterwarnings(action="ignore",
module="typeguard")
# Filter out warnings about TBB interface mismatch
warnings.filterwarnings(action='ignore',
message=r".*TBB_INTERFACE_VERSION.*",
category=numba.errors.NumbaWarning,
module=r'numba\.np\.ufunc\.parallel.*')
cfunc()
self.assertEqual(len(raised_warnings), 0)
# Make sure the dynamic globals flag is set
has_dynamic_globals = [cres.library.has_dynamic_globals
for cres in cfunc.overloads.values()]
self.assertEqual(has_dynamic_globals, [False])
def test_statement_reordering_respects_aliasing(self):
def impl():
a = np.zeros(10)
a[1:8] = np.arange(0, 7)
print('a[3]:', a[3])
print('a[3]:', a[3])
return a
cres = self.compile_parallel(impl, ())
with captured_stdout() as stdout:
cres.entry_point()
for line in stdout.getvalue().splitlines():
self.assertEqual('a[3]: 2.0', line)
def test_parfor_ufunc_typing(self):
def test_impl(A):
return np.isinf(A)
A = np.array([np.inf, 0.0])
cfunc = njit(parallel=True)(test_impl)
# save global state
old_seq_flag = numba.parfors.parfor.sequential_parfor_lowering
try:
numba.parfors.parfor.sequential_parfor_lowering = True
np.testing.assert_array_equal(test_impl(A), cfunc(A))
finally:
# recover global state
numba.parfors.parfor.sequential_parfor_lowering = old_seq_flag
def test_init_block_dce(self):
# issue4690
def test_impl():
res = 0
arr = [1,2,3,4,5]
numba.parfors.parfor.init_prange()
dummy = arr
for i in numba.prange(5):
res += arr[i]
return res + dummy[2]
self.assertEqual(get_init_block_size(test_impl, ()), 0)
def test_alias_analysis_for_parfor1(self):
def test_impl():
acc = 0
for _ in range(4):
acc += 1
data = np.zeros((acc,))
return data
self.check(test_impl)
def test_no_state_change_in_gufunc_lowering_on_error(self):
# tests #5098, if there's an exception arising in gufunc lowering the
# sequential_parfor_lowering global variable should remain as False on
# stack unwind.
BROKEN_MSG = 'BROKEN_MSG'
@register_pass(mutates_CFG=True, analysis_only=False)
class BreakParfors(AnalysisPass):
_name = "break_parfors"
def __init__(self):
AnalysisPass.__init__(self)
def run_pass(self, state):
for blk in state.func_ir.blocks.values():
for stmt in blk.body:
if isinstance(stmt, numba.parfors.parfor.Parfor):
# races should be a set(), that list is iterable
# permits it to get through to the
# _create_gufunc_for_parfor_body routine at which
# point it needs to be a set so e.g. set.difference
# can be computed, this therefore creates an error
# in the right location.
class Broken(list):
def difference(self, other):
raise errors.LoweringError(BROKEN_MSG)
stmt.races = Broken()
return True
class BreakParforsCompiler(CompilerBase):
def define_pipelines(self):
pm = DefaultPassBuilder.define_nopython_pipeline(self.state)
pm.add_pass_after(BreakParfors, IRLegalization)
pm.finalize()
return [pm]
@njit(parallel=True, pipeline_class=BreakParforsCompiler)
def foo():
x = 1
for _ in prange(1):
x += 1
return x
# assert default state for global
self.assertFalse(numba.parfors.parfor.sequential_parfor_lowering)
with self.assertRaises(errors.LoweringError) as raises:
foo()
self.assertIn(BROKEN_MSG, str(raises.exception))
# assert state has not changed
self.assertFalse(numba.parfors.parfor.sequential_parfor_lowering)
def test_issue_5098(self):
class DummyType(types.Opaque):
pass
dummy_type = DummyType("my_dummy")
register_model(DummyType)(models.OpaqueModel)
class Dummy(object):
pass
@typeof_impl.register(Dummy)
def typeof_Dummy(val, c):
return dummy_type
@unbox(DummyType)
def unbox_index(typ, obj, c):
return NativeValue(c.context.get_dummy_value())
@overload_method(DummyType, "method1", jit_options={"parallel":True})
def _get_method1(obj, arr, func):
def _foo(obj, arr, func):
def baz(a, f):
c = a.copy()
c[np.isinf(a)] = np.nan
return f(c)
length = len(arr)
output_arr = np.empty(length, dtype=np.float64)
for i in prange(length):
output_arr[i] = baz(arr[i], func)
for i in prange(length - 1):
output_arr[i] += baz(arr[i], func)
return output_arr
return _foo
@njit
def bar(v):
return v.mean()
@njit
def test1(d):
return d.method1(np.array([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]]), bar)
save_state = numba.parfors.parfor.sequential_parfor_lowering
self.assertFalse(save_state)
try:
test1(Dummy())
self.assertFalse(numba.parfors.parfor.sequential_parfor_lowering)
finally:
# always set the sequential_parfor_lowering state back to the
# original state
numba.parfors.parfor.sequential_parfor_lowering = save_state
def test_oversized_tuple_as_arg_to_kernel(self):
@njit(parallel=True)
def oversize_tuple(idx):
big_tup = (1,2,3,4)
z = 0
for x in prange(10):
z += big_tup[idx]
return z
with override_env_config('NUMBA_PARFOR_MAX_TUPLE_SIZE', '3'):
with self.assertRaises(errors.UnsupportedParforsError) as raises:
oversize_tuple(0)
errstr = str(raises.exception)
self.assertIn("Use of a tuple", errstr)
self.assertIn("in a parallel region", errstr)
def test_issue5167(self):
def ndvi_njit(img_nir, img_red):
fillvalue = 0
out_img = np.full(img_nir.shape, fillvalue, dtype=img_nir.dtype)
dims = img_nir.shape
for y in prange(dims[0]):
for x in prange(dims[1]):
out_img[y, x] = ((img_nir[y, x] - img_red[y, x]) /
(img_nir[y, x] + img_red[y, x]))
return out_img
tile_shape = (4, 4)
array1 = np.random.uniform(low=1.0, high=10000.0, size=tile_shape)
array2 = np.random.uniform(low=1.0, high=10000.0, size=tile_shape)
self.check(ndvi_njit, array1, array2)
def test_issue5065(self):
def reproducer(a, dist, dist_args):
result = np.zeros((a.shape[0], a.shape[0]), dtype=np.float32)
for i in prange(a.shape[0]):
for j in range(i + 1, a.shape[0]):
d = dist(a[i], a[j], *dist_args)
result[i, j] = d
result[j, i] = d
return result
@njit
def euclidean(x, y):
result = 0.0
for i in range(x.shape[0]):
result += (x[i] - y[i]) ** 2
return np.sqrt(result)
a = np.random.random(size=(5, 2))
got = njit(parallel=True)(reproducer)(a.copy(), euclidean,())
expected = reproducer(a.copy(), euclidean,())
np.testing.assert_allclose(got, expected)
def test_issue5001(self):
def test_numba_parallel(myarray):
result = [0] * len(myarray)
for i in prange(len(myarray)):
result[i] = len(myarray[i])
return result
myarray = (np.empty(100),np.empty(50))
self.check(test_numba_parallel, myarray)
def test_issue3169(self):
@njit
def foo(grids):
pass
@njit(parallel=True)
def bar(grids):
for x in prange(1):
foo(grids)
# returns nothing, just check it compiles
bar(([1],) * 2)
@disabled_test
def test_issue4846(self):
mytype = namedtuple("mytype", ("a", "b"))
def outer(mydata):
for k in prange(3):
inner(k, mydata)
return mydata.a
@njit(nogil=True)
def inner(k, mydata):
f = (k, mydata.a)
g = (k, mydata.b)
mydata = mytype(a="a", b="b")
self.check(outer, mydata)
def test_issue3748(self):
def test1b():
x = (1, 2, 3, 4, 5)
a = 0
for i in prange(len(x)):
a += x[i]
return a
self.check(test1b,)
def test_issue5277(self):
def parallel_test(size, arr):
for x in prange(size[0]):
for y in prange(size[1]):
arr[y][x] = x * 4.5 + y
return arr
size = (10, 10)
arr = np.zeros(size, dtype=int)
self.check(parallel_test, size, arr)
def test_issue5570_ssa_races(self):
@njit(parallel=True)
def foo(src, method, out):
for i in prange(1):
for j in range(1):
out[i, j] = 1
if method:
out += 1
return out
src = np.zeros((5,5))
method = 57
out = np.zeros((2, 2))
self.assertPreciseEqual(
foo(src, method, out),
foo.py_func(src, method, out)
)
def test_issue6095_numpy_max(self):
@njit(parallel=True)
def find_maxima_3D_jit(args):
package = args
for index in range(0, 10):
z_stack = package[index, :, :]
return np.max(z_stack)
np.random.seed(0)
args = np.random.random((10, 10, 10))
self.assertPreciseEqual(
find_maxima_3D_jit(args),
find_maxima_3D_jit.py_func(args),
)
def test_issue5942_1(self):
# issue5942: tests statement reordering of
# aliased arguments.
def test_impl(gg, gg_next):
gs = gg.shape
d = gs[0]
for i_gg in prange(d):
gg_next[i_gg, :] = gg[i_gg, :]
gg_next[i_gg, 0] += 1
return gg_next
d = 4
k = 2
gg = np.zeros((d, k), dtype = np.int32)
gg_next = np.zeros((d, k), dtype = np.int32)
self.check(test_impl, gg, gg_next)
def test_issue5942_2(self):
# issue5942: tests statement reordering
def test_impl(d, k):
gg = np.zeros((d, k), dtype = np.int32)
gg_next = np.zeros((d, k), dtype = np.int32)
for i_gg in prange(d):
for n in range(k):
gg[i_gg, n] = i_gg
gg_next[i_gg, :] = gg[i_gg, :]
gg_next[i_gg, 0] += 1
return gg_next
d = 4
k = 2
self.check(test_impl, d, k)
@skip_unless_scipy
def test_issue6102(self):
# The problem is originally observed on Python3.8 because of the
# changes in how loops are represented in 3.8 bytecode.
@njit(parallel=True)
def f(r):
for ir in prange(r.shape[0]):
dist = np.inf
tr = np.array([0, 0, 0], dtype=np.float32)
for i in [1, 0, -1]:
dist_t = np.linalg.norm(r[ir, :] + i)
if dist_t < dist:
dist = dist_t
tr = np.array([i, i, i], dtype=np.float32)
r[ir, :] += tr
return r
r = np.array([[0., 0., 0.], [0., 0., 1.]])
self.assertPreciseEqual(f(r), f.py_func(r))
def test_issue6774(self):
def test_impl():
n = 5
na_mask = np.ones((n,))
result = np.empty((n - 1,))
for i in prange(len(result)):
result[i] = np.sum(na_mask[i:i + 1])
return result
self.check(test_impl)
def test_issue4963_globals(self):
def test_impl():
buf = np.zeros((_GLOBAL_INT_FOR_TESTING1, _GLOBAL_INT_FOR_TESTING2))
return buf
self.check(test_impl)
def test_issue4963_freevars(self):
_FREEVAR_INT_FOR_TESTING1 = 17
_FREEVAR_INT_FOR_TESTING2 = 5
def test_impl():
buf = np.zeros((_FREEVAR_INT_FOR_TESTING1, _FREEVAR_INT_FOR_TESTING2))
return buf
self.check(test_impl)
def test_issue_9182_recursion_error(self):
from numba.types import ListType, Tuple, intp
@numba.njit
def _sink(x):
pass
@numba.njit(cache=False, parallel=True)
def _ground_node_rule(
clauses,
nodes,
):
for piter in prange(len(nodes)):
for clause in clauses:
clause_type = clause[0]
clause_variables = clause[2]
if clause_type == 0:
clause_var_1 = clause_variables[0]
elif len(clause_variables) == 2:
clause_var_1, clause_var_2 = (
clause_variables[0],
clause_variables[1],
)
elif len(clause_variables) == 4:
pass
if clause_type == 1:
_sink(clause_var_1)
_sink(clause_var_2)
_ground_node_rule.compile(
(
ListType(Tuple([intp, intp, ListType(intp)])),
ListType(intp),
)
)
def test_lookup_cycle_detection(self):
# This test is added due to a bug discovered in the PR 9244 patch.
# The cyclic detection was incorrectly flagging cycles.
@njit(parallel=True)
def foo():
# The following `acc` variable is used in the `lookup()` function
# in parfor's reduction code.
acc = 0
for n in prange(1):
for i in range(1):
for j in range(1):
acc += 1
return acc
self.assertEqual(foo(), foo.py_func())
def test_issue_9678_build_map(self):
def issue_9678(num_nodes):
out = 0
for inode_uint in numba.prange(num_nodes):
inode = numba.int64(inode_uint)
p = {inode: 0.0} # mainly this build_map bytecode here
for _ in range(5):
p[inode] += 1 # and here
out += p[inode]
return out
num_nodes = 12
issue_9678_serial = numba.jit(parallel=False)(issue_9678)
issue_9678_parallel = numba.jit(parallel=True)(issue_9678)
self.assertEqual(issue_9678_serial(num_nodes),
issue_9678_parallel(num_nodes))
@skip_parfors_unsupported
| TestParforsMisc |
python | apache__airflow | providers/google/tests/unit/google/marketing_platform/operators/test_campaign_manager.py | {
"start": 10280,
"end": 11326
} | class ____:
@mock.patch(
"airflow.providers.google.marketing_platform.operators.campaign_manager.GoogleCampaignManagerHook"
)
@mock.patch("airflow.providers.google.marketing_platform.operators.campaign_manager.BaseOperator")
def test_execute(self, mock_base_op, hook_mock):
op = GoogleCampaignManagerBatchInsertConversionsOperator(
task_id="insert_conversion",
profile_id=PROFILE_ID,
conversions=[CONVERSION],
encryption_source="AD_SERVING",
encryption_entity_type="DCM_ADVERTISER",
encryption_entity_id=123456789,
)
op.execute(None)
hook_mock.return_value.conversions_batch_insert.assert_called_once_with(
profile_id=PROFILE_ID,
conversions=[CONVERSION],
encryption_source="AD_SERVING",
encryption_entity_type="DCM_ADVERTISER",
encryption_entity_id=123456789,
max_failed_inserts=0,
)
| TestGoogleCampaignManagerBatchInsertConversionsOperator |
python | pypa__twine | twine/exceptions.py | {
"start": 657,
"end": 759
} | class ____(Exception):
"""Base class for all exceptions raised by twine."""
pass
| TwineException |
python | allegroai__clearml | clearml/backend_config/bucket_config.py | {
"start": 14752,
"end": 17813
} | class ____(object):
def __init__(
self,
container_configs: List[AzureContainerConfig] = None,
default_account: str = None,
default_key: str = None,
) -> None:
super(AzureContainerConfigurations, self).__init__()
self._container_configs = container_configs or []
self._default_account = default_account
self._default_key = default_key
@classmethod
def from_config(cls, configuration: dict) -> "AzureContainerConfigurations":
default_account = getenv("AZURE_STORAGE_ACCOUNT")
default_key = getenv("AZURE_STORAGE_KEY")
default_container_configs = []
if default_account and default_key:
default_container_configs.append(
AzureContainerConfig(account_name=default_account, account_key=default_key)
)
if configuration is None:
return cls(
default_container_configs,
default_account=default_account,
default_key=default_key,
)
containers = configuration.get("containers", list())
container_configs = [AzureContainerConfig(**entry) for entry in containers] + default_container_configs
return cls(container_configs, default_account=default_account, default_key=default_key)
def get_config_by_uri(self, uri: str) -> AzureContainerConfig:
"""
Get the credentials for an Azure Blob Storage container from the config
:param uri: URI of container or blob
:return: AzureContainerConfig: container config
"""
f = furl.furl(uri)
account_name = f.host.partition(".")[0]
if not f.path.segments:
raise ValueError(
"URI {} is missing a container name (expected "
"[https/azure]://<account-name>.../<container-name>)".format(uri)
)
container = f.path.segments[0]
config = copy(self.get_config(account_name, container))
if config and not config.container_name:
config.container_name = container
return config
def get_config(self, account_name: str, container: str) -> AzureContainerConfig:
return next(
(
config
for config in self._container_configs
if config.account_name == account_name
and (not config.container_name or config.container_name == container)
),
None,
)
def update_config_with_defaults(self, bucket_config: AzureContainerConfig) -> None:
bucket_config.update(
account_name=bucket_config.account_name or self._default_account,
account_key=bucket_config.account_key or self._default_key,
)
def add_config(self, bucket_config: AzureContainerConfig) -> None:
self._container_configs.append(bucket_config)
def remove_config(self, bucket_config: AzureContainerConfig) -> None:
self._container_configs.remove(bucket_config)
| AzureContainerConfigurations |
python | wandb__wandb | wandb/vendor/pygments/lexers/templates.py | {
"start": 38398,
"end": 38833
} | class ____(DelegatingLexer):
"""
Subclass of `PhpLexer` which highlights unmatched data with the `CssLexer`.
"""
name = 'CSS+PHP'
aliases = ['css+php']
alias_filenames = ['*.css']
mimetypes = ['text/css+php']
def __init__(self, **options):
super(CssPhpLexer, self).__init__(CssLexer, PhpLexer, **options)
def analyse_text(text):
return PhpLexer.analyse_text(text) - 0.05
| CssPhpLexer |
python | sphinx-doc__sphinx | sphinx/addnodes.py | {
"start": 13962,
"end": 14110
} | class ____(nodes.Element):
"""Inserted to set the highlight language and line number options for
subsequent code blocks.
"""
| highlightlang |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/pylint/eq_without_hash.py | {
"start": 2112,
"end": 2229
} | class ____(SingleClass):
def __eq__(self, other):
return True
__hash__ = SingleClass.__hash__
| ChildClass |
python | tornadoweb__tornado | tornado/test/web_test.py | {
"start": 26450,
"end": 26811
} | class ____(RequestHandler):
def prepare(self):
self.finish(
dict(
default=self.get_arguments("foo"),
query=self.get_query_arguments("foo"),
body=self.get_body_arguments("foo"),
)
)
# This test was shared with wsgi_test.py; now the name is meaningless.
| GetArgumentsHandler |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/function10.py | {
"start": 250,
"end": 281
} | class ____:
prop1: str
| Thing1 |
python | pypa__pipenv | pipenv/patched/pip/_vendor/rich/rule.py | {
"start": 276,
"end": 4613
} | class ____(JupyterMixin):
"""A console renderable to draw a horizontal rule (line).
Args:
title (Union[str, Text], optional): Text to render in the rule. Defaults to "".
characters (str, optional): Character(s) used to draw the line. Defaults to "─".
style (StyleType, optional): Style of Rule. Defaults to "rule.line".
end (str, optional): Character at end of Rule. defaults to "\\\\n"
align (str, optional): How to align the title, one of "left", "center", or "right". Defaults to "center".
"""
def __init__(
self,
title: Union[str, Text] = "",
*,
characters: str = "─",
style: Union[str, Style] = "rule.line",
end: str = "\n",
align: AlignMethod = "center",
) -> None:
if cell_len(characters) < 1:
raise ValueError(
"'characters' argument must have a cell width of at least 1"
)
if align not in ("left", "center", "right"):
raise ValueError(
f'invalid value for align, expected "left", "center", "right" (not {align!r})'
)
self.title = title
self.characters = characters
self.style = style
self.end = end
self.align = align
def __repr__(self) -> str:
return f"Rule({self.title!r}, {self.characters!r})"
def __rich_console__(
self, console: Console, options: ConsoleOptions
) -> RenderResult:
width = options.max_width
characters = (
"-"
if (options.ascii_only and not self.characters.isascii())
else self.characters
)
chars_len = cell_len(characters)
if not self.title:
yield self._rule_line(chars_len, width)
return
if isinstance(self.title, Text):
title_text = self.title
else:
title_text = console.render_str(self.title, style="rule.text")
title_text.plain = title_text.plain.replace("\n", " ")
title_text.expand_tabs()
required_space = 4 if self.align == "center" else 2
truncate_width = max(0, width - required_space)
if not truncate_width:
yield self._rule_line(chars_len, width)
return
rule_text = Text(end=self.end)
if self.align == "center":
title_text.truncate(truncate_width, overflow="ellipsis")
side_width = (width - cell_len(title_text.plain)) // 2
left = Text(characters * (side_width // chars_len + 1))
left.truncate(side_width - 1)
right_length = width - cell_len(left.plain) - cell_len(title_text.plain)
right = Text(characters * (side_width // chars_len + 1))
right.truncate(right_length)
rule_text.append(left.plain + " ", self.style)
rule_text.append(title_text)
rule_text.append(" " + right.plain, self.style)
elif self.align == "left":
title_text.truncate(truncate_width, overflow="ellipsis")
rule_text.append(title_text)
rule_text.append(" ")
rule_text.append(characters * (width - rule_text.cell_len), self.style)
elif self.align == "right":
title_text.truncate(truncate_width, overflow="ellipsis")
rule_text.append(characters * (width - title_text.cell_len - 1), self.style)
rule_text.append(" ")
rule_text.append(title_text)
rule_text.plain = set_cell_size(rule_text.plain, width)
yield rule_text
def _rule_line(self, chars_len: int, width: int) -> Text:
rule_text = Text(self.characters * ((width // chars_len) + 1), self.style)
rule_text.truncate(width)
rule_text.plain = set_cell_size(rule_text.plain, width)
return rule_text
def __rich_measure__(
self, console: Console, options: ConsoleOptions
) -> Measurement:
return Measurement(1, 1)
if __name__ == "__main__": # pragma: no cover
import sys
from pipenv.patched.pip._vendor.rich.console import Console
try:
text = sys.argv[1]
except IndexError:
text = "Hello, World"
console = Console()
console.print(Rule(title=text))
console = Console()
console.print(Rule("foo"), width=4)
| Rule |
python | dagster-io__dagster | python_modules/libraries/dagster-looker/dagster_looker/api/resource.py | {
"start": 6665,
"end": 14194
} | class ____(StateBackedDefinitionsLoader[Mapping[str, Any]]):
looker_resource: LookerResource
translator: DagsterLookerApiTranslator
looker_filter: LookerFilter
@property
def defs_key(self) -> str:
return f"{LOOKER_RECONSTRUCTION_METADATA_KEY_PREFIX}/{self.looker_resource.client_id}"
def fetch_state(self) -> Mapping[str, Any]:
looker_instance_data = self.fetch_looker_instance_data()
return looker_instance_data.to_state(self.looker_resource.get_sdk())
def defs_from_state(self, state: Mapping[str, Any]) -> Definitions:
looker_instance_data = LookerInstanceData.from_state(self.looker_resource.get_sdk(), state)
return self._build_defs_from_looker_instance_data(looker_instance_data, self.translator)
def _build_defs_from_looker_instance_data(
self,
looker_instance_data: LookerInstanceData,
dagster_looker_translator: DagsterLookerApiTranslator,
) -> Definitions:
explores = [
dagster_looker_translator.get_asset_spec(
LookerApiTranslatorStructureData(
structure_data=LookerStructureData(
structure_type=LookerStructureType.EXPLORE,
data=lookml_explore,
base_url=self.looker_resource.base_url,
),
instance_data=looker_instance_data,
)
)
for lookml_explore in looker_instance_data.explores_by_id.values()
]
views = [
dagster_looker_translator.get_asset_spec(
LookerApiTranslatorStructureData(
structure_data=LookerStructureData(
structure_type=LookerStructureType.DASHBOARD,
data=looker_dashboard,
base_url=self.looker_resource.base_url,
),
instance_data=looker_instance_data,
)
)
for looker_dashboard in looker_instance_data.dashboards_by_id.values()
]
return Definitions(assets=[*explores, *views])
@cached_method
def fetch_looker_instance_data(self) -> LookerInstanceData:
"""Fetches all explores and dashboards from the Looker instance.
TODO: Fetch explores in parallel using asyncio
TODO: Get all the LookML views upstream of the explores
"""
sdk = self.looker_resource.get_sdk()
folders = sdk.all_folders()
folder_by_id = {folder.id: folder for folder in folders if folder.id is not None}
# Get dashboards
dashboards = sdk.all_dashboards(
fields=",".join(
[
"id",
"hidden",
"folder",
]
)
)
folder_filter_strings = (
[
"/".join(folder_filter).lower()
for folder_filter in self.looker_filter.dashboard_folders
]
if self.looker_filter.dashboard_folders
else []
)
dashboard_ids_to_fetch = []
if len(folder_filter_strings) == 0:
dashboard_ids_to_fetch = [
dashboard.id for dashboard in dashboards if not dashboard.hidden
]
else:
for dashboard in dashboards:
if (
not dashboard.hidden
and dashboard.folder is not None
and dashboard.folder.id is not None
):
folder_string = "/".join(
build_folder_path(folder_by_id, dashboard.folder.id)
).lower()
if any(
folder_string.startswith(folder_filter_string)
for folder_filter_string in folder_filter_strings
):
dashboard_ids_to_fetch.append(dashboard.id)
with ThreadPoolExecutor(max_workers=None) as executor:
dashboards_by_id = dict(
list(
executor.map(
lambda dashboard_id: (
dashboard_id,
sdk.dashboard(dashboard_id=dashboard_id),
),
(dashboard_id for dashboard_id in dashboard_ids_to_fetch),
)
)
)
# Get explore names from models
explores_for_model = {
model.name: [explore.name for explore in (model.explores or []) if explore.name]
for model in sdk.all_lookml_models(
fields=",".join(
[
"name",
"explores",
]
)
)
if model.name
}
if self.looker_filter.only_fetch_explores_used_in_dashboards:
used_explores = set()
for dashboard in dashboards_by_id.values():
for dash_filter in dashboard.dashboard_filters or []:
used_explores.add((dash_filter.model, dash_filter.explore))
explores_for_model = {
model_name: [
explore_name
for explore_name in explore_names
if (model_name, explore_name) in used_explores
]
for model_name, explore_names in explores_for_model.items()
}
def fetch_explore(model_name, explore_name) -> Optional[tuple[str, "LookmlModelExplore"]]:
try:
lookml_explore = sdk.lookml_model_explore(
lookml_model_name=model_name,
explore_name=explore_name,
fields=",".join(
[
"id",
"view_name",
"sql_table_name",
"joins",
]
),
)
return (check.not_none(lookml_explore.id), lookml_explore)
except:
logger.warning(
f"Failed to fetch LookML explore '{explore_name}' for model '{model_name}'."
)
with ThreadPoolExecutor(max_workers=None) as executor:
explores_to_fetch = [
(model_name, explore_name)
for model_name, explore_names in explores_for_model.items()
for explore_name in explore_names
]
explores_by_id = dict(
cast(
"list[tuple[str, LookmlModelExplore]]",
(
entry
for entry in executor.map(
lambda explore: fetch_explore(*explore), explores_to_fetch
)
if entry is not None
),
)
)
user_ids_to_fetch = set()
for dashboard in dashboards_by_id.values():
if dashboard.user_id:
user_ids_to_fetch.update(dashboard.user_id)
users = sdk.search_users(id=",".join(user_ids_to_fetch))
return LookerInstanceData(
explores_by_id=explores_by_id,
dashboards_by_id=dashboards_by_id,
users_by_id={check.not_none(user.id): user for user in users},
)
| LookerApiDefsLoader |
python | huggingface__transformers | src/transformers/models/rt_detr_v2/modular_rt_detr_v2.py | {
"start": 1201,
"end": 22230
} | class ____(PreTrainedConfig):
r"""
This is the configuration class to store the configuration of a [`RTDetrV2Model`]. It is used to instantiate a
RT-DETR model according to the specified arguments, defining the model architecture. Instantiating a configuration
with the defaults will yield a similar configuration to that of the RT-DETR architecture.
e.g. [PekingU/rtdetr_r18vd](https://huggingface.co/PekingU/rtdetr_r18vd)
Configuration objects inherit from [`PreTrainedConfig`] and can be used to control the model outputs. Read the
documentation from [`PreTrainedConfig`] for more information.
Args:
initializer_range (`float`, *optional*, defaults to 0.01):
The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
initializer_bias_prior_prob (`float`, *optional*):
The prior probability used by the bias initializer to initialize biases for `enc_score_head` and `class_embed`.
If `None`, `prior_prob` computed as `prior_prob = 1 / (num_labels + 1)` while initializing model weights.
layer_norm_eps (`float`, *optional*, defaults to 1e-05):
The epsilon used by the layer normalization layers.
batch_norm_eps (`float`, *optional*, defaults to 1e-05):
The epsilon used by the batch normalization layers.
backbone_config (`Dict`, *optional*, defaults to `RTDetrV2ResNetConfig()`):
The configuration of the backbone model.
backbone (`str`, *optional*):
Name of backbone to use when `backbone_config` is `None`. If `use_pretrained_backbone` is `True`, this
will load the corresponding pretrained weights from the timm or transformers library. If `use_pretrained_backbone`
is `False`, this loads the backbone's config and uses that to initialize the backbone with random weights.
use_pretrained_backbone (`bool`, *optional*, defaults to `False`):
Whether to use pretrained weights for the backbone.
use_timm_backbone (`bool`, *optional*, defaults to `False`):
Whether to load `backbone` from the timm library. If `False`, the backbone is loaded from the transformers
library.
freeze_backbone_batch_norms (`bool`, *optional*, defaults to `True`):
Whether to freeze the batch normalization layers in the backbone.
backbone_kwargs (`dict`, *optional*):
Keyword arguments to be passed to AutoBackbone when loading from a checkpoint
e.g. `{'out_indices': (0, 1, 2, 3)}`. Cannot be specified if `backbone_config` is set.
encoder_hidden_dim (`int`, *optional*, defaults to 256):
Dimension of the layers in hybrid encoder.
encoder_in_channels (`list`, *optional*, defaults to `[512, 1024, 2048]`):
Multi level features input for encoder.
feat_strides (`list[int]`, *optional*, defaults to `[8, 16, 32]`):
Strides used in each feature map.
encoder_layers (`int`, *optional*, defaults to 1):
Total of layers to be used by the encoder.
encoder_ffn_dim (`int`, *optional*, defaults to 1024):
Dimension of the "intermediate" (often named feed-forward) layer in decoder.
encoder_attention_heads (`int`, *optional*, defaults to 8):
Number of attention heads for each attention layer in the Transformer encoder.
dropout (`float`, *optional*, defaults to 0.0):
The ratio for all dropout layers.
activation_dropout (`float`, *optional*, defaults to 0.0):
The dropout ratio for activations inside the fully connected layer.
encode_proj_layers (`list[int]`, *optional*, defaults to `[2]`):
Indexes of the projected layers to be used in the encoder.
positional_encoding_temperature (`int`, *optional*, defaults to 10000):
The temperature parameter used to create the positional encodings.
encoder_activation_function (`str`, *optional*, defaults to `"gelu"`):
The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
`"relu"`, `"silu"` and `"gelu_new"` are supported.
activation_function (`str`, *optional*, defaults to `"silu"`):
The non-linear activation function (function or string) in the general layer. If string, `"gelu"`,
`"relu"`, `"silu"` and `"gelu_new"` are supported.
eval_size (`tuple[int, int]`, *optional*):
Height and width used to compute the effective height and width of the position embeddings after taking
into account the stride.
normalize_before (`bool`, *optional*, defaults to `False`):
Determine whether to apply layer normalization in the transformer encoder layer before self-attention and
feed-forward modules.
hidden_expansion (`float`, *optional*, defaults to 1.0):
Expansion ratio to enlarge the dimension size of RepVGGBlock and CSPRepLayer.
d_model (`int`, *optional*, defaults to 256):
Dimension of the layers exclude hybrid encoder.
num_queries (`int`, *optional*, defaults to 300):
Number of object queries.
decoder_in_channels (`list`, *optional*, defaults to `[256, 256, 256]`):
Multi level features dimension for decoder
decoder_ffn_dim (`int`, *optional*, defaults to 1024):
Dimension of the "intermediate" (often named feed-forward) layer in decoder.
num_feature_levels (`int`, *optional*, defaults to 3):
The number of input feature levels.
decoder_n_points (`int`, *optional*, defaults to 4):
The number of sampled keys in each feature level for each attention head in the decoder.
decoder_layers (`int`, *optional*, defaults to 6):
Number of decoder layers.
decoder_attention_heads (`int`, *optional*, defaults to 8):
Number of attention heads for each attention layer in the Transformer decoder.
decoder_activation_function (`str`, *optional*, defaults to `"relu"`):
The non-linear activation function (function or string) in the decoder. If string, `"gelu"`,
`"relu"`, `"silu"` and `"gelu_new"` are supported.
attention_dropout (`float`, *optional*, defaults to 0.0):
The dropout ratio for the attention probabilities.
num_denoising (`int`, *optional*, defaults to 100):
The total number of denoising tasks or queries to be used for contrastive denoising.
label_noise_ratio (`float`, *optional*, defaults to 0.5):
The fraction of denoising labels to which random noise should be added.
box_noise_scale (`float`, *optional*, defaults to 1.0):
Scale or magnitude of noise to be added to the bounding boxes.
learn_initial_query (`bool`, *optional*, defaults to `False`):
Indicates whether the initial query embeddings for the decoder should be learned during training
anchor_image_size (`tuple[int, int]`, *optional*):
Height and width of the input image used during evaluation to generate the bounding box anchors. If None, automatic generate anchor is applied.
with_box_refine (`bool`, *optional*, defaults to `True`):
Whether to apply iterative bounding box refinement, where each decoder layer refines the bounding boxes
based on the predictions from the previous layer.
is_encoder_decoder (`bool`, *optional*, defaults to `True`):
Whether the architecture has an encoder decoder structure.
matcher_alpha (`float`, *optional*, defaults to 0.25):
Parameter alpha used by the Hungarian Matcher.
matcher_gamma (`float`, *optional*, defaults to 2.0):
Parameter gamma used by the Hungarian Matcher.
matcher_class_cost (`float`, *optional*, defaults to 2.0):
The relative weight of the class loss used by the Hungarian Matcher.
matcher_bbox_cost (`float`, *optional*, defaults to 5.0):
The relative weight of the bounding box loss used by the Hungarian Matcher.
matcher_giou_cost (`float`, *optional*, defaults to 2.0):
The relative weight of the giou loss of used by the Hungarian Matcher.
use_focal_loss (`bool`, *optional*, defaults to `True`):
Parameter informing if focal loss should be used.
auxiliary_loss (`bool`, *optional*, defaults to `True`):
Whether auxiliary decoding losses (loss at each decoder layer) are to be used.
focal_loss_alpha (`float`, *optional*, defaults to 0.75):
Parameter alpha used to compute the focal loss.
focal_loss_gamma (`float`, *optional*, defaults to 2.0):
Parameter gamma used to compute the focal loss.
weight_loss_vfl (`float`, *optional*, defaults to 1.0):
Relative weight of the varifocal loss in the object detection loss.
weight_loss_bbox (`float`, *optional*, defaults to 5.0):
Relative weight of the L1 bounding box loss in the object detection loss.
weight_loss_giou (`float`, *optional*, defaults to 2.0):
Relative weight of the generalized IoU loss in the object detection loss.
eos_coefficient (`float`, *optional*, defaults to 0.0001):
Relative classification weight of the 'no-object' class in the object detection loss.
decoder_n_levels (`int`, *optional*, defaults to 3):
The number of feature levels used by the decoder.
decoder_offset_scale (`float`, *optional*, defaults to 0.5):
Scaling factor applied to the attention offsets in the decoder.
decoder_method (`str`, *optional*, defaults to `"default"`):
The method to use for the decoder: `"default"` or `"discrete"`.
Examples:
```python
>>> from transformers import RTDetrV2Config, RTDetrV2Model
>>> # Initializing a RT-DETR configuration
>>> configuration = RTDetrV2Config()
>>> # Initializing a model (with random weights) from the configuration
>>> model = RTDetrV2Model(configuration)
>>> # Accessing the model configuration
>>> configuration = model.config
```
"""
model_type = "rt_detr_v2"
sub_configs = {"backbone_config": AutoConfig}
layer_types = ["basic", "bottleneck"]
attribute_map = {
"hidden_size": "d_model",
"num_attention_heads": "encoder_attention_heads",
}
def __init__(
self,
initializer_range=0.01,
initializer_bias_prior_prob=None,
layer_norm_eps=1e-5,
batch_norm_eps=1e-5,
# backbone
backbone_config=None,
backbone=None,
use_pretrained_backbone=False,
use_timm_backbone=False,
freeze_backbone_batch_norms=True,
backbone_kwargs=None,
# encoder HybridEncoder
encoder_hidden_dim=256,
encoder_in_channels=[512, 1024, 2048],
feat_strides=[8, 16, 32],
encoder_layers=1,
encoder_ffn_dim=1024,
encoder_attention_heads=8,
dropout=0.0,
activation_dropout=0.0,
encode_proj_layers=[2],
positional_encoding_temperature=10000,
encoder_activation_function="gelu",
activation_function="silu",
eval_size=None,
normalize_before=False,
hidden_expansion=1.0,
# decoder RTDetrV2Transformer
d_model=256,
num_queries=300,
decoder_in_channels=[256, 256, 256],
decoder_ffn_dim=1024,
num_feature_levels=3,
decoder_n_points=4,
decoder_layers=6,
decoder_attention_heads=8,
decoder_activation_function="relu",
attention_dropout=0.0,
num_denoising=100,
label_noise_ratio=0.5,
box_noise_scale=1.0,
learn_initial_query=False,
anchor_image_size=None,
with_box_refine=True,
is_encoder_decoder=True,
# Loss
matcher_alpha=0.25,
matcher_gamma=2.0,
matcher_class_cost=2.0,
matcher_bbox_cost=5.0,
matcher_giou_cost=2.0,
use_focal_loss=True,
auxiliary_loss=True,
focal_loss_alpha=0.75,
focal_loss_gamma=2.0,
weight_loss_vfl=1.0,
weight_loss_bbox=5.0,
weight_loss_giou=2.0,
eos_coefficient=1e-4,
decoder_n_levels=3, # default value
decoder_offset_scale=0.5, # default value
decoder_method="default",
**kwargs,
):
self.initializer_range = initializer_range
self.initializer_bias_prior_prob = initializer_bias_prior_prob
self.layer_norm_eps = layer_norm_eps
self.batch_norm_eps = batch_norm_eps
# backbone
if backbone_config is None and backbone is None:
logger.info(
"`backbone_config` and `backbone` are `None`. Initializing the config with the default `RTDetrV2-ResNet` backbone."
)
backbone_model_type = "rt_detr_resnet"
config_class = CONFIG_MAPPING[backbone_model_type]
# this will map it to RTDetrResNetConfig
# note: we can instead create RTDetrV2ResNetConfig but it will be exactly the same as V1
# and we would need to create RTDetrV2ResNetModel
backbone_config = config_class(
num_channels=3,
embedding_size=64,
hidden_sizes=[256, 512, 1024, 2048],
depths=[3, 4, 6, 3],
layer_type="bottleneck",
hidden_act="relu",
downsample_in_first_stage=False,
downsample_in_bottleneck=False,
out_features=None,
out_indices=[2, 3, 4],
)
elif isinstance(backbone_config, dict):
backbone_model_type = backbone_config.pop("model_type")
config_class = CONFIG_MAPPING[backbone_model_type]
backbone_config = config_class.from_dict(backbone_config)
verify_backbone_config_arguments(
use_timm_backbone=use_timm_backbone,
use_pretrained_backbone=use_pretrained_backbone,
backbone=backbone,
backbone_config=backbone_config,
backbone_kwargs=backbone_kwargs,
)
self.backbone_config = backbone_config
self.backbone = backbone
self.use_pretrained_backbone = use_pretrained_backbone
self.use_timm_backbone = use_timm_backbone
self.freeze_backbone_batch_norms = freeze_backbone_batch_norms
self.backbone_kwargs = backbone_kwargs
# encoder
self.encoder_hidden_dim = encoder_hidden_dim
self.encoder_in_channels = encoder_in_channels
self.feat_strides = feat_strides
self.encoder_ffn_dim = encoder_ffn_dim
self.dropout = dropout
self.activation_dropout = activation_dropout
self.encode_proj_layers = encode_proj_layers
self.encoder_layers = encoder_layers
self.positional_encoding_temperature = positional_encoding_temperature
self.eval_size = eval_size
self.normalize_before = normalize_before
self.encoder_activation_function = encoder_activation_function
self.activation_function = activation_function
self.hidden_expansion = hidden_expansion
self.num_queries = num_queries
self.decoder_ffn_dim = decoder_ffn_dim
self.decoder_in_channels = decoder_in_channels
self.num_feature_levels = num_feature_levels
self.decoder_n_points = decoder_n_points
self.decoder_layers = decoder_layers
self.decoder_attention_heads = decoder_attention_heads
self.decoder_activation_function = decoder_activation_function
self.attention_dropout = attention_dropout
self.num_denoising = num_denoising
self.label_noise_ratio = label_noise_ratio
self.box_noise_scale = box_noise_scale
self.learn_initial_query = learn_initial_query
self.anchor_image_size = anchor_image_size
self.auxiliary_loss = auxiliary_loss
self.with_box_refine = with_box_refine
# Loss
self.matcher_alpha = matcher_alpha
self.matcher_gamma = matcher_gamma
self.matcher_class_cost = matcher_class_cost
self.matcher_bbox_cost = matcher_bbox_cost
self.matcher_giou_cost = matcher_giou_cost
self.use_focal_loss = use_focal_loss
self.focal_loss_alpha = focal_loss_alpha
self.focal_loss_gamma = focal_loss_gamma
self.weight_loss_vfl = weight_loss_vfl
self.weight_loss_bbox = weight_loss_bbox
self.weight_loss_giou = weight_loss_giou
self.eos_coefficient = eos_coefficient
if not hasattr(self, "d_model"):
self.d_model = d_model
if not hasattr(self, "encoder_attention_heads"):
self.encoder_attention_heads = encoder_attention_heads
# add the new attributes with the given values or defaults
self.decoder_n_levels = decoder_n_levels
self.decoder_offset_scale = decoder_offset_scale
self.decoder_method = decoder_method
super().__init__(is_encoder_decoder=is_encoder_decoder, **kwargs)
self.tie_encoder_decoder = True
def multi_scale_deformable_attention_v2(
value: Tensor,
value_spatial_shapes: Tensor,
sampling_locations: Tensor,
attention_weights: Tensor,
num_points_list: list[int],
method="default",
) -> Tensor:
batch_size, _, num_heads, hidden_dim = value.shape
_, num_queries, num_heads, num_levels, num_points = sampling_locations.shape
value_list = (
value.permute(0, 2, 3, 1)
.flatten(0, 1)
.split([height * width for height, width in value_spatial_shapes], dim=-1)
)
# sampling_offsets [8, 480, 8, 12, 2]
if method == "default":
sampling_grids = 2 * sampling_locations - 1
elif method == "discrete":
sampling_grids = sampling_locations
sampling_grids = sampling_grids.permute(0, 2, 1, 3, 4).flatten(0, 1)
sampling_grids = sampling_grids.split(num_points_list, dim=-2)
sampling_value_list = []
for level_id, (height, width) in enumerate(value_spatial_shapes):
# batch_size, height*width, num_heads, hidden_dim
# -> batch_size, height*width, num_heads*hidden_dim
# -> batch_size, num_heads*hidden_dim, height*width
# -> batch_size*num_heads, hidden_dim, height, width
value_l_ = value_list[level_id].reshape(batch_size * num_heads, hidden_dim, height, width)
# batch_size, num_queries, num_heads, num_points, 2
# -> batch_size, num_heads, num_queries, num_points, 2
# -> batch_size*num_heads, num_queries, num_points, 2
sampling_grid_l_ = sampling_grids[level_id]
# batch_size*num_heads, hidden_dim, num_queries, num_points
if method == "default":
sampling_value_l_ = nn.functional.grid_sample(
value_l_, sampling_grid_l_, mode="bilinear", padding_mode="zeros", align_corners=False
)
elif method == "discrete":
sampling_coord = (sampling_grid_l_ * torch.tensor([[width, height]], device=value.device) + 0.5).to(
torch.int64
)
# Separate clamping for x and y coordinates
sampling_coord_x = sampling_coord[..., 0].clamp(0, width - 1)
sampling_coord_y = sampling_coord[..., 1].clamp(0, height - 1)
# Combine the clamped coordinates
sampling_coord = torch.stack([sampling_coord_x, sampling_coord_y], dim=-1)
sampling_coord = sampling_coord.reshape(batch_size * num_heads, num_queries * num_points_list[level_id], 2)
sampling_idx = (
torch.arange(sampling_coord.shape[0], device=value.device)
.unsqueeze(-1)
.repeat(1, sampling_coord.shape[1])
)
sampling_value_l_ = value_l_[sampling_idx, :, sampling_coord[..., 1], sampling_coord[..., 0]]
sampling_value_l_ = sampling_value_l_.permute(0, 2, 1).reshape(
batch_size * num_heads, hidden_dim, num_queries, num_points_list[level_id]
)
sampling_value_list.append(sampling_value_l_)
# (batch_size, num_queries, num_heads, num_levels, num_points)
# -> (batch_size, num_heads, num_queries, num_levels, num_points)
# -> (batch_size, num_heads, 1, num_queries, num_levels*num_points)
attention_weights = attention_weights.permute(0, 2, 1, 3).reshape(
batch_size * num_heads, 1, num_queries, sum(num_points_list)
)
output = (
(torch.concat(sampling_value_list, dim=-1) * attention_weights)
.sum(-1)
.view(batch_size, num_heads * hidden_dim, num_queries)
)
return output.transpose(1, 2).contiguous()
# the main change
| RTDetrV2Config |
python | kubernetes-client__python | kubernetes/client/models/v1_cinder_persistent_volume_source.py | {
"start": 383,
"end": 7145
} | class ____(object):
"""NOTE: This class is auto generated by OpenAPI Generator.
Ref: https://openapi-generator.tech
Do not edit the class manually.
"""
"""
Attributes:
openapi_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The key is attribute name
and the value is json key in definition.
"""
openapi_types = {
'fs_type': 'str',
'read_only': 'bool',
'secret_ref': 'V1SecretReference',
'volume_id': 'str'
}
attribute_map = {
'fs_type': 'fsType',
'read_only': 'readOnly',
'secret_ref': 'secretRef',
'volume_id': 'volumeID'
}
def __init__(self, fs_type=None, read_only=None, secret_ref=None, volume_id=None, local_vars_configuration=None): # noqa: E501
"""V1CinderPersistentVolumeSource - a model defined in OpenAPI""" # noqa: E501
if local_vars_configuration is None:
local_vars_configuration = Configuration()
self.local_vars_configuration = local_vars_configuration
self._fs_type = None
self._read_only = None
self._secret_ref = None
self._volume_id = None
self.discriminator = None
if fs_type is not None:
self.fs_type = fs_type
if read_only is not None:
self.read_only = read_only
if secret_ref is not None:
self.secret_ref = secret_ref
self.volume_id = volume_id
@property
def fs_type(self):
"""Gets the fs_type of this V1CinderPersistentVolumeSource. # noqa: E501
fsType Filesystem type to mount. Must be a filesystem type supported by the host operating system. Examples: \"ext4\", \"xfs\", \"ntfs\". Implicitly inferred to be \"ext4\" if unspecified. More info: https://examples.k8s.io/mysql-cinder-pd/README.md # noqa: E501
:return: The fs_type of this V1CinderPersistentVolumeSource. # noqa: E501
:rtype: str
"""
return self._fs_type
@fs_type.setter
def fs_type(self, fs_type):
"""Sets the fs_type of this V1CinderPersistentVolumeSource.
fsType Filesystem type to mount. Must be a filesystem type supported by the host operating system. Examples: \"ext4\", \"xfs\", \"ntfs\". Implicitly inferred to be \"ext4\" if unspecified. More info: https://examples.k8s.io/mysql-cinder-pd/README.md # noqa: E501
:param fs_type: The fs_type of this V1CinderPersistentVolumeSource. # noqa: E501
:type: str
"""
self._fs_type = fs_type
@property
def read_only(self):
"""Gets the read_only of this V1CinderPersistentVolumeSource. # noqa: E501
readOnly is Optional: Defaults to false (read/write). ReadOnly here will force the ReadOnly setting in VolumeMounts. More info: https://examples.k8s.io/mysql-cinder-pd/README.md # noqa: E501
:return: The read_only of this V1CinderPersistentVolumeSource. # noqa: E501
:rtype: bool
"""
return self._read_only
@read_only.setter
def read_only(self, read_only):
"""Sets the read_only of this V1CinderPersistentVolumeSource.
readOnly is Optional: Defaults to false (read/write). ReadOnly here will force the ReadOnly setting in VolumeMounts. More info: https://examples.k8s.io/mysql-cinder-pd/README.md # noqa: E501
:param read_only: The read_only of this V1CinderPersistentVolumeSource. # noqa: E501
:type: bool
"""
self._read_only = read_only
@property
def secret_ref(self):
"""Gets the secret_ref of this V1CinderPersistentVolumeSource. # noqa: E501
:return: The secret_ref of this V1CinderPersistentVolumeSource. # noqa: E501
:rtype: V1SecretReference
"""
return self._secret_ref
@secret_ref.setter
def secret_ref(self, secret_ref):
"""Sets the secret_ref of this V1CinderPersistentVolumeSource.
:param secret_ref: The secret_ref of this V1CinderPersistentVolumeSource. # noqa: E501
:type: V1SecretReference
"""
self._secret_ref = secret_ref
@property
def volume_id(self):
"""Gets the volume_id of this V1CinderPersistentVolumeSource. # noqa: E501
volumeID used to identify the volume in cinder. More info: https://examples.k8s.io/mysql-cinder-pd/README.md # noqa: E501
:return: The volume_id of this V1CinderPersistentVolumeSource. # noqa: E501
:rtype: str
"""
return self._volume_id
@volume_id.setter
def volume_id(self, volume_id):
"""Sets the volume_id of this V1CinderPersistentVolumeSource.
volumeID used to identify the volume in cinder. More info: https://examples.k8s.io/mysql-cinder-pd/README.md # noqa: E501
:param volume_id: The volume_id of this V1CinderPersistentVolumeSource. # noqa: E501
:type: str
"""
if self.local_vars_configuration.client_side_validation and volume_id is None: # noqa: E501
raise ValueError("Invalid value for `volume_id`, must not be `None`") # noqa: E501
self._volume_id = volume_id
def to_dict(self):
"""Returns the model properties as a dict"""
result = {}
for attr, _ in six.iteritems(self.openapi_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value
))
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict") else item,
value.items()
))
else:
result[attr] = value
return result
def to_str(self):
"""Returns the string representation of the model"""
return pprint.pformat(self.to_dict())
def __repr__(self):
"""For `print` and `pprint`"""
return self.to_str()
def __eq__(self, other):
"""Returns true if both objects are equal"""
if not isinstance(other, V1CinderPersistentVolumeSource):
return False
return self.to_dict() == other.to_dict()
def __ne__(self, other):
"""Returns true if both objects are not equal"""
if not isinstance(other, V1CinderPersistentVolumeSource):
return True
return self.to_dict() != other.to_dict()
| V1CinderPersistentVolumeSource |
python | facelessuser__pymdown-extensions | pymdownx/magiclink.py | {
"start": 37728,
"end": 48870
} | class ____(Extension):
"""Add auto link and link transformation extensions to Markdown class."""
def __init__(self, *args, **kwargs):
"""Initialize."""
self.config = {
'hide_protocol': [
False,
"If 'True', links are displayed without the initial ftp://, http:// or https://"
"- Default: False"
],
'repo_url_shortener': [
False,
"If 'True' repo commit and issue links are shortened - Default: False"
],
'social_url_shortener': [
False,
"If 'True' social links are shortened - Default: False"
],
'shortener_user_exclude': [
{
"bitbucket": ['dashboard', 'account', 'plans', 'support', 'repo'],
"github": ['marketplace', 'notifications', 'issues', 'pull', 'sponsors', 'settings', 'support'],
"gitlab": ['dashboard', '-', 'explore', 'help', 'projects'],
"twitter": ['i', 'messages', 'bookmarks', 'home'],
"x": ['i', 'messages', 'bookmarks', 'home']
},
"A list of user names to exclude from URL shortening."
],
'repo_url_shorthand': [
False,
"If 'True' repo shorthand syntax is converted to links - Default: False"
],
'social_url_shorthand': [
False,
"If 'True' social shorthand syntax is converted to links - Default: False"
],
'provider': [
'github',
'The base provider to use (github, gitlab, bitbucket, x) - Default: "github"'
],
'labels': [
{},
"Title labels - Default: {}"
],
'normalize_issue_symbols': [
False,
'Normalize issue, pull, and discussions symbols all to use # - Default: False'
],
'user': [
'',
'The base user name to use - Default: ""'
],
'repo': [
'',
'The base repo to use - Default: ""'
],
'custom': [
{},
"Custom repositories hosts - Default {}"
]
}
super().__init__(*args, **kwargs)
def setup_autolinks(self, md, config):
"""Setup auto links."""
# Setup general link patterns
auto_link_pattern = MagiclinkAutoPattern(RE_AUTOLINK, md)
auto_link_pattern.config = config
md.inlinePatterns.register(auto_link_pattern, "autolink", 120)
link_pattern = MagiclinkPattern(RE_LINK, md)
link_pattern.config = config
md.inlinePatterns.register(link_pattern, "magic-link", 85)
md.inlinePatterns.register(MagiclinkMailPattern(RE_MAIL, md), "magic-mail", 84.9)
def setup_shorthand(self, md):
"""Setup shorthand."""
# Setup URL shortener
escape_chars = ['@']
util.escape_chars(md, escape_chars)
# Repository shorthand
if self.git_short:
git_ext_repo = MagiclinkRepositoryPattern(
self.re_git_ext_repo_mentions,
md,
self.user,
self.repo,
self.provider,
self.labels,
self.normalize,
self.provider_info
)
md.inlinePatterns.register(git_ext_repo, "magic-repo-ext-mention", 79.9)
if not self.is_social:
git_int_repo = MagiclinkRepositoryPattern(
RE_GIT_INT_REPO_MENTIONS.format(self.int_mentions),
md,
self.user,
self.repo,
self.provider,
self.labels,
self.normalize,
self.provider_info
)
md.inlinePatterns.register(git_int_repo, "magic-repo-int-mention", 79.8)
# Mentions
pattern = RE_ALL_EXT_MENTIONS.format('|'.join(self.ext_mentions))
git_mention = MagiclinkMentionPattern(
pattern,
md,
self.user,
self.repo,
self.provider,
self.labels,
self.normalize,
self.provider_info
)
md.inlinePatterns.register(git_mention, "magic-ext-mention", 79.7)
git_mention = MagiclinkMentionPattern(
RE_INT_MENTIONS.format(self.int_mentions),
md,
self.user,
self.repo,
self.provider,
self.labels,
self.normalize,
self.provider_info
)
md.inlinePatterns.register(git_mention, "magic-int-mention", 79.6)
# Other project refs
if self.git_short:
git_ext_refs = MagiclinkExternalRefsPattern(
self.re_git_ext_refs,
md,
self.user,
self.repo,
self.provider,
self.labels,
self.normalize,
self.provider_info
)
md.inlinePatterns.register(git_ext_refs, "magic-ext-refs", 79.5)
if not self.is_social:
git_int_refs = MagiclinkExternalRefsPattern(
RE_GIT_INT_EXT_REFS.format(self.int_mentions),
md,
self.user,
self.repo,
self.provider,
self.labels,
self.normalize,
self.provider_info
)
md.inlinePatterns.register(git_int_refs, "magic-int-refs", 79.4)
git_int_micro_refs = MagiclinkInternalRefsPattern(
RE_GIT_INT_MICRO_REFS,
md,
self.user,
self.repo,
self.provider,
self.labels,
self.normalize,
self.provider_info
)
md.inlinePatterns.register(git_int_micro_refs, "magic-int-micro-refs", 79.3)
def setup_shortener(
self,
md,
config
):
"""Setup shortener."""
shortener = MagicShortenerTreeprocessor(
md,
self.base_url,
self.base_user_url,
self.labels,
self.normalize,
self.repo_shortner,
self.social_shortener,
self.custom_shortners,
self.shortener_exclusions,
self.provider,
self.provider_info
)
shortener.config = config
md.treeprocessors.register(shortener, "magic-repo-shortener", 9.9)
def get_base_urls(self, config):
"""Get base URLs."""
base_url = ''
base_user_url = ''
if self.is_social:
return base_url, base_user_url
if self.user and self.repo:
base_url = '{}/{}/{}/'.format(self.provider_info[self.provider]['url'], self.user, self.repo)
base_user_url = '{}/{}/'.format(self.provider_info[self.provider]['url'], self.user)
return base_url, base_user_url
def extendMarkdown(self, md):
"""Add support for turning html links and emails to link tags."""
config = self.getConfigs()
# Setup repo variables
self.user = config.get('user', '')
self.repo = config.get('repo', '')
self.provider = config.get('provider', 'github')
self.labels = config.get('labels', {})
self.normalize = config.get('normalize_issue_symbols', False)
self.is_social = self.provider in SOCIAL_PROVIDERS
self.git_short = config.get('repo_url_shorthand', False)
self.social_short = config.get('social_url_shorthand', False)
self.repo_shortner = config.get('repo_url_shortener', False)
self.social_shortener = config.get('social_url_shortener', False)
self.shortener_exclusions = {k: set(v) for k, v in DEFAULT_EXCLUDES.items()}
self.provider_info = PROVIDER_INFO.copy()
custom_provider = config.get('custom', {})
excludes = config.get('shortener_user_exclude', {})
self.custom_shortners = {}
external_users = [RE_GITHUB_EXT_MENTIONS, RE_GITLAB_EXT_MENTIONS, RE_BITBUCKET_EXT_MENTIONS]
for custom, entry in custom_provider.items():
if not RE_CUSTOM_NAME.match(custom):
raise ValueError(
f"Name '{custom}' not allowed, provider name must contain only letters and numbers"
)
if custom not in self.provider_info:
self.provider_info[custom] = create_provider(entry['type'], entry['host'])
self.provider_info[custom]['provider'] = entry['label']
self.custom_shortners[custom] = {
'repo': re.compile(
r'(?xi)^{}/?$'.format(
create_repo_link_pattern(entry['type'], entry['host'], entry.get('www', True))
)
),
'user': re.compile(
r'(?xi)^{}/?$'.format(
create_user_link_pattern(entry['type'], entry['host'], entry.get('www', True))
)
)
}
if custom not in excludes:
excludes[custom] = excludes.get(entry['type'], [])
external_users.append(create_ext_mentions(custom, entry['type']))
self.re_git_ext_repo_mentions = RE_GIT_EXT_REPO_MENTIONS.format('|'.join(external_users))
self.re_git_ext_refs = RE_GIT_EXT_REFS.format('|'.join(external_users))
for key, value in config.get('shortener_user_exclude', {}).items():
if key in self.provider_info and isinstance(value, (list, tuple, set)):
self.shortener_exclusions[key] = {x.lower() for x in value}
# Ensure valid provider
if self.provider not in self.provider_info:
self.provider = 'github'
self.setup_autolinks(md, config)
if self.git_short or self.social_short:
self.ext_mentions = []
if self.git_short:
self.ext_mentions.extend(external_users)
if self.social_short:
self.ext_mentions.append(RE_X_EXT_MENTIONS)
self.ext_mentions.append(RE_TWITTER_EXT_MENTIONS)
self.int_mentions = self.provider_info[self.provider]['user_pattern']
self.setup_shorthand(md)
# Setup link post processor for shortening repository links
if self.repo_shortner or self.social_shortener:
self.base_url, self.base_user_url = self.get_base_urls(config)
self.setup_shortener(md, config)
def makeExtension(*args, **kwargs):
"""Return extension."""
return MagiclinkExtension(*args, **kwargs)
| MagiclinkExtension |
python | pytest-dev__pytest | src/_pytest/_io/pprint.py | {
"start": 1815,
"end": 19622
} | class ____:
def __init__(
self,
indent: int = 4,
width: int = 80,
depth: int | None = None,
) -> None:
"""Handle pretty printing operations onto a stream using a set of
configured parameters.
indent
Number of spaces to indent for each level of nesting.
width
Attempted maximum number of columns in the output.
depth
The maximum depth to print out nested structures.
"""
if indent < 0:
raise ValueError("indent must be >= 0")
if depth is not None and depth <= 0:
raise ValueError("depth must be > 0")
if not width:
raise ValueError("width must be != 0")
self._depth = depth
self._indent_per_level = indent
self._width = width
def pformat(self, object: Any) -> str:
sio = _StringIO()
self._format(object, sio, 0, 0, set(), 0)
return sio.getvalue()
def _format(
self,
object: Any,
stream: IO[str],
indent: int,
allowance: int,
context: set[int],
level: int,
) -> None:
objid = id(object)
if objid in context:
stream.write(_recursion(object))
return
p = self._dispatch.get(type(object).__repr__, None)
if p is not None:
context.add(objid)
p(self, object, stream, indent, allowance, context, level + 1)
context.remove(objid)
elif (
_dataclasses.is_dataclass(object)
and not isinstance(object, type)
and object.__dataclass_params__.repr # type:ignore[attr-defined]
and
# Check dataclass has generated repr method.
hasattr(object.__repr__, "__wrapped__")
and "__create_fn__" in object.__repr__.__wrapped__.__qualname__
):
context.add(objid)
self._pprint_dataclass(
object, stream, indent, allowance, context, level + 1
)
context.remove(objid)
else:
stream.write(self._repr(object, context, level))
def _pprint_dataclass(
self,
object: Any,
stream: IO[str],
indent: int,
allowance: int,
context: set[int],
level: int,
) -> None:
cls_name = object.__class__.__name__
items = [
(f.name, getattr(object, f.name))
for f in _dataclasses.fields(object)
if f.repr
]
stream.write(cls_name + "(")
self._format_namespace_items(items, stream, indent, allowance, context, level)
stream.write(")")
_dispatch: dict[
Callable[..., str],
Callable[[PrettyPrinter, Any, IO[str], int, int, set[int], int], None],
] = {}
def _pprint_dict(
self,
object: Any,
stream: IO[str],
indent: int,
allowance: int,
context: set[int],
level: int,
) -> None:
write = stream.write
write("{")
items = sorted(object.items(), key=_safe_tuple)
self._format_dict_items(items, stream, indent, allowance, context, level)
write("}")
_dispatch[dict.__repr__] = _pprint_dict
def _pprint_ordered_dict(
self,
object: Any,
stream: IO[str],
indent: int,
allowance: int,
context: set[int],
level: int,
) -> None:
if not len(object):
stream.write(repr(object))
return
cls = object.__class__
stream.write(cls.__name__ + "(")
self._pprint_dict(object, stream, indent, allowance, context, level)
stream.write(")")
_dispatch[_collections.OrderedDict.__repr__] = _pprint_ordered_dict
def _pprint_list(
self,
object: Any,
stream: IO[str],
indent: int,
allowance: int,
context: set[int],
level: int,
) -> None:
stream.write("[")
self._format_items(object, stream, indent, allowance, context, level)
stream.write("]")
_dispatch[list.__repr__] = _pprint_list
def _pprint_tuple(
self,
object: Any,
stream: IO[str],
indent: int,
allowance: int,
context: set[int],
level: int,
) -> None:
stream.write("(")
self._format_items(object, stream, indent, allowance, context, level)
stream.write(")")
_dispatch[tuple.__repr__] = _pprint_tuple
def _pprint_set(
self,
object: Any,
stream: IO[str],
indent: int,
allowance: int,
context: set[int],
level: int,
) -> None:
if not len(object):
stream.write(repr(object))
return
typ = object.__class__
if typ is set:
stream.write("{")
endchar = "}"
else:
stream.write(typ.__name__ + "({")
endchar = "})"
object = sorted(object, key=_safe_key)
self._format_items(object, stream, indent, allowance, context, level)
stream.write(endchar)
_dispatch[set.__repr__] = _pprint_set
_dispatch[frozenset.__repr__] = _pprint_set
def _pprint_str(
self,
object: Any,
stream: IO[str],
indent: int,
allowance: int,
context: set[int],
level: int,
) -> None:
write = stream.write
if not len(object):
write(repr(object))
return
chunks = []
lines = object.splitlines(True)
if level == 1:
indent += 1
allowance += 1
max_width1 = max_width = self._width - indent
for i, line in enumerate(lines):
rep = repr(line)
if i == len(lines) - 1:
max_width1 -= allowance
if len(rep) <= max_width1:
chunks.append(rep)
else:
# A list of alternating (non-space, space) strings
parts = re.findall(r"\S*\s*", line)
assert parts
assert not parts[-1]
parts.pop() # drop empty last part
max_width2 = max_width
current = ""
for j, part in enumerate(parts):
candidate = current + part
if j == len(parts) - 1 and i == len(lines) - 1:
max_width2 -= allowance
if len(repr(candidate)) > max_width2:
if current:
chunks.append(repr(current))
current = part
else:
current = candidate
if current:
chunks.append(repr(current))
if len(chunks) == 1:
write(rep)
return
if level == 1:
write("(")
for i, rep in enumerate(chunks):
if i > 0:
write("\n" + " " * indent)
write(rep)
if level == 1:
write(")")
_dispatch[str.__repr__] = _pprint_str
def _pprint_bytes(
self,
object: Any,
stream: IO[str],
indent: int,
allowance: int,
context: set[int],
level: int,
) -> None:
write = stream.write
if len(object) <= 4:
write(repr(object))
return
parens = level == 1
if parens:
indent += 1
allowance += 1
write("(")
delim = ""
for rep in _wrap_bytes_repr(object, self._width - indent, allowance):
write(delim)
write(rep)
if not delim:
delim = "\n" + " " * indent
if parens:
write(")")
_dispatch[bytes.__repr__] = _pprint_bytes
def _pprint_bytearray(
self,
object: Any,
stream: IO[str],
indent: int,
allowance: int,
context: set[int],
level: int,
) -> None:
write = stream.write
write("bytearray(")
self._pprint_bytes(
bytes(object), stream, indent + 10, allowance + 1, context, level + 1
)
write(")")
_dispatch[bytearray.__repr__] = _pprint_bytearray
def _pprint_mappingproxy(
self,
object: Any,
stream: IO[str],
indent: int,
allowance: int,
context: set[int],
level: int,
) -> None:
stream.write("mappingproxy(")
self._format(object.copy(), stream, indent, allowance, context, level)
stream.write(")")
_dispatch[_types.MappingProxyType.__repr__] = _pprint_mappingproxy
def _pprint_simplenamespace(
self,
object: Any,
stream: IO[str],
indent: int,
allowance: int,
context: set[int],
level: int,
) -> None:
if type(object) is _types.SimpleNamespace:
# The SimpleNamespace repr is "namespace" instead of the class
# name, so we do the same here. For subclasses; use the class name.
cls_name = "namespace"
else:
cls_name = object.__class__.__name__
items = object.__dict__.items()
stream.write(cls_name + "(")
self._format_namespace_items(items, stream, indent, allowance, context, level)
stream.write(")")
_dispatch[_types.SimpleNamespace.__repr__] = _pprint_simplenamespace
def _format_dict_items(
self,
items: list[tuple[Any, Any]],
stream: IO[str],
indent: int,
allowance: int,
context: set[int],
level: int,
) -> None:
if not items:
return
write = stream.write
item_indent = indent + self._indent_per_level
delimnl = "\n" + " " * item_indent
for key, ent in items:
write(delimnl)
write(self._repr(key, context, level))
write(": ")
self._format(ent, stream, item_indent, 1, context, level)
write(",")
write("\n" + " " * indent)
def _format_namespace_items(
self,
items: list[tuple[Any, Any]],
stream: IO[str],
indent: int,
allowance: int,
context: set[int],
level: int,
) -> None:
if not items:
return
write = stream.write
item_indent = indent + self._indent_per_level
delimnl = "\n" + " " * item_indent
for key, ent in items:
write(delimnl)
write(key)
write("=")
if id(ent) in context:
# Special-case representation of recursion to match standard
# recursive dataclass repr.
write("...")
else:
self._format(
ent,
stream,
item_indent + len(key) + 1,
1,
context,
level,
)
write(",")
write("\n" + " " * indent)
def _format_items(
self,
items: list[Any],
stream: IO[str],
indent: int,
allowance: int,
context: set[int],
level: int,
) -> None:
if not items:
return
write = stream.write
item_indent = indent + self._indent_per_level
delimnl = "\n" + " " * item_indent
for item in items:
write(delimnl)
self._format(item, stream, item_indent, 1, context, level)
write(",")
write("\n" + " " * indent)
def _repr(self, object: Any, context: set[int], level: int) -> str:
return self._safe_repr(object, context.copy(), self._depth, level)
def _pprint_default_dict(
self,
object: Any,
stream: IO[str],
indent: int,
allowance: int,
context: set[int],
level: int,
) -> None:
rdf = self._repr(object.default_factory, context, level)
stream.write(f"{object.__class__.__name__}({rdf}, ")
self._pprint_dict(object, stream, indent, allowance, context, level)
stream.write(")")
_dispatch[_collections.defaultdict.__repr__] = _pprint_default_dict
def _pprint_counter(
self,
object: Any,
stream: IO[str],
indent: int,
allowance: int,
context: set[int],
level: int,
) -> None:
stream.write(object.__class__.__name__ + "(")
if object:
stream.write("{")
items = object.most_common()
self._format_dict_items(items, stream, indent, allowance, context, level)
stream.write("}")
stream.write(")")
_dispatch[_collections.Counter.__repr__] = _pprint_counter
def _pprint_chain_map(
self,
object: Any,
stream: IO[str],
indent: int,
allowance: int,
context: set[int],
level: int,
) -> None:
if not len(object.maps) or (len(object.maps) == 1 and not len(object.maps[0])):
stream.write(repr(object))
return
stream.write(object.__class__.__name__ + "(")
self._format_items(object.maps, stream, indent, allowance, context, level)
stream.write(")")
_dispatch[_collections.ChainMap.__repr__] = _pprint_chain_map
def _pprint_deque(
self,
object: Any,
stream: IO[str],
indent: int,
allowance: int,
context: set[int],
level: int,
) -> None:
stream.write(object.__class__.__name__ + "(")
if object.maxlen is not None:
stream.write(f"maxlen={object.maxlen}, ")
stream.write("[")
self._format_items(object, stream, indent, allowance + 1, context, level)
stream.write("])")
_dispatch[_collections.deque.__repr__] = _pprint_deque
def _pprint_user_dict(
self,
object: Any,
stream: IO[str],
indent: int,
allowance: int,
context: set[int],
level: int,
) -> None:
self._format(object.data, stream, indent, allowance, context, level - 1)
_dispatch[_collections.UserDict.__repr__] = _pprint_user_dict
def _pprint_user_list(
self,
object: Any,
stream: IO[str],
indent: int,
allowance: int,
context: set[int],
level: int,
) -> None:
self._format(object.data, stream, indent, allowance, context, level - 1)
_dispatch[_collections.UserList.__repr__] = _pprint_user_list
def _pprint_user_string(
self,
object: Any,
stream: IO[str],
indent: int,
allowance: int,
context: set[int],
level: int,
) -> None:
self._format(object.data, stream, indent, allowance, context, level - 1)
_dispatch[_collections.UserString.__repr__] = _pprint_user_string
def _safe_repr(
self, object: Any, context: set[int], maxlevels: int | None, level: int
) -> str:
typ = type(object)
if typ in _builtin_scalars:
return repr(object)
r = getattr(typ, "__repr__", None)
if issubclass(typ, dict) and r is dict.__repr__:
if not object:
return "{}"
objid = id(object)
if maxlevels and level >= maxlevels:
return "{...}"
if objid in context:
return _recursion(object)
context.add(objid)
components: list[str] = []
append = components.append
level += 1
for k, v in sorted(object.items(), key=_safe_tuple):
krepr = self._safe_repr(k, context, maxlevels, level)
vrepr = self._safe_repr(v, context, maxlevels, level)
append(f"{krepr}: {vrepr}")
context.remove(objid)
return "{{{}}}".format(", ".join(components))
if (issubclass(typ, list) and r is list.__repr__) or (
issubclass(typ, tuple) and r is tuple.__repr__
):
if issubclass(typ, list):
if not object:
return "[]"
format = "[%s]"
elif len(object) == 1:
format = "(%s,)"
else:
if not object:
return "()"
format = "(%s)"
objid = id(object)
if maxlevels and level >= maxlevels:
return format % "..."
if objid in context:
return _recursion(object)
context.add(objid)
components = []
append = components.append
level += 1
for o in object:
orepr = self._safe_repr(o, context, maxlevels, level)
append(orepr)
context.remove(objid)
return format % ", ".join(components)
return repr(object)
_builtin_scalars = frozenset(
{str, bytes, bytearray, float, complex, bool, type(None), int}
)
def _recursion(object: Any) -> str:
return f"<Recursion on {type(object).__name__} with id={id(object)}>"
def _wrap_bytes_repr(object: Any, width: int, allowance: int) -> Iterator[str]:
current = b""
last = len(object) // 4 * 4
for i in range(0, len(object), 4):
part = object[i : i + 4]
candidate = current + part
if i == last:
width -= allowance
if len(repr(candidate)) > width:
if current:
yield repr(current)
current = part
else:
current = candidate
if current:
yield repr(current)
| PrettyPrinter |
python | bokeh__bokeh | src/bokeh/models/annotations/labels.py | {
"start": 6579,
"end": 9667
} | class ____(DataAnnotation):
''' Render multiple text labels as annotations.
``LabelSet`` will render multiple text labels at given ``x`` and ``y``
coordinates, which can be in either screen (pixel) space, or data (axis
range) space. In this case (as opposed to the single ``Label`` model),
``x`` and ``y`` can also be the name of a column from a
:class:`~bokeh.models.sources.ColumnDataSource`, in which case the labels
will be "vectorized" using coordinate values from the specified columns.
The label can also be configured with a screen space offset from ``x`` and
``y``, by using the ``x_offset`` and ``y_offset`` properties. These offsets
may be vectorized by giving the name of a data source column.
Additionally, the label can be rotated with the ``angle`` property (which
may also be a column name.)
There are also standard text, fill, and line properties to control the
appearance of the text, its background, as well as the rectangular bounding
box border.
The data source is provided by setting the ``source`` property.
'''
# explicit __init__ to support Init signatures
def __init__(self, *args: Any, **kwargs: Any) -> None:
super().__init__(*args, **kwargs)
x = NumberSpec(default=field("x"), help="""
The x-coordinates to locate the text anchors.
""")
x_units = Enum(CoordinateUnits, default='data', help="""
The unit type for the ``xs`` attribute. Interpreted as |data units| by
default.
""")
y = NumberSpec(default=field("y"), help="""
The y-coordinates to locate the text anchors.
""")
y_units = Enum(CoordinateUnits, default='data', help="""
The unit type for the ``ys`` attribute. Interpreted as |data units| by
default.
""")
text = NullStringSpec(default=field("text"), help="""
The text values to render.
""")
angle = AngleSpec(default=0, help="""
The angles to rotate the text, as measured from the horizontal.
""")
x_offset = NumberSpec(default=0, help="""
Offset values to apply to the x-coordinates.
This is useful, for instance, if it is desired to "float" text a fixed
distance in |screen units| from a given data position.
""")
y_offset = NumberSpec(default=0, help="""
Offset values to apply to the y-coordinates.
This is useful, for instance, if it is desired to "float" text a fixed
distance in |screen units| from a given data position.
""")
text_props = Include(TextProps, help="""
The {prop} values for the text.
""")
background_fill_props = Include(FillProps, prefix="background", help="""
The {prop} values for the text bounding box.
""")
background_hatch_props = Include(HatchProps, prefix="background", help="""
The {prop} values for the text bounding box.
""")
background_fill_color = Override(default=None)
border_props = Include(LineProps, prefix="border", help="""
The {prop} values for the text bounding box.
""")
border_line_color = Override(default=None)
| LabelSet |
python | walkccc__LeetCode | solutions/2461. Maximum Sum of Distinct Subarrays With Length K/2461.py | {
"start": 0,
"end": 501
} | class ____:
def maximumSubarraySum(self, nums: list[int], k: int) -> int:
ans = 0
summ = 0
distinct = 0
count = collections.Counter()
for i, num in enumerate(nums):
summ += num
count[num] += 1
if count[num] == 1:
distinct += 1
if i >= k:
count[nums[i - k]] -= 1
if count[nums[i - k]] == 0:
distinct -= 1
summ -= nums[i - k]
if i >= k - 1 and distinct == k:
ans = max(ans, summ)
return ans
| Solution |
python | sqlalchemy__sqlalchemy | test/typing/plain_files/inspection_inspect.py | {
"start": 488,
"end": 606
} | class ____(Base):
__tablename__ = "a"
id: Mapped[int] = mapped_column(primary_key=True)
data: Mapped[str]
| A |
python | networkx__networkx | networkx/algorithms/isomorphism/tests/test_isomorphvf2.py | {
"start": 4252,
"end": 14484
} | class ____:
@classmethod
def setup_class(cls):
global atlas
from networkx.generators import atlas
cls.GAG = atlas.graph_atlas_g()
def test_graph_atlas(self):
rng = random.Random(42)
# Atlas = nx.graph_atlas_g()[0:208] # 208, 6 nodes or less
Atlas = self.GAG[0:100]
alphabet = list(range(26))
for graph in Atlas:
nlist = list(graph)
labels = alphabet[: len(nlist)]
for _ in range(10):
rng.shuffle(labels)
d = dict(zip(nlist, labels))
relabel = nx.relabel_nodes(graph, d)
gm = iso.GraphMatcher(graph, relabel)
assert gm.is_isomorphic()
def test_multiedge():
# Simple test for multigraphs
# Need something much more rigorous
edges = [
(0, 1),
(1, 2),
(2, 3),
(3, 4),
(4, 5),
(5, 6),
(6, 7),
(7, 8),
(8, 9),
(9, 10),
(10, 11),
(10, 11),
(11, 12),
(11, 12),
(12, 13),
(12, 13),
(13, 14),
(13, 14),
(14, 15),
(14, 15),
(15, 16),
(15, 16),
(16, 17),
(16, 17),
(17, 18),
(17, 18),
(18, 19),
(18, 19),
(19, 0),
(19, 0),
]
nodes = list(range(20))
rng = random.Random(42)
for g1 in [nx.MultiGraph(), nx.MultiDiGraph()]:
g1.add_edges_from(edges)
for _ in range(10):
new_nodes = list(nodes)
rng.shuffle(new_nodes)
d = dict(zip(nodes, new_nodes))
g2 = nx.relabel_nodes(g1, d)
if not g1.is_directed():
gm = iso.GraphMatcher(g1, g2)
else:
gm = iso.DiGraphMatcher(g1, g2)
assert gm.is_isomorphic()
# Testing if monomorphism works in multigraphs
assert gm.subgraph_is_monomorphic()
@pytest.mark.parametrize("G1", [nx.Graph(), nx.MultiGraph()])
@pytest.mark.parametrize("G2", [nx.Graph(), nx.MultiGraph()])
def test_matcher_raises(G1, G2):
undirected_matchers = [iso.GraphMatcher, iso.MultiGraphMatcher]
directed_matchers = [iso.DiGraphMatcher, iso.MultiDiGraphMatcher]
for matcher in undirected_matchers:
matcher(G1, G2)
msg = r"\(Multi-\)GraphMatcher\(\) not defined for directed graphs"
with pytest.raises(nx.NetworkXError, match=msg):
matcher(G1.to_directed(), G2.to_directed())
for matcher in directed_matchers:
matcher(G1.to_directed(), G2.to_directed())
msg = r"\(Multi-\)DiGraphMatcher\(\) not defined for undirected graphs"
with pytest.raises(nx.NetworkXError, match=msg):
matcher(G1, G2)
for matcher in undirected_matchers + directed_matchers:
msg = r"G1 and G2 must have the same directedness"
with pytest.raises(nx.NetworkXError, match=msg):
matcher(G1, G2.to_directed())
with pytest.raises(nx.NetworkXError, match=msg):
matcher(G1.to_directed(), G2)
def test_selfloop():
# Simple test for graphs with selfloops
edges = [
(0, 1),
(0, 2),
(1, 2),
(1, 3),
(2, 2),
(2, 4),
(3, 1),
(3, 2),
(4, 2),
(4, 5),
(5, 4),
]
nodes = list(range(6))
rng = random.Random(42)
for g1 in [nx.Graph(), nx.DiGraph()]:
g1.add_edges_from(edges)
for _ in range(100):
new_nodes = list(nodes)
rng.shuffle(new_nodes)
d = dict(zip(nodes, new_nodes))
g2 = nx.relabel_nodes(g1, d)
if not g1.is_directed():
gm = iso.GraphMatcher(g1, g2)
else:
gm = iso.DiGraphMatcher(g1, g2)
assert gm.is_isomorphic()
def test_selfloop_mono():
# Simple test for graphs with selfloops
edges0 = [
(0, 1),
(0, 2),
(1, 2),
(1, 3),
(2, 4),
(3, 1),
(3, 2),
(4, 2),
(4, 5),
(5, 4),
]
edges = edges0 + [(2, 2)]
nodes = list(range(6))
rng = random.Random(42)
for g1 in [nx.Graph(), nx.DiGraph()]:
g1.add_edges_from(edges)
for _ in range(100):
new_nodes = list(nodes)
rng.shuffle(new_nodes)
d = dict(zip(nodes, new_nodes))
g2 = nx.relabel_nodes(g1, d)
g2.remove_edges_from(nx.selfloop_edges(g2))
if not g1.is_directed():
gm = iso.GraphMatcher(g2, g1)
else:
gm = iso.DiGraphMatcher(g2, g1)
assert not gm.subgraph_is_monomorphic()
def test_isomorphism_iter1():
# As described in:
# http://groups.google.com/group/networkx-discuss/browse_thread/thread/2ff65c67f5e3b99f/d674544ebea359bb?fwc=1
g1 = nx.DiGraph()
g2 = nx.DiGraph()
g3 = nx.DiGraph()
g1.add_edge("A", "B")
g1.add_edge("B", "C")
g2.add_edge("Y", "Z")
g3.add_edge("Z", "Y")
gm12 = iso.DiGraphMatcher(g1, g2)
gm13 = iso.DiGraphMatcher(g1, g3)
x = list(gm12.subgraph_isomorphisms_iter())
y = list(gm13.subgraph_isomorphisms_iter())
assert {"A": "Y", "B": "Z"} in x
assert {"B": "Y", "C": "Z"} in x
assert {"A": "Z", "B": "Y"} in y
assert {"B": "Z", "C": "Y"} in y
assert len(x) == len(y)
assert len(x) == 2
def test_monomorphism_iter1():
g1 = nx.DiGraph()
g2 = nx.DiGraph()
g1.add_edge("A", "B")
g1.add_edge("B", "C")
g1.add_edge("C", "A")
g2.add_edge("X", "Y")
g2.add_edge("Y", "Z")
gm12 = iso.DiGraphMatcher(g1, g2)
x = list(gm12.subgraph_monomorphisms_iter())
assert {"A": "X", "B": "Y", "C": "Z"} in x
assert {"A": "Y", "B": "Z", "C": "X"} in x
assert {"A": "Z", "B": "X", "C": "Y"} in x
assert len(x) == 3
gm21 = iso.DiGraphMatcher(g2, g1)
# Check if StopIteration exception returns False
assert not gm21.subgraph_is_monomorphic()
def test_isomorphism_iter2():
# Path
for L in range(2, 10):
g1 = nx.path_graph(L)
gm = iso.GraphMatcher(g1, g1)
s = len(list(gm.isomorphisms_iter()))
assert s == 2
# Cycle
for L in range(3, 10):
g1 = nx.cycle_graph(L)
gm = iso.GraphMatcher(g1, g1)
s = len(list(gm.isomorphisms_iter()))
assert s == 2 * L
def test_multiple():
# Verify that we can use the graph matcher multiple times
edges = [("A", "B"), ("B", "A"), ("B", "C")]
for g1, g2 in [(nx.Graph(), nx.Graph()), (nx.DiGraph(), nx.DiGraph())]:
g1.add_edges_from(edges)
g2.add_edges_from(edges)
g3 = nx.subgraph(g2, ["A", "B"])
if not g1.is_directed():
gmA = iso.GraphMatcher(g1, g2)
gmB = iso.GraphMatcher(g1, g3)
else:
gmA = iso.DiGraphMatcher(g1, g2)
gmB = iso.DiGraphMatcher(g1, g3)
assert gmA.is_isomorphic()
g2.remove_node("C")
if not g1.is_directed():
gmA = iso.GraphMatcher(g1, g2)
else:
gmA = iso.DiGraphMatcher(g1, g2)
assert gmA.subgraph_is_isomorphic()
assert gmB.subgraph_is_isomorphic()
assert gmA.subgraph_is_monomorphic()
assert gmB.subgraph_is_monomorphic()
# for m in [gmB.mapping, gmB.mapping]:
# assert_true(m['A'] == 'A')
# assert_true(m['B'] == 'B')
# assert_true('C' not in m)
def test_noncomparable_nodes():
node1 = object()
node2 = object()
node3 = object()
# Graph
G = nx.path_graph([node1, node2, node3])
gm = iso.GraphMatcher(G, G)
assert gm.is_isomorphic()
# Just testing some cases
assert gm.subgraph_is_monomorphic()
# DiGraph
G = nx.path_graph([node1, node2, node3], create_using=nx.DiGraph)
H = nx.path_graph([node3, node2, node1], create_using=nx.DiGraph)
dgm = iso.DiGraphMatcher(G, H)
assert dgm.is_isomorphic()
# Just testing some cases
assert dgm.subgraph_is_monomorphic()
def test_monomorphism_edge_match():
G = nx.DiGraph()
G.add_node(1)
G.add_node(2)
G.add_edge(1, 2, label="A")
G.add_edge(2, 1, label="B")
G.add_edge(2, 2, label="C")
SG = nx.DiGraph()
SG.add_node(5)
SG.add_node(6)
SG.add_edge(5, 6, label="A")
gm = iso.DiGraphMatcher(G, SG, edge_match=iso.categorical_edge_match("label", None))
assert gm.subgraph_is_monomorphic()
def test_isomorphvf2pp_multidigraphs():
g = nx.MultiDiGraph({0: [1, 1, 2, 2, 3], 1: [2, 3, 3], 2: [3]})
h = nx.MultiDiGraph({0: [1, 1, 2, 2, 3], 1: [2, 3, 3], 3: [2]})
assert not (nx.vf2pp_is_isomorphic(g, h))
@pytest.mark.parametrize(
("e1", "e2", "isomorphic", "subgraph_is_isomorphic"),
[
([(0, 1), (0, 2)], [(0, 1), (0, 2), (1, 2)], False, False),
([(0, 1), (0, 2)], [(0, 1), (0, 2), (2, 1)], False, False),
([(0, 1), (1, 2)], [(0, 1), (1, 2), (2, 0)], False, False),
([(0, 1)], [(0, 1), (1, 2), (2, 0)], False, False),
([(0, 1), (1, 2), (2, 0)], [(0, 1)], False, True),
([(0, 1), (1, 2)], [(0, 1), (2, 0), (2, 1)], False, False),
([(0, 1), (0, 2), (1, 2)], [(0, 1), (0, 2), (2, 1)], True, True),
([(0, 1), (0, 2), (1, 2)], [(0, 1), (1, 2), (2, 0)], False, False),
(
[(0, 0), (0, 1), (1, 2), (2, 1)],
[(0, 1), (1, 0), (1, 2), (2, 0)],
False,
False,
),
(
[(0, 0), (1, 0), (1, 2), (2, 1)],
[(0, 1), (0, 2), (1, 0), (1, 2)],
False,
False,
),
(
[(0, 0), (0, 1), (0, 2), (1, 0), (1, 2), (2, 0), (2, 1), (2, 2)],
[(0, 0), (0, 1), (0, 2), (1, 1), (1, 2), (2, 0), (2, 1), (2, 2)],
False,
False,
),
],
)
def test_three_node(e1, e2, isomorphic, subgraph_is_isomorphic):
"""Test some edge cases distilled from random search of the input space."""
G1 = nx.DiGraph(e1)
G2 = nx.DiGraph(e2)
gm = iso.DiGraphMatcher(G1, G2)
assert gm.is_isomorphic() == isomorphic
assert gm.subgraph_is_isomorphic() == subgraph_is_isomorphic
| TestAtlas |
python | django__django | tests/delete_regress/models.py | {
"start": 3134,
"end": 3221
} | class ____(models.Model):
name = models.CharField(max_length=64, unique=True)
| OrgUnit |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/dialects/mysql/types.py | {
"start": 10039,
"end": 10703
} | class ____(_IntegerType, sqltypes.BIGINT):
"""MySQL BIGINTEGER type."""
__visit_name__ = "BIGINT"
def __init__(self, display_width: Optional[int] = None, **kw: Any):
"""Construct a BIGINTEGER.
:param display_width: Optional, maximum display width for this number.
:param unsigned: a boolean, optional.
:param zerofill: Optional. If true, values will be stored as strings
left-padded with zeros. Note that this does not effect the values
returned by the underlying database API, which continue to be
numeric.
"""
super().__init__(display_width=display_width, **kw)
| BIGINT |
python | modin-project__modin | asv_bench/benchmarks/benchmarks.py | {
"start": 17850,
"end": 19241
} | class ____:
param_names = ["value_type", "shape", "limit"]
params = [
["scalar", "dict", "DataFrame", "Series"],
get_benchmark_shapes("TimeFillnaDataFrame"),
[None, 0.8],
]
def setup(self, value_type, shape, limit):
self.df = gen_nan_data(*shape)
columns = self.df.columns
if value_type == "scalar":
self.value = 18.19
elif value_type == "dict":
self.value = {k: i * 1.23 for i, k in enumerate(columns)}
elif value_type == "Series":
self.value = IMPL.Series(
[i * 1.23 for i in range(len(columns))], index=columns
)
elif value_type == "DataFrame":
self.value = IMPL.DataFrame(
{
k: [i + j * 1.23 for j in range(shape[0])]
for i, k in enumerate(columns)
},
index=IMPL.RangeIndex(shape[0]),
columns=columns,
)
else:
assert False
limit = int(limit * shape[0]) if limit else None
self.kw = {"value": self.value, "limit": limit}
def time_fillna(self, value_type, shape, limit):
execute(self.df.fillna(**self.kw))
def time_fillna_inplace(self, value_type, shape, limit):
self.df.fillna(inplace=True, **self.kw)
execute(self.df)
| TimeFillnaDataFrame |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-braintree/source_braintree/source.py | {
"start": 2262,
"end": 2922
} | class ____(BraintreeExtractor):
"""
Extractor for Merchant Accounts stream.
It parses output XML and finds all `Merchant Account` occurrences in it.
"""
def extract_records(
self,
response: requests.Response,
) -> List[Record]:
data = XmlUtil.dict_from_xml(response.text)["merchant_accounts"]
merchant_accounts = self._extract_as_array(data, "merchant_account")
return [
MerchantAccount(**self._get_json_from_resource(BMerchantAccount(None, merchant_account))).dict(exclude_unset=True)
for merchant_account in merchant_accounts
]
@dataclass
| MerchantAccountExtractor |
python | scrapy__scrapy | tests/test_core_downloader.py | {
"start": 3199,
"end": 4257
} | class ____(TestContextFactoryBase):
@deferred_f_from_coro_f
async def testPayload(self, server_url: str) -> None:
s = "0123456789" * 10
crawler = get_crawler()
settings = Settings()
client_context_factory = load_context_factory_from_settings(settings, crawler)
body = await self.get_page(
server_url + "payload", client_context_factory, body=s
)
assert body == to_bytes(s)
def test_override_getContext(self):
class MyFactory(ScrapyClientContextFactory):
def getContext(
self, hostname: Any = None, port: Any = None
) -> OpenSSL.SSL.Context:
ctx: OpenSSL.SSL.Context = super().getContext(hostname, port)
return ctx
with warnings.catch_warnings(record=True) as w:
MyFactory()
assert len(w) == 1
assert (
"Overriding ScrapyClientContextFactory.getContext() is deprecated"
in str(w[0].message)
)
| TestContextFactory |
python | wandb__wandb | wandb/agents/pyagent.py | {
"start": 13585,
"end": 14279
} | class ____(Exception):
"""Exception raised when a job fails during execution."""
pass
def _get_exception_logger_and_term_strs(exc):
if isinstance(exc, _JobError) and exc.__cause__:
# If it's a JobException, get the original exception for display
job_exc = exc.__cause__
log_str = _format_exception_traceback(job_exc)
# Don't long full stacktrace to terminal again because we already
# printed it to stderr.
term_str = " " + str(job_exc)
else:
log_str = _format_exception_traceback(exc)
term_str = "\n" + log_str
return log_str, term_str
_INSTANCES = 0
def is_running():
return bool(_INSTANCES)
| _JobError |
python | huggingface__transformers | src/transformers/models/nanochat/modeling_nanochat.py | {
"start": 12099,
"end": 12700
} | class ____(nn.Module):
def __init__(self, config):
super().__init__()
self.config = config
self.activation_fn = ACT2FN[config.hidden_act]
self.fc1 = nn.Linear(config.hidden_size, config.intermediate_size, bias=False)
self.fc2 = nn.Linear(config.intermediate_size, config.hidden_size, bias=False)
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
hidden_states = self.fc1(hidden_states)
hidden_states = self.activation_fn(hidden_states)
hidden_states = self.fc2(hidden_states)
return hidden_states
| NanoChatMLP |
python | sphinx-doc__sphinx | sphinx/ext/apidoc/_shared.py | {
"start": 990,
"end": 1909
} | class ____:
"""Options for apidoc."""
dest_dir: Path
module_path: Path
exclude_pattern: Sequence[str] = ()
max_depth: int = 4
follow_links: bool = False
separate_modules: bool = False
include_private: bool = False
toc_file: str = 'modules'
no_headings: bool = False
module_first: bool = False
implicit_namespaces: bool = False
automodule_options: Set[str] = dataclasses.field(default_factory=set)
suffix: str = 'rst'
remove_old: bool = True
quiet: bool = False
dry_run: bool = False
force: bool = True
# --full only
full: bool = False
append_syspath: bool = False
header: str = ''
author: str | None = None
version: str | None = None
release: str | None = None
extensions: Sequence[str] | None = None
template_dir: str | None = None
@dataclasses.dataclass(frozen=True, kw_only=True, slots=True)
| ApidocOptions |
python | python-poetry__poetry | src/poetry/inspection/lazy_wheel.py | {
"start": 17210,
"end": 29798
} | class ____(LazyFileOverHTTP):
"""File-like object mapped to a ZIP file over HTTP.
This uses HTTP range requests to lazily fetch the file's content, which should be
provided as the first argument to a ``ZipFile``.
"""
# Cache this on the type to avoid trying and failing our initial lazy wheel request
# multiple times in the same invocation against an index without this support.
_domains_without_negative_range: ClassVar[set[str]] = set()
_metadata_regex = re.compile(r"^[^/]*\.dist-info/METADATA$")
def read_metadata(self, name: str) -> bytes:
"""Download and read the METADATA file from the remote wheel."""
with ZipFile(self) as zf:
# prefetch metadata to reduce the number of range requests
filename = self._prefetch_metadata(name)
return zf.read(filename)
@classmethod
def _initial_chunk_length(cls) -> int:
"""Return the size of the chunk (in bytes) to download from the end of the file.
This method is called in ``self._fetch_content_length()``. As noted in that
method's docstring, this should be set high enough to cover the central
directory sizes of the *average* wheels you expect to see, in order to avoid
further requests before being able to process the zip file's contents at all.
If we choose a small number, we need one more range request for larger wheels.
If we choose a big number, we download unnecessary data from smaller wheels.
If the chunk size from this method is larger than the size of an entire wheel,
that may raise an HTTP error, but this is gracefully handled in
``self._fetch_content_length()`` with a small performance penalty.
"""
return 10_000
def _fetch_content_length(self) -> int:
"""Get the total remote file length, but also download a chunk from the end.
This method is called within ``__enter__``. In an attempt to reduce
the total number of requests needed to populate this lazy file's contents, this
method will also attempt to fetch a chunk of the file's actual content. This
chunk will be ``self._initial_chunk_length()`` bytes in size, or just the remote
file's length if that's smaller, and the chunk will come from the *end* of
the file.
This method will first attempt to download with a negative byte range request,
i.e. a GET with the headers ``Range: bytes=-N`` for ``N`` equal to
``self._initial_chunk_length()``. If negative offsets are unsupported, it will
instead fall back to making a HEAD request first to extract the length, followed
by a GET request with the double-ended range header ``Range: bytes=X-Y`` to
extract the final ``N`` bytes from the remote resource.
"""
initial_chunk_size = self._initial_chunk_length()
ret_length, tail = self._extract_content_length(initial_chunk_size)
# Need to explicitly truncate here in order to perform the write and seek
# operations below when we write the chunk of file contents to disk.
self.truncate(ret_length)
if tail is None:
# If we could not download any file contents yet (e.g. if negative byte
# ranges were not supported, or the requested range was larger than the file
# size), then download all of this at once, hopefully pulling in the entire
# central directory.
initial_start = max(0, ret_length - initial_chunk_size)
self._ensure_downloaded(initial_start, ret_length)
else:
# If we *could* download some file contents, then write them to the end of
# the file and set up our bisect boundaries by hand.
with self._stay(), tail:
response_length = int(tail.headers["Content-Length"])
assert response_length == min(initial_chunk_size, ret_length)
self.seek(-response_length, io.SEEK_END)
# Default initial chunk size is currently 1MB, but streaming content
# here allows it to be set arbitrarily large.
for chunk in tail.iter_content(CONTENT_CHUNK_SIZE):
self._file.write(chunk)
# We now need to update our bookkeeping to cover the interval we just
# wrote to file so we know not to do it in later read()s.
init_chunk_start = ret_length - response_length
# MergeIntervals uses inclusive boundaries i.e. start <= x <= end.
init_chunk_end = ret_length - 1
assert self._merge_intervals is not None
assert ((init_chunk_start, init_chunk_end),) == tuple(
# NB: We expect LazyRemoteResource to reset `self._merge_intervals`
# just before it calls the current method, so our assertion here
# checks that indeed no prior overlapping intervals have
# been covered.
self._merge_intervals.minimal_intervals_covering(
init_chunk_start, init_chunk_end
)
)
return ret_length
@staticmethod
def _parse_full_length_from_content_range(arg: str) -> int:
"""Parse the file's full underlying length from the Content-Range header.
This supports both * and numeric ranges, from success or error responses:
https://www.rfc-editor.org/rfc/rfc9110#field.content-range.
"""
m = re.match(r"bytes [^/]+/([0-9]+)", arg)
if m is None:
raise HTTPRangeRequestUnsupportedError(
f"could not parse Content-Range: '{arg}'"
)
return int(m.group(1))
def _try_initial_chunk_request(
self, initial_chunk_size: int
) -> tuple[int, Response]:
"""Attempt to fetch a chunk from the end of the file with a negative offset."""
headers = self._uncached_headers()
# Perform a negative range index, which is not supported by some servers.
headers["Range"] = f"bytes=-{initial_chunk_size}"
logger.debug("initial bytes request: %s", headers["Range"])
self._request_count += 1
tail = self._session.get(self._url, headers=headers, stream=True)
try:
tail.raise_for_status()
code = tail.status_code
if code != codes.partial_content:
# According to
# https://developer.mozilla.org/en-US/docs/Web/HTTP/Range_requests,
# a 200 OK implies that range requests are not supported,
# regardless of the requested size.
# However, some servers that support negative range requests also return a
# 200 OK if the requested range from the end was larger than the file size.
if code == codes.ok:
accept_ranges = tail.headers.get("Accept-Ranges", None)
content_length = int(tail.headers["Content-Length"])
if (
accept_ranges == "bytes"
and content_length <= initial_chunk_size
):
return content_length, tail
raise HTTPRangeRequestUnsupportedError(
f"did not receive partial content: got code {code}"
)
if "Content-Range" not in tail.headers:
raise LazyWheelUnsupportedError(
f"file length cannot be determined for {self._url}, "
f"did not receive content range header from server"
)
file_length = self._parse_full_length_from_content_range(
tail.headers["Content-Range"]
)
return (file_length, tail)
except BaseException:
tail.close()
raise
def _extract_content_length(
self, initial_chunk_size: int
) -> tuple[int, Response | None]:
"""Get the Content-Length of the remote file, and possibly a chunk of it."""
domain = urlparse(self._url).netloc
if domain in self._domains_without_negative_range:
return (self._content_length_from_head(), None)
tail: Response | None
try:
# Initial range request for just the end of the file.
file_length, tail = self._try_initial_chunk_request(initial_chunk_size)
except HTTPError as e:
# Our initial request using a negative byte range was not supported.
resp = e.response
code = resp.status_code if resp is not None else None
# This indicates that the requested range from the end was larger than the
# actual file size: https://www.rfc-editor.org/rfc/rfc9110#status.416.
if (
code == codes.requested_range_not_satisfiable
and resp is not None
and "Content-Range" in resp.headers
):
# In this case, we don't have any file content yet, but we do know the
# size the file will be, so we can return that and exit here.
file_length = self._parse_full_length_from_content_range(
resp.headers["Content-Range"]
)
return file_length, None
# pypi notably does not support negative byte ranges: see
# https://github.com/pypi/warehouse/issues/12823.
logger.debug(
"Negative byte range not supported for domain '%s': "
"using HEAD request before lazy wheel from now on (code: %s)",
domain,
code,
)
# Avoid trying a negative byte range request against this domain for the
# rest of the resolve.
self._domains_without_negative_range.add(domain)
# Apply a HEAD request to get the real size, and nothing else for now.
return self._content_length_from_head(), None
# Some servers that do not support negative offsets,
# handle a negative offset like "-10" as "0-10"...
# ... or behave even more strangely, see
# https://github.com/python-poetry/poetry/issues/9056#issuecomment-1973273721
if int(tail.headers["Content-Length"]) > initial_chunk_size or tail.headers.get(
"Content-Range", ""
).startswith("bytes -"):
tail.close()
tail = None
self._domains_without_negative_range.add(domain)
return file_length, tail
def _prefetch_metadata(self, name: str) -> str:
"""Locate the *.dist-info/METADATA entry from a temporary ``ZipFile`` wrapper,
and download it.
This method assumes that the *.dist-info directory (containing e.g. METADATA) is
contained in a single contiguous section of the zip file in order to ensure it
can be downloaded in a single ranged GET request."""
logger.debug("begin prefetching METADATA for %s", name)
start: int | None = None
end: int | None = None
# This may perform further requests if __init__() did not pull in the entire
# central directory at the end of the file (although _initial_chunk_length()
# should be set large enough to avoid this).
zf = ZipFile(self)
filename = ""
for info in zf.infolist():
if start is None:
if self._metadata_regex.search(info.filename):
filename = info.filename
start = info.header_offset
continue
else:
# The last .dist-info/ entry may be before the end of the file if the
# wheel's entries are sorted lexicographically (which is unusual).
if not self._metadata_regex.search(info.filename):
end = info.header_offset
break
if start is None:
raise UnsupportedWheelError(
f"no {self._metadata_regex!r} found for {name} in {self.name}"
)
# If it is the last entry of the zip, then give us everything
# until the start of the central directory.
if end is None:
end = zf.start_dir
logger.debug(f"fetch {filename}")
self._ensure_downloaded(start, end)
logger.debug("done prefetching METADATA for %s", name)
return filename
| LazyWheelOverHTTP |
python | Netflix__metaflow | test/core/tests/card_component_refresh_test.py | {
"start": 72,
"end": 7321
} | class ____(MetaflowTest):
"""
This test will validates the card component API based for runtime updates.
"""
PRIORITY = 3
SKIP_GRAPHS = [
"simple_switch",
"nested_switch",
"branch_in_switch",
"foreach_in_switch",
"switch_in_branch",
"switch_in_foreach",
"recursive_switch",
"recursive_switch_inside_foreach",
]
@tag('environment(vars={"METAFLOW_CARD_NO_WARNING": "True"})')
@tag('card(type="test_component_refresh_card", id="refresh_card", save_errors=False)') # fmt: skip
@steps(
0,
[
"singleton-start",
"sigleton-end",
"singleton",
"foreach-split-small",
"foreach-inner-small",
"foreach-join-small",
"split-and",
"single-branch-split",
"join-and",
"parallel-step",
],
)
def step_start(self):
import random
import string
def _create_random_strings(char_len):
return "".join(random.choice(string.ascii_letters) for i in range(char_len))
def _array_is_a_subset(arr1, arr2):
return set(arr1).issubset(set(arr2))
def create_random_string_array(size=10):
return [_create_random_strings(10) for i in range(size)]
from metaflow import current
from metaflow.plugins.cards.card_client import Card
from metaflow.plugins.cards.card_modules.test_cards import (
_component_values_to_hash,
TestJSONComponent,
)
import random
import time
possible_reload_tokens = []
make_reload_token = lambda a1, a2: "runtime-%s" % _component_values_to_hash(
{"random_key_1": {"abc": a1}, "random_key_2": {"abc": a2}}
)
component_1_arr = create_random_string_array(5)
# Calling the first refresh should trigger a render of the card.
current.card.append(
TestJSONComponent({"abc": component_1_arr}), id="component_1"
)
component_2_arr = create_random_string_array(5)
inscope_component = TestJSONComponent({"abc": component_2_arr})
current.card.append(inscope_component)
current.card.refresh()
# sleep for a little bit because the card refresh is async.
# This feels a little hacky but need better ideas on how to test this
# when async processes may write cards/data in a "best-effort" manner.
# The `try_to_get_card` function will keep retrying to get a card until a
# timeout value is reached. After which the function will throw a `TimeoutError`.
_reload_tok = make_reload_token(component_1_arr, component_2_arr)
card = try_to_get_card(id="refresh_card")
assert_equals(isinstance(card, Card), True)
sleep_between_refreshes = 2 # Set based on the RUNTIME_CARD_MIN_REFRESH_INTERVAL which acts as a rate-limit to what is refreshed.
card_html = card.get()
possible_reload_tokens.append(_reload_tok)
# The reload token for card type `test_component_refresh_card` contains a hash of the component values.
# The first assertion will check if this reload token exists is set to what we expect in the HTML page.
assert_equals(_reload_tok in card_html, True)
card_data = None
for i in range(5):
# We need to test the following :
# 1. We can call `inscope_component.update()` with new data and it will be reflected in the card.
# 2. `current.card.components["component1"].update()` and it will be reflected in the card.
# How do we test it :
# 1. Add new values to the components that have been created.
# 2. Since the card is calculating the reload token based on the hash of the value, we verify that dataupdates have the same reload token or any of the possible reload tokens.
# 3. We also verify that the card_data contains the `data` key that has the lastest information updated for `component_1`
component_2_arr.append(_create_random_strings(10))
component_1_arr.append(_create_random_strings(10))
inscope_component.update({"abc": component_2_arr})
current.card.components["component_1"].update({"abc": component_1_arr})
_reload_tok = make_reload_token(component_1_arr, component_2_arr)
current.card.refresh()
possible_reload_tokens.append(_reload_tok)
card_data = card.get_data()
if card_data is not None:
assert_equals(card_data["reload_token"] in possible_reload_tokens, True)
assert_equals(
_array_is_a_subset(
card_data["data"]["component_1"]["abc"], component_1_arr
),
True,
)
time.sleep(sleep_between_refreshes)
assert_equals(card_data is not None, True)
self.final_data = component_1_arr
# setting step name here helps us figure out what steps should be validated by the checker
self.step_name = current.step_name
@steps(1, ["all"])
def step_all(self):
pass
def check_results(self, flow, checker):
def _array_is_a_subset(arr1, arr2):
return set(arr1).issubset(set(arr2))
if checker.__class__.__name__ != "MetadataCheck":
return
run = checker.get_run()
for step in flow:
meta_check_dict = checker.artifact_dict_if_exists(step.name, "final_data")
# Which ever steps ran the actual card testing code
# contains the `final_data` attribute and the `step_name` attribute.
# If these exist then we can succesfully validate the card data since it is meant to exist.
step_done_check_dict = checker.artifact_dict_if_exists(
step.name, "step_name"
)
for task_id in step_done_check_dict:
if (
len(step_done_check_dict[task_id]) == 0
or step_done_check_dict[task_id]["step_name"] != step.name
):
print(
"Skipping task pathspec %s" % run[step.name][task_id].pathspec
)
continue
# If the `step_name` attribute was set then surely `final_data` will also be set;
data_obj = meta_check_dict[task_id]["final_data"]
card_present, card_data = checker.get_card_data(
step.name,
task_id,
"test_component_refresh_card",
card_id="refresh_card",
)
assert_equals(card_present, True)
data_has_latest_artifact = _array_is_a_subset(
data_obj, card_data["data"]["component_1"]["abc"]
)
assert_equals(data_has_latest_artifact, True)
print(
"Succesfully validated task pathspec %s"
% run[step.name][task_id].pathspec
)
| CardComponentRefreshTest |
python | conda__conda | conda/core/path_actions.py | {
"start": 41147,
"end": 41951
} | class ____(PathAction):
def __init__(self, transaction_context, target_prefix):
self.transaction_context = transaction_context
self.target_prefix = target_prefix
self._execute_successful = False
def verify(self):
self._verified = True
def execute(self):
log.log(TRACE, "unregistering environment in catalog %s", self.target_prefix)
unregister_env(self.target_prefix)
self._execute_successful = True
def reverse(self):
pass
def cleanup(self):
pass
@property
def target_full_path(self):
raise NotImplementedError()
# ######################################################
# Fetch / Extract Actions
# ######################################################
| UnregisterEnvironmentLocationAction |
python | getsentry__sentry | src/sentry/sentry_apps/metrics.py | {
"start": 2538,
"end": 4545
} | class ____(StrEnum):
"""Events/features that Sentry Apps can do"""
# event webhooks
ERROR_CREATED = "error.created"
ISSUE_CREATED = "issue.created"
# issue alert webhooks
EVENT_ALERT_TRIGGERED = "event_alert.triggered"
# external request webhooks
EXTERNAL_ISSUE_CREATED = "external_issue.created"
EXTERNAL_ISSUE_LINKED = "external_issue.linked"
SELECT_OPTIONS_REQUESTED = "select_options.requested"
ALERT_RULE_ACTION_REQUESTED = "alert_rule_action.requested"
# metric alert webhooks
METRIC_ALERT_OPEN = "metric_alert.open"
METRIC_ALERT_RESOLVED = "metric_alert.resolved"
METRIC_ALERT_CRITICAL = "metric_alert.critical"
METRIC_ALERT_WARNING = "metric_alert.warning"
# comment webhooks
COMMENT_CREATED = "comment.created"
COMMENT_UPDATED = "comment.updated"
COMMENT_DELETED = "comment.deleted"
# installation webhooks
INSTALLATION_CREATED = "installation.created"
INSTALLATION_DELETED = "installation.deleted"
# workflow notification
ISSUE_IGNORED = "issue.ignored"
ISSUE_ARCHIVED = "issue.archived"
ISSUE_UNRESOLVED = "issue.unresolved"
ISSUE_RESOLVED = "issue.resolved"
ISSUE_ASSIGNED = "issue.assigned"
# authorizations
GRANT_EXCHANGER = "grant_exchanger"
REFRESHER = "refresher"
MANUAL_REFRESHER = "manual_refresher"
# management
APP_CREATE = "app_create"
APP_UPDATE = "app_update"
REQUESTS = "requests"
WEBHOOK_UPDATE = "webhook_update"
INSTALLATION_CREATE = "install_create"
INSTALLATION_WEBHOOK_UPDATE = "installation_webhook_update"
# seer webhooks
SEER_ROOT_CAUSE_STARTED = "seer.root_cause_started"
SEER_ROOT_CAUSE_COMPLETED = "seer.root_cause_completed"
SEER_SOLUTION_STARTED = "seer.solution_started"
SEER_SOLUTION_COMPLETED = "seer.solution_completed"
SEER_CODING_STARTED = "seer.coding_started"
SEER_CODING_COMPLETED = "seer.coding_completed"
SEER_PR_CREATED = "seer.pr_created"
| SentryAppEventType |
python | kamyu104__LeetCode-Solutions | Python/jump-game-viii.py | {
"start": 46,
"end": 634
} | class ____(object):
def minCost(self, nums, costs):
"""
:type nums: List[int]
:type costs: List[int]
:rtype: int
"""
stk1, stk2 = [], []
dp = [float("inf")]*len(nums)
dp[0] = 0
for i in xrange(len(nums)):
while stk1 and nums[stk1[-1]] <= nums[i]:
dp[i] = min(dp[i], dp[stk1.pop()]+costs[i])
stk1.append(i)
while stk2 and nums[stk2[-1]] > nums[i]:
dp[i] = min(dp[i], dp[stk2.pop()]+costs[i])
stk2.append(i)
return dp[-1]
| Solution |
python | doocs__leetcode | solution/1300-1399/1340.Jump Game V/Solution.py | {
"start": 0,
"end": 535
} | class ____:
def maxJumps(self, arr: List[int], d: int) -> int:
@cache
def dfs(i):
ans = 1
for j in range(i - 1, -1, -1):
if i - j > d or arr[j] >= arr[i]:
break
ans = max(ans, 1 + dfs(j))
for j in range(i + 1, n):
if j - i > d or arr[j] >= arr[i]:
break
ans = max(ans, 1 + dfs(j))
return ans
n = len(arr)
return max(dfs(i) for i in range(n))
| Solution |
python | falconry__falcon | tests/test_httperror.py | {
"start": 7460,
"end": 7581
} | class ____:
def on_get(self, req, resp):
raise falcon.HTTPMissingParam('id', code='P1003')
| MissingParamResource |
python | sympy__sympy | sympy/physics/mechanics/tests/test_pathway.py | {
"start": 602,
"end": 5822
} | class ____:
def test_is_pathway_base_subclass(self):
assert issubclass(LinearPathway, PathwayBase)
@staticmethod
@pytest.mark.parametrize(
'args, kwargs',
[
((Point('pA'), Point('pB')), {}),
]
)
def test_valid_constructor(args, kwargs):
pointA, pointB = args
instance = LinearPathway(*args, **kwargs)
assert isinstance(instance, LinearPathway)
assert hasattr(instance, 'attachments')
assert len(instance.attachments) == 2
assert instance.attachments[0] is pointA
assert instance.attachments[1] is pointB
assert isinstance(instance.attachments[0], Point)
assert instance.attachments[0].name == 'pA'
assert isinstance(instance.attachments[1], Point)
assert instance.attachments[1].name == 'pB'
@staticmethod
@pytest.mark.parametrize(
'attachments',
[
(Point('pA'), ),
(Point('pA'), Point('pB'), Point('pZ')),
]
)
def test_invalid_attachments_incorrect_number(attachments):
with pytest.raises(ValueError):
_ = LinearPathway(*attachments)
@staticmethod
@pytest.mark.parametrize(
'attachments',
[
(None, Point('pB')),
(Point('pA'), None),
]
)
def test_invalid_attachments_not_point(attachments):
with pytest.raises(TypeError):
_ = LinearPathway(*attachments)
@pytest.fixture(autouse=True)
def _linear_pathway_fixture(self):
self.N = ReferenceFrame('N')
self.pA = Point('pA')
self.pB = Point('pB')
self.pathway = LinearPathway(self.pA, self.pB)
self.q1 = dynamicsymbols('q1')
self.q2 = dynamicsymbols('q2')
self.q3 = dynamicsymbols('q3')
self.q1d = dynamicsymbols('q1', 1)
self.q2d = dynamicsymbols('q2', 1)
self.q3d = dynamicsymbols('q3', 1)
self.F = Symbol('F')
def test_properties_are_immutable(self):
instance = LinearPathway(self.pA, self.pB)
with pytest.raises(AttributeError):
instance.attachments = None
with pytest.raises(TypeError):
instance.attachments[0] = None
with pytest.raises(TypeError):
instance.attachments[1] = None
def test_repr(self):
pathway = LinearPathway(self.pA, self.pB)
expected = 'LinearPathway(pA, pB)'
assert repr(pathway) == expected
def test_static_pathway_length(self):
self.pB.set_pos(self.pA, 2*self.N.x)
assert self.pathway.length == 2
def test_static_pathway_extension_velocity(self):
self.pB.set_pos(self.pA, 2*self.N.x)
assert self.pathway.extension_velocity == 0
def test_static_pathway_to_loads(self):
self.pB.set_pos(self.pA, 2*self.N.x)
expected = [
(self.pA, - self.F*self.N.x),
(self.pB, self.F*self.N.x),
]
assert self.pathway.to_loads(self.F) == expected
def test_2D_pathway_length(self):
self.pB.set_pos(self.pA, 2*self.q1*self.N.x)
expected = 2*sqrt(self.q1**2)
assert self.pathway.length == expected
def test_2D_pathway_extension_velocity(self):
self.pB.set_pos(self.pA, 2*self.q1*self.N.x)
expected = 2*sqrt(self.q1**2)*self.q1d/self.q1
assert self.pathway.extension_velocity == expected
def test_2D_pathway_to_loads(self):
self.pB.set_pos(self.pA, 2*self.q1*self.N.x)
expected = [
(self.pA, - self.F*(self.q1 / sqrt(self.q1**2))*self.N.x),
(self.pB, self.F*(self.q1 / sqrt(self.q1**2))*self.N.x),
]
assert self.pathway.to_loads(self.F) == expected
def test_3D_pathway_length(self):
self.pB.set_pos(
self.pA,
self.q1*self.N.x - self.q2*self.N.y + 2*self.q3*self.N.z,
)
expected = sqrt(self.q1**2 + self.q2**2 + 4*self.q3**2)
assert simplify(self.pathway.length - expected) == 0
def test_3D_pathway_extension_velocity(self):
self.pB.set_pos(
self.pA,
self.q1*self.N.x - self.q2*self.N.y + 2*self.q3*self.N.z,
)
length = sqrt(self.q1**2 + self.q2**2 + 4*self.q3**2)
expected = (
self.q1*self.q1d/length
+ self.q2*self.q2d/length
+ 4*self.q3*self.q3d/length
)
assert simplify(self.pathway.extension_velocity - expected) == 0
def test_3D_pathway_to_loads(self):
self.pB.set_pos(
self.pA,
self.q1*self.N.x - self.q2*self.N.y + 2*self.q3*self.N.z,
)
length = sqrt(self.q1**2 + self.q2**2 + 4*self.q3**2)
pO_force = (
- self.F*self.q1*self.N.x/length
+ self.F*self.q2*self.N.y/length
- 2*self.F*self.q3*self.N.z/length
)
pI_force = (
self.F*self.q1*self.N.x/length
- self.F*self.q2*self.N.y/length
+ 2*self.F*self.q3*self.N.z/length
)
expected = [
(self.pA, pO_force),
(self.pB, pI_force),
]
assert self.pathway.to_loads(self.F) == expected
| TestLinearPathway |
python | readthedocs__readthedocs.org | readthedocs/rtd_tests/tests/test_resolver.py | {
"start": 6353,
"end": 7242
} | class ____(ResolverBase):
"""Tests to make sure we can override resolve_path correctly."""
def test_resolver_force_language(self):
url = self.resolver.resolve_path(
project=self.pip,
filename="index.html",
language="cz",
)
self.assertEqual(url, "/cz/latest/index.html")
def test_resolver_force_version(self):
url = self.resolver.resolve_path(
project=self.pip,
filename="index.html",
version_slug="foo",
)
self.assertEqual(url, "/en/foo/index.html")
def test_resolver_force_language_version(self):
url = self.resolver.resolve_path(
project=self.pip,
filename="index.html",
language="cz",
version_slug="foo",
)
self.assertEqual(url, "/cz/foo/index.html")
| ResolverPathOverrideTests |
python | getsentry__sentry | tests/sentry/rules/processing/test_buffer_processing.py | {
"start": 10430,
"end": 13144
} | class ____(CreateEventTestCase):
def setUp(self) -> None:
super().setUp()
self.project = self.create_project()
self.group = self.create_group(self.project)
self.group_two = self.create_group(self.project)
self.group_three = self.create_group(self.project)
self.rule = self.create_alert_rule()
@patch("sentry.rules.processing.delayed_processing.apply_delayed.apply_async")
def test_no_redis_data(self, mock_apply_delayed: MagicMock) -> None:
process_in_batches(buffer.backend, self.project.id, "delayed_processing")
mock_apply_delayed.assert_called_once_with(
kwargs={"project_id": self.project.id}, headers={"sentry-propagate-traces": False}
)
@patch("sentry.rules.processing.delayed_processing.apply_delayed.apply_async")
def test_basic(self, mock_apply_delayed: MagicMock) -> None:
self.push_to_hash(self.project.id, self.rule.id, self.group.id)
self.push_to_hash(self.project.id, self.rule.id, self.group_two.id)
self.push_to_hash(self.project.id, self.rule.id, self.group_three.id)
process_in_batches(buffer.backend, self.project.id, "delayed_processing")
mock_apply_delayed.assert_called_once_with(
kwargs={"project_id": self.project.id}, headers={"sentry-propagate-traces": False}
)
@override_options({"delayed_processing.batch_size": 2})
@patch("sentry.rules.processing.delayed_processing.apply_delayed.apply_async")
def test_batch(self, mock_apply_delayed: MagicMock) -> None:
self.push_to_hash(self.project.id, self.rule.id, self.group.id)
self.push_to_hash(self.project.id, self.rule.id, self.group_two.id)
self.push_to_hash(self.project.id, self.rule.id, self.group_three.id)
process_in_batches(buffer.backend, self.project.id, "delayed_processing")
assert mock_apply_delayed.call_count == 2
# Validate the batches are created correctly
batch_one_key = mock_apply_delayed.call_args_list[0][1]["kwargs"]["batch_key"]
batch_one = buffer.backend.get_hash(
model=Project, field={"project_id": self.project.id, "batch_key": batch_one_key}
)
batch_two_key = mock_apply_delayed.call_args_list[1][1]["kwargs"]["batch_key"]
batch_two = buffer.backend.get_hash(
model=Project, field={"project_id": self.project.id, "batch_key": batch_two_key}
)
assert len(batch_one) == 2
assert len(batch_two) == 1
# Validate that we've cleared the original data to reduce storage usage
assert not buffer.backend.get_hash(model=Project, field={"project_id": self.project.id})
| ProcessInBatchesTest |
python | has2k1__plotnine | plotnine/geoms/geom_errorbar.py | {
"start": 461,
"end": 2199
} | class ____(geom):
"""
Vertical interval represented as an errorbar
{usage}
Parameters
----------
{common_parameters}
width : float, default=0.5
Bar width as a fraction of the resolution of the data.
"""
DEFAULT_AES = {
"alpha": 1,
"color": "black",
"linetype": "solid",
"size": 0.5,
}
REQUIRED_AES = {"x", "ymin", "ymax"}
DEFAULT_PARAMS = {
"stat": "identity",
"position": "identity",
"na_rm": False,
"width": 0.5,
}
draw_legend = staticmethod(geom_path.draw_legend)
def setup_data(self, data: pd.DataFrame) -> pd.DataFrame:
if "width" not in data:
if self.params["width"]:
data["width"] = self.params["width"]
else:
data["width"] = resolution(data["x"], False) * 0.9
data["xmin"] = data["x"] - data["width"] / 2
data["xmax"] = data["x"] + data["width"] / 2
del data["width"]
return data
@staticmethod
def draw_group(
data: pd.DataFrame,
panel_params: panel_view,
coord: coord,
ax: Axes,
params: dict[str, Any],
):
f = np.hstack
# create (two horizontal bars) + vertical bar
bars = pd.DataFrame(
{
"x": f([data["xmin"], data["xmin"], data["x"]]),
"xend": f([data["xmax"], data["xmax"], data["x"]]),
"y": f([data["ymin"], data["ymax"], data["ymax"]]),
"yend": f([data["ymin"], data["ymax"], data["ymin"]]),
}
)
copy_missing_columns(bars, data)
geom_segment.draw_group(bars, panel_params, coord, ax, params)
| geom_errorbar |
python | great-expectations__great_expectations | contrib/great_expectations_semantic_types_expectations/great_expectations_semantic_types_expectations/expectations/expect_column_values_to_be_valid_sphenic_number.py | {
"start": 834,
"end": 1844
} | class ____(ColumnMapMetricProvider):
# This is the id string that will be used to reference your metric.
condition_metric_name = "column_values.valid_sphenic_number"
# This method implements the core logic for the PandasExecutionEngine
@column_condition_partial(engine=PandasExecutionEngine)
def _pandas(cls, column, **kwargs):
return column.apply(lambda x: is_valid_sphenic_number(x))
# This method defines the business logic for evaluating your metric when using a SqlAlchemyExecutionEngine
# @column_condition_partial(engine=SqlAlchemyExecutionEngine)
# def _sqlalchemy(cls, column, _dialect, **kwargs):
# raise NotImplementedError
# This method defines the business logic for evaluating your metric when using a SparkDFExecutionEngine
# @column_condition_partial(engine=SparkDFExecutionEngine)
# def _spark(cls, column, **kwargs):
# raise NotImplementedError
# This class defines the Expectation itself
| ColumnValuesToBeValidSphenicNumber |
python | ray-project__ray | python/ray/tests/test_placement_group_2.py | {
"start": 18316,
"end": 20326
} | class ____:
def create_pg(self):
create_pg()
ray.get(f.remote())
a = A.remote()
ray.get(a.create_pg.remote())
# Create 2 pgs to make sure multiple placement groups that belong
# to a single job will be properly cleaned.
create_pg()
create_pg()
ray.shutdown()
"""
run_string_as_driver(driver_code)
# Wait until the driver is reported as dead by GCS.
def is_job_done():
jobs = ray._private.state.jobs()
for job in jobs:
if job["IsDead"]:
return True
return False
def assert_num_cpus(expected_num_cpus):
if expected_num_cpus == 0:
return "CPU" not in ray.available_resources()
return ray.available_resources()["CPU"] == expected_num_cpus
wait_for_condition(is_job_done)
available_cpus = ray.available_resources()["CPU"]
wait_for_condition(lambda: assert_num_cpus(num_nodes * num_cpu_per_node))
def test_automatic_cleanup_detached_actors(ray_start_cluster):
# Make sure the placement groups created by a
# detached actors are cleaned properly.
cluster = ray_start_cluster
num_nodes = 3
num_cpu_per_node = 2
# Create 3 nodes cluster.
for _ in range(num_nodes):
cluster.add_node(num_cpus=num_cpu_per_node)
cluster.wait_for_nodes()
info = ray.init(address=cluster.address, namespace="default_test_namespace")
available_cpus = ray.available_resources()["CPU"]
assert available_cpus == num_nodes * num_cpu_per_node
driver_code = f"""
import ray
ray.init(address="{info["address"]}", namespace="default_test_namespace")
def create_pg():
pg = ray.util.placement_group(
[{{"CPU": 1}} for _ in range(3)],
strategy="STRICT_SPREAD")
ray.get(pg.ready())
return pg
# TODO(sang): Placement groups created by tasks launched by detached actor
# is not cleaned with the current protocol.
# @ray.remote(num_cpus=0)
# def f():
# create_pg()
@ray.remote(num_cpus=0, max_restarts=1, max_task_retries=-1)
| A |
python | encode__django-rest-framework | tests/test_viewsets.py | {
"start": 10027,
"end": 11900
} | class ____(TestCase):
def test_default_basename(self):
view = ActionViewSet()
view.basename = router.get_default_basename(ActionViewSet)
view.request = None
assert view.reverse_action('list') == '/api/actions/'
assert view.reverse_action('list-action') == '/api/actions/list_action/'
assert view.reverse_action('list-custom') == '/api/actions/custom_list_action/'
assert view.reverse_action('detail', args=['1']) == '/api/actions/1/'
assert view.reverse_action('detail-action', args=['1']) == '/api/actions/1/detail_action/'
assert view.reverse_action('detail-custom', args=['1']) == '/api/actions/1/custom_detail_action/'
def test_custom_basename(self):
view = ActionViewSet()
view.basename = 'actions-alt'
view.request = None
assert view.reverse_action('list') == '/api/actions-alt/'
assert view.reverse_action('list-action') == '/api/actions-alt/list_action/'
assert view.reverse_action('list-custom') == '/api/actions-alt/custom_list_action/'
assert view.reverse_action('detail', args=['1']) == '/api/actions-alt/1/'
assert view.reverse_action('detail-action', args=['1']) == '/api/actions-alt/1/detail_action/'
assert view.reverse_action('detail-custom', args=['1']) == '/api/actions-alt/1/custom_detail_action/'
def test_request_passing(self):
view = ActionViewSet()
view.basename = router.get_default_basename(ActionViewSet)
view.request = factory.get('/')
# Passing the view's request object should result in an absolute URL.
assert view.reverse_action('list') == 'http://testserver/api/actions/'
# Users should be able to explicitly not pass the view's request.
assert view.reverse_action('list', request=None) == '/api/actions/'
| ReverseActionTests |
python | sdispater__pendulum | src/pendulum/interval.py | {
"start": 737,
"end": 12736
} | class ____(Duration, Generic[_T]):
"""
An interval of time between two datetimes.
"""
def __new__(cls, start: _T, end: _T, absolute: bool = False) -> Self:
if (isinstance(start, datetime) and not isinstance(end, datetime)) or (
not isinstance(start, datetime) and isinstance(end, datetime)
):
raise ValueError(
"Both start and end of an Interval must have the same type"
)
if (
isinstance(start, datetime)
and isinstance(end, datetime)
and (
(start.tzinfo is None and end.tzinfo is not None)
or (start.tzinfo is not None and end.tzinfo is None)
)
):
raise TypeError("can't compare offset-naive and offset-aware datetimes")
if absolute and start > end:
end, start = start, end
_start = start
_end = end
if isinstance(start, pendulum.DateTime):
_start = cast(
"_T",
datetime(
start.year,
start.month,
start.day,
start.hour,
start.minute,
start.second,
start.microsecond,
tzinfo=start.tzinfo,
fold=start.fold,
),
)
elif isinstance(start, pendulum.Date):
_start = cast("_T", date(start.year, start.month, start.day))
if isinstance(end, pendulum.DateTime):
_end = cast(
"_T",
datetime(
end.year,
end.month,
end.day,
end.hour,
end.minute,
end.second,
end.microsecond,
tzinfo=end.tzinfo,
fold=end.fold,
),
)
elif isinstance(end, pendulum.Date):
_end = cast("_T", date(end.year, end.month, end.day))
# Fixing issues with datetime.__sub__()
# not handling offsets if the tzinfo is the same
if (
isinstance(_start, datetime)
and isinstance(_end, datetime)
and _start.tzinfo is _end.tzinfo
):
if _start.tzinfo is not None:
offset = cast("timedelta", cast("datetime", start).utcoffset())
_start = cast("_T", (_start - offset).replace(tzinfo=None))
if isinstance(end, datetime) and _end.tzinfo is not None:
offset = cast("timedelta", end.utcoffset())
_end = cast("_T", (_end - offset).replace(tzinfo=None))
delta: timedelta = _end - _start
return super().__new__(cls, seconds=delta.total_seconds())
def __init__(self, start: _T, end: _T, absolute: bool = False) -> None:
super().__init__()
_start: _T
if not isinstance(start, pendulum.Date):
if isinstance(start, datetime):
start = cast("_T", pendulum.instance(start))
else:
start = cast("_T", pendulum.date(start.year, start.month, start.day))
_start = start
else:
if isinstance(start, pendulum.DateTime):
_start = cast(
"_T",
datetime(
start.year,
start.month,
start.day,
start.hour,
start.minute,
start.second,
start.microsecond,
tzinfo=start.tzinfo,
),
)
else:
_start = cast("_T", date(start.year, start.month, start.day))
_end: _T
if not isinstance(end, pendulum.Date):
if isinstance(end, datetime):
end = cast("_T", pendulum.instance(end))
else:
end = cast("_T", pendulum.date(end.year, end.month, end.day))
_end = end
else:
if isinstance(end, pendulum.DateTime):
_end = cast(
"_T",
datetime(
end.year,
end.month,
end.day,
end.hour,
end.minute,
end.second,
end.microsecond,
tzinfo=end.tzinfo,
),
)
else:
_end = cast("_T", date(end.year, end.month, end.day))
self._invert = False
if start > end:
self._invert = True
if absolute:
end, start = start, end
_end, _start = _start, _end
self._absolute = absolute
self._start: _T = start
self._end: _T = end
self._delta: PreciseDiff = precise_diff(_start, _end)
@property
def years(self) -> int:
return self._delta.years
@property
def months(self) -> int:
return self._delta.months
@property
def weeks(self) -> int:
return abs(self._delta.days) // 7 * self._sign(self._delta.days)
@property
def days(self) -> int:
return self._days
@property
def remaining_days(self) -> int:
return abs(self._delta.days) % 7 * self._sign(self._days)
@property
def hours(self) -> int:
return self._delta.hours
@property
def minutes(self) -> int:
return self._delta.minutes
@property
def start(self) -> _T:
return self._start
@property
def end(self) -> _T:
return self._end
def in_years(self) -> int:
"""
Gives the duration of the Interval in full years.
"""
return self.years
def in_months(self) -> int:
"""
Gives the duration of the Interval in full months.
"""
return self.years * MONTHS_PER_YEAR + self.months
def in_weeks(self) -> int:
days = self.in_days()
sign = 1
if days < 0:
sign = -1
return sign * (abs(days) // 7)
def in_days(self) -> int:
return self._delta.total_days
def in_words(self, locale: str | None = None, separator: str = " ") -> str:
"""
Get the current interval in words in the current locale.
Ex: 6 jours 23 heures 58 minutes
:param locale: The locale to use. Defaults to current locale.
:param separator: The separator to use between each unit
"""
from pendulum.locales.locale import Locale
intervals = [
("year", self.years),
("month", self.months),
("week", self.weeks),
("day", self.remaining_days),
("hour", self.hours),
("minute", self.minutes),
("second", self.remaining_seconds),
]
loaded_locale: Locale = Locale.load(locale or pendulum.get_locale())
parts = []
for interval in intervals:
unit, interval_count = interval
if abs(interval_count) > 0:
translation = loaded_locale.translation(
f"units.{unit}.{loaded_locale.plural(abs(interval_count))}"
)
parts.append(translation.format(interval_count))
if not parts:
count: str | int = 0
if abs(self.microseconds) > 0:
unit = f"units.second.{loaded_locale.plural(1)}"
count = f"{abs(self.microseconds) / 1e6:.2f}"
else:
unit = f"units.microsecond.{loaded_locale.plural(0)}"
translation = loaded_locale.translation(unit)
parts.append(translation.format(count))
return separator.join(parts)
def range(self, unit: str, amount: int = 1) -> Iterator[_T]:
method = "add"
op = operator.le
if not self._absolute and self.invert:
method = "subtract"
op = operator.ge
start, end = self.start, self.end
i = amount
while op(start, end):
yield start
start = getattr(self.start, method)(**{unit: i})
i += amount
def as_duration(self) -> Duration:
"""
Return the Interval as a Duration.
"""
return Duration(seconds=self.total_seconds())
def __iter__(self) -> Iterator[_T]:
return self.range("days")
def __contains__(self, item: _T) -> bool:
return self.start <= item <= self.end
def __add__(self, other: timedelta) -> Duration: # type: ignore[override]
return self.as_duration().__add__(other)
__radd__ = __add__ # type: ignore[assignment]
def __sub__(self, other: timedelta) -> Duration: # type: ignore[override]
return self.as_duration().__sub__(other)
def __neg__(self) -> Self:
return self.__class__(self.end, self.start, self._absolute)
def __mul__(self, other: int | float) -> Duration: # type: ignore[override]
return self.as_duration().__mul__(other)
__rmul__ = __mul__ # type: ignore[assignment]
@overload # type: ignore[override]
def __floordiv__(self, other: timedelta) -> int: ...
@overload
def __floordiv__(self, other: int) -> Duration: ...
def __floordiv__(self, other: int | timedelta) -> int | Duration:
return self.as_duration().__floordiv__(other)
__div__ = __floordiv__ # type: ignore[assignment]
@overload # type: ignore[override]
def __truediv__(self, other: timedelta) -> float: ...
@overload
def __truediv__(self, other: float) -> Duration: ...
def __truediv__(self, other: float | timedelta) -> Duration | float:
return self.as_duration().__truediv__(other)
def __mod__(self, other: timedelta) -> Duration: # type: ignore[override]
return self.as_duration().__mod__(other)
def __divmod__(self, other: timedelta) -> tuple[int, Duration]:
return self.as_duration().__divmod__(other)
def __abs__(self) -> Self:
return self.__class__(self.start, self.end, absolute=True)
def __repr__(self) -> str:
return f"<Interval [{self._start} -> {self._end}]>"
def __str__(self) -> str:
return self.__repr__()
def _cmp(self, other: timedelta) -> int:
# Only needed for PyPy
assert isinstance(other, timedelta)
if isinstance(other, Interval):
other = other.as_timedelta()
td = self.as_timedelta()
return 0 if td == other else 1 if td > other else -1
def _getstate(self, protocol: SupportsIndex = 3) -> tuple[_T, _T, bool]:
start, end = self.start, self.end
if self._invert and self._absolute:
end, start = start, end
return start, end, self._absolute
def __reduce__(
self,
) -> tuple[type[Self], tuple[_T, _T, bool]]:
return self.__reduce_ex__(2)
def __reduce_ex__(
self, protocol: SupportsIndex
) -> tuple[type[Self], tuple[_T, _T, bool]]:
return self.__class__, self._getstate(protocol)
def __hash__(self) -> int:
return hash((self.start, self.end, self._absolute))
def __eq__(self, other: object) -> bool:
if isinstance(other, Interval):
return (self.start, self.end, self._absolute) == (
other.start,
other.end,
other._absolute,
)
else:
return self.as_duration() == other
def __ne__(self, other: object) -> bool:
return not self.__eq__(other)
def __deepcopy__(self, memo: dict[int, Any]) -> Self:
return self.__class__(
copy.deepcopy(self.start, memo),
copy.deepcopy(self.end, memo),
self._absolute,
)
| Interval |
python | pexpect__pexpect | tests/test_interact.py | {
"start": 1148,
"end": 3990
} | class ____ (PexpectTestCase.PexpectTestCase):
def setUp(self):
super(InteractTestCase, self).setUp()
self.env = env = os.environ.copy()
# Ensure 'import pexpect' works in subprocess interact*.py
if 'PYTHONPATH' in env:
env['PYTHONPATH'] = os.pathsep.join((self.project_dir,
env['PYTHONPATH']))
else:
env['PYTHONPATH'] = self.project_dir
self.interact_py = ('{self.PYTHONBIN} interact.py'.format(self=self))
def test_interact_escape(self):
" Ensure `escape_character' value exits interactive mode. "
p = pexpect.spawn(self.interact_py, timeout=5, env=self.env)
p.expect('READY')
p.sendcontrol(']') # chr(29), the default `escape_character'
# value of pexpect.interact().
p.expect_exact('Escaped interact')
p.expect(pexpect.EOF)
assert not p.isalive()
assert p.exitstatus == 0
def test_interact_escape_None(self):
" Return only after Termination when `escape_character=None'. "
p = pexpect.spawn('{self.interact_py} --no-escape'.format(self=self),
timeout=5, env=self.env)
p.expect('READY')
p.sendcontrol(']')
p.expect('29<STOP>')
p.send('\x00')
if not os.environ.get('CI', None):
# on CI platforms, we sometimes miss trailing stdout from the
# chain of child processes, not entirely sure why. So this
# is skipped on such systems.
p.expect('0<STOP>')
p.expect_exact('Escaped interact')
p.expect(pexpect.EOF)
assert not p.isalive()
assert p.exitstatus == 0
def test_interact_exit_unicode(self):
" Ensure subprocess receives utf8. "
p = pexpect.spawnu('{self.interact_py} --utf8'.format(self=self),
timeout=5, env=self.env)
p.expect('READY')
p.send('ɑ') # >>> map(ord, u'ɑ'.encode('utf8'))
p.expect('201<STOP>') # [201, 145]
p.expect('145<STOP>')
p.send('Β') # >>> map(ord, u'Β'.encode('utf8'))
p.expect('206<STOP>') # [206, 146]
p.expect('146<STOP>')
p.send('\x00')
if not os.environ.get('CI', None):
# on CI platforms, we sometimes miss trailing stdout from the
# chain of child processes, not entirely sure why. So this
# is skipped on such systems.
p.expect('0<STOP>')
p.expect_exact('Escaped interact')
p.expect(pexpect.EOF)
assert not p.isalive()
assert p.exitstatus == 0
if __name__ == '__main__':
unittest.main()
suite = unittest.TestLoader().loadTestsFromTestCase(InteractTestCase)
| InteractTestCase |
python | explosion__spaCy | spacy/lang/fr/__init__.py | {
"start": 424,
"end": 741
} | class ____(BaseDefaults):
tokenizer_exceptions = TOKENIZER_EXCEPTIONS
prefixes = TOKENIZER_PREFIXES
infixes = TOKENIZER_INFIXES
suffixes = TOKENIZER_SUFFIXES
token_match = TOKEN_MATCH
lex_attr_getters = LEX_ATTRS
syntax_iterators = SYNTAX_ITERATORS
stop_words = STOP_WORDS
| FrenchDefaults |
python | weaviate__weaviate-python-client | weaviate/proto/v1/v52/v1/file_replication_pb2_grpc.py | {
"start": 993,
"end": 3052
} | class ____(object):
"""Missing associated documentation comment in .proto file."""
def __init__(self, channel):
"""Constructor.
Args:
channel: A grpc.Channel.
"""
self.PauseFileActivity = channel.unary_unary(
'/weaviate.v1.FileReplicationService/PauseFileActivity',
request_serializer=v1_dot_file__replication__pb2.PauseFileActivityRequest.SerializeToString,
response_deserializer=v1_dot_file__replication__pb2.PauseFileActivityResponse.FromString,
_registered_method=True)
self.ResumeFileActivity = channel.unary_unary(
'/weaviate.v1.FileReplicationService/ResumeFileActivity',
request_serializer=v1_dot_file__replication__pb2.ResumeFileActivityRequest.SerializeToString,
response_deserializer=v1_dot_file__replication__pb2.ResumeFileActivityResponse.FromString,
_registered_method=True)
self.ListFiles = channel.unary_unary(
'/weaviate.v1.FileReplicationService/ListFiles',
request_serializer=v1_dot_file__replication__pb2.ListFilesRequest.SerializeToString,
response_deserializer=v1_dot_file__replication__pb2.ListFilesResponse.FromString,
_registered_method=True)
self.GetFileMetadata = channel.stream_stream(
'/weaviate.v1.FileReplicationService/GetFileMetadata',
request_serializer=v1_dot_file__replication__pb2.GetFileMetadataRequest.SerializeToString,
response_deserializer=v1_dot_file__replication__pb2.FileMetadata.FromString,
_registered_method=True)
self.GetFile = channel.stream_stream(
'/weaviate.v1.FileReplicationService/GetFile',
request_serializer=v1_dot_file__replication__pb2.GetFileRequest.SerializeToString,
response_deserializer=v1_dot_file__replication__pb2.FileChunk.FromString,
_registered_method=True)
| FileReplicationServiceStub |
python | xlwings__xlwings | xlwings/base_classes.py | {
"start": 21129,
"end": 22498
} | class ____:
@property
def api(self):
raise NotImplementedError()
@property
def name(self):
raise NotImplementedError()
@name.setter
def name(self, value):
raise NotImplementedError()
@property
def parent(self):
raise NotImplementedError()
def set_source_data(self, rng):
raise NotImplementedError()
@property
def chart_type(self):
raise NotImplementedError()
@chart_type.setter
def chart_type(self, chart_type):
raise NotImplementedError()
@property
def left(self):
raise NotImplementedError()
@left.setter
def left(self, value):
raise NotImplementedError()
@property
def top(self):
raise NotImplementedError()
@top.setter
def top(self, value):
raise NotImplementedError()
@property
def width(self):
raise NotImplementedError()
@width.setter
def width(self, value):
raise NotImplementedError()
@property
def height(self):
raise NotImplementedError()
@height.setter
def height(self, value):
raise NotImplementedError()
def delete(self):
raise NotImplementedError()
def to_png(self, path):
raise NotImplementedError()
def to_pdf(self, path, quality):
raise NotImplementedError()
| Chart |
python | huggingface__transformers | src/transformers/models/modernbert/modeling_modernbert.py | {
"start": 9098,
"end": 19037
} | class ____(nn.Module):
inv_freq: torch.Tensor # fix linting for `register_buffer`
def __init__(self, config: ModernBertConfig, device=None):
super().__init__()
self.max_seq_len_cached = config.max_position_embeddings
self.original_max_seq_len = config.max_position_embeddings
self.config = config
self.layer_types = list(set(config.layer_types))
self.rope_type = {}
for layer_type in self.layer_types:
rope_params = self.config.rope_parameters[layer_type]
if rope_params is None:
continue
self.rope_type[layer_type] = rope_params["rope_type"]
rope_init_fn: Callable = self.compute_default_rope_parameters
if self.rope_type[layer_type] != "default":
rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type[layer_type]]
curr_inv_freq, curr_attention_scaling = rope_init_fn(self.config, device, layer_type=layer_type)
self.register_buffer(f"{layer_type}_inv_freq", curr_inv_freq, persistent=False)
setattr(self, f"{layer_type}_original_inv_freq", curr_inv_freq)
setattr(self, f"{layer_type}_attention_scaling", curr_attention_scaling)
@staticmethod
def compute_default_rope_parameters(
config: Optional[ModernBertConfig] = None,
device: Optional["torch.device"] = None,
seq_len: Optional[int] = None,
layer_type: Optional[str] = None,
) -> tuple["torch.Tensor", float]:
"""
Computes the inverse frequencies according to the original RoPE implementation
Args:
config ([`~transformers.PreTrainedConfig`]):
The model configuration.
device (`torch.device`):
The device to use for initialization of the inverse frequencies.
seq_len (`int`, *optional*):
The current sequence length. Unused for this type of RoPE.
layer_type (`str`, *optional*):
The current layer type if the model has different RoPE parameters per type.
Should not be used unless `config.layer_types is not None`
Returns:
Tuple of (`torch.Tensor`, `float`), containing the inverse frequencies for the RoPE embeddings and the
post-processing scaling factor applied to the computed cos/sin (unused in this type of RoPE).
"""
# For backward compatibility standardize the `rope_parameters_dict` if it uses old format
base = config.rope_parameters[layer_type]["rope_theta"]
dim = getattr(config, "head_dim", None) or config.hidden_size // config.num_attention_heads
attention_factor = 1.0 # Unused in this type of RoPE
# Compute the inverse frequencies
inv_freq = 1.0 / (
base ** (torch.arange(0, dim, 2, dtype=torch.int64).to(device=device, dtype=torch.float) / dim)
)
return inv_freq, attention_factor
@torch.no_grad()
@dynamic_rope_update # power user: used with advanced RoPE types (e.g. dynamic rope)
def forward(self, x, position_ids, layer_type=None):
inv_freq = getattr(self, f"{layer_type}_inv_freq")
attention_scaling = getattr(self, f"{layer_type}_attention_scaling")
inv_freq_expanded = inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1).to(x.device)
position_ids_expanded = position_ids[:, None, :].float()
device_type = x.device.type if isinstance(x.device.type, str) and x.device.type != "mps" else "cpu"
with torch.autocast(device_type=device_type, enabled=False): # Force float32
freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
emb = torch.cat((freqs, freqs), dim=-1)
cos = emb.cos() * attention_scaling
sin = emb.sin() * attention_scaling
return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
def rotate_half(x):
"""Rotates half the hidden dims of the input."""
x1 = x[..., : x.shape[-1] // 2]
x2 = x[..., x.shape[-1] // 2 :]
return torch.cat((-x2, x1), dim=-1)
@use_kernel_func_from_hub("rotary_pos_emb")
def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):
"""Applies Rotary Position Embedding to the query and key tensors.
Args:
q (`torch.Tensor`): The query tensor.
k (`torch.Tensor`): The key tensor.
cos (`torch.Tensor`): The cosine part of the rotary embedding.
sin (`torch.Tensor`): The sine part of the rotary embedding.
position_ids (`torch.Tensor`, *optional*):
Deprecated and unused.
unsqueeze_dim (`int`, *optional*, defaults to 1):
The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
Returns:
`tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
"""
cos = cos.unsqueeze(unsqueeze_dim)
sin = sin.unsqueeze(unsqueeze_dim)
q_embed = (q * cos) + (rotate_half(q) * sin)
k_embed = (k * cos) + (rotate_half(k) * sin)
return q_embed, k_embed
def eager_attention_forward(
module: "ModernBertAttention",
qkv: torch.Tensor,
attention_mask: torch.Tensor,
sliding_window_mask: torch.Tensor,
position_ids: Optional[torch.LongTensor],
local_attention: tuple[int, int],
bs: int,
dim: int,
position_embeddings: torch.Tensor,
output_attentions: Optional[bool] = False,
**_kwargs,
) -> Union[tuple[torch.Tensor, torch.Tensor], tuple[torch.Tensor]]:
# qkv: [batch_size, seqlen, 3, nheads, headdim]
cos, sin = position_embeddings
query, key, value = qkv.transpose(3, 1).unbind(dim=2)
# query, key, value: [batch_size, heads, seq_len, head_dim]
query, key = apply_rotary_pos_emb(query, key, cos, sin)
scale = module.head_dim**-0.5
attn_weights = torch.matmul(query, key.transpose(2, 3)) * scale
if local_attention != (-1, -1):
attention_mask = sliding_window_mask
attn_weights = attn_weights + attention_mask
# upcast attention to fp32
attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype)
attn_weights = nn.functional.dropout(attn_weights, p=module.attention_dropout, training=module.training)
attn_output = torch.matmul(attn_weights, value)
attn_output = attn_output.transpose(1, 2).contiguous()
attn_output = attn_output.view(bs, -1, dim)
if output_attentions:
return (attn_output, attn_weights)
return (attn_output,)
def flash_attention_forward(
module: "ModernBertAttention",
qkv: torch.Tensor,
rotary_emb: ModernBertUnpaddedRotaryEmbedding,
cu_seqlens: torch.Tensor,
max_seqlen: int,
local_attention: tuple[int, int],
bs: int,
dim: int,
target_dtype: torch.dtype = torch.bfloat16,
**_kwargs,
) -> tuple[torch.Tensor]:
# (total_seqlen, 3, nheads, headdim)
qkv = rotary_emb(qkv, cu_seqlens=cu_seqlens, max_seqlen=max_seqlen)
convert_dtype = qkv.dtype not in (torch.float16, torch.bfloat16)
if convert_dtype:
# FA2 implementation only supports fp16 and bf16. If FA2 is supported,
# bfloat16 must be supported as of FA2 2.5.7. (Turing GPUs not supported)
orig_dtype = qkv.dtype
qkv = qkv.to(target_dtype)
attn = flash_attn_varlen_qkvpacked_func(
qkv,
cu_seqlens=cu_seqlens,
max_seqlen=max_seqlen,
dropout_p=module.attention_dropout if module.training else 0.0,
deterministic=module.deterministic_flash_attn,
window_size=local_attention,
)
attn = attn.to(orig_dtype) # type: ignore
else:
attn = flash_attn_varlen_qkvpacked_func(
qkv,
cu_seqlens=cu_seqlens,
max_seqlen=max_seqlen,
dropout_p=module.attention_dropout if module.training else 0.0,
deterministic=module.deterministic_flash_attn,
window_size=local_attention,
)
return (attn.view(bs, dim),)
def sdpa_attention_forward(
module: "ModernBertAttention",
qkv: torch.Tensor,
attention_mask: torch.Tensor,
sliding_window_mask: torch.Tensor,
position_ids: Optional[torch.LongTensor],
local_attention: tuple[int, int],
bs: int,
dim: int,
position_embeddings: torch.Tensor,
**_kwargs,
) -> tuple[torch.Tensor]:
# qkv: [batch_size, seqlen, 3, nheads, headdim]
cos, sin = position_embeddings
query, key, value = qkv.transpose(3, 1).unbind(dim=2)
# query, key, value: [batch_size, heads, seq_len, head_dim]
query, key = apply_rotary_pos_emb(query, key, cos, sin)
if local_attention != (-1, -1):
attention_mask = sliding_window_mask
attn_output = (
F.scaled_dot_product_attention(
query,
key,
value,
dropout_p=module.attention_dropout if module.training else 0.0,
attn_mask=attention_mask,
)
.transpose(1, 2)
.contiguous()
)
attn_output = attn_output.view(bs, -1, dim)
return (attn_output,)
MODERNBERT_ATTENTION_FUNCTION = {
"flash_attention_2": flash_attention_forward,
"eager": eager_attention_forward,
"sdpa": sdpa_attention_forward,
}
| ModernBertRotaryEmbedding |
python | sympy__sympy | sympy/physics/secondquant.py | {
"start": 8789,
"end": 8835
} | class ____(SqOperator):
pass
| BosonicOperator |
python | apache__airflow | providers/amazon/src/airflow/providers/amazon/aws/transfers/dynamodb_to_s3.py | {
"start": 1556,
"end": 2367
} | class ____(json.JSONEncoder):
"""Custom json encoder implementation."""
def default(self, obj):
"""Convert decimal objects in a json serializable format."""
if isinstance(obj, Decimal):
return float(obj)
return super().default(obj)
def _convert_item_to_json_bytes(item: dict[str, Any]) -> bytes:
return (json.dumps(item, cls=JSONEncoder) + "\n").encode("utf-8")
def _upload_file_to_s3(
file_obj: IO,
bucket_name: str,
s3_key_prefix: str,
aws_conn_id: str | None | ArgNotSet = AwsBaseHook.default_conn_name,
) -> None:
s3_client = S3Hook(aws_conn_id=aws_conn_id).get_conn()
file_obj.seek(0)
s3_client.upload_file(
Filename=file_obj.name,
Bucket=bucket_name,
Key=s3_key_prefix + str(uuid4()),
)
| JSONEncoder |
python | pytest-dev__pytest-xdist | src/xdist/workermanage.py | {
"start": 9662,
"end": 9702
} | class ____(enum.Enum):
END = -1
| Marker |
python | apache__airflow | providers/google/src/airflow/providers/google/cloud/links/cloud_run.py | {
"start": 892,
"end": 1091
} | class ____(BaseGoogleLink):
"""Helper class for constructing Cloud Run Job Logging link."""
name = "Cloud Run Job Logging"
key = "log_uri"
format_str = "{log_uri}"
| CloudRunJobLoggingLink |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.