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 | bokeh__bokeh | tests/unit/bokeh/core/test_has_props.py | {
"start": 14695,
"end": 14818
} | class ____(hp.HasProps, hp.Local):
f0 = String(default="xyz")
f1 = List(String, default=["x", "y", "z"])
| Some1HasProps |
python | kamyu104__LeetCode-Solutions | Python/zigzag-conversion.py | {
"start": 29,
"end": 523
} | class ____(object):
def convert(self, s, numRows):
"""
:type s: str
:type numRows: int
:rtype: str
"""
if numRows == 1:
return s
step, zigzag = 2 * numRows - 2, ""
for i in xrange(numRows):
for j in xrange(i, len(s), step):
zigzag += s[j]
if 0 < i < numRows - 1 and j + step - 2 * i < len(s):
zigzag += s[j + step - 2 * i]
return zigzag
| Solution |
python | dagster-io__dagster | python_modules/libraries/dagster-dg-cli/dagster_dg_cli/api_layer/api/schedule.py | {
"start": 442,
"end": 1787
} | class ____:
"""API for schedule operations."""
client: IGraphQLClient
def list_schedules(
self,
repository_location_name: Optional[str] = None,
repository_name: Optional[str] = None,
) -> "DgApiScheduleList":
"""List all schedules, optionally filtered by code location and name."""
return list_schedules_via_graphql(
self.client,
repository_location_name=repository_location_name,
repository_name=repository_name,
)
def get_schedule(
self,
schedule_name: str,
repository_location_name: str,
repository_name: str,
) -> "DgApiSchedule":
"""Get schedule by name and code location details."""
return get_schedule_via_graphql(
self.client,
schedule_name=schedule_name,
repository_location_name=repository_location_name,
repository_name=repository_name,
)
def get_schedule_by_name(self, schedule_name: str) -> "DgApiSchedule":
"""Get schedule by name, searching across all code locations."""
from dagster_dg_cli.api_layer.graphql_adapter.schedule import (
get_schedule_by_name_via_graphql,
)
return get_schedule_by_name_via_graphql(self.client, schedule_name=schedule_name)
| DgApiScheduleApi |
python | huggingface__transformers | tests/generation/test_flash_attention_parity.py | {
"start": 890,
"end": 5686
} | class ____(unittest.TestCase):
# From https://github.com/sgl-project/sglang/blob/main/python/sglang/test/test_utils.py
def _lcs(self, X, Y):
m = len(X)
n = len(Y)
L = [[0] * (n + 1) for _ in range(m + 1)]
for i in range(m + 1):
for j in range(n + 1):
if i == 0 or j == 0:
L[i][j] = 0
elif X[i - 1] == Y[j - 1]:
L[i][j] = L[i - 1][j - 1] + 1
else:
L[i][j] = max(L[i - 1][j], L[i][j - 1])
return L[m][n]
# From https://github.com/sgl-project/sglang/blob/main/python/sglang/test/test_utils.py
def _calculate_rouge_l(self, output_strs_list1, output_strs_list2):
rouge_l_scores = []
for s1, s2 in zip(output_strs_list1, output_strs_list2):
lcs_len = self._lcs(s1, s2)
precision = lcs_len / len(s1) if len(s1) > 0 else 0
recall = lcs_len / len(s2) if len(s2) > 0 else 0
if precision + recall > 0:
fmeasure = (2 * precision * recall) / (precision + recall)
else:
fmeasure = 0.0
rouge_l_scores.append(fmeasure)
return rouge_l_scores
def _benchmark_generation(self, model, inputs, n_warmup=3, n_runs=5):
for _ in range(n_warmup):
model.generate(**inputs, max_new_tokens=20, do_sample=False)
torch.cuda.synchronize()
start_time = torch.cuda.Event(enable_timing=True)
end_time = torch.cuda.Event(enable_timing=True)
start_time.record()
for _ in range(n_runs):
model.generate(**inputs, max_new_tokens=20, do_sample=False)
end_time.record()
torch.cuda.synchronize()
return start_time.elapsed_time(end_time) / n_runs
@pytest.mark.flash_attn_3_test
@require_torch_gpu
@require_flash_attn
@require_flash_attn_3
@slow
def test_flash_attention_2_3_parity(self):
model_id = "meta-llama/Llama-3.2-1B-Instruct"
prompt = ["The ETH AI Center is", "What is life?"]
# 1. Load model and tokenizer
model = AutoModelForCausalLM.from_pretrained(
model_id,
dtype=torch.bfloat16,
attn_implementation="flash_attention_2",
).to("cuda")
tokenizer = AutoTokenizer.from_pretrained(model_id)
tokenizer.pad_token_id = tokenizer.eos_token_id
# 2. Generate with both models
inputs = tokenizer(prompt, padding=True, padding_side="left", return_tensors="pt").to("cuda")
with torch.no_grad():
output_2 = model.generate(
**inputs, max_new_tokens=20, do_sample=False, output_scores=True, return_dict_in_generate=True
)
model.set_attn_implementation("flash_attention_3")
output_3 = model.generate(
**inputs, max_new_tokens=20, do_sample=False, output_scores=True, return_dict_in_generate=True
)
# 3. Correctness check
# 3a. Logits
logits_2 = torch.stack(output_2.scores)
logits_3 = torch.stack(output_3.scores)
torch.testing.assert_close(logits_2, logits_3, atol=1e-3, rtol=1e-3)
logprobs_2 = torch.nn.functional.log_softmax(logits_2, dim=-1)
logprobs_3 = torch.nn.functional.log_softmax(logits_3, dim=-1)
max_logprob_diff = torch.max(torch.abs(logprobs_2 - logprobs_3)).item()
# 3b. Generated text
text_2s, text_3s = [], []
for i in range(len(prompt)):
text_2s.append(tokenizer.decode(output_2.sequences[i], skip_special_tokens=True))
text_3s.append(tokenizer.decode(output_3.sequences[i], skip_special_tokens=True))
rouge_scores = self._calculate_rouge_l(text_2s, text_3s)
for i in range(len(rouge_scores)):
assert rouge_scores[i] > 0.99, f"Generated texts at prompt {i} do not match (ROUGE-L: {rouge_scores[i]})"
# 4. Performance check
with torch.no_grad():
time_3 = self._benchmark_generation(model, inputs)
model.set_attn_implementation("flash_attention_2")
time_2 = self._benchmark_generation(model, inputs)
print(f"\n--- Flash Attention {2, 3} Parity Test on {model_id} ---")
print(f"Prompt: '{prompt}'")
print(f"Generated text with Flash Attention 2: {text_2s}")
print(f"Generated text with Flash Attention 3: {text_3s}")
print(f"ROUGE-L: {rouge_scores}")
print(f"Max absolute difference in logprobs: {max_logprob_diff:.5e}")
print(f"Flash Attention 2 latency: {time_2:.2f} ms")
print(f"Flash Attention 3 latency: {time_3:.2f} ms")
print(f"Speed-up: {time_2 / time_3:.2f}x")
print("---")
| FlashAttentionParityTest |
python | davidhalter__jedi | test/completion/goto.py | {
"start": 1014,
"end": 1290
} | class ____():
x = 3
#! ['x = 3']
ClassVar.x
#! ['x = 3']
ClassVar().x
# before assignments
#! 10 ['x = 3']
ClassVar.x = ''
#! 12 ['x = 3']
ClassVar().x = ''
# Recurring use of the same var name, github #315
def f(t=None):
#! 9 ['param t=None']
t = t or 1
| ClassVar |
python | allegroai__clearml | clearml/backend_api/services/v2_20/projects.py | {
"start": 79370,
"end": 82731
} | class ____(Response):
"""
Response of projects.get_by_id endpoint.
:param project: Project info
:type project: Project
"""
_service = "projects"
_action = "get_by_id"
_version = "2.20"
_schema = {
"definitions": {
"project": {
"properties": {
"basename": {
"description": "Project base name",
"type": ["string", "null"],
},
"company": {
"description": "Company id",
"type": ["string", "null"],
},
"created": {
"description": "Creation time",
"format": "date-time",
"type": ["string", "null"],
},
"default_output_destination": {
"description": "The default output destination URL for new tasks under this project",
"type": ["string", "null"],
},
"description": {
"description": "Project description",
"type": ["string", "null"],
},
"id": {"description": "Project id", "type": ["string", "null"]},
"last_update": {
"description": "Last project update time. Reflects the last time the project metadata was changed or a task in this project has changed status",
"format": "date-time",
"type": ["string", "null"],
},
"name": {"description": "Project name", "type": ["string", "null"]},
"system_tags": {
"description": "System tags. This field is reserved for system use, please don't use it.",
"items": {"type": "string"},
"type": ["array", "null"],
},
"tags": {
"description": "User-defined tags",
"items": {"type": "string"},
"type": ["array", "null"],
},
"user": {
"description": "Associated user id",
"type": ["string", "null"],
},
},
"type": "object",
}
},
"properties": {
"project": {
"description": "Project info",
"oneOf": [{"$ref": "#/definitions/project"}, {"type": "null"}],
}
},
"type": "object",
}
def __init__(self, project: Any = None, **kwargs: Any) -> None:
super(GetByIdResponse, self).__init__(**kwargs)
self.project = project
@schema_property("project")
def project(self) -> Any:
return self._property_project
@project.setter
def project(self, value: Any) -> None:
if value is None:
self._property_project = None
return
if isinstance(value, dict):
value = Project.from_dict(value)
else:
self.assert_isinstance(value, "project", Project)
self._property_project = value
| GetByIdResponse |
python | ansible__ansible | test/integration/targets/collections/collection_root_user/ansible_collections/testns/testcoll/plugins/action/subclassed_normal.py | {
"start": 109,
"end": 335
} | class ____(NormalAction):
def run(self, *args, **kwargs):
result = super(ActionModule, self).run(*args, **kwargs)
result['hacked'] = 'I got run under a subclassed normal, yay'
return result
| ActionModule |
python | ipython__ipython | tests/test_completer.py | {
"start": 6954,
"end": 7117
} | class ____:
def __init__(self, things=()):
self.things = things
def _ipython_key_completions_(self):
return list(self.things)
| KeyCompletable |
python | vyperlang__vyper | vyper/exceptions.py | {
"start": 9360,
"end": 9431
} | class ____(VyperException):
"""Module was not found"""
| ModuleNotFound |
python | django__django | tests/auth_tests/test_views.py | {
"start": 28580,
"end": 29480
} | class ____(AuthViewsTestCase):
def test_user_password_change_updates_session(self):
"""
#21649 - Ensure contrib.auth.views.password_change updates the user's
session auth hash after a password change so the session isn't logged
out.
"""
self.login()
original_session_key = self.client.session.session_key
response = self.client.post(
"/password_change/",
{
"old_password": "password",
"new_password1": "password1",
"new_password2": "password1",
},
)
# if the hash isn't updated, retrieving the redirection page will fail.
self.assertRedirects(response, "/password_change/done/")
# The session key is rotated.
self.assertNotEqual(original_session_key, self.client.session.session_key)
| SessionAuthenticationTests |
python | google__jax | tests/hijax_test.py | {
"start": 4493,
"end": 4951
} | class ____(HiPrimitive):
def abstract_eval(_, lo_aval):
return QArrayTy(lo_aval.shape), set()
def to_lojax(_, lo_val):
m, _ = lo_val.shape
scale = lo_val.max(1) / 32.
return QArray((lo_val / scale[:, None]).astype('int8'), scale)
def jvp(_, primals, tangents):
(x,), (xdot,) = primals, tangents
return to_qarray(x), to_qarray(xdot)
def transpose(_, out_bar, __):
return [from_qarray(out_bar)]
to_qarray_p = ToQ('to_q')
| ToQ |
python | joke2k__faker | faker/providers/geo/cs_CZ/__init__.py | {
"start": 41,
"end": 11409
} | class ____(GeoProvider):
# Source:
# https://www.latlong.net/category/cities-59-15.html
# https://github.com/33bcdd/souradnice-mest
land_coords = (
("50.50301", "13.63617", "Most", "CZ", "Europe/Prague"),
("50.23271", "12.87117", "Karlovy Vary", "CZ", "Europe/Prague"),
("50.073658", "14.418540", "Praha", "CZ", "Europe/Prague"),
("49.144482", "15.006139", "Jindřichův Hradec", "CZ", "Europe/Prague"),
("48.975658", "14.480255", "České Budějovice", "CZ", "Europe/Prague"),
("50.511002", "14.150558", "Terezín", "CZ", "Europe/Prague"),
("49.183239", "15.454273", "Telč", "CZ", "Europe/Prague"),
("49.952431", "15.268654", "Kutná Hora", "CZ", "Europe/Prague"),
("49.593777", "17.250879", "Olomouc", "CZ", "Europe/Prague"),
("49.738430", "13.373637", "Plzeň", "CZ", "Europe/Prague"),
("48.812737", "14.317466", "Český Krumlov", "CZ", "Europe/Prague"),
("49.195061", "16.606836", "Brno", "CZ", "Europe/Prague"),
("50.598427", "13.610242", "Litvínov", "CZ", "Europe/Prague"),
("49.820923", "18.262524", "Ostrava", "CZ", "Europe/Prague"),
("49.967305", "14.086384", "Beroun", "CZ", "Europe/Prague"),
("50.678620", "14.539799", "Česká Lípa", "CZ", "Europe/Prague"),
("50.772656", "14.212861", "DĚČÍN", "CZ", "Europe/Prague"),
("49.682031", "18.367422", "FRÝDEK-MÍSTEK", "CZ", "Europe/Prague"),
("49.780492", "18.430725", "HAVÍŘOV", "CZ", "Europe/Prague"),
("49.052354", "14.434371", "Hluboká nad Vltavou", "CZ", "Europe/Prague"),
("50.210461", "15.825311", "HRADEC KRÁLOVÉ", "CZ", "Europe/Prague"),
("50.463598", "13.410837", "Chomutov", "CZ", "Europe/Prague"),
("50.703569", "15.429698", "Jablonec nad Jizerou", "CZ", "Europe/Prague"),
("50.722153", "15.170414", "Jablonec nad Nisou", "CZ", "Europe/Prague"),
("50.435433", "15.361144", "Jičín", "CZ", "Europe/Prague"),
("49.415860", "15.595469", "Jihlava", "CZ", "Europe/Prague"),
("49.939604", "14.188146", "Karlštejn", "CZ", "Europe/Prague"),
("49.856752", "18.543319", "KARVINÁ", "CZ", "Europe/Prague"),
("50.141799", "14.106846", "Kladno", "CZ", "Europe/Prague"),
("50.525685", "14.047429", "Lhotka nad Labem", "CZ", "Europe/Prague"),
("49.890040", "13.581715", "Lhotka u Radnic", "CZ", "Europe/Prague"),
("50.055957", "16.268803", "Lhoty u Potštejna", "CZ", "Europe/Prague"),
("50.766380", "15.054439", "Liberec", "CZ", "Europe/Prague"),
("49.772128", "15.676917", "Maleč", "CZ", "Europe/Prague"),
("50.413525", "14.908538", "Mladá Boleslav", "CZ", "Europe/Prague"),
("49.425534", "16.256425", "Moravecké Pavlovice", "CZ", "Europe/Prague"),
("49.940760", "17.894899", "Opava", "CZ", "Europe/Prague"),
("49.916939", "17.869927", "Otice", "CZ", "Europe/Prague"),
("50.034409", "15.781299", "Pardubice", "CZ", "Europe/Prague"),
("49.472549", "17.106851", "PROSTĚJOV", "CZ", "Europe/Prague"),
("49.456579", "17.450330", "PŘEROV", "CZ", "Europe/Prague"),
("50.072880", "15.802625", "Ráby", "CZ", "Europe/Prague"),
("49.458626", "18.143131", "Rožnov pod Radhoštěm", "CZ", "Europe/Prague"),
("49.981095", "16.877925", "Ruda nad Moravou", "CZ", "Europe/Prague"),
("50.020519", "17.377529", "Rudná pod Pradědem", "CZ", "Europe/Prague"),
("50.454193", "16.036726", "Slatina nad Úpou", "CZ", "Europe/Prague"),
("49.377245", "17.670437", "Slavkov pod Hostýnem", "CZ", "Europe/Prague"),
("49.153354", "16.876598", "Slavkov u Brna", "CZ", "Europe/Prague"),
("49.991014", "15.350597", "Svatý Mikuláš", "CZ", "Europe/Prague"),
("49.977941", "16.971875", "Šumperk", "CZ", "Europe/Prague"),
("49.413089", "14.677566", "Tábor", "CZ", "Europe/Prague"),
("50.644558", "13.835384", "Teplice", "CZ", "Europe/Prague"),
("49.214887", "15.879652", "Třebíč", "CZ", "Europe/Prague"),
("49.677731", "18.670890", "Třinec", "CZ", "Europe/Prague"),
("50.151203", "16.078551", "Týniště nad Orlicí", "CZ", "Europe/Prague"),
("50.661216", "14.053246", "ÚSTÍ NAD LABEM", "CZ", "Europe/Prague"),
("49.139664", "18.008570", "Valašské Klobouky", "CZ", "Europe/Prague"),
("49.471904", "17.971237", "Valašské Meziříčí", "CZ", "Europe/Prague"),
("49.954364", "16.164268", "Vysoké Mýto", "CZ", "Europe/Prague"),
("49.224537", "17.662863", "ZLÍN", "CZ", "Europe/Prague"),
("50.538847", "16.213389", "Žďár nad Metují", "CZ", "Europe/Prague"),
("50.119855", "16.069446", "Žďár nad Orlicí", "CZ", "Europe/Prague"),
("49.564288", "15.939507", "Žďár nad Sázavou", "CZ", "Europe/Prague"),
("49.696057", "15.813706", "Ždírec nad Doubravou", "CZ", "Europe/Prague"),
("50.139886", "16.064472", "Albrechtice nad Orlicí", "CZ", "Europe/Prague"),
("49.253337", "14.302929", "Albrechtice nad Vltavou", "CZ", "Europe/Prague"),
("50.762400", "15.275813", "Albrechtice v Jizerských horách", "CZ", "Europe/Prague"),
("50.223983", "12.195113", "Aš", "CZ", "Europe/Prague"),
("50.482406", "14.941596", "Bakov nad Jizerou", "CZ", "Europe/Prague"),
("49.452124", "14.608319", "Balkova Lhota", "CZ", "Europe/Prague"),
("50.164080", "16.547862", "Bartošovice v Orlických horách", "CZ", "Europe/Prague"),
("49.245527", "17.426201", "Bařice-Velké Těšany", "CZ", "Europe/Prague"),
("50.083561", "12.838429", "Bečov nad Teplou", "CZ", "Europe/Prague"),
("49.956809", "15.079916", "Bečváry", "CZ", "Europe/Prague"),
("49.295336", "14.468202", "Bechyně", "CZ", "Europe/Prague"),
("49.591261", "12.717718", "Bělá nad Radbuzou", "CZ", "Europe/Prague"),
("50.501314", "14.804290", "Bělá pod Bezdězem", "CZ", "Europe/Prague"),
("50.164036", "17.196677", "Bělá pod Pradědem", "CZ", "Europe/Prague"),
("50.198081", "15.942805", "Běleč nad Orlicí", "CZ", "Europe/Prague"),
("49.668757", "17.317289", "Bělkovice-Lašťany", "CZ", "Europe/Prague"),
("50.289261", "14.824612", "Benátky nad Jizerou", "CZ", "Europe/Prague"),
("49.709629", "16.975180", "Bílá Lhota", "CZ", "Europe/Prague"),
("50.444749", "15.741120", "Bílá Třemešná", "CZ", "Europe/Prague"),
("49.364950", "16.647855", "Blansko", "CZ", "Europe/Prague"),
("49.525208", "13.302442", "Borovy", "CZ", "Europe/Prague"),
("50.409844", "12.924571", "Boží Dar", "CZ", "Europe/Prague"),
("49.888057", "17.882754", "Branka u Opavy", "CZ", "Europe/Prague"),
("49.835396", "12.741203", "Brod nad Tichou", "CZ", "Europe/Prague"),
("48.753240", "16.882617", "Břeclav", "CZ", "Europe/Prague"),
("49.644277", "16.518096", "Březová nad Svitavou", "CZ", "Europe/Prague"),
("49.904148", "14.411028", "Březová-Oleško", "CZ", "Europe/Prague"),
("49.795210", "17.629792", "Budišov nad Budišovkou", "CZ", "Europe/Prague"),
("50.404377", "14.126018", "Budyně nad Ohří", "CZ", "Europe/Prague"),
("49.042267", "17.100961", "Bukovany", "CZ", "Europe/Prague"),
("50.604834", "15.401976", "Bystrá nad Jizerou", "CZ", "Europe/Prague"),
("49.551061", "17.037775", "Čechy pod Kosířem", "CZ", "Europe/Prague"),
("50.080411", "16.144089", "Čermná nad Orlicí", "CZ", "Europe/Prague"),
("49.941659", "14.806890", "Černé Voděrady", "CZ", "Europe/Prague"),
("49.810991", "14.928256", "Český Šternberk", "CZ", "Europe/Prague"),
("49.747144", "18.623896", "Český Těšín", "CZ", "Europe/Prague"),
("50.438699", "13.908578", "Děčany", "CZ", "Europe/Prague"),
("50.171283", "13.554483", "Děkov", "CZ", "Europe/Prague"),
("50.147821", "15.641146", "Dobřenice", "CZ", "Europe/Prague"),
("49.304851", "16.060208", "Dolní Heřmanice", "CZ", "Europe/Prague"),
("49.486182", "14.797204", "Dolní Hrachovice", "CZ", "Europe/Prague"),
("50.982619", "14.286956", "Dolní Poustevna", "CZ", "Europe/Prague"),
("50.438436", "16.151339", "Dolní Radechová", "CZ", "Europe/Prague"),
("50.080232", "13.475770", "Drahouš", "CZ", "Europe/Prague"),
("49.591902", "18.358605", "Frýdlant nad Ostravicí", "CZ", "Europe/Prague"),
("50.652357", "15.158867", "Frýdštejn", "CZ", "Europe/Prague"),
("50.665963", "15.089960", "Hodkovice nad Mohelkou", "CZ", "Europe/Prague"),
("49.406486", "16.777804", "Holštejn", "CZ", "Europe/Prague"),
("49.057721", "13.558075", "Horská Kvilda", "CZ", "Europe/Prague"),
("49.530286", "12.944527", "Horšovský Týn", "CZ", "Europe/Prague"),
("50.852892", "14.844658", "Hrádek nad Nisou", "CZ", "Europe/Prague"),
("49.971920", "13.646002", "Chříč", "CZ", "Europe/Prague"),
("49.094184", "15.893408", "Jaroměřice nad Rokytnou", "CZ", "Europe/Prague"),
("49.189995", "15.067440", "Jarošov nad Nežárkou", "CZ", "Europe/Prague"),
("50.755788", "15.263030", "Jiřetín pod Bukovou", "CZ", "Europe/Prague"),
("50.874552", "14.575190", "Jiřetín pod Jedlovou", "CZ", "Europe/Prague"),
("49.045476", "17.407042", "Kostelany nad Moravou", "CZ", "Europe/Prague"),
("50.184587", "14.954085", "Kostomlaty nad Labem", "CZ", "Europe/Prague"),
("50.383135", "14.333177", "Kostomlaty pod Řípem", "CZ", "Europe/Prague"),
("50.774549", "14.933501", "Kryštofovo Údolí", "CZ", "Europe/Prague"),
("50.499571", "13.136207", "Kryštofovy Hamry", "CZ", "Europe/Prague"),
("50.768777", "14.678722", "Kunratice u Cvikova", "CZ", "Europe/Prague"),
("49.695269", "15.277827", "Ledeč nad Sázavou", "CZ", "Europe/Prague"),
("49.304675", "17.958094", "Lhota u Vsetína", "CZ", "Europe/Prague"),
("49.613125", "15.413664", "Lipnice nad Sázavou", "CZ", "Europe/Prague"),
("49.526832", "17.586743", "Lipník nad Bečvou", "CZ", "Europe/Prague"),
("49.602226", "17.065499", "Náměšť na Hané", "CZ", "Europe/Prague"),
("49.205556", "16.155845", "Náměšť nad Oslavou", "CZ", "Europe/Prague"),
("49.561543", "16.074288", "Nové Město na Moravě", "CZ", "Europe/Prague"),
("50.344662", "16.151571", "Nové Město nad Metují", "CZ", "Europe/Prague"),
("50.925011", "15.229539", "Nové Město pod Smrkem", "CZ", "Europe/Prague"),
("49.325143", "16.168556", "Osová Bítýška", "CZ", "Europe/Prague"),
("49.953112", "12.779206", "Ovesné Kladruby", "CZ", "Europe/Prague"),
("50.160370", "14.825129", "Přerov nad Labem", "CZ", "Europe/Prague"),
("50.315762", "15.796171", "Račice nad Trotinou", "CZ", "Europe/Prague"),
("49.276006", "16.872942", "Račice-Pístovice", "CZ", "Europe/Prague"),
("49.630522", "17.328172", "Samotišky", "CZ", "Europe/Prague"),
("49.143644", "15.877648", "Výčapy", "CZ", "Europe/Prague"),
("49.842785", "14.884454", "Xaverov", "CZ", "Europe/Prague"),
("49.511965", "17.431217", "Zábeštní Lhota", "CZ", "Europe/Prague"),
("49.046302", "13.899419", "Žárovná", "CZ", "Europe/Prague"),
("49.610734", "15.735236", "Žižkovo Pole", "CZ", "Europe/Prague"),
("49.873077", "15.858205", "Žumberk", "CZ", "Europe/Prague"),
)
| Provider |
python | scrapy__scrapy | tests/test_commands.py | {
"start": 2890,
"end": 3382
} | class ____(TestProjectBase):
"""Test that the command uses the expected kind of *CrawlerProcess
and produces expected errors when needed."""
name = "crawl"
NORMAL_MSG = "Using CrawlerProcess"
ASYNC_MSG = "Using AsyncCrawlerProcess"
@pytest.fixture(autouse=True)
def create_files(self, proj_path: Path) -> None:
proj_mod_path = proj_path / self.project_name
(proj_mod_path / "spiders" / "sp.py").write_text("""
import scrapy
| TestCommandCrawlerProcess |
python | scipy__scipy | scipy/stats/tests/test_mstats_basic.py | {
"start": 814,
"end": 2138
} | class ____:
def test_mquantiles_limit_keyword(self):
# Regression test for Trac ticket #867
data = np.array([[6., 7., 1.],
[47., 15., 2.],
[49., 36., 3.],
[15., 39., 4.],
[42., 40., -999.],
[41., 41., -999.],
[7., -999., -999.],
[39., -999., -999.],
[43., -999., -999.],
[40., -999., -999.],
[36., -999., -999.]])
desired = [[19.2, 14.6, 1.45],
[40.0, 37.5, 2.5],
[42.8, 40.05, 3.55]]
quants = mstats.mquantiles(data, axis=0, limit=(0, 50))
assert_almost_equal(quants, desired)
def check_equal_gmean(array_like, desired, axis=None, dtype=None, rtol=1e-7):
# Note this doesn't test when axis is not specified
x = mstats.gmean(array_like, axis=axis, dtype=dtype)
assert_allclose(x, desired, rtol=rtol)
assert_equal(x.dtype, dtype)
def check_equal_hmean(array_like, desired, axis=None, dtype=None, rtol=1e-7):
x = stats.hmean(array_like, axis=axis, dtype=dtype)
assert_allclose(x, desired, rtol=rtol)
assert_equal(x.dtype, dtype)
@skip_xp_invalid_arg
| TestMquantiles |
python | boto__boto3 | boto3/resources/factory.py | {
"start": 953,
"end": 22708
} | class ____:
"""
A factory to create new :py:class:`~boto3.resources.base.ServiceResource`
classes from a :py:class:`~boto3.resources.model.ResourceModel`. There are
two types of lookups that can be done: one on the service itself (e.g. an
SQS resource) and another on models contained within the service (e.g. an
SQS Queue resource).
"""
def __init__(self, emitter):
self._collection_factory = CollectionFactory()
self._emitter = emitter
def load_from_definition(
self, resource_name, single_resource_json_definition, service_context
):
"""
Loads a resource from a model, creating a new
:py:class:`~boto3.resources.base.ServiceResource` subclass
with the correct properties and methods, named based on the service
and resource name, e.g. EC2.Instance.
:type resource_name: string
:param resource_name: Name of the resource to look up. For services,
this should match the ``service_name``.
:type single_resource_json_definition: dict
:param single_resource_json_definition:
The loaded json of a single service resource or resource
definition.
:type service_context: :py:class:`~boto3.utils.ServiceContext`
:param service_context: Context about the AWS service
:rtype: Subclass of :py:class:`~boto3.resources.base.ServiceResource`
:return: The service or resource class.
"""
logger.debug(
'Loading %s:%s', service_context.service_name, resource_name
)
# Using the loaded JSON create a ResourceModel object.
resource_model = ResourceModel(
resource_name,
single_resource_json_definition,
service_context.resource_json_definitions,
)
# Do some renaming of the shape if there was a naming collision
# that needed to be accounted for.
shape = None
if resource_model.shape:
shape = service_context.service_model.shape_for(
resource_model.shape
)
resource_model.load_rename_map(shape)
# Set some basic info
meta = ResourceMeta(
service_context.service_name, resource_model=resource_model
)
attrs = {
'meta': meta,
}
# Create and load all of attributes of the resource class based
# on the models.
# Identifiers
self._load_identifiers(
attrs=attrs,
meta=meta,
resource_name=resource_name,
resource_model=resource_model,
)
# Load/Reload actions
self._load_actions(
attrs=attrs,
resource_name=resource_name,
resource_model=resource_model,
service_context=service_context,
)
# Attributes that get auto-loaded
self._load_attributes(
attrs=attrs,
meta=meta,
resource_name=resource_name,
resource_model=resource_model,
service_context=service_context,
)
# Collections and their corresponding methods
self._load_collections(
attrs=attrs,
resource_model=resource_model,
service_context=service_context,
)
# References and Subresources
self._load_has_relations(
attrs=attrs,
resource_name=resource_name,
resource_model=resource_model,
service_context=service_context,
)
# Waiter resource actions
self._load_waiters(
attrs=attrs,
resource_name=resource_name,
resource_model=resource_model,
service_context=service_context,
)
# Create the name based on the requested service and resource
cls_name = resource_name
if service_context.service_name == resource_name:
cls_name = 'ServiceResource'
cls_name = service_context.service_name + '.' + cls_name
base_classes = [ServiceResource]
if self._emitter is not None:
self._emitter.emit(
f'creating-resource-class.{cls_name}',
class_attributes=attrs,
base_classes=base_classes,
service_context=service_context,
)
return type(str(cls_name), tuple(base_classes), attrs)
def _load_identifiers(self, attrs, meta, resource_model, resource_name):
"""
Populate required identifiers. These are arguments without which
the resource cannot be used. Identifiers become arguments for
operations on the resource.
"""
for identifier in resource_model.identifiers:
meta.identifiers.append(identifier.name)
attrs[identifier.name] = self._create_identifier(
identifier, resource_name
)
def _load_actions(
self, attrs, resource_name, resource_model, service_context
):
"""
Actions on the resource become methods, with the ``load`` method
being a special case which sets internal data for attributes, and
``reload`` is an alias for ``load``.
"""
if resource_model.load:
attrs['load'] = self._create_action(
action_model=resource_model.load,
resource_name=resource_name,
service_context=service_context,
is_load=True,
)
attrs['reload'] = attrs['load']
for action in resource_model.actions:
attrs[action.name] = self._create_action(
action_model=action,
resource_name=resource_name,
service_context=service_context,
)
def _load_attributes(
self, attrs, meta, resource_name, resource_model, service_context
):
"""
Load resource attributes based on the resource shape. The shape
name is referenced in the resource JSON, but the shape itself
is defined in the Botocore service JSON, hence the need for
access to the ``service_model``.
"""
if not resource_model.shape:
return
shape = service_context.service_model.shape_for(resource_model.shape)
identifiers = {
i.member_name: i
for i in resource_model.identifiers
if i.member_name
}
attributes = resource_model.get_attributes(shape)
for name, (orig_name, member) in attributes.items():
if name in identifiers:
prop = self._create_identifier_alias(
resource_name=resource_name,
identifier=identifiers[name],
member_model=member,
service_context=service_context,
)
else:
prop = self._create_autoload_property(
resource_name=resource_name,
name=orig_name,
snake_cased=name,
member_model=member,
service_context=service_context,
)
attrs[name] = prop
def _load_collections(self, attrs, resource_model, service_context):
"""
Load resource collections from the model. Each collection becomes
a :py:class:`~boto3.resources.collection.CollectionManager` instance
on the resource instance, which allows you to iterate and filter
through the collection's items.
"""
for collection_model in resource_model.collections:
attrs[collection_model.name] = self._create_collection(
resource_name=resource_model.name,
collection_model=collection_model,
service_context=service_context,
)
def _load_has_relations(
self, attrs, resource_name, resource_model, service_context
):
"""
Load related resources, which are defined via a ``has``
relationship but conceptually come in two forms:
1. A reference, which is a related resource instance and can be
``None``, such as an EC2 instance's ``vpc``.
2. A subresource, which is a resource constructor that will always
return a resource instance which shares identifiers/data with
this resource, such as ``s3.Bucket('name').Object('key')``.
"""
for reference in resource_model.references:
# This is a dangling reference, i.e. we have all
# the data we need to create the resource, so
# this instance becomes an attribute on the class.
attrs[reference.name] = self._create_reference(
reference_model=reference,
resource_name=resource_name,
service_context=service_context,
)
for subresource in resource_model.subresources:
# This is a sub-resource class you can create
# by passing in an identifier, e.g. s3.Bucket(name).
attrs[subresource.name] = self._create_class_partial(
subresource_model=subresource,
resource_name=resource_name,
service_context=service_context,
)
self._create_available_subresources_command(
attrs, resource_model.subresources
)
def _create_available_subresources_command(self, attrs, subresources):
_subresources = [subresource.name for subresource in subresources]
_subresources = sorted(_subresources)
def get_available_subresources(factory_self):
"""
Returns a list of all the available sub-resources for this
Resource.
:returns: A list containing the name of each sub-resource for this
resource
:rtype: list of str
"""
return _subresources
attrs['get_available_subresources'] = get_available_subresources
def _load_waiters(
self, attrs, resource_name, resource_model, service_context
):
"""
Load resource waiters from the model. Each waiter allows you to
wait until a resource reaches a specific state by polling the state
of the resource.
"""
for waiter in resource_model.waiters:
attrs[waiter.name] = self._create_waiter(
resource_waiter_model=waiter,
resource_name=resource_name,
service_context=service_context,
)
def _create_identifier(factory_self, identifier, resource_name):
"""
Creates a read-only property for identifier attributes.
"""
def get_identifier(self):
# The default value is set to ``None`` instead of
# raising an AttributeError because when resources are
# instantiated a check is made such that none of the
# identifiers have a value ``None``. If any are ``None``,
# a more informative user error than a generic AttributeError
# is raised.
return getattr(self, '_' + identifier.name, None)
get_identifier.__name__ = str(identifier.name)
get_identifier.__doc__ = docstring.IdentifierDocstring(
resource_name=resource_name,
identifier_model=identifier,
include_signature=False,
)
return property(get_identifier)
def _create_identifier_alias(
factory_self, resource_name, identifier, member_model, service_context
):
"""
Creates a read-only property that aliases an identifier.
"""
def get_identifier(self):
return getattr(self, '_' + identifier.name, None)
get_identifier.__name__ = str(identifier.member_name)
get_identifier.__doc__ = docstring.AttributeDocstring(
service_name=service_context.service_name,
resource_name=resource_name,
attr_name=identifier.member_name,
event_emitter=factory_self._emitter,
attr_model=member_model,
include_signature=False,
)
return property(get_identifier)
def _create_autoload_property(
factory_self,
resource_name,
name,
snake_cased,
member_model,
service_context,
):
"""
Creates a new property on the resource to lazy-load its value
via the resource's ``load`` method (if it exists).
"""
# The property loader will check to see if this resource has already
# been loaded and return the cached value if possible. If not, then
# it first checks to see if it CAN be loaded (raise if not), then
# calls the load before returning the value.
def property_loader(self):
if self.meta.data is None:
if hasattr(self, 'load'):
self.load()
else:
raise ResourceLoadException(
f'{self.__class__.__name__} has no load method'
)
return self.meta.data.get(name)
property_loader.__name__ = str(snake_cased)
property_loader.__doc__ = docstring.AttributeDocstring(
service_name=service_context.service_name,
resource_name=resource_name,
attr_name=snake_cased,
event_emitter=factory_self._emitter,
attr_model=member_model,
include_signature=False,
)
return property(property_loader)
def _create_waiter(
factory_self, resource_waiter_model, resource_name, service_context
):
"""
Creates a new wait method for each resource where both a waiter and
resource model is defined.
"""
waiter = WaiterAction(
resource_waiter_model,
waiter_resource_name=resource_waiter_model.name,
)
def do_waiter(self, *args, **kwargs):
waiter(self, *args, **kwargs)
do_waiter.__name__ = str(resource_waiter_model.name)
do_waiter.__doc__ = docstring.ResourceWaiterDocstring(
resource_name=resource_name,
event_emitter=factory_self._emitter,
service_model=service_context.service_model,
resource_waiter_model=resource_waiter_model,
service_waiter_model=service_context.service_waiter_model,
include_signature=False,
)
return do_waiter
def _create_collection(
factory_self, resource_name, collection_model, service_context
):
"""
Creates a new property on the resource to lazy-load a collection.
"""
cls = factory_self._collection_factory.load_from_definition(
resource_name=resource_name,
collection_model=collection_model,
service_context=service_context,
event_emitter=factory_self._emitter,
)
def get_collection(self):
return cls(
collection_model=collection_model,
parent=self,
factory=factory_self,
service_context=service_context,
)
get_collection.__name__ = str(collection_model.name)
get_collection.__doc__ = docstring.CollectionDocstring(
collection_model=collection_model, include_signature=False
)
return property(get_collection)
def _create_reference(
factory_self, reference_model, resource_name, service_context
):
"""
Creates a new property on the resource to lazy-load a reference.
"""
# References are essentially an action with no request
# or response, so we can re-use the response handlers to
# build up resources from identifiers and data members.
handler = ResourceHandler(
search_path=reference_model.resource.path,
factory=factory_self,
resource_model=reference_model.resource,
service_context=service_context,
)
# Are there any identifiers that need access to data members?
# This is important when building the resource below since
# it requires the data to be loaded.
needs_data = any(
i.source == 'data' for i in reference_model.resource.identifiers
)
def get_reference(self):
# We need to lazy-evaluate the reference to handle circular
# references between resources. We do this by loading the class
# when first accessed.
# This is using a *response handler* so we need to make sure
# our data is loaded (if possible) and pass that data into
# the handler as if it were a response. This allows references
# to have their data loaded properly.
if needs_data and self.meta.data is None and hasattr(self, 'load'):
self.load()
return handler(self, {}, self.meta.data)
get_reference.__name__ = str(reference_model.name)
get_reference.__doc__ = docstring.ReferenceDocstring(
reference_model=reference_model, include_signature=False
)
return property(get_reference)
def _create_class_partial(
factory_self, subresource_model, resource_name, service_context
):
"""
Creates a new method which acts as a functools.partial, passing
along the instance's low-level `client` to the new resource
class' constructor.
"""
name = subresource_model.resource.type
def create_resource(self, *args, **kwargs):
# We need a new method here because we want access to the
# instance's client.
positional_args = []
# We lazy-load the class to handle circular references.
json_def = service_context.resource_json_definitions.get(name, {})
resource_cls = factory_self.load_from_definition(
resource_name=name,
single_resource_json_definition=json_def,
service_context=service_context,
)
# Assumes that identifiers are in order, which lets you do
# e.g. ``sqs.Queue('foo').Message('bar')`` to create a new message
# linked with the ``foo`` queue and which has a ``bar`` receipt
# handle. If we did kwargs here then future positional arguments
# would lead to failure.
identifiers = subresource_model.resource.identifiers
if identifiers is not None:
for identifier, value in build_identifiers(identifiers, self):
positional_args.append(value)
return partial(
resource_cls, *positional_args, client=self.meta.client
)(*args, **kwargs)
create_resource.__name__ = str(name)
create_resource.__doc__ = docstring.SubResourceDocstring(
resource_name=resource_name,
sub_resource_model=subresource_model,
service_model=service_context.service_model,
include_signature=False,
)
return create_resource
def _create_action(
factory_self,
action_model,
resource_name,
service_context,
is_load=False,
):
"""
Creates a new method which makes a request to the underlying
AWS service.
"""
# Create the action in in this closure but before the ``do_action``
# method below is invoked, which allows instances of the resource
# to share the ServiceAction instance.
action = ServiceAction(
action_model, factory=factory_self, service_context=service_context
)
# A resource's ``load`` method is special because it sets
# values on the resource instead of returning the response.
if is_load:
# We need a new method here because we want access to the
# instance via ``self``.
def do_action(self, *args, **kwargs):
response = action(self, *args, **kwargs)
self.meta.data = response
# Create the docstring for the load/reload methods.
lazy_docstring = docstring.LoadReloadDocstring(
action_name=action_model.name,
resource_name=resource_name,
event_emitter=factory_self._emitter,
load_model=action_model,
service_model=service_context.service_model,
include_signature=False,
)
else:
# We need a new method here because we want access to the
# instance via ``self``.
def do_action(self, *args, **kwargs):
response = action(self, *args, **kwargs)
if hasattr(self, 'load'):
# Clear cached data. It will be reloaded the next
# time that an attribute is accessed.
# TODO: Make this configurable in the future?
self.meta.data = None
return response
lazy_docstring = docstring.ActionDocstring(
resource_name=resource_name,
event_emitter=factory_self._emitter,
action_model=action_model,
service_model=service_context.service_model,
include_signature=False,
)
do_action.__name__ = str(action_model.name)
do_action.__doc__ = lazy_docstring
return do_action
| ResourceFactory |
python | huggingface__transformers | tests/models/wav2vec2_conformer/test_modeling_wav2vec2_conformer.py | {
"start": 15226,
"end": 24858
} | class ____(ModelTesterMixin, PipelineTesterMixin, unittest.TestCase):
all_model_classes = (
(
Wav2Vec2ConformerForCTC,
Wav2Vec2ConformerModel,
Wav2Vec2ConformerForSequenceClassification,
Wav2Vec2ConformerForPreTraining,
Wav2Vec2ConformerForAudioFrameClassification,
Wav2Vec2ConformerForXVector,
)
if is_torch_available()
else ()
)
pipeline_model_mapping = (
{
"audio-classification": Wav2Vec2ConformerForSequenceClassification,
"automatic-speech-recognition": Wav2Vec2ConformerForCTC,
"feature-extraction": Wav2Vec2ConformerModel,
}
if is_torch_available()
else {}
)
def setUp(self):
self.model_tester = Wav2Vec2ConformerModelTester(self)
self.config_tester = ConfigTester(self, config_class=Wav2Vec2ConformerConfig, hidden_size=37)
def test_config(self):
self.config_tester.run_common_tests()
def test_model(self):
config_and_inputs = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_model(*config_and_inputs)
@is_flaky(
description="The `codevector_idx` computed with `argmax()` in `Wav2Vec2ConformerGumbelVectorQuantizer.forward` is not stable."
)
def test_batching_equivalence(self, atol=1e-4, rtol=1e-4):
super().test_batching_equivalence(atol=atol, rtol=rtol)
def test_model_with_relative(self):
config_and_inputs = self.model_tester.prepare_config_and_inputs(position_embeddings_type="relative")
self.model_tester.create_and_check_model(*config_and_inputs)
def test_model_with_rotary(self):
config_and_inputs = self.model_tester.prepare_config_and_inputs(position_embeddings_type="rotary")
self.model_tester.create_and_check_model(*config_and_inputs)
def test_model_with_no_rel_pos(self):
config_and_inputs = self.model_tester.prepare_config_and_inputs(position_embeddings_type=None)
self.model_tester.create_and_check_model(*config_and_inputs)
def test_model_with_adapter(self):
config_and_inputs = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_model_with_adapter(*config_and_inputs)
def test_model_with_adapter_for_ctc(self):
config_and_inputs = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_model_with_adapter_for_ctc(*config_and_inputs)
def test_model_with_adapter_proj_dim(self):
config_and_inputs = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_model_with_adapter_proj_dim(*config_and_inputs)
@require_torch_accelerator
@require_torch_fp16
def test_model_float16_with_relative(self):
config_and_inputs = self.model_tester.prepare_config_and_inputs(position_embeddings_type="relative")
self.model_tester.create_and_check_model_float16(*config_and_inputs)
@require_torch_accelerator
@require_torch_fp16
def test_model_float16_with_rotary(self):
config_and_inputs = self.model_tester.prepare_config_and_inputs(position_embeddings_type="rotary")
self.model_tester.create_and_check_model_float16(*config_and_inputs)
def test_ctc_loss_inference(self):
config_and_inputs = self.model_tester.prepare_config_and_inputs()
self.model_tester.check_ctc_loss(*config_and_inputs)
def test_seq_classifier_loss_inference(self):
config_and_inputs = self.model_tester.prepare_config_and_inputs()
self.model_tester.check_seq_classifier_loss(*config_and_inputs)
def test_ctc_train(self):
config_and_inputs = self.model_tester.prepare_config_and_inputs()
self.model_tester.check_ctc_training(*config_and_inputs)
def test_seq_classifier_train(self):
config_and_inputs = self.model_tester.prepare_config_and_inputs()
self.model_tester.check_seq_classifier_training(*config_and_inputs)
def test_xvector_train(self):
config_and_inputs = self.model_tester.prepare_config_and_inputs()
self.model_tester.check_xvector_training(*config_and_inputs)
def test_labels_out_of_vocab(self):
config_and_inputs = self.model_tester.prepare_config_and_inputs()
self.model_tester.check_labels_out_of_vocab(*config_and_inputs)
@unittest.skip(reason="Wav2Vec2Conformer has not inputs_embeds")
def test_inputs_embeds(self):
pass
@unittest.skip(reason="Wav2Vec2Conformer has input_values instead of input_ids")
def test_forward_signature(self):
pass
@unittest.skip(reason="Wav2Vec2Conformer has not token embeddings")
def test_resize_tokens_embeddings(self):
pass
@unittest.skip(reason="Wav2Vec2Conformer has not inputs_embeds")
def test_model_get_set_embeddings(self):
pass
def test_retain_grad_hidden_states_attentions(self):
config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()
config.output_hidden_states = True
config.output_attentions = True
# no need to test all models as different heads yield the same functionality
model_class = self.all_model_classes[0]
model = model_class(config)
model.to(torch_device)
# set layer drop to 0
model.config.layerdrop = 0.0
input_values = inputs_dict["input_values"]
input_lengths = torch.tensor(
[input_values.shape[1] for _ in range(input_values.shape[0])], dtype=torch.long, device=torch_device
)
output_lengths = model._get_feat_extract_output_lengths(input_lengths)
labels = ids_tensor((input_values.shape[0], output_lengths[0] - 2), self.model_tester.vocab_size)
inputs_dict["attention_mask"] = torch.ones_like(inputs_dict["attention_mask"])
inputs_dict["labels"] = labels
outputs = model(**inputs_dict)
output = outputs[0]
# Encoder-/Decoder-only models
hidden_states = outputs.hidden_states[0]
attentions = outputs.attentions[0]
hidden_states.retain_grad()
attentions.retain_grad()
output.flatten()[0].backward(retain_graph=True)
self.assertIsNotNone(hidden_states.grad)
self.assertIsNotNone(attentions.grad)
# overwrite from test_modeling_common
def _mock_init_weights(self, module):
if hasattr(module, "weight") and module.weight is not None:
module.weight.fill_(3)
if hasattr(module, "weight_g") and module.weight_g is not None:
module.weight_g.data.fill_(3)
if hasattr(module, "weight_v") and module.weight_v is not None:
module.weight_v.data.fill_(3)
if hasattr(module, "bias") and module.bias is not None:
module.bias.fill_(3)
if hasattr(module, "pos_bias_u") and module.pos_bias_u is not None:
module.pos_bias_u.data.fill_(3)
if hasattr(module, "pos_bias_v") and module.pos_bias_v is not None:
module.pos_bias_v.data.fill_(3)
if hasattr(module, "codevectors") and module.codevectors is not None:
module.codevectors.data.fill_(3)
if hasattr(module, "masked_spec_embed") and module.masked_spec_embed is not None:
module.masked_spec_embed.data.fill_(3)
def test_mask_feature_prob_ctc(self):
model = Wav2Vec2ConformerForCTC.from_pretrained(
"hf-internal-testing/tiny-random-wav2vec2-conformer", mask_feature_prob=0.2, mask_feature_length=2
)
model.to(torch_device).train()
processor = Wav2Vec2Processor.from_pretrained(
"hf-internal-testing/tiny-random-wav2vec2-conformer", return_attention_mask=True
)
batch_duration_in_seconds = [1, 3, 2, 6]
input_features = [np.random.random(16_000 * s) for s in batch_duration_in_seconds]
batch = processor(
input_features, padding=True, sampling_rate=processor.feature_extractor.sampling_rate, return_tensors="pt"
)
logits = model(
input_values=batch["input_values"].to(torch_device),
attention_mask=batch["attention_mask"].to(torch_device),
).logits
self.assertEqual(logits.shape, (4, 1498, 32))
def test_mask_time_prob_ctc(self):
model = Wav2Vec2ConformerForCTC.from_pretrained(
"hf-internal-testing/tiny-random-wav2vec2-conformer", mask_time_prob=0.2, mask_time_length=2
)
model.to(torch_device).train()
processor = Wav2Vec2Processor.from_pretrained(
"hf-internal-testing/tiny-random-wav2vec2-conformer", return_attention_mask=True
)
batch_duration_in_seconds = [1, 3, 2, 6]
input_features = [np.random.random(16_000 * s) for s in batch_duration_in_seconds]
batch = processor(
input_features, padding=True, sampling_rate=processor.feature_extractor.sampling_rate, return_tensors="pt"
)
logits = model(
input_values=batch["input_values"].to(torch_device),
attention_mask=batch["attention_mask"].to(torch_device),
).logits
self.assertEqual(logits.shape, (4, 1498, 32))
@unittest.skip(reason="Feed forward chunking is not implemented")
def test_feed_forward_chunking(self):
pass
@slow
def test_model_from_pretrained(self):
model = Wav2Vec2ConformerModel.from_pretrained("facebook/wav2vec2-conformer-rel-pos-large")
self.assertIsNotNone(model)
@require_torch
| Wav2Vec2ConformerModelTest |
python | doocs__leetcode | solution/3300-3399/3305.Count of Substrings Containing Every Vowel and K Consonants I/Solution.py | {
"start": 0,
"end": 698
} | class ____:
def countOfSubstrings(self, word: str, k: int) -> int:
def f(k: int) -> int:
cnt = Counter()
ans = l = x = 0
for c in word:
if c in "aeiou":
cnt[c] += 1
else:
x += 1
while x >= k and len(cnt) == 5:
d = word[l]
if d in "aeiou":
cnt[d] -= 1
if cnt[d] == 0:
cnt.pop(d)
else:
x -= 1
l += 1
ans += l
return ans
return f(k) - f(k + 1)
| Solution |
python | sympy__sympy | sympy/codegen/cfunctions.py | {
"start": 9676,
"end": 10829
} | class ____(Function): # 'cbrt' already defined in sympy.functions.elementary.miscellaneous
"""
Represents the cube root function.
Explanation
===========
The reason why one would use ``Cbrt(x)`` over ``cbrt(x)``
is that the latter is internally represented as ``Pow(x, Rational(1, 3))`` which
may not be what one wants when doing code-generation.
Examples
========
>>> from sympy.abc import x
>>> from sympy.codegen.cfunctions import Cbrt
>>> Cbrt(x)
Cbrt(x)
>>> Cbrt(x).diff(x)
1/(3*x**(2/3))
See Also
========
Sqrt
"""
nargs = 1
def fdiff(self, argindex=1):
"""
Returns the first derivative of this function.
"""
if argindex == 1:
return Pow(self.args[0], Rational(-_Two/3))/3
else:
raise ArgumentIndexError(self, argindex)
def _eval_expand_func(self, **hints):
return _Cbrt(*self.args)
def _eval_rewrite_as_Pow(self, arg, **kwargs):
return _Cbrt(arg)
_eval_rewrite_as_tractable = _eval_rewrite_as_Pow
def _hypot(x, y):
return sqrt(Pow(x, 2) + Pow(y, 2))
| Cbrt |
python | allegroai__clearml | clearml/backend_api/services/v2_23/datasets.py | {
"start": 162455,
"end": 164434
} | class ____(Request):
"""
Get the field names that can be used in lucene query for the given dataset versions
:param versions: The IDs of the versions. Either dataset or versions should be
specified
:type versions: Sequence[str]
:param dataset: The ID of the dataset. Either dataset or versions should be
specified
:type dataset: str
"""
_service = "datasets"
_action = "get_schema_keys"
_version = "2.23"
_schema = {
"definitions": {},
"properties": {
"dataset": {
"description": "The ID of the dataset. Either dataset or versions should be specified",
"type": "string",
},
"versions": {
"description": "The IDs of the versions. Either dataset or versions should be specified",
"items": {"type": "string"},
"type": "array",
},
},
"required": ["versions"],
"type": "object",
}
def __init__(self, versions, dataset=None, **kwargs):
super(GetSchemaKeysRequest, self).__init__(**kwargs)
self.versions = versions
self.dataset = dataset
@schema_property("versions")
def versions(self):
return self._property_versions
@versions.setter
def versions(self, value):
if value is None:
self._property_versions = None
return
self.assert_isinstance(value, "versions", (list, tuple))
self.assert_isinstance(value, "versions", six.string_types, is_array=True)
self._property_versions = value
@schema_property("dataset")
def dataset(self):
return self._property_dataset
@dataset.setter
def dataset(self, value):
if value is None:
self._property_dataset = None
return
self.assert_isinstance(value, "dataset", six.string_types)
self._property_dataset = value
| GetSchemaKeysRequest |
python | run-llama__llama_index | llama-index-integrations/tools/llama-index-tools-scrapegraph/examples/scrapegraph-agentic-scraper-llama-index.py | {
"start": 725,
"end": 896
} | class ____(BaseModel):
"""Schema for representing multiple products."""
products: List[ProductInfo] = Field(description="List of products found")
| ProductsListSchema |
python | astropy__astropy | astropy/io/votable/exceptions.py | {
"start": 48314,
"end": 48570
} | class ____(VOWarning, ValueError):
"""
The table had *x* fields defined, but the data itself has only *y*
columns.
"""
message_template = "Data has fewer columns ({}) than are defined in the header ({})"
default_args = ("x", "y")
| E21 |
python | facebook__pyre-check | client/commands/pyre_server_options.py | {
"start": 1013,
"end": 4596
} | class ____:
server_start_command: frontend_configuration.ServerStartCommand
project_identifier: str
start_arguments: start.Arguments
language_server_features: features.LanguageServerFeatures
strict_default: bool
excludes: Sequence[str]
flavor: identifiers.PyreFlavor
def get_socket_path(self) -> Path:
return daemon_socket.get_socket_path(
self.project_identifier,
flavor=self.flavor,
)
@staticmethod
def create_from_start_arguments(
start_arguments: start.Arguments,
configuration: frontend_configuration.Base,
language_server_features: features.LanguageServerFeatures,
flavor: identifiers.PyreFlavor,
unsaved_changes_only: bool = False,
) -> PyreServerOptions:
server_start_command = configuration.get_server_start_command(
download_if_needed=True
)
if server_start_command is None:
raise configuration_module.InvalidConfiguration(
"Cannot locate a Pyre binary to run."
)
if start_arguments.watchman_root is None and not unsaved_changes_only:
raise commands.ClientException(
"Cannot locate a `watchman` root. Pyre's server will not function "
"properly."
)
return PyreServerOptions(
server_start_command=server_start_command,
project_identifier=configuration.get_project_identifier(),
start_arguments=start_arguments,
language_server_features=language_server_features,
strict_default=configuration.is_strict(),
excludes=configuration.get_excludes(),
flavor=flavor,
)
@staticmethod
def create(
start_command_argument: command_arguments.StartArguments,
configuration: frontend_configuration.Base,
language_server_features: features.LanguageServerFeatures,
unsaved_changes_only: bool = False,
) -> PyreServerOptions:
start_arguments = start.create_server_arguments(
configuration,
start_command_argument,
False, # kill_buck_after_build
)
return PyreServerOptions.create_from_start_arguments(
start_arguments,
configuration,
language_server_features,
start_command_argument.flavor,
unsaved_changes_only,
)
@staticmethod
def create_reader(
start_command_argument: command_arguments.StartArguments,
read_frontend_configuration: FrontendConfigurationReader,
language_server_features: features.LanguageServerFeatures,
) -> PyreServerOptionsReader:
def read() -> PyreServerOptions:
return PyreServerOptions.create(
start_command_argument=start_command_argument,
configuration=read_frontend_configuration(),
language_server_features=language_server_features,
)
return read
def read_server_options(
server_options_reader: PyreServerOptionsReader,
remote_logging: Optional[backend_arguments.RemoteLogging],
) -> "PyreServerOptions":
try:
LOG.info("Reading Pyre server configurations...")
return server_options_reader()
except Exception:
log_lsp_event.log(
remote_logging=remote_logging,
event=log_lsp_event.LSPEvent.NOT_CONFIGURED,
normals={
"exception": traceback.format_exc(),
},
)
raise
| PyreServerOptions |
python | tensorflow__tensorflow | tensorflow/python/debug/lib/debug_events_reader.py | {
"start": 25206,
"end": 26496
} | class ____(BaseDigest):
"""Light-weight summary of a intra-graph tensor execution event.
Use `DebugDataReader.read_graph_execution_trace()` on this object to read more
detailed data (`GraphExecutionTrace`).
Properties (beyond the base class):
op_type: Type name of the executed op (e.g., "Conv2D").
op_name: Name of the op (e.g., "conv_2d_3/Conv2D").
output_slot: Output slot index of the tensor.
graph_id: The debugger-generated ID of the innermost (immediately-enclosing)
graph.
"""
def __init__(self, wall_time, locator, op_type, op_name, output_slot,
graph_id):
super().__init__(wall_time, locator)
self._op_type = op_type
self._op_name = op_name
self._output_slot = output_slot
self._graph_id = graph_id
@property
def op_type(self):
return self._op_type
@property
def op_name(self):
return self._op_name
@property
def output_slot(self):
return self._output_slot
@property
def graph_id(self):
return self._graph_id
def to_json(self):
output = super().to_json()
output.update({
"op_type": self.op_type,
"op_name": self.op_name,
"output_slot": self.output_slot,
"graph_id": self.graph_id,
})
return output
| GraphExecutionTraceDigest |
python | instagram__MonkeyType | tests/test_typing.py | {
"start": 24945,
"end": 25168
} | class ____(TypeRewriter):
"""Dummy rewriter for testing."""
def rewrite_List(self, lst):
return int
def rewrite_type_variable(self, type_variable):
return Dict[str, type_variable]
| RewriteListToInt |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/dialects/postgresql/pg8000.py | {
"start": 8388,
"end": 8706
} | class ____(PGExecutionContext):
def create_server_side_cursor(self):
ident = "c_%s_%s" % (hex(id(self))[2:], hex(_server_side_id())[2:])
return ServerSideCursor(self._dbapi_connection.cursor(), ident)
def pre_exec(self):
if not self.compiled:
return
| PGExecutionContext_pg8000 |
python | MongoEngine__mongoengine | mongoengine/fields.py | {
"start": 36407,
"end": 38500
} | class ____(ComplexBaseField):
"""A dictionary field that wraps a standard Python dictionary. This is
similar to an embedded document, but the structure is not defined.
.. note::
Required means it cannot be empty - as the default for DictFields is {}
"""
def __init__(self, field=None, *args, **kwargs):
kwargs.setdefault("default", dict)
super().__init__(*args, field=field, **kwargs)
self.set_auto_dereferencing(False)
def validate(self, value):
"""Make sure that a list of valid fields is being used."""
if not isinstance(value, dict):
self.error("Only dictionaries may be used in a DictField")
if key_not_string(value):
msg = "Invalid dictionary key - documents must have only string keys"
self.error(msg)
# Following condition applies to MongoDB >= 3.6
# older Mongo has stricter constraints but
# it will be rejected upon insertion anyway
# Having a validation that depends on the MongoDB version
# is not straightforward as the field isn't aware of the connected Mongo
if key_starts_with_dollar(value):
self.error(
'Invalid dictionary key name - keys may not startswith "$" characters'
)
super().validate(value)
def lookup_member(self, member_name):
return DictField(db_field=member_name)
def prepare_query_value(self, op, value):
match_operators = [*STRING_OPERATORS]
if op in match_operators and isinstance(value, str):
return StringField().prepare_query_value(op, value)
if hasattr(
self.field, "field"
): # Used for instance when using DictField(ListField(IntField()))
if op in ("set", "unset") and isinstance(value, dict):
return {
k: self.field.prepare_query_value(op, v) for k, v in value.items()
}
return self.field.prepare_query_value(op, value)
return super().prepare_query_value(op, value)
| DictField |
python | pydantic__pydantic | tests/mypy/outputs/mypy-default_ini/plugin_success.py | {
"start": 2408,
"end": 2949
} | class ____(BaseModel):
x: str = Field(alias='x_alias')
y: str = Field(validation_alias='y_alias')
z: str = Field(validation_alias='z_alias', alias='unused')
alias_model = AliasModel(x_alias='a', y_alias='a', z_alias='a')
# MYPY: error: Unexpected keyword argument "y_alias" for "AliasModel"; did you mean "x_alias"? [call-arg]
# MYPY: error: Unexpected keyword argument "z_alias" for "AliasModel"; did you mean "x_alias"? [call-arg]
assert alias_model.x == 'a'
assert alias_model.y == 'a'
assert alias_model.z == 'a'
| AliasModel |
python | google__jax | jax/_src/errors.py | {
"start": 18225,
"end": 23837
} | class ____(JAXTypeError):
"""
This error occurs when you use a JAX value that has leaked out of a function.
What does it mean to leak a value? If you use a JAX transformation on a
function ``f`` that stores, in some scope outside of ``f``, a reference to
an intermediate value, that value is considered to have been leaked.
Leaking values is a side effect. (Read more about avoiding side effects in
`Pure Functions <https://docs.jax.dev/en/latest/notebooks/Common_Gotchas_in_JAX.html#pure-functions>`_)
JAX detects leaks when you then use the leaked value in another
operation later on, at which point it raises an ``UnexpectedTracerError``.
To fix this, avoid side effects: if a function computes a value needed
in an outer scope, return that value from the transformed function explicitly.
Specifically, a ``Tracer`` is JAX's internal representation of a function's
intermediate values during transformations, e.g. within :func:`~jax.jit`,
:func:`~jax.pmap`, :func:`~jax.vmap`, etc. Encountering a ``Tracer`` outside
of a transformation implies a leak.
Life-cycle of a leaked value
Consider the following example of a transformed function which leaks a value
to an outer scope::
>>> from jax import jit
>>> import jax.numpy as jnp
>>> outs = []
>>> @jit # 1
... def side_effecting(x):
... y = x + 1 # 3
... outs.append(y) # 4
>>> x = 1
>>> side_effecting(x) # 2
>>> outs[0] + 1 # 5 # doctest: +IGNORE_EXCEPTION_DETAIL
Traceback (most recent call last):
...
UnexpectedTracerError: Encountered an unexpected tracer.
In this example we leak a Traced value from an inner transformed scope to an
outer scope. We get an ``UnexpectedTracerError`` when the leaked value is
used, not when the value is leaked.
This example also demonstrates the life-cycle of a leaked value:
1. A function is transformed (in this case, by :func:`~jax.jit`)
2. The transformed function is called (initiating an abstract trace of the
function and turning ``x`` into a ``Tracer``)
3. The intermediate value ``y``, which will later be leaked, is created
(an intermediate value of a traced function is also a ``Tracer``)
4. The value is leaked (appended to a list in an outer scope, escaping
the function through a side-channel)
5. The leaked value is used, and an UnexpectedTracerError is raised.
The UnexpectedTracerError message tries to point to these locations in your
code by including information about each stage. Respectively:
1. The name of the transformed function (``side_effecting``) and which
transform kicked off the trace :func:`~jax.jit`).
2. A reconstructed stack trace of where the leaked Tracer was created,
which includes where the transformed function was called.
(``When the Tracer was created, the final 5 stack frames were...``).
3. From the reconstructed stack trace, the line of code that created
the leaked Tracer.
4. The leak location is not included in the error message because it is
difficult to pin down! JAX can only tell you what the leaked value
looks like (what shape it has and where it was created) and what
boundary it was leaked over (the name of the transformation and the
name of the transformed function).
5. The current error's stack trace points to where the value is used.
The error can be fixed by the returning the value out of the
transformed function::
>>> from jax import jit
>>> import jax.numpy as jnp
>>> outs = []
>>> @jit
... def not_side_effecting(x):
... y = x+1
... return y
>>> x = 1
>>> y = not_side_effecting(x)
>>> outs.append(y)
>>> outs[0] + 1 # all good! no longer a leaked value.
Array(3, dtype=int32, weak_type=True)
Leak checker
As discussed in point 2 and 3 above, JAX shows a reconstructed stack trace
which points to where the leaked value was created. This is because
JAX only raises an error when the leaked value is used, not when the
value is leaked. This is not the most useful place to raise this error,
because you need to know the location where the Tracer was leaked to fix the
error.
To make this location easier to track down, you can use the leak checker.
When the leak checker is enabled, an error is raised as soon as a ``Tracer``
is leaked. (To be more exact, it will raise an error when the transformed
function from which the ``Tracer`` is leaked returns)
To enable the leak checker you can use the ``JAX_CHECK_TRACER_LEAKS``
environment variable or the ``with jax.checking_leaks()`` context manager.
.. note::
Note that this tool is experimental and may report false positives. It
works by disabling some JAX caches, so it will have a negative effect on
performance and should only be used when debugging.
Example usage::
>>> from jax import jit
>>> import jax.numpy as jnp
>>> outs = []
>>> @jit
... def side_effecting(x):
... y = x+1
... outs.append(y)
>>> x = 1
>>> with jax.checking_leaks():
... y = side_effecting(x) # doctest: +IGNORE_EXCEPTION_DETAIL
Traceback (most recent call last):
...
Exception: Leaked Trace
"""
def __init__(self, msg: str):
super().__init__(msg)
@export
| UnexpectedTracerError |
python | scikit-learn__scikit-learn | sklearn/random_projection.py | {
"start": 20841,
"end": 28400
} | class ____(BaseRandomProjection):
"""Reduce dimensionality through sparse random projection.
Sparse random matrix is an alternative to dense random
projection matrix that guarantees similar embedding quality while being
much more memory efficient and allowing faster computation of the
projected data.
If we note `s = 1 / density` the components of the random matrix are
drawn from:
.. code-block:: text
-sqrt(s) / sqrt(n_components) with probability 1 / 2s
0 with probability 1 - 1 / s
+sqrt(s) / sqrt(n_components) with probability 1 / 2s
Read more in the :ref:`User Guide <sparse_random_matrix>`.
.. versionadded:: 0.13
Parameters
----------
n_components : int or 'auto', default='auto'
Dimensionality of the target projection space.
n_components can be automatically adjusted according to the
number of samples in the dataset and the bound given by the
Johnson-Lindenstrauss lemma. In that case the quality of the
embedding is controlled by the ``eps`` parameter.
It should be noted that Johnson-Lindenstrauss lemma can yield
very conservative estimated of the required number of components
as it makes no assumption on the structure of the dataset.
density : float or 'auto', default='auto'
Ratio in the range (0, 1] of non-zero component in the random
projection matrix.
If density = 'auto', the value is set to the minimum density
as recommended by Ping Li et al.: 1 / sqrt(n_features).
Use density = 1 / 3.0 if you want to reproduce the results from
Achlioptas, 2001.
eps : float, default=0.1
Parameter to control the quality of the embedding according to
the Johnson-Lindenstrauss lemma when n_components is set to
'auto'. This value should be strictly positive.
Smaller values lead to better embedding and higher number of
dimensions (n_components) in the target projection space.
dense_output : bool, default=False
If True, ensure that the output of the random projection is a
dense numpy array even if the input and random projection matrix
are both sparse. In practice, if the number of components is
small the number of zero components in the projected data will
be very small and it will be more CPU and memory efficient to
use a dense representation.
If False, the projected data uses a sparse representation if
the input is sparse.
compute_inverse_components : bool, default=False
Learn the inverse transform by computing the pseudo-inverse of the
components during fit. Note that the pseudo-inverse is always a dense
array, even if the training data was sparse. This means that it might be
necessary to call `inverse_transform` on a small batch of samples at a
time to avoid exhausting the available memory on the host. Moreover,
computing the pseudo-inverse does not scale well to large matrices.
random_state : int, RandomState instance or None, default=None
Controls the pseudo random number generator used to generate the
projection matrix at fit time.
Pass an int for reproducible output across multiple function calls.
See :term:`Glossary <random_state>`.
Attributes
----------
n_components_ : int
Concrete number of components computed when n_components="auto".
components_ : sparse matrix of shape (n_components, n_features)
Random matrix used for the projection. Sparse matrix will be of CSR
format.
inverse_components_ : ndarray of shape (n_features, n_components)
Pseudo-inverse of the components, only computed if
`compute_inverse_components` is True.
.. versionadded:: 1.1
density_ : float in range 0.0 - 1.0
Concrete density computed from when density = "auto".
n_features_in_ : int
Number of features seen during :term:`fit`.
.. versionadded:: 0.24
feature_names_in_ : ndarray of shape (`n_features_in_`,)
Names of features seen during :term:`fit`. Defined only when `X`
has feature names that are all strings.
.. versionadded:: 1.0
See Also
--------
GaussianRandomProjection : Reduce dimensionality through Gaussian
random projection.
References
----------
.. [1] Ping Li, T. Hastie and K. W. Church, 2006,
"Very Sparse Random Projections".
https://web.stanford.edu/~hastie/Papers/Ping/KDD06_rp.pdf
.. [2] D. Achlioptas, 2001, "Database-friendly random projections",
https://cgi.di.uoa.gr/~optas/papers/jl.pdf
Examples
--------
>>> import numpy as np
>>> from sklearn.random_projection import SparseRandomProjection
>>> rng = np.random.RandomState(42)
>>> X = rng.rand(25, 3000)
>>> transformer = SparseRandomProjection(random_state=rng)
>>> X_new = transformer.fit_transform(X)
>>> X_new.shape
(25, 2759)
>>> # very few components are non-zero
>>> np.mean(transformer.components_ != 0)
np.float64(0.0182)
"""
_parameter_constraints: dict = {
**BaseRandomProjection._parameter_constraints,
"density": [Interval(Real, 0.0, 1.0, closed="right"), StrOptions({"auto"})],
"dense_output": ["boolean"],
}
def __init__(
self,
n_components="auto",
*,
density="auto",
eps=0.1,
dense_output=False,
compute_inverse_components=False,
random_state=None,
):
super().__init__(
n_components=n_components,
eps=eps,
compute_inverse_components=compute_inverse_components,
random_state=random_state,
)
self.dense_output = dense_output
self.density = density
def _make_random_matrix(self, n_components, n_features):
"""Generate the random projection matrix
Parameters
----------
n_components : int
Dimensionality of the target projection space.
n_features : int
Dimensionality of the original source space.
Returns
-------
components : sparse matrix of shape (n_components, n_features)
The generated random matrix in CSR format.
"""
random_state = check_random_state(self.random_state)
self.density_ = _check_density(self.density, n_features)
return _sparse_random_matrix(
n_components, n_features, density=self.density_, random_state=random_state
)
def transform(self, X):
"""Project the data by using matrix product with the random matrix.
Parameters
----------
X : {ndarray, sparse matrix} of shape (n_samples, n_features)
The input data to project into a smaller dimensional space.
Returns
-------
X_new : {ndarray, sparse matrix} of shape (n_samples, n_components)
Projected array. It is a sparse matrix only when the input is sparse and
`dense_output = False`.
"""
check_is_fitted(self)
X = validate_data(
self,
X,
accept_sparse=["csr", "csc"],
reset=False,
dtype=[np.float64, np.float32],
)
return safe_sparse_dot(X, self.components_.T, dense_output=self.dense_output)
| SparseRandomProjection |
python | has2k1__plotnine | plotnine/scales/scale_identity.py | {
"start": 1081,
"end": 1266
} | class ____(scale_color_identity):
"""
No color scaling
"""
_aesthetics = ["fill"]
_: KW_ONLY
guide: Literal["legend"] | None = None
@dataclass
| scale_fill_identity |
python | apache__airflow | providers/fab/src/airflow/providers/fab/auth_manager/views/user_edit.py | {
"start": 1408,
"end": 1788
} | class ____(ResetMyPasswordView):
"""Customize permission names for FAB's builtin ResetMyPasswordView."""
class_permission_name = permissions.RESOURCE_MY_PASSWORD
method_permission_name = {
"this_form_get": "read",
"this_form_post": "edit",
}
base_permissions = [permissions.ACTION_CAN_EDIT, permissions.ACTION_CAN_READ]
| CustomResetMyPasswordView |
python | PyCQA__pylint | tests/functional/s/super/super_init_not_called.py | {
"start": 1224,
"end": 1410
} | class ____(ParentWithoutInit):
def __init__(self): # [super-init-not-called]
...
# Regression test as reported in
# https://github.com/pylint-dev/pylint/issues/6027
| ChildThree |
python | kamyu104__LeetCode-Solutions | Python/subarrays-distinct-element-sum-of-squares-i.py | {
"start": 133,
"end": 2015
} | class ____(object):
def sumCounts(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
MOD = 10**9+7
class BIT(object): # 0-indexed.
def __init__(self, n):
self.__bit = [0]*(n+1) # Extra one for dummy node.
def add(self, i, val):
i += 1 # Extra one for dummy node.
while i < len(self.__bit):
self.__bit[i] = (self.__bit[i]+val) % MOD
i += (i & -i)
def query(self, i):
i += 1 # Extra one for dummy node.
ret = 0
while i > 0:
ret = (ret+self.__bit[i]) % MOD
i -= (i & -i)
return ret
def update(accu, d):
i = sl.bisect_left(idxs[x][-1])
accu = (accu + d*(len(nums)*(2*len(sl)-1) - (2*i+1)*idxs[x][-1] - 2*(bit.query(len(nums)-1)-bit.query(idxs[x][-1])))) % MOD
bit.add(idxs[x][-1], d*idxs[x][-1])
return accu
idxs = collections.defaultdict(list)
for i in reversed(xrange(len(nums))):
idxs[nums[i]].append(i)
result = 0
sl = SortedList(idxs[x][-1] for x in idxs)
accu = (len(nums)*len(sl)**2) % MOD
for i, x in enumerate(sl):
accu = (accu-(2*i+1)*x) % MOD
bit = BIT(len(nums))
for x in sl:
bit.add(x, x)
for x in nums:
result = (result+accu) % MOD # accu = sum(count(i, k) for k in range(i, len(nums)))
accu = update(accu, -1)
del sl[0]
idxs[x].pop()
if not idxs[x]:
continue
sl.add(idxs[x][-1])
accu = update(accu, +1)
assert(accu == 0)
return result
# Time: O(nlogn)
# Space: O(n)
# dp, segment tree, math
| Solution |
python | encode__django-rest-framework | tests/test_versioning.py | {
"start": 1673,
"end": 2118
} | class ____(RequestVersionView):
def determine_version(self, request, *args, **kwargs):
scheme = self.versioning_class()
scheme.allowed_versions = ('v1', 'v2', None)
scheme.default_version = 'v2'
return (scheme.determine_version(request, *args, **kwargs), scheme)
factory = APIRequestFactory()
def dummy_view(request):
pass
def dummy_pk_view(request, pk):
pass
| AllowedWithNoneAndDefaultVersionsView |
python | keras-team__keras | keras/src/ops/numpy.py | {
"start": 100403,
"end": 101153
} | class ____(Operation):
def call(self, x1, x2):
return backend.numpy.equal(x1, x2)
def compute_output_spec(self, x1, x2):
x1_shape = getattr(x1, "shape", [])
x2_shape = getattr(x2, "shape", [])
output_shape = broadcast_shapes(x1_shape, x2_shape)
return KerasTensor(output_shape, dtype="bool")
@keras_export(["keras.ops.equal", "keras.ops.numpy.equal"])
def equal(x1, x2):
"""Returns `(x1 == x2)` element-wise.
Args:
x1: Tensor to compare.
x2: Tensor to compare.
Returns:
Output tensor, element-wise comparison of `x1` and `x2`.
"""
if any_symbolic_tensors((x1, x2)):
return Equal().symbolic_call(x1, x2)
return backend.numpy.equal(x1, x2)
| Equal |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/dataclassHash1.py | {
"start": 332,
"end": 437
} | class ____:
a: int
# This should generate an error.
v3: Hashable = DC3(0)
@dataclass(frozen=True)
| DC3 |
python | SmileyChris__easy-thumbnails | easy_thumbnails/files.py | {
"start": 4696,
"end": 4956
} | class ____:
name = 'fake'
def __init__(self, storage=None):
if storage is None:
storage = default_storage
self.storage = storage
def generate_filename(self, instance, name, *args, **kwargs):
return name
| FakeField |
python | joke2k__faker | tests/providers/test_ssn.py | {
"start": 40178,
"end": 41214
} | class ____(unittest.TestCase):
num_sample_runs = 10
def setUp(self):
Faker.seed(0)
self.fake = Faker("tr_TR")
self.samples = [self.fake.ssn() for _ in range(self.num_sample_runs)]
def test_first_part_non_zero(self):
for sample in self.samples:
self.assertNotEqual(sample[0], "0")
def test_eleventh_digit_matches_sum_mod_10(self):
for sample in self.samples:
first_ten_number = sample[:-1]
last_part = int(sample[-1])
total_sum = sum(int(x) for x in first_ten_number)
self.assertEqual(total_sum % 10, last_part)
def test_tenth_digit_correct(self):
for sample in self.samples:
digits = [int(d) for d in sample]
odd_sum = sum(digits[i] for i in [0, 2, 4, 6, 8])
even_sum = sum(digits[i] for i in [1, 3, 5, 7])
tenth_digit = digits[9]
expected_tenth = ((odd_sum * 7) - even_sum) % 10
self.assertEqual(tenth_digit, expected_tenth)
| TestTrTr |
python | plotly__plotly.py | plotly/graph_objs/layout/yaxis/_title.py | {
"start": 235,
"end": 4975
} | class ____(_BaseLayoutHierarchyType):
_parent_path_str = "layout.yaxis"
_path_str = "layout.yaxis.title"
_valid_props = {"font", "standoff", "text"}
@property
def font(self):
"""
Sets this axis' title font.
The 'font' property is an instance of Font
that may be specified as:
- An instance of :class:`plotly.graph_objs.layout.yaxis.title.Font`
- A dict of string/value properties that will be passed
to the Font constructor
Returns
-------
plotly.graph_objs.layout.yaxis.title.Font
"""
return self["font"]
@font.setter
def font(self, val):
self["font"] = val
@property
def standoff(self):
"""
Sets the standoff distance (in px) between the axis labels and
the title text The default value is a function of the axis tick
labels, the title `font.size` and the axis `linewidth`. Note
that the axis title position is always constrained within the
margins, so the actual standoff distance is always less than
the set or default value. By setting `standoff` and turning on
`automargin`, plotly.js will push the margins to fit the axis
title at given standoff distance.
The 'standoff' property is a number and may be specified as:
- An int or float in the interval [0, inf]
Returns
-------
int|float
"""
return self["standoff"]
@standoff.setter
def standoff(self, val):
self["standoff"] = val
@property
def text(self):
"""
Sets the title of this axis.
The 'text' property is a string and must be specified as:
- A string
- A number that will be converted to a string
Returns
-------
str
"""
return self["text"]
@text.setter
def text(self, val):
self["text"] = val
@property
def _prop_descriptions(self):
return """\
font
Sets this axis' title font.
standoff
Sets the standoff distance (in px) between the axis
labels and the title text The default value is a
function of the axis tick labels, the title `font.size`
and the axis `linewidth`. Note that the axis title
position is always constrained within the margins, so
the actual standoff distance is always less than the
set or default value. By setting `standoff` and turning
on `automargin`, plotly.js will push the margins to fit
the axis title at given standoff distance.
text
Sets the title of this axis.
"""
def __init__(self, arg=None, font=None, standoff=None, text=None, **kwargs):
"""
Construct a new Title object
Parameters
----------
arg
dict of properties compatible with this constructor or
an instance of
:class:`plotly.graph_objs.layout.yaxis.Title`
font
Sets this axis' title font.
standoff
Sets the standoff distance (in px) between the axis
labels and the title text The default value is a
function of the axis tick labels, the title `font.size`
and the axis `linewidth`. Note that the axis title
position is always constrained within the margins, so
the actual standoff distance is always less than the
set or default value. By setting `standoff` and turning
on `automargin`, plotly.js will push the margins to fit
the axis title at given standoff distance.
text
Sets the title of this axis.
Returns
-------
Title
"""
super().__init__("title")
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.layout.yaxis.Title
constructor must be a dict or
an instance of :class:`plotly.graph_objs.layout.yaxis.Title`""")
self._skip_invalid = kwargs.pop("skip_invalid", False)
self._validate = kwargs.pop("_validate", True)
self._set_property("font", arg, font)
self._set_property("standoff", arg, standoff)
self._set_property("text", arg, text)
self._process_kwargs(**dict(arg, **kwargs))
self._skip_invalid = False
| Title |
python | huggingface__transformers | src/transformers/models/arcee/modular_arcee.py | {
"start": 1110,
"end": 8221
} | class ____(LlamaConfig):
r"""
This is the configuration class to store the configuration of a [`ArceeModel`]. It is used to instantiate an Arcee
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 AFM-4.5B-Base.
Pre-trained weights are available at
[arcee-ai/AFM-4.5B](https://huggingface.co/arcee-ai/AFM-4.5B)
and were used to build the examples below.
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 Arcee model. Defines the number of different tokens that can be represented by the
`inputs_ids` passed when calling [`ArceeModel`]
hidden_size (`int`, *optional*, defaults to 2560):
Dimension of the hidden representations.
intermediate_size (`int`, *optional*, defaults to 18432):
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 checkout [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 `"relu2"`):
The non-linear activation function (function or string) in the decoder.
max_position_embeddings (`int`, *optional*, defaults to 4096):
The maximum sequence length that this model might ever be used with. AFM-4.5B-Base supports up to 16384 tokens.
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-05):
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 128000):
Beginning of stream token id.
eos_token_id (`int`, *optional*, defaults to 128001):
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.
head_dim (`int`, *optional*):
The attention head dimension. If None, it will default to hidden_size // num_attention_heads
```python
>>> from transformers import ArceeModel, ArceeConfig
>>> # Initializing an Arcee AFM-4.5B-Base style configuration
>>> configuration = ArceeConfig()
>>> # Initializing a model from the AFM-4.5B-Base style configuration
>>> model = ArceeModel(configuration)
>>> # Accessing the model configuration
>>> configuration = model.config
```"""
model_type = "arcee"
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.up_proj": "colwise",
"layers.*.mlp.down_proj": "rowwise",
}
def __init__(
self,
vocab_size: Optional[int] = 32000,
hidden_size: Optional[int] = 2560,
intermediate_size: Optional[int] = 18432,
num_hidden_layers: Optional[int] = 32,
num_attention_heads: Optional[int] = 32,
num_key_value_heads: Optional[int] = None,
hidden_act: Optional[str] = "relu2",
max_position_embeddings: Optional[int] = 4096,
initializer_range: Optional[float] = 0.02,
rms_norm_eps: Optional[int] = 1e-5,
use_cache: Optional[bool] = True,
pad_token_id: Optional[int] = None,
bos_token_id: Optional[int] = 128000,
eos_token_id: Optional[int] = 128001,
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,
head_dim: Optional[int] = None,
**kwargs,
):
super().__init__(
vocab_size=vocab_size,
hidden_size=hidden_size,
intermediate_size=intermediate_size,
num_hidden_layers=num_hidden_layers,
num_attention_heads=num_attention_heads,
num_key_value_heads=num_key_value_heads,
hidden_act=hidden_act,
max_position_embeddings=max_position_embeddings,
initializer_range=initializer_range,
rms_norm_eps=rms_norm_eps,
use_cache=use_cache,
pad_token_id=pad_token_id,
bos_token_id=bos_token_id,
eos_token_id=eos_token_id,
tie_word_embeddings=tie_word_embeddings,
rope_parameters=rope_parameters,
attention_bias=attention_bias,
attention_dropout=attention_dropout,
mlp_bias=mlp_bias,
head_dim=head_dim,
**kwargs,
)
del self.pretraining_tp
| ArceeConfig |
python | fluentpython__example-code-2e | 24-class-metaprog/metabunch/pre3.6/bunch.py | {
"start": 1348,
"end": 1391
} | class ____(metaclass=MetaBunch):
pass
| Bunch |
python | squidfunk__mkdocs-material | material/plugins/tags/structure/mapping/storage/__init__.py | {
"start": 1683,
"end": 6407
} | class ____:
"""
A mapping storage.
The mapping storage allows to save and load mappings to and from a JSON
file, which allows for sharing tags across multiple MkDocs projects.
"""
def __init__(self, config: TagsConfig):
"""
Initialize the mapping storage.
Arguments:
config: The configuration.
"""
self.config = config
# -------------------------------------------------------------------------
config: TagsConfig
"""
The configuration.
"""
# -------------------------------------------------------------------------
def save(self, path: str, mappings: Iterable[Mapping]) -> None:
"""
Save mappings to file.
Arguments:
path: The file path.
mappings: The mappings.
"""
path = os.path.abspath(path)
os.makedirs(os.path.dirname(path), exist_ok = True)
# Save serialized mappings to file
with open(path, "w", encoding = "utf-8") as f:
data = [_mapping_to_json(mapping) for mapping in mappings]
json.dump(dict(mappings = data), f)
def load(self, path: str) -> Iterable[Mapping]:
"""
Load mappings from file.
Arguments:
path: The file path.
Yields:
The current mapping.
"""
with open(path, "r", encoding = "utf-8") as f:
data = json.load(f)
# Ensure root dictionary
if not isinstance(data, dict):
raise ValidationError(
f"Expected dictionary, but received: {data}"
)
# Ensure mappings are iterable
mappings = data.get("mappings")
if not isinstance(mappings, list):
raise ValidationError(
f"Expected list, but received: {mappings}"
)
# Create and yield mappings
for mapping in mappings:
yield _mapping_from_json(mapping)
# -----------------------------------------------------------------------------
# Functions
# -----------------------------------------------------------------------------
def _mapping_to_json(mapping: Mapping) -> dict:
"""
Return a serializable representation of a mapping.
Arguments:
mapping: The mapping.
Returns:
Serializable representation.
"""
return dict(
item = _mapping_item_to_json(mapping.item),
tags = [str(tag) for tag in sorted(mapping.tags)]
)
def _mapping_item_to_json(item: Page | Link) -> dict:
"""
Return a serializable representation of a page or link.
Arguments:
item: The page or link.
Returns:
Serializable representation.
"""
return dict(url = item.url, title = item.title)
# -------------------------------------------------------------------------
def _mapping_from_json(data: object) -> Mapping:
"""
Return a mapping from a serialized representation.
Arguments:
data: Serialized representation.
Returns:
The mapping.
"""
if not isinstance(data, dict):
raise ValidationError(
f"Expected dictionary, but received: {data}"
)
# Ensure tags are iterable
tags = data.get("tags")
if not isinstance(tags, list):
raise ValidationError(
f"Expected list, but received: {tags}"
)
# Ensure tags are valid
for tag in tags:
if not isinstance(tag, str):
raise ValidationError(
f"Expected string, but received: {tag}"
)
# Create and return mapping
return Mapping(
_mapping_item_from_json(data.get("item")),
tags = [Tag(tag) for tag in tags]
)
def _mapping_item_from_json(data: object) -> Link:
"""
Return a link from a serialized representation.
When loading a mapping, we must always return a link, as the sources of
pages might not be available because we're building another project.
Arguments:
data: Serialized representation.
Returns:
The link.
"""
if not isinstance(data, dict):
raise ValidationError(
f"Expected dictionary, but received: {data}"
)
# Ensure item has URL
url = data.get("url")
if not isinstance(url, str):
raise ValidationError(
f"Expected string, but received: {url}"
)
# Ensure item has title
title = data.get("title")
if not isinstance(title, str):
raise ValidationError(
f"Expected string, but received: {title}"
)
# Create and return item
return Link(title, url)
| MappingStorage |
python | huggingface__transformers | src/transformers/models/decision_transformer/modeling_decision_transformer.py | {
"start": 26670,
"end": 27437
} | class ____(ModelOutput):
r"""
state_preds (`torch.FloatTensor` of shape `(batch_size, sequence_length, state_dim)`):
Environment state predictions
action_preds (`torch.FloatTensor` of shape `(batch_size, sequence_length, action_dim)`):
Model action predictions
return_preds (`torch.FloatTensor` of shape `(batch_size, sequence_length, 1)`):
Predicted returns for each state
"""
state_preds: Optional[torch.FloatTensor] = None
action_preds: Optional[torch.FloatTensor] = None
return_preds: Optional[torch.FloatTensor] = None
hidden_states: Optional[torch.FloatTensor] = None
attentions: Optional[torch.FloatTensor] = None
last_hidden_state: Optional[torch.FloatTensor] = None
| DecisionTransformerOutput |
python | PyCQA__pylint | doc/data/messages/d/deprecated-decorator/bad.py | {
"start": 13,
"end": 116
} | class ____:
@abc.abstractclassmethod # [deprecated-decorator]
def breath(cls):
pass
| Animal |
python | huggingface__transformers | src/transformers/models/deepseek_v3/modular_deepseek_v3.py | {
"start": 12161,
"end": 12796
} | class ____(LlamaDecoderLayer):
def __init__(self, config: DeepseekV3Config, layer_idx: int):
nn.Module.__init__(self)
self.hidden_size = config.hidden_size
self.self_attn = DeepseekV3Attention(config=config, layer_idx=layer_idx)
if layer_idx >= config.first_k_dense_replace:
self.mlp = DeepseekV3MoE(config)
else:
self.mlp = DeepseekV3MLP(config)
self.input_layernorm = DeepseekV3RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
self.post_attention_layernorm = DeepseekV3RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
| DeepseekV3DecoderLayer |
python | huggingface__transformers | src/transformers/models/decision_transformer/modeling_decision_transformer.py | {
"start": 16690,
"end": 18034
} | class ____(PreTrainedModel):
config: DecisionTransformerConfig
base_model_prefix = "transformer"
supports_gradient_checkpointing = True
_can_compile_fullgraph = False
def __init__(self, *inputs, **kwargs):
super().__init__(*inputs, **kwargs)
@torch.no_grad()
def _init_weights(self, module):
"""Initialize the weights."""
super()._init_weights(module)
# Reinitialize selected weights subject to the OpenAI GPT-2 Paper Scheme:
# > A modified initialization which accounts for the accumulation on the residual path with model depth. Scale
# > the weights of residual layers at initialization by a factor of 1/√N where N is the # of residual layers.
# > -- GPT-2 :: https://openai.com/blog/better-language-models/
#
# Reference (Megatron-LM): https://github.com/NVIDIA/Megatron-LM/blob/main/megatron/model/gpt_model.py
if isinstance(module, PreTrainedModel):
for name, p in module.named_parameters():
if "c_proj" in name and "weight" in name:
# Special Scaled Initialization --> There are 2 Layer Norms per Transformer Block
init.normal_(p, mean=0.0, std=self.config.initializer_range / math.sqrt(2 * self.config.n_layer))
| DecisionTransformerGPT2PreTrainedModel |
python | PyCQA__pylint | tests/functional/i/init_not_called.py | {
"start": 219,
"end": 307
} | class ____:
"""ancestor 1"""
def __init__(self):
print("init", self)
| AAAA |
python | numpy__numpy | numpy/random/tests/test_random.py | {
"start": 68318,
"end": 71278
} | class ____:
def _create_arrays(self):
return np.array([2]), np.array([3]), np.array([4]), (1,)
def test_one_arg_funcs(self):
argOne, _, _, tgtShape = self._create_arrays()
funcs = (np.random.exponential, np.random.standard_gamma,
np.random.chisquare, np.random.standard_t,
np.random.pareto, np.random.weibull,
np.random.power, np.random.rayleigh,
np.random.poisson, np.random.zipf,
np.random.geometric, np.random.logseries)
probfuncs = (np.random.geometric, np.random.logseries)
for func in funcs:
if func in probfuncs: # p < 1.0
out = func(np.array([0.5]))
else:
out = func(argOne)
assert_equal(out.shape, tgtShape)
def test_two_arg_funcs(self):
argOne, argTwo, _, tgtShape = self._create_arrays()
funcs = (np.random.uniform, np.random.normal,
np.random.beta, np.random.gamma,
np.random.f, np.random.noncentral_chisquare,
np.random.vonmises, np.random.laplace,
np.random.gumbel, np.random.logistic,
np.random.lognormal, np.random.wald,
np.random.binomial, np.random.negative_binomial)
probfuncs = (np.random.binomial, np.random.negative_binomial)
for func in funcs:
if func in probfuncs: # p <= 1
argTwo = np.array([0.5])
else:
argTwo = argTwo
out = func(argOne, argTwo)
assert_equal(out.shape, tgtShape)
out = func(argOne[0], argTwo)
assert_equal(out.shape, tgtShape)
out = func(argOne, argTwo[0])
assert_equal(out.shape, tgtShape)
def test_randint(self):
_, _, _, tgtShape = self._create_arrays()
itype = [bool, np.int8, np.uint8, np.int16, np.uint16,
np.int32, np.uint32, np.int64, np.uint64]
func = np.random.randint
high = np.array([1])
low = np.array([0])
for dt in itype:
out = func(low, high, dtype=dt)
assert_equal(out.shape, tgtShape)
out = func(low[0], high, dtype=dt)
assert_equal(out.shape, tgtShape)
out = func(low, high[0], dtype=dt)
assert_equal(out.shape, tgtShape)
def test_three_arg_funcs(self):
argOne, argTwo, argThree, tgtShape = self._create_arrays()
funcs = [np.random.noncentral_f, np.random.triangular,
np.random.hypergeometric]
for func in funcs:
out = func(argOne, argTwo, argThree)
assert_equal(out.shape, tgtShape)
out = func(argOne[0], argTwo, argThree)
assert_equal(out.shape, tgtShape)
out = func(argOne, argTwo[0], argThree)
assert_equal(out.shape, tgtShape)
| TestSingleEltArrayInput |
python | huggingface__transformers | src/transformers/models/longcat_flash/modular_longcat_flash.py | {
"start": 1878,
"end": 2275
} | class ____(DeepseekV3MLP):
def __init__(self, config, hidden_size=None, intermediate_size=None):
super().__init__(config)
self.hidden_size = config.hidden_size if hidden_size is None else hidden_size
self.intermediate_size = config.ffn_hidden_size if intermediate_size is None else intermediate_size
# TODO remap config key moe_topk -> num_experts_per_tok
| LongcatFlashMLP |
python | django-compressor__django-compressor | compressor/tests/test_utils.py | {
"start": 1734,
"end": 2153
} | class ____(TestCase):
def test_get_class_import_exception(self):
with self.assertRaises(FilterError) as context:
get_class("common.uglify.JsUglifySourcemapCompressor")
self.assertTrue(
(
"Failed to import common.uglify.JsUglifySourcemapCompressor. "
"ImportError is: No module named" in str(context.exception)
)
)
| TestGetClass |
python | sympy__sympy | sympy/physics/secondquant.py | {
"start": 4075,
"end": 4130
} | class ____(Expr):
is_commutative = True
| TensorSymbol |
python | kamyu104__LeetCode-Solutions | Python/maximum-total-reward-using-operations-i.py | {
"start": 81,
"end": 526
} | class ____(object):
def maxTotalReward(self, rewardValues):
"""
:type rewardValues: List[int]
:rtype: int
"""
mx = max(rewardValues)
dp = 1
mask = (1<<mx)-1
for v in sorted(set(rewardValues)):
x = dp&((1<<v)-1)
dp |= (x<<v)&mask
return mx+(dp.bit_length()-1)
# Time: O(nlogn + r^2), r = max(rewardValues)
# Space: O(r)
# sort, dp, bitset
| Solution |
python | mlflow__mlflow | dev/clint/src/clint/rules/markdown_link.py | {
"start": 36,
"end": 249
} | class ____(Rule):
def _message(self) -> str:
return (
"Markdown link is not supported in docstring. "
"Use reST link instead (e.g., `Link text <link URL>`_)."
)
| MarkdownLink |
python | python-poetry__poetry | src/poetry/puzzle/exceptions.py | {
"start": 509,
"end": 788
} | class ____(Exception):
def __init__(self, *overrides: dict[Package, dict[str, Dependency]]) -> None:
self._overrides = overrides
@property
def overrides(self) -> tuple[dict[Package, dict[str, Dependency]], ...]:
return self._overrides
| OverrideNeededError |
python | dagster-io__dagster | python_modules/automation/automation/dagster_docs/docstring_rules/base.py | {
"start": 312,
"end": 766
} | class ____:
"""Context information for validation rules."""
docstring: str
symbol_path: str
processed_rst: Optional[str] = None
def with_processed_rst(self, rst: str) -> "ValidationContext":
"""Return a new context with processed RST content."""
return ValidationContext(
docstring=self.docstring,
symbol_path=self.symbol_path,
processed_rst=rst,
)
@record
| ValidationContext |
python | huggingface__transformers | src/transformers/models/edgetam_video/modeling_edgetam_video.py | {
"start": 7325,
"end": 9965
} | class ____(nn.Module):
"""
Vision Rotary Position Embedding for SAM2, following transformers library standards.
Supports 2D (axial) rotary embeddings for spatial dimensions.
"""
def __init__(self, config: EdgeTamVideoConfig, end_x: Optional[int] = None, end_y: Optional[int] = None):
super().__init__()
dim = config.memory_attention_hidden_size // (
config.memory_attention_downsample_rate * config.memory_attention_num_attention_heads
)
# Ensure even dimension for proper axial splitting
if dim % 4 != 0:
raise ValueError("Dimension must be divisible by 4 for axial RoPE")
end_x, end_y = config.memory_attention_rope_feat_sizes if end_x is None else (end_x, end_y)
freqs = 1.0 / (config.memory_attention_rope_theta ** (torch.arange(0, dim, 4)[: (dim // 4)].float() / dim))
# Generate 2D position indices for axial rotary embedding
flattened_indices = torch.arange(end_x * end_y, dtype=torch.long)
x_positions = flattened_indices % end_x
y_positions = torch.div(flattened_indices, end_x, rounding_mode="floor")
freqs_x = torch.outer(x_positions, freqs).float()
freqs_y = torch.outer(y_positions, freqs).float()
inv_freq = torch.cat([freqs_x, freqs_y], dim=-1)
inv_freq = inv_freq.repeat_interleave(2, dim=-1)
# directly register the cos and sin embeddings as we have a fixed feature shape
self.register_buffer("rope_embeddings_cos", inv_freq.cos(), persistent=False)
self.register_buffer("rope_embeddings_sin", inv_freq.sin(), persistent=False)
@torch.no_grad()
def forward(self) -> tuple[torch.Tensor, torch.Tensor]:
# As the feature map size is fixed, we can just return the pre-computed embeddings.
return self.rope_embeddings_cos, self.rope_embeddings_sin
def eager_attention_forward(
module: nn.Module,
query: torch.Tensor,
key: torch.Tensor,
value: torch.Tensor,
attention_mask: Optional[torch.Tensor],
scaling: float,
dropout: float = 0.0,
**kwargs,
):
attn_weights = torch.matmul(query, key.transpose(2, 3)) * scaling
if attention_mask is not None:
attn_weights = attn_weights + attention_mask
attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype)
attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
attn_output = torch.matmul(attn_weights, value)
attn_output = attn_output.transpose(1, 2).contiguous()
return attn_output, attn_weights
| EdgeTamVideoVisionRotaryEmbedding |
python | dagster-io__dagster | python_modules/libraries/dagster-papertrail/dagster_papertrail/loggers.py | {
"start": 91,
"end": 2420
} | class ____(logging.Filter):
hostname = socket.gethostname()
def filter(self, record):
record.hostname = ContextFilter.hostname
return True
@logger(
{
"log_level": Field(StringSource, is_required=False, default_value="INFO"),
"name": Field(StringSource, is_required=False, default_value="dagster_papertrail"),
"papertrail_address": Field(StringSource, description="Papertrail URL", is_required=True),
"papertrail_port": Field(IntSource, description="Papertrail port", is_required=True),
},
description="A JSON-formatted console logger",
)
def papertrail_logger(init_context):
"""Use this logger to configure your Dagster job to log to Papertrail. You'll need an
active Papertrail account with URL and port.
Example:
.. code-block:: python
@job(logger_defs={
"console": colored_console_logger,
"papertrail": papertrail_logger,
})
def simple_job():
...
simple_job.execute_in_process(
run_config={
"loggers": {
"console": {
"config": {
"log_level": "INFO",
}
},
"papertrail": {
"config": {
"log_level": "INFO",
"name": "hello_job",
"papertrail_address": "127.0.0.1",
"papertrail_port": 12345,
}
},
}
}
)
"""
level, name, papertrail_address, papertrail_port = (
init_context.logger_config.get(k)
for k in ("log_level", "name", "papertrail_address", "papertrail_port")
)
klass = logging.getLoggerClass()
logger_ = klass(name, level=level)
log_format = "%(asctime)s %(hostname)s " + name + ": %(message)s"
formatter = logging.Formatter(log_format, datefmt="%b %d %H:%M:%S")
handler = logging.handlers.SysLogHandler(address=(papertrail_address, papertrail_port)) # pyright: ignore[reportAttributeAccessIssue]
handler.addFilter(ContextFilter())
handler.setFormatter(formatter)
logger_.addHandler(handler)
return logger_
| ContextFilter |
python | getsentry__sentry | src/sentry/grouping/grouptype.py | {
"start": 831,
"end": 1289
} | class ____(GroupType):
type_id = DEFAULT_TYPE_ID
slug = "error"
description = "Error"
category = GroupCategory.ERROR.value
category_v2 = GroupCategory.ERROR.value
default_priority = PriorityLevel.MEDIUM
released = True
detector_settings = DetectorSettings(
handler=ErrorDetectorHandler,
validator=ErrorDetectorValidator,
config_schema={"type": "object", "additionalProperties": False},
)
| ErrorGroupType |
python | gevent__gevent | src/greentest/3.10/test_asyncore.py | {
"start": 26608,
"end": 26753
} | class ____(TestAPI_UseUnixSockets, unittest.TestCase):
use_poll = True
if __name__ == "__main__":
unittest.main()
| TestAPI_UseUnixSocketsPoll |
python | ray-project__ray | python/ray/_private/log_monitor.py | {
"start": 1422,
"end": 4066
} | class ____:
def __init__(
self,
filename=None,
size_when_last_opened=None,
file_position=None,
file_handle=None,
is_err_file=False,
job_id=None,
worker_pid=None,
):
assert (
filename is not None
and size_when_last_opened is not None
and file_position is not None
)
self.filename = filename
self.size_when_last_opened = size_when_last_opened
self.file_position = file_position
self.file_handle = file_handle
self.is_err_file = is_err_file
self.job_id = job_id
self.worker_pid = worker_pid
self.actor_name = None
self.task_name = None
def reopen_if_necessary(self):
"""Check if the file's inode has changed and reopen it if necessary.
There are a variety of reasons what we would logically consider a file
would have different inodes, such as log rotation or file syncing
semantics.
If the file is smaller than our recorded file position, we assume it has been
rotated and start reading it from the beginning.
"""
try:
open_inode = None
if self.file_handle and not self.file_handle.closed:
open_inode = os.fstat(self.file_handle.fileno()).st_ino
new_statinfo = os.stat(self.filename)
if new_statinfo.st_ino != open_inode:
self.file_handle = open(self.filename, "rb")
# If the new file is smaller than the last read position, assume that
# the file has been rotated and read from the beginning. Else, continue
# from the existing file position.
if new_statinfo.st_size < self.file_position:
self.file_position = 0
self.file_handle.seek(self.file_position)
self.size_when_last_opened = new_statinfo.st_size
except Exception:
logger.debug(f"file no longer exists, skip re-opening of {self.filename}")
def __repr__(self):
return (
"FileInfo(\n"
f"\tfilename: {self.filename}\n"
f"\tsize_when_last_opened: {self.size_when_last_opened}\n"
f"\tfile_position: {self.file_position}\n"
f"\tfile_handle: {self.file_handle}\n"
f"\tis_err_file: {self.is_err_file}\n"
f"\tjob_id: {self.job_id}\n"
f"\tworker_pid: {self.worker_pid}\n"
f"\tactor_name: {self.actor_name}\n"
f"\ttask_name: {self.task_name}\n"
")"
)
| LogFileInfo |
python | great-expectations__great_expectations | contrib/great_expectations_zipcode_expectations/great_expectations_zipcode_expectations/expectations/expect_column_values_to_be_valid_tennessee_zip.py | {
"start": 752,
"end": 1759
} | class ____(ColumnMapMetricProvider):
# This is the id string that will be used to reference your metric.
condition_metric_name = "column_values.valid_tennessee_zip"
# This method implements the core logic for the PandasExecutionEngine
@column_condition_partial(engine=PandasExecutionEngine)
def _pandas(cls, column, **kwargs):
return column.apply(lambda x: is_valid_tennessee_zip(x))
# This method defines the business logic for evaluating your metric when using a SqlAlchemyExecutionEngine
# @column_condition_partial(engine=SqlAlchemyExecutionEngine)
# def _sqlalchemy(cls, column, _dialect, **kwargs):
# raise NotImplementedError
# This method defines the business logic for evaluating your metric when using a SparkDFExecutionEngine
# @column_condition_partial(engine=SparkDFExecutionEngine)
# def _spark(cls, column, **kwargs):
# raise NotImplementedError
# This class defines the Expectation itself
| ColumnValuesToBeValidTennesseeZip |
python | huggingface__transformers | src/transformers/models/align/modeling_align.py | {
"start": 13543,
"end": 16560
} | class ____(nn.Module):
r"""
This corresponds to the block module of original the EfficientNet vision encoder implementation.
Args:
config ([`AlignVisionConfig`]):
Model configuration class.
in_dim (`int`):
Number of input channels.
out_dim (`int`):
Number of output channels.
stride (`int`):
Stride size to be used in convolution layers.
expand_ratio (`int`):
Expand ratio to set the output dimensions for the expansion and squeeze-excite layers.
kernel_size (`int`):
Kernel size for the depthwise convolution layer.
drop_rate (`float`):
Dropout rate to be used in the final phase of each block.
id_skip (`bool`):
Whether to apply dropout and sum the final hidden states with the input embeddings during the final phase
of each block. Set to `True` for the first block of each stage.
adjust_padding (`bool`):
Whether to apply padding to only right and bottom side of the input kernel before the depthwise convolution
operation, set to `True` for inputs with odd input sizes.
"""
def __init__(
self,
config: AlignVisionConfig,
in_dim: int,
out_dim: int,
stride: int,
expand_ratio: int,
kernel_size: int,
drop_rate: float,
id_skip: bool,
adjust_padding: bool,
):
super().__init__()
self.expand_ratio = expand_ratio
self.expand = self.expand_ratio != 1
expand_in_dim = in_dim * expand_ratio
if self.expand:
self.expansion = AlignVisionExpansionLayer(
config=config, in_dim=in_dim, out_dim=expand_in_dim, stride=stride
)
self.depthwise_conv = AlignVisionDepthwiseLayer(
config=config,
in_dim=expand_in_dim if self.expand else in_dim,
stride=stride,
kernel_size=kernel_size,
adjust_padding=adjust_padding,
)
self.squeeze_excite = AlignVisionSqueezeExciteLayer(
config=config, in_dim=in_dim, expand_dim=expand_in_dim, expand=self.expand
)
self.projection = AlignVisionFinalBlockLayer(
config=config,
in_dim=expand_in_dim if self.expand else in_dim,
out_dim=out_dim,
stride=stride,
drop_rate=drop_rate,
id_skip=id_skip,
)
def forward(self, hidden_states: torch.FloatTensor) -> torch.Tensor:
embeddings = hidden_states
# Expansion and depthwise convolution phase
if self.expand_ratio != 1:
hidden_states = self.expansion(hidden_states)
hidden_states = self.depthwise_conv(hidden_states)
# Squeeze and excite phase
hidden_states = self.squeeze_excite(hidden_states)
hidden_states = self.projection(embeddings, hidden_states)
return hidden_states
| AlignVisionBlock |
python | django__django | tests/admin_views/models.py | {
"start": 20143,
"end": 20319
} | class ____(models.Model):
name = models.CharField(max_length=100)
age = models.PositiveIntegerField()
is_employee = models.BooleanField(null=True)
| ComplexSortedPerson |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 464336,
"end": 464873
} | class ____(sgqlc.types.Type):
"""Autogenerated return type of AddEnterpriseOrganizationMember"""
__schema__ = github_schema
__field_names__ = ("client_mutation_id", "users")
client_mutation_id = sgqlc.types.Field(String, graphql_name="clientMutationId")
"""A unique identifier for the client performing the mutation."""
users = sgqlc.types.Field(sgqlc.types.list_of(sgqlc.types.non_null("User")), graphql_name="users")
"""The users who were added to the organization."""
| AddEnterpriseOrganizationMemberPayload |
python | sympy__sympy | sympy/matrices/immutable.py | {
"start": 3917,
"end": 5591
} | class ____(SparseRepMatrix, ImmutableRepMatrix): # type:ignore
"""Create an immutable version of a sparse matrix.
Examples
========
>>> from sympy import eye, ImmutableSparseMatrix
>>> ImmutableSparseMatrix(1, 1, {})
Matrix([[0]])
>>> ImmutableSparseMatrix(eye(3))
Matrix([
[1, 0, 0],
[0, 1, 0],
[0, 0, 1]])
>>> _[0, 0] = 42
Traceback (most recent call last):
...
TypeError: Cannot set values of ImmutableSparseMatrix
>>> _.shape
(3, 3)
"""
is_Matrix = True
_class_priority = 9
@classmethod
def _new(cls, *args, **kwargs):
rows, cols, smat = cls._handle_creation_inputs(*args, **kwargs)
rep = cls._smat_to_DomainMatrix(rows, cols, smat)
return cls._fromrep(rep)
@classmethod
def _fromrep(cls, rep):
rows, cols = rep.shape
smat = rep.to_sympy().to_dok()
obj = Basic.__new__(cls, Integer(rows), Integer(cols), Dict(smat))
obj._rows = rows
obj._cols = cols
obj._rep = rep
return obj
@dispatch(ImmutableDenseMatrix, ImmutableDenseMatrix)
def _eval_is_eq(lhs, rhs): # noqa:F811
"""Helper method for Equality with matrices.sympy.
Relational automatically converts matrices to ImmutableDenseMatrix
instances, so this method only applies here. Returns True if the
matrices are definitively the same, False if they are definitively
different, and None if undetermined (e.g. if they contain Symbols).
Returning None triggers default handling of Equalities.
"""
if lhs.shape != rhs.shape:
return False
return (lhs - rhs).is_zero_matrix
| ImmutableSparseMatrix |
python | getsentry__sentry | src/sentry/auth/access.py | {
"start": 29826,
"end": 40230
} | class ____(OrganizationlessAccess):
def __init__(self) -> None:
super().__init__(
auth_state=RpcAuthState(
sso_state=RpcMemberSsoState(is_required=False, is_valid=True),
permissions=[],
),
)
def from_request_org_and_scopes(
*,
request: HttpRequest,
rpc_user_org_context: RpcUserOrganizationContext | None = None,
scopes: Iterable[str] | None = None,
) -> Access:
"""
Note that `scopes` is usually None because request.auth is not set at `get_authorization_header`
when the request is made from the frontend using cookies
"""
is_staff = is_active_staff(request)
if not rpc_user_org_context:
return from_user_and_rpc_user_org_context(
user=request.user,
rpc_user_org_context=rpc_user_org_context,
is_superuser=is_active_superuser(request),
is_staff=is_staff,
scopes=scopes,
)
if getattr(request.user, "is_sentry_app", False):
return _from_rpc_sentry_app(rpc_user_org_context)
if is_active_superuser(request):
member = rpc_user_org_context.member
auth_state = access_service.get_user_auth_state(
user_id=request.user.id,
organization_id=rpc_user_org_context.organization.id,
is_superuser=True,
is_staff=is_staff,
org_member=member,
)
superuser_scopes = get_superuser_scopes(auth_state, request.user, rpc_user_org_context)
if scopes:
superuser_scopes = superuser_scopes.union(set(scopes))
if member and member.scopes:
superuser_scopes = superuser_scopes.union(set(member.scopes))
return ApiBackedOrganizationGlobalAccess(
rpc_user_organization_context=rpc_user_org_context,
auth_state=auth_state,
scopes=superuser_scopes,
)
if request.auth is not None and not request.user.is_authenticated:
return from_rpc_auth(request.auth, rpc_user_org_context)
return from_user_and_rpc_user_org_context(
user=request.user,
rpc_user_org_context=rpc_user_org_context,
is_superuser=False,
is_staff=is_staff,
scopes=scopes,
)
def organizationless_access(
user: User | RpcUser | AnonymousUser, is_superuser: bool, is_staff: bool
) -> Access:
return OrganizationlessAccess(
auth_state=access_service.get_user_auth_state(
user_id=user.id,
is_superuser=is_superuser,
is_staff=is_staff,
organization_id=None,
org_member=None,
)
)
def normalize_valid_user(user: User | RpcUser | AnonymousUser | None) -> User | RpcUser | None:
if not user or user.is_anonymous or not user.is_active:
return None
return user
def from_user_and_rpc_user_org_context(
*,
user: User | AnonymousUser | RpcUser | None,
rpc_user_org_context: RpcUserOrganizationContext | None = None,
is_superuser: bool = False,
is_staff: bool = False,
scopes: Iterable[str] | None = None,
auth_state: RpcAuthState | None = None,
) -> Access:
if (user := normalize_valid_user(user)) is None:
return DEFAULT
if not rpc_user_org_context or not rpc_user_org_context.member:
return organizationless_access(user, is_superuser, is_staff)
return from_rpc_member(
rpc_user_organization_context=rpc_user_org_context,
scopes=scopes,
is_superuser=is_superuser,
is_staff=is_staff,
auth_state=auth_state,
)
def from_request(
request: Request, organization: Organization | None = None, scopes: Iterable[str] | None = None
) -> Access:
is_staff = is_active_staff(request)
if not organization:
return from_user(
request.user,
organization=organization,
scopes=scopes,
is_superuser=is_active_superuser(request),
is_staff=is_staff,
)
if request.user.is_authenticated and request.user.is_sentry_app:
return _from_sentry_app(request.user, organization=organization)
if is_active_superuser(request):
member: OrganizationMember | None = None
try:
member = OrganizationMember.objects.get(
user_id=request.user.id, organization_id=organization.id
)
except OrganizationMember.DoesNotExist:
pass
auth_state = access_service.get_user_auth_state(
user_id=request.user.id,
organization_id=organization.id,
is_superuser=True,
is_staff=is_staff,
org_member=(summarize_member(member) if member is not None else None),
)
sso_state = auth_state.sso_state
superuser_scopes = get_superuser_scopes(auth_state, request.user, organization)
if scopes:
superuser_scopes = superuser_scopes.union(set(scopes))
if member and (member_scopes := member.get_scopes()):
superuser_scopes = superuser_scopes.union(set(member_scopes))
return OrganizationGlobalAccess(
organization=organization,
_member=member,
scopes=superuser_scopes,
sso_is_valid=sso_state.is_valid,
requires_sso=sso_state.is_required,
permissions=access_service.get_permissions_for_user(request.user.id),
)
if request.auth is not None and not request.user.is_authenticated:
return from_auth(request.auth, organization)
return from_user(user=request.user, organization=organization, scopes=scopes, is_staff=is_staff)
# only used internally
def _from_sentry_app(user: User, organization: Organization | None = None) -> Access:
if not organization:
return NoAccess()
sentry_app_query = SentryApp.objects.filter(proxy_user=user)
if not sentry_app_query.exists():
return NoAccess()
sentry_app = sentry_app_query.get()
if not sentry_app.is_installed_on(organization):
return NoAccess()
return OrganizationGlobalMembership(organization, sentry_app.scope_list, sso_is_valid=True)
def _from_rpc_sentry_app(context: RpcUserOrganizationContext | None = None) -> Access:
from sentry.sentry_apps.services.app import app_service
if not context or context.user_id is None:
return NoAccess()
installation = app_service.find_installation_by_proxy_user(
proxy_user_id=context.user_id, organization_id=context.organization.id
)
if installation is None:
return NoAccess()
return ApiOrganizationGlobalMembership(
rpc_user_organization_context=context,
auth_state=RpcAuthState(
sso_state=RpcMemberSsoState(
is_valid=True,
is_required=False,
),
permissions=[],
),
scopes=installation.sentry_app.scope_list,
)
def from_user(
user: User | RpcUser | AnonymousUser | None,
organization: Organization | None = None,
scopes: Iterable[str] | None = None,
is_superuser: bool = False,
is_staff: bool = False,
) -> Access:
if (user := normalize_valid_user(user)) is None:
return DEFAULT
if not organization:
return organizationless_access(user, is_superuser, is_staff)
try:
om = OrganizationMember.objects.get(user_id=user.id, organization_id=organization.id)
except OrganizationMember.DoesNotExist:
return organizationless_access(user, is_superuser, is_staff)
# ensure cached relation
om.organization = organization
return from_member(om, scopes=scopes, is_superuser=is_superuser, is_staff=is_staff)
def from_member(
member: OrganizationMember,
scopes: Iterable[str] | None = None,
is_superuser: bool = False,
is_staff: bool = False,
) -> Access:
if scopes is not None:
scope_intersection = frozenset(scopes) & member.get_scopes()
else:
scope_intersection = member.get_scopes()
if (is_superuser or is_staff) and member.user_id is not None:
# "permissions" is a bit of a misnomer -- these are all admin level permissions, and the intent is that if you
# have them, you can only use them when you are acting, as a superuser or staff. This is intentional.
permissions = access_service.get_permissions_for_user(member.user_id)
else:
permissions = frozenset()
return OrganizationMemberAccess(member, scope_intersection, permissions, scopes)
def from_rpc_member(
rpc_user_organization_context: RpcUserOrganizationContext,
scopes: Iterable[str] | None = None,
is_superuser: bool = False,
is_staff: bool = False,
auth_state: RpcAuthState | None = None,
) -> Access:
if rpc_user_organization_context.user_id is None:
return DEFAULT
return RpcBackedAccess(
rpc_user_organization_context=rpc_user_organization_context,
scopes_upper_bound=_wrap_scopes(scopes),
auth_state=auth_state
or access_service.get_user_auth_state(
user_id=rpc_user_organization_context.user_id,
organization_id=rpc_user_organization_context.organization.id,
is_superuser=is_superuser,
is_staff=is_staff,
org_member=rpc_user_organization_context.member,
),
)
def from_auth(auth: AuthenticatedToken, organization: Organization) -> Access:
if is_system_auth(auth):
return SystemAccess()
elif auth.organization_id == organization.id:
return OrganizationGlobalAccess(
auth.organization_id, settings.SENTRY_SCOPES, sso_is_valid=True
)
else:
return DEFAULT
def from_rpc_auth(
auth: AuthenticatedToken, rpc_user_org_context: RpcUserOrganizationContext
) -> Access:
if is_system_auth(auth):
return SystemAccess()
if auth.organization_id == rpc_user_org_context.organization.id:
return ApiBackedOrganizationGlobalAccess(
rpc_user_organization_context=rpc_user_org_context,
auth_state=RpcAuthState(
permissions=[],
sso_state=RpcMemberSsoState(
is_valid=True,
is_required=False,
),
),
scopes=settings.SENTRY_SCOPES,
)
else:
return DEFAULT
DEFAULT = NoAccess()
| NoAccess |
python | apache__airflow | task-sdk/src/airflow/sdk/exceptions.py | {
"start": 1484,
"end": 1659
} | class ____(AirflowException):
"""Raise when the requested object/resource is not available in the system."""
status_code = HTTPStatus.NOT_FOUND
| AirflowNotFoundException |
python | charliermarsh__ruff | crates/ruff_python_formatter/resources/test/fixtures/ruff/statement/top_level.py | {
"start": 47,
"end": 115
} | class ____:
def __init__(self):
pass
def foo():
pass
| B |
python | pytorch__pytorch | torch/_library/fake_impl.py | {
"start": 4765,
"end": 8772
} | class ____:
"""
Context object for writing fake implementations for custom operators.
"""
def __init__(self, _fake_mode, _op):
self._fake_mode = _fake_mode
self._shape_env = _fake_mode.shape_env
self._op = _op
@deprecated(
"`create_unbacked_symint` is deprecated, please use `new_dynamic_size` instead",
category=FutureWarning,
)
def create_unbacked_symint(self, *, min=2, max=None) -> torch.SymInt:
return self.new_dynamic_size(min=min, max=max)
def new_dynamic_size(self, *, min=0, max=None) -> torch.SymInt:
"""Constructs a new symint (symbolic int) representing a data-dependent value.
This is useful for writing the fake implementation (which is necessary
for torch.compile) for a CustomOp where an output Tensor has a size
that depends on the data of the input Tensors.
Args:
min (int): A statically known inclusive lower bound for this symint. Default: 0
max (Optional[int]): A statically known inclusive upper bound for this
symint. Default: None
.. warning:
It is important that the ``min`` and ``max`` (if not None) values are set
correctly, otherwise, there will be undefined behavior under
torch.compile. The default value of ``min`` is 2 due to torch.compile
specializing on 0/1 sizes.
You must also verify that your implementation on concrete Tensors
(e.g. CPU/CUDA) only returns Tensors where the size that corresponds
to the symint also has respects these constraint.
The easiest way to do this is to add an assertion in the CPU/CUDA/etc
implementation that the size follows these bounds.
Example::
>>> # An operator with data-dependent output shape
>>> lib = torch.library.Library("mymodule", "FRAGMENT")
>>> lib.define("mymodule::custom_nonzero(Tensor x) -> Tensor")
>>>
>>> @torch.library.register_fake("mymodule::custom_nonzero")
>>> def _(x):
>>> # Number of nonzero-elements is data-dependent.
>>> # Since we cannot peek at the data in an fake impl,
>>> # we use the ctx object to construct a new symint that
>>> # represents the data-dependent size.
>>> ctx = torch.library.get_ctx()
>>> nnz = ctx.new_dynamic_size()
>>> shape = [nnz, x.dim()]
>>> result = x.new_empty(shape, dtype=torch.int64)
>>> return result
>>>
>>> @torch.library.impl(lib, "custom_nonzero", "CPU")
>>> def _(x):
>>> x_np = x.numpy()
>>> res = np.stack(np.nonzero(x_np), axis=1)
>>> return torch.tensor(res, device=x.device)
"""
if (
self._shape_env is None
or not self._shape_env.allow_dynamic_output_shape_ops
):
raise torch._subclasses.fake_tensor.DynamicOutputShapeException(self._op)
if isinstance(min, torch.SymInt) or isinstance(max, torch.SymInt):
raise ValueError(
f"ctx.new_dynamic_size(min={min}, max={max}): expected "
f"min and max to be statically known ints but got SymInt. "
f"This is not supported."
)
if min < 0:
raise ValueError(
f"ctx.new_dynamic_size(min={min}, ...): expected min to be "
f"greater than or equal to 0: this API can only create "
f"non-negative sizes."
)
return allocate_size(self._shape_env, min, max)
def allocate_size(shape_env, min_val=0, max_val=None):
result = shape_env.create_unbacked_symint()
torch.fx.experimental.symbolic_shapes._constrain_range_for_size(
result, min=min_val, max=max_val
)
return result
| FakeImplCtx |
python | huggingface__transformers | src/transformers/models/minimax/modular_minimax.py | {
"start": 28917,
"end": 29215
} | class ____(MixtralForQuestionAnswering):
pass
__all__ = [
"MiniMaxConfig",
"MiniMaxPreTrainedModel",
"MiniMaxModel",
"MiniMaxForCausalLM",
"MiniMaxForSequenceClassification",
"MiniMaxForTokenClassification",
"MiniMaxForQuestionAnswering",
]
| MiniMaxForQuestionAnswering |
python | ray-project__ray | python/ray/_private/thirdparty/pynvml/pynvml.py | {
"start": 65411,
"end": 65785
} | class ____(_PrintableStructure):
_fields_ = [
('vgpuInstance', _nvmlVgpuInstance_t),
('pid', c_uint),
('processName', c_char * NVML_VGPU_NAME_BUFFER_SIZE),
('timeStamp', c_ulonglong),
('smUtil', c_uint),
('memUtil', c_uint),
('encUtil', c_uint),
('decUtil', c_uint),
]
| c_nvmlVgpuProcessUtilizationSample_t |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/genericType4.py | {
"start": 353,
"end": 571
} | class ____(Base2[float], Generic[T]):
pass
val2_1: Base2[float] = Derived2[int]()
# This should generate an error because Derived2[int]
# isn't assignable to Base2[int].
val2_2: Base2[int] = Derived2[int]()
| Derived2 |
python | Textualize__textual | tests/snapshot_tests/snapshot_apps/mount_style_fix.py | {
"start": 184,
"end": 669
} | class ____(App[None]):
CSS = """
Screen {
align: center middle;
}
Static {
width: 50%;
height: 50%;
border: solid;
}
Screen.go-red Static {
background: red;
}
"""
def compose(self) -> ComposeResult:
yield Static("This should have a red background")
def on_mount(self) -> None:
self.screen.set_class(True, "go-red")
if __name__ == "__main__":
BrokenClassesApp().run()
| BrokenClassesApp |
python | astropy__astropy | astropy/visualization/tests/test_norm.py | {
"start": 1037,
"end": 7586
} | class ____:
def test_invalid_interval(self):
with pytest.raises(TypeError):
ImageNormalize(vmin=2.0, vmax=10.0, interval=ManualInterval, clip=True)
def test_invalid_vmin_vmax(self):
with pytest.raises(ValueError):
norm = ImageNormalize(vmin=10.0, vmax=2.0)
norm(10)
def test_invalid_stretch(self):
with pytest.raises(TypeError):
ImageNormalize(vmin=2.0, vmax=10.0, stretch=SqrtStretch, clip=True)
def test_stretch_none(self):
with pytest.raises(ValueError):
ImageNormalize(vmin=2.0, vmax=10.0, stretch=None)
def test_scalar(self):
norm = ImageNormalize(vmin=2.0, vmax=10.0, stretch=SqrtStretch(), clip=True)
norm2 = ImageNormalize(
data=6, interval=ManualInterval(2, 10), stretch=SqrtStretch(), clip=True
)
assert_allclose(norm(6), 0.70710678)
assert_allclose(norm(6), norm2(6))
def test_vmin_vmax_equal(self):
norm = ImageNormalize(vmin=2.0, vmax=2.0)
data = np.arange(10) - 5.0
assert_array_equal(norm(data), 0)
def test_clip(self):
norm = ImageNormalize(vmin=2.0, vmax=10.0, stretch=SqrtStretch(), clip=True)
norm2 = ImageNormalize(
DATA, interval=ManualInterval(2, 10), stretch=SqrtStretch(), clip=True
)
output = norm(DATA)
expected = [0.0, 0.35355339, 0.70710678, 0.93541435, 1.0, 1.0]
assert_allclose(output, expected)
assert_allclose(output.mask, [0, 0, 0, 0, 0, 0])
assert_allclose(output, norm2(DATA))
def test_noclip(self):
norm = ImageNormalize(
vmin=2.0, vmax=10.0, stretch=SqrtStretch(), clip=False, invalid=None
)
norm2 = ImageNormalize(
DATA,
interval=ManualInterval(2, 10),
stretch=SqrtStretch(),
clip=False,
invalid=None,
)
output = norm(DATA)
expected = [np.nan, 0.35355339, 0.70710678, 0.93541435, 1.11803399, 1.27475488]
assert_allclose(output, expected)
assert_allclose(output.mask, [0, 0, 0, 0, 0, 0])
assert_allclose(norm.inverse(norm(DATA))[1:], DATA[1:])
assert_allclose(output, norm2(DATA))
def test_implicit_autoscale(self):
norm = ImageNormalize(vmin=None, vmax=10.0, stretch=SqrtStretch(), clip=False)
norm2 = ImageNormalize(
DATA, interval=ManualInterval(None, 10), stretch=SqrtStretch(), clip=False
)
output = norm(DATA)
assert norm.vmin == np.min(DATA)
assert norm.vmax == 10.0
assert_allclose(output, norm2(DATA))
norm = ImageNormalize(vmin=2.0, vmax=None, stretch=SqrtStretch(), clip=False)
norm2 = ImageNormalize(
DATA, interval=ManualInterval(2, None), stretch=SqrtStretch(), clip=False
)
output = norm(DATA)
assert norm.vmin == 2.0
assert norm.vmax == np.max(DATA)
assert_allclose(output, norm2(DATA))
def test_call_clip(self):
"""Test that the clip keyword is used when calling the object."""
data = np.arange(5)
norm = ImageNormalize(vmin=1.0, vmax=3.0, clip=False)
output = norm(data, clip=True)
assert_equal(output.data, [0, 0, 0.5, 1.0, 1.0])
assert np.all(~output.mask)
output = norm(data, clip=False)
assert_equal(output.data, [-0.5, 0, 0.5, 1.0, 1.5])
assert np.all(~output.mask)
def test_masked_clip(self):
mdata = ma.array(DATA, mask=[0, 0, 1, 0, 0, 0])
norm = ImageNormalize(vmin=2.0, vmax=10.0, stretch=SqrtStretch(), clip=True)
norm2 = ImageNormalize(
mdata, interval=ManualInterval(2, 10), stretch=SqrtStretch(), clip=True
)
output = norm(mdata)
expected = [0.0, 0.35355339, 1.0, 0.93541435, 1.0, 1.0]
assert_allclose(output.filled(-10), expected)
assert_allclose(output.mask, [0, 0, 0, 0, 0, 0])
assert_allclose(output, norm2(mdata))
def test_masked_noclip(self):
mdata = ma.array(DATA, mask=[0, 0, 1, 0, 0, 0])
norm = ImageNormalize(
vmin=2.0, vmax=10.0, stretch=SqrtStretch(), clip=False, invalid=None
)
norm2 = ImageNormalize(
mdata,
interval=ManualInterval(2, 10),
stretch=SqrtStretch(),
clip=False,
invalid=None,
)
output = norm(mdata)
expected = [np.nan, 0.35355339, -10, 0.93541435, 1.11803399, 1.27475488]
assert_allclose(output.filled(-10), expected)
assert_allclose(output.mask, [0, 0, 1, 0, 0, 0])
assert_allclose(norm.inverse(norm(DATA))[1:], DATA[1:])
assert_allclose(output, norm2(mdata))
def test_invalid_data(self):
data = np.arange(25.0).reshape((5, 5))
data[2, 2] = np.nan
data[1, 2] = np.inf
percent = 85.0
interval = PercentileInterval(percent)
# initialized without data
norm = ImageNormalize(interval=interval)
norm(data) # sets vmin/vmax
assert_equal((norm.vmin, norm.vmax), (1.65, 22.35))
# initialized with data
norm2 = ImageNormalize(data, interval=interval)
assert_equal((norm2.vmin, norm2.vmax), (norm.vmin, norm.vmax))
norm3 = simple_norm(data, "linear", percent=percent)
assert_equal((norm3.vmin, norm3.vmax), (norm.vmin, norm.vmax))
assert_allclose(norm(data), norm2(data))
assert_allclose(norm(data), norm3(data))
norm4 = ImageNormalize()
norm4(data) # sets vmin/vmax
assert_equal((norm4.vmin, norm4.vmax), (0, 24))
norm5 = ImageNormalize(data)
assert_equal((norm5.vmin, norm5.vmax), (norm4.vmin, norm4.vmax))
@pytest.mark.parametrize("stretch", STRETCHES)
def test_invalid_keyword(self, stretch):
norm1 = ImageNormalize(
stretch=stretch, vmin=-1, vmax=1, clip=False, invalid=None
)
norm2 = ImageNormalize(stretch=stretch, vmin=-1, vmax=1, clip=False)
norm3 = ImageNormalize(
DATA3, stretch=stretch, vmin=-1, vmax=1, clip=False, invalid=-1.0
)
result1 = norm1(DATA3)
result2 = norm2(DATA3)
result3 = norm3(DATA3)
assert_equal(result1[0:2], (np.nan, np.nan))
assert_equal(result2[0:2], (-1.0, -1.0))
assert_equal(result1[2:], result2[2:])
assert_equal(result2, result3)
@pytest.mark.skipif(not HAS_PLT, reason="requires matplotlib")
| TestNormalize |
python | ray-project__ray | python/ray/tests/unit/test_runtime_env_validation.py | {
"start": 6226,
"end": 7557
} | class ____:
def test_validate_conda_invalid_types(self):
with pytest.raises(TypeError):
parse_and_validate_conda(1)
with pytest.raises(TypeError):
parse_and_validate_conda(True)
def test_validate_conda_str(self):
assert parse_and_validate_conda("my_env_name") == "my_env_name"
def test_validate_conda_invalid_path(self):
with pytest.raises(ValueError):
parse_and_validate_conda("../bad_path.yaml")
@pytest.mark.parametrize("absolute_path", [True, False])
def test_validate_conda_valid_file(self, test_directory, absolute_path):
_, _, good_conda_file, _ = test_directory
if absolute_path:
good_conda_file = good_conda_file.resolve()
assert parse_and_validate_conda(str(good_conda_file)) == _CONDA_DICT
@pytest.mark.parametrize("absolute_path", [True, False])
def test_validate_conda_invalid_file(self, test_directory, absolute_path):
_, _, _, bad_conda_file = test_directory
if absolute_path:
bad_conda_file = bad_conda_file.resolve()
with pytest.raises(ValueError):
parse_and_validate_conda(str(bad_conda_file))
def test_validate_conda_valid_dict(self):
assert parse_and_validate_conda(_CONDA_DICT) == _CONDA_DICT
| TestValidateConda |
python | huggingface__transformers | tests/models/colqwen2/test_modeling_colqwen2.py | {
"start": 10494,
"end": 15266
} | class ____(unittest.TestCase):
model_name: ClassVar[str] = "vidore/colqwen2-v1.0-hf"
def setUp(self):
self.processor = ColQwen2Processor.from_pretrained(self.model_name)
def tearDown(self):
cleanup(torch_device, gc_collect=True)
@require_bitsandbytes
@slow
def test_model_integration_test(self):
"""
Test if the model is able to retrieve the correct pages for a small and easy dataset.
"""
model = ColQwen2ForRetrieval.from_pretrained(
self.model_name,
dtype=torch.float16,
quantization_config=BitsAndBytesConfig(load_in_8bit=True),
).eval()
# Load the test dataset
ds = load_dataset("hf-internal-testing/document-visual-retrieval-test", split="test")
# Preprocess the examples
batch_images = self.processor(images=ds["image"]).to(torch_device)
batch_queries = self.processor(text=ds["query"]).to(torch_device)
# Run inference
with torch.inference_mode():
image_embeddings = model(**batch_images).embeddings
query_embeddings = model(**batch_queries).embeddings
# Compute retrieval scores
scores = self.processor.score_retrieval(
query_embeddings=query_embeddings,
passage_embeddings=image_embeddings,
) # (num_queries, num_passages)
assert scores.ndim == 2, f"Expected 2D tensor, got {scores.ndim}"
assert scores.shape == (len(ds), len(ds)), f"Expected shape {(len(ds), len(ds))}, got {scores.shape}"
# Check if the maximum scores per row are in the diagonal of the matrix score
self.assertTrue((scores.argmax(axis=1) == torch.arange(len(ds), device=scores.device)).all())
# Further validation: fine-grained check, with a hardcoded score from the original Hf implementation.
expectations = Expectations(
{
("cuda", 7): [
[15.0938, 8.3203, 15.0391],
[9.6328, 16.9062, 10.5312],
[15.6562, 12.2656, 20.2969],
],
("cuda", 8): [
[16.2812, 8.3672, 14.5703],
[9.4922, 17.1875, 10.3281],
[15.0312, 11.3984, 20.1719],
],
}
)
expected_scores = torch.tensor(expectations.get_expectation(), dtype=scores.dtype)
assert torch.allclose(scores, expected_scores, atol=1e-3), f"Expected scores {expected_scores}, got {scores}"
@slow
def test_model_integration_test_2(self):
"""
Test if the model is able to retrieve the correct pages for a small and easy dataset.
This test uses a ColQwen2.5 checkpoint that is compatible with the ColQwen2 architecture.
"""
model = ColQwen2ForRetrieval.from_pretrained(
"Sahil-Kabir/colqwen2.5-v0.2-hf",
device_map=torch_device,
dtype=torch.bfloat16,
).eval()
processor = ColQwen2Processor.from_pretrained("Sahil-Kabir/colqwen2.5-v0.2-hf", trust_remote_code=True)
# Load the test dataset
ds = load_dataset("hf-internal-testing/document-visual-retrieval-test", split="test")
# Preprocess the examples
batch_images = processor(images=list(ds["image"])).to(torch_device)
batch_queries = processor(text=list(ds["query"])).to(torch_device)
with torch.inference_mode():
image_embeddings = model(**batch_images).embeddings
query_embeddings = model(**batch_queries).embeddings
# Compute retrieval scores
scores = processor.score_retrieval(
query_embeddings=query_embeddings,
passage_embeddings=image_embeddings,
)
assert scores.ndim == 2, f"Expected 2D tensor, got {scores.ndim}"
assert scores.shape == (len(ds), len(ds)), f"Expected shape {(len(ds), len(ds))}, got {scores.shape}"
# Check if the maximum scores per row are in the diagonal of the matrix score
self.assertTrue((scores.argmax(axis=1) == torch.arange(len(ds), device=scores.device)).all())
# Further validation: fine-grained check, with a hardcoded score from the original Hf implementation.
expectations = Expectations(
{
("cuda", 8): [
[16.3750, 10.9375, 14.7500],
[11.3750, 16.8750, 12.0625],
[15.3125, 13.1250, 21.5000],
]
}
)
expected_scores = torch.tensor(expectations.get_expectation(), dtype=scores.dtype)
assert torch.allclose(scores, expected_scores, atol=0.15), f"Expected scores {expected_scores}, got {scores}"
| ColQwen2ModelIntegrationTest |
python | getsentry__sentry | src/sentry/api/endpoints/rule_snooze.py | {
"start": 10357,
"end": 12387
} | class ____(BaseRuleSnoozeEndpoint[AlertRule]):
owner = ApiOwner.ISSUES
publish_status = {
"DELETE": ApiPublishStatus.PRIVATE,
"POST": ApiPublishStatus.PRIVATE,
}
rule_field = "alert_rule"
@track_alert_endpoint_execution("POST", "sentry-api-0-metric-rule-snooze")
def post(self, request: Request, project: Project, rule: AlertRule) -> Response:
# Mark that we're using legacy AlertRule models
report_used_legacy_models()
return super().post(request, project, rule)
@track_alert_endpoint_execution("DELETE", "sentry-api-0-metric-rule-snooze")
def delete(self, request: Request, project: Project, rule: AlertRule) -> Response:
# Mark that we're using legacy AlertRule models
report_used_legacy_models()
return super().delete(request, project, rule)
def fetch_rule_list(self, project: Project) -> BaseQuerySet[AlertRule]:
queryset = AlertRule.objects.fetch_for_project(project=project)
return queryset
def fetch_instance(self, rule: AlertRule, user_id: int | None, **kwargs: Any) -> RuleSnooze:
rule_snooze = RuleSnooze.objects.get(user_id=user_id, alert_rule=rule, **kwargs)
return rule_snooze
def create_instance(self, rule: AlertRule, user_id: int | None, **kwargs: Any) -> RuleSnooze:
with transaction.atomic(router.db_for_write(RuleSnooze)):
rule_snooze = RuleSnooze.objects.create(user_id=user_id, alert_rule=rule, **kwargs)
_update_workflow_engine_models(rule_snooze, is_enabled=False)
return rule_snooze
def record_audit_log_entry(
self, request: Request, organization: Organization, rule: AlertRule, **kwargs: Any
) -> None:
self.create_audit_entry(
request=request,
organization=organization,
target_object=rule.id,
event=audit_log.get_event_id("ALERT_RULE_SNOOZE"),
data=rule.get_audit_log_data(),
**kwargs,
)
| MetricRuleSnoozeEndpoint |
python | django__django | tests/defer_regress/models.py | {
"start": 2493,
"end": 2550
} | class ____(Base):
other_text = models.TextField()
| Derived |
python | pandas-dev__pandas | pandas/tests/arrays/categorical/test_repr.py | {
"start": 681,
"end": 27255
} | class ____:
def test_big_print(self):
codes = np.array([0, 1, 2, 0, 1, 2] * 100)
dtype = CategoricalDtype(categories=Index(["a", "b", "c"], dtype=object))
factor = Categorical.from_codes(codes, dtype=dtype)
expected = [
"['a', 'b', 'c', 'a', 'b', ..., 'b', 'c', 'a', 'b', 'c']",
"Length: 600",
"Categories (3, object): ['a', 'b', 'c']",
]
expected = "\n".join(expected)
actual = repr(factor)
assert actual == expected
def test_empty_print(self):
factor = Categorical([], Index(["a", "b", "c"], dtype=object))
expected = "[], Categories (3, object): ['a', 'b', 'c']"
actual = repr(factor)
assert actual == expected
assert expected == actual
factor = Categorical([], Index(["a", "b", "c"], dtype=object), ordered=True)
expected = "[], Categories (3, object): ['a' < 'b' < 'c']"
actual = repr(factor)
assert expected == actual
factor = Categorical([], [])
expected = "[], Categories (0, object): []"
assert expected == repr(factor)
def test_print_none_width(self):
# GH10087
a = Series(Categorical([1, 2, 3, 4]))
exp = (
"0 1\n1 2\n2 3\n3 4\n"
"dtype: category\nCategories (4, int64): [1, 2, 3, 4]"
)
with option_context("display.width", None):
assert exp == repr(a)
def test_unicode_print(self, using_infer_string):
c = Categorical(["aaaaa", "bb", "cccc"] * 20)
expected = """\
['aaaaa', 'bb', 'cccc', 'aaaaa', 'bb', ..., 'bb', 'cccc', 'aaaaa', 'bb', 'cccc']
Length: 60
Categories (3, object): ['aaaaa', 'bb', 'cccc']"""
if using_infer_string:
expected = expected.replace("object", "str")
assert repr(c) == expected
c = Categorical(["ああああ", "いいいいい", "ううううううう"] * 20)
expected = """\
['ああああ', 'いいいいい', 'ううううううう', 'ああああ', 'いいいいい', ..., 'いいいいい', 'ううううううう', 'ああああ', 'いいいいい', 'ううううううう']
Length: 60
Categories (3, object): ['ああああ', 'いいいいい', 'ううううううう']""" # noqa: E501
if using_infer_string:
expected = expected.replace("object", "str")
assert repr(c) == expected
# unicode option should not affect to Categorical, as it doesn't care
# the repr width
with option_context("display.unicode.east_asian_width", True):
c = Categorical(["ああああ", "いいいいい", "ううううううう"] * 20)
expected = """['ああああ', 'いいいいい', 'ううううううう', 'ああああ', 'いいいいい', ..., 'いいいいい', 'ううううううう', 'ああああ', 'いいいいい', 'ううううううう']
Length: 60
Categories (3, object): ['ああああ', 'いいいいい', 'ううううううう']""" # noqa: E501
if using_infer_string:
expected = expected.replace("object", "str")
assert repr(c) == expected
def test_categorical_repr(self):
c = Categorical([1, 2, 3])
exp = """[1, 2, 3]
Categories (3, int64): [1, 2, 3]"""
assert repr(c) == exp
c = Categorical([1, 2, 3, 1, 2, 3], categories=[1, 2, 3])
exp = """[1, 2, 3, 1, 2, 3]
Categories (3, int64): [1, 2, 3]"""
assert repr(c) == exp
c = Categorical([1, 2, 3, 4, 5] * 10)
exp = """[1, 2, 3, 4, 5, ..., 1, 2, 3, 4, 5]
Length: 50
Categories (5, int64): [1, 2, 3, 4, 5]"""
assert repr(c) == exp
c = Categorical(np.arange(20, dtype=np.int64))
exp = """[0, 1, 2, 3, 4, ..., 15, 16, 17, 18, 19]
Length: 20
Categories (20, int64): [0, 1, 2, 3, ..., 16, 17, 18, 19]"""
assert repr(c) == exp
def test_categorical_repr_ordered(self):
c = Categorical([1, 2, 3], ordered=True)
exp = """[1, 2, 3]
Categories (3, int64): [1 < 2 < 3]"""
assert repr(c) == exp
c = Categorical([1, 2, 3, 1, 2, 3], categories=[1, 2, 3], ordered=True)
exp = """[1, 2, 3, 1, 2, 3]
Categories (3, int64): [1 < 2 < 3]"""
assert repr(c) == exp
c = Categorical([1, 2, 3, 4, 5] * 10, ordered=True)
exp = """[1, 2, 3, 4, 5, ..., 1, 2, 3, 4, 5]
Length: 50
Categories (5, int64): [1 < 2 < 3 < 4 < 5]"""
assert repr(c) == exp
c = Categorical(np.arange(20, dtype=np.int64), ordered=True)
exp = """[0, 1, 2, 3, 4, ..., 15, 16, 17, 18, 19]
Length: 20
Categories (20, int64): [0 < 1 < 2 < 3 ... 16 < 17 < 18 < 19]"""
assert repr(c) == exp
def test_categorical_repr_datetime(self):
idx = date_range("2011-01-01 09:00", freq="h", periods=5, unit="ns")
c = Categorical(idx)
exp = (
"[2011-01-01 09:00:00, 2011-01-01 10:00:00, 2011-01-01 11:00:00, "
"2011-01-01 12:00:00, 2011-01-01 13:00:00]\n"
"Categories (5, datetime64[ns]): [2011-01-01 09:00:00, "
"2011-01-01 10:00:00, 2011-01-01 11:00:00,\n"
" 2011-01-01 12:00:00, "
"2011-01-01 13:00:00]"
""
)
assert repr(c) == exp
c = Categorical(idx.append(idx), categories=idx)
exp = (
"[2011-01-01 09:00:00, 2011-01-01 10:00:00, 2011-01-01 11:00:00, "
"2011-01-01 12:00:00, 2011-01-01 13:00:00, 2011-01-01 09:00:00, "
"2011-01-01 10:00:00, 2011-01-01 11:00:00, 2011-01-01 12:00:00, "
"2011-01-01 13:00:00]\n"
"Categories (5, datetime64[ns]): [2011-01-01 09:00:00, "
"2011-01-01 10:00:00, 2011-01-01 11:00:00,\n"
" 2011-01-01 12:00:00, "
"2011-01-01 13:00:00]"
)
assert repr(c) == exp
idx = date_range(
"2011-01-01 09:00", freq="h", periods=5, tz="US/Eastern", unit="ns"
)
c = Categorical(idx)
exp = (
"[2011-01-01 09:00:00-05:00, 2011-01-01 10:00:00-05:00, "
"2011-01-01 11:00:00-05:00, 2011-01-01 12:00:00-05:00, "
"2011-01-01 13:00:00-05:00]\n"
"Categories (5, datetime64[ns, US/Eastern]): "
"[2011-01-01 09:00:00-05:00, 2011-01-01 10:00:00-05:00,\n"
" "
"2011-01-01 11:00:00-05:00, 2011-01-01 12:00:00-05:00,\n"
" "
"2011-01-01 13:00:00-05:00]"
)
assert repr(c) == exp
c = Categorical(idx.append(idx), categories=idx)
exp = (
"[2011-01-01 09:00:00-05:00, 2011-01-01 10:00:00-05:00, "
"2011-01-01 11:00:00-05:00, 2011-01-01 12:00:00-05:00, "
"2011-01-01 13:00:00-05:00, 2011-01-01 09:00:00-05:00, "
"2011-01-01 10:00:00-05:00, 2011-01-01 11:00:00-05:00, "
"2011-01-01 12:00:00-05:00, 2011-01-01 13:00:00-05:00]\n"
"Categories (5, datetime64[ns, US/Eastern]): "
"[2011-01-01 09:00:00-05:00, 2011-01-01 10:00:00-05:00,\n"
" "
"2011-01-01 11:00:00-05:00, 2011-01-01 12:00:00-05:00,\n"
" "
"2011-01-01 13:00:00-05:00]"
)
assert repr(c) == exp
def test_categorical_repr_datetime_ordered(self):
idx = date_range("2011-01-01 09:00", freq="h", periods=5, unit="ns")
c = Categorical(idx, ordered=True)
exp = """[2011-01-01 09:00:00, 2011-01-01 10:00:00, 2011-01-01 11:00:00, 2011-01-01 12:00:00, 2011-01-01 13:00:00]
Categories (5, datetime64[ns]): [2011-01-01 09:00:00 < 2011-01-01 10:00:00 < 2011-01-01 11:00:00 <
2011-01-01 12:00:00 < 2011-01-01 13:00:00]""" # noqa: E501
assert repr(c) == exp
c = Categorical(idx.append(idx), categories=idx, ordered=True)
exp = """[2011-01-01 09:00:00, 2011-01-01 10:00:00, 2011-01-01 11:00:00, 2011-01-01 12:00:00, 2011-01-01 13:00:00, 2011-01-01 09:00:00, 2011-01-01 10:00:00, 2011-01-01 11:00:00, 2011-01-01 12:00:00, 2011-01-01 13:00:00]
Categories (5, datetime64[ns]): [2011-01-01 09:00:00 < 2011-01-01 10:00:00 < 2011-01-01 11:00:00 <
2011-01-01 12:00:00 < 2011-01-01 13:00:00]""" # noqa: E501
assert repr(c) == exp
idx = date_range(
"2011-01-01 09:00", freq="h", periods=5, tz="US/Eastern", unit="ns"
)
c = Categorical(idx, ordered=True)
exp = """[2011-01-01 09:00:00-05:00, 2011-01-01 10:00:00-05:00, 2011-01-01 11:00:00-05:00, 2011-01-01 12:00:00-05:00, 2011-01-01 13:00:00-05:00]
Categories (5, datetime64[ns, US/Eastern]): [2011-01-01 09:00:00-05:00 < 2011-01-01 10:00:00-05:00 <
2011-01-01 11:00:00-05:00 < 2011-01-01 12:00:00-05:00 <
2011-01-01 13:00:00-05:00]""" # noqa: E501
assert repr(c) == exp
c = Categorical(idx.append(idx), categories=idx, ordered=True)
exp = """[2011-01-01 09:00:00-05:00, 2011-01-01 10:00:00-05:00, 2011-01-01 11:00:00-05:00, 2011-01-01 12:00:00-05:00, 2011-01-01 13:00:00-05:00, 2011-01-01 09:00:00-05:00, 2011-01-01 10:00:00-05:00, 2011-01-01 11:00:00-05:00, 2011-01-01 12:00:00-05:00, 2011-01-01 13:00:00-05:00]
Categories (5, datetime64[ns, US/Eastern]): [2011-01-01 09:00:00-05:00 < 2011-01-01 10:00:00-05:00 <
2011-01-01 11:00:00-05:00 < 2011-01-01 12:00:00-05:00 <
2011-01-01 13:00:00-05:00]""" # noqa: E501
assert repr(c) == exp
def test_categorical_repr_int_with_nan(self):
c = Categorical([1, 2, np.nan])
c_exp = """[1, 2, NaN]\nCategories (2, int64): [1, 2]"""
assert repr(c) == c_exp
s = Series([1, 2, np.nan], dtype="object").astype("category")
s_exp = """0 1\n1 2\n2 NaN
dtype: category
Categories (2, int64): [1, 2]"""
assert repr(s) == s_exp
def test_categorical_repr_period(self):
idx = period_range("2011-01-01 09:00", freq="h", periods=5)
c = Categorical(idx)
exp = """[2011-01-01 09:00, 2011-01-01 10:00, 2011-01-01 11:00, 2011-01-01 12:00, 2011-01-01 13:00]
Categories (5, period[h]): [2011-01-01 09:00, 2011-01-01 10:00, 2011-01-01 11:00, 2011-01-01 12:00,
2011-01-01 13:00]""" # noqa: E501
assert repr(c) == exp
c = Categorical(idx.append(idx), categories=idx)
exp = """[2011-01-01 09:00, 2011-01-01 10:00, 2011-01-01 11:00, 2011-01-01 12:00, 2011-01-01 13:00, 2011-01-01 09:00, 2011-01-01 10:00, 2011-01-01 11:00, 2011-01-01 12:00, 2011-01-01 13:00]
Categories (5, period[h]): [2011-01-01 09:00, 2011-01-01 10:00, 2011-01-01 11:00, 2011-01-01 12:00,
2011-01-01 13:00]""" # noqa: E501
assert repr(c) == exp
idx = period_range("2011-01", freq="M", periods=5)
c = Categorical(idx)
exp = """[2011-01, 2011-02, 2011-03, 2011-04, 2011-05]
Categories (5, period[M]): [2011-01, 2011-02, 2011-03, 2011-04, 2011-05]"""
assert repr(c) == exp
c = Categorical(idx.append(idx), categories=idx)
exp = """[2011-01, 2011-02, 2011-03, 2011-04, 2011-05, 2011-01, 2011-02, 2011-03, 2011-04, 2011-05]
Categories (5, period[M]): [2011-01, 2011-02, 2011-03, 2011-04, 2011-05]""" # noqa: E501
assert repr(c) == exp
def test_categorical_repr_period_ordered(self):
idx = period_range("2011-01-01 09:00", freq="h", periods=5)
c = Categorical(idx, ordered=True)
exp = """[2011-01-01 09:00, 2011-01-01 10:00, 2011-01-01 11:00, 2011-01-01 12:00, 2011-01-01 13:00]
Categories (5, period[h]): [2011-01-01 09:00 < 2011-01-01 10:00 < 2011-01-01 11:00 < 2011-01-01 12:00 <
2011-01-01 13:00]""" # noqa: E501
assert repr(c) == exp
c = Categorical(idx.append(idx), categories=idx, ordered=True)
exp = """[2011-01-01 09:00, 2011-01-01 10:00, 2011-01-01 11:00, 2011-01-01 12:00, 2011-01-01 13:00, 2011-01-01 09:00, 2011-01-01 10:00, 2011-01-01 11:00, 2011-01-01 12:00, 2011-01-01 13:00]
Categories (5, period[h]): [2011-01-01 09:00 < 2011-01-01 10:00 < 2011-01-01 11:00 < 2011-01-01 12:00 <
2011-01-01 13:00]""" # noqa: E501
assert repr(c) == exp
idx = period_range("2011-01", freq="M", periods=5)
c = Categorical(idx, ordered=True)
exp = """[2011-01, 2011-02, 2011-03, 2011-04, 2011-05]
Categories (5, period[M]): [2011-01 < 2011-02 < 2011-03 < 2011-04 < 2011-05]"""
assert repr(c) == exp
c = Categorical(idx.append(idx), categories=idx, ordered=True)
exp = """[2011-01, 2011-02, 2011-03, 2011-04, 2011-05, 2011-01, 2011-02, 2011-03, 2011-04, 2011-05]
Categories (5, period[M]): [2011-01 < 2011-02 < 2011-03 < 2011-04 < 2011-05]""" # noqa: E501
assert repr(c) == exp
def test_categorical_repr_timedelta(self):
idx = timedelta_range("1 days", periods=5)
c = Categorical(idx)
exp = """[1 days, 2 days, 3 days, 4 days, 5 days]
Categories (5, timedelta64[ns]): [1 days, 2 days, 3 days, 4 days, 5 days]"""
assert repr(c) == exp
c = Categorical(idx.append(idx), categories=idx)
exp = """[1 days, 2 days, 3 days, 4 days, 5 days, 1 days, 2 days, 3 days, 4 days, 5 days]
Categories (5, timedelta64[ns]): [1 days, 2 days, 3 days, 4 days, 5 days]""" # noqa: E501
assert repr(c) == exp
idx = timedelta_range("1 hours", periods=20)
c = Categorical(idx)
exp = """[0 days 01:00:00, 1 days 01:00:00, 2 days 01:00:00, 3 days 01:00:00, 4 days 01:00:00, ..., 15 days 01:00:00, 16 days 01:00:00, 17 days 01:00:00, 18 days 01:00:00, 19 days 01:00:00]
Length: 20
Categories (20, timedelta64[ns]): [0 days 01:00:00, 1 days 01:00:00, 2 days 01:00:00,
3 days 01:00:00, ..., 16 days 01:00:00, 17 days 01:00:00,
18 days 01:00:00, 19 days 01:00:00]""" # noqa: E501
assert repr(c) == exp
c = Categorical(idx.append(idx), categories=idx)
exp = """[0 days 01:00:00, 1 days 01:00:00, 2 days 01:00:00, 3 days 01:00:00, 4 days 01:00:00, ..., 15 days 01:00:00, 16 days 01:00:00, 17 days 01:00:00, 18 days 01:00:00, 19 days 01:00:00]
Length: 40
Categories (20, timedelta64[ns]): [0 days 01:00:00, 1 days 01:00:00, 2 days 01:00:00,
3 days 01:00:00, ..., 16 days 01:00:00, 17 days 01:00:00,
18 days 01:00:00, 19 days 01:00:00]""" # noqa: E501
assert repr(c) == exp
def test_categorical_repr_timedelta_ordered(self):
idx = timedelta_range("1 days", periods=5)
c = Categorical(idx, ordered=True)
exp = """[1 days, 2 days, 3 days, 4 days, 5 days]
Categories (5, timedelta64[ns]): [1 days < 2 days < 3 days < 4 days < 5 days]"""
assert repr(c) == exp
c = Categorical(idx.append(idx), categories=idx, ordered=True)
exp = """[1 days, 2 days, 3 days, 4 days, 5 days, 1 days, 2 days, 3 days, 4 days, 5 days]
Categories (5, timedelta64[ns]): [1 days < 2 days < 3 days < 4 days < 5 days]""" # noqa: E501
assert repr(c) == exp
idx = timedelta_range("1 hours", periods=20)
c = Categorical(idx, ordered=True)
exp = """[0 days 01:00:00, 1 days 01:00:00, 2 days 01:00:00, 3 days 01:00:00, 4 days 01:00:00, ..., 15 days 01:00:00, 16 days 01:00:00, 17 days 01:00:00, 18 days 01:00:00, 19 days 01:00:00]
Length: 20
Categories (20, timedelta64[ns]): [0 days 01:00:00 < 1 days 01:00:00 < 2 days 01:00:00 <
3 days 01:00:00 ... 16 days 01:00:00 < 17 days 01:00:00 <
18 days 01:00:00 < 19 days 01:00:00]""" # noqa: E501
assert repr(c) == exp
c = Categorical(idx.append(idx), categories=idx, ordered=True)
exp = """[0 days 01:00:00, 1 days 01:00:00, 2 days 01:00:00, 3 days 01:00:00, 4 days 01:00:00, ..., 15 days 01:00:00, 16 days 01:00:00, 17 days 01:00:00, 18 days 01:00:00, 19 days 01:00:00]
Length: 40
Categories (20, timedelta64[ns]): [0 days 01:00:00 < 1 days 01:00:00 < 2 days 01:00:00 <
3 days 01:00:00 ... 16 days 01:00:00 < 17 days 01:00:00 <
18 days 01:00:00 < 19 days 01:00:00]""" # noqa: E501
assert repr(c) == exp
def test_categorical_index_repr(self):
idx = CategoricalIndex(Categorical([1, 2, 3]))
exp = """CategoricalIndex([1, 2, 3], categories=[1, 2, 3], ordered=False, dtype='category')""" # noqa: E501
assert repr(idx) == exp
i = CategoricalIndex(Categorical(np.arange(10, dtype=np.int64)))
exp = """CategoricalIndex([0, 1, 2, 3, 4, 5, 6, 7, 8, 9], categories=[0, 1, 2, 3, ..., 6, 7, 8, 9], ordered=False, dtype='category')""" # noqa: E501
assert repr(i) == exp
def test_categorical_index_repr_ordered(self):
i = CategoricalIndex(Categorical([1, 2, 3], ordered=True))
exp = """CategoricalIndex([1, 2, 3], categories=[1, 2, 3], ordered=True, dtype='category')""" # noqa: E501
assert repr(i) == exp
i = CategoricalIndex(Categorical(np.arange(10, dtype=np.int64), ordered=True))
exp = """CategoricalIndex([0, 1, 2, 3, 4, 5, 6, 7, 8, 9], categories=[0, 1, 2, 3, ..., 6, 7, 8, 9], ordered=True, dtype='category')""" # noqa: E501
assert repr(i) == exp
def test_categorical_index_repr_datetime(self):
idx = date_range("2011-01-01 09:00", freq="h", periods=5)
i = CategoricalIndex(Categorical(idx))
exp = """CategoricalIndex(['2011-01-01 09:00:00', '2011-01-01 10:00:00',
'2011-01-01 11:00:00', '2011-01-01 12:00:00',
'2011-01-01 13:00:00'],
categories=[2011-01-01 09:00:00, 2011-01-01 10:00:00, 2011-01-01 11:00:00, 2011-01-01 12:00:00, 2011-01-01 13:00:00], ordered=False, dtype='category')""" # noqa: E501
assert repr(i) == exp
idx = date_range("2011-01-01 09:00", freq="h", periods=5, tz="US/Eastern")
i = CategoricalIndex(Categorical(idx))
exp = """CategoricalIndex(['2011-01-01 09:00:00-05:00', '2011-01-01 10:00:00-05:00',
'2011-01-01 11:00:00-05:00', '2011-01-01 12:00:00-05:00',
'2011-01-01 13:00:00-05:00'],
categories=[2011-01-01 09:00:00-05:00, 2011-01-01 10:00:00-05:00, 2011-01-01 11:00:00-05:00, 2011-01-01 12:00:00-05:00, 2011-01-01 13:00:00-05:00], ordered=False, dtype='category')""" # noqa: E501
assert repr(i) == exp
def test_categorical_index_repr_datetime_ordered(self):
idx = date_range("2011-01-01 09:00", freq="h", periods=5)
i = CategoricalIndex(Categorical(idx, ordered=True))
exp = """CategoricalIndex(['2011-01-01 09:00:00', '2011-01-01 10:00:00',
'2011-01-01 11:00:00', '2011-01-01 12:00:00',
'2011-01-01 13:00:00'],
categories=[2011-01-01 09:00:00, 2011-01-01 10:00:00, 2011-01-01 11:00:00, 2011-01-01 12:00:00, 2011-01-01 13:00:00], ordered=True, dtype='category')""" # noqa: E501
assert repr(i) == exp
idx = date_range("2011-01-01 09:00", freq="h", periods=5, tz="US/Eastern")
i = CategoricalIndex(Categorical(idx, ordered=True))
exp = """CategoricalIndex(['2011-01-01 09:00:00-05:00', '2011-01-01 10:00:00-05:00',
'2011-01-01 11:00:00-05:00', '2011-01-01 12:00:00-05:00',
'2011-01-01 13:00:00-05:00'],
categories=[2011-01-01 09:00:00-05:00, 2011-01-01 10:00:00-05:00, 2011-01-01 11:00:00-05:00, 2011-01-01 12:00:00-05:00, 2011-01-01 13:00:00-05:00], ordered=True, dtype='category')""" # noqa: E501
assert repr(i) == exp
i = CategoricalIndex(Categorical(idx.append(idx), ordered=True))
exp = """CategoricalIndex(['2011-01-01 09:00:00-05:00', '2011-01-01 10:00:00-05:00',
'2011-01-01 11:00:00-05:00', '2011-01-01 12:00:00-05:00',
'2011-01-01 13:00:00-05:00', '2011-01-01 09:00:00-05:00',
'2011-01-01 10:00:00-05:00', '2011-01-01 11:00:00-05:00',
'2011-01-01 12:00:00-05:00', '2011-01-01 13:00:00-05:00'],
categories=[2011-01-01 09:00:00-05:00, 2011-01-01 10:00:00-05:00, 2011-01-01 11:00:00-05:00, 2011-01-01 12:00:00-05:00, 2011-01-01 13:00:00-05:00], ordered=True, dtype='category')""" # noqa: E501
assert repr(i) == exp
def test_categorical_index_repr_period(self):
# test all length
idx = period_range("2011-01-01 09:00", freq="h", periods=1)
i = CategoricalIndex(Categorical(idx))
exp = """CategoricalIndex(['2011-01-01 09:00'], categories=[2011-01-01 09:00], ordered=False, dtype='category')""" # noqa: E501
assert repr(i) == exp
idx = period_range("2011-01-01 09:00", freq="h", periods=2)
i = CategoricalIndex(Categorical(idx))
exp = """CategoricalIndex(['2011-01-01 09:00', '2011-01-01 10:00'], categories=[2011-01-01 09:00, 2011-01-01 10:00], ordered=False, dtype='category')""" # noqa: E501
assert repr(i) == exp
idx = period_range("2011-01-01 09:00", freq="h", periods=3)
i = CategoricalIndex(Categorical(idx))
exp = """CategoricalIndex(['2011-01-01 09:00', '2011-01-01 10:00', '2011-01-01 11:00'], categories=[2011-01-01 09:00, 2011-01-01 10:00, 2011-01-01 11:00], ordered=False, dtype='category')""" # noqa: E501
assert repr(i) == exp
idx = period_range("2011-01-01 09:00", freq="h", periods=5)
i = CategoricalIndex(Categorical(idx))
exp = """CategoricalIndex(['2011-01-01 09:00', '2011-01-01 10:00', '2011-01-01 11:00',
'2011-01-01 12:00', '2011-01-01 13:00'],
categories=[2011-01-01 09:00, 2011-01-01 10:00, 2011-01-01 11:00, 2011-01-01 12:00, 2011-01-01 13:00], ordered=False, dtype='category')""" # noqa: E501
assert repr(i) == exp
i = CategoricalIndex(Categorical(idx.append(idx)))
exp = """CategoricalIndex(['2011-01-01 09:00', '2011-01-01 10:00', '2011-01-01 11:00',
'2011-01-01 12:00', '2011-01-01 13:00', '2011-01-01 09:00',
'2011-01-01 10:00', '2011-01-01 11:00', '2011-01-01 12:00',
'2011-01-01 13:00'],
categories=[2011-01-01 09:00, 2011-01-01 10:00, 2011-01-01 11:00, 2011-01-01 12:00, 2011-01-01 13:00], ordered=False, dtype='category')""" # noqa: E501
assert repr(i) == exp
idx = period_range("2011-01", freq="M", periods=5)
i = CategoricalIndex(Categorical(idx))
exp = """CategoricalIndex(['2011-01', '2011-02', '2011-03', '2011-04', '2011-05'], categories=[2011-01, 2011-02, 2011-03, 2011-04, 2011-05], ordered=False, dtype='category')""" # noqa: E501
assert repr(i) == exp
def test_categorical_index_repr_period_ordered(self):
idx = period_range("2011-01-01 09:00", freq="h", periods=5)
i = CategoricalIndex(Categorical(idx, ordered=True))
exp = """CategoricalIndex(['2011-01-01 09:00', '2011-01-01 10:00', '2011-01-01 11:00',
'2011-01-01 12:00', '2011-01-01 13:00'],
categories=[2011-01-01 09:00, 2011-01-01 10:00, 2011-01-01 11:00, 2011-01-01 12:00, 2011-01-01 13:00], ordered=True, dtype='category')""" # noqa: E501
assert repr(i) == exp
idx = period_range("2011-01", freq="M", periods=5)
i = CategoricalIndex(Categorical(idx, ordered=True))
exp = """CategoricalIndex(['2011-01', '2011-02', '2011-03', '2011-04', '2011-05'], categories=[2011-01, 2011-02, 2011-03, 2011-04, 2011-05], ordered=True, dtype='category')""" # noqa: E501
assert repr(i) == exp
def test_categorical_index_repr_timedelta(self):
idx = timedelta_range("1 days", periods=5)
i = CategoricalIndex(Categorical(idx))
exp = """CategoricalIndex(['1 days', '2 days', '3 days', '4 days', '5 days'], categories=[1 days, 2 days, 3 days, 4 days, 5 days], ordered=False, dtype='category')""" # noqa: E501
assert repr(i) == exp
idx = timedelta_range("1 hours", periods=10)
i = CategoricalIndex(Categorical(idx))
exp = """CategoricalIndex(['0 days 01:00:00', '1 days 01:00:00', '2 days 01:00:00',
'3 days 01:00:00', '4 days 01:00:00', '5 days 01:00:00',
'6 days 01:00:00', '7 days 01:00:00', '8 days 01:00:00',
'9 days 01:00:00'],
categories=[0 days 01:00:00, 1 days 01:00:00, 2 days 01:00:00, 3 days 01:00:00, ..., 6 days 01:00:00, 7 days 01:00:00, 8 days 01:00:00, 9 days 01:00:00], ordered=False, dtype='category')""" # noqa: E501
assert repr(i) == exp
def test_categorical_index_repr_timedelta_ordered(self):
idx = timedelta_range("1 days", periods=5)
i = CategoricalIndex(Categorical(idx, ordered=True))
exp = """CategoricalIndex(['1 days', '2 days', '3 days', '4 days', '5 days'], categories=[1 days, 2 days, 3 days, 4 days, 5 days], ordered=True, dtype='category')""" # noqa: E501
assert repr(i) == exp
idx = timedelta_range("1 hours", periods=10)
i = CategoricalIndex(Categorical(idx, ordered=True))
exp = """CategoricalIndex(['0 days 01:00:00', '1 days 01:00:00', '2 days 01:00:00',
'3 days 01:00:00', '4 days 01:00:00', '5 days 01:00:00',
'6 days 01:00:00', '7 days 01:00:00', '8 days 01:00:00',
'9 days 01:00:00'],
categories=[0 days 01:00:00, 1 days 01:00:00, 2 days 01:00:00, 3 days 01:00:00, ..., 6 days 01:00:00, 7 days 01:00:00, 8 days 01:00:00, 9 days 01:00:00], ordered=True, dtype='category')""" # noqa: E501
assert repr(i) == exp
def test_categorical_str_repr(self):
# GH 33676
result = repr(Categorical([1, "2", 3, 4]))
expected = "[1, '2', 3, 4]\nCategories (4, object): [1, 3, 4, '2']"
assert result == expected
def test_categorical_with_string_dtype(self, string_dtype_no_object):
# GH 63045 - ensure categories are quoted for string dtypes
s = Series(
["apple", "banana", "cherry", "cherry"], dtype=string_dtype_no_object
)
result = repr(Categorical(s))
expected = f"['apple', 'banana', 'cherry', 'cherry']\nCategories (3, {string_dtype_no_object!s}): ['apple', 'banana', 'cherry']" # noqa: E501
assert result == expected
| TestCategoricalRepr |
python | kubernetes-client__python | kubernetes/client/models/v1_csi_volume_source.py | {
"start": 383,
"end": 8057
} | class ____(object):
"""NOTE: This class is auto generated by OpenAPI Generator.
Ref: https://openapi-generator.tech
Do not edit the class manually.
"""
"""
Attributes:
openapi_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The key is attribute name
and the value is json key in definition.
"""
openapi_types = {
'driver': 'str',
'fs_type': 'str',
'node_publish_secret_ref': 'V1LocalObjectReference',
'read_only': 'bool',
'volume_attributes': 'dict(str, str)'
}
attribute_map = {
'driver': 'driver',
'fs_type': 'fsType',
'node_publish_secret_ref': 'nodePublishSecretRef',
'read_only': 'readOnly',
'volume_attributes': 'volumeAttributes'
}
def __init__(self, driver=None, fs_type=None, node_publish_secret_ref=None, read_only=None, volume_attributes=None, local_vars_configuration=None): # noqa: E501
"""V1CSIVolumeSource - a model defined in OpenAPI""" # noqa: E501
if local_vars_configuration is None:
local_vars_configuration = Configuration()
self.local_vars_configuration = local_vars_configuration
self._driver = None
self._fs_type = None
self._node_publish_secret_ref = None
self._read_only = None
self._volume_attributes = None
self.discriminator = None
self.driver = driver
if fs_type is not None:
self.fs_type = fs_type
if node_publish_secret_ref is not None:
self.node_publish_secret_ref = node_publish_secret_ref
if read_only is not None:
self.read_only = read_only
if volume_attributes is not None:
self.volume_attributes = volume_attributes
@property
def driver(self):
"""Gets the driver of this V1CSIVolumeSource. # noqa: E501
driver is the name of the CSI driver that handles this volume. Consult with your admin for the correct name as registered in the cluster. # noqa: E501
:return: The driver of this V1CSIVolumeSource. # noqa: E501
:rtype: str
"""
return self._driver
@driver.setter
def driver(self, driver):
"""Sets the driver of this V1CSIVolumeSource.
driver is the name of the CSI driver that handles this volume. Consult with your admin for the correct name as registered in the cluster. # noqa: E501
:param driver: The driver of this V1CSIVolumeSource. # noqa: E501
:type: str
"""
if self.local_vars_configuration.client_side_validation and driver is None: # noqa: E501
raise ValueError("Invalid value for `driver`, must not be `None`") # noqa: E501
self._driver = driver
@property
def fs_type(self):
"""Gets the fs_type of this V1CSIVolumeSource. # noqa: E501
fsType to mount. Ex. \"ext4\", \"xfs\", \"ntfs\". If not provided, the empty value is passed to the associated CSI driver which will determine the default filesystem to apply. # noqa: E501
:return: The fs_type of this V1CSIVolumeSource. # noqa: E501
:rtype: str
"""
return self._fs_type
@fs_type.setter
def fs_type(self, fs_type):
"""Sets the fs_type of this V1CSIVolumeSource.
fsType to mount. Ex. \"ext4\", \"xfs\", \"ntfs\". If not provided, the empty value is passed to the associated CSI driver which will determine the default filesystem to apply. # noqa: E501
:param fs_type: The fs_type of this V1CSIVolumeSource. # noqa: E501
:type: str
"""
self._fs_type = fs_type
@property
def node_publish_secret_ref(self):
"""Gets the node_publish_secret_ref of this V1CSIVolumeSource. # noqa: E501
:return: The node_publish_secret_ref of this V1CSIVolumeSource. # noqa: E501
:rtype: V1LocalObjectReference
"""
return self._node_publish_secret_ref
@node_publish_secret_ref.setter
def node_publish_secret_ref(self, node_publish_secret_ref):
"""Sets the node_publish_secret_ref of this V1CSIVolumeSource.
:param node_publish_secret_ref: The node_publish_secret_ref of this V1CSIVolumeSource. # noqa: E501
:type: V1LocalObjectReference
"""
self._node_publish_secret_ref = node_publish_secret_ref
@property
def read_only(self):
"""Gets the read_only of this V1CSIVolumeSource. # noqa: E501
readOnly specifies a read-only configuration for the volume. Defaults to false (read/write). # noqa: E501
:return: The read_only of this V1CSIVolumeSource. # noqa: E501
:rtype: bool
"""
return self._read_only
@read_only.setter
def read_only(self, read_only):
"""Sets the read_only of this V1CSIVolumeSource.
readOnly specifies a read-only configuration for the volume. Defaults to false (read/write). # noqa: E501
:param read_only: The read_only of this V1CSIVolumeSource. # noqa: E501
:type: bool
"""
self._read_only = read_only
@property
def volume_attributes(self):
"""Gets the volume_attributes of this V1CSIVolumeSource. # noqa: E501
volumeAttributes stores driver-specific properties that are passed to the CSI driver. Consult your driver's documentation for supported values. # noqa: E501
:return: The volume_attributes of this V1CSIVolumeSource. # noqa: E501
:rtype: dict(str, str)
"""
return self._volume_attributes
@volume_attributes.setter
def volume_attributes(self, volume_attributes):
"""Sets the volume_attributes of this V1CSIVolumeSource.
volumeAttributes stores driver-specific properties that are passed to the CSI driver. Consult your driver's documentation for supported values. # noqa: E501
:param volume_attributes: The volume_attributes of this V1CSIVolumeSource. # noqa: E501
:type: dict(str, str)
"""
self._volume_attributes = volume_attributes
def to_dict(self):
"""Returns the model properties as a dict"""
result = {}
for attr, _ in six.iteritems(self.openapi_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value
))
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict") else item,
value.items()
))
else:
result[attr] = value
return result
def to_str(self):
"""Returns the string representation of the model"""
return pprint.pformat(self.to_dict())
def __repr__(self):
"""For `print` and `pprint`"""
return self.to_str()
def __eq__(self, other):
"""Returns true if both objects are equal"""
if not isinstance(other, V1CSIVolumeSource):
return False
return self.to_dict() == other.to_dict()
def __ne__(self, other):
"""Returns true if both objects are not equal"""
if not isinstance(other, V1CSIVolumeSource):
return True
return self.to_dict() != other.to_dict()
| V1CSIVolumeSource |
python | langchain-ai__langchain | libs/core/langchain_core/indexing/api.py | {
"start": 7651,
"end": 8994
} | class ____:
def __init__(self, *args: Any, **kwargs: Any) -> None:
"""Raise an error if this class is instantiated."""
msg = (
"_HashedDocument is an internal abstraction that was deprecated in "
" langchain-core 0.3.63. This abstraction is marked as private and "
" should not have been used directly. If you are seeing this error, please "
" update your code appropriately."
)
raise NotImplementedError(msg)
def _delete(
vector_store: VectorStore | DocumentIndex,
ids: list[str],
) -> None:
if isinstance(vector_store, VectorStore):
delete_ok = vector_store.delete(ids)
if delete_ok is not None and delete_ok is False:
msg = "The delete operation to VectorStore failed."
raise IndexingException(msg)
elif isinstance(vector_store, DocumentIndex):
delete_response = vector_store.delete(ids)
if "num_failed" in delete_response and delete_response["num_failed"] > 0:
msg = "The delete operation to DocumentIndex failed."
raise IndexingException(msg)
else:
msg = (
f"Vectorstore should be either a VectorStore or a DocumentIndex. "
f"Got {type(vector_store)}."
)
raise TypeError(msg)
# PUBLIC API
| _HashedDocument |
python | huggingface__transformers | src/transformers/models/perception_lm/modeling_perception_lm.py | {
"start": 4068,
"end": 5400
} | class ____(BaseModelOutputWithPast):
r"""
past_key_values (`Cache`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
It is a [`~cache_utils.Cache`] instance. For more details, see our [kv cache guide](https://huggingface.co/docs/transformers/en/kv_cache).
Contains pre-computed hidden-states (key and values in the self-attention blocks) that can be used (see
`past_key_values` input) to speed up sequential decoding.
image_hidden_states (`torch.FloatTensor`, *optional*):
A `torch.FloatTensor` of size `(batch_size, num_images, sequence_length, hidden_size)`.
Image hidden_states of the model produced by the vision encoder and after projecting the last hidden state.
video_hidden_states (`torch.FloatTensor`, *optional*):
A `torch.FloatTensor` of size `(batch_size, num_videos, sequence_length, hidden_size)`.
Video hidden_states of the model produced by the vision encoder and after projecting the last hidden state.
"""
image_hidden_states: Optional[torch.FloatTensor] = None
video_hidden_states: Optional[torch.FloatTensor] = None
@dataclass
@auto_docstring(
custom_intro="""
Base class for PerceptionLM causal language model (or autoregressive) outputs.
"""
)
| PerceptionLMModelOutputWithPast |
python | getsentry__sentry | src/sentry/uptime/migrations/0048_delete_uptime_status_columns.py | {
"start": 240,
"end": 1722
} | class ____(CheckedMigration):
# This flag is used to mark that a migration shouldn't be automatically run in production.
# This should only be used for operations where it's safe to run the migration after your
# code has deployed. So this should not be used for most operations that alter the schema
# of a table.
# Here are some things that make sense to mark as post deployment:
# - Large data migrations. Typically we want these to be run manually so that they can be
# monitored and not block the deploy for a long period of time while they run.
# - Adding indexes to large tables. Since this can take a long time, we'd generally prefer to
# run this outside deployments so that we don't block them. Note that while adding an index
# is a schema change, it's completely safe to run the operation after the code has deployed.
# Once deployed, run these manually via: https://develop.sentry.dev/database-migrations/#migration-deployment
is_post_deployment = False
dependencies = [
("uptime", "0047_remove_uptime_status_columns"),
]
operations = [
SafeRemoveField(
model_name="uptimesubscription",
name="uptime_status",
deletion_action=DeletionAction.DELETE,
),
SafeRemoveField(
model_name="uptimesubscription",
name="uptime_status_update_date",
deletion_action=DeletionAction.DELETE,
),
]
| Migration |
python | ray-project__ray | python/ray/air/execution/resources/placement_group.py | {
"start": 554,
"end": 1374
} | class ____(AcquiredResources):
placement_group: PlacementGroup
def _annotate_remote_entity(
self, entity: RemoteRayEntity, bundle: Dict[str, float], bundle_index: int
) -> RemoteRayEntity:
bundle = bundle.copy()
num_cpus = bundle.pop("CPU", 0)
num_gpus = bundle.pop("GPU", 0)
memory = bundle.pop("memory", 0.0)
return entity.options(
scheduling_strategy=PlacementGroupSchedulingStrategy(
placement_group=self.placement_group,
placement_group_bundle_index=bundle_index,
placement_group_capture_child_tasks=True,
),
num_cpus=num_cpus,
num_gpus=num_gpus,
memory=memory,
resources=bundle,
)
@DeveloperAPI
| PlacementGroupAcquiredResources |
python | kamyu104__LeetCode-Solutions | Python/roman-to-integer.py | {
"start": 29,
"end": 475
} | class ____(object):
# @return an integer
def romanToInt(self, s):
numeral_map = {"I": 1, "V": 5, "X": 10, "L": 50, "C":100, "D": 500, "M": 1000}
decimal = 0
for i in xrange(len(s)):
if i > 0 and numeral_map[s[i]] > numeral_map[s[i - 1]]:
decimal += numeral_map[s[i]] - 2 * numeral_map[s[i - 1]]
else:
decimal += numeral_map[s[i]]
return decimal
| Solution |
python | spack__spack | lib/spack/spack/spec.py | {
"start": 51954,
"end": 53800
} | class ____:
def __init__(self) -> None:
self.original_spec_format = SPECFILE_FORMAT_VERSION
self.compiler_node_attribute: Optional["Spec"] = None
def with_spec_format(self, spec_format: int) -> "SpecAnnotations":
self.original_spec_format = spec_format
return self
def with_compiler(self, compiler: "Spec") -> "SpecAnnotations":
self.compiler_node_attribute = compiler
return self
def __repr__(self) -> str:
result = f"SpecAnnotations().with_spec_format({self.original_spec_format})"
if self.compiler_node_attribute:
result += f".with_compiler({str(self.compiler_node_attribute)})"
return result
def _anonymous_star(dep: DependencySpec, dep_format: str) -> str:
"""Determine if a spec needs a star to disambiguate it from an anonymous spec w/variants.
Returns:
"*" if a star is needed, "" otherwise
"""
# named spec never needs star
if dep.spec.name:
return ""
# virtuals without a name always need *: %c=* @4.0 foo=bar
if dep.virtuals:
return "*"
# versions are first so checking for @ is faster than != VersionList(':')
if dep_format.startswith("@"):
return ""
# compiler flags are key-value pairs and can be ambiguous with virtual assignment
if dep.spec.compiler_flags:
return "*"
# booleans come first, and they don't need a star. key-value pairs do. If there are
# no key value pairs, we're left with either an empty spec, which needs * as in
# '^*', or we're left with arch, which is a key value pair, and needs a star.
if not any(v.type == vt.VariantType.BOOL for v in dep.spec.variants.values()):
return "*"
return "*" if dep.spec.architecture else ""
@lang.lazy_lexicographic_ordering(set_hash=False)
| SpecAnnotations |
python | tensorflow__tensorflow | tensorflow/compiler/mlir/tfr/python/test_utils.py | {
"start": 795,
"end": 1803
} | class ____(test.TestCase):
"""Test utils."""
def _assertOpAndComposite(self, vars_, compute_op, compute_composite, kwargs,
op_kwargs=None):
if op_kwargs is None:
op_kwargs = kwargs
if test_util.IsMklEnabled():
self.skipTest("Not compatible with oneDNN custom ops.")
# compute with op.
with backprop.GradientTape() as gt:
for var_ in vars_:
gt.watch(var_)
y = compute_op(**op_kwargs) # uses op and decomposites by the graph pass.
grads = gt.gradient(y, vars_) # uses registered gradient function.
# compute with composition
with backprop.GradientTape() as gt:
for var_ in vars_:
gt.watch(var_)
re_y = compute_composite(**kwargs) # uses composite function.
re_grads = gt.gradient(re_y, vars_) # uses gradients compposite function.
for v, re_v in zip(y, re_y):
self.assertAllClose(v, re_v)
for g, re_g in zip(grads, re_grads):
self.assertAllClose(g, re_g)
| OpsDefsTest |
python | PrefectHQ__prefect | src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py | {
"start": 263776,
"end": 264157
} | class ____(sgqlc.types.Type):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__field_names__ = ("cursor", "node")
cursor = sgqlc.types.Field(sgqlc.types.non_null(String), graphql_name="cursor")
node = sgqlc.types.Field(
"CreatedPullRequestReviewContribution", graphql_name="node"
)
| CreatedPullRequestReviewContributionEdge |
python | keras-team__keras | keras/src/ops/numpy.py | {
"start": 159520,
"end": 160298
} | class ____(Operation):
def call(self, x1, x2):
return backend.numpy.not_equal(x1, x2)
def compute_output_spec(self, x1, x2):
x1_shape = getattr(x1, "shape", [])
x2_shape = getattr(x2, "shape", [])
output_shape = broadcast_shapes(x1_shape, x2_shape)
return KerasTensor(output_shape, dtype="bool")
@keras_export(["keras.ops.not_equal", "keras.ops.numpy.not_equal"])
def not_equal(x1, x2):
"""Return `(x1 != x2)` element-wise.
Args:
x1: First input tensor.
x2: Second input tensor.
Returns:
Output tensor, element-wise comparison of `x1` and `x2`.
"""
if any_symbolic_tensors((x1, x2)):
return NotEqual().symbolic_call(x1, x2)
return backend.numpy.not_equal(x1, x2)
| NotEqual |
python | Lightning-AI__lightning | tests/tests_pytorch/checkpointing/test_model_checkpoint.py | {
"start": 43274,
"end": 43483
} | class ____(Callback):
def on_before_optimizer_step(self, trainer, pl_module, optimizer):
if trainer.current_epoch == 1:
raise RuntimeError("Trouble!")
| TroubleCallbackOnBeforeOptimizerStep |
python | realpython__materials | python-guitar-synthesizer/source_code_final/demo/play_diablo.py | {
"start": 1111,
"end": 1278
} | class ____:
SLOW = Time.from_milliseconds(40)
FAST = Time.from_milliseconds(20)
SUPER_FAST = Time.from_milliseconds(5)
@dataclass(frozen=True)
| StrummingSpeed |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/typeVar9.py | {
"start": 2486,
"end": 2664
} | class ____(Generic[_T]):
# This should generate an error because _T can go unsolved.
def __init__(self, x: _T = ...) -> None: ...
_T2 = TypeVar("_T2", default=int)
| ClassA |
python | pydata__xarray | xarray/computation/rolling.py | {
"start": 47202,
"end": 50059
} | class ____(Coarsen["Dataset"]):
__slots__ = ()
_reduce_extra_args_docstring = """"""
@classmethod
def _reduce_method(
cls, func: Callable, include_skipna: bool = False, numeric_only: bool = False
) -> Callable[..., Dataset]:
"""
Return a wrapped function for injecting reduction methods.
see ops.inject_reduce_methods
"""
kwargs: dict[str, Any] = {}
if include_skipna:
kwargs["skipna"] = None
def wrapped_func(
self: DatasetCoarsen, keep_attrs: bool | None = None, **kwargs
) -> Dataset:
from xarray.core.dataset import Dataset
keep_attrs = self._get_keep_attrs(keep_attrs)
if keep_attrs:
attrs = self.obj.attrs
else:
attrs = {}
reduced = {}
for key, da in self.obj.data_vars.items():
reduced[key] = da.variable.coarsen(
self.windows,
func,
self.boundary,
self.side,
keep_attrs=keep_attrs,
**kwargs,
)
coords = {}
for c, v in self.obj.coords.items():
# variable.coarsen returns variables not containing the window dims
# unchanged (maybe removes attrs)
coords[c] = v.variable.coarsen(
self.windows,
self.coord_func[c],
self.boundary,
self.side,
keep_attrs=keep_attrs,
**kwargs,
)
return Dataset(reduced, coords=coords, attrs=attrs)
return wrapped_func
def reduce(self, func: Callable, keep_attrs=None, **kwargs) -> Dataset:
"""Reduce the items in this group by applying `func` along some
dimension(s).
Parameters
----------
func : callable
Function which can be called in the form `func(x, axis, **kwargs)`
to return the result of collapsing an np.ndarray over the coarsening
dimensions. It must be possible to provide the `axis` argument with
a tuple of integers.
keep_attrs : bool, default: None
If True, the attributes (``attrs``) will be copied from the original
object to the new one. If False, the new object will be returned
without attributes. If None uses the global default.
**kwargs : dict
Additional keyword arguments passed on to `func`.
Returns
-------
reduced : Dataset
Arrays with summarized data.
"""
wrapped_func = self._reduce_method(func)
return wrapped_func(self, keep_attrs=keep_attrs, **kwargs)
| DatasetCoarsen |
python | huggingface__transformers | src/transformers/models/granite/modeling_granite.py | {
"start": 5423,
"end": 8640
} | class ____(nn.Module):
"""Multi-headed attention from 'Attention Is All You Need' paper"""
def __init__(self, config: GraniteConfig, layer_idx: Optional[int] = None):
super().__init__()
self.config = config
self.layer_idx = layer_idx
self.head_dim = getattr(config, "head_dim", config.hidden_size // config.num_attention_heads)
self.num_key_value_groups = config.num_attention_heads // config.num_key_value_heads
self.scaling = config.attention_multiplier
self.attention_dropout = config.attention_dropout
self.is_causal = True
self.q_proj = nn.Linear(
config.hidden_size, config.num_attention_heads * self.head_dim, bias=config.attention_bias
)
self.k_proj = nn.Linear(
config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
)
self.v_proj = nn.Linear(
config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
)
self.o_proj = nn.Linear(
config.num_attention_heads * self.head_dim, config.hidden_size, bias=config.attention_bias
)
self.rotary_fn = apply_rotary_pos_emb
def forward(
self,
hidden_states: torch.Tensor,
position_embeddings: Optional[tuple[torch.Tensor, torch.Tensor]] = None,
attention_mask: Optional[torch.Tensor] = None,
past_key_values: Optional[Cache] = None,
cache_position: Optional[torch.LongTensor] = None,
**kwargs: Unpack[TransformersKwargs],
) -> tuple[torch.Tensor, torch.Tensor]:
input_shape = hidden_states.shape[:-1]
hidden_shape = (*input_shape, -1, self.head_dim)
query_states = self.q_proj(hidden_states).view(hidden_shape).transpose(1, 2)
key_states = self.k_proj(hidden_states).view(hidden_shape).transpose(1, 2)
value_states = self.v_proj(hidden_states).view(hidden_shape).transpose(1, 2)
cos, sin = position_embeddings
query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
if past_key_values is not None:
# sin and cos are specific to RoPE models; cache_position needed for the static cache
cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
key_states, value_states = past_key_values.update(key_states, value_states, self.layer_idx, cache_kwargs)
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.attention_dropout,
scaling=self.scaling,
**kwargs,
)
attn_output = attn_output.reshape(*input_shape, -1).contiguous()
attn_output = self.o_proj(attn_output)
return attn_output, attn_weights
@use_kernel_forward_from_hub("RMSNorm")
| GraniteAttention |
python | vyperlang__vyper | vyper/ast/nodes.py | {
"start": 36416,
"end": 36518
} | class ____(Operator):
__slots__ = ()
_description = "greater-or-equal"
_op = operator.ge
| GtE |
python | ansible__ansible | lib/ansible/module_utils/facts/network/sunos.py | {
"start": 856,
"end": 4650
} | class ____(GenericBsdIfconfigNetwork):
"""
This is the SunOS Network Class.
It uses the GenericBsdIfconfigNetwork.
Solaris can have different FLAGS and MTU for IPv4 and IPv6 on the same interface
so these facts have been moved inside the 'ipv4' and 'ipv6' lists.
"""
platform = 'SunOS'
# Solaris 'ifconfig -a' will print interfaces twice, once for IPv4 and again for IPv6.
# MTU and FLAGS also may differ between IPv4 and IPv6 on the same interface.
# 'parse_interface_line()' checks for previously seen interfaces before defining
# 'current_if' so that IPv6 facts don't clobber IPv4 facts (or vice versa).
def get_interfaces_info(self, ifconfig_path):
interfaces = {}
current_if = {}
ips = dict(
all_ipv4_addresses=[],
all_ipv6_addresses=[],
)
rc, out, err = self.module.run_command([ifconfig_path, '-a'])
for line in out.splitlines():
if line:
words = line.split()
if re.match(r'^\S', line) and len(words) > 3:
current_if = self.parse_interface_line(words, current_if, interfaces)
interfaces[current_if['device']] = current_if
elif words[0].startswith('options='):
self.parse_options_line(words, current_if, ips)
elif words[0] == 'nd6':
self.parse_nd6_line(words, current_if, ips)
elif words[0] == 'ether':
self.parse_ether_line(words, current_if, ips)
elif words[0] == 'media:':
self.parse_media_line(words, current_if, ips)
elif words[0] == 'status:':
self.parse_status_line(words, current_if, ips)
elif words[0] == 'lladdr':
self.parse_lladdr_line(words, current_if, ips)
elif words[0] == 'inet':
self.parse_inet_line(words, current_if, ips)
elif words[0] == 'inet6':
self.parse_inet6_line(words, current_if, ips)
else:
self.parse_unknown_line(words, current_if, ips)
# 'parse_interface_line' and 'parse_inet*_line' leave two dicts in the
# ipv4/ipv6 lists which is ugly and hard to read.
# This quick hack merges the dictionaries. Purely cosmetic.
for iface in interfaces:
for v in 'ipv4', 'ipv6':
combined_facts = {}
for facts in interfaces[iface][v]:
combined_facts.update(facts)
if len(combined_facts.keys()) > 0:
interfaces[iface][v] = [combined_facts]
return interfaces, ips
def parse_interface_line(self, words, current_if, interfaces):
device = words[0][0:-1]
if device not in interfaces:
current_if = {'device': device, 'ipv4': [], 'ipv6': [], 'type': 'unknown'}
else:
current_if = interfaces[device]
flags = self.get_options(words[1])
v = 'ipv4'
if 'IPv6' in flags:
v = 'ipv6'
if 'LOOPBACK' in flags:
current_if['type'] = 'loopback'
current_if[v].append({'flags': flags, 'mtu': words[3]})
current_if['macaddress'] = 'unknown' # will be overwritten later
return current_if
# Solaris displays single digit octets in MAC addresses e.g. 0:1:2:d:e:f
# Add leading zero to each octet where needed.
def parse_ether_line(self, words, current_if, ips):
macaddress = ''
for octet in words[1].split(':'):
octet = ('0' + octet)[-2:None]
macaddress += (octet + ':')
current_if['macaddress'] = macaddress[0:-1]
| SunOSNetwork |
python | realpython__materials | python-formatted-output/person.py | {
"start": 0,
"end": 425
} | class ____:
def __init__(self, name, age):
self.name = name
self.age = age
def __str__(self):
return f"I'm {self.name}, and I'm {self.age} years old."
def __repr__(self):
return f"{type(self).__name__}(name='{self.name}', age={self.age})"
jane = Person("Jane", 25)
print(f"{jane!s}")
print(f"{jane!r}")
print("{jane!s}".format(jane=jane))
print("{jane!r}".format(jane=jane))
| Person |
python | pytorch__pytorch | torch/testing/_internal/distributed/distributed_utils.py | {
"start": 220,
"end": 1871
} | class ____(dist.ProcessGroup):
def getBackendName(self):
return "mock_process_group"
def create_mock_pg(prefix_store, rank, world_size, timeout):
return MockProcessGroup(rank, world_size)
dist.Backend.register_backend("mock_process_group", create_mock_pg)
def mock_init_dist(rank, world_size):
# !!! WARNING !!!
# Kids don't try this at home, this is a cute pile of hacks that
# depends on a small mountain of c10d internals
assert not dist.is_initialized()
store = dist.HashStore()
# Trick _store_based_barrier into believing everyone else already checked-in
# Zero is the group index
store.add(f"{c10d.STORE_BASED_BARRIER_PREFIX}:0", world_size - 1)
dist.init_process_group(
backend="mock_process_group",
rank=rank,
world_size=world_size,
store=store,
group_name="fake",
timeout=timedelta(seconds=1),
)
@contextmanager
def with_dist(rank=0, world_size=2):
"""
Context manager that initializer c10d with a fake process group.
"""
mock_init_dist(rank=rank, world_size=world_size)
try:
yield
finally:
dist.destroy_process_group()
def with_fake_comms(func=None, rank=0, world_size=2):
"""
Function wrapper that inits a fake process group designed for testing.
Right now only querying for world size is available
"""
if func is None:
return partial(with_fake_comms, rank=rank, world_size=world_size)
@wraps(func)
def wrapper(self, *args, **kwargs):
with with_dist(rank, world_size):
func(self, *args, **kwargs)
return wrapper
| MockProcessGroup |
python | huggingface__transformers | tests/quantization/mxfp4/test_mxfp4.py | {
"start": 1858,
"end": 3741
} | class ____(unittest.TestCase):
def test_basic_config_creation(self):
"""Test basic configuration creation with default values"""
config = Mxfp4Config()
self.assertEqual(config.quant_method.value, "mxfp4")
self.assertIsNone(config.modules_to_not_convert)
self.assertFalse(config.dequantize)
def test_config_with_modules_to_not_convert(self):
"""Test configuration with modules to not convert"""
modules = ["model.layers.*.self_attn", "lm_head"]
config = Mxfp4Config(modules_to_not_convert=modules)
self.assertEqual(config.modules_to_not_convert, modules)
def test_config_with_dequantize(self):
"""Test configuration with dequantize enabled"""
config = Mxfp4Config(dequantize=True)
self.assertTrue(config.dequantize)
def test_get_loading_attributes(self):
"""Test get_loading_attributes method"""
config = Mxfp4Config(dequantize=True)
attrs = config.get_loading_attributes()
self.assertEqual(attrs["dequantize"], True)
def test_to_dict(self):
"""Test configuration serialization to dict"""
config = Mxfp4Config(modules_to_not_convert=["lm_head"], dequantize=True)
config_dict = config.to_dict()
self.assertEqual(config_dict["quant_method"], "mxfp4")
self.assertEqual(config_dict["modules_to_not_convert"], ["lm_head"])
# we don't keep dequantize in config_dict
self.assertTrue("dequantize" not in config_dict)
def test_from_dict(self):
"""Test configuration creation from dict"""
config_dict = {"quant_method": "mxfp4", "modules_to_not_convert": ["lm_head"], "dequantize": True}
config = Mxfp4Config.from_dict(config_dict)
self.assertEqual(config.modules_to_not_convert, ["lm_head"])
self.assertTrue(config.dequantize)
| Mxfp4ConfigTest |
python | streamlit__streamlit | lib/tests/streamlit/runtime/state/widgets_test.py | {
"start": 12236,
"end": 13095
} | class ____(unittest.TestCase):
def test_get_widget_with_generated_key(self):
element_id = compute_and_register_element_id(
"button",
label="the label",
user_key="my_key",
dg=None,
key_as_main_identity=False,
)
assert element_id.startswith(GENERATED_ELEMENT_ID_PREFIX)
# These kwargs are not supposed to be used for element ID calculation:
EXCLUDED_KWARGS_FOR_ELEMENT_ID_COMPUTATION = {
# Internal stuff
"ctx",
# Formatting/display stuff: can be changed without resetting an element.
"disabled",
"format_func",
"label_visibility",
# on_change callbacks and similar/related parameters.
"args",
"kwargs",
"on_change",
"on_click",
"on_submit",
# Key should be provided via `user_key` instead.
"key",
}
| WidgetHelperTests |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.