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 | xlwings__xlwings | xlwings/udfs.py | {
"start": 8364,
"end": 28421
} | class ____(Range):
"""
A Range subclass that stores the impl as
a serialized COM object so it can be passed between
threads easily
https://devblogs.microsoft.com/oldnewthing/20151021-00/?p=91311
"""
def __init__(self, rng):
super().__init__(impl=rng.impl)
self._ser_thread = threading.get_ident()
self._ser = pythoncom.CoMarshalInterThreadInterfaceInStream(
pythoncom.IID_IDispatch, rng.api
)
self._ser_resultCLSID = self._impl.api.CLSID
self._deser_thread = None
self._deser = None
@property
def impl(self):
if threading.get_ident() == self._ser_thread:
return self._impl
elif threading.get_ident() == self._deser_thread:
return self._deser
assert self._deser is None, f"already deserialized on {self._deser_thread}"
self._deser_thread = threading.get_ident()
deser = pythoncom.CoGetInterfaceAndReleaseStream(
self._ser, pythoncom.IID_IDispatch
)
dispatch = Dispatch(deser, resultCLSID=self._ser_resultCLSID)
self._ser = None # single-use
self._deser = xlwings._xlwindows.Range(xl=dispatch)
return self._deser
def __copy__(self):
"""
We need to re-serialize the COM object as they're
single-use
"""
return ComRange(self)
async def _com(self, fn, *args, backoff=1):
"""
:param backoff: if the call fails, time to wait in ms
before the next one. Random exponential backoff to
a cap.
"""
loop = asyncio.get_running_loop()
try:
return await loop.run_in_executor(
com_executor, functools.partial(fn, copy.copy(self), *args)
)
except AttributeError:
# the Dispatch object that the `com_executor` thread
# didn't deserialize properly, as Excel was too busy
# to handle the TypeInfo call when requested
pass
except Exception as e:
if getattr(e, "hresult", 0) not in RPC_E_SERVERCALL_RETRYLATER:
raise
await asyncio.sleep(backoff / 1e3)
return await self._com(
fn, *args, backoff=min(backoff * round(1 + random()), MAX_BACKOFF_MS)
)
async def clear_contents(self):
await self._com(lambda rng: rng.impl.clear_contents())
async def set_formula_array(self, f):
await self._com(lambda rng: setattr(rng.impl, "formula_array", f))
async def set_formula(self, f):
await self._com(lambda rng: setattr(rng.impl, "formula", f))
async def set_formula2(self, f):
await self._com(lambda rng: setattr(rng.impl, "formula2", f))
async def get_shape(self):
return await self._com(lambda rng: rng.impl.shape)
async def get_formula_array(self):
return await self._com(lambda rng: rng.impl.formula_array)
async def get_formula(self):
return await self._com(lambda rng: rng.impl.formula)
async def get_formula2(self):
return await self._com(lambda rng: rng.impl.formula2)
async def get_address(self):
return await self._com(lambda rng: rng.impl.address)
async def delayed_resize_dynamic_array_formula(target_range, caller):
try:
await asyncio.sleep(0.1)
stashme = await caller.get_formula_array()
if not stashme:
stashme = await caller.get_formula()
c_y, c_x = await caller.get_shape()
t_y, t_x = await target_range.get_shape()
if c_x > t_x or c_y > t_y:
await caller.clear_contents()
# this will call the UDF again (hitting the cache),
# but you'll have the right size output this time
# (`caller` will be `target_range`). We'll have to
# be careful not to block the async loop!
await target_range.set_formula_array(stashme)
except: # noqa: E722
exception(logger, "couldn't resize")
def get_udf_module(module_name, xl_workbook):
module_info = udf_modules.get(module_name, None)
if module_info is not None:
module = module_info["module"]
# If filetime is None, it's not reloadable
if module_info["filetime"] is not None:
mtime = os.path.getmtime(module_info["filename"])
if mtime != module_info["filetime"]:
module = reload(module)
module_info["filetime"] = mtime
module_info["module"] = module
else:
# Handle embedded code (Excel only)
if xl_workbook:
wb = Book(impl=xlwings._xlwindows.Book(Dispatch(xl_workbook)))
for sheet in wb.sheets:
if sheet.name.endswith(".py") and not __pro__:
raise LicenseError("Embedded code requires a valid LICENSE_KEY.")
elif sheet.name.endswith(".py") and __pro__:
from .pro.embedded_code import dump_embedded_code
from .pro.utils import get_embedded_code_temp_dir
dump_embedded_code(wb, get_embedded_code_temp_dir())
module = import_module(module_name)
filename = os.path.normcase(module.__file__.lower())
try: # getmtime fails for zip imports and frozen modules
mtime = os.path.getmtime(filename)
except OSError:
mtime = None
udf_modules[module_name] = {
"filename": filename,
"filetime": mtime,
"module": module,
}
return module
def get_cache_key(func, args, caller):
"""only use this if function is called from cells, not VBA"""
xw_caller = Range(impl=xlwings._xlwindows.Range(xl=caller))
return (
func.__name__
+ str(args)
+ str(xw_caller.sheet.book.app.pid)
+ xw_caller.sheet.book.name
+ xw_caller.sheet.name
+ xw_caller.address.split(":")[0]
)
def call_udf(module_name, func_name, args, this_workbook=None, caller=None):
"""
This method executes the UDF synchronously from the COM server thread
"""
module = get_udf_module(module_name, this_workbook)
func = getattr(module, func_name)
func_info = func.__xlfunc__
args_info = func_info["args"]
ret_info = func_info["ret"]
is_dynamic_array = ret_info["options"].get("expand")
xw_caller = Range(impl=xlwings._xlwindows.Range(xl=caller))
# If there is the 'reserved' argument "caller", assign the caller object
for info in args_info:
if info["name"] == "caller":
args = list(args)
args[info["pos"]] = ComRange(xw_caller)
args = tuple(args)
writing = func_info.get("writing", None)
if writing and writing == xw_caller.address:
return func_info["rval"]
args = list(args)
for i, arg in enumerate(args):
arg_info = args_info[min(i, len(args_info) - 1)]
if isinstance(arg, int) and arg == -2147352572: # missing
args[i] = arg_info.get("optional", None)
elif xlwings._xlwindows.is_range_instance(arg):
args[i] = conversion.read(
Range(impl=xlwings._xlwindows.Range(xl=arg)),
None,
arg_info["options"],
)
else:
args[i] = conversion.read(None, arg, arg_info["options"])
if this_workbook:
xlwings._xlwindows.BOOK_CALLER = Dispatch(this_workbook)
from .com_server import loop
if func_info["async_mode"] and func_info["async_mode"] == "threading":
if caller is None:
asyncio.run_coroutine_threadsafe(
async_thread_nocaller(func, args),
loop,
)
return [[0]]
cache_key = get_cache_key(func, args, caller)
cached_value = cache.get(cache_key)
if (
cached_value is not None
): # test against None as np arrays don't have a truth value
if not is_dynamic_array: # for dynamic arrays, the cache is cleared below
del cache[cache_key]
ret = cached_value
else:
ret = [["#N/A waiting..." * xw_caller.columns.count] * xw_caller.rows.count]
# this does a lot of nested COM calls, so do this all
# synchronously on the COM thread until there is async
# support for Sheet, Book & App.
my_has_dynamic_array = has_dynamic_array(xw_caller.sheet.book.app.pid)
asyncio.run_coroutine_threadsafe(
async_thread(
ComRange(xw_caller),
my_has_dynamic_array,
func,
args,
cache_key,
is_dynamic_array,
),
loop,
)
return ret
else:
if is_dynamic_array:
cache_key = get_cache_key(func, args, caller)
cached_value = cache.get(cache_key)
if cached_value is not None:
ret = cached_value
else:
if inspect.iscoroutinefunction(func):
ret = asyncio.run_coroutine_threadsafe(func(*args), loop).result()
else:
ret = func(*args)
cache[cache_key] = ret
elif inspect.iscoroutinefunction(func):
ret = asyncio.run_coroutine_threadsafe(func(*args), loop).result()
else:
ret = func(*args)
xl_result = conversion.write(ret, None, ret_info["options"])
if is_dynamic_array:
current_size = (len(xw_caller.rows), len(xw_caller.columns))
result_size = (1, 1)
if type(xl_result) is list:
result_height = len(xl_result)
result_width = result_height and len(xl_result[0])
result_size = (max(1, result_height), max(1, result_width))
if current_size != result_size:
target_range = xw_caller.resize(*result_size)
asyncio.run_coroutine_threadsafe(
delayed_resize_dynamic_array_formula(
target_range=ComRange(target_range), caller=ComRange(xw_caller)
),
loop,
)
else:
del cache[cache_key]
return xl_result
def generate_vba_wrapper(module_name, module, f, xl_workbook):
vba = VBAWriter(f)
for svar in map(lambda attr: getattr(module, attr), dir(module)):
if hasattr(svar, "__xlfunc__"):
xlfunc = svar.__xlfunc__
fname = xlfunc["name"]
call_in_wizard = xlfunc["call_in_wizard"]
volatile = xlfunc["volatile"]
ftype = "Sub" if xlfunc["sub"] else "Function"
func_sig = ftype + " " + fname + "("
first = True
vararg = ""
for arg in xlfunc["args"]:
if arg["name"] == "caller":
arg[
"vba"
] = "Nothing" # will be replaced with caller under call_udf
if not arg["vba"]:
argname = arg["name"]
if not first:
func_sig += ", "
if "optional" in arg:
func_sig += "Optional "
elif arg["vararg"]:
func_sig += "ParamArray "
vararg = argname
func_sig += argname
if arg["vararg"]:
func_sig += "()"
first = False
func_sig += ")"
with vba.block(func_sig):
if ftype == "Function":
if not call_in_wizard:
vba.writeln(
'If (Not Application.CommandBars("Standard")'
".Controls(1).Enabled) Then Exit Function"
)
if volatile:
vba.writeln("Application.Volatile")
if vararg != "":
vba.writeln("Dim argsArray() As Variant")
non_varargs = [
arg["vba"] or arg["name"]
for arg in xlfunc["args"]
if not arg["vararg"]
]
vba.writeln(
"argsArray = Array(%s)" % tuple({", ".join(non_varargs)})
)
vba.writeln(
"ReDim Preserve argsArray(0 to UBound("
+ vararg
+ ") - LBound("
+ vararg
+ ") + "
+ str(len(non_varargs))
+ ")"
)
vba.writeln(
"For k = LBound(" + vararg + ") To UBound(" + vararg + ")"
)
vba.writeln(
"argsArray("
+ str(len(non_varargs))
+ " + k - LBound("
+ vararg
+ ")) = "
+ argname
+ "(k)"
)
vba.writeln("Next k")
args_vba = "argsArray"
else:
args_vba = (
"Array("
+ ", ".join(arg["vba"] or arg["name"] for arg in xlfunc["args"])
+ ")"
)
# Add-ins work with ActiveWorkbook instead of ThisWorkbook
vba_workbook = (
"ActiveWorkbook"
if xl_workbook.Name.endswith(".xlam")
else "ThisWorkbook"
)
if ftype == "Sub":
with vba.block('#If App = "Microsoft Excel" Then'):
vba.writeln(
'XLPy.CallUDF "{module_name}", "{fname}", '
"{args_vba}, {vba_workbook}, Application.Caller",
module_name=module_name,
fname=fname,
args_vba=args_vba,
vba_workbook=vba_workbook,
)
with vba.block("#Else"):
vba.writeln(
'XLPy.CallUDF "{module_name}", "{fname}", {args_vba}',
module_name=module_name,
fname=fname,
args_vba=args_vba,
)
vba.writeln("#End If")
else:
with vba.block('#If App = "Microsoft Excel" Then'):
vba.writeln(
"If TypeOf Application.Caller Is Range Then "
"On Error GoTo failed"
)
vba.writeln(
'{fname} = XLPy.CallUDF("{module_name}", "{fname}", '
"{args_vba}, {vba_workbook}, Application.Caller)",
module_name=module_name,
fname=fname,
args_vba=args_vba,
vba_workbook=vba_workbook,
)
vba.writeln("Exit " + ftype)
with vba.block("#Else"):
vba.writeln(
'{fname} = XLPy.CallUDF("{module_name}", '
'"{fname}", {args_vba})',
module_name=module_name,
fname=fname,
args_vba=args_vba,
)
vba.writeln("Exit " + ftype)
vba.writeln("#End If")
vba.write_label("failed")
vba.writeln(fname + " = Err.Description")
vba.writeln("End " + ftype)
vba.writeln("")
def import_udfs(module_names, xl_workbook):
module_names = module_names.split(";")
tf = tempfile.NamedTemporaryFile(mode="w", delete=False)
vba = VBAWriter(tf.file)
vba.writeln('Attribute VB_Name = "xlwings_udfs"')
vba.writeln(
"'Autogenerated code by xlwings - changes will be lost with next import!"
)
vba.writeln(
"""#Const App = "Microsoft Excel" 'Adjust when using outside of Excel"""
)
if __pro__:
for module_name in module_names:
sheet_config = read_config_sheet(
Book(impl=xlwings._xlwindows.Book(Dispatch(xl_workbook)))
)
code_map = sheet_config.get("RELEASE_EMBED_CODE_MAP", "{}")
sheetname_to_path = json.loads(code_map)
if module_name + ".py" in sheetname_to_path:
real_module_name = sheetname_to_path[module_name + ".py"][:-3]
module_names.remove(module_name)
module_names.append(real_module_name)
for module_name in module_names:
module = get_udf_module(module_name, xl_workbook)
generate_vba_wrapper(module_name, module, tf.file, xl_workbook)
tf.close()
try:
xl_workbook.VBProject.VBComponents.Remove(
xl_workbook.VBProject.VBComponents("xlwings_udfs")
)
except pywintypes.com_error:
pass
try:
xl_workbook.VBProject.VBComponents.Import(tf.name)
except pywintypes.com_error:
# Fallback. Some users get in Excel "Automation error 440" with this traceback
# in Python: pywintypes.com_error: (-2147352567, 'Exception occurred.',
# (0, None, None, None, 0, -2146827284), None)
xl_workbook.Application.Run("ImportXlwingsUdfsModule", tf.name)
for module_name in module_names:
module = get_udf_module(module_name, xl_workbook)
for mvar in map(lambda attr: getattr(module, attr), dir(module)):
if hasattr(mvar, "__xlfunc__"):
xlfunc = mvar.__xlfunc__
xlret = xlfunc["ret"]
xlargs = xlfunc["args"]
fname = xlfunc["name"]
fdoc = xlret["doc"][:255]
fcategory = xlfunc["category"]
excel_version = [
int(x) for x in re.split("[,\\.]", xl_workbook.Application.Version)
]
if excel_version[0] >= 14:
argdocs = [arg["doc"][:255] for arg in xlargs if not arg["vba"]]
xl_workbook.Application.MacroOptions(
"'" + xl_workbook.Name + "'!" + fname,
Description=fdoc,
HasMenu=False,
MenuText=None,
HasShortcutKey=False,
ShortcutKey=None,
Category=fcategory,
StatusBar=None,
HelpContextID=None,
HelpFile=None,
ArgumentDescriptions=argdocs if argdocs else None,
)
else:
xl_workbook.Application.MacroOptions(
"'" + xl_workbook.Name + "'!" + fname, Description=fdoc
)
# try to delete the temp file - doesn't matter too much if it fails
try:
os.unlink(tf.name)
except: # noqa: E722
pass
msg = f'Imported functions from the following modules: {", ".join(module_names)}'
logger.info(msg) if logger.hasHandlers() else print(msg)
@functools.lru_cache(None)
def has_dynamic_array(pid):
"""This check in this form doesn't work on macOS,
that's why it's here and not in utils
"""
try:
apps[pid].api.WorksheetFunction.Unique("dummy")
return True
except (AttributeError, pywintypes.com_error):
return False
| ComRange |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_set_column11.py | {
"start": 315,
"end": 1673
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("set_column06.xlsx")
def test_create_file(self):
"""Test the creation of a simple XlsxWriter file."""
workbook = Workbook(self.got_filename)
worksheet = workbook.add_worksheet()
chart = workbook.add_chart({"type": "line"})
bold = workbook.add_format({"bold": 1})
italic = workbook.add_format({"italic": 1})
chart.axis_ids = [69197824, 69199360]
data = [
[1, 2, 3, 4, 5],
[2, 4, 6, 8, 10],
[3, 6, 9, 12, 15],
]
worksheet.write("A1", "Foo", bold)
worksheet.write("B1", "Bar", italic)
worksheet.write_column("A2", data[0])
worksheet.write_column("B2", data[1])
worksheet.write_column("C2", data[2])
worksheet.set_row_pixels(12, None, None, {"hidden": True})
worksheet.set_column_pixels("F:F", None, None, {"hidden": True})
chart.add_series({"values": "=Sheet1!$A$2:$A$6"})
chart.add_series({"values": "=Sheet1!$B$2:$B$6"})
chart.add_series({"values": "=Sheet1!$C$2:$C$6"})
worksheet.insert_chart("E9", chart)
workbook.close()
self.assertExcelEqual()
| TestCompareXLSXFiles |
python | scrapy__scrapy | scrapy/downloadermiddlewares/httpauth.py | {
"start": 544,
"end": 1604
} | class ____:
"""Set Basic HTTP Authorization header
(http_user and http_pass spider class attributes)"""
@classmethod
def from_crawler(cls, crawler: Crawler) -> Self:
o = cls()
crawler.signals.connect(o.spider_opened, signal=signals.spider_opened)
return o
def spider_opened(self, spider: Spider) -> None:
usr = getattr(spider, "http_user", "")
pwd = getattr(spider, "http_pass", "")
if usr or pwd:
self.auth = basic_auth_header(usr, pwd)
self.domain = spider.http_auth_domain # type: ignore[attr-defined]
@_warn_spider_arg
def process_request(
self, request: Request, spider: Spider | None = None
) -> Request | Response | None:
auth = getattr(self, "auth", None)
if (
auth
and b"Authorization" not in request.headers
and (not self.domain or url_is_from_any_domain(request.url, [self.domain]))
):
request.headers[b"Authorization"] = auth
return None
| HttpAuthMiddleware |
python | ansible__ansible | test/units/parsing/vault/test_vault.py | {
"start": 25379,
"end": 42829
} | class ____(unittest.TestCase):
def setUp(self):
self.vault_password = "test-vault-password"
text_secret = TextVaultSecret(self.vault_password)
self.vault_secrets = [('default', text_secret),
('test_id', text_secret)]
self.v = vault.VaultLib(self.vault_secrets)
def _vault_secrets_from_password(self, vault_id, password):
return [(vault_id, TextVaultSecret(password))]
def test_encrypt(self):
plaintext = u'Some text to encrypt in a café'
b_vaulttext = self.v.encrypt(plaintext)
self.assertIsInstance(b_vaulttext, bytes)
b_header = b'$ANSIBLE_VAULT;1.1;AES256\n'
self.assertEqual(b_vaulttext[:len(b_header)], b_header)
def test_encrypt_vault_id(self):
plaintext = u'Some text to encrypt in a café'
b_vaulttext = self.v.encrypt(plaintext, vault_id='test_id')
self.assertIsInstance(b_vaulttext, bytes)
b_header = b'$ANSIBLE_VAULT;1.2;AES256;test_id\n'
self.assertEqual(b_vaulttext[:len(b_header)], b_header)
def test_encrypt_bytes(self):
plaintext = to_bytes(u'Some text to encrypt in a café')
b_vaulttext = self.v.encrypt(plaintext)
self.assertIsInstance(b_vaulttext, bytes)
b_header = b'$ANSIBLE_VAULT;1.1;AES256\n'
self.assertEqual(b_vaulttext[:len(b_header)], b_header)
def test_encrypt_no_secret_empty_secrets(self):
vault_secrets = []
v = vault.VaultLib(vault_secrets)
plaintext = u'Some text to encrypt in a café'
self.assertRaisesRegex(vault.AnsibleVaultError,
'.*A vault password must be specified to encrypt data.*',
v.encrypt,
plaintext)
def test_format_vaulttext_envelope(self):
cipher_name = "TEST"
b_ciphertext = b"ansible"
b_vaulttext = vault.format_vaulttext_envelope(b_ciphertext,
cipher_name,
version=self.v.b_version,
vault_id='default')
b_lines = b_vaulttext.split(b'\n')
self.assertGreater(len(b_lines), 1, msg="failed to properly add header")
b_header = b_lines[0]
# self.assertTrue(b_header.endswith(b';TEST'), msg="header does not end with cipher name")
b_header_parts = b_header.split(b';')
self.assertEqual(len(b_header_parts), 4, msg="header has the wrong number of parts")
self.assertEqual(b_header_parts[0], b'$ANSIBLE_VAULT', msg="header does not start with $ANSIBLE_VAULT")
self.assertEqual(b_header_parts[1], self.v.b_version, msg="header version is incorrect")
self.assertEqual(b_header_parts[2], b'TEST', msg="header does not end with cipher name")
# And just to verify, lets parse the results and compare
b_ciphertext2, b_version2, cipher_name2, vault_id2 = \
vault.parse_vaulttext_envelope(b_vaulttext)
self.assertEqual(b_ciphertext, b_ciphertext2)
self.assertEqual(self.v.b_version, b_version2)
self.assertEqual(cipher_name, cipher_name2)
self.assertEqual('default', vault_id2)
def test_parse_vaulttext_envelope(self):
b_vaulttext = b"$ANSIBLE_VAULT;9.9;TEST\nansible"
b_ciphertext, b_version, cipher_name, vault_id = vault.parse_vaulttext_envelope(b_vaulttext)
b_lines = b_ciphertext.split(b'\n')
self.assertEqual(b_lines[0], b"ansible", msg="Payload was not properly split from the header")
self.assertEqual(cipher_name, u'TEST', msg="cipher name was not properly set")
self.assertEqual(b_version, b"9.9", msg="version was not properly set")
def test_parse_vaulttext_envelope_crlf(self):
b_vaulttext = b"$ANSIBLE_VAULT;9.9;TEST\r\nansible"
b_ciphertext, b_version, cipher_name, vault_id = vault.parse_vaulttext_envelope(b_vaulttext)
b_lines = b_ciphertext.split(b'\n')
self.assertEqual(b_lines[0], b"ansible", msg="Payload was not properly split from the header")
self.assertEqual(cipher_name, u'TEST', msg="cipher name was not properly set")
self.assertEqual(b_version, b"9.9", msg="version was not properly set")
def test_encrypt_decrypt_aes256(self):
self.v.cipher_name = u'AES256'
plaintext = u"foobar"
b_vaulttext = self.v.encrypt(plaintext)
b_plaintext = self.v.decrypt(b_vaulttext)
self.assertNotEqual(b_vaulttext, b"foobar", msg="encryption failed")
self.assertEqual(b_plaintext, b"foobar", msg="decryption failed")
def test_encrypt_decrypt_aes256_none_secrets(self):
vault_secrets = self._vault_secrets_from_password('default', 'ansible')
v = vault.VaultLib(vault_secrets)
plaintext = u"foobar"
b_vaulttext = v.encrypt(plaintext)
# VaultLib will default to empty {} if secrets is None
v_none = vault.VaultLib(None)
# so set secrets None explicitly
v_none.secrets = None
self.assertRaisesRegex(vault.AnsibleVaultError,
'.*A vault password must be specified to decrypt data.*',
v_none.decrypt,
b_vaulttext)
def test_encrypt_decrypt_aes256_empty_secrets(self):
vault_secrets = self._vault_secrets_from_password('default', 'ansible')
v = vault.VaultLib(vault_secrets)
plaintext = u"foobar"
b_vaulttext = v.encrypt(plaintext)
vault_secrets_empty = []
v_none = vault.VaultLib(vault_secrets_empty)
self.assertRaisesRegex(vault.AnsibleVaultError,
'.*Attempting to decrypt but no vault secrets found.*',
v_none.decrypt,
b_vaulttext)
def test_encrypt_decrypt_aes256_multiple_secrets_all_wrong(self):
plaintext = u'Some text to encrypt in a café'
b_vaulttext = self.v.encrypt(plaintext)
vault_secrets = [('default', TextVaultSecret('another-wrong-password')),
('wrong-password', TextVaultSecret('wrong-password'))]
v_multi = vault.VaultLib(vault_secrets)
with self.assertRaisesRegex(errors.AnsibleError, '.*Decryption failed.*'):
v_multi.decrypt(b_vaulttext)
def test_encrypt_decrypt_aes256_multiple_secrets_one_valid(self):
plaintext = u'Some text to encrypt in a café'
b_vaulttext = self.v.encrypt(plaintext)
correct_secret = TextVaultSecret(self.vault_password)
wrong_secret = TextVaultSecret('wrong-password')
vault_secrets = [('default', wrong_secret),
('corect_secret', correct_secret),
('wrong_secret', wrong_secret)]
v_multi = vault.VaultLib(vault_secrets)
b_plaintext = v_multi.decrypt(b_vaulttext)
self.assertNotEqual(b_vaulttext, to_bytes(plaintext), msg="encryption failed")
self.assertEqual(b_plaintext, to_bytes(plaintext), msg="decryption failed")
def test_encrypt_decrypt_aes256_existing_vault(self):
self.v.cipher_name = u'AES256'
b_orig_plaintext = b"Setec Astronomy"
vaulttext = u"""$ANSIBLE_VAULT;1.1;AES256
33363965326261303234626463623963633531343539616138316433353830356566396130353436
3562643163366231316662386565383735653432386435610a306664636137376132643732393835
63383038383730306639353234326630666539346233376330303938323639306661313032396437
6233623062366136310a633866373936313238333730653739323461656662303864663666653563
3138"""
b_plaintext = self.v.decrypt(vaulttext)
self.assertEqual(b_plaintext, b_plaintext, msg="decryption failed")
b_vaulttext = to_bytes(vaulttext, encoding='ascii', errors='strict')
b_plaintext = self.v.decrypt(b_vaulttext)
self.assertEqual(b_plaintext, b_orig_plaintext, msg="decryption failed")
def test_decrypt_and_get_vault_id(self):
b_expected_plaintext = to_bytes('foo bar\n')
vaulttext = """$ANSIBLE_VAULT;1.2;AES256;ansible_devel
65616435333934613466373335363332373764363365633035303466643439313864663837393234
3330656363343637313962633731333237313636633534630a386264363438363362326132363239
39363166646664346264383934393935653933316263333838386362633534326664646166663736
6462303664383765650a356637643633366663643566353036303162386237336233393065393164
6264"""
vault_secrets = self._vault_secrets_from_password('ansible_devel', 'ansible')
v = vault.VaultLib(vault_secrets)
b_vaulttext = to_bytes(vaulttext)
b_plaintext, vault_id_used, vault_secret_used = v.decrypt_and_get_vault_id(b_vaulttext)
self.assertEqual(b_expected_plaintext, b_plaintext)
self.assertEqual(vault_id_used, 'ansible_devel')
self.assertEqual(vault_secret_used.text, 'ansible')
def test_decrypt_non_default_1_2(self):
b_expected_plaintext = to_bytes('foo bar\n')
vaulttext = """$ANSIBLE_VAULT;1.2;AES256;ansible_devel
65616435333934613466373335363332373764363365633035303466643439313864663837393234
3330656363343637313962633731333237313636633534630a386264363438363362326132363239
39363166646664346264383934393935653933316263333838386362633534326664646166663736
6462303664383765650a356637643633366663643566353036303162386237336233393065393164
6264"""
vault_secrets = self._vault_secrets_from_password('default', 'ansible')
v = vault.VaultLib(vault_secrets)
b_vaulttext = to_bytes(vaulttext)
b_plaintext = v.decrypt(b_vaulttext)
self.assertEqual(b_expected_plaintext, b_plaintext)
b_ciphertext, b_version, cipher_name, vault_id = vault.parse_vaulttext_envelope(b_vaulttext)
self.assertEqual('ansible_devel', vault_id)
self.assertEqual(b'1.2', b_version)
def test_decrypt_decrypted(self):
plaintext = u"ansible"
self.assertRaises(errors.AnsibleError, self.v.decrypt, plaintext)
b_plaintext = b"ansible"
self.assertRaises(errors.AnsibleError, self.v.decrypt, b_plaintext)
def test_cipher_not_set(self):
plaintext = u"ansible"
self.v.encrypt(plaintext)
self.assertEqual(self.v.cipher_name, "AES256")
def test_verify_encrypted_string_methods():
"""Verify all relevant methods on `str` are implemented on `EncryptedString`."""
str_methods_to_not_implement = {
'__class__',
'__dir__',
'__getattribute__', # generated by Python, identical to the one on `str` in Python 3.13+, but different on earlier versions
'__getnewargs__',
'__getstate__',
'__reduce__',
'__reduce_ex__',
}
str_methods = set(dir(''))
encrypted_string_methods = set(name for name in dir(EncryptedString) if name in str_methods and getattr(EncryptedString, name) is not getattr(str, name))
missing_methods = str_methods - encrypted_string_methods - str_methods_to_not_implement
assert not missing_methods
def test_vault_secrets_context_required(_zap_vault_secrets_context) -> None:
with pytest.raises(ReferenceError, match=f"A required {VaultSecretsContext.__name__} context is not active."):
VaultSecretsContext.current()
def test_vault_secrets_context_optional(_zap_vault_secrets_context) -> None:
assert VaultSecretsContext.current(optional=True) is None
def test_vault_secrets_context_current(_zap_vault_secrets_context) -> None:
ctx = VaultSecretsContext([])
VaultSecretsContext.initialize(ctx)
assert VaultSecretsContext.current() is ctx
def test_vault_secrets_context_already_initialized(_zap_vault_secrets_context) -> None:
VaultSecretsContext.initialize(VaultSecretsContext([]))
with pytest.raises(RuntimeError, match=f"The {VaultSecretsContext.__name__} context is already initialized."):
VaultSecretsContext.initialize(VaultSecretsContext([]))
def test_encrypted_string_unmanaged_access(_vault_secrets_context: VaultTestHelper) -> None:
"""
Validates that unmanaged access to an `EncryptedString`:
* properly decrypts and caches the value when secrets are available
* propagates Origin and VaultedValue tags
"""
plaintext = 'i am plaintext'
encrypted_string = _vault_secrets_context.make_encrypted_string(plaintext)
origin = Origin.get_required_tag(encrypted_string)
vaulted_value_tag = VaultedValue(ciphertext=VaultHelper.get_ciphertext(encrypted_string, with_tags=False))
res1 = str(encrypted_string)
res2 = str(encrypted_string)
assert res1 == res2 == plaintext
assert res1 is res2 # ensure the result is cached
assert Origin.get_required_tag(res1) is origin
assert VaultedValue.get_required_tag(res1).ciphertext == vaulted_value_tag.ciphertext
def test_encrypted_string_unmanaged_access_fail(_vault_secrets_context: VaultTestHelper) -> None:
"""Validates that unmanaged access to an `EncryptedString` fails with AnsibleVaultError when secrets are not available."""
encrypted_string = _vault_secrets_context.make_encrypted_string("i am plaintext")
VaultSecretsContext.current().secrets = []
with pytest.raises(AnsibleVaultError):
str(encrypted_string)
@pytest.mark.parametrize(
"value, conversion_func", (
("fourty-two", str),
(42, int),
(42.42, float),
))
def test_encrypted_string_conversion_methods(value: t.Any, conversion_func: t.Callable, _vault_secrets_context: VaultTestHelper):
"""Ensure that `EncryptedString` dunder conversion methods decrypt and pass through correctly."""
encrypted_string = _vault_secrets_context.make_encrypted_string(str(value))
converted = conversion_func(encrypted_string)
assert converted == value
def test_radd(_vault_secrets_context: VaultTestHelper) -> None:
"""Ensure that the __radd__ dunder method decrypts and passes through."""
assert "plain string " + _vault_secrets_context.make_encrypted_string("secret string") == "plain string secret string"
def make_marker(marker_type: type[Marker], *args, **kwargs):
"""Utility function to create marker values under a TemplateContext."""
with TemplateContext(template_value="blah", templar=TemplateEngine(), options=TemplateOptions.DEFAULT):
return marker_type(*args, **kwargs)
origin = Origin(path="/test")
@pytest.mark.parametrize("value, expected_ciphertext", (
(origin.tag(EncryptedString(ciphertext="ciphertext")), "ciphertext"),
(origin.tag(VaultedValue(ciphertext="ciphertext").tag("something")), "ciphertext"),
(make_marker(VaultExceptionMarker, ciphertext=origin.tag("ciphertext"), event=_messages.Event(msg="")), "ciphertext"),
(make_marker(TruncationMarker), None),
("not vaulted", None),
))
def test_vaulthelper_get_ciphertext(value: t.Any, expected_ciphertext: str | None) -> None:
"""Validate `get_ciphertext` helper responses and tag preservation behavior."""
expected_tags = {origin} if expected_ciphertext is not None else set()
tagged_ciphertext = VaultHelper.get_ciphertext(value, with_tags=True)
untagged_ciphertext = VaultHelper.get_ciphertext(value, with_tags=False)
assert untagged_ciphertext == expected_ciphertext
assert tagged_ciphertext == expected_ciphertext
assert AnsibleTagHelper.tags(tagged_ciphertext) == expected_tags
assert not AnsibleTagHelper.tags(untagged_ciphertext)
@pytest.mark.parametrize("expression, expected_expression", (
("os.path.join(ed, efn)", "str(temp_file)"),
("os.path.exists(ef)", "True"),
("os.path.dirname(ef)", "str(temp_dir)"),
("os.path.isdir(ed)", "True"),
("os.path.basename(ef)", "temp_file.name"),
("os.listdir(ed)", "[temp_file.name]"),
("open(ef).read()", "'Ansible'"),
))
def test_encrypted_string_path_fspath(_vault_secrets_context: VaultTestHelper, expression: str, expected_expression: str) -> None:
"""Ensure that `EncryptedString` works with `PathLike` duck-typing consumers."""
with tempfile.TemporaryDirectory() as temp_dir_path:
temp_dir = pathlib.Path(temp_dir_path)
temp_file = (pathlib.Path(temp_dir) / 'temp_file')
temp_file.write_text('Ansible')
expression_locals = dict(
temp_file=temp_file,
temp_dir=temp_dir,
ed=_vault_secrets_context.make_encrypted_string(str(temp_dir)),
edn=_vault_secrets_context.make_encrypted_string(temp_dir.name),
ef=_vault_secrets_context.make_encrypted_string(str(temp_file)),
efn=_vault_secrets_context.make_encrypted_string(temp_file.name),
)
expected = eval(expected_expression, globals(), expression_locals)
result = eval(expression, globals(), expression_locals)
assert result == expected
def test_protocol_conformance(_vault_secrets_context: VaultTestHelper) -> None:
"""Verify that the `_EncryptedStringProtocol` defined by the collection loader is implemented."""
assert isinstance(_vault_secrets_context.make_encrypted_string("hey"), _EncryptedStringProtocol)
def test_encrypted_string_cannot_be_trusted() -> None:
"""Verify that `EncryptedString` cannot be trusted for templating."""
es = EncryptedString(ciphertext='x')
still_not_trusted = TrustedAsTemplate().tag(es)
assert not TrustedAsTemplate.is_tagged_on(still_not_trusted)
| TestVaultLib |
python | arrow-py__arrow | tests/test_locales.py | {
"start": 112172,
"end": 113300
} | class ____:
def test_format_timeframe(self):
assert self.locale._format_timeframe("now", 0) == "agora"
assert self.locale._format_timeframe("second", 1) == "um segundo"
assert self.locale._format_timeframe("seconds", 30) == "30 segundos"
assert self.locale._format_timeframe("minute", 1) == "um minuto"
assert self.locale._format_timeframe("minutes", 40) == "40 minutos"
assert self.locale._format_timeframe("hour", 1) == "uma hora"
assert self.locale._format_timeframe("hours", 23) == "23 horas"
assert self.locale._format_timeframe("day", 1) == "um dia"
assert self.locale._format_timeframe("days", 12) == "12 dias"
assert self.locale._format_timeframe("month", 1) == "um mês"
assert self.locale._format_timeframe("months", 11) == "11 meses"
assert self.locale._format_timeframe("year", 1) == "um ano"
assert self.locale._format_timeframe("years", 12) == "12 anos"
assert self.locale._format_relative("uma hora", "hour", -1) == "faz uma hora"
@pytest.mark.usefixtures("lang_locale")
| TestBrazilianPortugueseLocale |
python | doocs__leetcode | solution/0900-0999/0911.Online Election/Solution.py | {
"start": 0,
"end": 564
} | class ____:
def __init__(self, persons: List[int], times: List[int]):
cnt = Counter()
self.times = times
self.wins = []
cur = 0
for p in persons:
cnt[p] += 1
if cnt[cur] <= cnt[p]:
cur = p
self.wins.append(cur)
def q(self, t: int) -> int:
i = bisect_right(self.times, t) - 1
return self.wins[i]
# Your TopVotedCandidate object will be instantiated and called as such:
# obj = TopVotedCandidate(persons, times)
# param_1 = obj.q(t)
| TopVotedCandidate |
python | huggingface__transformers | src/transformers/models/granite/configuration_granite.py | {
"start": 1168,
"end": 9190
} | class ____(PreTrainedConfig):
r"""
This is the configuration class to store the configuration of a [`GraniteModel`]. It is used to instantiate an Granite
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 Granite-3B.
Configuration objects inherit from [`PreTrainedConfig`] and can be used to control the model outputs. Read the
documentation from [`PreTrainedConfig`] for more information.
Args:
vocab_size (`int`, *optional*, defaults to 32000):
Vocabulary size of the Granite model. Defines the number of different tokens that can be represented by the
`inputs_ids` passed when calling [`GraniteModel`]
hidden_size (`int`, *optional*, defaults to 4096):
Dimension of the hidden representations.
intermediate_size (`int`, *optional*, defaults to 11008):
Dimension of the MLP representations.
num_hidden_layers (`int`, *optional*, defaults to 32):
Number of hidden layers in the Transformer decoder.
num_attention_heads (`int`, *optional*, defaults to 32):
Number of attention heads for each attention layer in the Transformer decoder.
num_key_value_heads (`int`, *optional*):
This is the number of key_value heads that should be used to implement Grouped Query Attention. If
`num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
`num_key_value_heads=1` the model will use Multi Query Attention (MQA) otherwise GQA is used. When
converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
by meanpooling all the original heads within that group. For more details, check out [this
paper](https://huggingface.co/papers/2305.13245). If it is not specified, will default to
`num_attention_heads`.
hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):
The non-linear activation function (function or string) in the decoder.
max_position_embeddings (`int`, *optional*, defaults to 2048):
The maximum sequence length that this model might ever be used with.
initializer_range (`float`, *optional*, defaults to 0.02):
The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
rms_norm_eps (`float`, *optional*, defaults to 1e-06):
The epsilon used by the rms normalization layers.
use_cache (`bool`, *optional*, defaults to `True`):
Whether or not the model should return the last key/values attentions (not used by all models). Only
relevant if `config.is_decoder=True`.
pad_token_id (`int`, *optional*):
Padding token id.
bos_token_id (`int`, *optional*, defaults to 1):
Beginning of stream token id.
eos_token_id (`int`, *optional*, defaults to 2):
End of stream token id.
tie_word_embeddings (`bool`, *optional*, defaults to `False`):
Whether to tie weight embeddings
rope_parameters (`RopeParameters`, *optional*):
Dictionary containing the configuration parameters for the RoPE embeddings. The dictionary should contain
a value for `rope_theta` and optionally parameters used for scaling in case you want to use RoPE
with longer `max_position_embeddings`.
attention_bias (`bool`, *optional*, defaults to `False`):
Whether to use a bias in the query, key, value and output projection layers during self-attention.
attention_dropout (`float`, *optional*, defaults to 0.0):
The dropout ratio for the attention probabilities.
mlp_bias (`bool`, *optional*, defaults to `False`):
Whether to use a bias in up_proj, down_proj and gate_proj layers in the MLP layers.
embedding_multiplier (`float`, *optional*, defaults to 1.0): embedding multiplier
logits_scaling (`float`, *optional*, defaults to 1.0): divisor for output logits
residual_multiplier (`float`, *optional*, defaults to 1.0): residual multiplier
attention_multiplier (`float`, *optional*, defaults to 1.0): attention multiplier
```python
>>> from transformers import GraniteModel, GraniteConfig
>>> # Initializing a Granite granite-3b style configuration
>>> configuration = GraniteConfig()
>>> # Initializing a model from the granite-7b style configuration
>>> model = GraniteModel(configuration)
>>> # Accessing the model configuration
>>> configuration = model.config
```"""
model_type = "granite"
keys_to_ignore_at_inference = ["past_key_values"]
# Default tensor parallel plan for base model `GraniteModel`
base_model_tp_plan = {
"layers.*.self_attn.q_proj": "colwise",
"layers.*.self_attn.k_proj": "colwise",
"layers.*.self_attn.v_proj": "colwise",
"layers.*.self_attn.o_proj": "rowwise",
"layers.*.mlp.gate_proj": "colwise",
"layers.*.mlp.up_proj": "colwise",
"layers.*.mlp.down_proj": "rowwise",
}
base_model_pp_plan = {
"embed_tokens": (["input_ids"], ["inputs_embeds"]),
"layers": (["hidden_states", "attention_mask"], ["hidden_states"]),
"norm": (["hidden_states"], ["hidden_states"]),
}
def __init__(
self,
vocab_size: Optional[int] = 32000,
hidden_size: Optional[int] = 4096,
intermediate_size: Optional[int] = 11008,
num_hidden_layers: Optional[int] = 32,
num_attention_heads: Optional[int] = 32,
num_key_value_heads: Optional[int] = None,
hidden_act: Optional[str] = "silu",
max_position_embeddings: Optional[int] = 2048,
initializer_range: Optional[float] = 0.02,
rms_norm_eps: Optional[int] = 1e-6,
use_cache: Optional[bool] = True,
pad_token_id: Optional[int] = None,
bos_token_id: Optional[int] = 1,
eos_token_id: Optional[int] = 2,
tie_word_embeddings: Optional[bool] = False,
rope_parameters: Optional[RopeParameters | dict[str, RopeParameters]] = None,
attention_bias: Optional[bool] = False,
attention_dropout: Optional[float] = 0.0,
mlp_bias: Optional[bool] = False,
embedding_multiplier: Optional[float] = 1.0,
logits_scaling: Optional[float] = 1.0,
residual_multiplier: Optional[float] = 1.0,
attention_multiplier: Optional[float] = 1.0,
**kwargs,
):
self.vocab_size = vocab_size
self.max_position_embeddings = max_position_embeddings
self.hidden_size = hidden_size
self.intermediate_size = intermediate_size
self.num_hidden_layers = num_hidden_layers
self.num_attention_heads = num_attention_heads
# for backward compatibility
if num_key_value_heads is None:
num_key_value_heads = num_attention_heads
self.num_key_value_heads = num_key_value_heads
self.hidden_act = hidden_act
self.initializer_range = initializer_range
self.rms_norm_eps = rms_norm_eps
self.use_cache = use_cache
self.attention_bias = attention_bias
self.attention_dropout = attention_dropout
self.mlp_bias = mlp_bias
self.embedding_multiplier = embedding_multiplier
self.logits_scaling = logits_scaling
self.residual_multiplier = residual_multiplier
self.attention_multiplier = attention_multiplier
self.rope_parameters = rope_parameters
super().__init__(
pad_token_id=pad_token_id,
bos_token_id=bos_token_id,
eos_token_id=eos_token_id,
tie_word_embeddings=tie_word_embeddings,
**kwargs,
)
__all__ = ["GraniteConfig"]
| GraniteConfig |
python | python-openxml__python-docx | tests/test_table.py | {
"start": 21861,
"end": 23103
} | class ____:
"""Unit-test suite for `docx.table._Columns` objects."""
def it_has_sequence_behaviors(self, table_: Mock):
columns = _Columns(cast(CT_Tbl, element("w:tbl/w:tblGrid/(w:gridCol,w:gridCol)")), table_)
# -- it supports len() --
assert len(columns) == 2
# -- it is iterable --
assert len(tuple(c for c in columns)) == 2
assert all(type(c) is _Column for c in columns)
# -- it is indexable --
assert all(type(columns[i]) is _Column for i in range(2))
def it_raises_on_indexed_access_out_of_range(self, table_: Mock):
columns = _Columns(cast(CT_Tbl, element("w:tbl/w:tblGrid/(w:gridCol,w:gridCol)")), table_)
with pytest.raises(IndexError):
columns[2]
with pytest.raises(IndexError):
columns[-3]
def it_provides_access_to_the_table_it_belongs_to(self, table_: Mock):
columns = _Columns(cast(CT_Tbl, element("w:tbl")), table_)
table_.table = table_
assert columns.table is table_
# fixtures -------------------------------------------------------
@pytest.fixture
def table_(self, request: FixtureRequest):
return instance_mock(request, Table)
| Describe_Columns |
python | allegroai__clearml | clearml/backend_api/services/v2_9/events.py | {
"start": 88805,
"end": 89689
} | class ____(Request):
"""
:param task: Task ID
:type task: str
"""
_service = "events"
_action = "get_vector_metrics_and_variants"
_version = "2.9"
_schema = {
"definitions": {},
"properties": {"task": {"description": "Task ID", "type": "string"}},
"required": ["task"],
"type": "object",
}
def __init__(self, task: str, **kwargs: Any) -> None:
super(GetVectorMetricsAndVariantsRequest, self).__init__(**kwargs)
self.task = task
@schema_property("task")
def task(self) -> str:
return self._property_task
@task.setter
def task(self, value: str) -> None:
if value is None:
self._property_task = None
return
self.assert_isinstance(value, "task", six.string_types)
self._property_task = value
| GetVectorMetricsAndVariantsRequest |
python | django__django | tests/admin_changelist/models.py | {
"start": 2813,
"end": 2944
} | class ____(models.Manager):
def get_queryset(self):
return super().get_queryset().order_by("number")
| OrderedObjectManager |
python | google__pytype | pytype/rewrite/flow/frame_base.py | {
"start": 928,
"end": 3890
} | class ____(Generic[_T]):
"""Virtual machine frame.
Attributes:
_final_locals: The frame's `locals` dictionary after it finishes execution.
This is a protected attribute so that subclasses can choose whether and
how to expose control flow information.
current_opcode: The current opcode.
"""
def __init__(
self, code: blocks.OrderedCode,
initial_locals: Mapping[str, variables.Variable[_T]],
):
# Sanity check: non-empty code
assert code.order and all(block.code for block in code.order)
self._code = code # bytecode
# Local names before and after frame runs
self._initial_locals = initial_locals
self._final_locals: Mapping[str, variables.Variable[_T]] = None
self._current_step = _Step(0, 0) # current block and opcode indices
self._states: dict[int, state.BlockState[_T]] = {} # block id to state
# Initialize the state of the first block.
self._states[self._code.order[0].id] = state.BlockState(
locals_=dict(self._initial_locals))
self._current_state: state.BlockState[_T] = None # state of current block
@property
def current_opcode(self) -> opcodes.Opcode:
return self._code.order[self._current_step.block][self._current_step.opcode]
def step(self) -> None:
"""Runs one opcode."""
# Grab the current block and opcode.
block_index = self._current_step.block
if block_index == _FINAL:
raise FrameConsumedError()
opcode_index = self._current_step.opcode
block = self._code.order[block_index]
opcode = block[opcode_index]
# Grab the block's initial state.
self._current_state = self._states[block.id]
if not opcode_index:
log.info('Entering block: %d', block.id)
# Run the opcode.
opname = opcode.__class__.__name__
try:
op_impl = getattr(self, f'byte_{opname}')
except AttributeError as e:
raise NotImplementedError(f'Opcode {opname} not implemented') from e
log.info(str(opcode))
op_impl(opcode)
# Update current block and opcode.
if opcode is not block[-1]:
self._current_step.opcode += 1
return
log.info('Exiting block: %d', block.id)
if not opcode.carry_on_to_next():
# Update the frame's final state.
self._merge_state_into(self._current_state, _FINAL)
elif not opcode.has_known_jump():
# Merge the current state into the next.
self._merge_state_into(self._current_state, opcode.next.index)
if block is self._code.order[-1]:
self._current_step.block = _FINAL
self._final_locals = self._states[_FINAL].get_locals()
else:
self._current_step.block += 1
self._current_step.opcode = 0
def stepn(self, n: int) -> None:
"""Runs n opcodes."""
for _ in range(n):
self.step()
def _merge_state_into(
self, from_state: state.BlockState[_T], block_id: int) -> None:
self._states[block_id] = from_state.merge_into(self._states.get(block_id))
| FrameBase |
python | jina-ai__jina | jina/types/request/data.py | {
"start": 14234,
"end": 14701
} | class ____(DataRequest):
"""
Response is the :class:`~jina.types.request.Request` object returned by the flow.
At the moment it is an alias for :class:`~jina.types.request.Request`,
and therefore shares an identical representation.
Currently, its sole purpose is to give a more consistent semantic on
the client API: send a :class:`~jina.types.request.data.DataRequest` and receive a :class:`~jina.types.request.data.Response`.
"""
| Response |
python | celery__celery | celery/backends/dynamodb.py | {
"start": 667,
"end": 19580
} | class ____(KeyValueStoreBackend):
"""AWS DynamoDB result backend.
Raises:
celery.exceptions.ImproperlyConfigured:
if module :pypi:`boto3` is not available.
"""
#: default DynamoDB table name (`default`)
table_name = 'celery'
#: Read Provisioned Throughput (`default`)
read_capacity_units = 1
#: Write Provisioned Throughput (`default`)
write_capacity_units = 1
#: AWS region (`default`)
aws_region = None
#: The endpoint URL that is passed to boto3 (local DynamoDB) (`default`)
endpoint_url = None
#: Item time-to-live in seconds (`default`)
time_to_live_seconds = None
# DynamoDB supports Time to Live as an auto-expiry mechanism.
supports_autoexpire = True
_key_field = DynamoDBAttribute(name='id', data_type='S')
# Each record has either a value field or count field
_value_field = DynamoDBAttribute(name='result', data_type='B')
_count_filed = DynamoDBAttribute(name="chord_count", data_type='N')
_timestamp_field = DynamoDBAttribute(name='timestamp', data_type='N')
_ttl_field = DynamoDBAttribute(name='ttl', data_type='N')
_available_fields = None
implements_incr = True
def __init__(self, url=None, table_name=None, *args, **kwargs):
super().__init__(*args, **kwargs)
self.url = url
self.table_name = table_name or self.table_name
if not boto3:
raise ImproperlyConfigured(
'You need to install the boto3 library to use the '
'DynamoDB backend.')
aws_credentials_given = False
aws_access_key_id = None
aws_secret_access_key = None
if url is not None:
scheme, region, port, username, password, table, query = \
parse_url(url)
aws_access_key_id = username
aws_secret_access_key = password
access_key_given = aws_access_key_id is not None
secret_key_given = aws_secret_access_key is not None
if access_key_given != secret_key_given:
raise ImproperlyConfigured(
'You need to specify both the Access Key ID '
'and Secret.')
aws_credentials_given = access_key_given
if region == 'localhost' or DynamoDBBackend._is_valid_ip(region):
# We are using the downloadable, local version of DynamoDB
self.endpoint_url = f'http://{region}:{port}'
self.aws_region = 'us-east-1'
logger.warning(
'Using local-only DynamoDB endpoint URL: {}'.format(
self.endpoint_url
)
)
else:
self.aws_region = region
# If endpoint_url is explicitly set use it instead
_get = self.app.conf.get
config_endpoint_url = _get('dynamodb_endpoint_url')
if config_endpoint_url:
self.endpoint_url = config_endpoint_url
self.read_capacity_units = int(
query.get(
'read',
self.read_capacity_units
)
)
self.write_capacity_units = int(
query.get(
'write',
self.write_capacity_units
)
)
ttl = query.get('ttl_seconds', self.time_to_live_seconds)
if ttl:
try:
self.time_to_live_seconds = int(ttl)
except ValueError as e:
logger.error(
f'TTL must be a number; got "{ttl}"',
exc_info=e
)
raise e
self.table_name = table or self.table_name
self._available_fields = (
self._key_field,
self._value_field,
self._timestamp_field
)
self._client = None
if aws_credentials_given:
self._get_client(
access_key_id=aws_access_key_id,
secret_access_key=aws_secret_access_key
)
@staticmethod
def _is_valid_ip(ip):
try:
ip_address(ip)
return True
except ValueError:
return False
def _get_client(self, access_key_id=None, secret_access_key=None):
"""Get client connection."""
if self._client is None:
client_parameters = {
'region_name': self.aws_region
}
if access_key_id is not None:
client_parameters.update({
'aws_access_key_id': access_key_id,
'aws_secret_access_key': secret_access_key
})
if self.endpoint_url is not None:
client_parameters['endpoint_url'] = self.endpoint_url
self._client = boto3.client(
'dynamodb',
**client_parameters
)
self._get_or_create_table()
if self._has_ttl() is not None:
self._validate_ttl_methods()
self._set_table_ttl()
return self._client
def _get_table_schema(self):
"""Get the boto3 structure describing the DynamoDB table schema."""
return {
'AttributeDefinitions': [
{
'AttributeName': self._key_field.name,
'AttributeType': self._key_field.data_type
}
],
'TableName': self.table_name,
'KeySchema': [
{
'AttributeName': self._key_field.name,
'KeyType': 'HASH'
}
],
'ProvisionedThroughput': {
'ReadCapacityUnits': self.read_capacity_units,
'WriteCapacityUnits': self.write_capacity_units
}
}
def _get_or_create_table(self):
"""Create table if not exists, otherwise return the description."""
table_schema = self._get_table_schema()
try:
return self._client.describe_table(TableName=self.table_name)
except ClientError as e:
error_code = e.response['Error'].get('Code', 'Unknown')
if error_code == 'ResourceNotFoundException':
table_description = self._client.create_table(**table_schema)
logger.info(
'DynamoDB Table {} did not exist, creating.'.format(
self.table_name
)
)
# In case we created the table, wait until it becomes available.
self._wait_for_table_status('ACTIVE')
logger.info(
'DynamoDB Table {} is now available.'.format(
self.table_name
)
)
return table_description
else:
raise e
def _has_ttl(self):
"""Return the desired Time to Live config.
- True: Enable TTL on the table; use expiry.
- False: Disable TTL on the table; don't use expiry.
- None: Ignore TTL on the table; don't use expiry.
"""
return None if self.time_to_live_seconds is None \
else self.time_to_live_seconds >= 0
def _validate_ttl_methods(self):
"""Verify boto support for the DynamoDB Time to Live methods."""
# Required TTL methods.
required_methods = (
'update_time_to_live',
'describe_time_to_live',
)
# Find missing methods.
missing_methods = []
for method in list(required_methods):
if not hasattr(self._client, method):
missing_methods.append(method)
if missing_methods:
logger.error(
(
'boto3 method(s) {methods} not found; ensure that '
'boto3>=1.9.178 and botocore>=1.12.178 are installed'
).format(
methods=','.join(missing_methods)
)
)
raise AttributeError(
'boto3 method(s) {methods} not found'.format(
methods=','.join(missing_methods)
)
)
def _get_ttl_specification(self, ttl_attr_name):
"""Get the boto3 structure describing the DynamoDB TTL specification."""
return {
'TableName': self.table_name,
'TimeToLiveSpecification': {
'Enabled': self._has_ttl(),
'AttributeName': ttl_attr_name
}
}
def _get_table_ttl_description(self):
# Get the current TTL description.
try:
description = self._client.describe_time_to_live(
TableName=self.table_name
)
except ClientError as e:
error_code = e.response['Error'].get('Code', 'Unknown')
error_message = e.response['Error'].get('Message', 'Unknown')
logger.error((
'Error describing Time to Live on DynamoDB table {table}: '
'{code}: {message}'
).format(
table=self.table_name,
code=error_code,
message=error_message,
))
raise e
return description
def _set_table_ttl(self):
"""Enable or disable Time to Live on the table."""
# Get the table TTL description, and return early when possible.
description = self._get_table_ttl_description()
status = description['TimeToLiveDescription']['TimeToLiveStatus']
if status in ('ENABLED', 'ENABLING'):
cur_attr_name = \
description['TimeToLiveDescription']['AttributeName']
if self._has_ttl():
if cur_attr_name == self._ttl_field.name:
# We want TTL enabled, and it is currently enabled or being
# enabled, and on the correct attribute.
logger.debug((
'DynamoDB Time to Live is {situation} '
'on table {table}'
).format(
situation='already enabled'
if status == 'ENABLED'
else 'currently being enabled',
table=self.table_name
))
return description
elif status in ('DISABLED', 'DISABLING'):
if not self._has_ttl():
# We want TTL disabled, and it is currently disabled or being
# disabled.
logger.debug((
'DynamoDB Time to Live is {situation} '
'on table {table}'
).format(
situation='already disabled'
if status == 'DISABLED'
else 'currently being disabled',
table=self.table_name
))
return description
# The state shouldn't ever have any value beyond the four handled
# above, but to ease troubleshooting of potential future changes, emit
# a log showing the unknown state.
else: # pragma: no cover
logger.warning((
'Unknown DynamoDB Time to Live status {status} '
'on table {table}. Attempting to continue.'
).format(
status=status,
table=self.table_name
))
# At this point, we have one of the following situations:
#
# We want TTL enabled,
#
# - and it's currently disabled: Try to enable.
#
# - and it's being disabled: Try to enable, but this is almost sure to
# raise ValidationException with message:
#
# Time to live has been modified multiple times within a fixed
# interval
#
# - and it's currently enabling or being enabled, but on the wrong
# attribute: Try to enable, but this will raise ValidationException
# with message:
#
# TimeToLive is active on a different AttributeName: current
# AttributeName is ttlx
#
# We want TTL disabled,
#
# - and it's currently enabled: Try to disable.
#
# - and it's being enabled: Try to disable, but this is almost sure to
# raise ValidationException with message:
#
# Time to live has been modified multiple times within a fixed
# interval
#
attr_name = \
cur_attr_name if status == 'ENABLED' else self._ttl_field.name
try:
specification = self._client.update_time_to_live(
**self._get_ttl_specification(
ttl_attr_name=attr_name
)
)
logger.info(
(
'DynamoDB table Time to Live updated: '
'table={table} enabled={enabled} attribute={attr}'
).format(
table=self.table_name,
enabled=self._has_ttl(),
attr=self._ttl_field.name
)
)
return specification
except ClientError as e:
error_code = e.response['Error'].get('Code', 'Unknown')
error_message = e.response['Error'].get('Message', 'Unknown')
logger.error((
'Error {action} Time to Live on DynamoDB table {table}: '
'{code}: {message}'
).format(
action='enabling' if self._has_ttl() else 'disabling',
table=self.table_name,
code=error_code,
message=error_message,
))
raise e
def _wait_for_table_status(self, expected='ACTIVE'):
"""Poll for the expected table status."""
achieved_state = False
while not achieved_state:
table_description = self.client.describe_table(
TableName=self.table_name
)
logger.debug(
'Waiting for DynamoDB table {} to become {}.'.format(
self.table_name,
expected
)
)
current_status = table_description['Table']['TableStatus']
achieved_state = current_status == expected
sleep(1)
def _prepare_get_request(self, key):
"""Construct the item retrieval request parameters."""
return {
'TableName': self.table_name,
'Key': {
self._key_field.name: {
self._key_field.data_type: key
}
}
}
def _prepare_put_request(self, key, value):
"""Construct the item creation request parameters."""
timestamp = time()
put_request = {
'TableName': self.table_name,
'Item': {
self._key_field.name: {
self._key_field.data_type: key
},
self._value_field.name: {
self._value_field.data_type: value
},
self._timestamp_field.name: {
self._timestamp_field.data_type: str(timestamp)
}
}
}
if self._has_ttl():
put_request['Item'].update({
self._ttl_field.name: {
self._ttl_field.data_type:
str(int(timestamp + self.time_to_live_seconds))
}
})
return put_request
def _prepare_init_count_request(self, key: str) -> Dict[str, Any]:
"""Construct the counter initialization request parameters"""
timestamp = time()
return {
'TableName': self.table_name,
'Item': {
self._key_field.name: {
self._key_field.data_type: key
},
self._count_filed.name: {
self._count_filed.data_type: "0"
},
self._timestamp_field.name: {
self._timestamp_field.data_type: str(timestamp)
}
}
}
def _prepare_inc_count_request(self, key: str) -> Dict[str, Any]:
"""Construct the counter increment request parameters"""
return {
'TableName': self.table_name,
'Key': {
self._key_field.name: {
self._key_field.data_type: key
}
},
'UpdateExpression': f"set {self._count_filed.name} = {self._count_filed.name} + :num",
"ExpressionAttributeValues": {
":num": {"N": "1"},
},
"ReturnValues": "UPDATED_NEW",
}
def _item_to_dict(self, raw_response):
"""Convert get_item() response to field-value pairs."""
if 'Item' not in raw_response:
return {}
return {
field.name: raw_response['Item'][field.name][field.data_type]
for field in self._available_fields
}
@property
def client(self):
return self._get_client()
def get(self, key):
key = str(key)
request_parameters = self._prepare_get_request(key)
item_response = self.client.get_item(**request_parameters)
item = self._item_to_dict(item_response)
return item.get(self._value_field.name)
def set(self, key, value):
key = str(key)
request_parameters = self._prepare_put_request(key, value)
self.client.put_item(**request_parameters)
def mget(self, keys):
return [self.get(key) for key in keys]
def delete(self, key):
key = str(key)
request_parameters = self._prepare_get_request(key)
self.client.delete_item(**request_parameters)
def incr(self, key: bytes) -> int:
"""Atomically increase the chord_count and return the new count"""
key = str(key)
request_parameters = self._prepare_inc_count_request(key)
item_response = self.client.update_item(**request_parameters)
new_count: str = item_response["Attributes"][self._count_filed.name][self._count_filed.data_type]
return int(new_count)
def _apply_chord_incr(self, header_result_args, body, **kwargs):
chord_key = self.get_key_for_chord(header_result_args[0])
init_count_request = self._prepare_init_count_request(str(chord_key))
self.client.put_item(**init_count_request)
return super()._apply_chord_incr(
header_result_args, body, **kwargs)
| DynamoDBBackend |
python | has2k1__plotnine | plotnine/scales/scale_manual.py | {
"start": 2478,
"end": 3715
} | class ____(_scale_manual):
"""
Custom discrete linetype scale
See Also
--------
[](`matplotlib.markers`)
"""
values: InitVar[Sequence[Any] | dict[Any, Any]]
"""
Linetypes that make up the palette. Possible values of the list are:
1. Strings like
```python
'solid' # solid line
'dashed' # dashed line
'dashdot' # dash-dotted line
'dotted' # dotted line
'None' or ' ' or '' # draw nothing
```
2. Tuples of the form (offset, (on, off, on, off, ....))
e.g. (0, (1, 1)), (1, (2, 2)), (2, (5, 3, 1, 3))
The values will be matched with the `limits` of the scale or the
`breaks` if provided. If it is a dict then it should map data
values to linetypes.
"""
_aesthetics = ["linetype"]
def map(self, x, limits=None):
result = super().map(x, limits)
# Ensure that custom linetypes are tuples, so that they can
# be properly inserted and extracted from the dataframe
if len(result) and hasattr(result[0], "__hash__"):
result = [x if isinstance(x, str) else tuple(x) for x in result]
return result
@dataclass
| scale_linetype_manual |
python | keras-team__keras | keras/src/callbacks/early_stopping_test.py | {
"start": 212,
"end": 9576
} | class ____(testing.TestCase):
@pytest.mark.requires_trainable_backend
def test_early_stopping(self):
x_train = np.random.random((10, 5))
y_train = np.random.random((10, 1))
x_test = np.random.random((10, 5))
y_test = np.random.random((10, 1))
model = models.Sequential(
(
layers.Dense(1, activation="relu"),
layers.Dense(1, activation="relu"),
)
)
model.compile(
loss="mae",
optimizer="adam",
metrics=[
"mse",
"acc",
"accuracy",
"hinge",
metrics.F1Score(name="f1_score"),
],
)
cases = [
("max", "val_mse", "max"),
("min", "val_loss", "min"),
("auto", "val_mse", "min"),
("auto", "loss", "min"),
("auto", "acc", "max"),
("auto", "val_accuracy", "max"),
("auto", "hinge", "min"),
("auto", "f1_score", "max"),
]
for mode, monitor, expected_mode in cases:
patience = 0
cbks = [
callbacks.EarlyStopping(
patience=patience, monitor=monitor, mode=mode
)
]
model.fit(
x_train,
y_train,
batch_size=5,
validation_data=(x_test, y_test),
callbacks=cbks,
epochs=2,
verbose=0,
)
if expected_mode == "max":
monitor_op = ops.greater
else:
monitor_op = ops.less
self.assertEqual(cbks[0].monitor_op, monitor_op)
with self.assertRaises(ValueError):
cbks = [
callbacks.EarlyStopping(patience=patience, monitor="unknown")
]
model.fit(
x_train,
y_train,
batch_size=5,
validation_data=(x_test, y_test),
callbacks=cbks,
epochs=2,
verbose=0,
)
@pytest.mark.requires_trainable_backend
def test_early_stopping_patience(self):
cases = [0, 1, 2, 3]
losses = [10.0, 9.0, 8.0, 9.0, 8.9, 8.8, 8.7, 8.6, 8.5]
for patience in cases:
stopper = callbacks.EarlyStopping(monitor="loss", patience=patience)
stopper.set_model(models.Sequential())
stopper.model.compile(loss="mse", optimizer="sgd")
stopper.on_train_begin()
for epoch, loss in enumerate(losses):
stopper.on_epoch_end(epoch=epoch, logs={"loss": loss})
if stopper.model.stop_training:
break
self.assertEqual(stopper.stopped_epoch, max(patience, 1) + 2)
@pytest.mark.requires_trainable_backend
def test_early_stopping_reuse(self):
patience = 3
data = np.random.random((100, 1))
labels = np.where(data > 0.5, 1, 0)
model = models.Sequential(
(
layers.Dense(1, activation="relu"),
layers.Dense(1, activation="relu"),
)
)
model.compile(
optimizer="sgd",
loss="mae",
metrics=["mse"],
)
stopper = callbacks.EarlyStopping(monitor="mse", patience=patience)
history1 = model.fit(
data, labels, callbacks=[stopper], verbose=0, epochs=20
)
self.assertGreaterEqual(len(history1.epoch), patience)
history2 = model.fit(
data, labels, callbacks=[stopper], verbose=0, epochs=20
)
self.assertGreaterEqual(len(history2.epoch), patience)
@pytest.mark.requires_trainable_backend
def test_early_stopping_with_baseline(self):
baseline = 0.6
x_train = np.random.random((10, 5))
y_train = np.random.random((10, 1))
model = models.Sequential(
(
layers.Dense(1, activation="relu"),
layers.Dense(1, activation="relu"),
)
)
model.compile(optimizer="sgd", loss="mae", metrics=["mse"])
patience = 3
stopper = callbacks.EarlyStopping(
monitor="mse", patience=patience, baseline=baseline
)
hist = model.fit(
x_train, y_train, callbacks=[stopper], verbose=0, epochs=20
)
assert len(hist.epoch) >= patience
def test_early_stopping_final_weights_when_restoring_model_weights(self):
class DummyModel:
def __init__(self):
self.stop_training = False
self.weights = -1
def get_weights(self):
return self.weights
def set_weights(self, weights):
self.weights = weights
def set_weight_to_epoch(self, epoch):
self.weights = epoch
early_stop = callbacks.EarlyStopping(
monitor="val_loss", patience=2, restore_best_weights=True
)
early_stop.set_model(DummyModel())
losses = [0.2, 0.15, 0.1, 0.11, 0.12]
# The best configuration is in the epoch 2 (loss = 0.1000).
epochs_trained = 0
early_stop.on_train_begin()
for epoch in range(len(losses)):
epochs_trained += 1
early_stop.model.set_weight_to_epoch(epoch=epoch)
early_stop.on_epoch_end(epoch, logs={"val_loss": losses[epoch]})
if early_stop.model.stop_training:
break
early_stop.on_train_end()
# The best configuration is in epoch 2 (loss = 0.1000),
# and while patience = 2, we're restoring the best weights,
# so we end up at the epoch with the best weights, i.e. epoch 2
self.assertEqual(early_stop.model.get_weights(), 2)
# Check early stopping when no model beats the baseline.
early_stop = callbacks.EarlyStopping(
monitor="val_loss",
patience=5,
baseline=0.5,
restore_best_weights=True,
)
early_stop.set_model(DummyModel())
losses = [0.9, 0.8, 0.7, 0.71, 0.72, 0.73]
# The best configuration is in the epoch 2 (loss = 0.7000).
epochs_trained = 0
early_stop.on_train_begin()
for epoch in range(len(losses)):
epochs_trained += 1
early_stop.model.set_weight_to_epoch(epoch=epoch)
early_stop.on_epoch_end(epoch, logs={"val_loss": losses[epoch]})
if early_stop.model.stop_training:
break
early_stop.on_train_end()
# No epoch improves on the baseline, so we should train for only 5
# epochs, and restore the second model.
self.assertEqual(epochs_trained, 5)
self.assertEqual(early_stop.model.get_weights(), 2)
# Check weight restoration when another callback requests a stop.
early_stop = callbacks.EarlyStopping(
monitor="val_loss",
patience=5,
baseline=0.5,
restore_best_weights=True,
)
early_stop.set_model(DummyModel())
losses = [0.9, 0.8, 0.7, 0.71, 0.72, 0.73]
# The best configuration is in the epoch 2 (loss = 0.7000).
epochs_trained = 0
early_stop.on_train_begin()
for epoch in range(len(losses)):
epochs_trained += 1
early_stop.model.set_weight_to_epoch(epoch=epoch)
early_stop.on_epoch_end(epoch, logs={"val_loss": losses[epoch]})
if epoch == 3:
early_stop.model.stop_training = True
if early_stop.model.stop_training:
break
early_stop.on_train_end()
# We should restore the second model.
self.assertEqual(epochs_trained, 4)
self.assertEqual(early_stop.model.get_weights(), 2)
@pytest.mark.requires_trainable_backend
def test_early_stopping_with_start_from_epoch(self):
x_train = np.random.random((10, 5))
y_train = np.random.random((10, 1))
model = models.Sequential(
(
layers.Dense(1, activation="relu"),
layers.Dense(1, activation="relu"),
)
)
model.compile(optimizer="sgd", loss="mae", metrics=["mse"])
start_from_epoch = 2
patience = 3
stopper = callbacks.EarlyStopping(
monitor="mse",
patience=patience,
start_from_epoch=start_from_epoch,
)
history = model.fit(
x_train, y_train, callbacks=[stopper], verbose=0, epochs=20
)
# Test 'patience' argument functions correctly when used
# in conjunction with 'start_from_epoch'.
self.assertGreaterEqual(len(history.epoch), patience + start_from_epoch)
start_from_epoch = 2
patience = 0
stopper = callbacks.EarlyStopping(
monitor="mse",
patience=patience,
start_from_epoch=start_from_epoch,
)
history = model.fit(
x_train, y_train, callbacks=[stopper], verbose=0, epochs=20
)
# Test for boundary condition when 'patience' = 0.
self.assertGreaterEqual(len(history.epoch), start_from_epoch)
| EarlyStoppingTest |
python | getsentry__sentry | tests/sentry/utils/sdk_crashes/test_sdk_crash_detection.py | {
"start": 6506,
"end": 13674
} | class ____(
TestCase,
PerformanceEventTestMixin,
SDKCrashReportTestMixin,
):
def create_event(self, data, project_id, assert_no_errors=True):
return self.store_event(data=data, project_id=project_id, assert_no_errors=assert_no_errors)
@pytest.mark.parametrize(
["sample_rate", "random_value", "sampled"],
[
(0.0, 0.0001, False),
(0.0, 0.5, False),
(1.0, 0.0001, True),
(1.0, 0.9999, True),
(0.1, 0.0001, True),
(0.1, 0.09, True),
(0.1, 0.1, True),
(0.1, 0.11, False),
(0.1, 0.5, False),
(0.1, 0.999, False),
],
)
@django_db_all
@pytest.mark.snuba
@patch("sentry.utils.sdk_crashes.sdk_crash_detection.sdk_crash_detection.sdk_crash_reporter")
def test_sample_rate(
mock_sdk_crash_reporter: MagicMock,
store_event: Callable[[dict[str, Collection[str]]], Event],
sample_rate: float,
random_value: float,
sampled: bool,
) -> None:
event = store_event(get_crash_event())
with patch("random.random", return_value=random_value):
configs = build_sdk_configs()
configs[0].sample_rate = sample_rate
sdk_crash_detection.detect_sdk_crash(event=event, configs=configs)
if sampled:
assert mock_sdk_crash_reporter.report.call_count == 1
else:
assert mock_sdk_crash_reporter.report.call_count == 0
@django_db_all
@pytest.mark.snuba
@patch("sentry.utils.sdk_crashes.sdk_crash_detection.sdk_crash_detection.sdk_crash_reporter")
def test_multiple_configs_first_one_picked(mock_sdk_crash_reporter, store_event) -> None:
event = store_event(data=get_crash_event())
sdk_configs = build_sdk_configs()
configs = [sdk_configs[0], sdk_configs[0]]
sdk_crash_detection.detect_sdk_crash(event=event, configs=configs)
assert mock_sdk_crash_reporter.report.call_count == 1
project_id = mock_sdk_crash_reporter.report.call_args.args[1]
assert project_id == 1234
@django_db_all
@pytest.mark.snuba
@patch("sentry.utils.sdk_crashes.sdk_crash_detection.sdk_crash_detection.sdk_crash_reporter")
@patch("sentry.utils.metrics.incr")
def test_should_increment_counters_for_sdk_crash(incr, sdk_crash_reporter, store_event) -> None:
event = store_event(data=get_crash_event())
sdk_configs = build_sdk_configs()
configs = [sdk_configs[0], sdk_configs[0]]
sdk_crash_detection.detect_sdk_crash(event=event, configs=configs)
incr.assert_has_calls(
[
call(
"post_process.sdk_crash_monitoring.sdk_event",
tags={"sdk_name": "sentry.cocoa", "sdk_version": "8.2.0"},
),
call(
"post_process.sdk_crash_monitoring.detecting_sdk_crash",
tags={"sdk_name": "sentry.cocoa", "sdk_version": "8.2.0"},
),
call(
"post_process.sdk_crash_monitoring.sdk_crash_detected",
tags={"sdk_name": "sentry.cocoa", "sdk_version": "8.2.0"},
),
],
any_order=True,
)
@django_db_all
@pytest.mark.snuba
@patch("sentry.utils.sdk_crashes.sdk_crash_detection.sdk_crash_detection.sdk_crash_reporter")
@patch("sentry.utils.metrics.incr")
def test_should_only_increment_detecting_counter_for_non_crash_event(
incr, sdk_crash_reporter, store_event
):
non_crash_event = store_event(data=get_crash_event(function="+[SentrySDK crash]"))
sdk_configs = build_sdk_configs()
configs = [sdk_configs[0], sdk_configs[0]]
sdk_crash_detection.detect_sdk_crash(event=non_crash_event, configs=configs)
incr.assert_has_calls(
[
call(
"post_process.sdk_crash_monitoring.sdk_event",
tags={"sdk_name": "sentry.cocoa", "sdk_version": "8.2.0"},
),
call(
"post_process.sdk_crash_monitoring.detecting_sdk_crash",
tags={"sdk_name": "sentry.cocoa", "sdk_version": "8.2.0"},
),
],
any_order=True,
)
# Ensure that the counter sdk_crash_detected is not incremented
for call_args in incr.call_args_list:
assert call_args[0][0] != "post_process.sdk_crash_monitoring.sdk_crash_detected"
@django_db_all
@pytest.mark.snuba
@patch("sentry.utils.sdk_crashes.sdk_crash_detection.sdk_crash_detection.sdk_crash_reporter")
@patch("sentry.utils.metrics.incr")
def test_should_not_increment_counters_for_not_supported_sdk(
incr, sdk_crash_reporter, store_event
) -> None:
event_data = get_crash_event()
set_path(event_data, "sdk", "name", value="sentry.coco")
crash_event = store_event(data=event_data)
sdk_configs = build_sdk_configs()
configs = [sdk_configs[0], sdk_configs[0]]
sdk_crash_detection.detect_sdk_crash(event=crash_event, configs=configs)
# Ensure that no counter is incremented
for call_args in incr.call_args_list:
assert call_args[0][0] != "post_process.sdk_crash_monitoring.sdk_error_event"
assert call_args[0][0] != "post_process.sdk_crash_monitoring.detecting_sdk_crash"
assert call_args[0][0] != "post_process.sdk_crash_monitoring.sdk_crash_detected"
@django_db_all
@pytest.mark.snuba
@patch("sentry.utils.sdk_crashes.sdk_crash_detection.sdk_crash_detection.sdk_crash_reporter")
@patch("sentry.utils.metrics.incr")
def test_should_increment_counter_for_non_crash_event(
incr, sdk_crash_reporter, store_event
) -> None:
event_data = get_crash_event(handled=True)
crash_event = store_event(data=event_data)
sdk_configs = build_sdk_configs()
configs = [sdk_configs[0], sdk_configs[0]]
sdk_crash_detection.detect_sdk_crash(event=crash_event, configs=configs)
incr.assert_called_with(
"post_process.sdk_crash_monitoring.sdk_event",
tags={"sdk_name": "sentry.cocoa", "sdk_version": "8.2.0"},
)
# Ensure that no counter is incremented
for call_args in incr.call_args_list:
assert call_args[0][0] != "post_process.sdk_crash_monitoring.detecting_sdk_crash"
assert call_args[0][0] != "post_process.sdk_crash_monitoring.sdk_crash_detected"
@django_db_all
@pytest.mark.snuba
@patch("sentry.utils.sdk_crashes.sdk_crash_detection.sdk_crash_detection.sdk_crash_reporter")
@patch("sentry.utils.metrics.incr")
def test_should_not_increment_counters_already_reported_sdk_crash(
incr, sdk_crash_reporter, store_event
):
event_data = get_crash_event()
set_path(
event_data,
"contexts",
"sdk_crash_detection",
value={"original_project_id": 1234, "original_event_id": 1234},
)
crash_event = store_event(data=event_data)
sdk_configs = build_sdk_configs()
configs = [sdk_configs[0], sdk_configs[0]]
sdk_crash_detection.detect_sdk_crash(event=crash_event, configs=configs)
# Ensure that no counter is incremented
for call_args in incr.call_args_list:
assert call_args[0][0] != "post_process.sdk_crash_monitoring.sdk_event"
assert call_args[0][0] != "post_process.sdk_crash_monitoring.detecting_sdk_crash"
assert call_args[0][0] != "post_process.sdk_crash_monitoring.sdk_crash_detected"
| SDKCrashDetectionTest |
python | pytorch__pytorch | torch/_higher_order_ops/partitioner.py | {
"start": 12529,
"end": 13594
} | class ____:
@staticmethod
def create_partitioned_graph(
fw_fn: Callable,
fw_args: tuple[Union[torch.Tensor, torch.SymInt], ...],
*,
always_recompute_complex_exprs: bool = False,
) -> HopPartitionedGraph:
"""
Inputs:
- fw_fn: the forward function that we'll use to create a joint graph and partition
- fw_args: the flat_args to fw_fn
- always_recompute_complex_exprs: when set to True, the bw_gm will do a re-compute
for inputs that are complex expressions such that the partitioning boundary
only consists of basic symbols and tensors.
Returns a HopPartitionedGraph
"""
from torch._functorch.partitioners import min_cut_rematerialization_partition
joint_graph: HopJointGraph = create_hop_joint_graph(
fw_fn, fw_args, functionalize=True
)
return joint_graph.partition(
min_cut_rematerialization_partition, always_recompute_complex_exprs
)
| HopGraphMinCutPartitioner |
python | plotly__plotly.py | plotly/graph_objs/choroplethmap/colorbar/title/_font.py | {
"start": 233,
"end": 9944
} | class ____(_BaseTraceHierarchyType):
_parent_path_str = "choroplethmap.colorbar.title"
_path_str = "choroplethmap.colorbar.title.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 color bar's title font.
Parameters
----------
arg
dict of properties compatible with this constructor or
an instance of :class:`plotly.graph_objs.choroplethmap.
colorbar.title.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.choroplethmap.colorbar.title.Font
constructor must be a dict or
an instance of :class:`plotly.graph_objs.choroplethmap.colorbar.title.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 | keras-team__keras | keras/src/metrics/confusion_metrics_test.py | {
"start": 28632,
"end": 32127
} | class ____(testing.TestCase):
def test_config(self):
s_obj = metrics.SpecificityAtSensitivity(
0.4,
num_thresholds=100,
class_id=12,
name="specificity_at_sensitivity_1",
)
self.assertEqual(s_obj.name, "specificity_at_sensitivity_1")
self.assertLen(s_obj.variables, 4)
self.assertEqual(s_obj.sensitivity, 0.4)
self.assertEqual(s_obj.num_thresholds, 100)
self.assertEqual(s_obj.class_id, 12)
# Check save and restore config
s_obj2 = metrics.SpecificityAtSensitivity.from_config(
s_obj.get_config()
)
self.assertEqual(s_obj2.name, "specificity_at_sensitivity_1")
self.assertLen(s_obj2.variables, 4)
self.assertEqual(s_obj2.sensitivity, 0.4)
self.assertEqual(s_obj2.num_thresholds, 100)
self.assertEqual(s_obj.class_id, 12)
def test_unweighted_all_correct(self):
s_obj = metrics.SpecificityAtSensitivity(0.7)
inputs = np.random.randint(0, 2, size=(100, 1))
y_pred = np.array(inputs, dtype="float32")
y_true = np.array(inputs)
self.assertAlmostEqual(1, s_obj(y_true, y_pred))
def test_unweighted_high_sensitivity(self):
s_obj = metrics.SpecificityAtSensitivity(1.0)
pred_values = [0.0, 0.1, 0.2, 0.3, 0.4, 0.01, 0.02, 0.25, 0.26, 0.26]
label_values = [0, 0, 0, 0, 0, 1, 1, 1, 1, 1]
y_pred = np.array(pred_values, dtype="float32")
y_true = np.array(label_values)
self.assertAlmostEqual(0.2, s_obj(y_true, y_pred))
def test_unweighted_low_sensitivity(self):
s_obj = metrics.SpecificityAtSensitivity(0.4)
pred_values = [0.0, 0.1, 0.2, 0.3, 0.4, 0.01, 0.02, 0.25, 0.26, 0.26]
label_values = [0, 0, 0, 0, 0, 1, 1, 1, 1, 1]
y_pred = np.array(pred_values, dtype="float32")
y_true = np.array(label_values)
self.assertAlmostEqual(0.6, s_obj(y_true, y_pred))
def test_unweighted_class_id(self):
s_obj = metrics.SpecificityAtSensitivity(0.4, class_id=2)
pred_values = [0.0, 0.1, 0.2, 0.3, 0.4, 0.01, 0.02, 0.25, 0.26, 0.26]
label_values = [0, 0, 0, 0, 0, 2, 2, 2, 2, 2]
y_pred = ops.transpose(np.array([pred_values] * 3))
y_true = ops.one_hot(np.array(label_values), num_classes=3)
self.assertAlmostEqual(0.6, s_obj(y_true, y_pred))
@parameterized.parameters(["bool", "int32", "float32"])
def test_weighted(self, label_dtype):
s_obj = metrics.SpecificityAtSensitivity(0.4)
pred_values = [0.0, 0.1, 0.2, 0.3, 0.4, 0.01, 0.02, 0.25, 0.26, 0.26]
label_values = [0, 0, 0, 0, 0, 1, 1, 1, 1, 1]
weight_values = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
y_pred = np.array(pred_values, dtype="float32")
y_true = ops.cast(label_values, dtype=label_dtype)
weights = np.array(weight_values)
result = s_obj(y_true, y_pred, sample_weight=weights)
self.assertAlmostEqual(0.4, result)
def test_invalid_sensitivity(self):
with self.assertRaisesRegex(
ValueError, r"`sensitivity` must be in the range \[0, 1\]."
):
metrics.SpecificityAtSensitivity(-1)
def test_invalid_num_thresholds(self):
with self.assertRaisesRegex(
ValueError, "Argument `num_thresholds` must be an integer > 0"
):
metrics.SpecificityAtSensitivity(0.4, num_thresholds=-1)
| SpecificityAtSensitivityTest |
python | bokeh__bokeh | src/bokeh/core/property/descriptor_factory.py | {
"start": 3055,
"end": 5110
} | class ____(Generic[T]):
""" Base class for all Bokeh properties.
A Bokeh property really consist of two parts: the familiar "property"
portion, such as ``Int``, ``String``, etc., as well as an associated
Python descriptor that delegates attribute access (e.g. ``range.start``)
to the property instance.
Consider the following class definition:
.. code-block:: python
from bokeh.model import Model
from bokeh.core.properties import Int
class SomeModel(Model):
foo = Int(default=10)
Then we can observe the following:
.. code-block:: python
>>> m = SomeModel()
# The class itself has had a descriptor for 'foo' installed
>>> getattr(SomeModel, 'foo')
<bokeh.core.property.descriptors.PropertyDescriptor at 0x1065ffb38>
# which is used when 'foo' is accessed on instances
>>> m.foo
10
"""
def make_descriptors(self, name: str) -> list[PropertyDescriptor[T]]:
""" Return a list of ``PropertyDescriptor`` instances to install on a
class, in order to delegate attribute access to this property.
Args:
name (str) : the name of the property these descriptors are for
Returns:
list[PropertyDescriptor]
The descriptors returned are collected by the ``MetaHasProps``
metaclass and added to ``HasProps`` subclasses during class creation.
Subclasses of ``PropertyDescriptorFactory`` are responsible for
implementing this function to return descriptors specific to their
needs.
"""
raise NotImplementedError("make_descriptors not implemented")
#-----------------------------------------------------------------------------
# Private API
#-----------------------------------------------------------------------------
#-----------------------------------------------------------------------------
# Code
#-----------------------------------------------------------------------------
| PropertyDescriptorFactory |
python | pypa__warehouse | tests/unit/admin/views/test_users.py | {
"start": 4084,
"end": 6665
} | class ____:
def test_gets_user(self, db_request):
email = EmailFactory.create(primary=True)
user = UserFactory.create(emails=[email])
project = ProjectFactory.create()
roles = sorted([RoleFactory(project=project, user=user, role_name="Owner")])
journal_entries = sorted(
[JournalEntryFactory.create(submitted_by=user) for _ in range(5)],
key=lambda j: j.submitted_date,
reverse=True,
)
db_request.matchdict["username"] = str(user.username)
db_request.POST = NoVars()
breach_service = pretend.stub(get_email_breach_count=lambda count: 0)
db_request.find_service = lambda interface, **kwargs: {
IEmailBreachedService: breach_service,
}[interface]
result = views.user_detail(user, db_request)
assert result["user"] == user
assert result["roles"] == roles
assert result["emails_form"].emails[0].primary.data
assert result["submitted_by_journals"] == journal_entries[:5]
assert result["user_projects"] == [
{
"name": project.name,
"normalized_name": project.normalized_name,
"releases_count": 0,
"total_size": 0,
"lifecycle_status": None,
"role_name": "Owner",
}
]
def test_updates_user(self, db_request):
user = UserFactory.create()
db_request.matchdict["username"] = str(user.username)
db_request.method = "POST"
db_request.POST["name"] = "Jane Doe"
db_request.POST = MultiDict(db_request.POST)
db_request.current_route_path = pretend.call_recorder(
lambda: f"/admin/users/{user.username}/"
)
resp = views.user_detail(user, db_request)
assert resp.status_code == 303
assert resp.location == f"/admin/users/{user.username}/"
assert user.name == "Jane Doe"
def test_user_detail_redirects_actual_name(self, db_request):
user = UserFactory.create(username="wu-tang")
db_request.matchdict["username"] = "Wu-Tang"
db_request.current_route_path = pretend.call_recorder(
lambda username: "/user/the-redirect/"
)
result = views.user_detail(user, db_request)
assert isinstance(result, HTTPMovedPermanently)
assert result.headers["Location"] == "/user/the-redirect/"
assert db_request.current_route_path.calls == [
pretend.call(username=user.username)
]
| TestUserDetail |
python | keras-team__keras | keras/src/ops/numpy.py | {
"start": 107336,
"end": 108450
} | class ____(Operation):
def __init__(self, dtype=None, *, name=None):
super().__init__(name=name)
self.dtype = None if dtype is None else backend.standardize_dtype(dtype)
def call(self, x, fill_value):
return backend.numpy.full_like(x, fill_value, dtype=self.dtype)
def compute_output_spec(self, x, fill_value):
dtype = (
backend.standardize_dtype(x.dtype)
if self.dtype is None
else self.dtype
)
return KerasTensor(x.shape, dtype=dtype)
@keras_export(["keras.ops.full_like", "keras.ops.numpy.full_like"])
def full_like(x, fill_value, dtype=None):
"""Return a full tensor with the same shape and type as the given tensor.
Args:
x: Input tensor.
fill_value: Fill value.
dtype: Overrides data type of the result.
Returns:
Tensor of `fill_value` with the same shape and type as `x`.
"""
if any_symbolic_tensors((x, fill_value)):
return FullLike(dtype=dtype).symbolic_call(x, fill_value)
return backend.numpy.full_like(x, fill_value, dtype=dtype)
| FullLike |
python | django__django | tests/view_tests/tests/test_debug.py | {
"start": 78766,
"end": 79094
} | class ____(SafeExceptionReporterFilter):
cleansed_substitute = "XXXXXXXXXXXXXXXXXXXX"
hidden_settings = _lazy_re_compile("PASS|DATABASE", flags=re.I)
@override_settings(
ROOT_URLCONF="view_tests.urls",
DEFAULT_EXCEPTION_REPORTER_FILTER="%s.CustomExceptionReporterFilter" % __name__,
)
| CustomExceptionReporterFilter |
python | Textualize__textual | tests/snapshot_tests/snapshot_apps/progress_gradient.py | {
"start": 120,
"end": 715
} | class ____(App[None]):
def compose(self) -> ComposeResult:
gradient = Gradient.from_colors(
"#881177",
"#aa3355",
"#cc6666",
"#ee9944",
"#eedd00",
"#99dd55",
"#44dd88",
"#22ccbb",
"#00bbcc",
"#0099cc",
"#3366bb",
"#663399",
)
yield ProgressBar(total=100, gradient=gradient)
def on_mount(self) -> None:
self.query_one(ProgressBar).update(progress=50)
if __name__ == "__main__":
ProgressApp().run()
| ProgressApp |
python | allegroai__clearml | clearml/backend_api/services/v2_20/auth.py | {
"start": 15603,
"end": 18944
} | class ____(Response):
"""
Response of auth.get_credentials endpoint.
:param credentials: List of credentials, each with an empty secret field.
:type credentials: Sequence[CredentialKey]
:param additional_credentials: The user credentials for the user tenant
companies, each with an empty secret field.
:type additional_credentials: dict
"""
_service = "auth"
_action = "get_credentials"
_version = "2.20"
_schema = {
"definitions": {
"credential_key": {
"properties": {
"access_key": {
"description": "Credentials access key",
"type": ["string", "null"],
},
"label": {
"description": "Optional credentials label",
"type": ["string", "null"],
},
"last_used": {
"description": "",
"format": "date-time",
"type": ["string", "null"],
},
"last_used_from": {"description": "", "type": ["string", "null"]},
},
"type": "object",
}
},
"properties": {
"additional_credentials": {
"additionalProperties": True,
"description": "The user credentials for the user tenant companies, each with an empty secret field.",
"type": ["object", "null"],
},
"credentials": {
"description": "List of credentials, each with an empty secret field.",
"items": {"$ref": "#/definitions/credential_key"},
"type": ["array", "null"],
},
},
"type": "object",
}
def __init__(
self, credentials: Optional[List[Any]] = None, additional_credentials: Optional[dict] = None, **kwargs: Any
) -> None:
super(GetCredentialsResponse, self).__init__(**kwargs)
self.credentials = credentials
self.additional_credentials = additional_credentials
@schema_property("credentials")
def credentials(self) -> Optional[List[Any]]:
return self._property_credentials
@credentials.setter
def credentials(self, value: Optional[List[Any]]) -> None:
if value is None:
self._property_credentials = None
return
self.assert_isinstance(value, "credentials", (list, tuple))
if any((isinstance(v, dict) for v in value)):
value = [CredentialKey.from_dict(v) if isinstance(v, dict) else v for v in value]
else:
self.assert_isinstance(value, "credentials", CredentialKey, is_array=True)
self._property_credentials = value
@schema_property("additional_credentials")
def additional_credentials(self) -> Optional[dict]:
return self._property_additional_credentials
@additional_credentials.setter
def additional_credentials(self, value: Optional[dict]) -> None:
if value is None:
self._property_additional_credentials = None
return
self.assert_isinstance(value, "additional_credentials", (dict,))
self._property_additional_credentials = value
| GetCredentialsResponse |
python | pydata__xarray | xarray/tests/__init__.py | {
"start": 9549,
"end": 9620
} | class ____:
def __getitem__(self, key):
return key
| ReturnItem |
python | django__django | tests/utils_tests/test_archive.py | {
"start": 3053,
"end": 4652
} | class ____(SimpleTestCase):
def test_extract_function_traversal(self):
archives_dir = os.path.join(os.path.dirname(__file__), "traversal_archives")
tests = [
("traversal.tar", ".."),
("traversal_absolute.tar", "/tmp/evil.py"),
]
if sys.platform == "win32":
tests += [
("traversal_disk_win.tar", "d:evil.py"),
("traversal_disk_win.zip", "d:evil.py"),
]
msg = "Archive contains invalid path: '%s'"
for entry, invalid_path in tests:
with self.subTest(entry), tempfile.TemporaryDirectory() as tmpdir:
with self.assertRaisesMessage(SuspiciousOperation, msg % invalid_path):
archive.extract(os.path.join(archives_dir, entry), tmpdir)
def test_extract_function_traversal_startswith(self):
with tempfile.TemporaryDirectory() as tmpdir:
base = os.path.abspath(tmpdir)
tarfile_handle = tempfile.NamedTemporaryFile(suffix=".zip", delete=False)
tar_path = tarfile_handle.name
tarfile_handle.close()
self.addCleanup(os.remove, tar_path)
malicious_member = os.path.join(base + "abc", "evil.txt")
with zipfile.ZipFile(tar_path, "w") as zf:
zf.writestr(malicious_member, "evil\n")
zf.writestr("test.txt", "data\n")
with self.assertRaisesMessage(
SuspiciousOperation, "Archive contains invalid path"
):
archive.extract(tar_path, base)
| TestArchiveInvalid |
python | langchain-ai__langchain | libs/partners/groq/tests/integration_tests/test_standard.py | {
"start": 426,
"end": 2822
} | class ____(ChatModelIntegrationTests):
@property
def chat_model_class(self) -> type[BaseChatModel]:
return ChatGroq
@property
def chat_model_params(self) -> dict:
return {"model": "llama-3.3-70b-versatile", "rate_limiter": rate_limiter}
@pytest.mark.xfail(reason="Not yet implemented.")
def test_tool_message_histories_list_content(
self, model: BaseChatModel, my_adder_tool: BaseTool
) -> None:
super().test_tool_message_histories_list_content(model, my_adder_tool)
@pytest.mark.xfail(
reason="Groq models have inconsistent tool calling performance. See: "
"https://github.com/langchain-ai/langchain/discussions/19990"
)
def test_bind_runnables_as_tools(self, model: BaseChatModel) -> None:
super().test_bind_runnables_as_tools(model)
@pytest.mark.xfail(reason="Retry flaky tool calling behavior")
@pytest.mark.retry(count=3, delay=1)
def test_tool_calling(self, model: BaseChatModel) -> None:
super().test_tool_calling(model)
@pytest.mark.xfail(reason="Retry flaky tool calling behavior")
@pytest.mark.retry(count=3, delay=1)
async def test_tool_calling_async(self, model: BaseChatModel) -> None:
await super().test_tool_calling_async(model)
@pytest.mark.xfail(reason="Retry flaky tool calling behavior")
@pytest.mark.retry(count=3, delay=1)
def test_tool_calling_with_no_arguments(self, model: BaseChatModel) -> None:
super().test_tool_calling_with_no_arguments(model)
@property
def supports_json_mode(self) -> bool:
return True
@pytest.mark.parametrize("schema_type", ["pydantic", "typeddict", "json_schema"])
def test_json_schema(
schema_type: Literal["pydantic", "typeddict", "json_schema"],
) -> None:
class JsonSchemaTests(ChatModelIntegrationTests):
@property
def chat_model_class(self) -> type[ChatGroq]:
return ChatGroq
@property
def chat_model_params(self) -> dict:
return {"model": "openai/gpt-oss-120b", "rate_limiter": rate_limiter}
@property
def structured_output_kwargs(self) -> dict:
return {"method": "json_schema"}
test_instance = JsonSchemaTests()
model = test_instance.chat_model_class(**test_instance.chat_model_params)
JsonSchemaTests().test_structured_output(model, schema_type)
| TestGroq |
python | tensorflow__tensorflow | tensorflow/python/ops/distributions/distribution.py | {
"start": 7343,
"end": 9682
} | class ____:
"""Instances of this class represent how sampling is reparameterized.
Two static instances exist in the distributions library, signifying
one of two possible properties for samples from a distribution:
`FULLY_REPARAMETERIZED`: Samples from the distribution are fully
reparameterized, and straight-through gradients are supported.
`NOT_REPARAMETERIZED`: Samples from the distribution are not fully
reparameterized, and straight-through gradients are either partially
unsupported or are not supported at all. In this case, for purposes of
e.g. RL or variational inference, it is generally safest to wrap the
sample results in a `stop_gradients` call and use policy
gradients / surrogate loss instead.
"""
@deprecation.deprecated(
"2019-01-01",
"The TensorFlow Distributions library has moved to "
"TensorFlow Probability "
"(https://github.com/tensorflow/probability). You "
"should update all references to use `tfp.distributions` "
"instead of `tf.distributions`.",
warn_once=True)
def __init__(self, rep_type):
self._rep_type = rep_type
def __repr__(self):
return "<Reparameterization Type: %s>" % self._rep_type
def __eq__(self, other):
"""Determine if this `ReparameterizationType` is equal to another.
Since ReparameterizationType instances are constant static global
instances, equality checks if two instances' id() values are equal.
Args:
other: Object to compare against.
Returns:
`self is other`.
"""
return self is other
# Fully reparameterized distribution: samples from a fully
# reparameterized distribution support straight-through gradients with
# respect to all parameters.
FULLY_REPARAMETERIZED = ReparameterizationType("FULLY_REPARAMETERIZED")
tf_export(v1=["distributions.FULLY_REPARAMETERIZED"]).export_constant(
__name__, "FULLY_REPARAMETERIZED")
# Not reparameterized distribution: samples from a non-
# reparameterized distribution do not support straight-through gradients for
# at least some of the parameters.
NOT_REPARAMETERIZED = ReparameterizationType("NOT_REPARAMETERIZED")
tf_export(v1=["distributions.NOT_REPARAMETERIZED"]).export_constant(
__name__, "NOT_REPARAMETERIZED")
@tf_export(v1=["distributions.Distribution"])
| ReparameterizationType |
python | kamyu104__LeetCode-Solutions | Python/prison-cells-after-n-days.py | {
"start": 29,
"end": 424
} | class ____(object):
def prisonAfterNDays(self, cells, N):
"""
:type cells: List[int]
:type N: int
:rtype: List[int]
"""
N -= max(N-1, 0) // 14 * 14 # 14 is got from Solution2
for i in xrange(N):
cells = [0] + [cells[i-1] ^ cells[i+1] ^ 1 for i in xrange(1, 7)] + [0]
return cells
# Time: O(1)
# Space: O(1)
| Solution |
python | pytorch__pytorch | torch/_subclasses/fake_tensor.py | {
"start": 24223,
"end": 39589
} | class ____(Tensor):
"""
Meta tensors give you the ability to run PyTorch code without having to
actually do computation through tensors allocated on a `meta` device.
Because the device is `meta`, meta tensors do not model device propagation.
FakeTensor extends MetaTensors to also carry an additional `fake_device`
which tracks devices that would have been used.
"""
fake_device: torch.device
fake_mode: FakeTensorMode
constant: Optional[Tensor]
real_tensor: Optional[Tensor]
# TODO: Generalize this as needed, e.g., into a trie of memos, if
# you do something like x[0].item() (x[0] is fresh each time, so
# memo mechanism here won't work)
nonzero_memo = SymNumberMemoDescriptor()
item_memo = SymNumberMemoDescriptor()
unique_memo = SymNumberMemoDescriptor()
unique_consecutive_memo = SymNumberMemoDescriptor()
# We expect nested_int_memo to be None when an offsets is a graph
# intermediate, or an input that has never been associated with a
# nested int.
nested_int_memo = SymNumberMemoDescriptor(is_nested_int=True)
# FakeTensor doesn't fully emulate the original tensor's Python type
# and dispatch key set, therefore sometimes we want to track them
# separately.
pytype: Optional[type[Tensor]]
dispatch_keys: Optional[torch.DispatchKeySet]
# Indicates to our torch_dispatch dispatching infra that
# this is an "infra" mode with lower dispatching precedence.
_mode_key = torch._C._TorchDispatchModeKey.FAKE
@property
# pyrefly: ignore [bad-override]
def device(self) -> torch.device:
if self.fake_mode.in_kernel_invocation:
return torch.device("meta")
else:
return self.fake_device
@device.setter
def device(self, _: torch.device) -> None:
raise NotImplementedError
# Note: [Fake Tensor Dispatch Keys]
# In order to model the behavior of device-specific autocast
# and autograd logic, we update the dispatch keys of FakeTensors
# to reflect their fake device. This includes the BackendComponent
# (DispatchKey::Meta -> DispatchKey::CUDA), and also the BackendComponent
# related Autocast and Autograd keys. __torch_dispatch__ sits below
# Autocast and Autograd, and is only invoked when we are at the
# kernel for the BackendComponent. Then, we add Meta to the
# thread-local dispatch include set to hit the meta kernel
# instead of the kernel of the BackendComponent for the fake device.
# The `device_for_backend_keys` does that below
# NOTE: this probably will not do the right thing for backends
# that have dispatch keys which are higher than the "meta" key:
# https://github.com/pytorch/pytorch/blob/main/c10/core/DispatchKey.h#L189
# We don't support named tensors; graph break
@property
# pyrefly: ignore [bad-override]
def names(self) -> list[str]:
raise UnsupportedFakeTensorException(
"torch.compile doesn't support named tensors"
)
@names.setter
def names(self, _: list[str]) -> None:
raise NotImplementedError
@staticmethod
def __new__(
cls,
fake_mode: FakeTensorMode,
elem: Tensor,
device: torch.device,
constant: Optional[Tensor] = None,
real_tensor: Optional[Tensor] = None,
pytype: Optional[type[Tensor]] = None,
dispatch_keys: Optional[torch.DispatchKeySet] = None,
) -> Self:
self = Tensor._make_subclass(
cls,
elem,
elem.requires_grad,
dispatch_device=True,
device_for_backend_keys=device,
)
if not fake_mode._allow_unsafe_data_ptr_access:
torch._C._set_throw_on_mutable_data_ptr(self)
else:
torch._C._set_warn_deprecated_on_mutable_data_ptr(self)
assert elem.device.type == "meta", elem.device.type
device = device if isinstance(device, torch.device) else torch.device(device)
# NB: it is fine, if a little confusing, for device to be meta
# (we are faking a meta tensor in that case). However, it often
# indicates some sort of confusion (e.g., you accidentally passed
# in a meta tensor when you should have passed in the real tensor).
# So by default we disallow meta, and if you are working in a situation
# where it is helpful (e.g., crossref testing) you can turn it back
# on
if not fake_mode.allow_meta:
assert device.type != "meta"
# normalize device.
if device.type in ["cuda", "xpu"]:
init_gpu_context(device)
if (
device.type
in [
"cuda",
"hpu",
"xpu",
"mps",
"mtia",
torch._C._get_privateuse1_backend_name(),
]
and device.index is None
):
if device.type != "mps" and getattr(torch, device.type).is_initialized():
device = torch.device(
f"{device.type}:{getattr(torch, device.type).current_device()}"
)
else:
device = torch.device(f"{device.type}:0")
# pyrefly: ignore [read-only]
self.fake_device = device
self.fake_mode = fake_mode
self.constant = constant
self.pytype = pytype
self.dispatch_keys = dispatch_keys
assert not isinstance(real_tensor, FakeTensor)
self.real_tensor = real_tensor
self.nonzero_memo = None
self.item_memo = None
self.unique_memo = None
self.unique_consecutive_memo = None
self.nested_int_memo = None
if FakeTensorConfig.debug:
self._debug_trace = CapturedTraceback.extract() # type: ignore[attr-defined]
return self
# In some circumstances, a conventional Tensor constructor
# will get rewritten to call into FakeTensor. We must provide an
# __init__ method that can accept the Python interpreters initialization
# in such a situation; we must also be able to handle direct fake
# tensor construction via FakeTensor().
#
# In particular, the __init__ call will look funny in the following case:
#
# with FakeTensorMode():
# x = Tensor([1, 2, 3])
#
# this desugars into:
#
# with FakeTensorMode():
# x = Tensor.__new__([1, 2, 3])
# # NB: x is a fake tensor, because of the mode!
# x.__init__([1, 2, 3]) # not the normal fake tensor args!
#
def __init__(self, *args: object, **kwargs: object) -> None:
super().__init__()
if (
torch.compiler.is_exporting()
and torch._export.config.detect_non_strict_fake_tensor_leaks
):
fake_tensor_tls.non_strict_export_fake_tensor_tracker.add(self)
@staticmethod
def from_tensor(t: Tensor, fake_mode: FakeTensorMode) -> FakeTensor:
return fake_mode.from_tensor(t)
@classmethod
@count
def __torch_dispatch__( # type: ignore[override] # TODO
cls,
func: OpOverload,
types: Sequence[type],
args: Sequence[object] = (),
kwargs: Mapping[str, object] = immutable_dict(),
) -> object:
# need to handle here to avoid infinite recursion
# see [in_kernel_invocation]
if func is torch.ops.prim.device.default:
assert len(args) == 1 and isinstance(args[0], FakeTensor)
if args[0].fake_mode.in_kernel_invocation:
return torch.device("meta")
else:
return args[0].fake_device
# this handler must be done inside FakeTensor subclass, not mode, because
# we can end up dispatching here when we have a fake tensor with
# symbolic sizes running under in_kernel_invocation_manager.
# The subclass is asked to handle this query because size (not
# sym_size) was called, but we are unable to serve it directly because
# there are symbolic sizes in the class. The use of
# in_kernel_invocation_manager means it's incorrect to activate a
# mode to actually handle this (this caused
# https://github.com/pytorch/pytorch/issues/122772).
if handler := _DISPATCH_META_HANDLERS.get(func):
return handler(args)
# Because fake mode can return NotImplemented (if it sees a subclass
# it doesn't know how to deal with), this test here is important
# because the next dispatch after a fake mode will attempt to use
# subclasses of tensors to dispatch, and any FakeTensor arguments
# will be considered eligible.
unrecognized_types = [
t for t in types if not issubclass(t, FakeTensor) and t is not Tensor
]
if unrecognized_types:
not_implemented_log.debug(
"FakeTensor unrecognized subclass(es): %s", unrecognized_types
)
return NotImplemented
fake_mode = None
for arg in pytree.arg_tree_leaves(*args, **kwargs):
if isinstance(arg, FakeTensor):
fake_mode = arg.fake_mode
break
assert fake_mode is not None
# If the fake mode is already active, don't try to reapply it!
# NotImplemented is the right thing to return here, because the
# typical situation this can occur is if ProxyTensorMode returned a
# NotImplemented because of a not implemented subclass; we may have
# unluckily attempted to hit FakeTensor's dispatch first,
# NotImplemented lets us keep chaining until we find the actual
# subclass
maybe_cur_fake_mode = torch._C._get_dispatch_mode(
torch._C._TorchDispatchModeKey.FAKE
)
if maybe_cur_fake_mode:
not_implemented_log.debug(
"FakeTensor mode already active: %s in %s",
fake_mode,
maybe_cur_fake_mode,
)
return NotImplemented
assert not fake_mode.in_kernel_invocation
with fake_mode:
return func(*args, **kwargs)
@staticmethod
def _find_common_device(
func: OpOverload, flat_args: Sequence[object]
) -> tuple[torch.device, bool]:
# Returns: (common_device, has_scalar_only_inputs)
# cpu - zero-dim tensors can be called in cuda kernels,
# so overwrite the common_device if it the only existing
# device comes from a cpu zero-dim tensor
common_device = None
has_scalar_only_inputs = False
is_cpu_zero_dim = None
# list of ops which can have args(tensor/tensorList) in mixed device
mixed_device_fns = ordered_set(
aten._foreach_copy.default,
)
# list of ops not using zero dim cpu tensor logic to align with the eager mode.
bypass_zero_dim_cpu_tensor_check_ops = ordered_set(
aten.nextafter.default,
)
def check_cpu_device(device: torch.device) -> bool:
return device.type == "cpu"
def cpu_zero_dim(t: Tensor) -> bool:
return check_cpu_device(t.device) and t.dim() == 0
def merge_devices(t: object) -> None:
nonlocal common_device
nonlocal is_cpu_zero_dim
if not isinstance(t, FakeTensor):
return
if common_device is None:
common_device = t.device
is_cpu_zero_dim = cpu_zero_dim(t)
return
t_is_cpu_zero_dim = cpu_zero_dim(t)
if t.device == common_device:
if is_cpu_zero_dim:
is_cpu_zero_dim = t_is_cpu_zero_dim
return
is_bypass_zero_dim_cpu_tensor_check_op = (
func in bypass_zero_dim_cpu_tensor_check_ops
)
# mismatching devices !
# if current tensor is cpu 0 dim, defer to existing device
if t_is_cpu_zero_dim and not is_bypass_zero_dim_cpu_tensor_check_op:
return
# current device is from cpu 0 dim tensor, overwrite
if is_cpu_zero_dim and not is_bypass_zero_dim_cpu_tensor_check_op:
common_device = t.device
is_cpu_zero_dim = t_is_cpu_zero_dim
return
# if still device mismatches we will check ops which can work
# on different devices for ex. _foreach_copy, and one of the
# device must be cpu in this case we will return from here without
# throwing an error
if func in mixed_device_fns:
if any(map(check_cpu_device, (common_device, t.device))):
return
# if prefer_device_type is set, prefer that device type over others
prefer_device_type = torch._functorch.config.fake_tensor_prefer_device_type
if prefer_device_type is not None:
common_has_preferred = prefer_device_type in common_device.type
t_has_preferred = prefer_device_type in t.device.type
if not common_has_preferred and t_has_preferred:
# Switch to the preferred device type
common_device = t.device
is_cpu_zero_dim = t_is_cpu_zero_dim
return
elif common_has_preferred and not t_has_preferred:
# Keep the existing preferred device type
return
# mismatching devices of non-zero dim tensors, throw
# This might be valid behavior and need to be explicitly modeled, e.g. reshape_as
raise RuntimeError(
f"Unhandled FakeTensor Device Propagation for {func}, found two different devices {common_device}, {t.device}"
)
for arg in flat_args:
merge_devices(arg)
# some functions that allow Python numbers to bind to Tensors
# if we have failed to find a device, and we're running one of these operators,
# we must have scalar only inputs
if should_allow_numbers_as_tensors(func) and common_device is None:
# ops with scalar only inputs always have result on cpu
has_scalar_only_inputs = True
common_device = torch.device("cpu")
assert common_device is not None, f"Could not find common device for {func}"
return common_device, has_scalar_only_inputs
def get_nested_int(
self,
*,
coeff: Union[int, torch.SymInt] = 1,
) -> torch.SymInt:
if self.nested_int_memo is None:
self.nested_int_memo = self.fake_mode.create_symbolic_nested_int(
nt_tensor_id=None
)
assert isinstance(self.nested_int_memo, torch.SymInt)
return self.nested_int_memo * coeff
# Similar to FunctionalTensor.tolist
def tolist(self) -> Any:
if self.dim() == 0:
return self.item()
elif self.dim() == 1:
return [elem.item() for elem in self]
else:
return [elem.tolist() for elem in self]
_MetadataIntLike = Union[IntLikeType, "_PySymInputStub", "_SymIntOutputStub"]
@dataclass(slots=True)
| FakeTensor |
python | getsentry__sentry | src/sentry/utils/snuba.py | {
"start": 14961,
"end": 15152
} | class ____(QueryExecutionError):
"""
Exception raised when a query is rejected due to too many simultaneous
queries being performed on the database.
"""
| QueryTooManySimultaneous |
python | dagster-io__dagster | python_modules/dagster-graphql/dagster_graphql/schema/asset_graph.py | {
"start": 6434,
"end": 7530
} | class ____(graphene.ObjectType):
class Meta:
name = "AssetDependency"
asset = graphene.NonNull("dagster_graphql.schema.asset_graph.GrapheneAssetNode")
partitionMapping = graphene.Field(GraphenePartitionMapping)
def __init__(
self,
*,
asset_key: AssetKey,
partition_mapping: Optional[PartitionMapping] = None,
):
self._asset_key = check.inst_param(asset_key, "asset_key", AssetKey)
self._partition_mapping = check.opt_inst_param(
partition_mapping, "partition_mapping", PartitionMapping
)
super().__init__()
def resolve_asset(self, graphene_info: ResolveInfo):
remote_node = graphene_info.context.asset_graph.get(self._asset_key)
return GrapheneAssetNode(
remote_node=remote_node,
)
def resolve_partitionMapping(
self, graphene_info: ResolveInfo
) -> Optional[GraphenePartitionMapping]:
if self._partition_mapping:
return GraphenePartitionMapping(self._partition_mapping)
return None
| GrapheneAssetDependency |
python | PyCQA__pylint | pylint/reporters/ureports/nodes.py | {
"start": 2646,
"end": 2925
} | class ____(VNode):
"""A text portion.
attributes :
* data : the text value as an encoded or unicode string
"""
def __init__(self, data: str, escaped: bool = True) -> None:
super().__init__()
self.escaped = escaped
self.data = data
| Text |
python | keras-team__keras | keras/src/layers/convolutional/conv3d.py | {
"start": 179,
"end": 5918
} | class ____(BaseConv):
"""3D convolution layer.
This layer creates a convolution kernel that is convolved with the layer
input over a 3D spatial (or temporal) dimension (width,height and depth) to
produce a tensor of outputs. If `use_bias` is True, a bias vector is created
and added to the outputs. Finally, if `activation` is not `None`, it is
applied to the outputs as well.
Args:
filters: int, the dimension of the output space (the number of filters
in the convolution).
kernel_size: int or tuple/list of 3 integer, specifying the size of the
convolution window.
strides: int or tuple/list of 3 integer, specifying the stride length
of the convolution. `strides > 1` is incompatible with
`dilation_rate > 1`.
padding: string, either `"valid"` or `"same"` (case-insensitive).
`"valid"` means no padding. `"same"` results in padding evenly to
the left/right or up/down of the input. When `padding="same"` and
`strides=1`, the output has the same size as the input.
data_format: string, either `"channels_last"` or `"channels_first"`.
The ordering of the dimensions in the inputs. `"channels_last"`
corresponds to inputs with shape
`(batch_size, spatial_dim1, spatial_dim2, spatial_dim3, channels)`
while `"channels_first"` corresponds to inputs with shape
`(batch_size, channels, spatial_dim1, spatial_dim2, spatial_dim3)`.
It defaults to the `image_data_format` value found in your Keras
config file at `~/.keras/keras.json`. If you never set it, then it
will be `"channels_last"`.
dilation_rate: int or tuple/list of 3 integers, specifying the dilation
rate to use for dilated convolution.
groups: A positive int specifying the number of groups in which the
input is split along the channel axis. Each group is convolved
separately with `filters // groups` filters. The output is the
concatenation of all the `groups` results along the channel axis.
Input channels and `filters` must both be divisible by `groups`.
activation: Activation function. If `None`, no activation is applied.
use_bias: bool, if `True`, bias will be added to the output.
kernel_initializer: Initializer for the convolution kernel. If `None`,
the default initializer (`"glorot_uniform"`) will be used.
bias_initializer: Initializer for the bias vector. If `None`, the
default initializer (`"zeros"`) will be used.
kernel_regularizer: Optional regularizer for the convolution kernel.
bias_regularizer: Optional regularizer for the bias vector.
activity_regularizer: Optional regularizer function for the output.
kernel_constraint: Optional projection function to be applied to the
kernel after being updated by an `Optimizer` (e.g. used to implement
norm constraints or value constraints for layer weights). The
function must take as input the unprojected variable and must return
the projected variable (which must have the same shape). Constraints
are not safe to use when doing asynchronous distributed training.
bias_constraint: Optional projection function to be applied to the
bias after being updated by an `Optimizer`.
Input shape:
- If `data_format="channels_last"`:
5D tensor with shape:
`(batch_size, spatial_dim1, spatial_dim2, spatial_dim3, channels)`
- If `data_format="channels_first"`:
5D tensor with shape:
`(batch_size, channels, spatial_dim1, spatial_dim2, spatial_dim3)`
Output shape:
- If `data_format="channels_last"`:
5D tensor with shape:
`(batch_size, new_spatial_dim1, new_spatial_dim2, new_spatial_dim3,
filters)`
- If `data_format="channels_first"`:
5D tensor with shape:
`(batch_size, filters, new_spatial_dim1, new_spatial_dim2,
new_spatial_dim3)`
Returns:
A 5D tensor representing `activation(conv3d(inputs, kernel) + bias)`.
Raises:
ValueError: when both `strides > 1` and `dilation_rate > 1`.
Example:
>>> x = np.random.rand(4, 10, 10, 10, 128)
>>> y = keras.layers.Conv3D(32, 3, activation='relu')(x)
>>> print(y.shape)
(4, 8, 8, 8, 32)
"""
def __init__(
self,
filters,
kernel_size,
strides=(1, 1, 1),
padding="valid",
data_format=None,
dilation_rate=(1, 1, 1),
groups=1,
activation=None,
use_bias=True,
kernel_initializer="glorot_uniform",
bias_initializer="zeros",
kernel_regularizer=None,
bias_regularizer=None,
activity_regularizer=None,
kernel_constraint=None,
bias_constraint=None,
**kwargs,
):
super().__init__(
rank=3,
filters=filters,
kernel_size=kernel_size,
strides=strides,
padding=padding,
data_format=data_format,
dilation_rate=dilation_rate,
groups=groups,
activation=activation,
use_bias=use_bias,
kernel_initializer=kernel_initializer,
bias_initializer=bias_initializer,
kernel_regularizer=kernel_regularizer,
bias_regularizer=bias_regularizer,
activity_regularizer=activity_regularizer,
kernel_constraint=kernel_constraint,
bias_constraint=bias_constraint,
**kwargs,
)
| Conv3D |
python | walkccc__LeetCode | solutions/490. The Maze/490-2.py | {
"start": 0,
"end": 733
} | class ____:
def hasPath(
self,
maze: list[list[int]],
start: list[int],
destination: list[int],
) -> bool:
DIRS = ((0, 1), (1, 0), (0, -1), (-1, 0))
m = len(maze)
n = len(maze[0])
seen = set()
def isValid(x: int, y: int) -> bool:
return 0 <= x < m and 0 <= y < n and maze[x][y] == 0
def dfs(i: int, j: int) -> bool:
if [i, j] == destination:
return True
if (i, j) in seen:
return False
seen.add((i, j))
for dx, dy in DIRS:
x = i
y = j
while isValid(x + dx, y + dy):
x += dx
y += dy
if dfs(x, y):
return True
return False
return dfs(start[0], start[1])
| Solution |
python | nedbat__coveragepy | tests/test_oddball.py | {
"start": 5271,
"end": 8852
} | class ____(CoverageTest):
"""Attempt the impossible: test that memory doesn't leak.
Note: this test is truly unusual, and has had a colorful history. See
for example: https://github.com/coveragepy/coveragepy/issues/186
It may still fail occasionally, especially on PyPy.
"""
@pytest.mark.flaky
@pytest.mark.skipif(not testenv.C_TRACER, reason="Only the C tracer has refcounting issues")
def test_for_leaks(self) -> None:
# Our original bad memory leak only happened on line numbers > 255, so
# make a code object with more lines than that. Ugly string mumbo
# jumbo to get 300 blank lines at the beginning..
code = (
"""\
# blank line\n"""
* 300
+ """\
def once(x): # line 301
if x % 100 == 0:
raise Exception("100!")
elif x % 2:
return 10
else: # line 306
return 11
i = 0 # Portable loop without alloc'ing memory.
while i < ITERS:
try:
once(i)
except:
pass
i += 1 # line 315
"""
)
lines = list(range(301, 315))
lines.remove(306) # Line 306 is the "else".
# This is a non-deterministic test, so try it a few times, and fail it
# only if it predominantly fails.
fails = 0
for _ in range(10):
ram_0 = osinfo.process_ram()
self.check_coverage(code.replace("ITERS", "10"), lines=lines, missing="")
ram_10 = osinfo.process_ram()
self.check_coverage(code.replace("ITERS", "10000"), lines=lines, missing="")
ram_10k = osinfo.process_ram()
# Running the code 10k times shouldn't grow the ram much more than
# running it 10 times.
ram_growth = (ram_10k - ram_10) - (ram_10 - ram_0)
if ram_growth > 100000:
fails += 1 # pragma: only failure
if fails > 8:
pytest.fail("RAM grew by %d" % (ram_growth)) # pragma: only failure
@pytest.mark.skipif(
not testenv.C_TRACER,
reason="Only the C tracer has refcounting issues",
# In fact, sysmon explicitly holds onto all code objects,
# so this will definitely fail with sysmon.
)
@pytest.mark.skipif(
env.PYVERSION[:2] == (3, 13) and not env.GIL,
reason="3.13t never frees code objects: https://github.com/python/cpython/pull/131989",
)
@pytest.mark.parametrize("branch", [False, True])
def test_eval_codeobject_leak(self, branch: bool) -> None:
# https://github.com/coveragepy/coveragepy/issues/1924
code = """\
for i in range(10_000):
r = eval("'a' + '1'")
assert r == 'a1'
"""
# Looking for leaks is hard. We consider the leak fixed if at least
# one of our loops only increased the footprint by a small amount.
base = osinfo.process_ram()
deltas = []
for _ in range(30):
self.check_coverage(code, lines=[1, 2, 3], missing="", branch=branch)
now = osinfo.process_ram()
deltas.append(now - base)
print(f"Mem delta: {(now - base) // 1024}")
base = now
assert any(d < 50 * 1024 for d in deltas)
| MemoryLeakTest |
python | facebook__pyre-check | client/language_server/protocol.py | {
"start": 1468,
"end": 5571
} | class ____(Exception):
pass
async def _read_headers(
input_channel: connections.AsyncTextReader,
) -> List[str]:
headers = []
header = await input_channel.read_until("\r\n")
while header != "\r\n":
headers.append(header)
header = await input_channel.read_until("\r\n")
return headers
def _get_content_length(headers: Iterable[str]) -> int:
try:
parts: List[str] = []
for header in headers:
parts = [part.strip().lower() for part in header.split(":", maxsplit=1)]
if len(parts) <= 1:
continue
if parts[0] == "content-length":
return int(parts[1])
raise json_rpc.ParseError(f"Failed to find content length header from {parts}")
except ValueError as error:
raise json_rpc.ParseError(
"Cannot parse content length into integer."
) from error
async def _try_read_json_rpc(
input_channel: connections.AsyncTextReader,
) -> json_rpc.Request:
"""
Asynchronously read a JSON-RPC request from the given input channel.
May raise `json_rpc.ParseError`, `json_rpc.InvalidRequestError`,
`json_prc.InvalidParameterError`, and `ReadChannelClosedError`.
This is expected to throw errors if the editor sends empty requests,
most callsites should use `read_nonempty_json_rpc_request`
"""
try:
headers = await _read_headers(input_channel)
content_length = _get_content_length(headers)
payload = await input_channel.read_exactly(content_length)
return json_rpc.Request.from_string(payload)
except asyncio.IncompleteReadError as error:
if len(error.partial) == 0:
raise ReadChannelClosedError(
"Trying to read from a closed input channel"
) from None
else:
raise json_rpc.ParseError(str(error)) from None
async def read_json_rpc(
input_channel: connections.AsyncTextReader,
) -> json_rpc.Request:
"""
Read a JSON-RPC request from the given input channel. Ignores
any requests that are missing the "method" field, which is needed
because VSCode often sends empty requests.
May raise `json_rpc.ParseError`, `json_rpc.InvalidRequestError`,
`json_prc.InvalidParameterError`, and `ReadChannelClosedError`.
"""
while True:
try:
return await _try_read_json_rpc(input_channel)
except json_rpc.MissingMethodFieldInRequestError:
continue
def json_rpc_payload(message: json_rpc.JSONRPC) -> str:
payload = message.serialize()
return f"Content-Length: {len(payload)}\r\n\r\n{payload}"
async def write_json_rpc(
output_channel: connections.AsyncTextWriter,
response: json_rpc.JSONRPC,
) -> None:
"""
Asynchronously write a JSON-RPC response to the given output channel.
"""
await output_channel.write(json_rpc_payload(response))
async def write_json_rpc_ignore_connection_error(
output_channel: connections.AsyncTextWriter,
response: json_rpc.JSONRPC,
) -> None:
"""
Asynchronously write a JSON-RPC response to the given output channel, and ignore
any `ConnectionError` that occurred.
"""
try:
await write_json_rpc(output_channel, response)
except ConnectionError as error:
LOG.info(f"Ignoring connection error while writing JSON RPC. Error: {error}")
def _parse_parameters(parameters: json_rpc.Parameters, target: Type[T]) -> T:
"""
Parse the given JSON-RPC parameters into specified LSP parameters.
Raise `json_rpc.InvalidRequestError`on parsing failure.
"""
if not isinstance(parameters, json_rpc.ByNameParameters):
raise json_rpc.InvalidRequestError(
"Parameters for LSP requests must be passed by name"
)
try:
# pyre-ignore[6, 7]: Imprecise typing of `load()`
return target.cached_schema().load(parameters.values)
except (KeyError, ValueError, dataclasses_json.mm.ValidationError) as error:
raise json_rpc.InvalidRequestError(str(error)) from error
| ReadChannelClosedError |
python | gevent__gevent | src/greentest/3.10/test_socket.py | {
"start": 120746,
"end": 121947
} | class ____(RecvmsgGenericTests):
# Tests for recvmsg() which can use any socket type.
def testRecvmsgBadArgs(self):
# Check that recvmsg() rejects invalid arguments.
self.assertRaises(TypeError, self.serv_sock.recvmsg)
self.assertRaises(ValueError, self.serv_sock.recvmsg,
-1, 0, 0)
self.assertRaises(ValueError, self.serv_sock.recvmsg,
len(MSG), -1, 0)
self.assertRaises(TypeError, self.serv_sock.recvmsg,
[bytearray(10)], 0, 0)
self.assertRaises(TypeError, self.serv_sock.recvmsg,
object(), 0, 0)
self.assertRaises(TypeError, self.serv_sock.recvmsg,
len(MSG), object(), 0)
self.assertRaises(TypeError, self.serv_sock.recvmsg,
len(MSG), 0, object())
msg, ancdata, flags, addr = self.serv_sock.recvmsg(len(MSG), 0, 0)
self.assertEqual(msg, MSG)
self.checkRecvmsgAddress(addr, self.cli_addr)
self.assertEqual(ancdata, [])
self.checkFlags(flags, eor=True)
def _testRecvmsgBadArgs(self):
self.sendToServer(MSG)
| RecvmsgTests |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/flake8_pyi/PYI019_0.py | {
"start": 3605,
"end": 3729
} | class ____:
def m[S](self: S, other: S): ...
@classmethod
def n[S](cls: type[S], other: S): ...
| NoReturnAnnotations |
python | getsentry__sentry | tests/sentry/integrations/vsts/test_issues.py | {
"start": 2753,
"end": 6529
} | class ____(TestCase):
def setUp(self) -> None:
with assume_test_silo_mode(SiloMode.CONTROL):
model = self.create_provider_integration(
provider="vsts",
external_id="vsts_external_id",
name="fabrikam-fiber-inc",
metadata={
"domain_name": "https://fabrikam-fiber-inc.visualstudio.com/",
"default_project": "0987654321",
},
)
identity = Identity.objects.create(
idp=self.create_identity_provider(type="vsts"),
user=self.user,
external_id="vsts",
data={"access_token": "123456789", "expires": time() + 1234567},
)
model.add_organization(self.organization, self.user, identity.id)
self.config = {
"resolve_status": "Resolved",
"resolve_when": "Resolved",
"regression_status": "Active",
"sync_comments": True,
"sync_forward_assignment": True,
"sync_reverse_assignment": True,
}
self.integration = VstsIntegration(model, self.organization.id)
self.issue_id = "309"
responses.add(
responses.GET,
"https://fabrikam-fiber-inc.visualstudio.com/c0bf429a-c03c-4a99-9336-d45be74db5a6/_apis/wit/workitemtypes/Bug/states",
json=WORK_ITEM_STATES,
)
self.project_id_with_states = "c0bf429a-c03c-4a99-9336-d45be74db5a6"
def mock_categories(self, project):
responses.add(
responses.GET,
f"https://fabrikam-fiber-inc.visualstudio.com/{project}/_apis/wit/workitemtypecategories",
json={
"value": [
{
"workItemTypes": [
{
"url": f"https://fabrikam-fiber-inc.visualstudio.com/{project}/wit/workItemTypeCategories/Microsoft.VSTS.WorkItemTypes.Bug",
"name": "Bug",
}
],
},
{
"workItemTypes": [
{
"url": f"https://fabrikam-fiber-inc.visualstudio.com/{project}/wit/workItemTypeCategories/Microsoft.VSTS.WorkItemTypes.Bug",
"name": "Issue Bug",
},
{
"url": f"https://fabrikam-fiber-inc.visualstudio.com/{project}/wit/workItemTypeCategories/Some-Thing.GIssue",
"name": "G Issue",
},
],
},
{
"workItemTypes": [
{
"url": f"https://fabrikam-fiber-inc.visualstudio.com/{project}/wit/workItemTypeCategories/Microsoft.VSTS.WorkItemTypes.Task",
"name": "Task",
}
],
},
{
"workItemTypes": [
{
"url": f"https://fabrikam-fiber-inc.visualstudio.com/{project}/wit/workItemTypeCategories/Microsoft.VSTS.WorkItemTypes.UserStory",
"name": "User Story",
}
],
},
]
},
)
@override_settings(
SENTRY_SUBNET_SECRET="hush-hush-im-invisible",
SENTRY_CONTROL_ADDRESS="http://controlserver",
)
@region_silo_test(include_monolith_run=True)
| VstsIssueBase |
python | python-openxml__python-docx | src/docx/package.py | {
"start": 1643,
"end": 3971
} | class ____:
"""Collection of |ImagePart| objects corresponding to images in the package."""
def __init__(self):
self._image_parts: list[ImagePart] = []
def __contains__(self, item: object):
return self._image_parts.__contains__(item)
def __iter__(self):
return self._image_parts.__iter__()
def __len__(self):
return self._image_parts.__len__()
def append(self, item: ImagePart):
self._image_parts.append(item)
def get_or_add_image_part(self, image_descriptor: str | IO[bytes]) -> ImagePart:
"""Return |ImagePart| object containing image identified by `image_descriptor`.
The image-part is newly created if a matching one is not present in the
collection.
"""
image = Image.from_file(image_descriptor)
matching_image_part = self._get_by_sha1(image.sha1)
if matching_image_part is not None:
return matching_image_part
return self._add_image_part(image)
def _add_image_part(self, image: Image):
"""Return |ImagePart| instance newly created from `image` and appended to the collection."""
partname = self._next_image_partname(image.ext)
image_part = ImagePart.from_image(image, partname)
self.append(image_part)
return image_part
def _get_by_sha1(self, sha1: str) -> ImagePart | None:
"""Return the image part in this collection having a SHA1 hash matching `sha1`,
or |None| if not found."""
for image_part in self._image_parts:
if image_part.sha1 == sha1:
return image_part
return None
def _next_image_partname(self, ext: str) -> PackURI:
"""The next available image partname, starting from ``/word/media/image1.{ext}``
where unused numbers are reused.
The partname is unique by number, without regard to the extension. `ext` does
not include the leading period.
"""
def image_partname(n: int) -> PackURI:
return PackURI("/word/media/image%d.%s" % (n, ext))
used_numbers = [image_part.partname.idx for image_part in self]
for n in range(1, len(self) + 1):
if n not in used_numbers:
return image_partname(n)
return image_partname(len(self) + 1)
| ImageParts |
python | pytorch__pytorch | torchgen/model.py | {
"start": 85857,
"end": 86122
} | class ____:
argument: Argument
# Bundle of arguments that represent a TensorOptions. This is mostly
# relevant for the public C++ API but we bake it into the core data
# model because other APIs often have to interact with it
@dataclass(frozen=True)
| SelfArgument |
python | scrapy__scrapy | tests/test_downloadermiddleware_httpcache.py | {
"start": 3540,
"end": 5454
} | class ____:
"""Mixin containing storage-specific test methods."""
def test_storage(self):
with self._storage() as (storage, crawler):
request2 = self.request.copy()
assert storage.retrieve_response(crawler.spider, request2) is None
storage.store_response(crawler.spider, self.request, self.response)
response2 = storage.retrieve_response(crawler.spider, request2)
assert isinstance(response2, HtmlResponse) # content-type header
self.assertEqualResponse(self.response, response2)
time.sleep(2) # wait for cache to expire
assert storage.retrieve_response(crawler.spider, request2) is None
def test_storage_never_expire(self):
with self._storage(HTTPCACHE_EXPIRATION_SECS=0) as (storage, crawler):
assert storage.retrieve_response(crawler.spider, self.request) is None
storage.store_response(crawler.spider, self.request, self.response)
time.sleep(0.5) # give the chance to expire
assert storage.retrieve_response(crawler.spider, self.request)
def test_storage_no_content_type_header(self):
"""Test that the response body is used to get the right response class
even if there is no Content-Type header"""
with self._storage() as (storage, crawler):
assert storage.retrieve_response(crawler.spider, self.request) is None
response = Response(
"http://www.example.com",
body=b"<!DOCTYPE html>\n<title>.</title>",
status=202,
)
storage.store_response(crawler.spider, self.request, response)
cached_response = storage.retrieve_response(crawler.spider, self.request)
assert isinstance(cached_response, HtmlResponse)
self.assertEqualResponse(response, cached_response)
| StorageTestMixin |
python | getsentry__sentry | src/sentry/api/exceptions.py | {
"start": 492,
"end": 641
} | class ____(APIException):
status_code = status.HTTP_404_NOT_FOUND
default_detail = "The requested resource does not exist"
| ResourceDoesNotExist |
python | dagster-io__dagster | helm/dagster/schema/schema/charts/utils/kubernetes.py | {
"start": 4424,
"end": 4605
} | class ____(BaseModel):
model_config = {
"extra": "allow",
"json_schema_extra": {"$ref": create_definition_ref("io.k8s.api.core.v1.VolumeMount")},
}
| VolumeMount |
python | sphinx-doc__sphinx | tests/roots/test-ext-autodoc/target/need_mocks.py | {
"start": 769,
"end": 944
} | class ____(missing_module.Class):
"""docstring"""
pass
sphinx.missing_module4.missing_function(len(missing_name2))
#: docstring
Alias = missing_module2.Class
| Inherited |
python | pandas-dev__pandas | pandas/tests/scalar/timestamp/test_timestamp.py | {
"start": 758,
"end": 8029
} | class ____:
def test_properties_business(self):
freq = to_offset("B")
ts = Timestamp("2017-10-01")
assert ts.dayofweek == 6
assert ts.day_of_week == 6
assert ts.is_month_start # not a weekday
assert not freq.is_month_start(ts)
assert freq.is_month_start(ts + Timedelta(days=1))
assert not freq.is_quarter_start(ts)
assert freq.is_quarter_start(ts + Timedelta(days=1))
ts = Timestamp("2017-09-30")
assert ts.dayofweek == 5
assert ts.day_of_week == 5
assert ts.is_month_end
assert not freq.is_month_end(ts)
assert freq.is_month_end(ts - Timedelta(days=1))
assert ts.is_quarter_end
assert not freq.is_quarter_end(ts)
assert freq.is_quarter_end(ts - Timedelta(days=1))
@pytest.mark.parametrize(
"attr, expected",
[
["year", 2014],
["month", 12],
["day", 31],
["hour", 23],
["minute", 59],
["second", 0],
["microsecond", 0],
["nanosecond", 0],
["dayofweek", 2],
["day_of_week", 2],
["quarter", 4],
["dayofyear", 365],
["day_of_year", 365],
["week", 1],
["daysinmonth", 31],
],
)
@pytest.mark.parametrize("tz", [None, "US/Eastern"])
def test_fields(self, attr, expected, tz):
# GH 10050
# GH 13303
ts = Timestamp("2014-12-31 23:59:00", tz=tz)
result = getattr(ts, attr)
# that we are int like
assert isinstance(result, int)
assert result == expected
@pytest.mark.parametrize("tz", [None, "US/Eastern"])
def test_millisecond_raises(self, tz):
ts = Timestamp("2014-12-31 23:59:00", tz=tz)
msg = "'Timestamp' object has no attribute 'millisecond'"
with pytest.raises(AttributeError, match=msg):
ts.millisecond
@pytest.mark.parametrize(
"start", ["is_month_start", "is_quarter_start", "is_year_start"]
)
@pytest.mark.parametrize("tz", [None, "US/Eastern"])
def test_is_start(self, start, tz):
ts = Timestamp("2014-01-01 00:00:00", tz=tz)
assert getattr(ts, start)
@pytest.mark.parametrize("end", ["is_month_end", "is_year_end", "is_quarter_end"])
@pytest.mark.parametrize("tz", [None, "US/Eastern"])
def test_is_end(self, end, tz):
ts = Timestamp("2014-12-31 23:59:59", tz=tz)
assert getattr(ts, end)
# GH 12806
@pytest.mark.parametrize("tz", [None, "EST"])
# error: Unsupported operand types for + ("List[None]" and "List[str]")
@pytest.mark.parametrize(
"time_locale",
[None] + tm.get_locales(), # type: ignore[operator]
)
def test_names(self, tz, time_locale):
# GH 17354
# Test .day_name(), .month_name
data = Timestamp("2017-08-28 23:00:00", tz=tz)
if time_locale is None:
expected_day = "Monday"
expected_month = "August"
else:
with tm.set_locale(time_locale, locale.LC_TIME):
expected_day = calendar.day_name[0].capitalize()
expected_month = calendar.month_name[8].capitalize()
result_day = data.day_name(time_locale)
result_month = data.month_name(time_locale)
# Work around https://github.com/pandas-dev/pandas/issues/22342
# different normalizations
expected_day = unicodedata.normalize("NFD", expected_day)
expected_month = unicodedata.normalize("NFD", expected_month)
result_day = unicodedata.normalize("NFD", result_day)
result_month = unicodedata.normalize("NFD", result_month)
assert result_day == expected_day
assert result_month == expected_month
# Test NaT
nan_ts = Timestamp(NaT)
assert np.isnan(nan_ts.day_name(time_locale))
assert np.isnan(nan_ts.month_name(time_locale))
def test_is_leap_year(self, tz_naive_fixture):
tz = tz_naive_fixture
if not IS64 and tz == tzlocal():
# https://github.com/dateutil/dateutil/issues/197
pytest.skip(
"tzlocal() on a 32 bit platform causes internal overflow errors"
)
# GH 13727
dt = Timestamp("2000-01-01 00:00:00", tz=tz)
assert dt.is_leap_year
assert isinstance(dt.is_leap_year, bool)
dt = Timestamp("1999-01-01 00:00:00", tz=tz)
assert not dt.is_leap_year
dt = Timestamp("2004-01-01 00:00:00", tz=tz)
assert dt.is_leap_year
dt = Timestamp("2100-01-01 00:00:00", tz=tz)
assert not dt.is_leap_year
def test_woy_boundary(self):
# make sure weeks at year boundaries are correct
d = datetime(2013, 12, 31)
result = Timestamp(d).week
expected = 1 # ISO standard
assert result == expected
d = datetime(2008, 12, 28)
result = Timestamp(d).week
expected = 52 # ISO standard
assert result == expected
d = datetime(2009, 12, 31)
result = Timestamp(d).week
expected = 53 # ISO standard
assert result == expected
d = datetime(2010, 1, 1)
result = Timestamp(d).week
expected = 53 # ISO standard
assert result == expected
d = datetime(2010, 1, 3)
result = Timestamp(d).week
expected = 53 # ISO standard
assert result == expected
result = np.array(
[
Timestamp(datetime(*args)).week
for args in [(2000, 1, 1), (2000, 1, 2), (2005, 1, 1), (2005, 1, 2)]
]
)
assert (result == [52, 52, 53, 53]).all()
def test_resolution(self):
# GH#21336, GH#21365
dt = Timestamp("2100-01-01 00:00:00.000000000")
assert dt.resolution == Timedelta(nanoseconds=1)
# Check that the attribute is available on the class, mirroring
# the stdlib datetime behavior
assert Timestamp.resolution == Timedelta(nanoseconds=1)
assert dt.as_unit("us").resolution == Timedelta(microseconds=1)
assert dt.as_unit("ms").resolution == Timedelta(milliseconds=1)
assert dt.as_unit("s").resolution == Timedelta(seconds=1)
@pytest.mark.parametrize(
"date_string, expected",
[
("0000-2-29", 1),
("0000-3-1", 2),
("1582-10-14", 3),
("-0040-1-1", 4),
("2023-06-18", 6),
],
)
def test_dow_historic(self, date_string, expected):
# GH 53738
ts = Timestamp(date_string)
dow = ts.weekday()
assert dow == expected
@pytest.mark.slow
@given(
ts=st.datetimes(),
sign=st.sampled_from(["-", ""]),
)
def test_dow_parametric(self, ts, sign):
# GH 53738
ts = (
f"{sign}{str(ts.year).zfill(4)}"
f"-{str(ts.month).zfill(2)}"
f"-{str(ts.day).zfill(2)}"
)
result = Timestamp(ts).weekday()
expected = (
(np.datetime64(ts) - np.datetime64("1970-01-01")).astype("int64") - 4
) % 7
assert result == expected
| TestTimestampProperties |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/orm/path_registry.py | {
"start": 24580,
"end": 24841
} | class ____(Dict[Any, Any]):
def __init__(self, registry: _CachingEntityRegistry):
self.registry = registry
def __missing__(self, key: Any) -> _PropRegistry:
self[key] = item = _PropRegistry(self.registry, key)
return item
| _ERDict |
python | doocs__leetcode | solution/2100-2199/2146.K Highest Ranked Items Within a Price Range/Solution.py | {
"start": 0,
"end": 1005
} | class ____:
def highestRankedKItems(
self, grid: List[List[int]], pricing: List[int], start: List[int], k: int
) -> List[List[int]]:
m, n = len(grid), len(grid[0])
row, col = start
low, high = pricing
q = deque([(row, col)])
pq = []
if low <= grid[row][col] <= high:
pq.append((0, grid[row][col], row, col))
grid[row][col] = 0
dirs = (-1, 0, 1, 0, -1)
step = 0
while q:
step += 1
for _ in range(len(q)):
x, y = q.popleft()
for a, b in pairwise(dirs):
nx, ny = x + a, y + b
if 0 <= nx < m and 0 <= ny < n and grid[nx][ny] > 0:
if low <= grid[nx][ny] <= high:
pq.append((step, grid[nx][ny], nx, ny))
grid[nx][ny] = 0
q.append((nx, ny))
pq.sort()
return [list(x[2:]) for x in pq[:k]]
| Solution |
python | apache__airflow | devel-common/src/tests_common/test_utils/asserts.py | {
"start": 2032,
"end": 2951
} | class ____(NamedTuple):
"""QueriesTraceInfo holds information about the queries executed in the context."""
traces: tuple[QueriesTraceRecord, ...]
@classmethod
def from_traceback(cls, trace: traceback.StackSummary) -> QueriesTraceInfo:
records = [
QueriesTraceRecord.from_frame(f)
for f in trace
if "sqlalchemy" not in f.filename
and __file__ != f.filename
and ("session.py" not in f.filename and f.name != "wrapper")
]
return cls(traces=tuple(records))
def module_level(self, module: str) -> int:
stacklevel = 0
for ix, record in enumerate(reversed(self.traces), start=1):
if record.module == module:
stacklevel = ix
if stacklevel == 0:
raise LookupError(f"Unable to find module {stacklevel} in traceback")
return stacklevel
| QueriesTraceInfo |
python | apache__airflow | providers/http/src/airflow/providers/http/operators/http.py | {
"start": 1613,
"end": 15536
} | class ____(BaseOperator):
"""
Calls an endpoint on an HTTP system to execute an action.
.. seealso::
For more information on how to use this operator, take a look at the guide:
:ref:`howto/operator:HttpOperator`
:param http_conn_id: The :ref:`http connection<howto/connection:http>` to run
the operator against
:param endpoint: The relative part of the full url. (templated)
:param method: The HTTP method to use, default = "POST"
:param data: The data to pass. POST-data in POST/PUT and params
in the URL for a GET request. (templated)
:param headers: The HTTP headers to be added to the GET request
:param pagination_function: A callable that generates the parameters used to call the API again,
based on the previous response. Typically used when the API is paginated and returns for e.g a
cursor, a 'next page id', or a 'next page URL'. When provided, the Operator will call the API
repeatedly until this callable returns None. The result of the Operator will become by default a
list of Response.text objects (instead of a single response object). Same with the other injected
functions (like response_check, response_filter, ...) which will also receive a list of Response
objects. This function receives a Response object form previous call, and should return a nested
dictionary with the following optional keys: `endpoint`, `data`, `headers` and `extra_options.
Those keys will be merged and/or override the parameters provided into the HttpOperator declaration.
Parameters are merged when they are both a dictionary (e.g.: HttpOperator.headers will be merged
with the `headers` dict provided by this function). When merging, dict items returned by this
function will override initial ones (e.g: if both HttpOperator.headers and `headers` have a 'cookie'
item, the one provided by `headers` is kept). Parameters are simply overridden when any of them are
string (e.g.: HttpOperator.endpoint is overridden by `endpoint`).
:param response_check: A check against the 'requests' response object.
The callable takes the response object as the first positional argument
and optionally any number of keyword arguments available in the context dictionary.
It should return True for 'pass' and False otherwise. If a pagination_function
is provided, this function will receive a list of response objects instead of a
single response object.
:param response_filter: A function allowing you to manipulate the response
text. e.g response_filter=lambda response: json.loads(response.text).
The callable takes the response object as the first positional argument
and optionally any number of keyword arguments available in the context dictionary.
If a pagination_function is provided, this function will receive a list of response
object instead of a single response object.
:param extra_options: Extra options for the 'requests' library, see the
'requests' documentation (options to modify timeout, ssl, etc.)
:param log_response: Log the response (default: False)
:param auth_type: The auth type for the service
:param tcp_keep_alive: Enable TCP Keep Alive for the connection.
:param tcp_keep_alive_idle: The TCP Keep Alive Idle parameter (corresponds to ``socket.TCP_KEEPIDLE``).
:param tcp_keep_alive_count: The TCP Keep Alive count parameter (corresponds to ``socket.TCP_KEEPCNT``)
:param tcp_keep_alive_interval: The TCP Keep Alive interval parameter (corresponds to
``socket.TCP_KEEPINTVL``)
:param deferrable: Run operator in the deferrable mode
:param retry_args: Arguments which define the retry behaviour.
See Tenacity documentation at https://github.com/jd/tenacity
"""
conn_id_field = "http_conn_id"
template_fields: Sequence[str] = (
"endpoint",
"data",
"headers",
)
template_fields_renderers = {"headers": "json", "data": "py"}
template_ext: Sequence[str] = ()
ui_color = "#f4a460"
def __init__(
self,
*,
endpoint: str | None = None,
method: str = "POST",
data: dict[str, Any] | str | None = None,
headers: dict[str, str] | None = None,
pagination_function: Callable[..., Any] | None = None,
response_check: Callable[..., bool] | None = None,
response_filter: Callable[..., Any] | None = None,
extra_options: dict[str, Any] | None = None,
request_kwargs: dict[str, Any] | None = None,
http_conn_id: str = "http_default",
log_response: bool = False,
auth_type: type[AuthBase] | type[BasicAuth] | None = None,
tcp_keep_alive: bool = True,
tcp_keep_alive_idle: int = 120,
tcp_keep_alive_count: int = 20,
tcp_keep_alive_interval: int = 30,
deferrable: bool = conf.getboolean("operators", "default_deferrable", fallback=False),
retry_args: dict[str, Any] | None = None,
**kwargs: Any,
) -> None:
super().__init__(**kwargs)
self.http_conn_id = http_conn_id
self.method = method
self.endpoint = endpoint
self.headers = headers or {}
self.data = data or {}
self.pagination_function = pagination_function
self.response_check = response_check
self.response_filter = response_filter
self.extra_options = extra_options or {}
self.log_response = log_response
self.auth_type = auth_type
self.tcp_keep_alive = tcp_keep_alive
self.tcp_keep_alive_idle = tcp_keep_alive_idle
self.tcp_keep_alive_count = tcp_keep_alive_count
self.tcp_keep_alive_interval = tcp_keep_alive_interval
self.deferrable = deferrable
self.retry_args = retry_args
self.request_kwargs = request_kwargs or {}
@property
def hook(self) -> HttpHook:
"""Get Http Hook based on connection type."""
conn_id = getattr(self, self.conn_id_field)
self.log.debug("Get connection for %s", conn_id)
conn = BaseHook.get_connection(conn_id)
hook = conn.get_hook(
hook_params=dict(
method=self.method,
auth_type=self.auth_type,
tcp_keep_alive=self.tcp_keep_alive,
tcp_keep_alive_idle=self.tcp_keep_alive_idle,
tcp_keep_alive_count=self.tcp_keep_alive_count,
tcp_keep_alive_interval=self.tcp_keep_alive_interval,
)
)
return hook
def execute(self, context: Context) -> Any:
if self.deferrable:
self.execute_async(context=context)
else:
return self.execute_sync(context=context)
def execute_sync(self, context: Context) -> Any:
self.log.info("Calling HTTP method")
if self.retry_args:
response = self.hook.run_with_advanced_retry(
self.retry_args,
self.endpoint,
self.data,
self.headers,
self.extra_options,
**self.request_kwargs,
)
else:
response = self.hook.run(
self.endpoint,
self.data,
self.headers,
self.extra_options,
**self.request_kwargs,
)
response = self.paginate_sync(response=response)
return self.process_response(context=context, response=response)
def paginate_sync(self, response: Response) -> Response | list[Response]:
if not self.pagination_function:
return response
all_responses = [response]
while True:
next_page_params = self.pagination_function(response)
if not next_page_params:
break
if self.retry_args:
response = self.hook.run_with_advanced_retry(
self.retry_args,
**self._merge_next_page_parameters(next_page_params),
)
else:
response = self.hook.run(**self._merge_next_page_parameters(next_page_params))
all_responses.append(response)
return all_responses
def execute_async(self, context: Context) -> None:
self.defer(
trigger=HttpTrigger(
http_conn_id=self.http_conn_id,
auth_type=serialize_auth_type(self._resolve_auth_type()),
method=self.method,
endpoint=self.endpoint,
headers=self.headers,
data=self.data,
extra_options=self.extra_options,
),
method_name="execute_complete",
)
def _resolve_auth_type(self) -> type[AuthBase] | type[BasicAuth] | None:
"""
Resolve the authentication type for the HTTP request.
If auth_type is not explicitly set, attempt to infer it from the connection configuration.
For connections with login/password, default to BasicAuth.
:return: The resolved authentication type class, or None if no auth is needed.
"""
if self.auth_type is not None:
return self.auth_type
try:
conn = BaseHook.get_connection(self.http_conn_id)
if conn.login or conn.password:
return BasicAuth
except Exception as e:
self.log.warning("Failed to resolve auth type from connection: %s", e)
return None
def process_response(self, context: Context, response: Response | list[Response]) -> Any:
"""Process the response."""
from airflow.utils.operator_helpers import determine_kwargs
make_default_response: Callable = self._default_response_maker(response=response)
if self.log_response:
self.log.info(make_default_response())
if self.response_check:
kwargs = determine_kwargs(self.response_check, [response], context)
if not self.response_check(response, **kwargs):
raise AirflowException("Response check returned False.")
if self.response_filter:
kwargs = determine_kwargs(self.response_filter, [response], context)
return self.response_filter(response, **kwargs)
return make_default_response()
@staticmethod
def _default_response_maker(response: Response | list[Response]) -> Callable:
"""
Create a default response maker function based on the type of response.
:param response: The response object or list of response objects.
:return: A function that returns response text(s).
"""
if isinstance(response, Response):
response_object = response # Makes mypy happy
return lambda: response_object.text
response_list: list[Response] = response # Makes mypy happy
return lambda: [entry.text for entry in response_list]
def execute_complete(
self, context: Context, event: dict, paginated_responses: None | list[Response] = None
):
"""
Execute callback when the trigger fires; returns immediately.
Relies on trigger to throw an exception, otherwise it assumes execution was successful.
"""
if event["status"] == "success":
response = pickle.loads(base64.standard_b64decode(event["response"]))
self.paginate_async(context=context, response=response, previous_responses=paginated_responses)
return self.process_response(context=context, response=response)
raise AirflowException(f"Unexpected error in the operation: {event['message']}")
def paginate_async(
self, context: Context, response: Response, previous_responses: None | list[Response] = None
):
if self.pagination_function:
all_responses = previous_responses or []
all_responses.append(response)
next_page_params = self.pagination_function(response)
if not next_page_params:
return self.process_response(context=context, response=all_responses)
self.defer(
trigger=HttpTrigger(
http_conn_id=self.http_conn_id,
auth_type=serialize_auth_type(self._resolve_auth_type()),
method=self.method,
**self._merge_next_page_parameters(next_page_params),
),
method_name="execute_complete",
kwargs={"paginated_responses": all_responses},
)
def _merge_next_page_parameters(self, next_page_params: dict) -> dict:
"""
Merge initial request parameters with next page parameters.
Merge initial requests parameters with the ones for the next page, generated by
the pagination function. Items in the 'next_page_params' overrides those defined
in the previous request.
:param next_page_params: A dictionary containing the parameters for the next page.
:return: A dictionary containing the merged parameters.
"""
data: str | dict | None = None # makes mypy happy
next_page_data_param = next_page_params.get("data")
if isinstance(self.data, dict) and isinstance(next_page_data_param, dict):
data = merge_dicts(self.data, next_page_data_param)
else:
data = next_page_data_param or self.data
return dict(
endpoint=next_page_params.get("endpoint") or self.endpoint,
data=data,
headers=merge_dicts(self.headers, next_page_params.get("headers", {})),
extra_options=merge_dicts(self.extra_options, next_page_params.get("extra_options", {})),
**self.request_kwargs,
)
| HttpOperator |
python | pypa__setuptools | setuptools/tests/test_editable_install.py | {
"start": 27747,
"end": 31767
} | class ____:
PYPROJECT = """\
[build-system]
requires = ["setuptools"]
build-backend = "setuptools.build_meta"
[project]
name = "mypkg"
version = "3.14159"
"""
# Any: Would need a TypedDict. Keep it simple for tests
FLAT_LAYOUT: dict[str, Any] = {
"pyproject.toml": dedent(PYPROJECT),
"MANIFEST.in": EXAMPLE["MANIFEST.in"],
"otherfile.py": "",
"mypkg": {
"__init__.py": "",
"mod1.py": "var = 42",
"subpackage": {
"__init__.py": "",
"mod2.py": "var = 13",
"resource_file.txt": "resource 39",
},
},
}
EXAMPLES = {
"flat-layout": FLAT_LAYOUT,
"src-layout": {
"pyproject.toml": dedent(PYPROJECT),
"MANIFEST.in": EXAMPLE["MANIFEST.in"],
"otherfile.py": "",
"src": {"mypkg": FLAT_LAYOUT["mypkg"]},
},
"custom-layout": {
"pyproject.toml": dedent(PYPROJECT)
+ dedent(
"""\
[tool.setuptools]
packages = ["mypkg", "mypkg.subpackage"]
[tool.setuptools.package-dir]
"mypkg.subpackage" = "other"
"""
),
"MANIFEST.in": EXAMPLE["MANIFEST.in"],
"otherfile.py": "",
"mypkg": {
"__init__.py": "",
"mod1.py": FLAT_LAYOUT["mypkg"]["mod1.py"],
},
"other": FLAT_LAYOUT["mypkg"]["subpackage"],
},
"namespace": {
"pyproject.toml": dedent(PYPROJECT),
"MANIFEST.in": EXAMPLE["MANIFEST.in"],
"otherfile.py": "",
"src": {
"mypkg": {
"mod1.py": FLAT_LAYOUT["mypkg"]["mod1.py"],
"subpackage": FLAT_LAYOUT["mypkg"]["subpackage"],
},
},
},
}
@pytest.mark.xfail(sys.platform == "darwin", reason="pypa/setuptools#4328")
@pytest.mark.parametrize("layout", EXAMPLES.keys())
def test_editable_install(self, tmp_path, venv, layout, editable_opts):
project, _ = install_project(
"mypkg", venv, tmp_path, self.EXAMPLES[layout], *editable_opts
)
# Ensure stray files are not importable
cmd_import_error = """\
try:
import otherfile
except ImportError as ex:
print(ex)
"""
out = venv.run(["python", "-c", dedent(cmd_import_error)])
assert "No module named 'otherfile'" in out
# Ensure the modules are importable
cmd_get_vars = """\
import mypkg, mypkg.mod1, mypkg.subpackage.mod2
print(mypkg.mod1.var, mypkg.subpackage.mod2.var)
"""
out = venv.run(["python", "-c", dedent(cmd_get_vars)])
assert "42 13" in out
# Ensure resources are reachable
cmd_get_resource = """\
import mypkg.subpackage
from setuptools._importlib import resources as importlib_resources
text = importlib_resources.files(mypkg.subpackage) / "resource_file.txt"
print(text.read_text(encoding="utf-8"))
"""
out = venv.run(["python", "-c", dedent(cmd_get_resource)])
assert "resource 39" in out
# Ensure files are editable
mod1 = next(project.glob("**/mod1.py"))
mod2 = next(project.glob("**/mod2.py"))
resource_file = next(project.glob("**/resource_file.txt"))
mod1.write_text("var = 17", encoding="utf-8")
mod2.write_text("var = 781", encoding="utf-8")
resource_file.write_text("resource 374", encoding="utf-8")
out = venv.run(["python", "-c", dedent(cmd_get_vars)])
assert "42 13" not in out
assert "17 781" in out
out = venv.run(["python", "-c", dedent(cmd_get_resource)])
assert "resource 39" not in out
assert "resource 374" in out
| TestOverallBehaviour |
python | scipy__scipy | benchmarks/benchmarks/special.py | {
"start": 705,
"end": 1098
} | class ____(Benchmark):
def setup(self, *args):
self.N = np.arange(1, 1000, 50)
self.k = np.arange(1, 1000, 50)
@with_attributes(params=[(10, 100, 1000, 10000), (1, 10, 100)],
param_names=['N', 'k'])
def time_comb_exact(self, N, k):
comb(N, k, exact=True)
def time_comb_float(self):
comb(self.N[:,None], self.k[None,:])
| Comb |
python | huggingface__transformers | src/transformers/models/reformer/modeling_reformer.py | {
"start": 58355,
"end": 61795
} | class ____(nn.Module):
def __init__(self, config, layer_id=0):
super().__init__()
self.layer_id = layer_id
self.attn_layers = config.attn_layers
self.layer_norm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
if len(set(self.attn_layers)) == 1 and self.attn_layers[0] == "lsh":
self.self_attention = LSHSelfAttention(config, layer_idx=layer_id)
elif len(set(self.attn_layers)) == 1 and self.attn_layers[0] == "local":
self.self_attention = LocalSelfAttention(config, layer_idx=layer_id)
elif len(set(self.attn_layers)) == 2 and set(self.attn_layers) == {"lsh", "local"}:
# get correct attn layers
if self.attn_layers[self.layer_id] == "lsh":
self.self_attention = LSHSelfAttention(config, layer_idx=layer_id)
else:
self.self_attention = LocalSelfAttention(config, layer_idx=layer_id)
else:
raise NotImplementedError(
f"Only attn layer types 'lsh' and 'local' exist, but got `config.attn_layers`: {self.attn_layers}. "
"Select attn layer types from ['lsh', 'local'] only."
)
self.output = ReformerSelfOutput(config)
def forward(
self,
hidden_states,
attention_mask=None,
num_hashes=None,
past_buckets_states=None,
use_cache=False,
orig_sequence_length=None,
output_attentions=False,
buckets=None,
cache_position=None,
):
hidden_states = self.layer_norm(hidden_states)
# use cached buckets for backprob if buckets not None for LSHSelfAttention
self_attention_outputs = self.self_attention(
hidden_states=hidden_states,
attention_mask=attention_mask,
num_hashes=num_hashes,
past_buckets_states=past_buckets_states,
use_cache=use_cache,
output_attentions=output_attentions,
buckets=buckets,
cache_position=cache_position,
)
# add buckets if necessary
if hasattr(self_attention_outputs, "buckets"):
buckets = self_attention_outputs.buckets
else:
buckets = None
# cache hidden states for future use
if use_cache and past_buckets_states is not None:
# padded input should not be cached during prefill
states = (
hidden_states[:, :orig_sequence_length]
if len(past_buckets_states.states_cache) <= self.layer_id
else hidden_states
)
buckets = (
buckets[:, :, :, :orig_sequence_length]
if (
len(past_buckets_states.buckets_cache) <= self.layer_id
and buckets is not None
and orig_sequence_length > 1
)
else buckets
)
buckets, hidden_states = past_buckets_states.update(
buckets, states[:, :orig_sequence_length], self.layer_id
)
# compute attention feed forward output
attention_output = self.output(self_attention_outputs.hidden_states)
return AttentionOutput(
hidden_states=attention_output,
attention_probs=self_attention_outputs.attention_probs,
buckets=buckets,
)
| ReformerAttention |
python | pymupdf__PyMuPDF | pipcl.py | {
"start": 93264,
"end": 119112
} | class ____:
'''
Compile/link flags for the current python, for example the include path
needed to get `Python.h`.
The 'PIPCL_PYTHON_CONFIG' environment variable allows to override
the location of the python-config executable.
Members:
.includes:
String containing compiler flags for include paths.
.ldflags:
String containing linker flags for library paths.
'''
def __init__(self):
# Experimental detection of python flags from sysconfig.*() instead of
# python-config command.
includes_, ldflags_ = sysconfig_python_flags()
if pyodide():
_include_dir = os.environ[ 'PYO3_CROSS_INCLUDE_DIR']
_lib_dir = os.environ[ 'PYO3_CROSS_LIB_DIR']
self.includes = f'-I {_include_dir}'
self.ldflags = f'-L {_lib_dir}'
elif 0:
self.includes = includes_
self.ldflags = ldflags_
elif windows():
wp = wdev.WindowsPython()
self.includes = f'/I"{wp.include}"'
self.ldflags = f'/LIBPATH:"{wp.libs}"'
elif pyodide():
_include_dir = os.environ[ 'PYO3_CROSS_INCLUDE_DIR']
_lib_dir = os.environ[ 'PYO3_CROSS_LIB_DIR']
self.includes = f'-I {_include_dir}'
self.ldflags = f'-L {_lib_dir}'
else:
python_config = os.environ.get("PIPCL_PYTHON_CONFIG")
if not python_config:
# We use python-config which appears to work better than pkg-config
# because it copes with multiple installed python's, e.g.
# manylinux_2014's /opt/python/cp*-cp*/bin/python*.
#
# But... on non-macos it seems that we should not attempt to specify
# libpython on the link command. The manylinux docker containers
# don't actually contain libpython.so, and it seems that this
# deliberate. And the link command runs ok.
#
python_exe = os.path.realpath( sys.executable)
if darwin():
# Basic install of dev tools with `xcode-select --install` doesn't
# seem to provide a `python3-config` or similar, but there is a
# `python-config.py` accessible via sysconfig.
#
# We try different possibilities and use the last one that
# works.
#
python_config = None
for pc in (
f'python3-config',
f'{sys.executable} {sysconfig.get_config_var("srcdir")}/python-config.py',
f'{python_exe}-config',
):
e = subprocess.run(
f'{pc} --includes',
shell=1,
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
check=0,
).returncode
log2(f'{e=} from {pc!r}.')
if e == 0:
python_config = pc
assert python_config, f'Cannot find python-config'
else:
python_config = f'{python_exe}-config'
log2(f'Using {python_config=}.')
try:
self.includes = run( f'{python_config} --includes', capture=1, verbose=0).strip()
except Exception as e:
raise Exception('We require python development tools to be installed.') from e
self.ldflags = run( f'{python_config} --ldflags', capture=1, verbose=0).strip()
if linux():
# It seems that with python-3.10 on Linux, we can get an
# incorrect -lcrypt flag that on some systems (e.g. WSL)
# causes:
#
# ImportError: libcrypt.so.2: cannot open shared object file: No such file or directory
#
ldflags2 = self.ldflags.replace(' -lcrypt ', ' ')
if ldflags2 != self.ldflags:
log2(f'### Have removed `-lcrypt` from ldflags: {self.ldflags!r} -> {ldflags2!r}')
self.ldflags = ldflags2
if 0:
log1(f'{self.includes=}')
log1(f' {includes_=}')
log1(f'{self.ldflags=}')
log1(f' {ldflags_=}')
def macos_add_cross_flags(command):
'''
If running on MacOS and environment variables ARCHFLAGS is set
(indicating we are cross-building, e.g. for arm64), returns
`command` with extra flags appended. Otherwise returns unchanged
`command`.
'''
if darwin():
archflags = os.environ.get( 'ARCHFLAGS')
if archflags:
command = f'{command} {archflags}'
log2(f'Appending ARCHFLAGS to command: {command}')
return command
return command
def macos_patch( library, *sublibraries):
'''
If running on MacOS, patches `library` so that all references to items in
`sublibraries` are changed to `@rpath/{leafname}`. Does nothing on other
platforms.
library:
Path of shared library.
sublibraries:
List of paths of shared libraries; these have typically been
specified with `-l` when `library` was created.
'''
log2( f'macos_patch(): library={library} sublibraries={sublibraries}')
if not darwin():
return
if not sublibraries:
return
subprocess.run( f'otool -L {library}', shell=1, check=1)
command = 'install_name_tool'
names = []
for sublibrary in sublibraries:
name = subprocess.run(
f'otool -D {sublibrary}',
shell=1,
check=1,
capture_output=1,
encoding='utf8',
).stdout.strip()
name = name.split('\n')
assert len(name) == 2 and name[0] == f'{sublibrary}:', f'{name=}'
name = name[1]
# strip trailing so_name.
leaf = os.path.basename(name)
m = re.match('^(.+[.]((so)|(dylib)))[0-9.]*$', leaf)
assert m
log2(f'Changing {leaf=} to {m.group(1)}')
leaf = m.group(1)
command += f' -change {name} @rpath/{leaf}'
command += f' {library}'
log2( f'Running: {command}')
subprocess.run( command, shell=1, check=1)
subprocess.run( f'otool -L {library}', shell=1, check=1)
def _macos_fixup_platform_tag(tag):
'''
Patch up platform tag on MacOS.
E.g. `foo-1.2.3-cp311-none-macosx_13_x86_64.whl` causes `pip` to fail with:
`not a supported wheel on this platform`. We seem to need to add `_0` to
the OS version. (This is documented at
https://packaging.python.org/en/latest/specifications/platform-compatibility-tags/#macos).
And with graal we need to replace trailing `universal2` with x86_64
or arm64. On non-graal this causes problems because non-universal
platform tags seem more restricted than platform tags from
sysconfig.get_platform(). For example:
pip install ...-macosx_10_13_arm64.whl
ERROR: ...-macosx_10_13_arm64.whl is not a supported wheel on this platform.
pip install ...-macosx_10_13_universal2.whl
Ok.
'''
m = re.match( '^macosx_([0-9_]+)_([^0-9].+)$', tag)
if not m:
return tag
a = m.group(1)
if '_' not in a:
a += '_0'
b = m.group(2)
if sys.implementation.name == 'graalpy' and b == 'universal2':
# Replace 'universal2' with x86_64 or arm64.
b = platform.machine()
ret = f'macosx_{a}_{b}'
#log0(f'Changing from {tag=} to {ret=}.')
return ret
# Internal helpers.
#
def _command_lines( command):
'''
Process multiline command by running through `textwrap.dedent()`, removes
comments (lines starting with `#` or ` #` until end of line), removes
entirely blank lines.
Returns list of lines.
'''
command = textwrap.dedent( command)
lines = []
for line in command.split( '\n'):
if line.startswith( '#'):
h = 0
else:
h = line.find( ' #')
if h >= 0:
line = line[:h]
if line.strip():
lines.append(line.rstrip())
return lines
def cpu_bits():
return int.bit_length(sys.maxsize+1)
def _cpu_name():
'''
Returns `x32` or `x64` depending on Python build.
'''
#log(f'sys.maxsize={hex(sys.maxsize)}')
return f'x{32 if sys.maxsize == 2**31 - 1 else 64}'
def run_if( command, out, *prerequisites, caller=1):
'''
Runs a command only if the output file is not up to date.
Args:
command:
The command to run. We write this and a hash of argv[0] into a file
<out>.cmd so that we know to run a command if the command itself
has changed.
out:
Path of the output file.
prerequisites:
List of prerequisite paths or true/false/None items. If an item
is None it is ignored, otherwise if an item is not a string we
immediately return it cast to a bool. We recurse into directories,
effectively using the newest file in the directory.
Returns:
True if we ran the command, otherwise None.
If the output file does not exist, the command is run:
>>> verbose(1)
1
>>> log_line_numbers(0)
>>> out = 'run_if_test_out'
>>> if os.path.exists( out):
... os.remove( out)
>>> if os.path.exists( f'{out}.cmd'):
... os.remove( f'{out}.cmd')
>>> run_if( f'touch {out}', out, caller=0)
pipcl.py:run_if(): Running command because: File does not exist: 'run_if_test_out'
pipcl.py:run_if(): Running: touch run_if_test_out
True
If we repeat, the output file will be up to date so the command is not run:
>>> run_if( f'touch {out}', out, caller=0)
pipcl.py:run_if(): Not running command because up to date: 'run_if_test_out'
If we change the command, the command is run:
>>> run_if( f'touch {out};', out, caller=0)
pipcl.py:run_if(): Running command because: Command has changed:
pipcl.py:run_if(): @@ -1,2 +1,2 @@
pipcl.py:run_if(): touch
pipcl.py:run_if(): -run_if_test_out
pipcl.py:run_if(): +run_if_test_out;
pipcl.py:run_if():
pipcl.py:run_if(): Running: touch run_if_test_out;
True
If we add a prerequisite that is newer than the output, the command is run:
>>> time.sleep(1)
>>> prerequisite = 'run_if_test_prerequisite'
>>> run( f'touch {prerequisite}', caller=0)
pipcl.py:run(): Running: touch run_if_test_prerequisite
>>> run_if( f'touch {out}', out, prerequisite, caller=0)
pipcl.py:run_if(): Running command because: Command has changed:
pipcl.py:run_if(): @@ -1,2 +1,2 @@
pipcl.py:run_if(): touch
pipcl.py:run_if(): -run_if_test_out;
pipcl.py:run_if(): +run_if_test_out
pipcl.py:run_if():
pipcl.py:run_if(): Running: touch run_if_test_out
True
If we repeat, the output will be newer than the prerequisite, so the
command is not run:
>>> run_if( f'touch {out}', out, prerequisite, caller=0)
pipcl.py:run_if(): Not running command because up to date: 'run_if_test_out'
We detect changes to the contents of argv[0]:
Create a shell script and run it:
>>> _ = subprocess.run('rm run_if_test_argv0.* 1>/dev/null 2>/dev/null || true', shell=1)
>>> with open('run_if_test_argv0.sh', 'w') as f:
... print('#! /bin/sh', file=f)
... print('echo hello world > run_if_test_argv0.out', file=f)
>>> _ = subprocess.run(f'chmod u+x run_if_test_argv0.sh', shell=1)
>>> run_if( f'./run_if_test_argv0.sh', f'run_if_test_argv0.out', caller=0)
pipcl.py:run_if(): Running command because: File does not exist: 'run_if_test_argv0.out'
pipcl.py:run_if(): Running: ./run_if_test_argv0.sh
True
Running it a second time does nothing:
>>> run_if( f'./run_if_test_argv0.sh', f'run_if_test_argv0.out', caller=0)
pipcl.py:run_if(): Not running command because up to date: 'run_if_test_argv0.out'
Modify the script.
>>> with open('run_if_test_argv0.sh', 'a') as f:
... print('\\necho hello >> run_if_test_argv0.out', file=f)
And now it is run because the hash of argv[0] has changed:
>>> run_if( f'./run_if_test_argv0.sh', f'run_if_test_argv0.out', caller=0)
pipcl.py:run_if(): Running command because: arg0 hash has changed.
pipcl.py:run_if(): Running: ./run_if_test_argv0.sh
True
'''
doit = False
# Path of file containing pickle data for command and hash of command's
# first arg.
cmd_path = f'{out}.cmd'
def hash_get(path):
try:
with open(path, 'rb') as f:
return hashlib.md5(f.read()).hexdigest()
except Exception as e:
#log(f'Failed to get hash of {path=}: {e}')
return None
command_args = shlex.split(command or '')
command_arg0_path = fs_find_in_paths(command_args[0])
command_arg0_hash = hash_get(command_arg0_path)
cmd_args, cmd_arg0_hash = (None, None)
if os.path.isfile(cmd_path):
with open(cmd_path, 'rb') as f:
try:
cmd_args, cmd_arg0_hash = pickle.load(f)
except Exception as e:
#log(f'pickle.load() failed with {cmd_path=}: {e}')
pass
if not doit:
# Set doit if outfile does not exist.
out_mtime = _fs_mtime( out)
if out_mtime == 0:
doit = f'File does not exist: {out!r}'
if not doit:
# Set doit if command has changed.
if command_args != cmd_args:
if cmd_args is None:
doit = 'No previous command stored'
else:
doit = f'Command has changed'
if 0:
doit += f':\n {cmd!r}\n {command!r}'
if 0:
doit += f'\nbefore:\n'
doit += textwrap.indent(cmd, ' ')
doit += f'\nafter:\n'
doit += textwrap.indent(command, ' ')
if 1:
# Show diff based on commands split into pseudo lines by
# shlex.split().
doit += ':\n'
lines = difflib.unified_diff(
cmd_args,
command_args,
lineterm='',
)
# Skip initial lines.
assert next(lines) == '--- '
assert next(lines) == '+++ '
for line in lines:
doit += f' {line}\n'
if not doit:
# Set doit if argv[0] hash has changed.
#print(f'{cmd_arg0_hash=} {command_arg0_hash=}', file=sys.stderr)
if command_arg0_hash != cmd_arg0_hash:
doit = f'arg0 hash has changed.'
#doit = f'arg0 hash has changed from {cmd_arg0_hash=} to {command_arg0_hash=}..'
if not doit:
# See whether any prerequisites are newer than target.
def _make_prerequisites(p):
if isinstance( p, (list, tuple)):
return list(p)
else:
return [p]
prerequisites_all = list()
for p in prerequisites:
prerequisites_all += _make_prerequisites( p)
if 0:
log2( 'prerequisites_all:', caller=caller+1)
for i in prerequisites_all:
log2( f' {i!r}', caller=caller+1)
pre_mtime = 0
pre_path = None
for prerequisite in prerequisites_all:
if isinstance( prerequisite, str):
mtime = _fs_mtime_newest( prerequisite)
if mtime >= pre_mtime:
pre_mtime = mtime
pre_path = prerequisite
elif prerequisite is None:
pass
elif prerequisite:
doit = str(prerequisite)
break
if not doit:
if pre_mtime > out_mtime:
doit = f'Prerequisite is new: {os.path.abspath(pre_path)!r}'
if doit:
# Remove `cmd_path` before we run the command, so any failure
# will force rerun next time.
#
try:
os.remove( cmd_path)
except Exception:
pass
log1( f'Running command because: {doit}', caller=caller+1)
run( command, caller=caller+1)
# Write the command we ran, into `cmd_path`.
with open(cmd_path, 'wb') as f:
pickle.dump((command_args, command_arg0_hash), f)
return True
else:
log1( f'Not running command because up to date: {out!r}', caller=caller+1)
if 0:
log2( f'out_mtime={time.ctime(out_mtime)} pre_mtime={time.ctime(pre_mtime)}.'
f' pre_path={pre_path!r}: returning {ret!r}.'
)
def fs_find_in_paths( name, paths=None, verbose=False):
'''
Looks for `name` in paths and returns complete path. `paths` is list/tuple
or `os.pathsep`-separated string; if `None` we use `$PATH`. If `name`
contains `/`, we return `name` itself if it is a file or None, regardless
of <paths>.
'''
if '/' in name:
return name if os.path.isfile( name) else None
if paths is None:
paths = os.environ.get( 'PATH', '')
if verbose:
log('From os.environ["PATH"]: {paths=}')
if isinstance( paths, str):
paths = paths.split( os.pathsep)
if verbose:
log('After split: {paths=}')
for path in paths:
p = os.path.join( path, name)
if verbose:
log('Checking {p=}')
if os.path.isfile( p):
if verbose:
log('Returning because is file: {p!r}')
return p
if verbose:
log('Returning None because not found: {name!r}')
def _get_prerequisites(path):
'''
Returns list of prerequisites from Makefile-style dependency file, e.g.
created by `cc -MD -MF <path>`.
'''
ret = list()
if os.path.isfile(path):
with open(path) as f:
for line in f:
for item in line.split():
if item.endswith( (':', '\\')):
continue
ret.append( item)
return ret
def _fs_mtime_newest( path):
'''
path:
If a file, returns mtime of the file. If a directory, returns mtime of
newest file anywhere within directory tree. Otherwise returns 0.
'''
ret = 0
if os.path.isdir( path):
for dirpath, dirnames, filenames in os.walk( path):
for filename in filenames:
path = os.path.join( dirpath, filename)
ret = max( ret, _fs_mtime( path))
else:
ret = _fs_mtime( path)
return ret
def _flags( items, prefix='', quote=''):
'''
Turns sequence into string, prefixing/quoting each item.
'''
if not items:
return ''
if isinstance( items, str):
items = items,
ret = ''
for item in items:
if ret:
ret += ' '
ret += f'{prefix}{quote}{item}{quote}'
return ret.strip()
def _fs_mtime( filename, default=0):
'''
Returns mtime of file, or `default` if error - e.g. doesn't exist.
'''
try:
return os.path.getmtime( filename)
except OSError:
return default
def _normalise(name):
# https://packaging.python.org/en/latest/specifications/name-normalization/#name-normalization
return re.sub(r"[-_.]+", "-", name).lower()
def _normalise2(name):
# https://packaging.python.org/en/latest/specifications/binary-distribution-format/
return _normalise(name).replace('-', '_')
def _assert_version_pep_440(version):
assert re.match(
r'^([1-9][0-9]*!)?(0|[1-9][0-9]*)(\.(0|[1-9][0-9]*))*((a|b|rc)(0|[1-9][0-9]*))?(\.post(0|[1-9][0-9]*))?(\.dev(0|[1-9][0-9]*))?$',
version,
), \
f'Bad version: {version!r}.'
g_verbose = int(os.environ.get('PIPCL_VERBOSE', '1'))
def verbose(level=None):
'''
Sets verbose level if `level` is not None.
Returns verbose level.
'''
global g_verbose
if level is not None:
g_verbose = level
return g_verbose
g_log_line_numbers = True
def log_line_numbers(yes):
'''
Sets whether to include line numbers; helps with doctest.
'''
global g_log_line_numbers
g_log_line_numbers = bool(yes)
def log(text='', caller=1):
_log(text, 0, caller+1)
def log0(text='', caller=1):
_log(text, 0, caller+1)
def log1(text='', caller=1):
_log(text, 1, caller+1)
def log2(text='', caller=1):
_log(text, 2, caller+1)
def _log(text, level, caller):
'''
Logs lines with prefix, if <level> is lower or equal to <g_verbose>.
'''
if level <= g_verbose:
fr = inspect.stack(context=0)[caller]
filename = relpath(fr.filename)
for line in text.split('\n'):
if g_log_line_numbers:
print(f'{filename}:{fr.lineno}:{fr.function}(): {line}', file=sys.stdout, flush=1)
else:
print(f'{filename}:{fr.function}(): {line}', file=sys.stdout, flush=1)
def relpath(path, start=None, allow_up=True):
'''
A safe alternative to os.path.relpath(), avoiding an exception on Windows
if the drive needs to change - in this case we use os.path.abspath().
Args:
path:
Path to be processed.
start:
Start directory or current directory if None.
allow_up:
If false we return absolute path is <path> is not within <start>.
'''
if windows():
try:
ret = os.path.relpath(path, start)
except ValueError:
# os.path.relpath() fails if trying to change drives.
ret = os.path.abspath(path)
else:
ret = os.path.relpath(path, start)
if not allow_up and ret.startswith('../') or ret.startswith('..\\'):
ret = os.path.abspath(path)
return ret
def _so_suffix(use_so_versioning=True):
'''
Filename suffix for shared libraries is defined in pep-3149. The
pep claims to only address posix systems, but the recommended
sysconfig.get_config_var('EXT_SUFFIX') also seems to give the
right string on Windows.
If use_so_versioning is false, we return only the last component of
the suffix, which removes any version number, for example changing
`.cp312-win_amd64.pyd` to `.pyd`.
'''
# Example values:
# linux: .cpython-311-x86_64-linux-gnu.so
# macos: .cpython-311-darwin.so
# openbsd: .cpython-310.so
# windows .cp311-win_amd64.pyd
#
# Only Linux and Windows seem to identify the cpu. For example shared
# libraries in numpy-1.25.2-cp311-cp311-macosx_11_0_arm64.whl are called
# things like `numpy/core/_simd.cpython-311-darwin.so`.
#
ret = sysconfig.get_config_var('EXT_SUFFIX')
if not use_so_versioning:
# Use last component only.
ret = os.path.splitext(ret)[1]
return ret
def get_soname(path):
'''
If we are on Linux and `path` is softlink and points to a shared library
for which `objdump -p` contains 'SONAME', return the pointee. Otherwise
return `path`. Useful if Linux shared libraries have been created with
`-Wl,-soname,...`, where we need to embed the versioned library.
'''
if linux() and os.path.islink(path):
path2 = os.path.realpath(path)
if subprocess.run(f'objdump -p {path2}|grep SONAME', shell=1, check=0).returncode == 0:
return path2
elif openbsd():
# Return newest .so with version suffix.
sos = glob.glob(f'{path}.*')
log1(f'{sos=}')
sos2 = list()
for so in sos:
suffix = so[len(path):]
if not suffix or re.match('^[.][0-9.]*[0-9]$', suffix):
sos2.append(so)
sos2.sort(key=lambda p: os.path.getmtime(p))
log1(f'{sos2=}')
return sos2[-1]
return path
def current_py_limited_api():
'''
Returns value of PyLIMITED_API to build for current Python.
'''
a, b = map(int, platform.python_version().split('.')[:2])
return f'0x{a:02x}{b:02x}0000'
def install_dir(root=None):
'''
Returns install directory used by `install()`.
This will be `sysconfig.get_path('platlib')`, modified by `root` if not
None.
'''
# todo: for pure-python we should use sysconfig.get_path('purelib') ?
root2 = sysconfig.get_path('platlib')
if root:
if windows():
# If we are in a venv, `sysconfig.get_path('platlib')`
# can be absolute, e.g.
# `C:\\...\\venv-pypackage-3.11.1-64\\Lib\\site-packages`, so it's
# not clear how to append it to `root`. So we just use `root`.
return root
else:
# E.g. if `root` is `install' and `sysconfig.get_path('platlib')`
# is `/usr/local/lib/python3.9/site-packages`, we set `root2` to
# `install/usr/local/lib/python3.9/site-packages`.
#
return os.path.join( root, root2.lstrip( os.sep))
else:
return root2
| PythonFlags |
python | modin-project__modin | modin/core/storage_formats/pandas/merge.py | {
"start": 1381,
"end": 13122
} | class ____:
"""Provide implementations for merge/join."""
@classmethod
def range_partitioning_merge(cls, left, right, kwargs):
"""
Execute merge using range-partitioning implementation.
Parameters
----------
left : PandasQueryCompiler
right : PandasQueryCompiler
kwargs : dict
Keyword arguments for ``pandas.merge()`` function.
Returns
-------
PandasQueryCompiler
"""
if (
kwargs.get("left_index", False)
or kwargs.get("right_index", False)
or kwargs.get("left_on", None) is not None
or kwargs.get("left_on", None) is not None
or kwargs.get("how", "left") not in ("left", "inner")
):
raise NotImplementedError(
f"The passed parameters are not yet supported by range-partitioning merge: {kwargs=}"
)
on = kwargs.get("on", None)
if on is not None and not isinstance(on, list):
on = [on]
if on is None or len(on) > 1:
raise NotImplementedError(
f"Merging on multiple columns is not yet supported by range-partitioning merge: {on=}"
)
if any(col not in left.columns or col not in right.columns for col in on):
raise NotImplementedError(
"Merging on an index level is not yet supported by range-partitioning merge."
)
def func(left, right):
return left.merge(right, **kwargs)
new_columns, new_dtypes = cls._compute_result_metadata(
left,
right,
on,
left_on=None,
right_on=None,
suffixes=kwargs.get("suffixes", ("_x", "_y")),
)
return left.__constructor__(
left._modin_frame._apply_func_to_range_partitioning_broadcast(
right._modin_frame,
func=func,
key=on,
new_columns=new_columns,
new_dtypes=new_dtypes,
)
# pandas resets the index of the result unless we were merging on an index level,
# the current implementation only supports merging on column names, so dropping
# the index unconditionally
).reset_index(drop=True)
@classmethod
def row_axis_merge(
cls, left: PandasQueryCompiler, right: PandasQueryCompiler, kwargs: dict
) -> PandasQueryCompiler:
"""
Execute merge using row-axis implementation.
Parameters
----------
left : PandasQueryCompiler
right : PandasQueryCompiler
kwargs : dict
Keyword arguments for ``pandas.merge()`` function.
Returns
-------
PandasQueryCompiler
"""
how = kwargs.get("how", "inner")
on = kwargs.get("on", None)
left_on = kwargs.get("left_on", None)
right_on = kwargs.get("right_on", None)
left_index = kwargs.get("left_index", False)
right_index = kwargs.get("right_index", False)
sort = kwargs.get("sort", False)
if (
(
how in ["left", "inner"]
or (how == "right" and right._modin_frame._partitions.size != 0)
)
and left_index is False
and right_index is False
):
kwargs["sort"] = False
reverted = False
if how == "right":
left, right = right, left
reverted = True
def should_keep_index(
left: PandasQueryCompiler,
right: PandasQueryCompiler,
) -> bool:
keep_index = False
if left_on is not None and right_on is not None:
keep_index = any(
o in left.index.names
and o in right_on
and o in right.index.names
for o in left_on
)
elif on is not None:
keep_index = any(
o in left.index.names and o in right.index.names for o in on
)
return keep_index
def map_func(
left, right, kwargs=kwargs
) -> pandas.DataFrame: # pragma: no cover
if reverted:
df = pandas.merge(right, left, **kwargs)
else:
df = pandas.merge(left, right, **kwargs)
return df
# Want to ensure that these are python lists
if left_on is not None and right_on is not None:
left_on = list(left_on) if is_list_like(left_on) else [left_on]
right_on = list(right_on) if is_list_like(right_on) else [right_on]
elif on is not None:
on = list(on) if is_list_like(on) else [on]
right_to_broadcast = right._modin_frame.combine()
new_columns, new_dtypes = cls._compute_result_metadata(
*((left, right) if not reverted else (right, left)),
on,
left_on,
right_on,
kwargs.get("suffixes", ("_x", "_y")),
)
# We rebalance when the ratio of the number of existing partitions to
# the ideal number of partitions is smaller than this threshold. The
# threshold is a heuristic that may need to be tuned for performance.
if (
left._modin_frame._partitions.shape[0] < 0.3 * NPartitions.get()
# to avoid empty partitions after repartition; can materialize index
and len(left._modin_frame)
> NPartitions.get() * MinRowPartitionSize.get()
):
left = left.repartition(axis=0)
new_left = left.__constructor__(
left._modin_frame.broadcast_apply_full_axis(
axis=1,
func=map_func,
other=right_to_broadcast,
# We're going to explicitly change the shape across the 1-axis,
# so we want for partitioning to adapt as well
keep_partitioning=False,
num_splits=merge_partitioning(
left._modin_frame, right._modin_frame, axis=1
),
new_columns=new_columns,
sync_labels=False,
dtypes=new_dtypes,
)
)
# Here we want to understand whether we're joining on a column or on an index level.
# It's cool if indexes are already materialized so we can easily check that, if not
# it's fine too, we can also decide that by columns, which tend to be already
# materialized quite often compared to the indexes.
keep_index = False
if left.frame_has_materialized_index:
keep_index = should_keep_index(left, right)
else:
# Have to trigger columns materialization. Hope they're already available at this point.
if left_on is not None and right_on is not None:
keep_index = any(
o not in right.columns
and o in left_on
and o not in left.columns
for o in right_on
)
elif on is not None:
keep_index = any(
o not in right.columns and o not in left.columns for o in on
)
if sort:
if left_on is not None and right_on is not None:
new_left = (
new_left.sort_index(axis=0, level=left_on + right_on)
if keep_index
else new_left.sort_rows_by_column_values(left_on + right_on)
)
elif on is not None:
new_left = (
new_left.sort_index(axis=0, level=on)
if keep_index
else new_left.sort_rows_by_column_values(on)
)
return new_left if keep_index else new_left.reset_index(drop=True)
else:
return left.default_to_pandas(pandas.DataFrame.merge, right, **kwargs)
@classmethod
def _compute_result_metadata(
cls,
left: PandasQueryCompiler,
right: PandasQueryCompiler,
on,
left_on,
right_on,
suffixes,
) -> tuple[Optional[pandas.Index], Optional[ModinDtypes]]:
"""
Compute columns and dtypes metadata for the result of merge if possible.
Parameters
----------
left : PandasQueryCompiler
right : PandasQueryCompiler
on : label, list of labels or None
`on` argument that was passed to ``pandas.merge()``.
left_on : label, list of labels or None
`left_on` argument that was passed to ``pandas.merge()``.
right_on : label, list of labels or None
`right_on` argument that was passed to ``pandas.merge()``.
suffixes : list of strings
`suffixes` argument that was passed to ``pandas.merge()``.
Returns
-------
new_columns : pandas.Index or None
Columns for the result of merge. ``None`` if not enought metadata to compute.
new_dtypes : ModinDtypes or None
Dtypes for the result of merge. ``None`` if not enought metadata to compute.
"""
new_columns = None
new_dtypes = None
if not left.frame_has_materialized_columns:
return new_columns, new_dtypes
if left_on is None and right_on is None:
if on is None:
on = [c for c in left.columns if c in right.columns]
_left_on, _right_on = on, on
else:
if left_on is None or right_on is None:
raise MergeError(
"Must either pass only 'on' or 'left_on' and 'right_on', not combination of them."
)
_left_on, _right_on = left_on, right_on
try:
new_columns, left_renamer, right_renamer = join_columns(
left.columns,
right.columns,
_left_on,
_right_on,
suffixes,
)
except NotImplementedError:
# This happens when one of the keys to join is an index level. Pandas behaviour
# is really complicated in this case, so we're not computing resulted columns for now.
pass
else:
# renamers may contain columns from 'index', so trying to merge index and column dtypes here
right_index_dtypes = (
right.index.dtypes
if isinstance(right.index, pandas.MultiIndex)
else pandas.Series([right.index.dtype], index=[right.index.name])
)
right_dtypes = pandas.concat([right.dtypes, right_index_dtypes])[
right_renamer.keys()
].rename(right_renamer)
left_index_dtypes = left._modin_frame._index_cache.maybe_get_dtypes()
left_dtypes = (
ModinDtypes.concat([left._modin_frame._dtypes, left_index_dtypes])
.lazy_get(left_renamer.keys())
.set_index(list(left_renamer.values()))
)
new_dtypes = ModinDtypes.concat([left_dtypes, right_dtypes])
return new_columns, new_dtypes
| MergeImpl |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_excel2003_style07.py | {
"start": 315,
"end": 1174
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("excel2003_style07.xlsx")
self.ignore_elements = {
"xl/drawings/drawing1.xml": [
"<xdr:cNvPr",
"<a:picLocks",
"<a:srcRect/>",
"<xdr:spPr",
"<a:noFill/>",
]
}
def test_create_file(self):
"""Test the creation of a simple XlsxWriter file."""
workbook = Workbook(self.got_filename, {"excel2003_style": True})
worksheet = workbook.add_worksheet()
worksheet.insert_image(
"B3", self.image_dir + "yellow.jpg", {"x_offset": 4, "y_offset": 3}
)
workbook.close()
self.assertExcelEqual()
| TestCompareXLSXFiles |
python | boto__boto3 | boto3/docs/client.py | {
"start": 614,
"end": 1003
} | class ____(ClientDocumenter):
def _add_client_creation_example(self, section):
section.style.start_codeblock()
section.style.new_line()
section.write('import boto3')
section.style.new_line()
section.style.new_line()
section.write(f'client = boto3.client(\'{self._service_name}\')')
section.style.end_codeblock()
| Boto3ClientDocumenter |
python | kubernetes-client__python | kubernetes/base/config/kube_config.py | {
"start": 2657,
"end": 5616
} | class ____(object):
"""Utility class to read content of obj[%data_key_name] or file's
content of obj[%file_key_name] and represent it as file or data.
Note that the data is preferred. The obj[%file_key_name] will be used iff
obj['%data_key_name'] is not set or empty. Assumption is file content is
raw data and data field is base64 string. The assumption can be changed
with base64_file_content flag. If set to False, the content of the file
will assumed to be base64 and read as is. The default True value will
result in base64 encode of the file content after read."""
def __init__(self, obj, file_key_name, data_key_name=None,
file_base_path="", base64_file_content=True,
temp_file_path=None):
if not data_key_name:
data_key_name = file_key_name + "-data"
self._file = None
self._data = None
self._base64_file_content = base64_file_content
self._temp_file_path = temp_file_path
if not obj:
return
if data_key_name in obj:
self._data = obj[data_key_name]
elif file_key_name in obj:
self._file = os.path.normpath(
os.path.join(file_base_path, obj[file_key_name]))
def as_file(self):
"""If obj[%data_key_name] exists, return name of a file with base64
decoded obj[%data_key_name] content otherwise obj[%file_key_name]."""
use_data_if_no_file = not self._file and self._data
if use_data_if_no_file:
self._write_file()
if self._file and not os.path.isfile(self._file):
self._write_file(force_rewrite=True)
if self._file and not os.path.isfile(self._file):
raise ConfigException("File does not exist: %s" % self._file)
return self._file
def as_data(self):
"""If obj[%data_key_name] exists, Return obj[%data_key_name] otherwise
base64 encoded string of obj[%file_key_name] file content."""
use_file_if_no_data = not self._data and self._file
if use_file_if_no_data:
with open(self._file) as f:
if self._base64_file_content:
self._data = bytes.decode(
base64.standard_b64encode(str.encode(f.read())))
else:
self._data = f.read()
return self._data
def _write_file(self, force_rewrite=False):
if self._base64_file_content:
if isinstance(self._data, str):
content = self._data.encode()
else:
content = self._data
self._file = _create_temp_file_with_content(
base64.standard_b64decode(content), self._temp_file_path, force_recreate=force_rewrite)
else:
self._file = _create_temp_file_with_content(
self._data, self._temp_file_path, force_recreate=force_rewrite)
| FileOrData |
python | jmcnamara__XlsxWriter | xlsxwriter/test/comparison/test_chart_pattern10.py | {
"start": 315,
"end": 2203
} | class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("chart_pattern10.xlsx")
def test_create_file(self):
"""Test the creation of a simple XlsxWriter file."""
workbook = Workbook(self.got_filename)
worksheet = workbook.add_worksheet()
chart = workbook.add_chart({"type": "column"})
chart.axis_ids = [143227136, 143245312]
data = [
[2, 2, 2],
[2, 2, 2],
[2, 2, 2],
[2, 2, 2],
[2, 2, 2],
[2, 2, 2],
[2, 2, 2],
[2, 2, 2],
]
worksheet.write_column("A1", data[0])
worksheet.write_column("B1", data[1])
worksheet.write_column("C1", data[2])
worksheet.write_column("D1", data[3])
worksheet.write_column("E1", data[4])
worksheet.write_column("F1", data[5])
worksheet.write_column("G1", data[6])
worksheet.write_column("H1", data[7])
chart.add_series({"values": "=Sheet1!$A$1:$A$3"})
chart.add_series({"values": "=Sheet1!$B$1:$B$3"})
chart.add_series({"values": "=Sheet1!$C$1:$C$3"})
chart.add_series({"values": "=Sheet1!$D$1:$D$3"})
chart.add_series({"values": "=Sheet1!$E$1:$E$3"})
chart.add_series({"values": "=Sheet1!$F$1:$F$3"})
chart.add_series({"values": "=Sheet1!$G$1:$G$3"})
chart.add_series({"values": "=Sheet1!$H$1:$H$3"})
chart.set_plotarea(
{
"pattern": {
"pattern": "percent_5",
"fg_color": "red",
"bg_color": "yellow",
}
}
)
worksheet.insert_chart("E9", chart)
workbook.close()
self.assertExcelEqual()
| TestCompareXLSXFiles |
python | astropy__astropy | astropy/utils/masked/tests/test_functions.py | {
"start": 22085,
"end": 26434
} | class ____:
"""Test with structure dtypes, using erfa ufuncs."""
def test_erfa_d2tf_tf2d(self):
mask = np.array([True, False, False])
days = Masked([0.25, 0.875, 0.0625], mask=mask)
sign, ihmsf = erfa_ufunc.d2tf(3, days)
assert_array_equal(sign.mask["sign"], mask)
sign = sign.view("S1") # Like is done by the erfa wrapper.
assert_array_equal(sign.mask, mask)
for name in ihmsf.dtype.names:
assert_array_equal(ihmsf[name].mask, mask)
# Check roundtrip.
check, stat = erfa_ufunc.tf2d(
sign, ihmsf["h"], ihmsf["m"], ihmsf["s"] + ihmsf["f"]
)
assert_allclose(check.unmasked, days, atol=1e-3 / 24 / 3600)
assert_array_equal(check.mask, mask)
assert_array_equal(stat.unmasked, 0)
assert_array_equal(stat.mask, mask)
def test_erfa_astrom(self):
mask = np.array([True, False, False])
jd2 = Masked([0, 0.401182685, 0.5], mask=mask)
astrom, eo = erfa_ufunc.apci13(2456165.5, jd2)
assert_array_equal(eo.mask, mask)
for n in astrom.dtype.names:
# .T for multi-element fields.
assert np.all(astrom[n].mask.T == mask)
along = np.array([0.125, 0.25, 0.35])
# Not going to worry about different masks for different elements.
# In principle aper could propagate just what it needs.
astrom["along"] = Masked([0.125, 0.25, 0.35], mask)
astrom2 = erfa_ufunc.aper(Masked(np.ones(3), [False, True, False]), astrom)
assert_array_equal(astrom2["eral"].unmasked, along + 1.0)
mask2 = mask | [False, True, False]
for n in astrom2.dtype.names:
# .T for multi-element fields.
assert np.all(astrom2[n].mask.T == mask2)
def test_erfa_atioq(self):
# Regression test for gh-16123, using test from erfa.
astrom, _ = erfa_ufunc.apio13(
2456384.5,
0.969254051,
0.1550675,
-0.527800806,
-1.2345856,
2738.0,
2.47230737e-7,
1.82640464e-6,
731.0,
12.8,
0.59,
0.55,
)
astrom = Masked(astrom)
ri = 2.710121572969038991
di = 0.1729371367218230438
aob, zob, hob, dob, rob = erfa_ufunc.atioq(ri, di, astrom)
assert isinstance(aob, Masked)
# Really should not need to check the values, since done
# in units/tests/test_quantity_erfa_ufuncs, but why not...
assert_allclose(aob, 0.9233952224895122499e-1, atol=1e-12, rtol=0)
assert_allclose(zob, 1.407758704513549991, atol=1e-12, rtol=0)
assert_allclose(hob, -0.9247619879881698140e-1, atol=1e-12, rtol=0)
assert_allclose(dob, 0.1717653435756234676, atol=1e-12, rtol=0)
assert_allclose(rob, 2.710085107988480746, atol=1e-12, rtol=0)
def test_erfa_no_warnings_on_masked_entries():
# Erfa warns for invalid inputs for some routines.
msg = 'ERFA function "tf2d" yielded {count} of "ihour outside range 0-23"'
ihour1 = [25, 26, 10]
with pytest.warns(erfa.ErfaWarning, match=msg.format(count=2)):
res1 = erfa.tf2d("+", ihour1, 0, 0.0)
# But will not if they are masked.
mask = [True, True, False]
ihour2 = Masked(ihour1, mask)
res2 = erfa.tf2d("+", ihour2, 0, 0.0)
assert_array_equal(res2.unmasked, res1)
assert_array_equal(res2.mask, mask)
# And will count correctly.
mask = [True, False, False]
ihour3 = Masked(ihour1, mask)
count = 1 if minversion(erfa, "2.0.1.1", inclusive=False) else "—"
with pytest.warns(erfa.ErfaWarning, match=msg.format(count=count)):
res3 = erfa.tf2d("+", ihour3, 0, 0.0)
assert_array_equal(res3.unmasked, res1)
assert_array_equal(res3.mask, mask)
def test_erfa_no_exceptions_on_masked_entries():
# Erfa raises exceptions for invalid inputs in some routines.
iday1 = [25, 30]
with pytest.raises(erfa.ErfaError, match="bad day"):
erfa.dat(2000, 2, iday1, 0.0)
# But will not if they are masked.
mask = [False, True]
iday2 = Masked(iday1, mask)
res = erfa.dat(2000, 2, iday2, 0.0)
exp1 = erfa.dat(2000, 2, iday1[0], 0.0)
assert_array_equal(res.unmasked[0], exp1)
assert_array_equal(res.mask, mask)
| TestStructuredUfuncs |
python | huggingface__transformers | src/transformers/models/unispeech/modeling_unispeech.py | {
"start": 43240,
"end": 48498
} | class ____(UniSpeechPreTrainedModel):
def __init__(self, config: UniSpeechConfig):
super().__init__(config)
self.unispeech = UniSpeechModel(config)
self.dropout_features = nn.Dropout(config.feat_quantizer_dropout)
self.quantizer = UniSpeechGumbelVectorQuantizer(config)
self.project_q = nn.Linear(config.codevector_dim, config.proj_codevector_dim)
self.project_hid = nn.Linear(config.proj_codevector_dim, config.hidden_size)
self.ctc_proj = nn.Linear(config.hidden_size, config.num_ctc_classes)
self.dropout = nn.Dropout(config.final_dropout)
# Initialize weights and apply final processing
self.post_init()
def set_gumbel_temperature(self, temperature: int):
"""
Set the Gumbel softmax temperature to a given value. Only necessary for training
"""
self.quantizer.temperature = temperature
def freeze_feature_encoder(self):
"""
Calling this function will disable the gradient computation for the feature encoder so that its parameter will
not be updated during training.
"""
self.unispeech.feature_extractor._freeze_parameters()
@staticmethod
def compute_contrastive_logits(
target_features: torch.FloatTensor,
negative_features: torch.FloatTensor,
predicted_features: torch.FloatTensor,
temperature: int = 1,
):
"""
Compute logits for contrastive loss based using cosine similarity as the distance measure between
`[positive_feature, negative_features]` and `[predicted_features]`. Additionally, temperature can be applied.
"""
target_features = torch.cat([target_features, negative_features], dim=0)
logits = torch.cosine_similarity(predicted_features.float(), target_features.float(), dim=-1)
logits = logits.type_as(target_features)
# apply temperature
logits = logits / temperature
return logits
@auto_docstring
def forward(
self,
input_values: Optional[torch.Tensor],
attention_mask: Optional[torch.Tensor] = None,
output_attentions: Optional[bool] = None,
output_hidden_states: Optional[bool] = None,
return_dict: Optional[bool] = None,
) -> Union[tuple, UniSpeechForPreTrainingOutput]:
r"""
Example:
```python
>>> import torch
>>> from transformers import AutoFeatureExtractor, UniSpeechForPreTraining
>>> feature_extractor = AutoFeatureExtractor.from_pretrained("microsoft/unispeech-large-1500h-cv")
>>> model = UniSpeechForPreTraining.from_pretrained("microsoft/unispeech-large-1500h-cv")
>>> # TODO: Add full pretraining example
```"""
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
outputs = self.unispeech(
input_values,
attention_mask=attention_mask,
output_attentions=output_attentions,
output_hidden_states=output_hidden_states,
return_dict=return_dict,
)
transformer_features = outputs[0]
# quantize all (unmasked) extracted features and project to final vq dim
extract_features = self.dropout_features(outputs[1])
quantized_features, codevector_perplexity = self.quantizer(extract_features)
# project quantized features twice
quantized_features = self.project_q(quantized_features.to(self.project_q.weight.dtype))
quantized_features = self.project_hid(quantized_features)
prob_replace_matrix = torch.empty(transformer_features.size(0), transformer_features.size(1)).fill_(
self.config.replace_prob
)
prob_replace_matrix = prob_replace_matrix.transpose(0, 1)
sampled_replace_matrix = torch.bernoulli(prob_replace_matrix).bool().to(transformer_features.device)
sampled_replace_matrix = sampled_replace_matrix.transpose(0, 1)
sampled_replace_matrix = sampled_replace_matrix.unsqueeze(-1)
logits = transformer_features.masked_fill(sampled_replace_matrix, 0.0) + (
quantized_features.masked_fill(~sampled_replace_matrix, 0.0)
)
# project to ctc units
logits = self.dropout(logits)
logits = self.ctc_proj(logits)
# TODO(PVP) - add negative sampling & loss computation
loss = None
if not return_dict:
if loss is not None:
return (loss, transformer_features, quantized_features, codevector_perplexity) + outputs[2:]
return (transformer_features, quantized_features, codevector_perplexity) + outputs[2:]
return UniSpeechForPreTrainingOutput(
loss=loss,
projected_states=transformer_features,
projected_quantized_states=quantized_features,
codevector_perplexity=codevector_perplexity,
hidden_states=outputs.hidden_states,
attentions=outputs.attentions,
)
_HIDDEN_STATES_START_POSITION = 2
@auto_docstring(
custom_intro="""
UniSpeech Model with a `language modeling` head on top for Connectionist Temporal Classification (CTC).
"""
)
| UniSpeechForPreTraining |
python | getsentry__sentry | tests/sentry/monitors/endpoints/test_base_monitor_details.py | {
"start": 1142,
"end": 8674
} | class ____(MonitorTestCase):
__test__ = False
def setUp(self) -> None:
super().setUp()
self.login_as(user=self.user)
def test_simple(self) -> None:
monitor = self._create_monitor()
resp = self.get_success_response(self.organization.slug, monitor.slug)
assert resp.data["slug"] == monitor.slug
def test_simple_with_id(self) -> None:
monitor = self._create_monitor()
resp = self.get_success_response(self.organization.slug, monitor.slug)
assert resp.data["slug"] == monitor.slug
resp = self.get_success_response(self.organization.slug, monitor.guid)
assert resp.data["slug"] == monitor.slug
self.get_error_response(self.organization.slug, "asdf", status_code=404)
uuid = UUID("00000000-0000-0000-0000-000000000000")
self.get_error_response(self.organization.slug, uuid, status_code=404)
def test_simple_with_uuid_like_slug(self) -> None:
"""
When the slug looks like a UUID we still want to make sure we're
prioritizing slug lookup
"""
monitor = self._create_monitor(slug="8a65d0f2-b7d9-4b4a-9436-3de9db3c9e2f")
# We can still find our monitor by it's slug
resp = self.get_success_response(self.organization.slug, monitor.slug)
assert resp.data["slug"] == monitor.slug
# We can still find our monitor by it's id
resp = self.get_success_response(self.organization.slug, monitor.guid)
assert resp.data["slug"] == monitor.slug
def test_mismatched_org_slugs(self) -> None:
monitor = self._create_monitor()
self.get_error_response("asdf", monitor.slug, status_code=404)
def test_monitor_environment(self) -> None:
monitor = self._create_monitor()
self._create_monitor_environment(monitor)
self.get_success_response(self.organization.slug, monitor.slug, environment="production")
self.get_error_response(
self.organization.slug, monitor.slug, environment="jungle", status_code=404
)
def test_filtering_monitor_environment(self) -> None:
monitor = self._create_monitor()
prod_env = "production"
prod = self._create_monitor_environment(monitor, name=prod_env)
jungle_env = "jungle"
jungle = self._create_monitor_environment(monitor, name=jungle_env)
response = self.get_success_response(self.organization.slug, monitor.slug)
result_envs = response.data["environments"]
result_envs.sort(key=lambda env: env["name"])
assert result_envs == [
{
"name": jungle_env,
"status": jungle.get_status_display(),
"isMuted": jungle.is_muted,
"dateCreated": jungle.monitor.date_added,
"lastCheckIn": jungle.last_checkin,
"nextCheckIn": jungle.next_checkin,
"nextCheckInLatest": jungle.next_checkin_latest,
"activeIncident": None,
},
{
"name": prod_env,
"status": prod.get_status_display(),
"isMuted": prod.is_muted,
"dateCreated": prod.monitor.date_added,
"lastCheckIn": prod.last_checkin,
"nextCheckIn": prod.next_checkin,
"nextCheckInLatest": prod.next_checkin_latest,
"activeIncident": None,
},
]
response = self.get_success_response(
self.organization.slug, monitor.slug, environment="production"
)
assert response.data["environments"] == [
{
"name": prod_env,
"status": prod.get_status_display(),
"isMuted": prod.is_muted,
"dateCreated": prod.monitor.date_added,
"lastCheckIn": prod.last_checkin,
"nextCheckIn": prod.next_checkin,
"nextCheckInLatest": prod.next_checkin_latest,
"activeIncident": None,
}
]
def test_expand_issue_alert_rule(self) -> None:
monitor = self._create_monitor()
resp = self.get_success_response(self.organization.slug, monitor.slug, expand=["alertRule"])
assert resp.data["alertRule"] is None
self._create_issue_alert_rule(monitor)
resp = self.get_success_response(self.organization.slug, monitor.slug, expand=["alertRule"])
issue_alert_rule = resp.data["alertRule"]
assert issue_alert_rule is not None
assert issue_alert_rule["environment"] is not None
def test_with_active_incident_and_detection(self) -> None:
monitor = self._create_monitor()
monitor_env = self._create_monitor_environment(monitor)
resp = self.get_success_response(self.organization.slug, monitor.slug)
assert resp.data["environments"][0]["activeIncident"] is None
starting_timestamp = datetime(2023, 12, 15, tzinfo=timezone.utc)
monitor_incident = MonitorIncident.objects.create(
monitor=monitor, monitor_environment=monitor_env, starting_timestamp=starting_timestamp
)
detection_timestamp = datetime(2024, 1, 1, tzinfo=timezone.utc)
MonitorEnvBrokenDetection.objects.create(
monitor_incident=monitor_incident, user_notified_timestamp=detection_timestamp
)
resp = self.get_success_response(self.organization.slug, monitor.slug)
assert resp.data["environments"][0]["activeIncident"] == {
"startingTimestamp": monitor_incident.starting_timestamp,
"resolvingTimestamp": monitor_incident.resolving_timestamp,
"brokenNotice": {
"userNotifiedTimestamp": detection_timestamp,
"environmentMutedTimestamp": None,
},
}
def test_with_active_incident_no_detection(self) -> None:
monitor = self._create_monitor()
monitor_env = self._create_monitor_environment(monitor)
resp = self.get_success_response(self.organization.slug, monitor.slug)
assert resp.data["environments"][0]["activeIncident"] is None
starting_timestamp = datetime(2023, 12, 15, tzinfo=timezone.utc)
monitor_incident = MonitorIncident.objects.create(
monitor=monitor, monitor_environment=monitor_env, starting_timestamp=starting_timestamp
)
resp = self.get_success_response(self.organization.slug, monitor.slug)
assert resp.data["environments"][0]["activeIncident"] == {
"startingTimestamp": monitor_incident.starting_timestamp,
"resolvingTimestamp": monitor_incident.resolving_timestamp,
"brokenNotice": None,
}
def test_owner_user(self) -> None:
monitor = self._create_monitor()
resp = self.get_success_response(self.organization.slug, monitor.slug)
assert resp.data["owner"] == {
"type": "user",
"id": str(self.user.id),
"email": self.user.email,
"name": self.user.email,
}
def test_owner_team(self) -> None:
monitor = self._create_monitor(
owner_user_id=None,
owner_team_id=self.team.id,
)
resp = self.get_success_response(self.organization.slug, monitor.slug)
assert resp.data["owner"] == {
"type": "team",
"id": str(self.team.id),
"name": self.team.slug,
}
@freeze_time()
| BaseMonitorDetailsTest |
python | yaml__pyyaml | lib/yaml/tokens.py | {
"start": 745,
"end": 807
} | class ____(Token):
id = '<document start>'
| DocumentStartToken |
python | ray-project__ray | doc/source/custom_directives.py | {
"start": 16962,
"end": 18125
} | class ____(ExampleEnum):
"""Library type for example metadata."""
DATA = "Data"
SERVE = "Serve"
TRAIN = "Train"
@classmethod
def formatted_name(cls):
return "Library"
@classmethod
def key(cls: type) -> str:
return "library"
@classmethod
def from_path(cls, path: Union[pathlib.Path, str]) -> "Library":
"""Instantiate a Library instance from a path.
This function works its way up the file tree until it finds a directory that
matches one of the enum types; if none is found, raise an exception.
Parameters
----------
path : Union[pathlib.Path, str]
Path containing a directory named the same as one of the enum types.
Returns
-------
Library
A new Library instance for the given path.
"""
if isinstance(path, str):
path = pathlib.Path(path)
for part in path.parts:
try:
return Library(part)
except ValueError:
continue
raise ValueError(f"Cannot find library name from example config path {path}")
| Library |
python | huggingface__transformers | src/transformers/generation/streamers.py | {
"start": 6280,
"end": 9229
} | class ____(TextStreamer):
"""
Streamer that stores print-ready text in a queue, to be used by a downstream application as an iterator. This is
useful for applications that benefit from accessing the generated text in a non-blocking way (e.g. in an interactive
Gradio demo).
<Tip warning={true}>
The API for the streamer classes is still under development and may change in the future.
</Tip>
Parameters:
tokenizer (`AutoTokenizer`):
The tokenized used to decode the tokens.
skip_prompt (`bool`, *optional*, defaults to `False`):
Whether to skip the prompt to `.generate()` or not. Useful e.g. for chatbots.
timeout (`float`, *optional*):
The timeout for the text queue. If `None`, the queue will block indefinitely. Useful to handle exceptions
in `.generate()`, when it is called in a separate thread.
decode_kwargs (`dict`, *optional*):
Additional keyword arguments to pass to the tokenizer's `decode` method.
Examples:
```python
>>> from transformers import AutoModelForCausalLM, AutoTokenizer, TextIteratorStreamer
>>> from threading import Thread
>>> tok = AutoTokenizer.from_pretrained("openai-community/gpt2")
>>> model = AutoModelForCausalLM.from_pretrained("openai-community/gpt2")
>>> inputs = tok(["An increasing sequence: one,"], return_tensors="pt")
>>> streamer = TextIteratorStreamer(tok)
>>> # Run the generation in a separate thread, so that we can fetch the generated text in a non-blocking way.
>>> generation_kwargs = dict(inputs, streamer=streamer, max_new_tokens=20)
>>> thread = Thread(target=model.generate, kwargs=generation_kwargs)
>>> thread.start()
>>> generated_text = ""
>>> for new_text in streamer:
... generated_text += new_text
>>> generated_text
'An increasing sequence: one, two, three, four, five, six, seven, eight, nine, ten, eleven,'
```
"""
def __init__(
self, tokenizer: AutoTokenizer, skip_prompt: bool = False, timeout: float | None = None, **decode_kwargs
):
super().__init__(tokenizer, skip_prompt, **decode_kwargs)
self.text_queue = Queue()
self.stop_signal = None
self.timeout = timeout
def on_finalized_text(self, text: str, stream_end: bool = False):
"""Put the new text in the queue. If the stream is ending, also put a stop signal in the queue."""
self.text_queue.put(text, timeout=self.timeout)
if stream_end:
self.text_queue.put(self.stop_signal, timeout=self.timeout)
def __iter__(self):
return self
def __next__(self):
value = self.text_queue.get(timeout=self.timeout)
if value == self.stop_signal:
raise StopIteration()
else:
return value
| TextIteratorStreamer |
python | joke2k__faker | faker/providers/phone_number/sv_SE/__init__.py | {
"start": 49,
"end": 367
} | class ____(PhoneNumberProvider):
formats = (
"+46 (0)8 ### ### ##",
"+46 (0)## ## ## ##",
"+46 (0)### ### ##",
"08-### ### ##",
"08-### ## ##",
"08-## ## ##",
"0##-### ## ##",
"0##-## ## ##",
"0###-## ## ##",
"0###-### ##",
)
| Provider |
python | django__django | django/db/models/query.py | {
"start": 84052,
"end": 84342
} | class ____(metaclass=InstanceCheckMeta):
"""
Marker class to checking if a queryset is empty by .none():
isinstance(qs.none(), EmptyQuerySet) -> True
"""
def __init__(self, *args, **kwargs):
raise TypeError("EmptyQuerySet can't be instantiated")
| EmptyQuerySet |
python | pypa__hatch | tests/backend/builders/test_wheel.py | {
"start": 18995,
"end": 22601
} | class ____:
def test_default(self, isolation):
builder = WheelBuilder(str(isolation))
assert builder.config.extra_metadata == builder.config.extra_metadata == {}
def test_invalid_type(self, isolation):
config = {"tool": {"hatch": {"build": {"targets": {"wheel": {"extra-metadata": 42}}}}}}
builder = WheelBuilder(str(isolation), config=config)
with pytest.raises(TypeError, match="Field `tool.hatch.build.targets.wheel.extra-metadata` must be a mapping"):
_ = builder.config.extra_metadata
def test_absolute(self, isolation):
config = {
"tool": {
"hatch": {"build": {"targets": {"wheel": {"extra-metadata": {str(isolation / "source"): "/target/"}}}}}
}
}
builder = WheelBuilder(str(isolation), config=config)
assert builder.config.extra_metadata == {str(isolation / "source"): "target"}
def test_relative(self, isolation):
config = {"tool": {"hatch": {"build": {"targets": {"wheel": {"extra-metadata": {"../source": "/target/"}}}}}}}
builder = WheelBuilder(str(isolation / "foo"), config=config)
assert builder.config.extra_metadata == {str(isolation / "source"): "target"}
def test_source_empty_string(self, isolation):
config = {"tool": {"hatch": {"build": {"targets": {"wheel": {"extra-metadata": {"": "/target/"}}}}}}}
builder = WheelBuilder(str(isolation), config=config)
with pytest.raises(
ValueError,
match="Source #1 in field `tool.hatch.build.targets.wheel.extra-metadata` cannot be an empty string",
):
_ = builder.config.extra_metadata
def test_relative_path_not_string(self, isolation):
config = {"tool": {"hatch": {"build": {"targets": {"wheel": {"extra-metadata": {"source": 0}}}}}}}
builder = WheelBuilder(str(isolation), config=config)
with pytest.raises(
TypeError,
match="Path for source `source` in field `tool.hatch.build.targets.wheel.extra-metadata` must be a string",
):
_ = builder.config.extra_metadata
def test_relative_path_empty_string(self, isolation):
config = {"tool": {"hatch": {"build": {"targets": {"wheel": {"extra-metadata": {"source": ""}}}}}}}
builder = WheelBuilder(str(isolation), config=config)
with pytest.raises(
ValueError,
match=(
"Path for source `source` in field `tool.hatch.build.targets.wheel.extra-metadata` "
"cannot be an empty string"
),
):
_ = builder.config.extra_metadata
def test_order(self, isolation):
config = {
"tool": {
"hatch": {
"build": {
"targets": {
"wheel": {
"extra-metadata": {
"../very-nested": "target1/embedded",
"../source1": "/target2/",
"../source2": "/target1/",
}
}
}
}
}
}
}
builder = WheelBuilder(str(isolation / "foo"), config=config)
assert builder.config.extra_metadata == {
str(isolation / "source2"): "target1",
str(isolation / "very-nested"): f"target1{os.sep}embedded",
str(isolation / "source1"): "target2",
}
| TestExtraMetadata |
python | getsentry__sentry | tests/sentry/relocation/tasks/test_transfer.py | {
"start": 1791,
"end": 3629
} | class ____(TestCase):
@patch("sentry.relocation.tasks.transfer.process_relocation_transfer_control")
def test_no_records(self, mock_process: MagicMock) -> None:
find_relocation_transfer_control()
assert not mock_process.delay.called
@patch("sentry.relocation.tasks.transfer.process_relocation_transfer_control")
def test_no_due_records(self, mock_process: MagicMock) -> None:
create_control_relocation_transfer(
organization=self.organization, scheduled_for=timezone.now() + timedelta(minutes=2)
)
find_relocation_transfer_control()
assert not mock_process.delay.called
@patch("sentry.relocation.tasks.transfer.process_relocation_transfer_control")
def test_due_records(self, mock_process: MagicMock) -> None:
transfer = create_control_relocation_transfer(
organization=self.organization, scheduled_for=timezone.now() - timedelta(minutes=2)
)
find_relocation_transfer_control()
assert mock_process.delay.called
assert mock_process.delay.call_args[1]["transfer_id"] == transfer.id
transfer.refresh_from_db()
assert transfer.scheduled_for > timezone.now()
@patch("sentry.relocation.tasks.transfer.process_relocation_transfer_control")
def test_purge_expired(self, mock_process: MagicMock) -> None:
transfer = create_control_relocation_transfer(
organization=self.organization,
scheduled_for=timezone.now() - timedelta(minutes=2),
)
transfer.date_added = timezone.now() - timedelta(hours=1, minutes=2)
transfer.save()
find_relocation_transfer_control()
assert not mock_process.delay.called
assert not ControlRelocationTransfer.objects.filter(id=transfer.id).exists()
| FindRelocationTransferControlTest |
python | modin-project__modin | modin/tests/pandas/extensions/conftest.py | {
"start": 1185,
"end": 1352
} | class ____(NativeQueryCompiler):
storage_format = property(lambda self: "Test1_Storage_Format")
engine = property(lambda self: "Test1_Engine")
| Test1QueryCompiler |
python | pytorch__pytorch | test/inductor/test_torchinductor.py | {
"start": 10562,
"end": 24932
} | class ____:
n: int
device: str
def dense(self):
return torch.randn((self.n, self.n), device=self.device)
def transposed(self):
return self.dense().transpose(0, 1)
def strided(self):
return torch.randn((self.n * 2, self.n * 3), device=self.device)[
self.n :, self.n :: 2
]
def broadcast1(self):
return torch.randn((self.n,), device=self.device)
def broadcast2(self):
return torch.randn((1, self.n, 1), device=self.device)
def broadcast3(self):
return torch.randn((1,), device=self.device)
def double(self):
if self.device == "mps":
raise unittest.SkipTest("MPS does not support torch.float64")
return torch.randn((self.n, self.n), device=self.device, dtype=torch.double)
def int(self):
return torch.arange(self.n, device=self.device, dtype=torch.int32)
def compute_grads(args, kwrags, results, grads):
def gather_leaf_tensors(args, kwargs):
args = pytree.arg_tree_leaves(*args, **kwargs)
leaf_tensors = [
arg for arg in args if isinstance(arg, torch.Tensor) and arg.requires_grad
]
return leaf_tensors
flat_results = pytree.tree_leaves(results)
flat_diff_results = [
r for r in flat_results if isinstance(r, torch.Tensor) and r.requires_grad
]
assert len(flat_diff_results) > 0
leaf_tensors = gather_leaf_tensors(args, kwrags)
assert len(leaf_tensors) > 0
return torch.autograd.grad(
flat_diff_results,
leaf_tensors,
grads,
allow_unused=True,
retain_graph=True,
)
def check_model(
self: TestCase,
model,
example_inputs,
kwargs=None,
*,
atol=None,
rtol=None,
grad_atol=None,
grad_rtol=None,
check_lowp=True,
exact_dtype=True,
nopython=True,
copy_to_gpu=True,
reference_in_float=True,
assert_equal=True,
check_gradient=False,
check_has_compiled=True,
output_process_fn_grad=lambda x: x,
# TODO: enable this for all tests
exact_stride=False,
):
kwargs = kwargs or {}
torch._dynamo.reset()
ref_inputs = [clone_preserve_strides_offset(x) for x in example_inputs]
ref_kwargs = kwargs
has_lowp_args = False
if reference_in_float and exact_dtype:
# Store expected dtypes so we can check actual result gives the correct types
torch.manual_seed(0)
try:
eager_result = model(*ref_inputs, **ref_kwargs)
except RuntimeError:
# Eager model may fail if the dtype is not supported
eager_result = None
ref_inputs = [clone_preserve_strides_offset(x) for x in example_inputs]
expect_dtypes = [
x.dtype if isinstance(x, torch.Tensor) else None
for x in pytree.tree_leaves(eager_result)
]
del eager_result
ref_model = model
if reference_in_float:
# check_lowp is ignored here, it's kept just to be able to call `common` with extra arg
def upcast_fn(x):
nonlocal has_lowp_args
if isinstance(x, torch.Tensor) and (
x.dtype == torch.float16 or x.dtype == torch.bfloat16
):
has_lowp_args = True
# Preserve strides when casting
result = torch.empty_strided(
x.size(), x.stride(), device=x.device, dtype=torch.float
)
result.copy_(x)
return result
else:
return x
# We previously call upcast_fn on example_inputs. It's incorrect
# if example_inputs is already fp32 and get inplace updated in the model.
# Call on the cloned tensors instead
ref_inputs = list(map(upcast_fn, ref_inputs))
ref_kwargs = {k: upcast_fn(v) for k, v in kwargs.items()}
if has_lowp_args and hasattr(model, "to"):
ref_model = copy.deepcopy(model).to(torch.float)
torch.manual_seed(0)
correct = ref_model(*ref_inputs, **ref_kwargs)
torch._inductor.metrics.reset()
called = False
def compile_fx_wrapper(model_, example_inputs_):
nonlocal called
called = True
return compile_fx(model_, example_inputs_)
def run(*ex, **kwargs):
return model(*ex, **kwargs)
run = torch.compile(run, backend=compile_fx_wrapper, fullgraph=nopython)
torch.manual_seed(0)
actual = run(*example_inputs, **kwargs)
# if not called:
# exp = torch._dynamo.explain(run)(*example_inputs)
# print("Explain:", exp[0])
# for graph in exp[2]:
# print("Graph", graph)
if check_has_compiled:
assert called, "Ran graph without calling compile_fx"
assert type(actual) is type(correct)
if isinstance(actual, (tuple, list)):
assert len(actual) == len(correct)
assert all(
type(actual_item) is type(correct_item)
for actual_item, correct_item in zip(actual, correct)
)
correct_flat, correct_spec = tree_flatten(correct)
actual_flat = pytree.tree_leaves(actual)
def reference_to_expect(actual_flat, correct_flat):
return tuple(
(
y.to(x.dtype)
if isinstance(y, torch.Tensor) and y.dtype.is_floating_point
else y
)
for x, y in zip(actual_flat, correct_flat)
)
if reference_in_float and exact_dtype:
for expect_dtype, actual_result in zip(expect_dtypes, actual_flat):
if expect_dtype is not None:
assert actual_result.dtype == expect_dtype, (
f"dtype mismatch, expected {expect_dtype} but got {actual_result.dtype}"
)
if reference_in_float:
correct_flat = reference_to_expect(actual_flat, correct_flat)
correct = tree_unflatten(correct_flat, correct_spec)
# Allow assert_equal to be a custom function, instead of True or False, for
# cases where differences may not indicate incorrectness.
if assert_equal:
if callable(assert_equal):
def custom_assert_with_self(*args, **kwargs):
assert_equal(self, *args, **kwargs)
assert_equal_fn = custom_assert_with_self
else:
assert_equal_fn = self.assertEqual
assert_equal_fn(
actual,
correct,
atol=atol,
rtol=rtol,
equal_nan=True,
exact_dtype=exact_dtype,
exact_stride=exact_stride,
)
# In case of input mutations, check that inputs are the same
# (This never uses a custom assert_equal fn.)
self.assertEqual(
ref_inputs,
example_inputs,
atol=atol,
rtol=rtol,
equal_nan=True,
# our testing sometimes uses higher precision inputs for the reference
exact_dtype=False,
exact_stride=exact_stride,
)
else:
for correct_val, actual_val in zip(correct_flat, actual_flat):
if isinstance(correct_val, torch.Tensor):
assert correct_val.device == actual_val.device
assert correct_val.size() == actual_val.size()
strides_equal, _ = torch._prims_common.check_significant_strides(
correct_val, actual_val
)
assert strides_equal
assert correct_val.layout == actual_val.layout
if exact_dtype:
assert correct_val.dtype == actual_val.dtype
if exact_stride:
assert correct_val.stride() == actual_val.stride()
if check_gradient:
actual = output_process_fn_grad(actual)
correct = output_process_fn_grad(correct)
actual_flat = pytree.tree_leaves(actual)
correct_flat = pytree.tree_leaves(correct)
# generate random unit norm gradients
grads = [
torch.randn_like(r)
for r in correct_flat
if isinstance(r, torch.Tensor) and r.requires_grad
]
for g in grads:
g /= g.norm()
correct_grad = compute_grads(ref_inputs, ref_kwargs, correct, grads)
all_none_grads = all(x is None for x in correct_grad)
tensor_args = [
x
for x in pytree.tree_flatten(example_inputs)[0]
if isinstance(x, torch.Tensor)
]
any_non_leaves = any(x.grad_fn is not None for x in tensor_args)
if all_none_grads and any_non_leaves:
# See Note [Detaching inputs that never need gradients]
# There are a handful of ops that can return None gradients, into of zero gradients.
# If all inputs to an AOTAutograd graph are supposed to get None gradients,
# AOTAutograd will end up forcing all of the outputs of the forward to not require grad.
# There's no easy fix to this (see the note above), although one option is to
# force any derivative formulas in core to return tensors of zeros instead of None.
flat_results = pytree.tree_leaves(actual)
results_that_require_grad = [
x
for x in flat_results
if isinstance(x, torch.Tensor) and x.requires_grad
]
self.assertEqual(len(results_that_require_grad), 0)
else:
actual_grad = compute_grads(example_inputs, kwargs, actual, grads)
if reference_in_float:
expect_grad = reference_to_expect(actual_grad, correct_grad)
else:
expect_grad = correct_grad
self.assertEqual(
actual_grad,
expect_grad,
atol=grad_atol or atol,
rtol=grad_rtol or rtol,
equal_nan=True,
exact_dtype=exact_dtype,
exact_stride=exact_stride,
)
torch._dynamo.reset()
@torch._inductor.config.patch("triton.cudagraphs", False)
def check_model_gpu(
self: TestCase,
model,
example_inputs,
kwargs=None,
*,
atol=None,
rtol=None,
grad_atol=None,
grad_rtol=None,
check_lowp=True,
exact_dtype=True,
nopython=True,
copy_to_gpu=True,
reference_in_float=True,
assert_equal=True,
check_gradient=False,
check_has_compiled=True,
output_process_fn_grad=lambda x: x,
# TODO: enable this for all tests
exact_stride=False,
):
kwargs = kwargs or {}
if hasattr(model, "to"):
model = model.to(device=GPU_TYPE)
if copy_to_gpu:
example_inputs = tuple(
clone_preserve_strides_offset(x, device=GPU_TYPE) for x in example_inputs
)
check_model(
self,
model,
example_inputs,
kwargs,
atol=atol,
rtol=rtol,
grad_atol=grad_atol,
grad_rtol=grad_rtol,
exact_dtype=exact_dtype,
nopython=nopython,
reference_in_float=reference_in_float,
assert_equal=assert_equal,
check_gradient=check_gradient,
check_has_compiled=check_has_compiled,
output_process_fn_grad=output_process_fn_grad,
exact_stride=exact_stride,
)
if check_lowp:
def downcast_fn(x):
if not isinstance(x, torch.Tensor) or x.dtype != torch.float:
return x
return torch.empty_strided(
x.size(), x.stride(), device=GPU_TYPE, dtype=torch.half
).copy_(x)
example_inputs = list(map(downcast_fn, example_inputs))
if hasattr(model, "to"):
model = model.to(torch.half)
if rtol is not None:
rtol = max(2e-3, rtol)
check_model(
self,
model,
example_inputs,
kwargs,
atol=atol,
rtol=rtol,
grad_atol=grad_atol,
grad_rtol=grad_rtol,
exact_dtype=exact_dtype,
nopython=nopython,
reference_in_float=reference_in_float,
assert_equal=assert_equal,
check_gradient=check_gradient,
check_has_compiled=check_has_compiled,
output_process_fn_grad=output_process_fn_grad,
exact_stride=exact_stride,
)
check_model_cuda = check_model_gpu
def _run_and_assert_no_indirect_indexing(
test_case, func, *args, has_wrapping=None, has_assert=False, **kwargs
):
result, source_codes = run_and_get_code(func, *args, **kwargs)
for code in source_codes:
for line in code.split("\n"):
stmt = None
# Find indexing expressions
if ".load(" in line:
stmt = line.split(".load")[-1]
elif "tl.store" in line:
stmt = line.split(".store")[-1]
stmt = ",".join(stmt.split(",")[:-2]) # Remove store value and mask
elif ".store" in line:
stmt = line.split(".store")[-1]
elif "[" in line:
stmt = line.split("[")[-1].split("]")[0]
if "tl.make_block_ptr(" in line:
continue
if stmt is None:
continue
# indirect indexing involves a `tmp` variable
test_case.assertTrue(
"tmp" not in stmt,
msg=f"Found indirect indexing in statement '{stmt}' from code:\n{code}",
)
if has_wrapping is not None:
test_case.assertTrue(
("where" in code or ") ? (" in code) is has_wrapping,
msg=f"Wanted {has_wrapping=} but got\n{code}",
)
test_case.assertTrue(
any(
("device_assert" in code or "TORCH_CHECK" in code) is has_assert
for code in source_codes
)
)
return result
def assertGeneratedKernelCountEqual(self: TestCase, expected: int):
if config.triton.multi_kernel:
# when multi_kernel is enabled, we generated both persistent reduction
# and non-persistent reduction kernels for the same node schedule.
# That will mess up with the kernel count. Just don't check it.
return
self.assertEqual(torch._inductor.metrics.generated_kernel_count, expected)
| InputGen |
python | PrefectHQ__prefect | tests/workers/test_base_worker.py | {
"start": 62167,
"end": 69431
} | class ____:
async def test_start_syncs_with_the_server(self, work_pool: WorkPool):
worker = WorkerTestImpl(work_pool_name=work_pool.name)
assert worker._work_pool is None
await worker.start(run_once=True)
assert worker._work_pool is not None
assert worker._work_pool.base_job_template == work_pool.base_job_template
async def test_start_executes_flow_runs(
self,
prefect_client: PrefectClient,
worker_deployment_wq1: Deployment,
work_pool: WorkPool,
):
@flow
def test_flow():
pass
def create_run_with_deployment(state: State):
return prefect_client.create_flow_run_from_deployment(
worker_deployment_wq1.id, state=state
)
flow_run = await prefect_client.create_flow_run_from_deployment(
worker_deployment_wq1.id,
state=Scheduled(scheduled_time=now_fn("UTC") - timedelta(days=1)),
)
worker = WorkerTestImpl(work_pool_name=work_pool.name)
worker.run = AsyncMock()
await worker.start(run_once=True)
worker.run.assert_awaited_once()
assert worker.run.call_args[1]["flow_run"].id == flow_run.id
@pytest.mark.parametrize(
"work_pool_env, deployment_env, flow_run_env, expected_env",
[
(
{},
{"test-var": "foo"},
{"another-var": "boo"},
{"test-var": "foo", "another-var": "boo"},
),
(
{"A": "1", "B": "2"},
{"A": "1", "B": "3"},
{},
{"A": "1", "B": "3"},
),
(
{"A": "1", "B": "2"},
{"C": "3", "D": "4"},
{},
{"A": "1", "B": "2", "C": "3", "D": "4"},
),
(
{"A": "1", "B": "2"},
{"C": "42"},
{"C": "3", "D": "4"},
{"A": "1", "B": "2", "C": "3", "D": "4"},
),
(
{"A": "1", "B": "2"},
{"B": ""}, # empty strings are considered values and will still override
{},
{"A": "1", "B": ""},
),
],
ids=[
"flow_run_into_deployment",
"deployment_into_work_pool_overlap",
"deployment_into_work_pool_no_overlap",
"flow_run_into_work_pool",
"try_overwrite_with_empty_str",
],
)
@pytest.mark.parametrize(
"use_variable_defaults",
[True, False],
ids=["with_defaults", "without_defaults"],
)
async def test_env_merge_logic_is_deep(
prefect_client,
session,
flow,
work_pool,
work_pool_env,
deployment_env,
flow_run_env,
expected_env,
use_variable_defaults,
):
if work_pool_env:
base_job_template = (
{
"job_configuration": {"env": "{{ env }}"},
"variables": {
"properties": {"env": {"type": "object", "default": work_pool_env}}
},
}
if use_variable_defaults
else {
"job_configuration": {"env": work_pool_env},
"variables": {"properties": {"env": {"type": "object"}}},
}
)
await models.workers.update_work_pool(
session=session,
work_pool_id=work_pool.id,
work_pool=ServerWorkPoolUpdate(
base_job_template=base_job_template,
description="test",
is_paused=False,
concurrency_limit=None,
),
)
await session.commit()
deployment = await models.deployments.create_deployment(
session=session,
deployment=Deployment(
name="env-testing",
tags=["test"],
flow_id=flow.id,
path="./subdir",
entrypoint="/file.py:flow",
parameter_openapi_schema={"type": "object", "properties": {}},
job_variables={"env": deployment_env},
work_queue_id=work_pool.default_queue_id,
),
)
await session.commit()
flow_run = await prefect_client.create_flow_run_from_deployment(
deployment.id,
state=Pending(),
job_variables={"env": flow_run_env},
)
async with WorkerTestImpl(
name="test",
work_pool_name=work_pool.name if work_pool_env else "test-work-pool",
) as worker:
await worker.sync_with_backend()
config = await worker._get_configuration(
flow_run, schemas.responses.DeploymentResponse.model_validate(deployment)
)
for key, value in expected_env.items():
assert config.env[key] == value
async def test_work_pool_env_from_job_configuration_merges_with_variable_defaults(
prefect_client, session, flow, work_pool
):
"""
Test for issue #19256: Work pool env vars should merge from both job_configuration
and variable defaults, then merge with deployment env vars.
When a work pool has env vars in BOTH job_configuration.env AND
variables.properties.env.default, they should all be merged together along with
deployment env vars.
"""
# Configure work pool with env vars in BOTH places
base_job_template = {
"job_configuration": {
"env": {
"WORK_POOL_BASE_VAR": "from-job-config", # Should NOT be lost
}
},
"variables": {
"properties": {
"env": {
"type": "object",
"default": {"WORK_POOL_DEFAULT_VAR": "from-variable-defaults"},
}
}
},
}
await models.workers.update_work_pool(
session=session,
work_pool_id=work_pool.id,
work_pool=ServerWorkPoolUpdate(
base_job_template=base_job_template,
description="test",
is_paused=False,
concurrency_limit=None,
),
)
await session.commit()
# Create deployment with its own env vars
deployment = await models.deployments.create_deployment(
session=session,
deployment=Deployment(
name="env-testing-merge",
tags=["test"],
flow_id=flow.id,
path="./subdir",
entrypoint="/file.py:flow",
parameter_openapi_schema={"type": "object", "properties": {}},
job_variables={"env": {"DEPLOYMENT_VAR": "from-deployment"}},
work_queue_id=work_pool.default_queue_id,
),
)
await session.commit()
flow_run = await prefect_client.create_flow_run_from_deployment(
deployment.id,
state=Pending(),
)
async with WorkerTestImpl(
name="test",
work_pool_name=work_pool.name,
) as worker:
await worker.sync_with_backend()
config = await worker._get_configuration(
flow_run, schemas.responses.DeploymentResponse.model_validate(deployment)
)
# All env vars should be present: job_configuration + variable defaults + deployment
assert config.env["WORK_POOL_BASE_VAR"] == "from-job-config"
assert config.env["WORK_POOL_DEFAULT_VAR"] == "from-variable-defaults"
assert config.env["DEPLOYMENT_VAR"] == "from-deployment"
| TestBaseWorkerStart |
python | jina-ai__jina | tests/unit/orchestrate/flow/flow-construct/test_flow_except.py | {
"start": 288,
"end": 399
} | class ____(Executor):
@requests
def craft(self, *args, **kwargs):
return 1 / 0
| DummyCrafterExcept |
python | qdrant__qdrant-client | qdrant_client/http/models/models.py | {
"start": 77832,
"end": 80677
} | class ____(BaseModel, extra="forbid"):
deleted_threshold: Optional[float] = Field(
default=None,
description="The minimal fraction of deleted vectors in a segment, required to perform segment optimization",
)
vacuum_min_vector_number: Optional[int] = Field(
default=None, description="The minimal number of vectors in a segment, required to perform segment optimization"
)
default_segment_number: Optional[int] = Field(
default=None,
description="Target amount of segments optimizer will try to keep. Real amount of segments may vary depending on multiple parameters: - Amount of stored points - Current write RPS It is recommended to select default number of segments as a factor of the number of search threads, so that each segment would be handled evenly by one of the threads If `default_segment_number = 0`, will be automatically selected by the number of available CPUs",
)
max_segment_size: Optional[int] = Field(
default=None,
description="Do not create segments larger this size (in kilobytes). Large segments might require disproportionately long indexation times, therefore it makes sense to limit the size of segments. If indexation speed have more priority for your - make this parameter lower. If search speed is more important - make this parameter higher. Note: 1Kb = 1 vector of size 256",
)
memmap_threshold: Optional[int] = Field(
default=None,
description="Maximum size (in kilobytes) of vectors to store in-memory per segment. Segments larger than this threshold will be stored as read-only memmapped file. Memmap storage is disabled by default, to enable it, set this threshold to a reasonable value. To disable memmap storage, set this to `0`. Note: 1Kb = 1 vector of size 256 Deprecated since Qdrant 1.15.0",
)
indexing_threshold: Optional[int] = Field(
default=None,
description="Maximum size (in kilobytes) of vectors allowed for plain index, exceeding this threshold will enable vector indexing Default value is 20,000, based on <https://github.com/google-research/google-research/blob/master/scann/docs/algorithms.md>. To disable vector indexing, set to `0`. Note: 1kB = 1 vector of size 256.",
)
flush_interval_sec: Optional[int] = Field(default=None, description="Minimum interval between forced flushes.")
max_optimization_threads: Optional["MaxOptimizationThreads"] = Field(
default=None,
description="Max number of threads (jobs) for running optimizations per shard. Note: each optimization job will also use `max_indexing_threads` threads by itself for index building. If "auto" - have no limit and choose dynamically to saturate CPU. If 0 - no optimization threads, optimizations will be disabled.",
)
| OptimizersConfigDiff |
python | getsentry__sentry | tests/sentry/migrations/test_0913_split_discover_dataset_dashboards_self_hosted.py | {
"start": 522,
"end": 7027
} | class ____(TestMigrations, SnubaTestCase):
migrate_from = "0912_make_organizationmemberteam_replica_is_active_true"
migrate_to = "0913_split_discover_dataset_dashboards_self_hosted"
def setup_before_migration(self, apps):
User = apps.get_model("sentry", "User")
Dashboard = apps.get_model("sentry", "Dashboard")
DashboardWidget = apps.get_model("sentry", "DashboardWidget")
DashboardWidgetQuery = apps.get_model("sentry", "DashboardWidgetQuery")
with outbox_context(flush=False):
self.organization = Organization.objects.create(name="test", slug="test")
self.user = User.objects.create(email="test@test.com", is_superuser=False)
self.project = self.create_project(
name="test_project", slug="test_project", organization=self.organization
)
self.environment = self.create_environment(
name="test_environment", project=self.project, organization=self.organization
)
self.dashboard = Dashboard.objects.create(
title="test",
organization_id=self.organization.id,
created_by_id=self.user.id,
)
self.discover_error_widget = DashboardWidget.objects.create(
dashboard_id=self.dashboard.id,
title="test discover widget",
widget_type=DashboardWidgetTypes.DISCOVER,
dataset_source=DatasetSourcesTypes.UNKNOWN.value,
display_type=DashboardWidgetDisplayTypes.LINE_CHART,
interval="1d",
order=0,
)
self.discover_error_widget_query = DashboardWidgetQuery.objects.create(
widget_id=self.discover_error_widget.id,
name="test discover widget query",
fields=["count()"],
aggregates=["count()"],
columns=[],
conditions="environment:foo",
orderby=["-count()"],
order=0,
)
self.migrated_discover_widget = DashboardWidget.objects.create(
dashboard_id=self.dashboard.id,
title="test migrated discover widget",
widget_type=DashboardWidgetTypes.DISCOVER,
dataset_source=DatasetSourcesTypes.UNKNOWN.value,
discover_widget_split=DashboardWidgetTypes.TRANSACTION_LIKE,
display_type=DashboardWidgetDisplayTypes.LINE_CHART,
interval="1d",
order=1,
)
self.migrated_discover_widget_query = DashboardWidgetQuery.objects.create(
widget_id=self.migrated_discover_widget.id,
name="test migrated discover widget query",
fields=["count()"],
aggregates=["count()"],
columns=[],
conditions="environment:foo",
orderby=["-count()"],
order=1,
)
self.discover_transaction_widget = DashboardWidget.objects.create(
dashboard_id=self.dashboard.id,
title="test discover transaction widget",
widget_type=DashboardWidgetTypes.DISCOVER,
dataset_source=DatasetSourcesTypes.UNKNOWN.value,
display_type=DashboardWidgetDisplayTypes.LINE_CHART,
interval="1d",
order=2,
)
self.discover_transaction_widget_query = DashboardWidgetQuery.objects.create(
widget_id=self.discover_transaction_widget.id,
name="test discover transaction widget query",
fields=["count()", "transaction.duration"],
aggregates=["count()"],
columns=[],
conditions="environment:foo",
orderby=["-count()"],
order=2,
)
self.discover_ambiguous_widget = DashboardWidget.objects.create(
dashboard_id=self.dashboard.id,
title="test discover ambiguous widget",
widget_type=DashboardWidgetTypes.DISCOVER,
dataset_source=DatasetSourcesTypes.UNKNOWN.value,
display_type=DashboardWidgetDisplayTypes.LINE_CHART,
interval="1d",
order=3,
)
self.discover_ambiguous_widget_query = DashboardWidgetQuery.objects.create(
widget_id=self.discover_ambiguous_widget.id,
name="test discover ambiguous widget query",
fields=["count()", "transaction"],
aggregates=["count()"],
columns=[],
conditions="environment:test_environment",
orderby=["-count()"],
order=3,
)
# Now store test data that should only affect the ambiguous widget
self.nine_mins_ago = before_now(minutes=9)
self.ten_mins_ago = before_now(minutes=10)
data = load_data("transaction", timestamp=self.ten_mins_ago)
data["transaction"] = "/to_other/"
data["environment"] = self.environment.name
data["transaction.duration"] = 1000
self.store_event(data, project_id=self.project.id, assert_no_errors=False)
data = load_data("transaction", timestamp=self.ten_mins_ago)
data["transaction"] = "/to_other/2"
data["environment"] = self.environment.name
data["transaction.duration"] = 2000
self.store_event(data, project_id=self.project.id, assert_no_errors=False)
def test(self) -> None:
self.discover_error_widget.refresh_from_db()
self.migrated_discover_widget.refresh_from_db()
self.discover_transaction_widget.refresh_from_db()
self.discover_ambiguous_widget.refresh_from_db()
assert self.discover_error_widget.discover_widget_split == DashboardWidgetTypes.ERROR_EVENTS
assert (
self.migrated_discover_widget.discover_widget_split
== DashboardWidgetTypes.TRANSACTION_LIKE
)
assert (
self.discover_transaction_widget.discover_widget_split
== DashboardWidgetTypes.TRANSACTION_LIKE
)
assert (
self.discover_ambiguous_widget.discover_widget_split
== DashboardWidgetTypes.TRANSACTION_LIKE
)
| SplitDiscoverDatasetDashboardsSelfHostedTest |
python | python__mypy | mypyc/ir/ops.py | {
"start": 19523,
"end": 20619
} | class ____(RegisterOp):
"""Native method call obj.method(arg, ...)"""
def __init__(self, obj: Value, method: str, args: list[Value], line: int = -1) -> None:
self.obj = obj
self.method = method
self.args = args
assert isinstance(obj.type, RInstance), "Methods can only be called on instances"
self.receiver_type = obj.type
method_ir = self.receiver_type.class_ir.method_sig(method)
assert method_ir is not None, "{} doesn't have method {}".format(
self.receiver_type.name, method
)
ret_type = method_ir.ret_type
self.type = ret_type
if not ret_type.error_overlap:
self.error_kind = ERR_MAGIC
else:
self.error_kind = ERR_MAGIC_OVERLAPPING
super().__init__(line)
def sources(self) -> list[Value]:
return self.args.copy() + [self.obj]
def set_sources(self, new: list[Value]) -> None:
*self.args, self.obj = new
def accept(self, visitor: OpVisitor[T]) -> T:
return visitor.visit_method_call(self)
@final
| MethodCall |
python | scrapy__scrapy | tests/test_command_runspider.py | {
"start": 631,
"end": 3223
} | class ____(scrapy.Spider):
name = "bad"
async def start(self):
raise Exception("oops!")
yield
"""
def runspider(
self, cwd: Path, code: str, name: str | None = None, args: Iterable[str] = ()
) -> tuple[int, str, str]:
fname = cwd / (name or self.spider_filename)
fname.write_text(code, encoding="utf-8")
return proc("runspider", str(fname), *args, cwd=cwd)
def get_log(
self, cwd: Path, code: str, name: str | None = None, args: Iterable[str] = ()
) -> str:
_, _, stderr = self.runspider(cwd, code, name, args=args)
return stderr
def test_runspider(self, tmp_path: Path) -> None:
log = self.get_log(tmp_path, self.debug_log_spider)
assert "DEBUG: It Works!" in log
assert (
"Using reactor: twisted.internet.asyncioreactor.AsyncioSelectorReactor"
in log
)
assert "INFO: Spider closed (finished)" in log
def test_run_fail_spider(self, tmp_path: Path) -> None:
ret, _, _ = self.runspider(
tmp_path, "import scrapy\n" + inspect.getsource(ExceptionSpider)
)
assert ret != 0
def test_run_good_spider(self, tmp_path: Path) -> None:
ret, _, _ = self.runspider(
tmp_path, "import scrapy\n" + inspect.getsource(NoRequestsSpider)
)
assert ret == 0
def test_runspider_log_level(self, tmp_path: Path) -> None:
log = self.get_log(
tmp_path, self.debug_log_spider, args=("-s", "LOG_LEVEL=INFO")
)
assert "DEBUG: It Works!" not in log
assert "INFO: Spider opened" in log
def test_runspider_default_reactor(self, tmp_path: Path) -> None:
log = self.get_log(
tmp_path, self.debug_log_spider, args=("-s", "TWISTED_REACTOR=")
)
assert "DEBUG: It Works!" in log
assert (
"Using reactor: twisted.internet.asyncioreactor.AsyncioSelectorReactor"
not in log
)
assert "INFO: Spider opened" in log
assert "INFO: Closing spider (finished)" in log
assert "INFO: Spider closed (finished)" in log
def test_runspider_dnscache_disabled(self, tmp_path: Path) -> None:
# see https://github.com/scrapy/scrapy/issues/2811
# The spider below should not be able to connect to localhost:12345,
# which is intended,
# but this should not be because of DNS lookup error
# assumption: localhost will resolve in all cases (true?)
dnscache_spider = """
import scrapy
| BadSpider |
python | airbytehq__airbyte | airbyte-ci/connectors/pipelines/pipelines/airbyte_ci/connectors/migrate_to_manifest_only/declarative_component_schema.py | {
"start": 38385,
"end": 39222
} | class ____(BaseModel):
type: Literal["WaitUntilTimeFromHeader"]
header: str = Field(
...,
description="The name of the response header defining how long to wait before retrying.",
examples=["wait_time"],
title="Response Header",
)
min_wait: Optional[Union[float, str]] = Field(
None,
description="Minimum time to wait before retrying.",
examples=[10, "60"],
title="Minimum Wait Time",
)
regex: Optional[str] = Field(
None,
description="Optional regex to apply on the header to extract its value. The regex should define a capture group defining the wait time.",
examples=["([-+]?\\d+)"],
title="Extraction Regex",
)
parameters: Optional[Dict[str, Any]] = Field(None, alias="$parameters")
| WaitUntilTimeFromHeader |
python | getsentry__sentry | src/sentry/seer/anomaly_detection/types.py | {
"start": 1997,
"end": 2099
} | class ____(StrEnum):
LOW = "low"
MEDIUM = "medium"
HIGH = "high"
| AnomalyDetectionSensitivity |
python | Textualize__textual | docs/examples/app/widgets04.py | {
"start": 74,
"end": 281
} | class ____(App):
async def on_key(self) -> None:
await self.mount(Welcome())
self.query_one(Button).label = "YES!"
if __name__ == "__main__":
app = WelcomeApp()
app.run()
| WelcomeApp |
python | GoogleCloudPlatform__python-docs-samples | appengine/standard/ndb/projection_queries/snippets.py | {
"start": 1187,
"end": 1652
} | class ____(ndb.Model):
name = ndb.StringProperty()
addresses = ndb.StructuredProperty(Address, repeated=True)
def fetch_sub_properties():
Contact.query().fetch(projection=["name", "addresses.city"])
Contact.query().fetch(projection=[Contact.name, Contact.addresses.city])
def demonstrate_ndb_grouping():
Article.query(projection=[Article.author], group_by=[Article.author])
Article.query(projection=[Article.author], distinct=True)
| Contact |
python | tiangolo__fastapi | fastapi/security/http.py | {
"start": 3247,
"end": 7069
} | class ____(HTTPBase):
"""
HTTP Basic authentication.
Ref: https://datatracker.ietf.org/doc/html/rfc7617
## Usage
Create an instance object and use that object as the dependency in `Depends()`.
The dependency result will be an `HTTPBasicCredentials` object containing the
`username` and the `password`.
Read more about it in the
[FastAPI docs for HTTP Basic Auth](https://fastapi.tiangolo.com/advanced/security/http-basic-auth/).
## Example
```python
from typing import Annotated
from fastapi import Depends, FastAPI
from fastapi.security import HTTPBasic, HTTPBasicCredentials
app = FastAPI()
security = HTTPBasic()
@app.get("/users/me")
def read_current_user(credentials: Annotated[HTTPBasicCredentials, Depends(security)]):
return {"username": credentials.username, "password": credentials.password}
```
"""
def __init__(
self,
*,
scheme_name: Annotated[
Optional[str],
Doc(
"""
Security scheme name.
It will be included in the generated OpenAPI (e.g. visible at `/docs`).
"""
),
] = None,
realm: Annotated[
Optional[str],
Doc(
"""
HTTP Basic authentication realm.
"""
),
] = None,
description: Annotated[
Optional[str],
Doc(
"""
Security scheme description.
It will be included in the generated OpenAPI (e.g. visible at `/docs`).
"""
),
] = None,
auto_error: Annotated[
bool,
Doc(
"""
By default, if the HTTP Basic authentication is not provided (a
header), `HTTPBasic` will automatically cancel the request and send the
client an error.
If `auto_error` is set to `False`, when the HTTP Basic authentication
is not available, instead of erroring out, the dependency result will
be `None`.
This is useful when you want to have optional authentication.
It is also useful when you want to have authentication that can be
provided in one of multiple optional ways (for example, in HTTP Basic
authentication or in an HTTP Bearer token).
"""
),
] = True,
):
self.model = HTTPBaseModel(scheme="basic", description=description)
self.scheme_name = scheme_name or self.__class__.__name__
self.realm = realm
self.auto_error = auto_error
def make_authenticate_headers(self) -> Dict[str, str]:
if self.realm:
return {"WWW-Authenticate": f'Basic realm="{self.realm}"'}
return {"WWW-Authenticate": "Basic"}
async def __call__( # type: ignore
self, request: Request
) -> Optional[HTTPBasicCredentials]:
authorization = request.headers.get("Authorization")
scheme, param = get_authorization_scheme_param(authorization)
if not authorization or scheme.lower() != "basic":
if self.auto_error:
raise self.make_not_authenticated_error()
else:
return None
try:
data = b64decode(param).decode("ascii")
except (ValueError, UnicodeDecodeError, binascii.Error) as e:
raise self.make_not_authenticated_error() from e
username, separator, password = data.partition(":")
if not separator:
raise self.make_not_authenticated_error()
return HTTPBasicCredentials(username=username, password=password)
| HTTPBasic |
python | django__django | tests/multiple_database/tests.py | {
"start": 80539,
"end": 84387
} | class ____(TestCase):
databases = {"default", "other"}
def override_router(self):
return override_settings(DATABASE_ROUTERS=[WriteToOtherRouter()])
def test_database_arg_save_and_delete(self):
"""
The pre/post_save signal contains the correct database.
"""
# Make some signal receivers
pre_save_receiver = DatabaseReceiver()
post_save_receiver = DatabaseReceiver()
pre_delete_receiver = DatabaseReceiver()
post_delete_receiver = DatabaseReceiver()
# Make model and connect receivers
signals.pre_save.connect(sender=Person, receiver=pre_save_receiver)
signals.post_save.connect(sender=Person, receiver=post_save_receiver)
signals.pre_delete.connect(sender=Person, receiver=pre_delete_receiver)
signals.post_delete.connect(sender=Person, receiver=post_delete_receiver)
p = Person.objects.create(name="Darth Vader")
# Save and test receivers got calls
p.save()
self.assertEqual(pre_save_receiver._database, DEFAULT_DB_ALIAS)
self.assertEqual(post_save_receiver._database, DEFAULT_DB_ALIAS)
# Delete, and test
p.delete()
self.assertEqual(pre_delete_receiver._database, DEFAULT_DB_ALIAS)
self.assertEqual(post_delete_receiver._database, DEFAULT_DB_ALIAS)
# Save again to a different database
p.save(using="other")
self.assertEqual(pre_save_receiver._database, "other")
self.assertEqual(post_save_receiver._database, "other")
# Delete, and test
p.delete(using="other")
self.assertEqual(pre_delete_receiver._database, "other")
self.assertEqual(post_delete_receiver._database, "other")
signals.pre_save.disconnect(sender=Person, receiver=pre_save_receiver)
signals.post_save.disconnect(sender=Person, receiver=post_save_receiver)
signals.pre_delete.disconnect(sender=Person, receiver=pre_delete_receiver)
signals.post_delete.disconnect(sender=Person, receiver=post_delete_receiver)
def test_database_arg_m2m(self):
"""
The m2m_changed signal has a correct database arg.
"""
# Make a receiver
receiver = DatabaseReceiver()
# Connect it
signals.m2m_changed.connect(receiver=receiver)
# Create the models that will be used for the tests
b = Book.objects.create(
title="Pro Django", published=datetime.date(2008, 12, 16)
)
p = Person.objects.create(name="Marty Alchin")
# Create a copy of the models on the 'other' database to prevent
# integrity errors on backends that don't defer constraints checks
Book.objects.using("other").create(
pk=b.pk, title=b.title, published=b.published
)
Person.objects.using("other").create(pk=p.pk, name=p.name)
# Test addition
b.authors.add(p)
self.assertEqual(receiver._database, DEFAULT_DB_ALIAS)
with self.override_router():
b.authors.add(p)
self.assertEqual(receiver._database, "other")
# Test removal
b.authors.remove(p)
self.assertEqual(receiver._database, DEFAULT_DB_ALIAS)
with self.override_router():
b.authors.remove(p)
self.assertEqual(receiver._database, "other")
# Test addition in reverse
p.book_set.add(b)
self.assertEqual(receiver._database, DEFAULT_DB_ALIAS)
with self.override_router():
p.book_set.add(b)
self.assertEqual(receiver._database, "other")
# Test clearing
b.authors.clear()
self.assertEqual(receiver._database, DEFAULT_DB_ALIAS)
with self.override_router():
b.authors.clear()
self.assertEqual(receiver._database, "other")
| SignalTests |
python | langchain-ai__langchain | libs/langchain/langchain_classic/agents/structured_chat/output_parser.py | {
"start": 2201,
"end": 4075
} | class ____(AgentOutputParser):
"""Output parser with retries for the structured chat agent."""
base_parser: AgentOutputParser = Field(default_factory=StructuredChatOutputParser)
"""The base parser to use."""
output_fixing_parser: OutputFixingParser | None = None
"""The output fixing parser to use."""
@override
def get_format_instructions(self) -> str:
return FORMAT_INSTRUCTIONS
@override
def parse(self, text: str) -> AgentAction | AgentFinish:
try:
if self.output_fixing_parser is not None:
return self.output_fixing_parser.parse(text)
return self.base_parser.parse(text)
except Exception as e:
msg = f"Could not parse LLM output: {text}"
raise OutputParserException(msg) from e
@classmethod
def from_llm(
cls,
llm: BaseLanguageModel | None = None,
base_parser: StructuredChatOutputParser | None = None,
) -> StructuredChatOutputParserWithRetries:
"""Create a StructuredChatOutputParserWithRetries from a language model.
Args:
llm: The language model to use.
base_parser: An optional StructuredChatOutputParser to use.
Returns:
An instance of StructuredChatOutputParserWithRetries.
"""
if llm is not None:
base_parser = base_parser or StructuredChatOutputParser()
output_fixing_parser: OutputFixingParser = OutputFixingParser.from_llm(
llm=llm,
parser=base_parser,
)
return cls(output_fixing_parser=output_fixing_parser)
if base_parser is not None:
return cls(base_parser=base_parser)
return cls()
@property
def _type(self) -> str:
return "structured_chat_with_retries"
| StructuredChatOutputParserWithRetries |
python | HypothesisWorks__hypothesis | hypothesis-python/src/hypothesis/strategies/_internal/collections.py | {
"start": 1418,
"end": 4118
} | class ____(SearchStrategy[tuple[Ex, ...]]):
"""A strategy responsible for fixed length tuples based on heterogeneous
strategies for each of their elements."""
def __init__(self, strategies: Iterable[SearchStrategy[Any]]):
super().__init__()
self.element_strategies = tuple(strategies)
def do_validate(self) -> None:
for s in self.element_strategies:
s.validate()
def calc_label(self) -> int:
return combine_labels(
self.class_label, *(s.label for s in self.element_strategies)
)
def __repr__(self) -> str:
tuple_string = ", ".join(map(repr, self.element_strategies))
return f"TupleStrategy(({tuple_string}))"
def calc_has_reusable_values(self, recur: RecurT) -> bool:
return all(recur(e) for e in self.element_strategies)
def do_draw(self, data: ConjectureData) -> tuple[Ex, ...]:
return tuple(data.draw(e) for e in self.element_strategies)
def calc_is_empty(self, recur: RecurT) -> bool:
return any(recur(e) for e in self.element_strategies)
@overload
def tuples() -> SearchStrategy[tuple[()]]: # pragma: no cover
...
@overload
def tuples(__a1: SearchStrategy[Ex]) -> SearchStrategy[tuple[Ex]]: # pragma: no cover
...
@overload
def tuples(
__a1: SearchStrategy[Ex], __a2: SearchStrategy[T]
) -> SearchStrategy[tuple[Ex, T]]: # pragma: no cover
...
@overload
def tuples(
__a1: SearchStrategy[Ex], __a2: SearchStrategy[T], __a3: SearchStrategy[T3]
) -> SearchStrategy[tuple[Ex, T, T3]]: # pragma: no cover
...
@overload
def tuples(
__a1: SearchStrategy[Ex],
__a2: SearchStrategy[T],
__a3: SearchStrategy[T3],
__a4: SearchStrategy[T4],
) -> SearchStrategy[tuple[Ex, T, T3, T4]]: # pragma: no cover
...
@overload
def tuples(
__a1: SearchStrategy[Ex],
__a2: SearchStrategy[T],
__a3: SearchStrategy[T3],
__a4: SearchStrategy[T4],
__a5: SearchStrategy[T5],
) -> SearchStrategy[tuple[Ex, T, T3, T4, T5]]: # pragma: no cover
...
@overload
def tuples(
*args: SearchStrategy[Any],
) -> SearchStrategy[tuple[Any, ...]]: # pragma: no cover
...
@cacheable
@defines_strategy()
def tuples(*args: SearchStrategy[Any]) -> SearchStrategy[tuple[Any, ...]]:
"""Return a strategy which generates a tuple of the same length as args by
generating the value at index i from args[i].
e.g. tuples(integers(), integers()) would generate a tuple of length
two with both values an integer.
Examples from this strategy shrink by shrinking their component parts.
"""
for arg in args:
check_strategy(arg)
return TupleStrategy(args)
| TupleStrategy |
python | kamyu104__LeetCode-Solutions | Python/best-team-with-no-conflicts.py | {
"start": 2525,
"end": 3185
} | class ____(object):
def bestTeamScore(self, scores, ages):
"""
:type scores: List[int]
:type ages: List[int]
:rtype: int
"""
players = sorted(zip(scores, ages))
sorted_ages = sorted(set(ages))
lookup = {age:i for i, age in enumerate(sorted_ages)} # coordinate compression
segment_tree = SegmentTree(len(lookup))
result = 0
for score, age in players:
segment_tree.update(lookup[age], lookup[age], segment_tree.query(0, lookup[age])+score)
return segment_tree.query(0, len(lookup)-1)
# Time: O(nlogs)
# Space: O(n)
# optimized from Solution4
| Solution |
python | pytorch__pytorch | test/dynamo/test_base_hop.py | {
"start": 1575,
"end": 4887
} | class ____(torch.nn.Module):
def forward(self, L_x_: "f32[3, 3]", L_y_: "f32[3, 3]"):
l_x_ = L_x_
l_y_ = L_y_
subgraph_0 = self.subgraph_0
invoke_quant_test = torch.ops.higher_order.invoke_quant_test(subgraph_0, l_x_, l_y_, scheme = 'nf4'); subgraph_0 = l_x_ = l_y_ = None
getitem: "f32[3, 3]" = invoke_quant_test[0]; invoke_quant_test = None
return (getitem,)
class subgraph_0(torch.nn.Module):
def forward(self, l_x_: "f32[3, 3]", l_y_: "f32[3, 3]"):
matmul: "f32[3, 3]" = l_x_ @ l_y_; l_x_ = l_y_ = None
sin: "f32[3, 3]" = matmul.sin(); matmul = None
cos: "f32[3, 3]" = sin.cos(); sin = None
return (cos,)
""", # NOQA: B950
)
def test_schema_gen_single_return(self):
def inner(x, y):
return (x @ y).sin().cos()
x = torch.randn(3, 3, requires_grad=False)
y = torch.randn(3, 3, requires_grad=False)
backend = EagerAndRecordGraphs()
@torch.compile(backend=backend)
def f(x, y):
return invoke_quant_test(inner, x, y, scheme="nf4")
out = f(x.clone(), y)
self.assertEqual(out, inner(x.clone(), y))
schemas = find_hop_schema(backend.graphs[0], invoke_quant_test)
self.assertEqual(len(schemas), 1)
self.assertExpectedInline(
str(schemas[0]),
"""invoke_quant_test(Any subgraph, Tensor arg0, Tensor arg1, *, str scheme="nf4") -> ((Tensor))""", # noqa: B950
)
def test_schema_gen_pytree_in_out(self):
def inner(x_y):
x, y = x_y
return [
(x @ y).sin().cos(),
(x + y, x - y),
{"out": (x @ y,)},
]
# make x not require grad because we want to inplace mutate it
x = torch.randn(3, 3, requires_grad=False)
y = torch.randn(3, 3, requires_grad=True)
backend = EagerAndRecordGraphs()
@torch.compile(backend=backend)
def f(x, y):
return invoke_quant_test(inner, [x, y], scheme="nf4")
out = f(x.clone(), y)
self.assertEqual(out, inner([x.clone(), y]))
schemas = find_hop_schema(backend.graphs[0], invoke_quant_test)
self.assertEqual(len(schemas), 1)
self.assertExpectedInline(
str(schemas[0]),
"""invoke_quant_test(Any subgraph, Tensor arg0, Tensor arg1, *, str scheme="nf4") -> (Tensor, Tensor, Tensor, Tensor)""", # noqa: B950
)
def test_schema_gen_single_return_with_mutation(self):
def inner(x, y):
x.add_(1)
y.mul_(-1)
return (x @ y).sin().cos()
x = torch.randn(3, 3, requires_grad=False)
y = torch.randn(3, 3, requires_grad=False)
backend = EagerAndRecordGraphs()
def f(x, y):
return invoke_quant_test(inner, x, y, scheme="nf4")
with mock.patch(
"torch._dynamo.variables.higher_order_ops.BaseHOPVariable.supports_input_mutation",
True,
):
torch.compile(f, backend=backend, fullgraph=True)(x.clone(), y)
self.assertEqual(len(backend.graphs), 1)
self.assertExpectedInline(
normalize_graph(backend.graphs[0]),
"""\
| GraphModule |
python | pytorch__pytorch | tools/test/test_cmake.py | {
"start": 336,
"end": 3879
} | class ____(unittest.TestCase):
@unittest.mock.patch("multiprocessing.cpu_count")
def test_build_jobs(self, mock_cpu_count: unittest.mock.MagicMock) -> None:
"""Tests that the number of build jobs comes out correctly."""
mock_cpu_count.return_value = 13
cases = [
# MAX_JOBS, USE_NINJA, IS_WINDOWS, want
(("8", True, False), ["-j", "8"]), # noqa: E201,E241
((None, True, False), None), # noqa: E201,E241
(("7", False, False), ["-j", "7"]), # noqa: E201,E241
((None, False, False), ["-j", "13"]), # noqa: E201,E241
(("6", True, True), ["-j", "6"]), # noqa: E201,E241
((None, True, True), None), # noqa: E201,E241
(("11", False, True), ["-j", "11"]), # noqa: E201,E241
((None, False, True), ["-j", "13"]), # noqa: E201,E241
]
for (max_jobs, use_ninja, is_windows), want in cases:
with self.subTest(
MAX_JOBS=max_jobs, USE_NINJA=use_ninja, IS_WINDOWS=is_windows
):
with contextlib.ExitStack() as stack:
stack.enter_context(env_var("MAX_JOBS", max_jobs))
stack.enter_context(
unittest.mock.patch.object(
tools.setup_helpers.cmake, "USE_NINJA", use_ninja
)
)
stack.enter_context(
unittest.mock.patch.object(
tools.setup_helpers.cmake, "IS_WINDOWS", is_windows
)
)
cmake = tools.setup_helpers.cmake.CMake()
with unittest.mock.patch.object(cmake, "run") as cmake_run:
cmake.build({})
cmake_run.assert_called_once()
(call,) = cmake_run.mock_calls
build_args, _ = call.args
if want is None:
self.assertNotIn("-j", build_args)
else:
self.assert_contains_sequence(build_args, want)
@staticmethod
def assert_contains_sequence(
sequence: Sequence[T], subsequence: Sequence[T]
) -> None:
"""Raises an assertion if the subsequence is not contained in the sequence."""
if len(subsequence) == 0:
return # all sequences contain the empty subsequence
# Iterate over all windows of len(subsequence). Stop if the
# window matches.
for i in range(len(sequence) - len(subsequence) + 1):
candidate = sequence[i : i + len(subsequence)]
assert len(candidate) == len(subsequence) # sanity check
if candidate == subsequence:
return # found it
raise AssertionError(f"{subsequence} not found in {sequence}")
@contextlib.contextmanager
def env_var(key: str, value: str | None) -> Iterator[None]:
"""Sets/clears an environment variable within a Python context."""
# Get the previous value and then override it.
previous_value = os.environ.get(key)
set_env_var(key, value)
try:
yield
finally:
# Restore to previous value.
set_env_var(key, previous_value)
def set_env_var(key: str, value: str | None) -> None:
"""Sets/clears an environment variable."""
if value is None:
os.environ.pop(key, None)
else:
os.environ[key] = value
if __name__ == "__main__":
unittest.main()
| TestCMake |
python | mwaskom__seaborn | tests/_core/test_plot.py | {
"start": 73563,
"end": 73671
} | class ____:
def test_default_repr(self):
assert repr(Default()) == "<default>"
| TestDefaultObject |
python | geekcomputers__Python | venv/Lib/site-packages/pip/_vendor/pygments/formatters/terminal256.py | {
"start": 10210,
"end": 11753
} | class ____(Terminal256Formatter):
r"""
Format tokens with ANSI color sequences, for output in a true-color
terminal or console. Like in `TerminalFormatter` color sequences
are terminated at newlines, so that paging the output works correctly.
.. versionadded:: 2.1
Options accepted:
`style`
The style to use, can be a string or a Style subclass (default:
``'default'``).
"""
name = 'TerminalTrueColor'
aliases = ['terminal16m', 'console16m', '16m']
filenames = []
def _build_color_table(self):
pass
def _color_tuple(self, color):
try:
rgb = int(str(color), 16)
except ValueError:
return None
r = (rgb >> 16) & 0xff
g = (rgb >> 8) & 0xff
b = rgb & 0xff
return (r, g, b)
def _setup_styles(self):
for ttype, ndef in self.style:
escape = EscapeSequence()
if ndef['color']:
escape.fg = self._color_tuple(ndef['color'])
if ndef['bgcolor']:
escape.bg = self._color_tuple(ndef['bgcolor'])
if self.usebold and ndef['bold']:
escape.bold = True
if self.useunderline and ndef['underline']:
escape.underline = True
if self.useitalic and ndef['italic']:
escape.italic = True
self.style_string[str(ttype)] = (escape.true_color_string(),
escape.reset_string())
| TerminalTrueColorFormatter |
python | huggingface__transformers | src/transformers/models/mbart/modeling_mbart.py | {
"start": 5676,
"end": 11272
} | class ____(nn.Module):
"""Multi-headed attention from 'Attention Is All You Need' paper"""
def __init__(
self,
embed_dim: int,
num_heads: int,
dropout: float = 0.0,
is_decoder: bool = False,
bias: bool = True,
is_causal: bool = False,
config: Optional[MBartConfig] = None,
layer_idx: Optional[int] = None,
):
super().__init__()
self.embed_dim = embed_dim
self.num_heads = num_heads
self.dropout = dropout
self.head_dim = embed_dim // num_heads
self.config = config
if (self.head_dim * num_heads) != self.embed_dim:
raise ValueError(
f"embed_dim must be divisible by num_heads (got `embed_dim`: {self.embed_dim}"
f" and `num_heads`: {num_heads})."
)
self.scaling = self.head_dim**-0.5
self.is_decoder = is_decoder
self.is_causal = is_causal
self.layer_idx = layer_idx
if layer_idx is None and self.is_decoder:
logger.warning_once(
f"Instantiating a decoder {self.__class__.__name__} without passing `layer_idx` is not recommended and "
"will lead to errors during the forward call, if caching is used. Please make sure to provide a `layer_idx` "
"when creating this class."
)
self.k_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
self.v_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
self.q_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
self.out_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
def forward(
self,
hidden_states: torch.Tensor,
key_value_states: Optional[torch.Tensor] = None,
past_key_values: Optional[Cache] = None,
attention_mask: Optional[torch.Tensor] = None,
output_attentions: bool = False,
cache_position: Optional[torch.Tensor] = None,
# TODO: we need a refactor so that the different attention modules can get their specific kwargs
# ATM, we have mixed things encoder, decoder, and encoder-decoder attn
**kwargs: Unpack[FlashAttentionKwargs],
) -> tuple[torch.Tensor, Optional[torch.Tensor], Optional[tuple[torch.Tensor]]]:
"""Input shape: Batch x Time x Channel"""
# if key_value_states are provided this layer is used as a cross-attention layer
# for the decoder
is_cross_attention = key_value_states is not None
# determine input shapes
bsz, tgt_len = hidden_states.shape[:-1]
src_len = key_value_states.shape[1] if is_cross_attention else tgt_len
q_input_shape = (bsz, tgt_len, -1, self.head_dim)
kv_input_shape = (bsz, src_len, -1, self.head_dim)
# get query proj
query_states = self.q_proj(hidden_states).view(*q_input_shape).transpose(1, 2)
is_updated = False
if past_key_values is not None:
if isinstance(past_key_values, EncoderDecoderCache):
is_updated = past_key_values.is_updated.get(self.layer_idx)
if is_cross_attention:
# after the first generated id, we can subsequently re-use all key/value_states from cache
curr_past_key_values = past_key_values.cross_attention_cache
else:
curr_past_key_values = past_key_values.self_attention_cache
else:
curr_past_key_values = past_key_values
current_states = key_value_states if is_cross_attention else hidden_states
if is_cross_attention and past_key_values is not None and is_updated:
# reuse k,v, cross_attentions
key_states = curr_past_key_values.layers[self.layer_idx].keys
value_states = curr_past_key_values.layers[self.layer_idx].values
else:
key_states = self.k_proj(current_states)
value_states = self.v_proj(current_states)
key_states = key_states.view(*kv_input_shape).transpose(1, 2)
value_states = value_states.view(*kv_input_shape).transpose(1, 2)
if past_key_values is not None:
# save all key/value_states to cache to be re-used for fast auto-regressive generation
cache_position = cache_position if not is_cross_attention else None
key_states, value_states = curr_past_key_values.update(
key_states, value_states, self.layer_idx, {"cache_position": cache_position}
)
# set flag that curr layer for cross-attn is already updated so we can re-use in subsequent calls
if is_cross_attention and isinstance(past_key_values, EncoderDecoderCache):
past_key_values.is_updated[self.layer_idx] = True
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_states,
key_states,
value_states,
attention_mask,
dropout=0.0 if not self.training else self.dropout,
scaling=self.scaling,
output_attentions=output_attentions,
**kwargs,
)
attn_output = attn_output.reshape(bsz, tgt_len, -1).contiguous()
attn_output = self.out_proj(attn_output)
return attn_output, attn_weights
| MBartAttention |
python | numba__numba | numba/tests/npyufunc/test_ufuncbuilding.py | {
"start": 365,
"end": 3018
} | class ____(TestCase):
def test_basic_ufunc(self):
from numba.tests.npyufunc.ufuncbuilding_usecases import add
ufb = UFuncBuilder(add)
cres = ufb.add("int32(int32, int32)")
self.assertFalse(cres.objectmode)
cres = ufb.add("int64(int64, int64)")
self.assertFalse(cres.objectmode)
ufunc = ufb.build_ufunc()
def check(a):
b = ufunc(a, a)
self.assertPreciseEqual(a + a, b)
self.assertEqual(b.dtype, a.dtype)
a = np.arange(12, dtype='int32')
check(a)
# Non-contiguous dimension
a = a[::2]
check(a)
a = a.reshape((2, 3))
check(a)
# Metadata
self.assertEqual(ufunc.__name__, "add")
self.assertIn("An addition", ufunc.__doc__)
def test_ufunc_struct(self):
from numba.tests.npyufunc.ufuncbuilding_usecases import add
ufb = UFuncBuilder(add)
cres = ufb.add("complex64(complex64, complex64)")
self.assertFalse(cres.objectmode)
ufunc = ufb.build_ufunc()
def check(a):
b = ufunc(a, a)
self.assertPreciseEqual(a + a, b)
self.assertEqual(b.dtype, a.dtype)
a = np.arange(12, dtype='complex64') + 1j
check(a)
# Non-contiguous dimension
a = a[::2]
check(a)
a = a.reshape((2, 3))
check(a)
def test_ufunc_forceobj(self):
from numba.tests.npyufunc.ufuncbuilding_usecases import add
ufb = UFuncBuilder(add, targetoptions={'forceobj': True})
cres = ufb.add("int32(int32, int32)")
self.assertTrue(cres.objectmode)
ufunc = ufb.build_ufunc()
a = np.arange(10, dtype='int32')
b = ufunc(a, a)
self.assertPreciseEqual(a + a, b)
def test_nested_call(self):
"""
Check nested call to an implicitly-typed ufunc.
"""
from numba.tests.npyufunc.ufuncbuilding_usecases import outer
builder = UFuncBuilder(outer,
targetoptions={'nopython': True})
builder.add("(int64, int64)")
ufunc = builder.build_ufunc()
self.assertEqual(ufunc(-1, 3), 2)
def test_nested_call_explicit(self):
"""
Check nested call to an explicitly-typed ufunc.
"""
from numba.tests.npyufunc.ufuncbuilding_usecases import outer_explicit
builder = UFuncBuilder(outer_explicit,
targetoptions={'nopython': True})
builder.add("(int64, int64)")
ufunc = builder.build_ufunc()
self.assertEqual(ufunc(-1, 3), 2)
| TestUfuncBuilding |
python | google__jax | jax/_src/pallas/core.py | {
"start": 3561,
"end": 3640
} | class ____(AbstractSemaphoreTy):
name = "semaphore"
type = semaphore
| Semaphore |
python | allegroai__clearml | clearml/utilities/enum.py | {
"start": 37,
"end": 840
} | class ____(object):
"""Base class for enum-like classes using class-attributes with string values to represent enum key/value pairs"""
__cache = None
@classmethod
def values(cls) -> List[str]:
"""Extract list of enum-like options based on the derived classes' attributes.
Any class attribute who's key doesn't start with an underscore and who's value is not a class method
or callable is considered an option.
Returns a list of attribute names representing the options.
"""
if cls.__cache is None:
cls.__cache = [
v
for k, v in vars(cls).items()
if not k.startswith("_") and not callable(v) and not isinstance(v, classmethod)
]
return cls.__cache
| EnumOptions |
python | scipy__scipy | scipy/stats/_discrete_distns.py | {
"start": 16784,
"end": 22270
} | class ____(rv_discrete):
r"""A hypergeometric discrete random variable.
The hypergeometric distribution models drawing objects from a bin.
`M` is the total number of objects, `n` is total number of Type I objects.
The random variate represents the number of Type I objects in `N` drawn
without replacement from the total population.
%(before_notes)s
Notes
-----
The symbols used to denote the shape parameters (`M`, `n`, and `N`) are not
universally accepted. See the Examples for a clarification of the
definitions used here.
The probability mass function is defined as,
.. math:: p(k, M, n, N) = \frac{\binom{n}{k} \binom{M - n}{N - k}}
{\binom{M}{N}}
for :math:`k \in [\max(0, N - M + n), \min(n, N)]`, where the binomial
coefficients are defined as,
.. math:: \binom{n}{k} \equiv \frac{n!}{k! (n - k)!}.
This distribution uses routines from the Boost Math C++ library for
the computation of the ``pmf``, ``cdf``, ``sf`` and ``stats`` methods. [1]_
%(after_notes)s
References
----------
.. [1] The Boost Developers. "Boost C++ Libraries". https://www.boost.org/.
Examples
--------
>>> import numpy as np
>>> from scipy.stats import hypergeom
>>> import matplotlib.pyplot as plt
Suppose we have a collection of 20 animals, of which 7 are dogs. Then if
we want to know the probability of finding a given number of dogs if we
choose at random 12 of the 20 animals, we can initialize a frozen
distribution and plot the probability mass function:
>>> [M, n, N] = [20, 7, 12]
>>> rv = hypergeom(M, n, N)
>>> x = np.arange(0, n+1)
>>> pmf_dogs = rv.pmf(x)
>>> fig = plt.figure()
>>> ax = fig.add_subplot(111)
>>> ax.plot(x, pmf_dogs, 'bo')
>>> ax.vlines(x, 0, pmf_dogs, lw=2)
>>> ax.set_xlabel('# of dogs in our group of chosen animals')
>>> ax.set_ylabel('hypergeom PMF')
>>> plt.show()
Instead of using a frozen distribution we can also use `hypergeom`
methods directly. To for example obtain the cumulative distribution
function, use:
>>> prb = hypergeom.cdf(x, M, n, N)
And to generate random numbers:
>>> R = hypergeom.rvs(M, n, N, size=10)
See Also
--------
nhypergeom, binom, nbinom
"""
def _shape_info(self):
return [_ShapeInfo("M", True, (0, np.inf), (True, False)),
_ShapeInfo("n", True, (0, np.inf), (True, False)),
_ShapeInfo("N", True, (0, np.inf), (True, False))]
def _rvs(self, M, n, N, size=None, random_state=None):
return random_state.hypergeometric(n, M-n, N, size=size)
def _get_support(self, M, n, N):
return np.maximum(N-(M-n), 0), np.minimum(n, N)
def _argcheck(self, M, n, N):
cond = (M > 0) & (n >= 0) & (N >= 0)
cond &= (n <= M) & (N <= M)
cond &= _isintegral(M) & _isintegral(n) & _isintegral(N)
return cond
def _logpmf(self, k, M, n, N):
tot, good = M, n
bad = tot - good
result = (betaln(good+1, 1) + betaln(bad+1, 1) + betaln(tot-N+1, N+1) -
betaln(k+1, good-k+1) - betaln(N-k+1, bad-N+k+1) -
betaln(tot+1, 1))
return result
def _pmf(self, k, M, n, N):
return scu._hypergeom_pmf(k, n, N, M)
def _cdf(self, k, M, n, N):
return scu._hypergeom_cdf(k, n, N, M)
def _stats(self, M, n, N):
M, n, N = 1. * M, 1. * n, 1. * N
m = M - n
# Boost kurtosis_excess doesn't return the same as the value
# computed here.
g2 = M * (M + 1) - 6. * N * (M - N) - 6. * n * m
g2 *= (M - 1) * M * M
g2 += 6. * n * N * (M - N) * m * (5. * M - 6)
g2 /= n * N * (M - N) * m * (M - 2.) * (M - 3.)
return (
scu._hypergeom_mean(n, N, M),
scu._hypergeom_variance(n, N, M),
scu._hypergeom_skewness(n, N, M),
g2,
)
def _entropy(self, M, n, N):
k = np.r_[N - (M - n):min(n, N) + 1]
vals = self.pmf(k, M, n, N)
return np.sum(entr(vals), axis=0)
def _sf(self, k, M, n, N):
return scu._hypergeom_sf(k, n, N, M)
def _logsf(self, k, M, n, N):
res = []
for quant, tot, good, draw in zip(*np.broadcast_arrays(k, M, n, N)):
if (quant + 0.5) * (tot + 0.5) < (good - 0.5) * (draw - 0.5):
# Less terms to sum if we calculate log(1-cdf)
res.append(log1p(-exp(self.logcdf(quant, tot, good, draw))))
else:
# Integration over probability mass function using logsumexp
k2 = np.arange(quant + 1, draw + 1)
res.append(logsumexp(self._logpmf(k2, tot, good, draw)))
return np.asarray(res)
def _logcdf(self, k, M, n, N):
res = []
for quant, tot, good, draw in zip(*np.broadcast_arrays(k, M, n, N)):
if (quant + 0.5) * (tot + 0.5) > (good - 0.5) * (draw - 0.5):
# Less terms to sum if we calculate log(1-sf)
res.append(log1p(-exp(self.logsf(quant, tot, good, draw))))
else:
# Integration over probability mass function using logsumexp
k2 = np.arange(0, quant + 1)
res.append(logsumexp(self._logpmf(k2, tot, good, draw)))
return np.asarray(res)
hypergeom = hypergeom_gen(name='hypergeom')
| hypergeom_gen |
python | getsentry__sentry | tests/sentry/issues/endpoints/test_organization_group_search_view_details.py | {
"start": 403,
"end": 3538
} | class ____(APITestCase):
def create_base_data(self) -> dict[str, list[GroupSearchView]]:
user_1 = self.user
self.user_2 = self.create_user()
self.user_3 = self.create_user()
self.create_member(organization=self.organization, user=self.user_2)
self.create_member(organization=self.organization, user=self.user_3)
first_custom_view_user_one = GroupSearchView.objects.create(
name="Custom View One",
organization=self.organization,
user_id=user_1.id,
query="is:unresolved",
query_sort="date",
)
GroupSearchViewStarred.objects.create(
organization=self.organization,
user_id=user_1.id,
group_search_view=first_custom_view_user_one,
position=0,
)
# This is out of order to test that the endpoint returns the views in the correct order
third_custom_view_user_one = GroupSearchView.objects.create(
name="Custom View Three",
organization=self.organization,
user_id=user_1.id,
query="is:ignored",
query_sort="freq",
)
GroupSearchViewStarred.objects.create(
organization=self.organization,
user_id=user_1.id,
group_search_view=third_custom_view_user_one,
position=2,
)
second_custom_view_user_one = GroupSearchView.objects.create(
name="Custom View Two",
organization=self.organization,
user_id=user_1.id,
query="is:resolved",
query_sort="new",
)
GroupSearchViewStarred.objects.create(
organization=self.organization,
user_id=user_1.id,
group_search_view=second_custom_view_user_one,
position=1,
)
first_custom_view_user_two = GroupSearchView.objects.create(
name="Custom View One",
organization=self.organization,
user_id=self.user_2.id,
query="is:unresolved",
query_sort="date",
)
GroupSearchViewStarred.objects.create(
organization=self.organization,
user_id=self.user_2.id,
group_search_view=first_custom_view_user_two,
position=0,
)
second_custom_view_user_two = GroupSearchView.objects.create(
name="Custom View Two",
organization=self.organization,
user_id=self.user_2.id,
query="is:resolved",
query_sort="new",
)
GroupSearchViewStarred.objects.create(
organization=self.organization,
user_id=self.user_2.id,
group_search_view=second_custom_view_user_two,
position=1,
)
return {
"user_one_views": [
first_custom_view_user_one,
second_custom_view_user_one,
third_custom_view_user_one,
],
"user_two_views": [first_custom_view_user_two, second_custom_view_user_two],
}
| BaseGSVTestCase |
python | django__django | docs/_ext/djangodocs.py | {
"start": 3691,
"end": 6672
} | class ____(HTMLTranslator):
"""
Django-specific reST to HTML tweaks.
"""
# Don't use border=1, which docutils does by default.
def visit_table(self, node):
self.context.append(self.compact_p)
self.compact_p = True
# Needed by Sphinx.
self._table_row_indices.append(0)
self.body.append(self.starttag(node, "table", CLASS="docutils"))
def depart_table(self, node):
self.compact_p = self.context.pop()
self._table_row_indices.pop()
self.body.append("</table>\n")
def visit_desc_parameterlist(self, node):
self.body.append("(") # by default sphinx puts <big> around the "("
self.optional_param_level = 0
self.param_separator = node.child_text_separator
# Counts 'parameter groups' being either a required parameter, or a set
# of contiguous optional ones.
required_params = [
isinstance(c, addnodes.desc_parameter) for c in node.children
]
# How many required parameters are left.
self.required_params_left = sum(required_params)
if sphinx_version < (7, 1):
self.first_param = 1
else:
self.is_first_param = True
self.params_left_at_level = 0
self.param_group_index = 0
self.list_is_required_param = required_params
self.multi_line_parameter_list = False
def depart_desc_parameterlist(self, node):
self.body.append(")")
#
# Turn the "new in version" stuff (versionadded/versionchanged) into a
# better callout -- the Sphinx default is just a little span,
# which is a bit less obvious that I'd like.
#
# FIXME: these messages are all hardcoded in English. We need to change
# that to accommodate other language docs, but I can't work out how to make
# that work.
#
version_text = {
"versionchanged": "Changed in Django %s",
"versionadded": "New in Django %s",
}
def visit_versionmodified(self, node):
self.body.append(self.starttag(node, "div", CLASS=node["type"]))
version_text = self.version_text.get(node["type"])
if version_text:
title = "%s%s" % (version_text % node["version"], ":" if len(node) else ".")
self.body.append('<span class="title">%s</span> ' % title)
def depart_versionmodified(self, node):
self.body.append("</div>\n")
# Give each section a unique ID -- nice for custom CSS hooks
def visit_section(self, node):
old_ids = node.get("ids", [])
node["ids"] = ["s-" + i for i in old_ids]
node["ids"].extend(old_ids)
super().visit_section(node)
node["ids"] = old_ids
def parse_django_admin_node(env, sig, signode):
command = sig.split(" ")[0]
env.ref_context["std:program"] = command
title = "django-admin %s" % sig
signode += addnodes.desc_name(title, title)
return command
| DjangoHTMLTranslator |
python | dagster-io__dagster | python_modules/libraries/dagster-dg-core/dagster_dg_core/context.py | {
"start": 25256,
"end": 25577
} | class ____:
timestamp: float
raw_versions: list[str]
@property
def datetime(self) -> datetime.datetime:
return datetime.datetime.fromtimestamp(self.timestamp)
@cached_property
def versions(self) -> list[Version]:
return sorted(Version(v) for v in self.raw_versions)
| DgPyPiVersionInfo |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.