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 | scrapy__scrapy | tests/test_downloadermiddleware_httpauth.py | {
"start": 193,
"end": 267
} | class ____(Spider):
http_user = "foo"
http_pass = "bar"
| LegacySpider |
python | pypa__pip | src/pip/_internal/exceptions.py | {
"start": 9406,
"end": 9504
} | class ____(PipError):
"""Raised when there is an error in command-line arguments"""
| CommandError |
python | langchain-ai__langchain | libs/langchain/langchain_classic/memory/summary.py | {
"start": 906,
"end": 2746
} | class ____(BaseModel):
"""Mixin for summarizer."""
human_prefix: str = "Human"
ai_prefix: str = "AI"
llm: BaseLanguageModel
prompt: BasePromptTemplate = SUMMARY_PROMPT
summary_message_cls: type[BaseMessage] = SystemMessage
def predict_new_summary(
self,
messages: list[BaseMessage],
existing_summary: str,
) -> str:
"""Predict a new summary based on the messages and existing summary.
Args:
messages: List of messages to summarize.
existing_summary: Existing summary to build upon.
Returns:
A new summary string.
"""
new_lines = get_buffer_string(
messages,
human_prefix=self.human_prefix,
ai_prefix=self.ai_prefix,
)
chain = LLMChain(llm=self.llm, prompt=self.prompt)
return chain.predict(summary=existing_summary, new_lines=new_lines)
async def apredict_new_summary(
self,
messages: list[BaseMessage],
existing_summary: str,
) -> str:
"""Predict a new summary based on the messages and existing summary.
Args:
messages: List of messages to summarize.
existing_summary: Existing summary to build upon.
Returns:
A new summary string.
"""
new_lines = get_buffer_string(
messages,
human_prefix=self.human_prefix,
ai_prefix=self.ai_prefix,
)
chain = LLMChain(llm=self.llm, prompt=self.prompt)
return await chain.apredict(summary=existing_summary, new_lines=new_lines)
@deprecated(
since="0.3.1",
removal="1.0.0",
message=(
"Please see the migration guide at: "
"https://python.langchain.com/docs/versions/migrating_memory/"
),
)
| SummarizerMixin |
python | scipy__scipy | scipy/_lib/_pep440.py | {
"start": 7551,
"end": 14005
} | class ____(_BaseVersion):
_regex = re.compile(
r"^\s*" + VERSION_PATTERN + r"\s*$",
re.VERBOSE | re.IGNORECASE,
)
def __init__(self, version):
# Validate the version and parse it into pieces
match = self._regex.search(version)
if not match:
raise InvalidVersion(f"Invalid version: '{version}'")
# Store the parsed out pieces of the version
self._version = _Version(
epoch=int(match.group("epoch")) if match.group("epoch") else 0,
release=tuple(int(i) for i in match.group("release").split(".")),
pre=_parse_letter_version(
match.group("pre_l"),
match.group("pre_n"),
),
post=_parse_letter_version(
match.group("post_l"),
match.group("post_n1") or match.group("post_n2"),
),
dev=_parse_letter_version(
match.group("dev_l"),
match.group("dev_n"),
),
local=_parse_local_version(match.group("local")),
)
# Generate a key which will be used for sorting
self._key = _cmpkey(
self._version.epoch,
self._version.release,
self._version.pre,
self._version.post,
self._version.dev,
self._version.local,
)
def __repr__(self):
return f"<Version({repr(str(self))})>"
def __str__(self):
parts = []
# Epoch
if self._version.epoch != 0:
parts.append(f"{self._version.epoch}!")
# Release segment
parts.append(".".join(str(x) for x in self._version.release))
# Pre-release
if self._version.pre is not None:
parts.append("".join(str(x) for x in self._version.pre))
# Post-release
if self._version.post is not None:
parts.append(f".post{self._version.post[1]}")
# Development release
if self._version.dev is not None:
parts.append(f".dev{self._version.dev[1]}")
# Local version segment
if self._version.local is not None:
parts.append(
"+{}".format(".".join(str(x) for x in self._version.local))
)
return "".join(parts)
@property
def public(self):
return str(self).split("+", 1)[0]
@property
def base_version(self):
parts = []
# Epoch
if self._version.epoch != 0:
parts.append(f"{self._version.epoch}!")
# Release segment
parts.append(".".join(str(x) for x in self._version.release))
return "".join(parts)
@property
def local(self):
version_string = str(self)
if "+" in version_string:
return version_string.split("+", 1)[1]
@property
def is_prerelease(self):
return bool(self._version.dev or self._version.pre)
@property
def is_postrelease(self):
return bool(self._version.post)
def _parse_letter_version(letter, number):
if letter:
# We assume there is an implicit 0 in a pre-release if there is
# no numeral associated with it.
if number is None:
number = 0
# We normalize any letters to their lower-case form
letter = letter.lower()
# We consider some words to be alternate spellings of other words and
# in those cases we want to normalize the spellings to our preferred
# spelling.
if letter == "alpha":
letter = "a"
elif letter == "beta":
letter = "b"
elif letter in ["c", "pre", "preview"]:
letter = "rc"
elif letter in ["rev", "r"]:
letter = "post"
return letter, int(number)
if not letter and number:
# We assume that if we are given a number but not given a letter,
# then this is using the implicit post release syntax (e.g., 1.0-1)
letter = "post"
return letter, int(number)
_local_version_seperators = re.compile(r"[\._-]")
def _parse_local_version(local):
"""
Takes a string like abc.1.twelve and turns it into ("abc", 1, "twelve").
"""
if local is not None:
return tuple(
part.lower() if not part.isdigit() else int(part)
for part in _local_version_seperators.split(local)
)
def _cmpkey(epoch, release, pre, post, dev, local):
# When we compare a release version, we want to compare it with all of the
# trailing zeros removed. So we'll use a reverse the list, drop all the now
# leading zeros until we come to something non-zero, then take the rest,
# re-reverse it back into the correct order, and make it a tuple and use
# that for our sorting key.
release = tuple(
reversed(list(
itertools.dropwhile(
lambda x: x == 0,
reversed(release),
)
))
)
# We need to "trick" the sorting algorithm to put 1.0.dev0 before 1.0a0.
# We'll do this by abusing the pre-segment, but we _only_ want to do this
# if there is no pre- or a post-segment. If we have one of those, then
# the normal sorting rules will handle this case correctly.
if pre is None and post is None and dev is not None:
pre = -Infinity
# Versions without a pre-release (except as noted above) should sort after
# those with one.
elif pre is None:
pre = Infinity
# Versions without a post-segment should sort before those with one.
if post is None:
post = -Infinity
# Versions without a development segment should sort after those with one.
if dev is None:
dev = Infinity
if local is None:
# Versions without a local segment should sort before those with one.
local = -Infinity
else:
# Versions with a local segment need that segment parsed to implement
# the sorting rules in PEP440.
# - Alphanumeric segments sort before numeric segments
# - Alphanumeric segments sort lexicographically
# - Numeric segments sort numerically
# - Shorter versions sort before longer versions when the prefixes
# match exactly
local = tuple(
(i, "") if isinstance(i, int) else (-Infinity, i)
for i in local
)
return epoch, release, pre, post, dev, local
| Version |
python | realpython__materials | web-scraping-with-scrapy-and-mongodb/books/books/pipelines.py | {
"start": 108,
"end": 1206
} | class ____:
COLLECTION_NAME = "books"
def __init__(self, mongo_uri, mongo_db):
self.mongo_uri = mongo_uri
self.mongo_db = mongo_db
@classmethod
def from_crawler(cls, crawler):
return cls(
mongo_uri=crawler.settings.get("MONGO_URI"),
mongo_db=crawler.settings.get("MONGO_DATABASE"),
)
def open_spider(self, spider):
self.client = pymongo.MongoClient(self.mongo_uri)
self.db = self.client[self.mongo_db]
def close_spider(self, spider):
self.client.close()
def process_item(self, item, spider):
item_id = self.compute_item_id(item)
if self.db[self.COLLECTION_NAME].find_one({"_id": item_id}):
raise DropItem(f"Duplicate item found: {item}")
else:
item["_id"] = item_id
self.db[self.COLLECTION_NAME].insert_one(
ItemAdapter(item).asdict()
)
return item
def compute_item_id(self, item):
url = item["url"]
return hashlib.sha256(url.encode("utf-8")).hexdigest()
| MongoPipeline |
python | run-llama__llama_index | llama-index-integrations/tools/llama-index-tools-dappier/llama_index/tools/dappier/ai_recommendations/base.py | {
"start": 163,
"end": 11611
} | class ____(BaseToolSpec):
"""
Dappier AI Recommendations tool spec.
Provides AI-powered recommendations across various domains such as Sports News,
Lifestyle News, iHeartDogs, iHeartCats, GreenMonster, WISH-TV and 9 and 10 News.
"""
spec_functions = [
"get_sports_news_recommendations",
"get_lifestyle_news_recommendations",
"get_iheartdogs_recommendations",
"get_iheartcats_recommendations",
"get_greenmonster_recommendations",
"get_wishtv_recommendations",
"get_nine_and_ten_news_recommendations",
]
def __init__(self, api_key: Optional[str] = None) -> None:
"""
Initialize the Dappier AI Recommendations tool spec.
To obtain an API key, visit: https://platform.dappier.com/profile/api-keys
"""
from dappier import Dappier
self.api_key = api_key or os.environ.get("DAPPIER_API_KEY")
if not self.api_key:
raise ValueError(
"API key is required. Provide it as a parameter or set DAPPIER_API_KEY in environment variables.\n"
"To obtain an API key, visit: https://platform.dappier.com/profile/api-keys"
)
self.client = Dappier(api_key=self.api_key)
def get_sports_news_recommendations(
self,
query: str,
similarity_top_k: int = 10,
ref: Optional[str] = None,
num_articles_ref: int = 0,
search_algorithm: Literal[
"most_recent", "semantic", "most_recent_semantic", "trending"
] = "most_recent",
) -> str:
"""
Retrieves sports news.
Args:
query (str): Query to fetch sports news.
similarity_top_k (int): Number of documents to return.
ref (Optional[str]): Site domain where recommendations should be displayed.
num_articles_ref (int): Minimum number of articles to return from the reference domain.
search_algorithm (str): The search algorithm to use.
Returns:
str: A response message for the user specified query.
"""
data_model_id = "dm_01j0pb465keqmatq9k83dthx34" # Sports News
response = self.client.get_ai_recommendations(
query=query,
data_model_id=data_model_id,
similarity_top_k=similarity_top_k,
ref=ref,
num_articles_ref=num_articles_ref,
search_algorithm=search_algorithm,
)
return format_results(response)
def get_lifestyle_news_recommendations(
self,
query: str,
similarity_top_k: int = 10,
ref: Optional[str] = None,
num_articles_ref: int = 0,
search_algorithm: Literal[
"most_recent", "semantic", "most_recent_semantic", "trending"
] = "most_recent",
) -> str:
"""
Retrieves lifestyle news.
Args:
query (str): Query to fetch lifestyle news.
similarity_top_k (int): Number of documents to return.
ref (Optional[str]): Site domain where recommendations should be displayed.
num_articles_ref (int): Minimum number of articles to return from the reference domain.
search_algorithm (str): The search algorithm to use.
Returns:
str: A response message for the user specified query.
"""
data_model_id = "dm_01j0q82s4bfjmsqkhs3ywm3x6y" # Lifestyle News
response = self.client.get_ai_recommendations(
query=query,
data_model_id=data_model_id,
similarity_top_k=similarity_top_k,
ref=ref,
num_articles_ref=num_articles_ref,
search_algorithm=search_algorithm,
)
return format_results(response)
def get_iheartdogs_recommendations(
self,
query: str,
similarity_top_k: int = 10,
ref: Optional[str] = None,
num_articles_ref: int = 0,
search_algorithm: Literal[
"most_recent", "semantic", "most_recent_semantic", "trending"
] = "most_recent",
) -> str:
"""
Retrieves iHeartDogs articles - a dog care expert.
Args:
query (str): Query to fetch dog care articles.
similarity_top_k (int): Number of documents to return.
ref (Optional[str]): Site domain where recommendations should be displayed.
num_articles_ref (int): Minimum number of articles to return from the reference domain.
search_algorithm (str): The search algorithm to use.
Returns:
str: A response message for the user specified query.
"""
data_model_id = "dm_01j1sz8t3qe6v9g8ad102kvmqn" # iHeartDogs AI
response = self.client.get_ai_recommendations(
query=query,
data_model_id=data_model_id,
similarity_top_k=similarity_top_k,
ref=ref,
num_articles_ref=num_articles_ref,
search_algorithm=search_algorithm,
)
return format_results(response)
def get_iheartcats_recommendations(
self,
query: str,
similarity_top_k: int = 10,
ref: Optional[str] = None,
num_articles_ref: int = 0,
search_algorithm: Literal[
"most_recent", "semantic", "most_recent_semantic", "trending"
] = "most_recent",
) -> str:
"""
Retrieves iHeartCats articles - a cat care expert.
Args:
query (str): Query to fetch cat care articles.
similarity_top_k (int): Number of documents to return.
ref (Optional[str]): Site domain where recommendations should be displayed.
num_articles_ref (int): Minimum number of articles to return from the reference domain.
search_algorithm (str): The search algorithm to use.
Returns:
str: A response message for the user specified query.
"""
data_model_id = "dm_01j1sza0h7ekhaecys2p3y0vmj" # iHeartCats AI
response = self.client.get_ai_recommendations(
query=query,
data_model_id=data_model_id,
similarity_top_k=similarity_top_k,
ref=ref,
num_articles_ref=num_articles_ref,
search_algorithm=search_algorithm,
)
return format_results(response)
def get_greenmonster_recommendations(
self,
query: str,
similarity_top_k: int = 10,
ref: Optional[str] = None,
num_articles_ref: int = 0,
search_algorithm: Literal[
"most_recent", "semantic", "most_recent_semantic", "trending"
] = "most_recent",
) -> str:
"""
Retrieves GreenMonster articles - Compassionate Living Guide.
Args:
query (str): Query to fetch compassionate living guides.
similarity_top_k (int): Number of documents to return.
ref (Optional[str]): Site domain where recommendations should be displayed.
num_articles_ref (int): Minimum number of articles to return from the reference domain.
search_algorithm (str): The search algorithm to use.
Returns:
str: A response message for the user specified query.
"""
data_model_id = "dm_01j5xy9w5sf49bm6b1prm80m27" # GreenMonster
response = self.client.get_ai_recommendations(
query=query,
data_model_id=data_model_id,
similarity_top_k=similarity_top_k,
ref=ref,
num_articles_ref=num_articles_ref,
search_algorithm=search_algorithm,
)
return format_results(response)
def get_wishtv_recommendations(
self,
query: str,
similarity_top_k: int = 10,
ref: Optional[str] = None,
num_articles_ref: int = 0,
search_algorithm: Literal[
"most_recent", "semantic", "most_recent_semantic", "trending"
] = "most_recent",
) -> str:
"""
Retrieves news articles.
Args:
query (str): Query to fetch news articles.
similarity_top_k (int): The number of top documents to retrieve based on similarity. Defaults to 10.
ref (Optional[str]): The site domain where recommendations should be displayed. Defaults to None.
num_articles_ref (int): Minimum number of articles to return from the reference domain. Defaults to 0.
search_algorithm (str): The search algorithm to use. Defaults to "most_recent".
Returns:
str: A response message for the user specified query.
"""
data_model_id = "dm_01jagy9nqaeer9hxx8z1sk1jx6" # WISH-TV AI
response = self.client.get_ai_recommendations(
query=query,
data_model_id=data_model_id,
similarity_top_k=similarity_top_k,
ref=ref,
num_articles_ref=num_articles_ref,
search_algorithm=search_algorithm,
)
return format_results(response)
def get_nine_and_ten_news_recommendations(
self,
query: str,
similarity_top_k: int = 10,
ref: Optional[str] = None,
num_articles_ref: int = 0,
search_algorithm: Literal[
"most_recent", "semantic", "most_recent_semantic", "trending"
] = "most_recent",
) -> str:
"""
Retrieves up-to-date local news for Northern Michigan, Cadillac and
Traverse City.
Args:
query (str): Query to fetch local news.
similarity_top_k (int): Number of documents to return.
ref (Optional[str]): Site domain where recommendations should be displayed.
num_articles_ref (int): Minimum number of articles to return from the reference domain.
search_algorithm (str): The search algorithm to use.
Returns:
str: A response message for the user specified query.
"""
data_model_id = "dm_01jhtt138wf1b9j8jwswye99y5" # 9 and 10 News
response = self.client.get_ai_recommendations(
query=query,
data_model_id=data_model_id,
similarity_top_k=similarity_top_k,
ref=ref,
num_articles_ref=num_articles_ref,
search_algorithm=search_algorithm,
)
return format_results(response)
def format_results(response: Any) -> str:
"""
Converts a Dappier AI Recommendations API response into a human-readable text format for LLMs.
Args:
response (Any): JSON object returned by the Dappier API.
Returns:
str: A formatted string representation of the recommendations.
"""
if response.status != "success":
return "The API response was not successful."
results = response.response.results
formatted_text = ""
for idx, result in enumerate(results, start=1):
formatted_text += (
f"Result {idx}:\n"
f"Title: {result.title}\n"
f"Author: {result.author}\n"
f"Published on: {result.pubdate}\n"
f"Source: {result.site} ({result.site_domain})\n"
f"URL: {result.source_url}\n"
f"Image URL: {result.image_url}\n"
f"Summary: {result.summary}\n"
f"Score: {result.score}\n\n"
)
return formatted_text
| DappierAIRecommendationsToolSpec |
python | lazyprogrammer__machine_learning_examples | pytorch/rl_trader.py | {
"start": 544,
"end": 2063
} | class ____:
def __init__(self, obs_dim, act_dim, size):
self.obs1_buf = np.zeros([size, obs_dim], dtype=np.float32)
self.obs2_buf = np.zeros([size, obs_dim], dtype=np.float32)
self.acts_buf = np.zeros(size, dtype=np.uint8)
self.rews_buf = np.zeros(size, dtype=np.float32)
self.done_buf = np.zeros(size, dtype=np.uint8)
self.ptr, self.size, self.max_size = 0, 0, size
def store(self, obs, act, rew, next_obs, done):
self.obs1_buf[self.ptr] = obs
self.obs2_buf[self.ptr] = next_obs
self.acts_buf[self.ptr] = act
self.rews_buf[self.ptr] = rew
self.done_buf[self.ptr] = done
self.ptr = (self.ptr+1) % self.max_size
self.size = min(self.size+1, self.max_size)
def sample_batch(self, batch_size=32):
idxs = np.random.randint(0, self.size, size=batch_size)
return dict(s=self.obs1_buf[idxs],
s2=self.obs2_buf[idxs],
a=self.acts_buf[idxs],
r=self.rews_buf[idxs],
d=self.done_buf[idxs])
def get_scaler(env):
# return scikit-learn scaler object to scale the states
# Note: you could also populate the replay buffer here
states = []
for _ in range(env.n_step):
action = np.random.choice(env.action_space)
state, reward, done, info = env.step(action)
states.append(state)
if done:
break
scaler = StandardScaler()
scaler.fit(states)
return scaler
def maybe_make_dir(directory):
if not os.path.exists(directory):
os.makedirs(directory)
| ReplayBuffer |
python | django__django | tests/template_tests/filter_tests/test_lower.py | {
"start": 163,
"end": 901
} | class ____(SimpleTestCase):
@setup(
{
"lower01": (
"{% autoescape off %}{{ a|lower }} {{ b|lower }}{% endautoescape %}"
)
}
)
def test_lower01(self):
output = self.engine.render_to_string(
"lower01", {"a": "Apple & banana", "b": mark_safe("Apple & banana")}
)
self.assertEqual(output, "apple & banana apple & banana")
@setup({"lower02": "{{ a|lower }} {{ b|lower }}"})
def test_lower02(self):
output = self.engine.render_to_string(
"lower02", {"a": "Apple & banana", "b": mark_safe("Apple & banana")}
)
self.assertEqual(output, "apple & banana apple & banana")
| LowerTests |
python | vyperlang__vyper | vyper/ast/nodes.py | {
"start": 39259,
"end": 43036
} | class ____(VyperNode):
"""
A contract variable declaration.
Excludes `simple` attribute from Python `AnnAssign` node.
Attributes
----------
target : VyperNode
Left-hand side of the assignment.
value : VyperNode
Right-hand side of the assignment.
annotation : VyperNode
Type of variable.
is_constant : bool, optional
If true, indicates that the variable is a constant variable.
is_public : bool, optional
If true, indicates that the variable is a public state variable.
is_immutable : bool, optional
If true, indicates that the variable is an immutable variable.
"""
__slots__ = (
"target",
"annotation",
"value",
"is_constant",
"is_public",
"is_immutable",
"is_transient",
"is_reentrant",
"_expanded_getter",
)
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.is_constant = False
self.is_public = False
self.is_immutable = False
self.is_transient = False
self.is_reentrant = False
self._expanded_getter = None
def _check_args(annotation, call_name):
# do the same thing as `validate_call_args`
# (can't be imported due to cyclic dependency)
if len(annotation.args) != 1:
raise ArgumentException(f"Invalid number of arguments to `{call_name}`:", self)
# the annotation is a "function" call, e.g.
# `foo: public(constant(uint256))`
# pretend we were parsing actual Vyper AST. annotation would be
# TYPE | PUBLIC "(" TYPE | ((IMMUTABLE | CONSTANT) "(" TYPE ")") ")"
# unwrap reentrant and public. they can be in any order
seen = []
for _ in range(2):
func_id = self.annotation.get("func.id")
if func_id in seen:
_raise_syntax_exc(
f"Used variable annotation `{func_id}` multiple times", self.annotation
)
if func_id not in ("public", "reentrant"):
break
_check_args(self.annotation, func_id)
setattr(self, f"is_{func_id}", True)
# unwrap one layer
seen.append(func_id)
self.annotation = self.annotation.args[0]
func_id = self.annotation.get("func.id")
if func_id in ("immutable", "constant", "transient"):
_check_args(self.annotation, func_id)
setattr(self, f"is_{func_id}", True)
# unwrap one layer
self.annotation = self.annotation.args[0]
if isinstance(self.annotation, Call):
_raise_syntax_exc("Invalid scope for variable declaration", self.annotation)
@property
def _pretty_location(self) -> str:
if self.is_constant:
return "Constant"
if self.is_transient:
return "Transient"
if self.is_immutable:
return "Immutable"
return "Storage"
def validate(self):
if self.is_constant and self.value is None:
raise VariableDeclarationException("Constant must be declared with a value", self)
if self.is_reentrant and not self.is_public:
raise VariableDeclarationException(
"Only public variables can be marked `reentrant`!", self
)
if not self.is_constant and self.value is not None:
raise VariableDeclarationException(
f"{self._pretty_location} variables cannot have an initial value", self.value
)
if not isinstance(self.target, Name):
raise VariableDeclarationException("Invalid variable declaration", self.target)
| VariableDecl |
python | dagster-io__dagster | examples/docs_snippets/docs_snippets/guides/quality-testing/unit-testing-assets-and-ops/asset-combo.py | {
"start": 36,
"end": 529
} | class ____(dg.Config):
separator: str
@dg.asset
def processed_file(
primary_file: str, secondary_file: str, config: SeparatorConfig
) -> str:
return f"{primary_file}{config.separator}{secondary_file}"
# end_file
# start_test
def test_processed_file() -> None:
assert (
processed_file(
primary_file="abc",
secondary_file="def",
config=SeparatorConfig(separator=","),
)
== "abc,def"
)
# end_test
| SeparatorConfig |
python | kamyu104__LeetCode-Solutions | Python/count-numbers-with-non-decreasing-digits.py | {
"start": 81,
"end": 1582
} | class ____(object):
def countNumbers(self, l, r, b):
"""
:type l: str
:type r: str
:type b: int
:rtype: int
"""
MOD = 10**9+7
fact, inv, inv_fact = [[1]*2 for _ in xrange(3)]
def nCr(n, k):
while len(inv) <= n: # lazy initialization
fact.append(fact[-1]*len(inv) % MOD)
inv.append(inv[MOD%len(inv)]*(MOD-MOD//len(inv)) % MOD) # https://cp-algorithms.com/algebra/module-inverse.html
inv_fact.append(inv_fact[-1]*inv[-1] % MOD)
return (fact[n]*inv_fact[n-k] % MOD) * inv_fact[k] % MOD
def nHr(n, k):
return nCr(n+k-1, k)
def count(x):
digits_base = []
while x:
x, r = divmod(x, b)
digits_base.append(r)
digits_base.reverse()
if not digits_base:
digits_base.append(0)
result = 0
for i in xrange(len(digits_base)):
if i-1 >= 0 and digits_base[i-1] > digits_base[i]:
break
for j in xrange(digits_base[i-1] if i-1 >= 0 else 0, digits_base[i]):
result = (result + nHr((b-1)-j+1, len(digits_base)-(i+1))) % MOD
else:
result = (result+1)%MOD
return result
return (count(int(r)) - count(int(l)-1)) % MOD
# Time: O(n^2), n = len(r)
# Space: O(n)
# math, stars and bars, combinatorics
| Solution |
python | scrapy__scrapy | extras/qpsclient.py | {
"start": 293,
"end": 1623
} | class ____(Spider):
name = "qps"
benchurl = "http://localhost:8880/"
# Max concurrency is limited by global CONCURRENT_REQUESTS setting
max_concurrent_requests = 8
# Requests per second goal
qps = None # same as: 1 / download_delay
download_delay = None
# time in seconds to delay server responses
latency = None
# number of slots to create
slots = 1
def __init__(self, *a, **kw):
super().__init__(*a, **kw)
if self.qps is not None:
self.qps = float(self.qps)
self.download_delay = 1 / self.qps
elif self.download_delay is not None:
self.download_delay = float(self.download_delay)
async def start(self):
for item_or_request in self.start_requests():
yield item_or_request
def start_requests(self):
url = self.benchurl
if self.latency is not None:
url += f"?latency={self.latency}"
slots = int(self.slots)
if slots > 1:
urls = [url.replace("localhost", f"127.0.0.{x + 1}") for x in range(slots)]
else:
urls = [url]
idx = 0
while True:
url = urls[idx % len(urls)]
yield Request(url, dont_filter=True)
idx += 1
def parse(self, response):
pass
| QPSSpider |
python | bokeh__bokeh | src/bokeh/models/selections.py | {
"start": 1488,
"end": 3422
} | class ____(Model):
'''
A Selection represents a portion of the data in a ``DataSource``, which
can be visually manipulated in a plot.
Selections are typically created by selecting points in a plot with
a ``SelectTool``, but can also be programmatically specified.
For most glyphs, the ``indices`` property is the relevant value to use.
'''
# explicit __init__ to support Init signatures
def __init__(self, *args: Any, **kwargs: Any) -> None:
super().__init__(*args, **kwargs)
indices = Seq(Int, default=[], help="""
The "scatter" level indices included in a selection. For example, for a
selection on a ``Circle`` glyph, this list records the indices of which
individual circles are selected.
For "multi" glyphs such as ``Patches``, ``MultiLine``, ``MultiPolygons``,
etc, this list records the indices of which entire sub-items are selected.
For example, which individual polygons of a ``MultiPolygon`` are selected.
""")
line_indices = Seq(Int, default=[], help="""
The point indices included in a selection on a ``Line`` glyph.
This value records the indices of the individual points on a ``Line`` that
were selected by a selection tool.
""")
multiline_indices = Dict(Int, Seq(Int), default={}, help="""
The detailed point indices included in a selection on a ``MultiLine``.
This value records which points, on which lines, are part of a selection
on a ``MultiLine``. The keys are the top level indices (i.e. which line)
which map to lists of indices (i.e. which points on that line).
If you only need to know which lines are selected, without knowing what
individual points on those lines are selected, then you can look at the
keys of this dictionary (converted to ints).
""")
image_indices = List(Struct(index=Int, i=Int, j=Int, flat_index=Int), help="""
""")
@abstract
| Selection |
python | jmcnamara__XlsxWriter | xlsxwriter/chart_stock.py | {
"start": 285,
"end": 3540
} | class ____(chart.Chart):
"""
A class for writing the Excel XLSX Stock charts.
"""
###########################################################################
#
# Public API.
#
###########################################################################
def __init__(self) -> None:
"""
Constructor.
"""
super().__init__()
self.show_crosses = False
self.hi_low_lines = {}
self.date_category = True
# Override and reset the default axis values.
self.x_axis["defaults"]["num_format"] = "dd/mm/yyyy"
self.x2_axis["defaults"]["num_format"] = "dd/mm/yyyy"
# Set the available data label positions for this chart type.
self.label_position_default = "right"
self.label_positions = {
"center": "ctr",
"right": "r",
"left": "l",
"above": "t",
"below": "b",
# For backward compatibility.
"top": "t",
"bottom": "b",
}
self.set_x_axis({})
self.set_x2_axis({})
###########################################################################
#
# Private API.
#
###########################################################################
def _write_chart_type(self, args) -> None:
# Override the virtual superclass method with a chart specific method.
# Write the c:stockChart element.
self._write_stock_chart(args)
###########################################################################
#
# XML methods.
#
###########################################################################
def _write_stock_chart(self, args) -> None:
# Write the <c:stockChart> element.
# Overridden to add hi_low_lines().
if args["primary_axes"]:
series = self._get_primary_axes_series()
else:
series = self._get_secondary_axes_series()
if not series:
return
# Add default formatting to the series data.
self._modify_series_formatting()
self._xml_start_tag("c:stockChart")
# Write the series elements.
for data in series:
self._write_ser(data)
# Write the c:dropLines element.
self._write_drop_lines()
# Write the c:hiLowLines element.
if args.get("primary_axes"):
self._write_hi_low_lines()
# Write the c:upDownBars element.
self._write_up_down_bars()
# Write the c:axId elements
self._write_axis_ids(args)
self._xml_end_tag("c:stockChart")
def _modify_series_formatting(self) -> None:
# Add default formatting to the series data.
index = 0
for series in self.series:
if index % 4 != 3:
if not series["line"]["defined"]:
series["line"] = {"width": 2.25, "none": 1, "defined": 1}
if series["marker"] is None:
if index % 4 == 2:
series["marker"] = {"type": "dot", "size": 3}
else:
series["marker"] = {"type": "none"}
index += 1
| ChartStock |
python | scipy__scipy | scipy/fft/tests/mock_backend.py | {
"start": 54,
"end": 2685
} | class ____:
def __init__(self, return_value = None):
self.number_calls = threading.local()
self.return_value = return_value
self.last_args = threading.local()
def __call__(self, *args, **kwargs):
if not hasattr(self.number_calls, 'c'):
self.number_calls.c = 0
self.number_calls.c += 1
self.last_args.l = (args, kwargs)
return self.return_value
fft = _MockFunction(np.random.random(10))
fft2 = _MockFunction(np.random.random(10))
fftn = _MockFunction(np.random.random(10))
ifft = _MockFunction(np.random.random(10))
ifft2 = _MockFunction(np.random.random(10))
ifftn = _MockFunction(np.random.random(10))
rfft = _MockFunction(np.random.random(10))
rfft2 = _MockFunction(np.random.random(10))
rfftn = _MockFunction(np.random.random(10))
irfft = _MockFunction(np.random.random(10))
irfft2 = _MockFunction(np.random.random(10))
irfftn = _MockFunction(np.random.random(10))
hfft = _MockFunction(np.random.random(10))
hfft2 = _MockFunction(np.random.random(10))
hfftn = _MockFunction(np.random.random(10))
ihfft = _MockFunction(np.random.random(10))
ihfft2 = _MockFunction(np.random.random(10))
ihfftn = _MockFunction(np.random.random(10))
dct = _MockFunction(np.random.random(10))
idct = _MockFunction(np.random.random(10))
dctn = _MockFunction(np.random.random(10))
idctn = _MockFunction(np.random.random(10))
dst = _MockFunction(np.random.random(10))
idst = _MockFunction(np.random.random(10))
dstn = _MockFunction(np.random.random(10))
idstn = _MockFunction(np.random.random(10))
fht = _MockFunction(np.random.random(10))
ifht = _MockFunction(np.random.random(10))
__ua_domain__ = "numpy.scipy.fft"
_implements = {
scipy.fft.fft: fft,
scipy.fft.fft2: fft2,
scipy.fft.fftn: fftn,
scipy.fft.ifft: ifft,
scipy.fft.ifft2: ifft2,
scipy.fft.ifftn: ifftn,
scipy.fft.rfft: rfft,
scipy.fft.rfft2: rfft2,
scipy.fft.rfftn: rfftn,
scipy.fft.irfft: irfft,
scipy.fft.irfft2: irfft2,
scipy.fft.irfftn: irfftn,
scipy.fft.hfft: hfft,
scipy.fft.hfft2: hfft2,
scipy.fft.hfftn: hfftn,
scipy.fft.ihfft: ihfft,
scipy.fft.ihfft2: ihfft2,
scipy.fft.ihfftn: ihfftn,
scipy.fft.dct: dct,
scipy.fft.idct: idct,
scipy.fft.dctn: dctn,
scipy.fft.idctn: idctn,
scipy.fft.dst: dst,
scipy.fft.idst: idst,
scipy.fft.dstn: dstn,
scipy.fft.idstn: idstn,
scipy.fft.fht: fht,
scipy.fft.ifht: ifht
}
def __ua_function__(method, args, kwargs):
fn = _implements.get(method)
return (fn(*args, **kwargs) if fn is not None
else NotImplemented)
| _MockFunction |
python | catalyst-team__catalyst | catalyst/contrib/optimizers/ralamb.py | {
"start": 127,
"end": 5724
} | class ____(Optimizer):
"""RAdam optimizer with LARS/LAMB tricks.
Adapted from:
https://github.com/mgrankin/over9000/blob/master/ralamb.py
(Apache-2.0 License)
"""
def __init__(
self,
params: Iterable,
lr: float = 1e-3,
betas: Tuple[float, float] = (0.9, 0.999),
eps: float = 1e-8,
weight_decay: float = 0,
):
"""
Args:
params: iterable of parameters to optimize
or dicts defining parameter groups
lr (float, optional): learning rate (default: 1e-3)
betas (Tuple[float, float], optional): coefficients used for
computing running averages of gradient
and its square (default: (0.9, 0.999))
eps (float, optional): term added to the denominator to improve
numerical stability (default: 1e-8)
weight_decay (float, optional): weight decay
(L2 penalty) (default: 0)
"""
defaults = {
"lr": lr,
"betas": betas,
"eps": eps,
"weight_decay": weight_decay,
}
self.buffer = [[None, None, None] for ind in range(10)]
super(Ralamb, self).__init__(params, defaults)
def __setstate__(self, state):
"""Sets state."""
super(Ralamb, self).__setstate__(state)
def step(self, closure: Optional[Callable] = None):
"""Makes optimizer step.
Args:
closure (callable, optional): A closure that reevaluates
the model and returns the loss.
Returns:
computed loss
Raises:
RuntimeError: Ralamb does not support sparse gradients
"""
loss = None
if closure is not None:
loss = closure()
for group in self.param_groups:
for p in group["params"]:
if p.grad is None:
continue
grad = p.grad.data.float()
if grad.is_sparse:
raise RuntimeError("Ralamb does not support sparse gradients")
p_data_fp32 = p.data.float()
state = self.state[p]
if len(state) == 0:
state["step"] = 0
state["exp_avg"] = torch.zeros_like(p_data_fp32)
state["exp_avg_sq"] = torch.zeros_like(p_data_fp32)
else:
state["exp_avg"] = state["exp_avg"].type_as(p_data_fp32)
state["exp_avg_sq"] = state["exp_avg_sq"].type_as(p_data_fp32)
exp_avg, exp_avg_sq = state["exp_avg"], state["exp_avg_sq"]
beta1, beta2 = group["betas"]
# Decay the first and second moment running average coefficient
# m_t
exp_avg.mul_(beta1).add_(1 - beta1, grad)
# v_t
exp_avg_sq.mul_(beta2).addcmul_(1 - beta2, grad, grad)
state["step"] += 1
buffered = self.buffer[int(state["step"] % 10)]
if state["step"] == buffered[0]:
n_sma, radam_step_size = buffered[1], buffered[2]
else:
buffered[0] = state["step"]
beta2_t = beta2 ** state["step"]
n_sma_max = 2 / (1 - beta2) - 1
n_sma = n_sma_max - 2 * state["step"] * beta2_t / (1 - beta2_t)
buffered[1] = n_sma
# more conservative since it"s an approximated value
if n_sma >= 5:
radam_step_size = math.sqrt(
(1 - beta2_t)
* (n_sma - 4)
/ (n_sma_max - 4)
* (n_sma - 2)
/ n_sma
* n_sma_max
/ (n_sma_max - 2)
) / (1 - beta1 ** state["step"])
else:
radam_step_size = 1.0 / (1 - beta1 ** state["step"])
buffered[2] = radam_step_size
if group["weight_decay"] != 0:
p_data_fp32.add_(-group["weight_decay"] * group["lr"], p_data_fp32)
# more conservative since it"s an approximated value
radam_step = p_data_fp32.clone()
if n_sma >= 5:
denom = exp_avg_sq.sqrt().add_(group["eps"])
radam_step.addcdiv_(-radam_step_size * group["lr"], exp_avg, denom)
else:
radam_step.add_(-radam_step_size * group["lr"], exp_avg)
radam_norm = radam_step.pow(2).sum().sqrt()
weight_norm = p.data.pow(2).sum().sqrt().clamp(0, 10)
if weight_norm == 0 or radam_norm == 0:
trust_ratio = 1
else:
trust_ratio = weight_norm / radam_norm
state["weight_norm"] = weight_norm
state["adam_norm"] = radam_norm
state["trust_ratio"] = trust_ratio
if n_sma >= 5:
p_data_fp32.addcdiv_(
-radam_step_size * group["lr"] * trust_ratio, exp_avg, denom
)
else:
p_data_fp32.add_(
-radam_step_size * group["lr"] * trust_ratio, exp_avg
)
p.data.copy_(p_data_fp32)
return loss
__all__ = ["Ralamb"]
| Ralamb |
python | getsentry__sentry | src/sentry/utils/security/orgauthtoken_token.py | {
"start": 219,
"end": 1621
} | class ____(Exception):
# system.url-prefix is not set. You need to set this to generate a token.
pass
def generate_token(org_slug: str, region_url: str) -> str:
sentry_url = options.get("system.url-prefix")
if sentry_url is None:
raise SystemUrlPrefixMissingException
payload = {
"iat": datetime.utcnow().timestamp(),
"url": sentry_url,
"region_url": region_url,
"org": org_slug,
}
secret = b64encode(secrets.token_bytes(nbytes=32)).decode("ascii").rstrip("=")
json_str = json.dumps(payload)
payload_encoded = base64_encode_str(json_str)
return f"{SENTRY_ORG_AUTH_TOKEN_PREFIX}{payload_encoded}_{secret}"
def parse_token(token: str) -> dict[str, Any] | None:
if not token.startswith(SENTRY_ORG_AUTH_TOKEN_PREFIX) or token.count("_") != 2:
return None
payload_hashed = token[len(SENTRY_ORG_AUTH_TOKEN_PREFIX) : token.rindex("_")]
try:
payload_str = b64decode((payload_hashed).encode("ascii")).decode("ascii")
payload = json.loads(payload_str)
if not payload.get("iat"):
return None
return payload
except Exception:
return None
def base64_encode_str(s: str) -> str:
return b64encode(s.encode("ascii")).decode("ascii")
def hash_token(token: str) -> str:
return hashlib.sha256_text(token).hexdigest()
| SystemUrlPrefixMissingException |
python | tensorflow__tensorflow | tensorflow/dtensor/python/tests/layout_test.py | {
"start": 16710,
"end": 23041
} | class ____(test_util.DTensorBaseTest):
def setUp(self):
super().setUp()
global_ids = test_util.create_device_ids_array((2, 2))
local_ids = np.ravel(global_ids).tolist()
mesh_dict = { # pylint: disable=g-complex-comprehension
device: layout.Mesh(
[_MESH_DIM_X, _MESH_DIM_Y],
global_ids,
local_ids,
test_util.create_device_list((2, 2), device),
)
for device in ('CPU', 'GPU', 'TPU')
}
self.mesh = self.configTestMesh(mesh_dict)
# 1D Layouts
self.x_layout = layout.Layout.batch_sharded(self.mesh, _MESH_DIM_X, rank=1)
self.y_layout = layout.Layout.batch_sharded(self.mesh, _MESH_DIM_Y, rank=1)
# 2D Layouts
self.unsharded_unsharded_layout = layout.Layout.replicated(
self.mesh, rank=2
)
self.x_unsharded_layout = layout.Layout.batch_sharded(
self.mesh, _MESH_DIM_X, rank=2
)
self.unsharded_x_layout = layout.Layout.inner_sharded(
self.mesh, _MESH_DIM_X, rank=2
)
@combinations.generate(
combinations.combine(is_graph=[False, True], is_replicated=[False, True])
)
def test_relayout(self, is_graph, is_replicated):
inp = stateless_random_ops.stateless_random_uniform([4, 4], seed=[0, 1])
if is_replicated:
to_layout = self.unsharded_unsharded_layout
else:
to_layout = self.x_unsharded_layout
def do_relayout():
return api.relayout(inp, to_layout)
if is_graph:
relayout_fn = polymorphic_function.function(do_relayout)
self.assertRaisesRegex(
errors_impl.InvalidArgumentError,
"No OpKernel was registered to support Op 'Relayout'",
relayout_fn,
)
else:
self.assertDTensorEqual(inp, to_layout, do_relayout())
@combinations.generate(combinations.combine(is_graph=[False, True]))
def test_relayout_to_parted(self, is_graph):
data = np.array([1, 2, 3, 4.0], dtype='f4')
inp = api.relayout(data, self.y_layout)
def do_relayout():
return api.relayout(inp, self.y_layout.to_parted())
if is_graph:
do_relayout = polymorphic_function.function(do_relayout)
with api.default_mesh(self.mesh):
result = do_relayout()
self.assertDTensorEqual(data, self.y_layout.to_parted(), result)
@combinations.generate(combinations.combine(is_graph=[False, True]))
def test_relayout_like_simple(self, is_graph):
data = np.array([1, 2, 3, 4.0], dtype='f4')
inp = api.relayout(data, self.y_layout)
inp_layout = api.relayout(data, self.x_layout)
def do_relayout():
return api.relayout_like(inp, inp_layout)
if is_graph:
do_relayout = polymorphic_function.function(do_relayout)
with api.default_mesh(self.mesh):
result = do_relayout()
self.assertDTensorEqual(data, self.x_layout, result)
def test_relayout_like_init_scope(self):
data = np.array([1, 2, 3, 4.0], dtype='f4')
inp = api.relayout(data, self.y_layout)
inp_layout = api.relayout(data, self.x_layout)
@polymorphic_function.function
def do_relayout(x):
with ops.init_scope():
return api.relayout_like(inp, x)
with api.default_mesh(self.mesh):
with self.assertRaisesRegex(
TypeError, 'is out of scope and cannot be used here'
):
result = do_relayout(inp_layout)
result.numpy()
def test_nested_relayout_gradient_preserves_layout(self):
# Test that nesting gradient tapes with relayouts preserves the layout of
# the original DTensor input. The second-order gradient should have a layout
# equivalent to the original input, even if the inner gradient tape
# relayouts the DTensor to a different layout.
@polymorphic_function.function
def inner(x):
with backprop.GradientTape() as tape:
tape.watch(x)
t = x * 1.0
t = api.relayout(t, self.unsharded_x_layout)
cube = t * t * t
grad = tape.gradient(cube, x)
return grad
@polymorphic_function.function
def outer(x):
with backprop.GradientTape() as tape:
tape.watch(x)
t = api.relayout(x, self.x_unsharded_layout)
grad = inner(t)
out = grad + t
out_grad = tape.gradient(out, x)
return out_grad
a = stateless_random_ops.stateless_random_uniform([8, 8], seed=[0, 1])
a_dt = api.relayout(a, self.unsharded_unsharded_layout)
with ops.device_v2(api.device_name()):
inner_grad = inner(a_dt)
outer_grad = outer(a_dt)
self.assertDTensorEqual(
3 * a * a, self.unsharded_unsharded_layout, inner_grad
)
self.assertDTensorEqual(
6 * a + 1, self.unsharded_unsharded_layout, outer_grad
)
def test_wus_using_relayout(self):
sharded_layout = layout.Layout.batch_sharded(self.mesh, _MESH_DIM_X, rank=2)
w = stateless_random_ops.stateless_random_uniform(
[4, 4], seed=[0, 1], dtype=dtypes.float32
)
sharded_w = api.relayout(w, sharded_layout)
replicated_layout = layout.Layout(
[layout.UNSHARDED, layout.UNSHARDED], mesh=self.mesh
)
@polymorphic_function.function
def func_with_relayout(t):
with backprop.GradientTape() as tape:
tape.watch(t)
t = t + t
out = api.relayout(t, replicated_layout)
loss = math_ops.reduce_sum(out)
grad = tape.gradient(loss, t)
t = t - grad
return t
func_with_relayout(sharded_w)
@combinations.generate(
combinations.combine(size=[16, 4096], is_graph=[False, True])
)
def test_call_with_layout(self, size, is_graph):
layout_x = layout.Layout.batch_sharded(
self.mesh, batch_dim=_MESH_DIM_X, rank=1
)
layout_y = layout.Layout.batch_sharded(
self.mesh, batch_dim=_MESH_DIM_Y, rank=1
)
expected = array_ops.zeros(shape=[size])
def func():
tensor_x = api.call_with_layout(array_ops.zeros, layout_x, shape=[size])
tensor_y = api.call_with_layout(array_ops.zeros, layout_y, shape=[size])
return tensor_x, tensor_y
if is_graph:
func = polymorphic_function.function(func)
with api.default_mesh(self.mesh):
tensor_x, tensor_y = func()
self.assertDTensorEqual(expected, layout_x, tensor_x)
self.assertDTensorEqual(expected, layout_y, tensor_y)
if __name__ == '__main__':
test.main()
| RelayoutTest |
python | scipy__scipy | scipy/special/tests/test_spherical_bessel.py | {
"start": 10843,
"end": 11042
} | class ____(SphericalDerivativesTestCase):
def f(self, n, z):
return spherical_kn(n, z)
def df(self, n, z):
return spherical_kn(n, z, derivative=True)
| TestSphericalKnDerivatives |
python | spyder-ide__spyder | external-deps/python-lsp-server/pylsp/lsp.py | {
"start": 898,
"end": 958
} | class ____:
PlainText = 1
Snippet = 2
| InsertTextFormat |
python | pyqtgraph__pyqtgraph | pyqtgraph/widgets/TreeWidget.py | {
"start": 81,
"end": 8940
} | class ____(QtWidgets.QTreeWidget):
"""Extends QTreeWidget to allow internal drag/drop with widgets in the tree.
Also maintains the expanded state of subtrees as they are moved.
This class demonstrates the absurd lengths one must go to to make drag/drop work."""
sigItemMoved = QtCore.Signal(object, object, object) # (item, parent, index)
sigItemCheckStateChanged = QtCore.Signal(object, object)
sigItemTextChanged = QtCore.Signal(object, object)
sigColumnCountChanged = QtCore.Signal(object, object) # self, count
def __init__(self, parent=None):
QtWidgets.QTreeWidget.__init__(self, parent)
# wrap this item so that we can propagate tree change information
# to children.
self._invRootItem = InvisibleRootItem(QtWidgets.QTreeWidget.invisibleRootItem(self))
self.setAcceptDrops(True)
self.setDragEnabled(True)
self.setEditTriggers(QtWidgets.QAbstractItemView.EditTrigger.EditKeyPressed|QtWidgets.QAbstractItemView.EditTrigger.SelectedClicked)
self.placeholders = []
self.childNestingLimit = None
self.itemClicked.connect(self._itemClicked)
def setItemWidget(self, item, col, wid):
"""
Overrides QTreeWidget.setItemWidget such that widgets are added inside an invisible wrapper widget.
This makes it possible to move the item in and out of the tree without its widgets being automatically deleted.
"""
w = QtWidgets.QWidget() ## foster parent / surrogate child widget
l = QtWidgets.QVBoxLayout()
l.setContentsMargins(0,0,0,0)
w.setLayout(l)
w.setSizePolicy(wid.sizePolicy())
w.setMinimumHeight(wid.minimumHeight())
w.setMinimumWidth(wid.minimumWidth())
l.addWidget(wid)
w.realChild = wid
self.placeholders.append(w)
QtWidgets.QTreeWidget.setItemWidget(self, item, col, w)
def itemWidget(self, item, col):
w = QtWidgets.QTreeWidget.itemWidget(self, item, col)
if w is not None and hasattr(w, 'realChild'):
w = w.realChild
return w
def dropMimeData(self, parent, index, data, action):
item = self.currentItem()
p = parent
#print "drop", item, "->", parent, index
while True:
if p is None:
break
if p is item:
return False
#raise Exception("Can not move item into itself.")
p = p.parent()
if not self.itemMoving(item, parent, index):
return False
currentParent = item.parent()
if currentParent is None:
currentParent = self.invisibleRootItem()
if parent is None:
parent = self.invisibleRootItem()
if currentParent is parent and index > parent.indexOfChild(item):
index -= 1
self.prepareMove(item)
currentParent.removeChild(item)
#print " insert child to index", index
parent.insertChild(index, item) ## index will not be correct
self.setCurrentItem(item)
self.recoverMove(item)
#self.emit(QtCore.SIGNAL('itemMoved'), item, parent, index)
self.sigItemMoved.emit(item, parent, index)
return True
def itemMoving(self, item, parent, index):
"""Called when item has been dropped elsewhere in the tree.
Return True to accept the move, False to reject."""
return True
def prepareMove(self, item):
item.__widgets = []
item.__expanded = item.isExpanded()
for i in range(self.columnCount()):
w = self.itemWidget(item, i)
item.__widgets.append(w)
if w is None:
continue
w.setParent(None)
for i in range(item.childCount()):
self.prepareMove(item.child(i))
def recoverMove(self, item):
for i in range(self.columnCount()):
w = item.__widgets[i]
if w is None:
continue
self.setItemWidget(item, i, w)
for i in range(item.childCount()):
self.recoverMove(item.child(i))
item.setExpanded(False) ## Items do not re-expand correctly unless they are collapsed first.
QtWidgets.QApplication.instance().processEvents()
item.setExpanded(item.__expanded)
def collapseTree(self, item):
item.setExpanded(False)
for i in range(item.childCount()):
self.collapseTree(item.child(i))
def removeTopLevelItem(self, item):
for i in range(self.topLevelItemCount()):
if self.topLevelItem(i) is item:
self.takeTopLevelItem(i)
return
raise Exception("Item '%s' not in top-level items." % str(item))
def listAllItems(self, item=None):
items = []
if item is not None:
items.append(item)
else:
item = self.invisibleRootItem()
for cindex in range(item.childCount()):
foundItems = self.listAllItems(item=item.child(cindex))
for f in foundItems:
items.append(f)
return items
def dropEvent(self, ev):
super().dropEvent(ev)
self.updateDropFlags()
def updateDropFlags(self):
### intended to put a limit on how deep nests of children can go.
### self.childNestingLimit is upheld when moving items without children, but if the item being moved has children/grandchildren, the children/grandchildren
### can end up over the childNestingLimit.
if self.childNestingLimit is None:
pass # enable drops in all items (but only if there are drops that aren't enabled? for performance...)
else:
items = self.listAllItems()
for item in items:
parentCount = 0
p = item.parent()
while p is not None:
parentCount += 1
p = p.parent()
if parentCount >= self.childNestingLimit:
item.setFlags(item.flags() & (~QtCore.Qt.ItemFlag.ItemIsDropEnabled))
else:
item.setFlags(item.flags() | QtCore.Qt.ItemFlag.ItemIsDropEnabled)
@staticmethod
def informTreeWidgetChange(item):
if hasattr(item, 'treeWidgetChanged'):
item.treeWidgetChanged()
for i in range(item.childCount()):
TreeWidget.informTreeWidgetChange(item.child(i))
def addTopLevelItem(self, item):
QtWidgets.QTreeWidget.addTopLevelItem(self, item)
self.informTreeWidgetChange(item)
def addTopLevelItems(self, items):
QtWidgets.QTreeWidget.addTopLevelItems(self, items)
for item in items:
self.informTreeWidgetChange(item)
def insertTopLevelItem(self, index, item):
QtWidgets.QTreeWidget.insertTopLevelItem(self, index, item)
self.informTreeWidgetChange(item)
def insertTopLevelItems(self, index, items):
QtWidgets.QTreeWidget.insertTopLevelItems(self, index, items)
for item in items:
self.informTreeWidgetChange(item)
def takeTopLevelItem(self, index):
item = self.topLevelItem(index)
if item is not None:
self.prepareMove(item)
item = QtWidgets.QTreeWidget.takeTopLevelItem(self, index)
self.prepareMove(item)
self.informTreeWidgetChange(item)
return item
def topLevelItems(self):
return [self.topLevelItem(i) for i in range(self.topLevelItemCount())]
def clear(self):
items = self.topLevelItems()
for item in items:
self.prepareMove(item)
QtWidgets.QTreeWidget.clear(self)
## Why do we want to do this? It causes RuntimeErrors.
#for item in items:
#self.informTreeWidgetChange(item)
def invisibleRootItem(self):
return self._invRootItem
def itemFromIndex(self, index):
"""Return the item and column corresponding to a QModelIndex.
"""
col = index.column()
rows = []
while index.row() >= 0:
rows.insert(0, index.row())
index = index.parent()
item = self.topLevelItem(rows[0])
for row in rows[1:]:
item = item.child(row)
return item, col
def setColumnCount(self, c):
QtWidgets.QTreeWidget.setColumnCount(self, c)
self.sigColumnCountChanged.emit(self, c)
@QtCore.Slot(QtWidgets.QTreeWidgetItem, int)
def _itemClicked(self, item, col):
if hasattr(item, 'itemClicked'):
item.itemClicked(col)
| TreeWidget |
python | GoogleCloudPlatform__python-docs-samples | generative_ai/chat_completions/chat_completions_credentials_refresher.py | {
"start": 837,
"end": 2265
} | class ____:
def __init__(self, **kwargs: Any) -> None:
# Set a placeholder key here
self.client = openai.OpenAI(**kwargs, api_key="PLACEHOLDER")
self.creds, self.project = google.auth.default(
scopes=["https://www.googleapis.com/auth/cloud-platform"]
)
def __getattr__(self, name: str) -> Any:
if not self.creds.valid:
self.creds.refresh(google.auth.transport.requests.Request())
if not self.creds.valid:
raise RuntimeError("Unable to refresh auth")
self.client.api_key = self.creds.token
return getattr(self.client, name)
# [END generativeaionvertexai_credentials_refresher]
def generate_text(project_id: str, location: str = "us-central1") -> object:
# [START generativeaionvertexai_credentials_refresher]
# TODO(developer): Update and un-comment below lines
# project_id = "PROJECT_ID"
# location = "us-central1"
client = OpenAICredentialsRefresher(
base_url=f"https://{location}-aiplatform.googleapis.com/v1/projects/{project_id}/locations/{location}/endpoints/openapi",
)
response = client.chat.completions.create(
model="google/gemini-2.0-flash-001",
messages=[{"role": "user", "content": "Why is the sky blue?"}],
)
print(response)
# [END generativeaionvertexai_credentials_refresher]
return response
| OpenAICredentialsRefresher |
python | pytorch__pytorch | torch/_export/db/examples/scalar_output.py | {
"start": 117,
"end": 543
} | class ____(torch.nn.Module):
"""
Returning scalar values from the graph is supported, in addition to Tensor
outputs. Symbolic shapes are captured and rank is specialized.
"""
def __init__(self) -> None:
super().__init__()
def forward(self, x):
return x.shape[1] + 1
example_args = (x,)
tags = {"torch.dynamic-shape"}
dynamic_shapes = {"x": {1: dim1_x}}
model = ScalarOutput()
| ScalarOutput |
python | pytorch__pytorch | torchgen/gen_schema_utils.py | {
"start": 2202,
"end": 2481
} | class ____:
@staticmethod
def from_example(
name: str, obj: Any, default: str | None, annotation: Annotation | None
) -> Argument:
return Argument(
name, TypeGen.from_example(obj), default=default, annotation=annotation
)
| ArgumentGen |
python | doocs__leetcode | solution/0200-0299/0214.Shortest Palindrome/Solution2.py | {
"start": 0,
"end": 469
} | class ____:
def shortestPalindrome(self, s: str) -> str:
t = s + "#" + s[::-1] + "$"
n = len(t)
next = [0] * n
next[0] = -1
i, j = 2, 0
while i < n:
if t[i - 1] == t[j]:
j += 1
next[i] = j
i += 1
elif j:
j = next[j]
else:
next[i] = 0
i += 1
return s[::-1][: -next[-1]] + s
| Solution |
python | kamyu104__LeetCode-Solutions | Python/the-k-weakest-rows-in-a-matrix.py | {
"start": 33,
"end": 794
} | class ____(object):
def kWeakestRows(self, mat, k):
"""
:type mat: List[List[int]]
:type k: int
:rtype: List[int]
"""
result, lookup = [], set()
for j in xrange(len(mat[0])):
for i in xrange(len(mat)):
if mat[i][j] or i in lookup:
continue
lookup.add(i)
result.append(i)
if len(result) == k:
return result
for i in xrange(len(mat)):
if i in lookup:
continue
lookup.add(i)
result.append(i)
if len(result) == k:
break
return result
# Time: O(m * n)
# Space: O(k)
import collections
| Solution |
python | huggingface__transformers | src/transformers/models/altclip/modeling_altclip.py | {
"start": 17898,
"end": 19284
} | class ____(nn.Module):
def __init__(self, config):
super().__init__()
self.dense = nn.Linear(config.hidden_size, config.hidden_size)
self.activation = nn.Tanh()
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
# We "pool" the model by simply taking the hidden state corresponding
# to the first token.
first_token_tensor = hidden_states[:, 0]
pooled_output = self.dense(first_token_tensor)
pooled_output = self.activation(pooled_output)
return pooled_output
# Copied from transformers.models.siglip.modeling_siglip.eager_attention_forward
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(-1, -2)) * 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
| AltRobertaPooler |
python | django__django | tests/test_runner_apps/sample/tests_sample.py | {
"start": 259,
"end": 361
} | class ____(DjangoTestCase):
def test_sample(self):
self.assertEqual(1, 1)
| TestDjangoTestCase |
python | kamyu104__LeetCode-Solutions | Python/get-maximum-in-generated-array.py | {
"start": 55,
"end": 507
} | class ____(object):
def getMaximumGenerated(self, n):
"""
:type n: int
:rtype: int
"""
if n+1 > len(dp):
for i in xrange(len(nums), n+1):
if i%2 == 0:
nums.append(nums[i//2])
else:
nums.append(nums[i//2] + nums[i//2+1])
dp.append(max(dp[-1], nums[-1]))
return dp[n]
# Time: O(n)
# Space: O(n)
| Solution |
python | xlwings__xlwings | xlwings/com_server.py | {
"start": 1765,
"end": 2949
} | class ____:
_public_methods_ = ["Next", "Skip", "Reset", "Clone"]
def __init__(self, gen):
self.iter = gen.__iter__()
def _query_interface_(self, iid):
if iid == pythoncom.IID_IEnumVARIANT:
return 1
def Next(self, count):
r = []
try:
r.append(ToVariant(next(self.iter)))
except StopIteration:
pass
return r
def Skip(self, count):
raise win32com.server.exception.COMException(scode=0x80004001) # E_NOTIMPL
def Reset(self):
raise win32com.server.exception.COMException(scode=0x80004001) # E_NOTIMPL
def Clone(self):
raise win32com.server.exception.COMException(scode=0x80004001) # E_NOTIMPL
PyIDispatch = pythoncom.TypeIIDs[pythoncom.IID_IDispatch]
def FromVariant(var):
try:
obj = win32com.server.util.unwrap(var).obj
except: # noqa: E722
obj = var
if type(obj) is PyIDispatch:
obj = win32com.client.Dispatch(
obj, userName=obj.GetTypeInfo().GetDocumentation(-1)[0]
)
return obj
def ToVariant(obj):
return win32com.server.util.wrap(XLPythonObject(obj))
| XLPythonEnumerator |
python | arrow-py__arrow | tests/test_locales.py | {
"start": 149767,
"end": 153911
} | class ____:
def test_singles_mk(self):
assert self.locale._format_timeframe("second", 1) == "бір секунд"
assert self.locale._format_timeframe("minute", 1) == "бір минут"
assert self.locale._format_timeframe("hour", 1) == "бір сағат"
assert self.locale._format_timeframe("day", 1) == "бір күн"
assert self.locale._format_timeframe("week", 1) == "бір апта"
assert self.locale._format_timeframe("month", 1) == "бір ай"
assert self.locale._format_timeframe("year", 1) == "бір жыл"
def test_describe_mk(self):
assert self.locale.describe("second", only_distance=True) == "бір секунд"
assert self.locale.describe("second", only_distance=False) == "бір секунд кейін"
assert self.locale.describe("minute", only_distance=True) == "бір минут"
assert self.locale.describe("minute", only_distance=False) == "бір минут кейін"
assert self.locale.describe("hour", only_distance=True) == "бір сағат"
assert self.locale.describe("hour", only_distance=False) == "бір сағат кейін"
assert self.locale.describe("day", only_distance=True) == "бір күн"
assert self.locale.describe("day", only_distance=False) == "бір күн кейін"
assert self.locale.describe("week", only_distance=True) == "бір апта"
assert self.locale.describe("week", only_distance=False) == "бір апта кейін"
assert self.locale.describe("month", only_distance=True) == "бір ай"
assert self.locale.describe("month", only_distance=False) == "бір ай кейін"
assert self.locale.describe("year", only_distance=True) == "бір жыл"
assert self.locale.describe("year", only_distance=False) == "бір жыл кейін"
def test_relative_mk(self):
assert self.locale._format_relative("қазір", "now", 0) == "қазір"
assert (
self.locale._format_relative("1 секунд", "seconds", 1) == "1 секунд кейін"
)
assert (
self.locale._format_relative("1 секунд", "seconds", -1) == "1 секунд бұрын"
)
assert self.locale._format_relative("1 минут", "minutes", 1) == "1 минут кейін"
assert self.locale._format_relative("1 минут", "minutes", -1) == "1 минут бұрын"
assert self.locale._format_relative("1 сағат", "hours", 1) == "1 сағат кейін"
assert self.locale._format_relative("1 сағат", "hours", -1) == "1 сағат бұрын"
assert self.locale._format_relative("1 күн", "days", 1) == "1 күн кейін"
assert self.locale._format_relative("1 күн", "days", -1) == "1 күн бұрын"
assert self.locale._format_relative("1 апта", "weeks", 1) == "1 апта кейін"
assert self.locale._format_relative("1 апта", "weeks", -1) == "1 апта бұрын"
assert self.locale._format_relative("1 ай", "months", 1) == "1 ай кейін"
assert self.locale._format_relative("1 ай", "months", -1) == "1 ай бұрын"
assert self.locale._format_relative("1 жыл", "years", 1) == "1 жыл кейін"
assert self.locale._format_relative("1 жыл", "years", -1) == "1 жыл бұрын"
def test_plurals_mk(self):
assert self.locale._format_timeframe("now", 0) == "қазір"
assert self.locale._format_timeframe("second", 1) == "бір секунд"
assert self.locale._format_timeframe("seconds", 30) == "30 секунд"
assert self.locale._format_timeframe("minute", 1) == "бір минут"
assert self.locale._format_timeframe("minutes", 40) == "40 минут"
assert self.locale._format_timeframe("hour", 1) == "бір сағат"
assert self.locale._format_timeframe("hours", 23) == "23 сағат"
assert self.locale._format_timeframe("days", 12) == "12 күн"
assert self.locale._format_timeframe("week", 1) == "бір апта"
assert self.locale._format_timeframe("weeks", 38) == "38 апта"
assert self.locale._format_timeframe("month", 1) == "бір ай"
assert self.locale._format_timeframe("months", 11) == "11 ай"
assert self.locale._format_timeframe("year", 1) == "бір жыл"
assert self.locale._format_timeframe("years", 12) == "12 жыл"
@pytest.mark.usefixtures("lang_locale")
| TestKazakhLocale |
python | faif__python-patterns | patterns/behavioral/command.py | {
"start": 983,
"end": 1442
} | class ____:
"""
A command to hide a file given its name
"""
def __init__(self) -> None:
# an array of files hidden, to undo them as needed
self._hidden_files: List[str] = []
def execute(self, filename: str) -> None:
print(f"hiding {filename}")
self._hidden_files.append(filename)
def undo(self) -> None:
filename = self._hidden_files.pop()
print(f"un-hiding {filename}")
| HideFileCommand |
python | conda__conda | conda/exceptions.py | {
"start": 7579,
"end": 8626
} | class ____(ClobberError):
def __init__(
self,
target_path: PathType,
colliding_dist_being_linked: PackageRecord | str,
context: Context,
):
message = dals(
"""
The package '%(colliding_dist_being_linked)s' cannot be installed due to a
path collision for '%(target_path)s'.
This path already exists in the target prefix, and it won't be removed
by an uninstall action in this transaction. The path is one that conda
doesn't recognize. It may have been created by another package manager.
"""
)
if context.path_conflict == PathConflict.prevent:
message += (
"If you'd like to proceed anyway, re-run the command with "
"the `--clobber` flag.\n."
)
super().__init__(
message,
context.path_conflict,
target_path=target_path,
colliding_dist_being_linked=colliding_dist_being_linked,
)
| UnknownPackageClobberError |
python | doocs__leetcode | solution/1900-1999/1971.Find if Path Exists in Graph/Solution.py | {
"start": 0,
"end": 483
} | class ____:
def validPath(
self, n: int, edges: List[List[int]], source: int, destination: int
) -> bool:
def dfs(i: int) -> bool:
if i == destination:
return True
if i in vis:
return False
return any(dfs(j) for j in g[i])
g = [[] for _ in range(n)]
for u, v in edges:
g[u].append(v)
g[v].append(u)
vis = set()
return dfs(source)
| Solution |
python | readthedocs__readthedocs.org | readthedocs/projects/migrations/0152_create_gh_app_integration.py | {
"start": 862,
"end": 1089
} | class ____(migrations.Migration):
safe = Safe.after_deploy()
dependencies = [
("projects", "0151_addons_linkpreviews_selector"),
]
operations = [
migrations.RunPython(forwards_func),
]
| Migration |
python | tensorflow__tensorflow | tensorflow/python/module/module_test.py | {
"start": 14552,
"end": 15374
} | class ____(module.Module):
def __init__(self):
super().__init__()
self._setter_scope_name = None
@property
@module.Module.with_name_scope
def some_property(self):
getter_scope_name = get_name_scope()
return getter_scope_name, self._setter_scope_name
@some_property.setter
@module.Module.with_name_scope
def some_property(self, my_property):
self._setter_scope_name = get_name_scope()
@property
def no_name_scope_property(self):
getter_scope_name = get_name_scope()
return getter_scope_name, self._setter_scope_name
@no_name_scope_property.setter
def no_name_scope_property(self, my_property):
self._setter_scope_name = get_name_scope()
NamedPair = collections.namedtuple("NamedPair", ("first", "second"))
mk_index_dict = lambda v: dict(enumerate(v))
| PropertyModule |
python | getsentry__sentry | tests/sentry/integrations/msteams/test_webhook.py | {
"start": 1162,
"end": 23167
} | class ____(APITestCase):
@pytest.fixture(autouse=True)
def _setup_metric_patch(self) -> Generator[None]:
with mock.patch("sentry.shared_integrations.client.base.metrics") as self.metrics:
yield
def setUp(self) -> None:
super().setUp()
responses.add(
responses.GET,
"https://login.botframework.com/v1/.well-known/openidconfiguration",
json=OPEN_ID_CONFIG,
)
responses.add(
responses.GET,
OPEN_ID_CONFIG["jwks_uri"],
json=WELL_KNOWN_KEYS,
)
@responses.activate
@mock.patch("sentry.utils.jwt.decode")
@mock.patch("time.time")
def test_generic_event(self, mock_time: MagicMock, mock_decode: MagicMock) -> None:
mock_time.return_value = 1594839999 + 60
mock_decode.return_value = DECODED_TOKEN
resp = self.client.post(
path=webhook_url,
data=GENERIC_EVENT,
format="json",
HTTP_AUTHORIZATION=f"Bearer {TOKEN}",
)
assert resp.status_code == 204
mock_decode.assert_called_with(
TOKEN, mock.ANY, audience="msteams-client-id", algorithms=["RS256"]
)
assert (
responses.calls[0].request.url
== "https://login.botframework.com/v1/.well-known/openidconfiguration"
)
assert (
responses.calls[1].request.url == "https://login.botframework.com/v1/.well-known/keys"
)
@responses.activate
def test_post_empty_token(self) -> None:
resp = self.client.post(
path=webhook_url,
data=EXAMPLE_TEAM_MEMBER_ADDED,
format="json",
)
assert resp.data["detail"] == "Authorization header required"
assert resp.status_code == 403
@responses.activate
@mock.patch("sentry.utils.jwt.decode")
def test_decode_token_fails(self, mock_decode: MagicMock) -> None:
mock_decode.side_effect = jwt.DecodeError("fail")
resp = self.client.post(
path=webhook_url,
data=EXAMPLE_TEAM_MEMBER_ADDED,
format="json",
HTTP_AUTHORIZATION=f"Bearer {TOKEN}",
)
assert resp.data["detail"] == "Could not validate JWT. Got fail"
assert resp.status_code == 403
@responses.activate
@mock.patch("sentry.utils.jwt.decode")
def test_iss_does_not_match(self, mock_decode: MagicMock) -> None:
bad_token = DECODED_TOKEN.copy()
bad_token["iss"] = "bad"
mock_decode.return_value = bad_token
resp = self.client.post(
path=webhook_url,
data=EXAMPLE_TEAM_MEMBER_ADDED,
format="json",
HTTP_AUTHORIZATION=f"Bearer {TOKEN}",
)
assert resp.data["detail"] == "The field iss does not match"
assert resp.status_code == 403
@responses.activate
@mock.patch("sentry.utils.jwt.decode")
def test_service_url_does_not_match(self, mock_decode: MagicMock) -> None:
bad_token = DECODED_TOKEN.copy()
bad_token["serviceurl"] = "bad"
mock_decode.return_value = bad_token
resp = self.client.post(
path=webhook_url,
data=EXAMPLE_TEAM_MEMBER_ADDED,
format="json",
HTTP_AUTHORIZATION=f"Bearer {TOKEN}",
)
assert resp.data["detail"] == "The field serviceUrl does not match"
assert resp.status_code == 403
@responses.activate
@mock.patch("sentry.utils.jwt.decode")
@mock.patch("time.time")
def test_expired_token(self, mock_time: MagicMock, mock_decode: MagicMock) -> None:
mock_time.return_value = 1594839999 + 6 * 60
mock_decode.return_value = DECODED_TOKEN
resp = self.client.post(
path=webhook_url,
data=EXAMPLE_TEAM_MEMBER_ADDED,
format="json",
HTTP_AUTHORIZATION=f"Bearer {TOKEN}",
)
assert resp.data["detail"] == "Token is expired"
assert resp.status_code == 403
@responses.activate
@mock.patch("sentry.utils.jwt.decode")
@mock.patch("time.time")
def test_member_added(self, mock_time: MagicMock, mock_decode: MagicMock) -> None:
access_json = {"expires_in": 86399, "access_token": "my_token"}
responses.add(
responses.POST,
"https://login.microsoftonline.com/botframework.com/oauth2/v2.0/token",
json=access_json,
)
responses.add(
responses.POST,
"https://smba.trafficmanager.net/amer/v3/conversations/%s/activities" % team_id,
json={},
)
mock_time.return_value = 1594839999 + 60
mock_decode.return_value = DECODED_TOKEN
resp = self.client.post(
path=webhook_url,
data=EXAMPLE_TEAM_MEMBER_ADDED,
format="json",
HTTP_AUTHORIZATION=f"Bearer {TOKEN}",
)
assert resp.status_code == 201
assert responses.calls[2].request.body == urlencode(
{
"client_id": "msteams-client-id",
"client_secret": "msteams-client-secret",
"grant_type": "client_credentials",
"scope": "https://api.botframework.com/.default",
}
)
assert (
responses.calls[3].request.url
== "https://smba.trafficmanager.net/amer/v3/conversations/%s/activities" % team_id
)
assert "Bearer my_token" in responses.calls[3].request.headers["Authorization"]
@responses.activate
@mock.patch("sentry.utils.jwt.decode")
@mock.patch("time.time")
def test_different_member_added(self, mock_time: MagicMock, mock_decode: MagicMock) -> None:
access_json = {"expires_in": 86399, "access_token": "my_token"}
responses.add(
responses.POST,
"https://login.microsoftonline.com/botframework.com/oauth2/v2.0/token",
json=access_json,
)
responses.add(
responses.POST,
"https://smba.trafficmanager.net/amer/v3/conversations/%s/activities" % team_id,
json={},
)
different_member_added = deepcopy(EXAMPLE_TEAM_MEMBER_ADDED)
different_member_added["membersAdded"][0]["id"] = "28:another-id"
mock_time.return_value = 1594839999 + 60
mock_decode.return_value = DECODED_TOKEN
resp = self.client.post(
path=webhook_url,
data=different_member_added,
format="json",
HTTP_AUTHORIZATION=f"Bearer {TOKEN}",
)
assert resp.status_code == 204
assert len(responses.calls) == 2
@responses.activate
@mock.patch("sentry.utils.jwt.decode")
@mock.patch("time.time")
def test_member_removed(self, mock_time: MagicMock, mock_decode: MagicMock) -> None:
with assume_test_silo_mode(SiloMode.CONTROL):
integration = self.create_provider_integration(external_id=team_id, provider="msteams")
mock_time.return_value = 1594839999 + 60
mock_decode.return_value = DECODED_TOKEN
resp = self.client.post(
path=webhook_url,
data=EXAMPLE_TEAM_MEMBER_REMOVED,
format="json",
HTTP_AUTHORIZATION=f"Bearer {TOKEN}",
)
assert resp.status_code == 204
with assume_test_silo_mode(SiloMode.CONTROL):
assert not Integration.objects.filter(id=integration.id)
@responses.activate
@mock.patch("sentry.utils.jwt.decode")
@mock.patch("time.time")
def test_invalid_silo_member_removed(
self, mock_time: MagicMock, mock_decode: MagicMock
) -> None:
with assume_test_silo_mode(SiloMode.CONTROL):
integration = self.create_provider_integration(external_id=team_id, provider="msteams")
mock_time.return_value = 1594839999 + 60
mock_decode.return_value = DECODED_TOKEN
with override_settings(SILO_MODE=SiloMode.CONTROL):
resp = self.client.post(
path=webhook_url,
data=EXAMPLE_TEAM_MEMBER_REMOVED,
format="json",
HTTP_AUTHORIZATION=f"Bearer {TOKEN}",
)
assert resp.status_code == 400
with assume_test_silo_mode(SiloMode.CONTROL):
assert Integration.objects.filter(id=integration.id)
@responses.activate
@mock.patch("sentry.utils.jwt.decode")
@mock.patch("time.time")
def test_different_member_removed(self, mock_time: MagicMock, mock_decode: MagicMock) -> None:
different_member_removed = deepcopy(EXAMPLE_TEAM_MEMBER_REMOVED)
different_member_removed["membersRemoved"][0]["id"] = "28:another-id"
with assume_test_silo_mode(SiloMode.CONTROL):
integration = self.create_provider_integration(external_id=team_id, provider="msteams")
mock_time.return_value = 1594839999 + 60
mock_decode.return_value = DECODED_TOKEN
resp = self.client.post(
path=webhook_url,
data=different_member_removed,
format="json",
HTTP_AUTHORIZATION=f"Bearer {TOKEN}",
)
assert resp.status_code == 204
with assume_test_silo_mode(SiloMode.CONTROL):
assert Integration.objects.filter(id=integration.id)
@responses.activate
@mock.patch("sentry.utils.jwt.decode")
@mock.patch("time.time")
def test_personal_member_added(self, mock_time: MagicMock, mock_decode: MagicMock) -> None:
access_json = {"expires_in": 86399, "access_token": "my_token"}
responses.add(
responses.POST,
"https://login.microsoftonline.com/botframework.com/oauth2/v2.0/token",
json=access_json,
)
responses.add(
responses.POST,
"https://smba.trafficmanager.net/amer/v3/conversations/%s/activities"
% EXAMPLE_PERSONAL_MEMBER_ADDED["conversation"]["id"],
json={},
)
mock_time.return_value = 1594839999 + 60
mock_decode.return_value = DECODED_TOKEN
resp = self.client.post(
path=webhook_url,
data=EXAMPLE_PERSONAL_MEMBER_ADDED,
format="json",
HTTP_AUTHORIZATION=f"Bearer {TOKEN}",
)
assert resp.status_code == 201
assert "Personal Installation of Sentry" in responses.calls[3].request.body.decode("utf-8")
assert "Bearer my_token" in responses.calls[3].request.headers["Authorization"]
@responses.activate
@mock.patch("sentry.utils.jwt.decode")
@mock.patch("time.time")
def test_mentioned(self, mock_time: MagicMock, mock_decode: MagicMock) -> None:
access_json = {"expires_in": 86399, "access_token": "my_token"}
responses.add(
responses.POST,
"https://login.microsoftonline.com/botframework.com/oauth2/v2.0/token",
json=access_json,
)
responses.add(
responses.POST,
"https://smba.trafficmanager.net/amer/v3/conversations/%s/activities"
% EXAMPLE_PERSONAL_MEMBER_ADDED["conversation"]["id"],
json={},
)
mock_time.return_value = 1594839999 + 60
mock_decode.return_value = DECODED_TOKEN
resp = self.client.post(
path=webhook_url,
data=EXAMPLE_MENTIONED,
format="json",
HTTP_AUTHORIZATION=f"Bearer {TOKEN}",
)
assert resp.status_code == 204
assert "Sentry for Microsoft Teams does not support any commands" in responses.calls[
3
].request.body.decode("utf-8")
assert "Bearer my_token" in responses.calls[3].request.headers["Authorization"]
@responses.activate
@mock.patch("sentry.utils.jwt.decode")
@mock.patch("time.time")
def test_different_user_mentioned(self, mock_time: MagicMock, mock_decode: MagicMock) -> None:
mock_time.return_value = 1594839999 + 60
mock_decode.return_value = DECODED_TOKEN
different_user_mentioned = deepcopy(EXAMPLE_MENTIONED)
different_user_mentioned["entities"][0]["mentioned"]["id"] = "28:another-id"
resp = self.client.post(
path=webhook_url,
data=different_user_mentioned,
format="json",
HTTP_AUTHORIZATION=f"Bearer {TOKEN}",
)
assert resp.status_code == 204
assert len(responses.calls) == 2
@responses.activate
@mock.patch("sentry.integrations.utils.metrics.EventLifecycle.record_event")
@mock.patch("sentry.utils.jwt.decode")
@mock.patch("time.time")
def test_unlink_user(
self, mock_time: MagicMock, mock_decode: MagicMock, mock_record: MagicMock
) -> None:
access_json = {"expires_in": 86399, "access_token": "my_token"}
responses.add(
responses.POST,
"https://login.microsoftonline.com/botframework.com/oauth2/v2.0/token",
json=access_json,
)
responses.add(
responses.POST,
"https://smba.trafficmanager.net/amer/v3/conversations/%s/activities"
% EXAMPLE_UNLINK_COMMAND["conversation"]["id"],
json={},
)
mock_time.return_value = 1594839999 + 60
mock_decode.return_value = DECODED_TOKEN
resp = self.client.post(
path=webhook_url,
data=EXAMPLE_UNLINK_COMMAND,
format="json",
HTTP_AUTHORIZATION=f"Bearer {TOKEN}",
)
assert resp.status_code == 204
assert "Click below to unlink your identity" in responses.calls[3].request.body.decode(
"utf-8"
)
assert "Bearer my_token" in responses.calls[3].request.headers["Authorization"]
assert_slo_metric(mock_record, EventLifecycleOutcome.SUCCESS)
@responses.activate
@mock.patch("sentry.integrations.utils.metrics.EventLifecycle.record_event")
@mock.patch("sentry.utils.jwt.decode")
@mock.patch("time.time")
def test_help_command(
self, mock_time: MagicMock, mock_decode: MagicMock, mock_record: MagicMock
) -> None:
other_command = deepcopy(EXAMPLE_UNLINK_COMMAND)
other_command["text"] = "Help"
access_json = {"expires_in": 86399, "access_token": "my_token"}
responses.add(
responses.POST,
"https://login.microsoftonline.com/botframework.com/oauth2/v2.0/token",
json=access_json,
)
responses.add(
responses.POST,
"https://smba.trafficmanager.net/amer/v3/conversations/%s/activities"
% other_command["conversation"]["id"],
json={},
)
mock_time.return_value = 1594839999 + 60
mock_decode.return_value = DECODED_TOKEN
resp = self.client.post(
path=webhook_url,
data=other_command,
format="json",
HTTP_AUTHORIZATION=f"Bearer {TOKEN}",
)
assert resp.status_code == 204
assert "Please use one of the following commands for Sentry" in responses.calls[
3
].request.body.decode("utf-8")
assert "Bearer my_token" in responses.calls[3].request.headers["Authorization"]
assert_slo_metric(mock_record, EventLifecycleOutcome.SUCCESS)
@responses.activate
@mock.patch("sentry.integrations.utils.metrics.EventLifecycle.record_event")
@mock.patch("sentry.utils.jwt.decode")
@mock.patch("time.time")
def test_link_command(
self, mock_time: MagicMock, mock_decode: MagicMock, mock_record: MagicMock
) -> None:
other_command = deepcopy(EXAMPLE_UNLINK_COMMAND)
other_command["text"] = "link"
access_json = {"expires_in": 86399, "access_token": "my_token"}
responses.add(
responses.POST,
"https://login.microsoftonline.com/botframework.com/oauth2/v2.0/token",
json=access_json,
)
responses.add(
responses.POST,
"https://smba.trafficmanager.net/amer/v3/conversations/%s/activities"
% other_command["conversation"]["id"],
json={},
)
mock_time.return_value = 1594839999 + 60
mock_decode.return_value = DECODED_TOKEN
resp = self.client.post(
path=webhook_url,
data=other_command,
format="json",
HTTP_AUTHORIZATION=f"Bearer {TOKEN}",
)
assert resp.status_code == 204
assert (
"Your Microsoft Teams identity will be linked to your Sentry account"
in responses.calls[3].request.body.decode("utf-8")
)
assert "Bearer my_token" in responses.calls[3].request.headers["Authorization"]
# Check if metrics is generated properly
calls = [
call("integrations.http_request", sample_rate=1.0, tags={"integration": "msteams"}),
call(
"integrations.http_response",
sample_rate=1.0,
tags={"integration": "msteams", "status": 200},
),
] * 4
assert self.metrics.incr.mock_calls == calls
assert_slo_metric(mock_record, EventLifecycleOutcome.SUCCESS)
@responses.activate
@mock.patch("sentry.integrations.utils.metrics.EventLifecycle.record_event")
@mock.patch("sentry.utils.jwt.decode")
@mock.patch("time.time")
def test_link_command_already_linked(
self, mock_time: MagicMock, mock_decode: MagicMock, mock_record: MagicMock
) -> None:
other_command = deepcopy(EXAMPLE_UNLINK_COMMAND)
other_command["text"] = "link"
with assume_test_silo_mode(SiloMode.CONTROL):
idp = self.create_identity_provider(type="msteams", external_id=team_id)
Identity.objects.create(
external_id=other_command["from"]["id"], idp=idp, user=self.user
)
access_json = {"expires_in": 86399, "access_token": "my_token"}
responses.add(
responses.POST,
"https://login.microsoftonline.com/botframework.com/oauth2/v2.0/token",
json=access_json,
)
responses.add(
responses.POST,
"https://smba.trafficmanager.net/amer/v3/conversations/%s/activities"
% other_command["conversation"]["id"],
json={},
)
mock_time.return_value = 1594839999 + 60
mock_decode.return_value = DECODED_TOKEN
resp = self.client.post(
path=webhook_url,
data=other_command,
format="json",
HTTP_AUTHORIZATION=f"Bearer {TOKEN}",
)
assert resp.status_code == 204
assert (
"Your Microsoft Teams identity is already linked to a Sentry account"
in responses.calls[3].request.body.decode("utf-8")
)
assert "Bearer my_token" in responses.calls[3].request.headers["Authorization"]
assert_slo_metric(mock_record, EventLifecycleOutcome.SUCCESS)
@responses.activate
@mock.patch("sentry.utils.jwt.decode")
@mock.patch("time.time")
def test_other_command(self, mock_time: MagicMock, mock_decode: MagicMock) -> None:
other_command = deepcopy(EXAMPLE_UNLINK_COMMAND)
other_command["text"] = "other"
access_json = {"expires_in": 86399, "access_token": "my_token"}
responses.add(
responses.POST,
"https://login.microsoftonline.com/botframework.com/oauth2/v2.0/token",
json=access_json,
)
responses.add(
responses.POST,
"https://smba.trafficmanager.net/amer/v3/conversations/%s/activities"
% other_command["conversation"]["id"],
json={},
)
mock_time.return_value = 1594839999 + 60
mock_decode.return_value = DECODED_TOKEN
resp = self.client.post(
path=webhook_url,
data=other_command,
format="json",
HTTP_AUTHORIZATION=f"Bearer {TOKEN}",
)
assert resp.status_code == 204
assert "Sorry, I didn't understand 'other'" in responses.calls[3].request.body.decode(
"utf-8"
)
assert "Bearer my_token" in responses.calls[3].request.headers["Authorization"]
@responses.activate
@mock.patch("sentry.utils.jwt.decode")
@mock.patch("time.time")
def test_invalid_silo_card_action_payload(
self, mock_time: MagicMock, mock_decode: MagicMock
) -> None:
mock_time.return_value = 1594839999 + 60
mock_decode.return_value = DECODED_TOKEN
with override_settings(SILO_MODE=SiloMode.CONTROL):
integration = self.create_provider_integration(external_id=team_id, provider="msteams")
CARD_ACTION_RESPONSE = {
"type": "message",
"from": {"id": "user_id"},
"channelData": {
"tenant": {"id": "f5ffd8cf-a1aa-4242-adad-86509faa3be5"},
"channel": {"id": "channel_id"},
},
"conversation": {"conversationType": "channel", "id": "conversation_id"},
"value": {
"payload": {
"groupId": "groupId",
"eventId": "eventId",
"actionType": ACTION_TYPE.ASSIGN,
"rules": [],
"integrationId": integration.id,
},
"assignInput": "me",
},
"replyToId": "replyToId",
"serviceUrl": "https://smba.trafficmanager.net/amer/",
}
response = self.client.post(
path=webhook_url,
data=CARD_ACTION_RESPONSE,
format="json",
HTTP_AUTHORIZATION=f"Bearer {TOKEN}",
)
assert response.status_code == 400
| MsTeamsWebhookTest |
python | huggingface__transformers | src/transformers/models/dinov3_vit/modeling_dinov3_vit.py | {
"start": 1921,
"end": 6053
} | class ____(nn.Module):
"""
Construct the CLS token, mask token, position and patch embeddings.
"""
def __init__(self, config: DINOv3ViTConfig):
super().__init__()
self.config = config
self.cls_token = nn.Parameter(torch.randn(1, 1, config.hidden_size))
self.mask_token = nn.Parameter(torch.zeros(1, 1, config.hidden_size))
self.register_tokens = nn.Parameter(torch.empty(1, config.num_register_tokens, config.hidden_size))
self.patch_embeddings = nn.Conv2d(
config.num_channels, config.hidden_size, kernel_size=config.patch_size, stride=config.patch_size
)
def forward(self, pixel_values: torch.Tensor, bool_masked_pos: Optional[torch.Tensor] = None) -> torch.Tensor:
batch_size = pixel_values.shape[0]
target_dtype = self.patch_embeddings.weight.dtype
# (batch_size, num_channels, height, width) -> (batch_size, num_patches, hidden_size)
patch_embeddings = self.patch_embeddings(pixel_values.to(dtype=target_dtype))
patch_embeddings = patch_embeddings.flatten(2).transpose(1, 2)
if bool_masked_pos is not None:
mask_token = self.mask_token.to(patch_embeddings.dtype)
patch_embeddings = torch.where(bool_masked_pos.unsqueeze(-1), mask_token, patch_embeddings)
# Add CLS and register tokens
cls_token = self.cls_token.expand(batch_size, -1, -1)
register_tokens = self.register_tokens.expand(batch_size, -1, -1)
embeddings = torch.cat([cls_token, register_tokens, patch_embeddings], dim=1)
return embeddings
@compile_compatible_method_lru_cache(maxsize=32)
def get_patches_center_coordinates(
num_patches_h: int, num_patches_w: int, dtype: torch.dtype, device: torch.device
) -> torch.Tensor:
"""
Computes the 2D coordinates of the centers of image patches, normalized to the range [-1, +1].
The center of each patch is exactly halfway between its top-left and bottom-right corners.
Args:
num_patches_h (int): Number of patches along the vertical (height) axis.
num_patches_w (int): Number of patches along the horizontal (width) axis.
dtype (torch.dtype): The desired data type of the returned tensor.
Returns:
torch.Tensor: A tensor of shape (height * width, 2), where each row contains the (y, x)
coordinates of a patch center, normalized to [-1, +1].
"""
coords_h = torch.arange(0.5, num_patches_h, dtype=dtype, device=device)
coords_w = torch.arange(0.5, num_patches_w, dtype=dtype, device=device)
coords_h = coords_h / num_patches_h
coords_w = coords_w / num_patches_w
# (height, width, 2) -> (height * width, 2)
coords = torch.stack(torch.meshgrid(coords_h, coords_w, indexing="ij"), dim=-1)
coords = coords.flatten(0, 1)
# Shift range [0, 1] to [-1, +1]
coords = 2.0 * coords - 1.0
return coords
def augment_patches_center_coordinates(
coords: torch.Tensor,
shift: Optional[float] = None,
jitter: Optional[float] = None,
rescale: Optional[float] = None,
) -> torch.Tensor:
# Shift coords by adding a uniform value in [-shift, shift]
if shift is not None:
shift_hw = torch.empty((1, 2), device=coords.device, dtype=coords.dtype)
shift_hw = shift_hw.uniform_(-shift, shift)
coords = coords + shift_hw
# Jitter coords by multiplying the range [-1, 1] by a log-uniform value in [1/jitter, jitter]
if jitter is not None:
jitter_range = np.log(jitter)
jitter_hw = torch.empty((1, 2), device=coords.device, dtype=coords.dtype)
jitter_hw = jitter_hw.uniform_(-jitter_range, jitter_range).exp()
coords = coords * jitter_hw
# Rescale coords by multiplying the range [-1, 1] by a log-uniform value in [1/rescale, rescale]
if rescale is not None:
rescale_range = np.log(rescale)
rescale_hw = torch.empty(1, device=coords.device, dtype=coords.dtype)
rescale_hw = rescale_hw.uniform_(-rescale_range, rescale_range).exp()
coords = coords * rescale_hw
return coords
| DINOv3ViTEmbeddings |
python | sqlalchemy__sqlalchemy | test/sql/test_compare.py | {
"start": 48348,
"end": 55583
} | class ____(fixtures.CacheKeyFixture, CoreFixtures, fixtures.TestBase):
@testing.combinations(
table_a.insert().values( # multivalues doesn't cache
[
{"name": "some name"},
{"name": "some other name"},
{"name": "yet another name"},
]
),
)
def test_dml_not_cached_yet(self, dml_stmt):
eq_(dml_stmt._generate_cache_key(), None)
def test_values_doesnt_caches_right_now(self):
v1 = values(
column("mykey", Integer),
column("mytext", String),
column("myint", Integer),
name="myvalues",
).data([(1, "textA", 99), (2, "textB", 88)])
is_(v1._generate_cache_key(), None)
large_v1 = values(
column("mykey", Integer),
column("mytext", String),
column("myint", Integer),
name="myvalues",
).data([(i, "data %s" % i, i * 5) for i in range(500)])
is_(large_v1._generate_cache_key(), None)
@testing.combinations(
(lambda: column("x"), lambda: column("x"), lambda: column("y")),
(
lambda: func.foo_bar(1, 2, 3),
lambda: func.foo_bar(4, 5, 6),
lambda: func.foo_bar_bat(1, 2, 3),
),
)
def test_cache_key_object_comparators(self, lc1, lc2, lc3):
"""test ne issue detected as part of #10042"""
c1 = lc1()
c2 = lc2()
c3 = lc3()
eq_(c1._generate_cache_key(), c2._generate_cache_key())
ne_(c1._generate_cache_key(), c3._generate_cache_key())
is_true(c1._generate_cache_key() == c2._generate_cache_key())
is_false(c1._generate_cache_key() != c2._generate_cache_key())
is_true(c1._generate_cache_key() != c3._generate_cache_key())
is_false(c1._generate_cache_key() == c3._generate_cache_key())
def test_in_with_none(self):
"""test #12314"""
def fixture():
elements = list(
random_choices([1, 2, None, 3, 4], k=random.randint(1, 7))
)
# slight issue. if the first element is None and not an int,
# the type of the BindParameter goes from Integer to Nulltype.
# but if we set the left side to be Integer then it comes from
# that side, and the vast majority of in_() use cases come from
# a typed column expression, so this is fine
return (column("x", Integer).in_(elements),)
self._run_cache_key_fixture(fixture, compare_values=False)
def test_cache_key(self):
for fixtures_, compare_values in [
(self.fixtures, True),
(self.dont_compare_values_fixtures, False),
(self.type_cache_key_fixtures, False),
]:
for fixture in fixtures_:
self._run_cache_key_fixture(
fixture, compare_values=compare_values
)
def test_cache_key_equal(self):
for fixture in self.equal_fixtures:
self._run_cache_key_equal_fixture(fixture, True)
def test_literal_binds(self):
def fixture():
return (
bindparam(None, value="x", literal_execute=True),
bindparam(None, value="y", literal_execute=True),
)
self._run_cache_key_fixture(
fixture,
compare_values=True,
)
def test_bindparam_subclass_nocache(self):
# does not implement inherit_cache
class _literal_bindparam(BindParameter):
pass
l1 = _literal_bindparam(None, value="x1")
is_(l1._generate_cache_key(), None)
def test_bindparam_subclass_ok_cache(self):
# implements inherit_cache
class _literal_bindparam(BindParameter):
inherit_cache = True
def fixture():
return (
_literal_bindparam(None, value="x1"),
_literal_bindparam(None, value="x2"),
_literal_bindparam(None),
)
self._run_cache_key_fixture(fixture, compare_values=True)
def test_cache_key_unknown_traverse(self):
class Foobar1(ClauseElement):
_traverse_internals = [
("key", InternalTraversal.dp_anon_name),
("type_", InternalTraversal.dp_unknown_structure),
]
def __init__(self, key, type_):
self.key = key
self.type_ = type_
f1 = Foobar1("foo", String())
eq_(f1._generate_cache_key(), None)
def test_cache_key_no_method(self):
class Foobar1(ClauseElement):
pass
class Foobar2(ColumnElement):
pass
# the None for cache key will prevent objects
# which contain these elements from being cached.
f1 = Foobar1()
with expect_warnings(
"Class Foobar1 will not make use of SQL compilation caching"
):
eq_(f1._generate_cache_key(), None)
f2 = Foobar2()
with expect_warnings(
"Class Foobar2 will not make use of SQL compilation caching"
):
eq_(f2._generate_cache_key(), None)
s1 = select(column("q"), Foobar2())
# warning is memoized, won't happen the second time
eq_(s1._generate_cache_key(), None)
def test_get_children_no_method(self):
class Foobar1(ClauseElement):
pass
class Foobar2(ColumnElement):
pass
f1 = Foobar1()
eq_(f1.get_children(), [])
f2 = Foobar2()
eq_(f2.get_children(), [])
def test_copy_internals_no_method(self):
class Foobar1(ClauseElement):
pass
class Foobar2(ColumnElement):
pass
f1 = Foobar1()
f2 = Foobar2()
f1._copy_internals()
f2._copy_internals()
def test_generative_cache_key_regen(self):
t1 = table("t1", column("a"), column("b"))
s1 = select(t1)
ck1 = s1._generate_cache_key()
s2 = s1.where(t1.c.a == 5)
ck2 = s2._generate_cache_key()
ne_(ck1, ck2)
is_not(ck1, None)
is_not(ck2, None)
def test_generative_cache_key_regen_w_del(self):
t1 = table("t1", column("a"), column("b"))
s1 = select(t1)
ck1 = s1._generate_cache_key()
s2 = s1.where(t1.c.a == 5)
del s1
# there is now a good chance that id(s3) == id(s1), make sure
# cache key is regenerated
s3 = s2.order_by(t1.c.b)
ck3 = s3._generate_cache_key()
ne_(ck1, ck3)
is_not(ck1, None)
is_not(ck3, None)
def all_hascachekey_subclasses(ignore_subclasses=()):
def find_subclasses(cls: type):
for s in class_hierarchy(cls):
if (
# class_hierarchy may return values that
# aren't subclasses of cls
not issubclass(s, cls)
or "_traverse_internals" not in s.__dict__
or any(issubclass(s, ignore) for ignore in ignore_subclasses)
):
continue
yield s
return dict.fromkeys(find_subclasses(HasCacheKey))
| CacheKeyTest |
python | spack__spack | lib/spack/spack/report.py | {
"start": 5015,
"end": 5835
} | class ____(SpecRecord):
"""Record class with specialization for test logs."""
def __init__(self, spec, directory):
super().__init__(spec)
self.directory = directory
def fetch_log(self):
"""Get output from test log"""
log_file = os.path.join(self.directory, self._package.test_suite.test_log_name(self._spec))
try:
with open(log_file, "r", encoding="utf-8") as stream:
return "".join(stream.readlines())
except Exception:
return f"Cannot open log for {self._spec.cshort_spec}"
def succeed(self, externals):
"""Test reports skip externals by default."""
if self._spec.external and not externals:
return self.skip(msg="Skipping test of external package")
super().succeed()
| TestRecord |
python | apache__airflow | airflow-core/src/airflow/api_fastapi/core_api/datamodels/connections.py | {
"start": 3535,
"end": 4041
} | class ____(BaseModel):
"""
Response model for Hook information == Connection type meta data.
It is used to transfer providers information loaded by providers_manager such that
the API server/Web UI can use this data to render connection form UI.
"""
connection_type: str | None
hook_class_name: str | None
default_conn_name: str | None
hook_name: str
standard_fields: StandardHookFields | None
extra_fields: Mapping | None
# Request Models
| ConnectionHookMetaData |
python | doocs__leetcode | solution/2600-2699/2681.Power of Heroes/Solution.py | {
"start": 0,
"end": 314
} | class ____:
def sumOfPower(self, nums: List[int]) -> int:
mod = 10**9 + 7
nums.sort()
ans = 0
p = 0
for x in nums[::-1]:
ans = (ans + (x * x % mod) * x) % mod
ans = (ans + x * p) % mod
p = (p * 2 + x * x) % mod
return ans
| Solution |
python | scipy__scipy | scipy/spatial/transform/_rotation.py | {
"start": 99840,
"end": 106817
} | class ____:
"""Spherical Linear Interpolation of Rotations.
The interpolation between consecutive rotations is performed as a rotation
around a fixed axis with a constant angular velocity [1]_. This ensures
that the interpolated rotations follow the shortest path between initial
and final orientations.
Parameters
----------
times : array_like, shape (N,)
Times of the known rotations. At least 2 times must be specified.
rotations : `Rotation` instance
Rotations to perform the interpolation between. Must contain N
rotations.
Methods
-------
__call__
See Also
--------
Rotation
Notes
-----
This class only supports interpolation of rotations with a single leading
dimension.
.. versionadded:: 1.2.0
References
----------
.. [1] https://en.wikipedia.org/wiki/Slerp#Quaternion_Slerp
Examples
--------
>>> from scipy.spatial.transform import Rotation as R
>>> from scipy.spatial.transform import Slerp
Setup the fixed keyframe rotations and times:
>>> key_rots = R.random(5, random_state=2342345)
>>> key_times = [0, 1, 2, 3, 4]
Create the interpolator object:
>>> slerp = Slerp(key_times, key_rots)
Interpolate the rotations at the given times:
>>> times = [0, 0.5, 0.25, 1, 1.5, 2, 2.75, 3, 3.25, 3.60, 4]
>>> interp_rots = slerp(times)
The keyframe rotations expressed as Euler angles:
>>> key_rots.as_euler('xyz', degrees=True)
array([[ 14.31443779, -27.50095894, -3.7275787 ],
[ -1.79924227, -24.69421529, 164.57701743],
[146.15020772, 43.22849451, -31.34891088],
[ 46.39959442, 11.62126073, -45.99719267],
[-88.94647804, -49.64400082, -65.80546984]])
The interpolated rotations expressed as Euler angles. These agree with the
keyframe rotations at both endpoints of the range of keyframe times.
>>> interp_rots.as_euler('xyz', degrees=True)
array([[ 14.31443779, -27.50095894, -3.7275787 ],
[ 4.74588574, -32.44683966, 81.25139984],
[ 10.71094749, -31.56690154, 38.06896408],
[ -1.79924227, -24.69421529, 164.57701743],
[ 11.72796022, 51.64207311, -171.7374683 ],
[ 146.15020772, 43.22849451, -31.34891088],
[ 68.10921869, 20.67625074, -48.74886034],
[ 46.39959442, 11.62126073, -45.99719267],
[ 12.35552615, 4.21525086, -64.89288124],
[ -30.08117143, -19.90769513, -78.98121326],
[ -88.94647804, -49.64400082, -65.80546984]])
"""
@xp_capabilities(
jax_jit=False, skip_backends=[("dask.array", "missing linalg.cross function")]
)
def __init__(self, times: ArrayLike, rotations: Rotation):
if not isinstance(rotations, Rotation):
raise TypeError("`rotations` must be a `Rotation` instance.")
if rotations.single or len(rotations) <= 1:
raise ValueError("`rotations` must be a sequence of at least 2 rotations.")
q = rotations.as_quat()
if q.ndim > 2:
raise ValueError(
"Rotations with more than 1 leading dimension are not supported."
)
xp = array_namespace(q)
times = xp.asarray(times, device=xp_device(q), dtype=q.dtype)
if times.ndim != 1:
raise ValueError(
"Expected times to be specified in a 1 dimensional array, got "
f"{times.ndim} dimensions."
)
if times.shape[0] != len(rotations):
raise ValueError(
"Expected number of rotations to be equal to number of timestamps "
f"given, got {len(rotations)} rotations and {times.shape[0]} "
"timestamps."
)
self.times = times
self.timedelta = xp.diff(times)
# We cannot check for values for lazy backends, so we cannot raise an error on
# timedelta < 0 for lazy backends. Instead, we set timedelta to nans
neg_mask = xp.any(self.timedelta <= 0)
if is_lazy_array(neg_mask):
self.timedelta = xp.where(neg_mask, xp.nan, self.timedelta)
self.times = xp.where(neg_mask, xp.nan, self.times)
elif xp.any(neg_mask):
raise ValueError("Times must be in strictly increasing order.")
self.rotations = rotations[:-1]
self.rotvecs = (self.rotations.inv() * rotations[1:]).as_rotvec()
@xp_capabilities()
def __call__(self, times: ArrayLike) -> Rotation:
"""Interpolate rotations.
Compute the interpolated rotations at the given `times`.
Parameters
----------
times : array_like
Times to compute the interpolations at. Can be a scalar or
1-dimensional.
Returns
-------
interpolated_rotation : `Rotation` instance
Object containing the rotations computed at given `times`.
"""
xp = array_namespace(self.times)
device = xp_device(self.times)
# Clearly differentiate from self.times property
compute_times = xp.asarray(times, device=device, dtype=self.times.dtype)
if compute_times.ndim > 1:
raise ValueError("`times` must be at most 1-dimensional.")
single_time = compute_times.ndim == 0
compute_times = xpx.atleast_nd(compute_times, ndim=1, xp=xp)
# side = 'left' (default) excludes t_min.
ind = xp.searchsorted(self.times, compute_times) - 1
# Include t_min. Without this step, index for t_min equals -1
ind = xpx.at(ind, compute_times == self.times[0]).set(0)
# We cannot error out on invalid indices for jit compiled code. To not produce
# an index error, we set the index to 0 in case it is out of bounds, and later
# set the result to nan.
invalid_ind = (ind < 0) | (ind > len(self.rotations) - 1)
if is_lazy_array(invalid_ind):
ind = xpx.at(ind, invalid_ind).set(0)
elif xp.any(invalid_ind):
raise ValueError(
f"Interpolation times must be within the range [{self.times[0]}, "
f"{self.times[-1]}], both inclusive."
)
alpha = (compute_times - self.times[ind]) / self.timedelta[ind]
alpha = xpx.at(alpha, invalid_ind).set(xp.nan)
# The array API does not support integer arrays + ellipsis indexing and won't
# stabilize this feature due to blockers in PyTorch. Therefore we need to
# construct the index for the last dimension manually.
# See https://github.com/scipy/scipy/pull/23249#discussion_r2198363047
result = self.rotations[ind] * Rotation.from_rotvec(
self.rotvecs[ind[:, None], xp.arange(3, device=device)] * alpha[:, None]
)
if single_time:
result = result[0]
return result
| Slerp |
python | pytorch__pytorch | test/distributed/elastic/agent/server/test/local_elastic_agent_test.py | {
"start": 7188,
"end": 53296
} | class ____(unittest.TestCase):
@classmethod
def setUpClass(cls):
# start a standalone, single process etcd server to use for all tests
cls._etcd_server = EtcdServer()
cls._etcd_server.start()
@classmethod
def tearDownClass(cls):
# stop the standalone etcd server
cls._etcd_server.stop()
def setUp(self):
self._test_dir = tempfile.mkdtemp(prefix=self.__class__.__name__)
self._run_id = str(uuid.uuid4()).split("-")[0]
def tearDown(self):
shutil.rmtree(self._test_dir)
def log_dir(self) -> str:
return tempfile.mkdtemp(prefix="torchelastic_", dir=self._test_dir)
def get_worker_spec(
self,
node_config: Conf,
min_nodes=1,
max_nodes=1,
max_restarts=0,
monitor_interval=0.01,
master_addr_override: Optional[str] = None,
master_port_override: Optional[int] = None,
is_host=True,
):
rdzv_params = RendezvousParameters(
backend=self._backend,
endpoint=self._endpoint,
run_id=self._run_id,
min_nodes=min_nodes,
max_nodes=max_nodes,
is_host=is_host,
)
rdzv_handler = rdzv_registry.get_rendezvous_handler(rdzv_params)
return WorkerSpec(
role=node_config.role,
local_world_size=node_config.local_world_size,
entrypoint=node_config.entrypoint,
args=node_config.args,
rdzv_handler=rdzv_handler,
max_restarts=max_restarts,
monitor_interval=monitor_interval,
master_addr=master_addr_override,
master_port=master_port_override,
)
def get_agent(
self,
spec: WorkerSpec,
node_config: Conf,
start_method: str = "spawn",
exit_barrier_timeout=5,
log_line_prefix_template: Optional[str] = None,
) -> LocalElasticAgent:
return LocalElasticAgent(
spec,
start_method=start_method,
exit_barrier_timeout=exit_barrier_timeout,
logs_specs=DefaultLogsSpecs(
log_dir=self.log_dir(),
redirects=node_config.redirects,
tee=node_config.tee,
),
log_line_prefix_template=log_line_prefix_template,
)
# pyre-fixme[56]: Pyre was not able to infer the type of the decorator
# `torch.distributed.elastic.multiprocessing.errors.record`.
@record
def run_agent(
self,
conf: Conf,
agent_results: Optional[mp.Queue] = None, # (role, agent_result)
min_nodes=1,
max_nodes=1,
start_method: str = "spawn",
max_restarts: int = 0,
exit_barrier_timeout=5,
master_addr_override: Optional[str] = None,
master_port_override: Optional[int] = None,
is_host=True,
monitor_interval=0.01,
log_line_prefix_template: Optional[str] = None,
) -> Optional[RunResult]:
"""
Runs a single agent. This method can be called either on a separate process
or the main test process. When calling this method on a separate process make
sure to pass the ``agent_results`` multiprocessing Queue so that the agent's
run results can be returned. If ``agent_results`` is omitted, then the
run result is returned from the method.
"""
spec = self.get_worker_spec(
node_config=conf,
min_nodes=min_nodes,
max_nodes=max_nodes,
max_restarts=max_restarts,
master_addr_override=master_addr_override,
master_port_override=master_port_override,
is_host=is_host,
monitor_interval=monitor_interval,
)
agent = self.get_agent(
spec=spec,
node_config=conf,
start_method=start_method,
exit_barrier_timeout=exit_barrier_timeout,
log_line_prefix_template=log_line_prefix_template,
)
result = agent.run()
spec.rdzv_handler.shutdown()
if agent_results:
agent_results.put((conf.role, result))
if result.is_failed():
raise ChildFailedError(spec.get_entrypoint_name(), result.failures)
else:
if not agent_results:
return result
def run_job(
self,
node_configs: list[Conf],
exit_barrier_timeout: int = 5,
log_line_prefix_template: Optional[str] = None,
) -> dict[str, list[RunResult]]:
"""
Simulates running a distributed job by running multiple agents
(one on each process). Agent 0 is run on the main process for
test coverage and ease of debugging
"""
nnodes = len(node_configs)
# each element in this queue holds a tuple (role, RunResult) for each agent
agent_results = mp.Queue()
# run first agent of first config on main process for test coverage + ease of debugging
# it is important we loop in reverse order b/c running fn on the main process blocks
procs = []
for node_idx in reversed(range(len(node_configs))):
conf = node_configs[node_idx]
run_agent_args = {
"conf": conf,
"agent_results": agent_results,
"min_nodes": nnodes,
"max_nodes": nnodes,
"start_method": "spawn",
"max_restarts": 0,
"exit_barrier_timeout": exit_barrier_timeout,
"is_host": node_idx == 0,
"log_line_prefix_template": log_line_prefix_template,
}
p = mp.Process(target=self.run_agent, kwargs=run_agent_args)
procs.append(p)
p.start()
for p in procs:
p.join()
results: dict[str, list[RunResult]] = {}
while not agent_results.empty():
role, run_result = agent_results.get()
results.setdefault(role, []).append(run_result)
return results
def run_test_with_backend(self, backend: str, test_to_run: Callable):
"""
Sets the backend and determines the endpoint before running the
given test.
Note: This method must be invoked to run any test functions that spawn
an agent. This is because this function sets the backend and
endpoint parameters.
"""
self._backend = backend
if self._backend == "etcd-v2" or self._backend == "etcd":
self._endpoint = self._etcd_server.get_endpoint()
else:
# the default is c10d backend
self._endpoint = f"localhost:{acquire_available_port()}"
test_to_run()
def dummy_compute(self):
res = self.run_agent(Conf(entrypoint=dummy_compute, local_world_size=2))
self.assertFalse(res.is_failed())
for return_value in res.return_values.values():
self.assertIsInstance(return_value, torch.Tensor)
self.assertEqual((100, 100), return_value.shape)
@skip_but_pass_in_sandcastle_if(
TEST_WITH_DEV_DBG_ASAN, "test incompatible with dev/dbg asan"
)
def test_dummy_compute_c10d(self):
self.run_test_with_backend(backend="c10d", test_to_run=self.dummy_compute)
@skip_but_pass_in_sandcastle_if(
TEST_WITH_DEV_DBG_ASAN, "test incompatible with dev/dbg asan"
)
def test_dummy_compute_etcd(self):
self.run_test_with_backend(backend="etcd", test_to_run=self.dummy_compute)
@skip_but_pass_in_sandcastle_if(
TEST_WITH_DEV_DBG_ASAN, "test incompatible with dev/dbg asan"
)
def test_dummy_compute_etcd_v2(self):
self.run_test_with_backend(backend="etcd-v2", test_to_run=self.dummy_compute)
def run_happy_function(self):
res = self.run_agent(Conf(entrypoint=_happy_function, local_world_size=2))
self.assertFalse(res.is_failed())
self.assertIsNone(res.return_values[0])
self.assertIsNone(res.return_values[1])
@skip_but_pass_in_sandcastle_if(
TEST_WITH_DEV_DBG_ASAN, "test incompatible with dev/dbg asan"
)
def test_run_happy_function_c10d(self):
self.run_test_with_backend(backend="c10d", test_to_run=self.run_happy_function)
@skip_but_pass_in_sandcastle_if(
TEST_WITH_DEV_DBG_ASAN, "test incompatible with dev/dbg asan"
)
def test_run_happy_function_etcd(self):
self.run_test_with_backend(backend="etcd", test_to_run=self.run_happy_function)
@skip_but_pass_in_sandcastle_if(
TEST_WITH_DEV_DBG_ASAN, "test incompatible with dev/dbg asan"
)
def test_run_happy_function_etcd_v2(self):
self.run_test_with_backend(
backend="etcd-v2", test_to_run=self.run_happy_function
)
def check_master_addr_port_override(self):
master_addr = "test_host"
master_port = 42
res = self.run_agent(
Conf(
entrypoint=_check_master_port_addr_override,
args=(master_addr, master_port),
local_world_size=1,
),
master_addr_override=master_addr,
master_port_override=master_port,
)
self.assertFalse(res.is_failed())
self.assertIsNone(res.return_values[0])
@skip_but_pass_in_sandcastle_if(
TEST_WITH_DEV_DBG_ASAN, "test incompatible with dev/dbg asan"
)
def test_check_master_addr_port_override_etcd(self):
self.run_test_with_backend(
backend="etcd", test_to_run=self.check_master_addr_port_override
)
@skip_but_pass_in_sandcastle_if(
TEST_WITH_DEV_DBG_ASAN, "test incompatible with dev/dbg asan"
)
def test_check_master_addr_port_override_etcd_v2(self):
self.run_test_with_backend(
backend="etcd-v2", test_to_run=self.check_master_addr_port_override
)
def run_check_env_function(self):
# just checks that all env vars that we need to set on the user script
# is actually set
res = self.run_agent(Conf(entrypoint=_check_env_function, local_world_size=1))
self.assertFalse(res.is_failed())
def run_check_nccl_async_error_handling_env(self):
# make sure TORCH_NCCL_ASYNC_ERROR_HANDLING set in os.environ is honored
with patch.dict(os.environ, {"TORCH_NCCL_ASYNC_ERROR_HANDLING": "0"}):
res = self.run_agent(
Conf(
entrypoint=_check_env_value,
local_world_size=1,
args=("TORCH_NCCL_ASYNC_ERROR_HANDLING", "0"),
)
)
self.assertFalse(res.is_failed())
def run_check_nccl_async_error_handling_env_default(self):
# if not present in env var it should default to 1
res = self.run_agent(
Conf(
entrypoint=_check_env_value,
local_world_size=1,
args=("TORCH_NCCL_ASYNC_ERROR_HANDLING", "1"),
)
)
self.assertFalse(res.is_failed())
def run_agent_local_watchdog_setup_enabled(self):
# Set the env for watchdog
watchdog_env_name = TORCHELASTIC_TIMER_FILE
watchdog_file_path = "/tmp/watchdog_timer_" + str(uuid.uuid4())
os.environ[watchdog_env_name] = watchdog_file_path
# Run the agent
node_conf = Conf(
entrypoint=_check_local_watchdog_setup,
local_world_size=1,
args=(TORCHELASTIC_TIMER_FILE, True),
)
spec = self.get_worker_spec(node_conf, max_restarts=2)
agent = self.get_agent(spec, node_config=node_conf)
res = agent.run()
self.assertFalse(res.is_failed())
def run_agent_local_watchdog_setup_disabled(self):
# Do not set the env for watchdog
watchdog_env_name = TORCHELASTIC_TIMER_FILE
if watchdog_env_name in os.environ:
del os.environ[watchdog_env_name]
# Run the agent
node_conf = Conf(
entrypoint=_check_local_watchdog_setup,
local_world_size=1,
args=(TORCHELASTIC_TIMER_FILE, False),
)
spec = self.get_worker_spec(node_conf, max_restarts=2)
agent = self.get_agent(spec, node_config=node_conf)
res = agent.run()
self.assertFalse(res.is_failed())
@skip_but_pass_in_sandcastle_if(
TEST_WITH_DEV_DBG_ASAN, "test incompatible with dev/dbg asan"
)
def test_run_agent_local_watchdog_setup_enabled_etcd(self):
self.run_test_with_backend(
backend="etcd", test_to_run=self.run_agent_local_watchdog_setup_enabled
)
@skip_but_pass_in_sandcastle_if(
TEST_WITH_DEV_DBG_ASAN, "test incompatible with dev/dbg asan"
)
def test_run_agent_local_watchdog_setup_enabled_c10d(self):
self.run_test_with_backend(
backend="c10d", test_to_run=self.run_agent_local_watchdog_setup_enabled
)
@skip_but_pass_in_sandcastle_if(
TEST_WITH_DEV_DBG_ASAN, "test incompatible with dev/dbg asan"
)
def test_run_agent_local_watchdog_setup_disabled_etcd(self):
self.run_test_with_backend(
backend="etcd", test_to_run=self.run_agent_local_watchdog_setup_disabled
)
@skip_but_pass_in_sandcastle_if(
TEST_WITH_DEV_DBG_ASAN, "test incompatible with dev/dbg asan"
)
def test_run_agent_local_watchdog_setup_disabled_c10d(self):
self.run_test_with_backend(
backend="c10d", test_to_run=self.run_agent_local_watchdog_setup_disabled
)
def run_agent_healthcheck_setup_enabled(self):
# Set the env for healthcheck
healthcheck_port_env_name = TORCHELASTIC_HEALTH_CHECK_PORT
os.environ[healthcheck_port_env_name] = "12345"
# Run the agent
node_conf = Conf(
entrypoint=_check_local_watchdog_setup,
local_world_size=1,
args=(TORCHELASTIC_HEALTH_CHECK_PORT, True),
)
spec = self.get_worker_spec(node_conf, max_restarts=2)
agent = self.get_agent(spec, node_config=node_conf)
res = agent.run()
self.assertFalse(res.is_failed())
def run_agent_healthcheck_setup_disabled(self):
# Do not set the env for healthcheck
healthcheck_port_env_name = TORCHELASTIC_HEALTH_CHECK_PORT
if healthcheck_port_env_name in os.environ:
del os.environ[healthcheck_port_env_name]
# Run the agent
node_conf = Conf(
entrypoint=_check_local_watchdog_setup,
local_world_size=1,
args=(TORCHELASTIC_HEALTH_CHECK_PORT, False),
)
spec = self.get_worker_spec(node_conf, max_restarts=2)
agent = self.get_agent(spec, node_config=node_conf)
res = agent.run()
self.assertFalse(res.is_failed())
@skip_but_pass_in_sandcastle_if(
TEST_WITH_DEV_DBG_ASAN, "test incompatible with dev/dbg asan"
)
def test_run_agent_healthcheck_setup_enabled_etcd(self):
self.run_test_with_backend(
backend="etcd", test_to_run=self.run_agent_healthcheck_setup_enabled
)
@skip_but_pass_in_sandcastle_if(
TEST_WITH_DEV_DBG_ASAN, "test incompatible with dev/dbg asan"
)
def test_run_agent_healthcheck_setup_enabled_c10d(self):
self.run_test_with_backend(
backend="c10d", test_to_run=self.run_agent_healthcheck_setup_enabled
)
@skip_but_pass_in_sandcastle_if(
TEST_WITH_DEV_DBG_ASAN, "test incompatible with dev/dbg asan"
)
def test_run_agent_healthcheck_setup_disabled_etcd(self):
self.run_test_with_backend(
backend="etcd", test_to_run=self.run_agent_healthcheck_setup_disabled
)
@skip_but_pass_in_sandcastle_if(
TEST_WITH_DEV_DBG_ASAN, "test incompatible with dev/dbg asan"
)
def test_run_agent_healthcheck_setup_disabled_c10d(self):
self.run_test_with_backend(
backend="c10d", test_to_run=self.run_agent_healthcheck_setup_disabled
)
@skip_but_pass_in_sandcastle_if(
TEST_WITH_DEV_DBG_ASAN, "test incompatible with dev/dbg asan"
)
def test_run_check_env_function_etcd(self):
self.run_test_with_backend(
backend="etcd", test_to_run=self.run_check_env_function
)
@skip_but_pass_in_sandcastle_if(
TEST_WITH_DEV_DBG_ASAN, "test incompatible with dev/dbg asan"
)
def test_run_check_nccl_async_error_handling_env_c10d(self):
self.run_test_with_backend(
backend="c10d", test_to_run=self.run_check_nccl_async_error_handling_env
)
@skip_but_pass_in_sandcastle_if(
TEST_WITH_DEV_DBG_ASAN, "test incompatible with dev/dbg asan"
)
def test_run_check_nccl_async_error_handling_env_default_c10d(self):
self.run_test_with_backend(
backend="c10d",
test_to_run=self.run_check_nccl_async_error_handling_env_default,
)
def run_function_with_return_value(self):
res = self.run_agent(Conf(entrypoint=_echo, args=("foo",), local_world_size=2))
self.assertFalse(res.is_failed())
self.assertEqual("foo", res.return_values[0])
self.assertEqual("foo", res.return_values[1])
@skip_but_pass_in_sandcastle_if(
TEST_WITH_DEV_DBG_ASAN, "test incompatible with dev/dbg asan"
)
def test_run_function_with_return_value_c10d(self):
self.run_test_with_backend(
backend="c10d", test_to_run=self.run_function_with_return_value
)
@skip_but_pass_in_sandcastle_if(
TEST_WITH_DEV_DBG_ASAN, "test incompatible with dev/dbg asan"
)
def test_run_function_with_return_value_etcd(self):
self.run_test_with_backend(
backend="etcd", test_to_run=self.run_function_with_return_value
)
@skip_but_pass_in_sandcastle_if(
TEST_WITH_DEV_DBG_ASAN, "test incompatible with dev/dbg asan"
)
def test_run_function_with_return_value_etcd_v2(self):
self.run_test_with_backend(
backend="etcd-v2", test_to_run=self.run_function_with_return_value
)
def simple_dist_sum(self):
res = self.run_agent(Conf(entrypoint=_dist_sum, local_world_size=2))
self.assertFalse(res.is_failed())
# _dist_sum internally checks that the sum computed is valid
@skip_but_pass_in_sandcastle_if(
TEST_WITH_DEV_DBG_ASAN, "test incompatible with dev/dbg asan"
)
def test_simple_dist_sum_c10d(self):
self.run_test_with_backend(backend="c10d", test_to_run=self.simple_dist_sum)
@skip_but_pass_in_sandcastle_if(
TEST_WITH_DEV_DBG_ASAN, "test incompatible with dev/dbg asan"
)
def test_simple_dist_sum_etcd(self):
self.run_test_with_backend(backend="etcd", test_to_run=self.simple_dist_sum)
@skip_but_pass_in_sandcastle_if(
TEST_WITH_DEV_DBG_ASAN, "test incompatible with dev/dbg asan"
)
def test_simple_dist_sum_etcd_v2(self):
self.run_test_with_backend(backend="etcd-v2", test_to_run=self.simple_dist_sum)
def run_distributed_sum_homogeneous(
self, log_line_prefix_template: Optional[str] = None
):
node_configs = [
Conf(role="sum", entrypoint=_dist_sum, local_world_size=4, tee=Std.ALL),
Conf(role="sum", entrypoint=_dist_sum, local_world_size=4, tee=Std.ALL),
]
# When the process method is spawn, the coverage collector hangs
# due to getting stuck on the _dist_sum in waiting for TCPStore workers
# to join the cluster
# TODO(aivanou): t83447589 come up with the proper fix
res = self.run_job(
node_configs, log_line_prefix_template=log_line_prefix_template
)
self.assertEqual(2, len(res["sum"]))
ranks = set()
for run_results in res["sum"]:
self.assertFalse(run_results.is_failed())
ranks.update(run_results.return_values.keys())
self.assertSetEqual(set(range(4 + 4)), ranks)
@unittest.skipIf(
TEST_WITH_DEV_DBG_ASAN or TEST_WITH_TSAN,
"test incompatible with dev/dbg asan or tsan",
)
def test_run_distributed_sum_homogeneous_c10d(self):
self.run_test_with_backend(
backend="c10d", test_to_run=self.run_distributed_sum_homogeneous
)
def test_run_with_custom_log_lines(self):
log_line_prefix_template = "[${role_name}-${local_rank}:${rank}]:"
self.run_test_with_backend(
backend="c10d",
test_to_run=lambda: self.run_distributed_sum_homogeneous(
log_line_prefix_template
),
)
@unittest.skipIf(
TEST_WITH_DEV_DBG_ASAN or TEST_WITH_TSAN,
"test incompatible with dev/dbg asan or tsan",
)
def test_run_distributed_sum_homogeneous_etcd(self):
self.run_test_with_backend(
backend="etcd", test_to_run=self.run_distributed_sum_homogeneous
)
@unittest.skipIf(
TEST_WITH_DEV_DBG_ASAN or TEST_WITH_TSAN,
"test incompatible with dev/dbg asan or tsan",
)
def test_run_distributed_sum_homogeneous_etcd_v2(self):
self.run_test_with_backend(
backend="etcd-v2", test_to_run=self.run_distributed_sum_homogeneous
)
def run_distributed_sum_heterogeneous(self):
# sums all ranks on 3 agents; each running 1, 2, 3 workers respectively
# sum should be equal to 0 + (1 + 2) + (3 + 4 + 5) = 15
# sum asserted inside _dist_sum()
node_configs = [
Conf(role="sum", entrypoint=_dist_sum, local_world_size=1),
Conf(role="sum", entrypoint=_dist_sum, local_world_size=2),
Conf(role="sum", entrypoint=_dist_sum, local_world_size=3),
]
# When the process method is spawn, the coverage collector hangs
# due to getting stuck on the _dist_sum in waiting for TCPStore workers
# to join the cluster
# TODO(aivanou): t83447589 come up with the proper fix
res = self.run_job(node_configs)
self.assertEqual(3, len(res["sum"]))
ranks = set()
for run_results in res["sum"]:
self.assertFalse(run_results.is_failed())
ranks.update(run_results.return_values.keys())
self.assertSetEqual(set(range(1 + 2 + 3)), ranks)
@skip_but_pass_in_sandcastle_if(
TEST_WITH_DEV_DBG_ASAN, "test incompatible with dev/dbg asan"
)
def test_run_distributed_sum_heterogeneous_c10d(self):
self.run_test_with_backend(
backend="c10d", test_to_run=self.run_distributed_sum_heterogeneous
)
@skip_but_pass_in_sandcastle_if(
TEST_WITH_DEV_DBG_ASAN, "test incompatible with dev/dbg asan"
)
def test_run_distributed_sum_heterogeneous_etcd(self):
self.run_test_with_backend(
backend="etcd", test_to_run=self.run_distributed_sum_heterogeneous
)
@skip_but_pass_in_sandcastle_if(
TEST_WITH_DEV_DBG_ASAN, "test incompatible with dev/dbg asan"
)
def test_run_distributed_sum_heterogeneous_etcd_v2(self):
self.run_test_with_backend(
backend="etcd-v2", test_to_run=self.run_distributed_sum_heterogeneous
)
def run_sad_function(self):
"""
checks error propagation logic
"""
replyfile = os.path.join(self._test_dir, "error.json")
with mock.patch.dict(os.environ, {"TORCHELASTIC_ERROR_FILE": replyfile}):
with self.assertRaises(ChildFailedError) as cm:
self.run_agent(Conf(entrypoint=_sad_function, local_world_size=2))
rank, failure = cm.exception.get_first_failure()
failure_data = failure.error_file_data["message"]
with open(replyfile) as fp:
data = json.load(fp)["message"]
# ran two; both failed; first failure is either rank 0 or 1
self.assertTrue(rank in {0, 1})
self.assertTrue(failure.local_rank in {0, 1})
self.assertEqual(1, failure.exitcode)
self.assertEqual(data["message"], failure_data["message"])
self.assertEqual(int(data["extraInfo"]["timestamp"]), failure.timestamp)
@skip_but_pass_in_sandcastle_if(
TEST_WITH_DEV_DBG_ASAN, "test incompatible with dev/dbg asan"
)
def test_run_sad_function_c10d(self):
self.run_test_with_backend(backend="c10d", test_to_run=self.run_sad_function)
@skip_but_pass_in_sandcastle_if(
TEST_WITH_DEV_DBG_ASAN, "test incompatible with dev/dbg asan"
)
def test_run_sad_function_etcd(self):
self.run_test_with_backend(backend="etcd", test_to_run=self.run_sad_function)
@skip_but_pass_in_sandcastle_if(
TEST_WITH_DEV_DBG_ASAN, "test incompatible with dev/dbg asan"
)
def test_run_sad_function_etcd_v2(self):
self.run_test_with_backend(backend="etcd-v2", test_to_run=self.run_sad_function)
def run_bipolar_function(self):
"""
checks agent failure handling logic
"""
node_conf = Conf(entrypoint=_bipolar_function, local_world_size=4)
spec = self.get_worker_spec(node_conf, max_restarts=2)
agent = self.get_agent(spec, node_config=node_conf)
run_result = agent.run()
self.assertTrue(run_result.is_failed())
self.assertEqual(0, agent._remaining_restarts)
self.assertEqual(WorkerState.FAILED, agent.get_worker_group().state)
self.assertTrue(agent._total_execution_time > 0)
@skip_but_pass_in_sandcastle_if(
TEST_WITH_DEV_DBG_ASAN, "test incompatible with dev/dbg asan"
)
def test_run_bipolar_function_c10d(self):
self.run_test_with_backend(
backend="c10d", test_to_run=self.run_bipolar_function
)
@skip_but_pass_in_sandcastle_if(
TEST_WITH_DEV_DBG_ASAN, "test incompatible with dev/dbg asan"
)
def test_run_bipolar_function_etcd(self):
self.run_test_with_backend(
backend="etcd", test_to_run=self.run_bipolar_function
)
@skip_but_pass_in_sandcastle_if(
TEST_WITH_DEV_DBG_ASAN, "test incompatible with dev/dbg asan"
)
def test_run_bipolar_function_etcd_v2(self):
self.run_test_with_backend(
backend="etcd-v2", test_to_run=self.run_bipolar_function
)
def correct_rank_assignment_heterogeneous(self):
node_configs = [
Conf(role="master", entrypoint=_get_role_info, local_world_size=8),
Conf(role="trainer", entrypoint=_get_role_info, local_world_size=1),
Conf(role="trainer", entrypoint=_get_role_info, local_world_size=2),
Conf(role="trainer", entrypoint=_get_role_info, local_world_size=3),
Conf(role="trainer", entrypoint=_get_role_info, local_world_size=4),
Conf(role="ps", entrypoint=_get_role_info, local_world_size=5),
Conf(role="ps", entrypoint=_get_role_info, local_world_size=2),
]
results = self.run_job(node_configs)
print(f"heterogeneous job result: {results}")
self.assertEqual(1, len(results["master"]))
self.assertEqual(4, len(results["trainer"]))
self.assertEqual(2, len(results["ps"]))
self.assert_rank_consistency(
results,
expected_role_world_sizes={
"master": 8,
"trainer": 1 + 2 + 3 + 4,
"ps": 5 + 2,
},
)
@unittest.skipIf(
TEST_WITH_DEV_DBG_ASAN or TEST_WITH_TSAN,
"test incompatible with dev/dbg asan or tsan",
)
def test_correct_rank_assignment_heterogeneous_etcd(self):
self.run_test_with_backend(
backend="etcd", test_to_run=self.correct_rank_assignment_heterogeneous
)
@unittest.skipIf(
TEST_WITH_DEV_DBG_ASAN or TEST_WITH_TSAN,
"test incompatible with dev/dbg asan or tsan",
)
def test_correct_rank_assignment_heterogeneous_etcd_v2(self):
self.run_test_with_backend(
backend="etcd-v2", test_to_run=self.correct_rank_assignment_heterogeneous
)
def correct_rank_assignment_homogeneous(self):
node_configs = [
Conf(role="master", entrypoint=_get_role_info, local_world_size=1),
Conf(role="trainer", entrypoint=_get_role_info, local_world_size=4),
Conf(role="trainer", entrypoint=_get_role_info, local_world_size=4),
Conf(role="trainer", entrypoint=_get_role_info, local_world_size=4),
Conf(role="trainer", entrypoint=_get_role_info, local_world_size=4),
Conf(role="ps", entrypoint=_get_role_info, local_world_size=3),
Conf(role="ps", entrypoint=_get_role_info, local_world_size=3),
]
results = self.run_job(node_configs)
print(f"homogeneous job result: {results}")
self.assertEqual(1, len(results["master"]))
self.assertEqual(4, len(results["trainer"]))
self.assertEqual(2, len(results["ps"]))
self.assert_rank_consistency(
results,
expected_role_world_sizes={"master": 1, "trainer": 4 * 4, "ps": 3 * 2},
)
@unittest.skipIf(
TEST_WITH_DEV_DBG_ASAN or TEST_WITH_TSAN,
"test incompatible with dev/dbg asan or tsan",
)
def test_correct_rank_assignment_homogeneous_etcd(self):
self.run_test_with_backend(
backend="etcd", test_to_run=self.correct_rank_assignment_homogeneous
)
@unittest.skipIf(
TEST_WITH_DEV_DBG_ASAN or TEST_WITH_TSAN,
"test incompatible with dev/dbg asan or tsan",
)
def test_correct_rank_assignment_homogeneous_etcd_v2(self):
self.run_test_with_backend(
backend="etcd-v2", test_to_run=self.correct_rank_assignment_homogeneous
)
def assert_rank_consistency(
self,
run_results: dict[str, list[RunResult]],
expected_role_world_sizes: dict[str, int],
):
"""
Asserts that ranks are consecutive w.r.t role_rank. If local world sizes are 4:
role_rank_0 -> ranks: 0,1,2,3
role_rank_1 -> ranks: 4,5,6,7
... etc ...
"""
global_ranks: list[int] = []
# role -> [role_rank,...]
role_ranks: dict[str, list[int]] = {}
# group rank -> [(rank, role_rank),...]
grouped_ranks: dict[int, list[tuple[int, int]]] = {}
# global world size == sum of all the role world sizes
expected_world_size = sum(expected_role_world_sizes.values())
for role, results in run_results.items():
for result in results:
res = result.return_values
for role_info in res.values():
rank = role_info.rank
role_rank = role_info.role_rank
group_rank = role_info.group_rank
role_world_size = role_info.role_world_size
world_size = role_info.world_size
self.assertEqual(expected_world_size, world_size)
self.assertEqual(expected_role_world_sizes[role], role_world_size)
grouped_ranks.setdefault(group_rank, []).append((rank, role_rank))
role_ranks.setdefault(role, []).append(role_rank)
global_ranks.append(rank)
global_ranks = sorted(global_ranks)
self.assertEqual(list(range(expected_world_size)), global_ranks)
for role, expected_role_world_size in expected_role_world_sizes.items():
self.assertEqual(
list(range(expected_role_world_size)), sorted(role_ranks[role])
)
# Make sure that each agent assigns consecutive ranks to workers
# The first argument is the global_rank and the second argument
# is role_rank
for ranks_lst in grouped_ranks.values():
self.assert_ranks_sequential(ranks_lst, 0)
self.assert_ranks_sequential(ranks_lst, 1)
def assert_ranks_sequential(self, ranks_pairs, rank_idx):
ranks = sorted(rank_pair[rank_idx] for rank_pair in ranks_pairs)
start_rank, end_rank = ranks[0], ranks[-1]
self.assertEqual(list(range(start_rank, end_rank + 1)), ranks)
def double_agent_fault_tolerance(self):
"""
start ``nnodes`` agents, kill and restart odd ones, validate fault-tolerance works
"""
nnodes = 2
wait = 2
node_conf = Conf(entrypoint=_dist_sum, args=(wait,), local_world_size=2)
agent_results = mp.Queue()
agent_args = {
"conf": node_conf,
"agent_results": agent_results,
"min_nodes": nnodes,
"max_nodes": nnodes,
"max_restarts": 2,
}
procs = []
for _ in range(nnodes):
p = mp.Process(
target=self.run_agent,
kwargs=agent_args,
)
procs.append(p)
p.start()
# restart odd agents
for i in range(nnodes):
if i % 2 != 0:
procs[i].kill()
p = mp.Process(
target=self.run_agent,
kwargs=agent_args,
)
procs[i] = p
p.start()
for i in range(nnodes):
p = procs[i]
p.join()
self.assertEqual(0, p.exitcode)
@unittest.skipIf(
TEST_WITH_DEV_DBG_ASAN or TEST_WITH_TSAN,
"test incompatible with dev/dbg asan or tsan",
)
def test_double_agent_fault_tolerance_etcd(self):
self.run_test_with_backend(
backend="etcd", test_to_run=self.double_agent_fault_tolerance
)
@unittest.skipIf(
TEST_WITH_DEV_DBG_ASAN or TEST_WITH_TSAN,
"test incompatible with dev/dbg asan or tsan",
)
def test_double_agent_fault_tolerance_etcd_v2(self):
self.run_test_with_backend(
backend="etcd-v2", test_to_run=self.double_agent_fault_tolerance
)
def no_exit_barrier_on_failure(self):
"""
start ``nnodes`` agents, kill and restart odd ones, validate fault-tolerance works
"""
nnodes = 2
wait = 20
node_conf = Conf(
entrypoint=_bipolar_sleep_function, args=(wait,), local_world_size=2
)
agent_results = mp.Queue()
monitor_interval_s = 0.5
agent_args = {
"conf": node_conf,
"agent_results": agent_results,
"min_nodes": nnodes,
"max_nodes": nnodes,
"max_restarts": 0,
"exit_barrier_timeout": 300,
"monitor_interval": monitor_interval_s,
}
procs = []
for _ in range(nnodes):
p = mp.Process(
target=self.run_agent,
kwargs=agent_args,
)
procs.append(p)
p.start()
# wait for all processes to finish should not take exit barrier time
exit_interval_between_agents = 0
for i in range(nnodes):
p = procs[i]
p.join()
self.assertNotEqual(0, p.exitcode)
exit_interval_between_agents = (
time.monotonic() - exit_interval_between_agents
)
# Validate that the processes finish close to each other.
# Using a slightly higher timeout than 2 * monitor_interval (0.01) to make it less flaky
self.assertGreater(
2 * monitor_interval_s,
exit_interval_between_agents,
"Agents are not cleaned up until 2 * monitor_interval",
)
@unittest.skipIf(
TEST_WITH_DEV_DBG_ASAN or TEST_WITH_TSAN,
"test incompatible with dev/dbg asan or tsan",
)
def test_no_exit_barrier_on_failure(self):
self.run_test_with_backend(
backend="c10d", test_to_run=self.no_exit_barrier_on_failure
)
def double_agent_elastic(self):
"""
start ``nnodes`` agents, kill odd ones (do not restart), validate
elasticity (scale-down) works. (scale-up covered in fault_tolerance test)
"""
min_nodes = 1
max_nodes = 2
wait = 2
node_conf = Conf(entrypoint=_dist_sum, args=(wait,), local_world_size=2)
agent_results = mp.Queue()
agent_args = {
"conf": node_conf,
"agent_results": agent_results,
"min_nodes": min_nodes,
"max_nodes": max_nodes,
"max_restarts": 2,
}
procs = []
for _ in range(max_nodes):
p = mp.Process(
target=self.run_agent,
kwargs=agent_args,
)
procs.append(p)
p.start()
# kill odd agents
for i in range(max_nodes):
if i % 2 != 0:
procs[i].kill()
for i in range(max_nodes):
p = procs[i]
p.join()
if i % 2 == 0:
self.assertEqual(0, p.exitcode)
else:
self.assertEqual(-signal.SIGKILL, p.exitcode)
@unittest.skipIf(
TEST_WITH_DEV_DBG_ASAN or TEST_WITH_TSAN,
"test incompatible with dev/dbg asan or tsan",
)
def test_double_agent_elastic_c10d(self):
self.run_test_with_backend(
backend="c10d", test_to_run=self.double_agent_elastic
)
@unittest.skipIf(
TEST_WITH_DEV_DBG_ASAN or TEST_WITH_TSAN,
"test incompatible with dev/dbg asan or tsan",
)
def test_double_agent_elastic_etcd(self):
self.run_test_with_backend(
backend="etcd", test_to_run=self.double_agent_elastic
)
@unittest.skipIf(
TEST_WITH_DEV_DBG_ASAN or TEST_WITH_TSAN,
"test incompatible with dev/dbg asan or tsan",
)
def test_double_agent_elastic_etcd_v2(self):
self.run_test_with_backend(
backend="etcd-v2", test_to_run=self.double_agent_elastic
)
def torch_rpc(self):
"""
Simple torch rpc example with torchelastic.
Creates two agents (to simulate two node job),
each agent runs a single worker. worker0 calls an rpc_sync on
worker1.
"""
msg = "hello world"
node_configs = [
Conf(
role="master",
entrypoint=rpc_master,
args=(msg,),
local_world_size=1,
tee=Std.ALL,
),
Conf(
role="worker",
entrypoint=rpc_worker,
args=(),
local_world_size=1,
tee=Std.ALL,
),
]
results = self.run_job(node_configs)
master_retvals = results["master"][0].return_values
# there is only one master but the global rank is not stable
# so compare the master return value as a collection
self.assertEqual([f"{msg} from worker"], list(master_retvals.values()))
@unittest.skipIf(
TEST_WITH_DEV_DBG_ASAN or TEST_WITH_TSAN,
"test incompatible with dev/dbg asan or tsan",
)
def test_torch_rpc_c10d(self):
self.run_test_with_backend(backend="c10d", test_to_run=self.torch_rpc)
@unittest.skipIf(
TEST_WITH_DEV_DBG_ASAN or TEST_WITH_TSAN,
"test incompatible with dev/dbg asan or tsan",
)
def test_torch_rpc_etcd(self):
self.run_test_with_backend(backend="etcd", test_to_run=self.torch_rpc)
@unittest.skipIf(
TEST_WITH_DEV_DBG_ASAN or TEST_WITH_TSAN,
"test incompatible with dev/dbg asan or tsan",
)
def test_torch_rpc_etcd_v2(self):
self.run_test_with_backend(backend="etcd-v2", test_to_run=self.torch_rpc)
def workers_drift_success(self):
"""
two agents (one worker each) finishes within ``sec`` seconds of each other,
exit barrier timeout set to ``sec * 2 * 2``.
"""
sec = 1
node_configs = [
Conf(role="zzz", entrypoint=_sleep, args=(0 * sec,), local_world_size=1),
Conf(role="zzz", entrypoint=_sleep, args=(2 * sec,), local_world_size=1),
]
results = self.run_job(node_configs, exit_barrier_timeout=2 * 2 * sec)
for i in range(2):
run_results = results["zzz"][i]
self.assertFalse(run_results.is_failed())
for rank, output in run_results.return_values.items():
# _sleep() returns its own rank
self.assertEqual(rank, output)
@unittest.skipIf(
TEST_WITH_DEV_DBG_ASAN or TEST_WITH_TSAN,
"test incompatible with dev/dbg asan or tsan",
)
def test_workers_drift_success_etcd(self):
self.run_test_with_backend(
backend="etcd", test_to_run=self.workers_drift_success
)
@unittest.skipIf(
TEST_WITH_DEV_DBG_ASAN or TEST_WITH_TSAN,
"test incompatible with dev/dbg asan or tsan",
)
def test_workers_drift_success_etcd_v2(self):
self.run_test_with_backend(
backend="etcd-v2", test_to_run=self.workers_drift_success
)
def workers_drift_fail(self):
"""
two agents (one worker each) finishes within ``4 x sec`` seconds of each other,
exit barrier timeout set to 0. Exit barriers should NOT fail the job.
"""
sec = 1
node_configs = [
Conf(role="zzz", entrypoint=_sleep, args=(0 * sec,), local_world_size=1),
Conf(role="zzz", entrypoint=_sleep, args=(4 * sec,), local_world_size=1),
]
results = self.run_job(node_configs, exit_barrier_timeout=0)
for i in range(2):
run_results = results["zzz"][i]
self.assertFalse(run_results.is_failed())
for rank, output in run_results.return_values.items():
# _sleep() returns its own rank
self.assertEqual(rank, output)
@unittest.skipIf(
TEST_WITH_DEV_DBG_ASAN or TEST_WITH_TSAN,
"test incompatible with dev/dbg asan or tsan",
)
def test_workers_drift_fail_etcd(self):
self.run_test_with_backend(backend="etcd", test_to_run=self.workers_drift_fail)
@unittest.skipIf(
TEST_WITH_DEV_DBG_ASAN or TEST_WITH_TSAN,
"test incompatible with dev/dbg asan or tsan",
)
def test_workers_drift_fail_etcd_v2(self):
self.run_test_with_backend(
backend="etcd-v2", test_to_run=self.workers_drift_fail
)
@patch("torch.distributed.elastic.utils.store.barrier")
def barrier_failed(self, barrier_mock):
"""
Failure during the barrier should NOT fail the job.
"""
barrier_mock.side_effect = RuntimeError("test error")
res = self.run_agent(Conf(entrypoint=_happy_function, local_world_size=1))
self.assertFalse(res.is_failed())
barrier_mock.assert_called_once()
@skip_but_pass_in_sandcastle_if(
TEST_WITH_DEV_DBG_ASAN, "test incompatible with dev/dbg asan"
)
def test_barrier_failed_c10d(self):
self.run_test_with_backend(backend="c10d", test_to_run=self.barrier_failed)
@skip_but_pass_in_sandcastle_if(
TEST_WITH_DEV_DBG_ASAN, "test incompatible with dev/dbg asan"
)
def test_barrier_failed_etcd(self):
self.run_test_with_backend(backend="etcd", test_to_run=self.barrier_failed)
@skip_but_pass_in_sandcastle_if(
TEST_WITH_DEV_DBG_ASAN, "test incompatible with dev/dbg asan"
)
def test_barrier_failed_etcd_v2(self):
self.run_test_with_backend(backend="etcd-v2", test_to_run=self.barrier_failed)
@patch("torch.distributed.elastic.agent.server.local_elastic_agent.start_processes")
def shutdown_called(self, start_processes_mock):
pcontext_mock = Mock()
pcontext_mock.pids.return_value = {0: 0}
start_processes_mock.return_value = pcontext_mock
node_conf = Conf(entrypoint=_happy_function, local_world_size=1)
spec = self.get_worker_spec(node_conf, max_restarts=0)
agent = self.get_agent(spec, node_config=node_conf)
with patch.object(agent, "_monitor_workers") as monitor_mock:
monitor_mock.return_value = RunResult(
state=WorkerState.SUCCEEDED, return_values={0: 0}
)
agent.run("worker")
pcontext_mock.close.assert_called_once()
@skip_but_pass_in_sandcastle_if(
TEST_WITH_DEV_DBG_ASAN, "test incompatible with dev/dbg asan"
)
def test_shutdown_called_c10d(self):
self.run_test_with_backend(backend="c10d", test_to_run=self.shutdown_called)
@skip_but_pass_in_sandcastle_if(
TEST_WITH_DEV_DBG_ASAN, "test incompatible with dev/dbg asan"
)
def test_shutdown_called_etcd(self):
self.run_test_with_backend(backend="etcd", test_to_run=self.shutdown_called)
@skip_but_pass_in_sandcastle_if(
TEST_WITH_DEV_DBG_ASAN, "test incompatible with dev/dbg asan"
)
def test_shutdown_called_etcd_v2(self):
self.run_test_with_backend(backend="etcd-v2", test_to_run=self.shutdown_called)
def fail_rank_one_once(self):
res = self.run_agent(
Conf(entrypoint=dummy_compute_simulate_rank_failure, local_world_size=2),
max_restarts=3,
)
self.assertFalse(res.is_failed())
for return_value in res.return_values.values():
self.assertIsInstance(return_value, torch.Tensor)
self.assertEqual((100, 100), return_value.shape)
@skip_but_pass_in_sandcastle_if(
TEST_WITH_DEV_DBG_ASAN, "test incompatible with dev/dbg asan"
)
def test_rank_restart_after_failure(self):
self.run_test_with_backend(backend="c10d", test_to_run=self.fail_rank_one_once)
if __name__ == "__main__":
raise RuntimeError(
"This test is not currently used and should be "
"enabled in discover_tests.py if required."
)
| LocalElasticAgentTest |
python | huggingface__transformers | src/transformers/models/afmoe/modeling_afmoe.py | {
"start": 10472,
"end": 15219
} | class ____(nn.Module):
"""
Mixture of Experts (MoE) module for AFMoE.
This module implements a sparse MoE layer with both shared experts (always active) and
routed experts (activated based on token-choice routing).
"""
def __init__(self, config):
super().__init__()
self.config = config
self.router = AfmoeTokenChoiceRouter(config)
self.shared_experts = AfmoeMLP(config, config.moe_intermediate_size * config.num_shared_experts)
self.experts = AfmoeExperts(config)
self.expert_bias = nn.Parameter(torch.zeros(config.num_experts, dtype=torch.float32), requires_grad=False)
def forward(self, hidden_states):
batch_size, seq_len, hidden_dim = hidden_states.shape
hidden_states_flat = hidden_states.view(-1, hidden_dim)
# Get routing decisions
top_scores, selected_experts = self.router(hidden_states, self.expert_bias)
top_scores = top_scores.view(batch_size, seq_len, self.config.num_experts_per_tok)
selected_experts = selected_experts.view(batch_size, seq_len, self.config.num_experts_per_tok)
# Process through shared experts
shared_output = self.shared_experts(hidden_states_flat).view(batch_size, seq_len, hidden_dim)
routed_output = self.experts(hidden_states, selected_experts, top_scores)
return shared_output + routed_output
def rotate_half(x):
"""Rotates half the hidden dims of the input."""
x1 = x[..., : x.shape[-1] // 2]
x2 = x[..., x.shape[-1] // 2 :]
return torch.cat((-x2, x1), dim=-1)
@use_kernel_func_from_hub("rotary_pos_emb")
def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):
"""Applies Rotary Position Embedding to the query and key tensors.
Args:
q (`torch.Tensor`): The query tensor.
k (`torch.Tensor`): The key tensor.
cos (`torch.Tensor`): The cosine part of the rotary embedding.
sin (`torch.Tensor`): The sine part of the rotary embedding.
position_ids (`torch.Tensor`, *optional*):
Deprecated and unused.
unsqueeze_dim (`int`, *optional*, defaults to 1):
The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
Returns:
`tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
"""
cos = cos.unsqueeze(unsqueeze_dim)
sin = sin.unsqueeze(unsqueeze_dim)
q_embed = (q * cos) + (rotate_half(q) * sin)
k_embed = (k * cos) + (rotate_half(k) * sin)
return q_embed, k_embed
def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
"""
This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
"""
batch, num_key_value_heads, slen, head_dim = hidden_states.shape
if n_rep == 1:
return hidden_states
hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
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: Unpack[TransformersKwargs],
):
key_states = repeat_kv(key, module.num_key_value_groups)
value_states = repeat_kv(value, module.num_key_value_groups)
attn_weights = torch.matmul(query, key_states.transpose(2, 3)) * scaling
if attention_mask is not None:
causal_mask = attention_mask[:, :, :, : key_states.shape[-2]]
attn_weights = attn_weights + causal_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_states)
attn_output = attn_output.transpose(1, 2).contiguous()
return attn_output, attn_weights
| AfmoeMoE |
python | huggingface__transformers | src/transformers/models/levit/modeling_levit.py | {
"start": 17704,
"end": 18150
} | class ____(nn.Module):
"""
LeViT Classification Layer
"""
def __init__(self, input_dim, output_dim):
super().__init__()
self.batch_norm = nn.BatchNorm1d(input_dim)
self.linear = nn.Linear(input_dim, output_dim)
def forward(self, hidden_state):
hidden_state = self.batch_norm(hidden_state)
logits = self.linear(hidden_state)
return logits
@auto_docstring
| LevitClassificationLayer |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/genericType3.py | {
"start": 360,
"end": 599
} | class ____(Root[T]):
pass
root_int: Root[int] = Root[int](lambda x: x << 2)
# This should generate an error.
root_float: Root[float] = root_int
# This should generate an error.
root_float: Root[float] = Root[int](lambda x: x << 2)
| Leaf |
python | bokeh__bokeh | src/bokeh/models/expressions.py | {
"start": 9114,
"end": 9890
} | class ____(XYComponent):
""" Y-component of a coordinate system transform to cartesian coordinates. """
# explicit __init__ to support Init signatures
def __init__(self, *args: Any, **kwargs: Any) -> None:
super().__init__(*args, **kwargs)
#-----------------------------------------------------------------------------
# Dev API
#-----------------------------------------------------------------------------
#-----------------------------------------------------------------------------
# Private API
#-----------------------------------------------------------------------------
#-----------------------------------------------------------------------------
# Code
#-----------------------------------------------------------------------------
| YComponent |
python | numba__numba | numba/core/datamodel/models.py | {
"start": 39763,
"end": 41265
} | class ____(StructModel):
def __init__(self, dmm, fe_type):
array_types = fe_type.arrays
ndim = fe_type.ndim
shape_len = ndim if fe_type.need_shaped_indexing else 1
members = [('exhausted', types.EphemeralPointer(types.boolean)),
('arrays', types.Tuple(array_types)),
# The iterator's main shape and indices
('shape', types.UniTuple(types.intp, shape_len)),
('indices', types.EphemeralArray(types.intp, shape_len)),
]
# Indexing state for the various sub-iterators
# XXX use a tuple instead?
for i, sub in enumerate(fe_type.indexers):
kind, start_dim, end_dim, _ = sub
member_name = 'index%d' % i
if kind == 'flat':
# A single index into the flattened array
members.append((member_name, types.EphemeralPointer(types.intp)))
elif kind in ('scalar', 'indexed', '0d'):
# Nothing required
pass
else:
assert 0
# Slots holding values of the scalar args
# XXX use a tuple instead?
for i, ty in enumerate(fe_type.arrays):
if not isinstance(ty, types.Array):
member_name = 'scalar%d' % i
members.append((member_name, types.EphemeralPointer(ty)))
super(NdIter, self).__init__(dmm, fe_type, members)
@register_default(types.DeferredType)
| NdIter |
python | great-expectations__great_expectations | great_expectations/execution_engine/pandas_batch_data.py | {
"start": 167,
"end": 443
} | class ____(BatchData):
def __init__(self, execution_engine, dataframe: pd.DataFrame) -> None:
super().__init__(execution_engine=execution_engine)
self._dataframe = dataframe
@property
def dataframe(self):
return self._dataframe
| PandasBatchData |
python | pandas-dev__pandas | pandas/core/_numba/extensions.py | {
"start": 5784,
"end": 16982
} | class ____(models.StructModel):
def __init__(self, dmm, fe_type) -> None:
members = [
("index", fe_type.index),
("values", fe_type.as_array),
("name", fe_type.namety),
]
models.StructModel.__init__(self, dmm, fe_type, members)
make_attribute_wrapper(IndexType, "data", "_data")
make_attribute_wrapper(IndexType, "hashmap", "hashmap")
make_attribute_wrapper(SeriesType, "index", "index")
make_attribute_wrapper(SeriesType, "values", "values")
make_attribute_wrapper(SeriesType, "name", "name")
@lower_builtin(Series, types.Array, IndexType)
def pdseries_constructor(context, builder, sig, args):
data, index = args
series = cgutils.create_struct_proxy(sig.return_type)(context, builder)
series.index = index
series.values = data
series.name = context.get_constant(types.intp, 0)
return impl_ret_borrowed(context, builder, sig.return_type, series._getvalue())
@lower_builtin(Series, types.Array, IndexType, types.intp)
@lower_builtin(Series, types.Array, IndexType, types.float64)
@lower_builtin(Series, types.Array, IndexType, types.unicode_type)
def pdseries_constructor_with_name(context, builder, sig, args):
data, index, name = args
series = cgutils.create_struct_proxy(sig.return_type)(context, builder)
series.index = index
series.values = data
series.name = name
return impl_ret_borrowed(context, builder, sig.return_type, series._getvalue())
@lower_builtin(Index, types.Array, types.DictType, types.pyobject)
def index_constructor_2arg(context, builder, sig, args):
(data, hashmap, parent) = args
index = cgutils.create_struct_proxy(sig.return_type)(context, builder)
index.data = data
index.hashmap = hashmap
index.parent = parent
return impl_ret_borrowed(context, builder, sig.return_type, index._getvalue())
@lower_builtin(Index, types.Array, types.DictType)
def index_constructor_2arg_parent(context, builder, sig, args):
# Basically same as index_constructor_1arg, but also lets you specify the
# parent object
(data, hashmap) = args
index = cgutils.create_struct_proxy(sig.return_type)(context, builder)
index.data = data
index.hashmap = hashmap
return impl_ret_borrowed(context, builder, sig.return_type, index._getvalue())
@lower_builtin(Index, types.Array)
def index_constructor_1arg(context, builder, sig, args):
from numba.typed import Dict
key_type = sig.return_type.dtype
value_type = types.intp
def index_impl(data):
return Index(data, Dict.empty(key_type, value_type))
return context.compile_internal(builder, index_impl, sig, args)
# Helper to convert the unicodecharseq (numpy string scalar) into a unicode_type
# (regular string)
def maybe_cast_str(x):
# Dummy function that numba can overload
pass
@overload(maybe_cast_str)
def maybe_cast_str_impl(x):
"""Converts numba UnicodeCharSeq (numpy string scalar) -> unicode type (string).
Is a no-op for other types."""
if isinstance(x, types.UnicodeCharSeq):
return lambda x: str(x)
else:
return lambda x: x
@unbox(IndexType)
def unbox_index(typ, obj, c):
"""
Convert a Index object to a native structure.
Note: Object dtype is not allowed here
"""
data_obj = c.pyapi.object_getattr_string(obj, "_numba_data")
index = cgutils.create_struct_proxy(typ)(c.context, c.builder)
# If we see an object array, assume its been validated as only containing strings
# We still need to do the conversion though
index.data = c.unbox(typ.as_array, data_obj).value
typed_dict_obj = c.pyapi.unserialize(c.pyapi.serialize_object(numba.typed.Dict))
# Create an empty typed dict in numba for the hashmap for indexing
# equiv of numba.typed.Dict.empty(typ.dtype, types.intp)
arr_type_obj = c.pyapi.unserialize(c.pyapi.serialize_object(typ.dtype))
intp_type_obj = c.pyapi.unserialize(c.pyapi.serialize_object(types.intp))
hashmap_obj = c.pyapi.call_method(
typed_dict_obj, "empty", (arr_type_obj, intp_type_obj)
)
index.hashmap = c.unbox(types.DictType(typ.dtype, types.intp), hashmap_obj).value
# Set the parent for speedy boxing.
index.parent = obj
# Decrefs
c.pyapi.decref(data_obj)
c.pyapi.decref(arr_type_obj)
c.pyapi.decref(intp_type_obj)
c.pyapi.decref(typed_dict_obj)
return NativeValue(index._getvalue())
@unbox(SeriesType)
def unbox_series(typ, obj, c):
"""
Convert a Series object to a native structure.
"""
index_obj = c.pyapi.object_getattr_string(obj, "index")
values_obj = c.pyapi.object_getattr_string(obj, "values")
name_obj = c.pyapi.object_getattr_string(obj, "name")
series = cgutils.create_struct_proxy(typ)(c.context, c.builder)
series.index = c.unbox(typ.index, index_obj).value
series.values = c.unbox(typ.values, values_obj).value
series.name = c.unbox(typ.namety, name_obj).value
# Decrefs
c.pyapi.decref(index_obj)
c.pyapi.decref(values_obj)
c.pyapi.decref(name_obj)
return NativeValue(series._getvalue())
@box(IndexType)
def box_index(typ, val, c):
"""
Convert a native index structure to a Index object.
If our native index is of a numpy string dtype, we'll cast it to
object.
"""
# First build a Numpy array object, then wrap it in a Index
index = cgutils.create_struct_proxy(typ)(c.context, c.builder, value=val)
res = cgutils.alloca_once_value(c.builder, index.parent)
# Does parent exist?
# (it means already boxed once, or Index same as original df.index or df.columns)
# xref https://github.com/numba/numba/blob/596e8a55334cc46854e3192766e643767bd7c934/numba/core/boxing.py#L593C17-L593C17
with c.builder.if_else(cgutils.is_not_null(c.builder, index.parent)) as (
has_parent,
otherwise,
):
with has_parent:
c.pyapi.incref(index.parent)
with otherwise:
# TODO: preserve the original class for the index
# Also need preserve the name of the Index
# class_obj = c.pyapi.unserialize(c.pyapi.serialize_object(typ.pyclass))
class_obj = c.pyapi.unserialize(c.pyapi.serialize_object(Index))
array_obj = c.box(typ.as_array, index.data)
if isinstance(typ.dtype, types.UnicodeCharSeq):
# We converted to numpy string dtype, convert back
# to object since _simple_new won't do that for uss
object_str_obj = c.pyapi.unserialize(c.pyapi.serialize_object("object"))
array_obj = c.pyapi.call_method(array_obj, "astype", (object_str_obj,))
c.pyapi.decref(object_str_obj)
# this is basically Index._simple_new(array_obj, name_obj) in python
index_obj = c.pyapi.call_method(class_obj, "_simple_new", (array_obj,))
index.parent = index_obj
c.builder.store(index_obj, res)
# Decrefs
c.pyapi.decref(class_obj)
c.pyapi.decref(array_obj)
return c.builder.load(res)
@box(SeriesType)
def box_series(typ, val, c):
"""
Convert a native series structure to a Series object.
"""
series = cgutils.create_struct_proxy(typ)(c.context, c.builder, value=val)
series_const_obj = c.pyapi.unserialize(c.pyapi.serialize_object(Series._from_mgr))
mgr_const_obj = c.pyapi.unserialize(
c.pyapi.serialize_object(SingleBlockManager.from_array)
)
index_obj = c.box(typ.index, series.index)
array_obj = c.box(typ.as_array, series.values)
name_obj = c.box(typ.namety, series.name)
# This is basically equivalent of
# pd.Series(data=array_obj, index=index_obj)
# To improve perf, we will construct the Series from a manager
# object to avoid checks.
# We'll also set the name attribute manually to avoid validation
mgr_obj = c.pyapi.call_function_objargs(
mgr_const_obj,
(
array_obj,
index_obj,
),
)
mgr_axes_obj = c.pyapi.object_getattr_string(mgr_obj, "axes")
# Series._constructor_from_mgr(mgr, axes)
series_obj = c.pyapi.call_function_objargs(
series_const_obj, (mgr_obj, mgr_axes_obj)
)
c.pyapi.object_setattr_string(series_obj, "_name", name_obj)
# Decrefs
c.pyapi.decref(series_const_obj)
c.pyapi.decref(mgr_axes_obj)
c.pyapi.decref(mgr_obj)
c.pyapi.decref(mgr_const_obj)
c.pyapi.decref(index_obj)
c.pyapi.decref(array_obj)
c.pyapi.decref(name_obj)
return series_obj
# Add common series reductions (e.g. mean, sum),
# and also add common binops (e.g. add, sub, mul, div)
def generate_series_reduction(ser_reduction, ser_method):
@overload_method(SeriesType, ser_reduction)
def series_reduction(series):
def series_reduction_impl(series):
return ser_method(series.values)
return series_reduction_impl
return series_reduction
def generate_series_binop(binop):
@overload(binop)
def series_binop(series1, value):
if isinstance(series1, SeriesType):
if isinstance(value, SeriesType):
def series_binop_impl(series1, series2):
# TODO: Check index matching?
return Series(
binop(series1.values, series2.values),
series1.index,
series1.name,
)
return series_binop_impl
else:
def series_binop_impl(series1, value):
return Series(
binop(series1.values, value), series1.index, series1.name
)
return series_binop_impl
return series_binop
series_reductions = [
("sum", np.sum),
("mean", np.mean),
# Disabled due to discrepancies between numba std. dev
# and pandas std. dev (no way to specify dof)
# ("std", np.std),
# ("var", np.var),
("min", np.min),
("max", np.max),
]
for reduction, reduction_method in series_reductions:
generate_series_reduction(reduction, reduction_method)
series_binops = [operator.add, operator.sub, operator.mul, operator.truediv]
for ser_binop in series_binops:
generate_series_binop(ser_binop)
# get_loc on Index
@overload_method(IndexType, "get_loc")
def index_get_loc(index, item):
def index_get_loc_impl(index, item):
# Initialize the hash table if not initialized
if len(index.hashmap) == 0:
for i, val in enumerate(index._data):
index.hashmap[val] = i
return index.hashmap[item]
return index_get_loc_impl
# Indexing for Series/Index
@overload(operator.getitem)
def series_indexing(series, item):
if isinstance(series, SeriesType):
def series_getitem(series, item):
loc = series.index.get_loc(item)
return series.iloc[loc]
return series_getitem
@overload(operator.getitem)
def index_indexing(index, idx):
if isinstance(index, IndexType):
def index_getitem(index, idx):
return index._data[idx]
return index_getitem
| SeriesModel |
python | squidfunk__mkdocs-material | material/plugins/social/layout.py | {
"start": 3664,
"end": 5020
} | class ____(Config):
definitions = ListOfItems(Type(str), default = [])
tags = DictOfItems(Type(str), default = {})
size = SubConfig(Size)
layers = ListOfItems(SubConfig(Layer), default = [])
# -----------------------------------------------------------------------------
# Functions
# -----------------------------------------------------------------------------
# Get layer or layout size as tuple
def get_size(layer: Layer | Layout):
return layer.size.width, layer.size.height
# Get layer offset as tuple
def get_offset(layer: Layer, image: _Image):
x, y = layer.offset.x, layer.offset.y
# Compute offset from origin - if an origin is given, compute the offset
# relative to the image and layer size to allow for flexible positioning
if layer.origin != "start top":
origin = re.split(r"\s+", layer.origin)
# Get layer size
w, h = get_size(layer)
# Compute origin on x-axis
if "start" in origin: pass
elif "end" in origin: x += (image.width - w) - 2 * x
elif "center" in origin: x += (image.width - w) >> 1
# Compute origin on y-axis
if "top" in origin: pass
elif "bottom" in origin: y += (image.height - h) - 2 * y
elif "center" in origin: y += (image.height - h) >> 1
# Return offset
return x, y
| Layout |
python | coleifer__peewee | tests/sqlite.py | {
"start": 91692,
"end": 94972
} | class ____(ModelTestCase):
database = database
requires = [Person, User, KVR]
def test_sqlite_returning(self):
iq = (User
.insert_many([{'username': 'u%s' % i} for i in range(3)])
.returning(User.id))
self.assertEqual([r.id for r in iq.execute()], [1, 2, 3])
res = (User
.insert_many([{'username': 'u%s' % i} for i in (4, 5)])
.returning(User)
.execute())
self.assertEqual([(r.id, r.username) for r in res],
[(4, 'u4'), (5, 'u5')])
# Simple insert returns the ID.
res = User.insert(username='u6').execute()
self.assertEqual(res, 6)
iq = (User
.insert_many([{'username': 'u%s' % i} for i in (7, 8, 9)])
.returning(User)
.namedtuples())
curs = iq.execute()
self.assertEqual([u.id for u in curs], [7, 8, 9])
def test_sqlite_on_conflict_returning(self):
p = Person.create(first='f1', last='l1', dob='1990-01-01')
self.assertEqual(p.id, 1)
iq = Person.insert_many([
{'first': 'f%s' % i, 'last': 'l%s' %i, 'dob': '1990-01-%02d' % i}
for i in range(1, 3)])
iq = iq.on_conflict(conflict_target=[Person.first, Person.last],
update={'dob': '2000-01-01'})
p1, p2 = iq.returning(Person).execute()
self.assertEqual((p1.first, p1.last), ('f1', 'l1'))
self.assertEqual(p1.dob, datetime.date(2000, 1, 1))
self.assertEqual((p2.first, p2.last), ('f2', 'l2'))
self.assertEqual(p2.dob, datetime.date(1990, 1, 2))
p3 = Person.insert(first='f3', last='l3', dob='1990-01-03').execute()
self.assertEqual(p3, 3)
def test_text_pk(self):
res = KVR.create(key='k1', value=1)
self.assertEqual((res.key, res.value), ('k1', 1))
res = KVR.insert(key='k2', value=2).execute()
self.assertEqual(res, 2)
#self.assertEqual(res, 'k2')
# insert_many() returns the primary-key as usual.
iq = (KVR
.insert_many([{'key': 'k%s' % i, 'value': i} for i in (3, 4)])
.returning(KVR.key))
self.assertEqual([r.key for r in iq.execute()], ['k3', 'k4'])
iq = KVR.insert_many([{'key': 'k%s' % i, 'value': i} for i in (4, 5)])
iq = iq.on_conflict(conflict_target=[KVR.key],
update={KVR.value: KVR.value + 10})
res = iq.returning(KVR).execute()
self.assertEqual([(r.key, r.value) for r in res],
[('k4', 14), ('k5', 5)])
res = (KVR
.update(value=KVR.value + 10)
.where(KVR.key.in_(['k1', 'k3', 'kx']))
.returning(KVR)
.execute())
self.assertEqual([(r.key, r.value) for r in res],
[('k1', 11), ('k3', 13)])
res = (KVR.delete()
.where(KVR.key.not_in(['k2', 'k3', 'k4']))
.returning(KVR)
.execute())
self.assertEqual([(r.key, r.value) for r in res],
[('k1', 11), ('k5', 5)])
@skip_unless(database.server_version >= (3, 35, 0), 'sqlite returning clause required')
| TestSqliteReturning |
python | django__django | tests/deprecation/tests.py | {
"start": 208,
"end": 836
} | class ____(SimpleTestCase):
def setUp(self):
django_file_prefixes.cache_clear()
self.addCleanup(django_file_prefixes.cache_clear)
def test_no_file(self):
orig_file = django.__file__
try:
del django.__file__
self.assertEqual(django_file_prefixes(), ())
finally:
django.__file__ = orig_file
def test_with_file(self):
prefixes = django_file_prefixes()
self.assertIsInstance(prefixes, tuple)
self.assertEqual(len(prefixes), 1)
self.assertTrue(prefixes[0].endswith(f"{os.path.sep}django"))
| DjangoFilePrefixesTests |
python | davidhalter__jedi | test/test_api/test_full_name.py | {
"start": 1061,
"end": 1388
} | class ____(MixinTestFullName, TestCase):
operation = 'infer'
def test_tuple_mapping(self):
self.check("""
import re
any_re = re.compile('.*')
any_re""", 'typing.Pattern')
def test_from_import(self):
self.check('from os import path', 'os.path')
| TestFullNameWithGotoDefinitions |
python | openai__openai-python | src/openai/_response.py | {
"start": 9577,
"end": 12938
} | class ____(BaseAPIResponse[R]):
@property
def request_id(self) -> str | None:
return self.http_response.headers.get("x-request-id") # type: ignore[no-any-return]
@overload
def parse(self, *, to: type[_T]) -> _T: ...
@overload
def parse(self) -> R: ...
def parse(self, *, to: type[_T] | None = None) -> R | _T:
"""Returns the rich python representation of this response's data.
For lower-level control, see `.read()`, `.json()`, `.iter_bytes()`.
You can customise the type that the response is parsed into through
the `to` argument, e.g.
```py
from openai import BaseModel
class MyModel(BaseModel):
foo: str
obj = response.parse(to=MyModel)
print(obj.foo)
```
We support parsing:
- `BaseModel`
- `dict`
- `list`
- `Union`
- `str`
- `int`
- `float`
- `httpx.Response`
"""
cache_key = to if to is not None else self._cast_to
cached = self._parsed_by_type.get(cache_key)
if cached is not None:
return cached # type: ignore[no-any-return]
if not self._is_sse_stream:
self.read()
parsed = self._parse(to=to)
if is_given(self._options.post_parser):
parsed = self._options.post_parser(parsed)
if isinstance(parsed, BaseModel):
add_request_id(parsed, self.request_id)
self._parsed_by_type[cache_key] = parsed
return cast(R, parsed)
def read(self) -> bytes:
"""Read and return the binary response content."""
try:
return self.http_response.read()
except httpx.StreamConsumed as exc:
# The default error raised by httpx isn't very
# helpful in our case so we re-raise it with
# a different error message.
raise StreamAlreadyConsumed() from exc
def text(self) -> str:
"""Read and decode the response content into a string."""
self.read()
return self.http_response.text
def json(self) -> object:
"""Read and decode the JSON response content."""
self.read()
return self.http_response.json()
def close(self) -> None:
"""Close the response and release the connection.
Automatically called if the response body is read to completion.
"""
self.http_response.close()
def iter_bytes(self, chunk_size: int | None = None) -> Iterator[bytes]:
"""
A byte-iterator over the decoded response content.
This automatically handles gzip, deflate and brotli encoded responses.
"""
for chunk in self.http_response.iter_bytes(chunk_size):
yield chunk
def iter_text(self, chunk_size: int | None = None) -> Iterator[str]:
"""A str-iterator over the decoded response content
that handles both gzip, deflate, etc but also detects the content's
string encoding.
"""
for chunk in self.http_response.iter_text(chunk_size):
yield chunk
def iter_lines(self) -> Iterator[str]:
"""Like `iter_text()` but will only yield chunks for each line"""
for chunk in self.http_response.iter_lines():
yield chunk
| APIResponse |
python | django__django | django/contrib/auth/migrations/0006_require_contenttypes_0002.py | {
"start": 35,
"end": 369
} | class ____(migrations.Migration):
dependencies = [
("auth", "0005_alter_user_last_login_null"),
("contenttypes", "0002_remove_content_type_name"),
]
operations = [
# Ensure the contenttypes migration is applied before sending
# post_migrate signals (which create ContentTypes).
]
| Migration |
python | celery__celery | t/unit/worker/test_request.py | {
"start": 3199,
"end": 5695
} | class ____(RequestCase):
def test_process_cleanup_fails(self, patching):
_logger = patching('celery.app.trace.logger')
self.mytask.backend = Mock()
self.mytask.backend.process_cleanup = Mock(side_effect=KeyError())
tid = uuid()
ret = jail(self.app, tid, self.mytask.name, {}, [2], {})
assert ret == 4
self.mytask.backend.mark_as_done.assert_called()
assert 'Process cleanup failed' in _logger.error.call_args[0][0]
def test_process_cleanup_BaseException(self):
self.mytask.backend = Mock()
self.mytask.backend.process_cleanup = Mock(side_effect=SystemExit())
with pytest.raises(SystemExit):
jail(self.app, uuid(), self.mytask.name, {}, [2], {})
def test_execute_jail_success(self):
ret = jail(self.app, uuid(), self.mytask.name, {}, [2], {})
assert ret == 4
def test_marked_as_started(self):
_started = []
def store_result(tid, meta, state, **kwargs):
if state == states.STARTED:
_started.append(tid)
self.mytask.backend.store_result = Mock(name='store_result')
self.mytask.backend.store_result.side_effect = store_result
self.mytask.track_started = True
tid = uuid()
jail(self.app, tid, self.mytask.name, {}, [2], {})
assert tid in _started
self.mytask.ignore_result = True
tid = uuid()
jail(self.app, tid, self.mytask.name, {}, [2], {})
assert tid not in _started
def test_execute_jail_failure(self):
ret = jail(
self.app, uuid(), self.mytask_raising.name, {}, [4], {},
)
assert isinstance(ret, ExceptionInfo)
assert ret.exception.args == (4,)
def test_execute_task_ignore_result(self):
@self.app.task(shared=False, ignore_result=True)
def ignores_result(i):
return i ** i
task_id = uuid()
ret = jail(self.app, task_id, ignores_result.name, {}, [4], {})
assert ret == 256
assert not self.app.AsyncResult(task_id).ready()
def test_execute_request_ignore_result(self):
@self.app.task(shared=False)
def ignores_result(i):
return i ** i
task_id = uuid()
ret = jail(
self.app, task_id, ignores_result.name,
{'ignore_result': True}, [4], {}
)
assert ret == 256
assert not self.app.AsyncResult(task_id).ready()
| test_trace_task |
python | django__django | tests/or_lookups/tests.py | {
"start": 158,
"end": 7620
} | class ____(TestCase):
@classmethod
def setUpTestData(cls):
cls.a1 = Article.objects.create(
headline="Hello", pub_date=datetime(2005, 11, 27)
).pk
cls.a2 = Article.objects.create(
headline="Goodbye", pub_date=datetime(2005, 11, 28)
).pk
cls.a3 = Article.objects.create(
headline="Hello and goodbye", pub_date=datetime(2005, 11, 29)
).pk
def test_filter_or(self):
self.assertQuerySetEqual(
(
Article.objects.filter(headline__startswith="Hello")
| Article.objects.filter(headline__startswith="Goodbye")
),
["Hello", "Goodbye", "Hello and goodbye"],
attrgetter("headline"),
)
self.assertQuerySetEqual(
Article.objects.filter(headline__contains="Hello")
| Article.objects.filter(headline__contains="bye"),
["Hello", "Goodbye", "Hello and goodbye"],
attrgetter("headline"),
)
self.assertQuerySetEqual(
Article.objects.filter(headline__iexact="Hello")
| Article.objects.filter(headline__contains="ood"),
["Hello", "Goodbye", "Hello and goodbye"],
attrgetter("headline"),
)
self.assertQuerySetEqual(
Article.objects.filter(
Q(headline__startswith="Hello") | Q(headline__startswith="Goodbye")
),
["Hello", "Goodbye", "Hello and goodbye"],
attrgetter("headline"),
)
def test_stages(self):
# You can shorten this syntax with code like the following, which is
# especially useful if building the query in stages:
articles = Article.objects.all()
self.assertQuerySetEqual(
articles.filter(headline__startswith="Hello")
& articles.filter(headline__startswith="Goodbye"),
[],
)
self.assertQuerySetEqual(
articles.filter(headline__startswith="Hello")
& articles.filter(headline__contains="bye"),
["Hello and goodbye"],
attrgetter("headline"),
)
def test_pk_q(self):
self.assertQuerySetEqual(
Article.objects.filter(Q(pk=self.a1) | Q(pk=self.a2)),
["Hello", "Goodbye"],
attrgetter("headline"),
)
self.assertQuerySetEqual(
Article.objects.filter(Q(pk=self.a1) | Q(pk=self.a2) | Q(pk=self.a3)),
["Hello", "Goodbye", "Hello and goodbye"],
attrgetter("headline"),
)
def test_pk_in(self):
self.assertQuerySetEqual(
Article.objects.filter(pk__in=[self.a1, self.a2, self.a3]),
["Hello", "Goodbye", "Hello and goodbye"],
attrgetter("headline"),
)
self.assertQuerySetEqual(
Article.objects.filter(pk__in=(self.a1, self.a2, self.a3)),
["Hello", "Goodbye", "Hello and goodbye"],
attrgetter("headline"),
)
self.assertQuerySetEqual(
Article.objects.filter(pk__in=[self.a1, self.a2, self.a3, 40000]),
["Hello", "Goodbye", "Hello and goodbye"],
attrgetter("headline"),
)
def test_q_repr(self):
or_expr = Q(baz=Article(headline="Foö"))
self.assertEqual(repr(or_expr), "<Q: (AND: ('baz', <Article: Foö>))>")
negated_or = ~Q(baz=Article(headline="Foö"))
self.assertEqual(repr(negated_or), "<Q: (NOT (AND: ('baz', <Article: Foö>)))>")
def test_q_negated(self):
# Q objects can be negated
self.assertQuerySetEqual(
Article.objects.filter(Q(pk=self.a1) | ~Q(pk=self.a2)),
["Hello", "Hello and goodbye"],
attrgetter("headline"),
)
self.assertQuerySetEqual(
Article.objects.filter(~Q(pk=self.a1) & ~Q(pk=self.a2)),
["Hello and goodbye"],
attrgetter("headline"),
)
# This allows for more complex queries than filter() and exclude()
# alone would allow
self.assertQuerySetEqual(
Article.objects.filter(Q(pk=self.a1) & (~Q(pk=self.a2) | Q(pk=self.a3))),
["Hello"],
attrgetter("headline"),
)
def test_complex_filter(self):
# The 'complex_filter' method supports framework features such as
# 'limit_choices_to' which normally take a single dictionary of lookup
# arguments but need to support arbitrary queries via Q objects too.
self.assertQuerySetEqual(
Article.objects.complex_filter({"pk": self.a1}),
["Hello"],
attrgetter("headline"),
)
self.assertQuerySetEqual(
Article.objects.complex_filter(Q(pk=self.a1) | Q(pk=self.a2)),
["Hello", "Goodbye"],
attrgetter("headline"),
)
def test_empty_in(self):
# Passing "in" an empty list returns no results ...
self.assertQuerySetEqual(Article.objects.filter(pk__in=[]), [])
# ... but can return results if we OR it with another query.
self.assertQuerySetEqual(
Article.objects.filter(Q(pk__in=[]) | Q(headline__icontains="goodbye")),
["Goodbye", "Hello and goodbye"],
attrgetter("headline"),
)
def test_q_and(self):
# Q arg objects are ANDed
self.assertQuerySetEqual(
Article.objects.filter(
Q(headline__startswith="Hello"), Q(headline__contains="bye")
),
["Hello and goodbye"],
attrgetter("headline"),
)
# Q arg AND order is irrelevant
self.assertQuerySetEqual(
Article.objects.filter(
Q(headline__contains="bye"), headline__startswith="Hello"
),
["Hello and goodbye"],
attrgetter("headline"),
)
self.assertQuerySetEqual(
Article.objects.filter(
Q(headline__startswith="Hello") & Q(headline__startswith="Goodbye")
),
[],
)
def test_q_exclude(self):
self.assertQuerySetEqual(
Article.objects.exclude(Q(headline__startswith="Hello")),
["Goodbye"],
attrgetter("headline"),
)
def test_other_arg_queries(self):
# Try some arg queries with operations other than filter.
self.assertEqual(
Article.objects.get(
Q(headline__startswith="Hello"), Q(headline__contains="bye")
).headline,
"Hello and goodbye",
)
self.assertEqual(
Article.objects.filter(
Q(headline__startswith="Hello") | Q(headline__contains="bye")
).count(),
3,
)
self.assertSequenceEqual(
Article.objects.filter(
Q(headline__startswith="Hello"), Q(headline__contains="bye")
).values(),
[
{
"headline": "Hello and goodbye",
"id": self.a3,
"pub_date": datetime(2005, 11, 29),
},
],
)
self.assertEqual(
Article.objects.filter(Q(headline__startswith="Hello")).in_bulk(
[self.a1, self.a2]
),
{self.a1: Article.objects.get(pk=self.a1)},
)
| OrLookupsTests |
python | tensorflow__tensorflow | tensorflow/python/client/session.py | {
"start": 16770,
"end": 17507
} | class ____(_FetchMapper):
"""Fetch mapper for attrs decorated classes."""
def __init__(self, fetches):
"""Creates a _AttrsFetchMapper.
Args:
fetches: An instance of an attrs decorated class.
"""
values = _get_attrs_values(fetches)
self._fetch_type = type(fetches)
self._mappers = [_FetchMapper.for_fetch(fetch) for fetch in values]
self._unique_fetches, self._value_indices = _uniquify_fetches(self._mappers)
def unique_fetches(self):
return self._unique_fetches
def build_results(self, values):
results = []
for m, vi in zip(self._mappers, self._value_indices):
results.append(m.build_results([values[j] for j in vi]))
return self._fetch_type(*results)
| _AttrsFetchMapper |
python | tensorflow__tensorflow | tensorflow/tools/proto_splitter/split_graph_def.py | {
"start": 1167,
"end": 5369
} | class ____(split.ComposableSplitter):
"""Implements proto splitter for GraphDef.
This Splitter will modify the passed in proto in place.
"""
def build_chunks(self):
"""Splits a GraphDef proto into smaller chunks."""
proto = self._proto
if not isinstance(proto, graph_pb2.GraphDef):
raise TypeError("Can only split GraphDef type protos.")
proto_size = proto.ByteSize()
if proto_size < constants.max_size():
return
# Split `GraphDef.node`
node_splitter = RepeatedMessageSplitter(
proto,
"node",
[ConstantNodeDefSplitter, LargeMessageSplitter],
parent_splitter=self,
fields_in_parent=[],
)
# Split `GraphDef.library.function`
function_splitter = RepeatedMessageSplitter(
proto.library,
["function"],
[FunctionDefSplitter],
parent_splitter=self,
fields_in_parent=["library"],
)
library_size = proto.library.ByteSize()
approx_node_size = proto_size - library_size
if library_size > approx_node_size:
library_size -= function_splitter.build_chunks()
if library_size + approx_node_size > constants.max_size():
approx_node_size -= node_splitter.build_chunks()
else:
approx_node_size -= node_splitter.build_chunks()
if library_size + approx_node_size > constants.max_size():
library_size -= function_splitter.build_chunks()
if proto.ByteSize() > constants.max_size():
# Since there are chunks with the "library" field tag, insert this
# chunk before the other chunks at index 1 (index 0 is reserved for the
# base chunk).
self.add_chunk(proto.library, ["library"], 1)
proto.ClearField("library")
_KEEP_TENSOR_PROTO_FIELDS = ("dtype", "tensor_shape", "version_number")
def chunk_constant_value(node: node_def_pb2.NodeDef, size: int):
"""Extracts and clears the constant value from a NodeDef.
Args:
node: NodeDef with const value to extract.
size: Size of NodeDef (for error reporting).
Returns:
Bytes representation of the Constant tensor content.
"""
if node.op == _CONST_OP:
tensor_proto = node.attr["value"].tensor
if tensor_proto.tensor_content:
b = tensor_proto.tensor_content
else:
# The raw tensor value could be stored in one of the "xxx_val" attributes.
# Extract it here, and convert to bytes.
b = tensor_util.MakeNdarray(tensor_proto).tobytes()
# Keep the TensorProto's dtype, tensor_shape, and version_number fields,
# but clear the raw tensor content / "xxx_val" attributes.
kept_attributes = {
key: getattr(tensor_proto, key) for key in _KEEP_TENSOR_PROTO_FIELDS
}
tensor_proto.Clear()
for field, val in kept_attributes.items():
if isinstance(val, message.Message):
getattr(tensor_proto, field).MergeFrom(val)
else:
setattr(tensor_proto, field, val)
return b
else:
attributes_and_sizes = ", ".join(
[
f"{key}: {util.format_bytes(val.ByteSize())}"
for key, val in node.attr.items()
]
)
raise ValueError(
"Unable to split GraphDef because at least one of the nodes "
"individually exceeds the max size of "
f"{util.format_bytes(constants.max_size())}. "
"Currently only Const nodes can be further split."
"\nNode info:"
f"\n\tsize: {util.format_bytes(size)}"
f"\n\tname: {node.name}"
f"\n\top: {node.op}"
f"\n\tinputs: {node.input}"
f"\n\top: {node.op}"
f"\n\tdevice: {node.device}"
f"\n\tattr (and sizes): {attributes_and_sizes}"
)
def _split_repeated_field(
proto: message.Message,
new_proto: message.Message,
fields: util.FieldTypes,
start_index: int,
end_index: Optional[int] = None,
) -> None:
"""Generic function for copying a repeated field from one proto to another."""
util.get_field(new_proto, fields)[0].MergeFrom(
util.get_field(proto, fields)[0][start_index:end_index]
)
_ABOVE_MAX_SIZE = lambda x: x > constants.max_size()
_GREEDY_SPLIT = lambda x: x > constants.max_size() // 3
_ALWAYS_SPLIT = lambda x: True
| GraphDefSplitter |
python | spyder-ide__spyder | spyder/app/tests/script_outline_4.py | {
"start": 255,
"end": 350
} | class ____:
def __init__(self):
pass
def some_method(self):
pass
| SomeClass |
python | doocs__leetcode | solution/1600-1699/1642.Furthest Building You Can Reach/Solution.py | {
"start": 0,
"end": 446
} | class ____:
def furthestBuilding(self, heights: List[int], bricks: int, ladders: int) -> int:
h = []
for i, a in enumerate(heights[:-1]):
b = heights[i + 1]
d = b - a
if d > 0:
heappush(h, d)
if len(h) > ladders:
bricks -= heappop(h)
if bricks < 0:
return i
return len(heights) - 1
| Solution |
python | joke2k__faker | faker/documentor.py | {
"start": 318,
"end": 4246
} | class ____:
def __init__(self, generator: Union[Generator, Faker]) -> None:
"""
:param generator: a localized Generator with providers filled,
for which to write the documentation
:type generator: faker.Generator()
"""
self.generator = generator
self.max_name_len: int = 0
self.already_generated: List[str] = []
def get_formatters(
self,
locale: Optional[str] = None,
excludes: Optional[List[str]] = None,
**kwargs: Any,
) -> List[Tuple[BaseProvider, Dict[str, str]]]:
self.max_name_len = 0
self.already_generated = [] if excludes is None else excludes[:]
formatters = []
providers: List[BaseProvider] = self.generator.get_providers()
for provider in providers[::-1]: # reverse
if locale and provider.__lang__ and provider.__lang__ != locale:
continue
formatters.append(
(provider, self.get_provider_formatters(provider, **kwargs)),
)
return formatters
def get_provider_formatters(
self,
provider: BaseProvider,
prefix: str = "fake.",
with_args: bool = True,
with_defaults: bool = True,
) -> Dict[str, str]:
formatters = {}
for name, method in inspect.getmembers(provider, inspect.ismethod):
# skip 'private' method and inherited methods
if name.startswith("_") or name in self.already_generated:
continue
arguments = []
faker_args: List[Union[str, Type[Enum]]] = []
faker_kwargs = {}
if name == "binary":
faker_kwargs["length"] = 1024
elif name in ["zip", "tar"]:
faker_kwargs.update(
{
"uncompressed_size": 1024,
"min_file_size": 512,
}
)
if name == "enum":
faker_args = [FakerEnum]
if with_args:
# retrieve all parameter
argspec = inspect.getfullargspec(method)
lst = [x for x in argspec.args if x not in ["self", "cls"]]
for i, arg in enumerate(lst):
if argspec.defaults and with_defaults:
try:
default = argspec.defaults[i]
if isinstance(default, str):
default = repr(default)
else:
# TODO check default type
default = f"{default}"
arg = f"{arg}={default}"
except IndexError:
pass
arguments.append(arg)
if with_args == "first":
break
if with_args != "first":
if argspec.varargs:
arguments.append("*" + argspec.varargs)
if argspec.varkw:
arguments.append("**" + argspec.varkw)
# build fake method signature
signature = f"{prefix}{name}({', '.join(arguments)})"
try:
# make a fake example
example = self.generator.format(name, *faker_args, **faker_kwargs)
except (AttributeError, ValueError) as e:
warnings.warn(str(e))
continue
formatters[signature] = example
self.max_name_len = max(self.max_name_len, *(len(part) for part in signature.split()))
self.already_generated.append(name)
return formatters
@staticmethod
def get_provider_name(provider_class: BaseProvider) -> str:
return provider_class.__provider__
| Documentor |
python | doocs__leetcode | solution/2100-2199/2168.Unique Substrings With Equal Digit Frequency/Solution.py | {
"start": 0,
"end": 680
} | class ____:
def equalDigitFrequency(self, s: str) -> int:
def check(i, j):
v = set()
for k in range(10):
cnt = presum[j + 1][k] - presum[i][k]
if cnt > 0:
v.add(cnt)
if len(v) > 1:
return False
return True
n = len(s)
presum = [[0] * 10 for _ in range(n + 1)]
for i, c in enumerate(s):
presum[i + 1][int(c)] += 1
for j in range(10):
presum[i + 1][j] += presum[i][j]
vis = set(s[i : j + 1] for i in range(n) for j in range(i, n) if check(i, j))
return len(vis)
| Solution |
python | numpy__numpy | numpy/lib/tests/test_index_tricks.py | {
"start": 14581,
"end": 14976
} | class ____:
def test_regression_1(self):
# ticket #1196
a = np.arange(2)
assert_equal(a[:-1], a[s_[:-1]])
assert_equal(a[:-1], a[index_exp[:-1]])
def test_simple_1(self):
a = np.random.rand(4, 5, 6)
assert_equal(a[:, :3, [1, 2]], a[index_exp[:, :3, [1, 2]]])
assert_equal(a[:, :3, [1, 2]], a[s_[:, :3, [1, 2]]])
| TestIndexExpression |
python | scipy__scipy | scipy/integrate/_ivp/base.py | {
"start": 832,
"end": 8770
} | class ____:
"""Base class for ODE solvers.
In order to implement a new solver you need to follow the guidelines:
1. A constructor must accept parameters presented in the base class
(listed below) along with any other parameters specific to a solver.
2. A constructor must accept arbitrary extraneous arguments
``**extraneous``, but warn that these arguments are irrelevant
using `common.warn_extraneous` function. Do not pass these
arguments to the base class.
3. A solver must implement a private method `_step_impl(self)` which
propagates a solver one step further. It must return tuple
``(success, message)``, where ``success`` is a boolean indicating
whether a step was successful, and ``message`` is a string
containing description of a failure if a step failed or None
otherwise.
4. A solver must implement a private method `_dense_output_impl(self)`,
which returns a `DenseOutput` object covering the last successful
step.
5. A solver must have attributes listed below in Attributes section.
Note that ``t_old`` and ``step_size`` are updated automatically.
6. Use `fun(self, t, y)` method for the system rhs evaluation, this
way the number of function evaluations (`nfev`) will be tracked
automatically.
7. For convenience, a base class provides `fun_single(self, t, y)` and
`fun_vectorized(self, t, y)` for evaluating the rhs in
non-vectorized and vectorized fashions respectively (regardless of
how `fun` from the constructor is implemented). These calls don't
increment `nfev`.
8. If a solver uses a Jacobian matrix and LU decompositions, it should
track the number of Jacobian evaluations (`njev`) and the number of
LU decompositions (`nlu`).
9. By convention, the function evaluations used to compute a finite
difference approximation of the Jacobian should not be counted in
`nfev`, thus use `fun_single(self, t, y)` or
`fun_vectorized(self, t, y)` when computing a finite difference
approximation of the Jacobian.
Parameters
----------
fun : callable
Right-hand side of the system: the time derivative of the state ``y``
at time ``t``. The calling signature is ``fun(t, y)``, where ``t`` is a
scalar and ``y`` is an ndarray with ``len(y) = len(y0)``. ``fun`` must
return an array of the same shape as ``y``. See `vectorized` for more
information.
t0 : float
Initial time.
y0 : array_like, shape (n,)
Initial state.
t_bound : float
Boundary time --- the integration won't continue beyond it. It also
determines the direction of the integration.
vectorized : bool
Whether `fun` can be called in a vectorized fashion. Default is False.
If ``vectorized`` is False, `fun` will always be called with ``y`` of
shape ``(n,)``, where ``n = len(y0)``.
If ``vectorized`` is True, `fun` may be called with ``y`` of shape
``(n, k)``, where ``k`` is an integer. In this case, `fun` must behave
such that ``fun(t, y)[:, i] == fun(t, y[:, i])`` (i.e. each column of
the returned array is the time derivative of the state corresponding
with a column of ``y``).
Setting ``vectorized=True`` allows for faster finite difference
approximation of the Jacobian by methods 'Radau' and 'BDF', but
will result in slower execution for other methods. It can also
result in slower overall execution for 'Radau' and 'BDF' in some
circumstances (e.g. small ``len(y0)``).
support_complex : bool, optional
Whether integration in a complex domain should be supported.
Generally determined by a derived solver class capabilities.
Default is False.
Attributes
----------
n : int
Number of equations.
status : string
Current status of the solver: 'running', 'finished' or 'failed'.
t_bound : float
Boundary time.
direction : float
Integration direction: +1 or -1.
t : float
Current time.
y : ndarray
Current state.
t_old : float
Previous time. None if no steps were made yet.
step_size : float
Size of the last successful step. None if no steps were made yet.
nfev : int
Number of the system's rhs evaluations.
njev : int
Number of the Jacobian evaluations.
nlu : int
Number of LU decompositions.
"""
TOO_SMALL_STEP = "Required step size is less than spacing between numbers."
# generic type compatibility with scipy-stubs
__class_getitem__ = classmethod(GenericAlias)
def __init__(self, fun, t0, y0, t_bound, vectorized,
support_complex=False):
self.t_old = None
self.t = t0
self._fun, self.y = check_arguments(fun, y0, support_complex)
self.t_bound = t_bound
self.vectorized = vectorized
if vectorized:
def fun_single(t, y):
return self._fun(t, y[:, None]).ravel()
fun_vectorized = self._fun
else:
fun_single = self._fun
def fun_vectorized(t, y):
f = np.empty_like(y)
for i, yi in enumerate(y.T):
f[:, i] = self._fun(t, yi)
return f
def fun(t, y):
self.nfev += 1
return self.fun_single(t, y)
self.fun = fun
self.fun_single = fun_single
self.fun_vectorized = fun_vectorized
self.direction = np.sign(t_bound - t0) if t_bound != t0 else 1
self.n = self.y.size
self.status = 'running'
self.nfev = 0
self.njev = 0
self.nlu = 0
@property
def step_size(self):
if self.t_old is None:
return None
else:
return np.abs(self.t - self.t_old)
def step(self):
"""Perform one integration step.
Returns
-------
message : string or None
Report from the solver. Typically a reason for a failure if
`self.status` is 'failed' after the step was taken or None
otherwise.
"""
if self.status != 'running':
raise RuntimeError("Attempt to step on a failed or finished "
"solver.")
if self.n == 0 or self.t == self.t_bound:
# Handle corner cases of empty solver or no integration.
self.t_old = self.t
self.t = self.t_bound
message = None
self.status = 'finished'
else:
t = self.t
success, message = self._step_impl()
if not success:
self.status = 'failed'
else:
self.t_old = t
if self.direction * (self.t - self.t_bound) >= 0:
self.status = 'finished'
return message
def dense_output(self):
"""Compute a local interpolant over the last successful step.
Returns
-------
sol : `DenseOutput`
Local interpolant over the last successful step.
"""
if self.t_old is None:
raise RuntimeError("Dense output is available after a successful "
"step was made.")
if self.n == 0 or self.t == self.t_old:
# Handle corner cases of empty solver and no integration.
return ConstantDenseOutput(self.t_old, self.t, self.y)
else:
return self._dense_output_impl()
def _step_impl(self):
raise NotImplementedError
def _dense_output_impl(self):
raise NotImplementedError
| OdeSolver |
python | pytorch__pytorch | torch/_subclasses/functional_tensor.py | {
"start": 36109,
"end": 37906
} | class ____(BaseFunctionalizeAPI):
def __init__(self, interpreter):
self.interpreter = interpreter
def wrap_tensors(self, args: tuple[Any]) -> tuple[Any]:
from torch._functorch.eager_transforms import _wrap_all_tensors_to_functional
return _wrap_all_tensors_to_functional(args, level=self.interpreter.level())
def unwrap_tensors(
self, args: Union[torch.Tensor, tuple[torch.Tensor, ...]]
) -> Union[torch.Tensor, tuple[torch.Tensor, ...]]:
from torch._functorch.eager_transforms import (
_unwrap_all_tensors_from_functional,
)
return _unwrap_all_tensors_from_functional(
args, reapply_views=self.interpreter.functionalize_add_back_views()
)
def functionalize(self, inner_f: Callable) -> Callable:
return torch.func.functionalize(
inner_f,
remove=(
"mutations_and_views"
if self.interpreter.functionalize_add_back_views()
else "mutations"
),
)
def redispatch_to_next(self) -> AbstractContextManager:
return self.interpreter.lower()
def replace(self, input_tensor, output_tensor) -> None:
torch._functionalize_replace(input_tensor, output_tensor)
def commit_update(self, tensor) -> None:
torch._functionalize_commit_update(tensor)
def sync(self, tensor) -> None:
torch._functionalize_sync(tensor)
def mark_mutation_hidden_from_autograd(self, tensor) -> None:
torch._functionalize_mark_mutation_hidden_from_autograd(tensor)
def mb_unwrap_functional_tensor(tensor: torch.Tensor):
if isinstance(tensor, FunctionalTensor):
return torch._from_functional_tensor(tensor.elem)
return tensor
| FunctorchFunctionalizeAPI |
python | pandas-dev__pandas | pandas/tests/indexes/datetimes/methods/test_to_series.py | {
"start": 105,
"end": 495
} | class ____:
def test_to_series(self):
naive = DatetimeIndex(["2013-1-1 13:00", "2013-1-2 14:00"], name="B")
idx = naive.tz_localize("US/Pacific")
expected = Series(np.array(idx.tolist(), dtype="object"), name="B")
result = idx.to_series(index=range(2))
assert expected.dtype == idx.dtype
tm.assert_series_equal(result, expected)
| TestToSeries |
python | kamyu104__LeetCode-Solutions | Python/longest-common-prefix-of-k-strings-after-removal.py | {
"start": 72,
"end": 1388
} | class ____(object):
def longestCommonPrefix(self, words, k):
"""
:type words: List[str]
:type k: int
:rtype: List[int]
"""
idxs = range(len(words))
idxs.sort(key=lambda x: words[x])
def longest_common_prefix(k):
lcp = [0]*len(words)
for i in xrange(len(words)-(k-1)):
left = words[idxs[i]]
right = words[idxs[i+(k-1)]]
l = min(len(left), len(right))
lcp[i] = next((j for j in xrange(l) if left[j] != right[j]), l)
return lcp
lcp = longest_common_prefix(k)
prefix = [0]*len(words)
prefix[0] = lcp[0]
for i in xrange(len(prefix)-1):
prefix[i+1] = max(prefix[i], lcp[i+1])
suffix = [0]*len(words)
suffix[-1] = lcp[-1]
for i in reversed(xrange(len(suffix)-1)):
suffix[i] = max(suffix[i+1], lcp[i])
result = [0]*len(words)
mx = max(longest_common_prefix(k+1))
for i in xrange(len(words)):
idx = idxs[i]
mx1 = prefix[i-k] if i-k >= 0 else 0
mx2 = suffix[i+1] if i+1 < len(words) else 0
result[idx] = max(mx, mx1, mx2)
return result
# Time: O(n * l)
# Space: O(t)
# trie
| Solution |
python | huggingface__transformers | tests/models/mask2former/test_modeling_mask2former.py | {
"start": 15739,
"end": 23830
} | class ____(unittest.TestCase):
@cached_property
def model_checkpoints(self):
return "facebook/mask2former-swin-small-coco-instance"
@cached_property
def default_image_processor(self):
return Mask2FormerImageProcessor.from_pretrained(self.model_checkpoints) if is_vision_available() else None
def test_inference_no_head(self):
model = Mask2FormerModel.from_pretrained(self.model_checkpoints).to(torch_device)
image_processor = self.default_image_processor
image = prepare_img()
inputs = image_processor(image, return_tensors="pt").to(torch_device)
inputs_shape = inputs["pixel_values"].shape
# check size is divisible by 32
self.assertTrue((inputs_shape[-1] % 32) == 0 and (inputs_shape[-2] % 32) == 0)
# check size
self.assertEqual(inputs_shape, (1, 3, 384, 384))
with torch.no_grad():
outputs = model(**inputs)
expected_slice_hidden_state = torch.tensor(
[
[-0.2790, -1.0717, -1.1668],
[-0.5128, -0.3128, -0.4987],
[-0.5832, 0.1971, -0.0197],
]
).to(torch_device)
torch.testing.assert_close(
outputs.encoder_last_hidden_state[0, 0, :3, :3],
expected_slice_hidden_state,
atol=TOLERANCE,
rtol=TOLERANCE,
)
expectations = Expectations(
{
(None, None): [
[0.8973, 1.1847, 1.1776],
[1.1934, 1.5040, 1.5128],
[1.1153, 1.4486, 1.4951],
],
("cuda", 8): [
[0.8974, 1.1848, 1.1777],
[1.1933, 1.5041, 1.5128],
[1.1154, 1.4487, 1.4950],
],
}
)
expected_slice_hidden_state = torch.tensor(expectations.get_expectation()).to(torch_device)
torch.testing.assert_close(outputs.pixel_decoder_last_hidden_state[0, 0, :3, :3], expected_slice_hidden_state, atol=TOLERANCE,rtol=TOLERANCE) # fmt: skip
expectations = Expectations(
{
(None, None): [
[2.1152, 1.7000, -0.8603],
[1.5808, 1.8004, -0.9353],
[1.6043, 1.7495, -0.5999],
],
("cuda", 8): [
[2.1153, 1.7004, -0.8604],
[1.5807, 1.8007, -0.9354],
[1.6040, 1.7498, -0.6001],
],
}
)
expected_slice_hidden_state = torch.tensor(expectations.get_expectation()).to(torch_device)
torch.testing.assert_close(outputs.transformer_decoder_last_hidden_state[0, :3, :3], expected_slice_hidden_state, atol=TOLERANCE, rtol=TOLERANCE) # fmt: skip
def test_inference_universal_segmentation_head(self):
model = Mask2FormerForUniversalSegmentation.from_pretrained(self.model_checkpoints).to(torch_device).eval()
image_processor = self.default_image_processor
image = prepare_img()
inputs = image_processor(image, return_tensors="pt").to(torch_device)
inputs_shape = inputs["pixel_values"].shape
# check size is divisible by 32
self.assertTrue((inputs_shape[-1] % 32) == 0 and (inputs_shape[-2] % 32) == 0)
# check size
self.assertEqual(inputs_shape, (1, 3, 384, 384))
with torch.no_grad():
outputs = model(**inputs)
# masks_queries_logits
masks_queries_logits = outputs.masks_queries_logits
self.assertEqual(
masks_queries_logits.shape, (1, model.config.num_queries, inputs_shape[-2] // 4, inputs_shape[-1] // 4)
)
expectations = Expectations(
{
(None, None): [
[-8.7839, -9.0056, -8.8121],
[-7.4104, -7.0313, -6.5401],
[-6.6105, -6.3427, -6.4675],
],
("cuda", 8): [
[-8.7839, -9.0056, -8.8122],
[-7.4104, -7.0313, -6.5401],
[-6.6105, -6.3428, -6.4675],
],
}
)
expected_slice = torch.tensor(expectations.get_expectation()).to(torch_device)
torch.testing.assert_close(masks_queries_logits[0, 0, :3, :3], expected_slice, rtol=TOLERANCE, atol=TOLERANCE)
# class_queries_logits
class_queries_logits = outputs.class_queries_logits
self.assertEqual(class_queries_logits.shape, (1, model.config.num_queries, model.config.num_labels + 1))
expectations = Expectations(
{
(None, None): [
[1.8324, -8.0835, -4.1922],
[0.8450, -9.0050, -3.6053],
[0.3045, -7.7293, -3.0275],
],
("cuda", 8): [
[1.8324, -8.0835, -4.1922],
[0.8450, -9.0050, -3.6053],
[0.3045, -7.7293, -3.0275],
],
}
)
expected_slice = torch.tensor(expectations.get_expectation()).to(torch_device)
torch.testing.assert_close(
outputs.class_queries_logits[0, :3, :3], expected_slice, rtol=TOLERANCE, atol=TOLERANCE
)
@require_torch_accelerator
@require_torch_fp16
def test_inference_fp16(self):
model = (
Mask2FormerForUniversalSegmentation.from_pretrained(self.model_checkpoints)
.to(torch_device, dtype=torch.float16)
.eval()
)
image_processor = self.default_image_processor
image = prepare_img()
inputs = image_processor(image, return_tensors="pt").to(torch_device, dtype=torch.float16)
with torch.no_grad():
_ = model(**inputs)
def test_with_segmentation_maps_and_loss(self):
model = Mask2FormerForUniversalSegmentation.from_pretrained(self.model_checkpoints).to(torch_device).eval()
image_processor = self.default_image_processor
inputs = image_processor(
[np.zeros((3, 800, 1333)), np.zeros((3, 800, 1333))],
segmentation_maps=[np.zeros((384, 384)).astype(np.float32), np.zeros((384, 384)).astype(np.float32)],
return_tensors="pt",
)
inputs["pixel_values"] = inputs["pixel_values"].to(torch_device)
inputs["mask_labels"] = [el.to(torch_device) for el in inputs["mask_labels"]]
inputs["class_labels"] = [el.to(torch_device) for el in inputs["class_labels"]]
with torch.no_grad():
outputs = model(**inputs)
self.assertTrue(outputs.loss is not None)
@pytest.mark.torch_export_test
def test_export(self):
if not is_torch_greater_or_equal_than_2_4:
self.skipTest(reason="This test requires torch >= 2.4 to run.")
model = Mask2FormerForUniversalSegmentation.from_pretrained(self.model_checkpoints).to(torch_device).eval()
image_processor = self.default_image_processor
image = prepare_img()
inputs = image_processor(image, return_tensors="pt").to(torch_device)
exported_program = torch.export.export(
model,
args=(inputs["pixel_values"], inputs["pixel_mask"]),
strict=True,
)
with torch.no_grad():
eager_outputs = model(**inputs)
exported_outputs = exported_program.module().forward(inputs["pixel_values"], inputs["pixel_mask"])
self.assertEqual(eager_outputs.masks_queries_logits.shape, exported_outputs.masks_queries_logits.shape)
torch.testing.assert_close(
eager_outputs.masks_queries_logits, exported_outputs.masks_queries_logits, rtol=TOLERANCE, atol=TOLERANCE
)
self.assertEqual(eager_outputs.class_queries_logits.shape, exported_outputs.class_queries_logits.shape)
torch.testing.assert_close(
eager_outputs.class_queries_logits, exported_outputs.class_queries_logits, rtol=TOLERANCE, atol=TOLERANCE
)
| Mask2FormerModelIntegrationTest |
python | ray-project__ray | doc/source/serve/doc_code/grpc_proxy/user_defined_protos_pb2_grpc.py | {
"start": 1478,
"end": 3748
} | class ____(object):
"""Missing associated documentation comment in .proto file."""
def __call__(self, request, context):
"""Missing associated documentation comment in .proto file."""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details("Method not implemented!")
raise NotImplementedError("Method not implemented!")
def Multiplexing(self, request, context):
"""Missing associated documentation comment in .proto file."""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details("Method not implemented!")
raise NotImplementedError("Method not implemented!")
def Streaming(self, request, context):
"""Missing associated documentation comment in .proto file."""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details("Method not implemented!")
raise NotImplementedError("Method not implemented!")
def add_UserDefinedServiceServicer_to_server(servicer, server):
rpc_method_handlers = {
"__call__": grpc.unary_unary_rpc_method_handler(
servicer.__call__,
request_deserializer=user__defined__protos__pb2.UserDefinedMessage.FromString, # noqa: E501
response_serializer=user__defined__protos__pb2.UserDefinedResponse.SerializeToString, # noqa: E501
),
"Multiplexing": grpc.unary_unary_rpc_method_handler(
servicer.Multiplexing,
request_deserializer=user__defined__protos__pb2.UserDefinedMessage2.FromString, # noqa: E501
response_serializer=user__defined__protos__pb2.UserDefinedResponse2.SerializeToString, # noqa: E501
),
"Streaming": grpc.unary_stream_rpc_method_handler(
servicer.Streaming,
request_deserializer=user__defined__protos__pb2.UserDefinedMessage.FromString, # noqa: E501
response_serializer=user__defined__protos__pb2.UserDefinedResponse.SerializeToString, # noqa: E501
),
}
generic_handler = grpc.method_handlers_generic_handler(
"userdefinedprotos.UserDefinedService", rpc_method_handlers
)
server.add_generic_rpc_handlers((generic_handler,))
# This class is part of an EXPERIMENTAL API.
| UserDefinedServiceServicer |
python | readthedocs__readthedocs.org | readthedocs/gold/migrations/0002_rename_last_4_digits.py | {
"start": 120,
"end": 436
} | class ____(migrations.Migration):
safe = Safe.after_deploy()
dependencies = [
("gold", "0001_initial"),
]
operations = [
migrations.RenameField(
model_name="golduser",
old_name="last_4_digits",
new_name="last_4_card_digits",
),
]
| Migration |
python | openai__openai-python | src/openai/types/beta/threads/run.py | {
"start": 975,
"end": 1228
} | class ____(BaseModel):
code: Literal["server_error", "rate_limit_exceeded", "invalid_prompt"]
"""One of `server_error`, `rate_limit_exceeded`, or `invalid_prompt`."""
message: str
"""A human-readable description of the error."""
| LastError |
python | huggingface__transformers | src/transformers/models/unispeech_sat/modeling_unispeech_sat.py | {
"start": 26484,
"end": 29602
} | class ____(nn.Module):
"""
Vector quantization using gumbel softmax. See `[CATEGORICAL REPARAMETERIZATION WITH
GUMBEL-SOFTMAX](https://huggingface.co/papers/1611.01144) for more information.
"""
def __init__(self, config):
super().__init__()
self.num_groups = config.num_codevector_groups
self.num_vars = config.num_codevectors_per_group
if config.codevector_dim % self.num_groups != 0:
raise ValueError(
f"`config.codevector_dim {config.codevector_dim} must be divisible "
f"by `config.num_codevector_groups` {self.num_groups} for concatenation"
)
# storage for codebook variables (codewords)
self.codevectors = nn.Parameter(
torch.FloatTensor(1, self.num_groups * self.num_vars, config.codevector_dim // self.num_groups)
)
self.weight_proj = nn.Linear(config.hidden_size, self.num_groups * self.num_vars)
# can be decayed for training
self.temperature = 2
@staticmethod
def _compute_perplexity(probs, mask=None):
marginal_probs = probs.mean(dim=0)
perplexity = torch.exp(-torch.sum(marginal_probs * torch.log(marginal_probs + 1e-7), dim=-1)).sum()
return perplexity
def forward(self, hidden_states):
batch_size, sequence_length, hidden_size = hidden_states.shape
# project to codevector dim
hidden_states = self.weight_proj(hidden_states)
hidden_states = hidden_states.view(batch_size * sequence_length * self.num_groups, -1)
if self.training:
# sample code vector probs via gumbel in differentiateable way
codevector_probs = nn.functional.gumbel_softmax(
hidden_states.float(), tau=self.temperature, hard=True
).type_as(hidden_states)
# compute perplexity
codevector_soft_dist = torch.softmax(
hidden_states.view(batch_size * sequence_length, self.num_groups, -1).float(), dim=-1
)
perplexity = self._compute_perplexity(codevector_soft_dist)
else:
# take argmax in non-differentiable way
# comptute hard codevector distribution (one hot)
codevector_idx = hidden_states.argmax(dim=-1)
codevector_probs = hidden_states.new_zeros(*hidden_states.shape).scatter_(
-1, codevector_idx.view(-1, 1), 1.0
)
codevector_probs = codevector_probs.view(batch_size * sequence_length, self.num_groups, -1)
perplexity = self._compute_perplexity(codevector_probs)
codevector_probs = codevector_probs.view(batch_size * sequence_length, -1)
# use probs to retrieve codevectors
codevectors_per_group = codevector_probs.unsqueeze(-1) * self.codevectors
codevectors = codevectors_per_group.view(batch_size * sequence_length, self.num_groups, self.num_vars, -1)
codevectors = codevectors.sum(-2).view(batch_size, sequence_length, -1)
return codevectors, perplexity
@auto_docstring
| UniSpeechSatGumbelVectorQuantizer |
python | huggingface__transformers | src/transformers/models/janus/modeling_janus.py | {
"start": 21140,
"end": 22212
} | class ____(GradientCheckpointingLayer):
def __init__(self, config: JanusConfig):
super().__init__()
self.embed_dim = config.hidden_size
self.self_attn = JanusAttention(config)
self.layer_norm1 = nn.LayerNorm(self.embed_dim, eps=config.layer_norm_eps)
self.mlp = JanusMLP(config)
self.layer_norm2 = nn.LayerNorm(self.embed_dim, eps=config.layer_norm_eps)
@auto_docstring
def forward(
self,
hidden_states: torch.Tensor,
**kwargs: Unpack[TransformersKwargs],
) -> torch.FloatTensor:
residual = hidden_states
hidden_states = self.layer_norm1(hidden_states)
hidden_states, _ = self.self_attn(
hidden_states=hidden_states,
**kwargs,
)
hidden_states = hidden_states + residual
residual = hidden_states
hidden_states = self.layer_norm2(hidden_states)
hidden_states = self.mlp(hidden_states)
hidden_states = hidden_states + residual
return hidden_states
@auto_docstring
| JanusEncoderLayer |
python | airbytehq__airbyte | airbyte-ci/connectors/erd/tests/test_dbml_assembler.py | {
"start": 327,
"end": 2526
} | class ____(TestCase):
def setUp(self) -> None:
self._source = Mock(spec=Source)
self._source.is_dynamic.return_value = False
self._assembler = DbmlAssembler()
def test_given_no_streams_then_database_is_empty(self) -> None:
dbml = self._assembler.assemble(
self._source,
AirbyteCatalog(streams=[]),
{"streams": [RelationshipBuilder(_A_STREAM_NAME).build()]},
)
assert not dbml.tables
def test_given_stream_is_dynamic_then_ignore(self) -> None:
self._source.is_dynamic.return_value = True
dbml = self._assembler.assemble(
self._source,
AirbyteCatalog(
streams=[
AirbyteStream(
name=_A_STREAM_NAME,
json_schema={"properties": {}},
supported_sync_modes=[SyncMode.full_refresh],
)
]
),
{"streams": [RelationshipBuilder(_A_STREAM_NAME).build()]},
)
assert not dbml.tables
def test_given_stream_then_populate_table(self) -> None:
dbml = self._assembler.assemble(
self._source,
AirbyteCatalog(
streams=[
AirbyteStream(
name=_A_STREAM_NAME,
json_schema={
"properties": {
"a_primary_key": {"type": ["null", "string"]},
"an_integer": {"type": ["null", "number"]},
}
},
supported_sync_modes=[SyncMode.full_refresh],
source_defined_primary_key=[["a_primary_key"]],
)
]
),
{"streams": [RelationshipBuilder(_A_STREAM_NAME).build()]},
)
assert len(dbml.tables) == 1
assert len(dbml.tables[0].columns) == 2
assert dbml.tables[0].columns[0].name == "a_primary_key"
assert dbml.tables[0].columns[0].pk
assert dbml.tables[0].columns[1].name == "an_integer"
| RelationshipsMergerTest |
python | PrefectHQ__prefect | tests/server/models/test_block_schemas.py | {
"start": 36458,
"end": 37054
} | class ____:
async def test_list_available_block_capabilities(
self, session, block_schemas_with_capabilities
):
assert sorted(
await models.block_schemas.read_available_block_capabilities(
session=session
)
) == sorted(["run", "fly", "swim"])
async def test_list_available_block_capabilities_with_no_schemas(self, session):
assert (
await models.block_schemas.read_available_block_capabilities(
session=session
)
== []
)
| TestListAvailableBlockCapabilities |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/self11.py | {
"start": 158,
"end": 179
} | class ____(Base): ...
| A |
python | ApeWorX__ape | src/ape/types/private_mempool.py | {
"start": 2296,
"end": 2641
} | class ____(BaseModel):
"""
Data used by block builders to check if the bundle should be considered for inclusion.
"""
block: HexInt
"""
The first block the bundle is valid for.
"""
max_block: Union[HexInt, None] = Field(None, alias="maxBlock")
"""
The last block the bundle is valid for.
"""
| Inclusion |
python | HypothesisWorks__hypothesis | hypothesis-python/tests/nocover/test_build_signature.py | {
"start": 1307,
"end": 2077
} | class ____(Model):
def __init__(self, **kwargs):
assert set(kwargs) == {"a", "b", "x", "y"}
self.b = kwargs["b"]
assert self.b is None or isinstance(self.b, list)
@given(st.from_type(ModelForFromType))
def test_from_type_uses_signature_attribute(val):
assert isinstance(val, ModelForFromType)
def test_from_type_can_be_default_or_annotation():
find_any(st.from_type(ModelForFromType), lambda m: m.b is None)
find_any(st.from_type(ModelForFromType), lambda m: isinstance(m.b, list))
def use_annotations(
self, test_a: int, test_b: str | None = None, *, test_x: float, test_y: str
):
pass
def use_signature(
self, testA: int, testB: str | None = None, *, testX: float, testY: list[str]
):
pass
| ModelForFromType |
python | sphinx-doc__sphinx | sphinx/errors.py | {
"start": 3288,
"end": 3413
} | class ____(Exception):
"""Raised by get_filetype() if a filename matches no source suffix."""
pass
| FiletypeNotFoundError |
python | pytest-dev__pytest | testing/test_assertrewrite.py | {
"start": 56012,
"end": 58752
} | class ____:
def test_assertion_walrus_different_test_cases(self, pytester: Pytester) -> None:
"""Regression for (#11239)
Walrus operator rewriting would leak to separate test cases if they used the same variables.
"""
pytester.makepyfile(
"""
def test_1():
state = {"x": 2}.get("x")
assert state is not None
def test_2():
db = {"x": 2}
assert (state := db.get("x")) is not None
"""
)
result = pytester.runpytest()
assert result.ret == 0
@pytest.mark.skipif(
sys.maxsize <= (2**31 - 1), reason="Causes OverflowError on 32bit systems"
)
@pytest.mark.parametrize("offset", [-1, +1])
def test_source_mtime_long_long(pytester: Pytester, offset) -> None:
"""Support modification dates after 2038 in rewritten files (#4903).
pytest would crash with:
fp.write(struct.pack("<ll", mtime, size))
E struct.error: argument out of range
"""
p = pytester.makepyfile(
"""
def test(): pass
"""
)
# use unsigned long timestamp which overflows signed long,
# which was the cause of the bug
# +1 offset also tests masking of 0xFFFFFFFF
timestamp = 2**32 + offset
os.utime(str(p), (timestamp, timestamp))
result = pytester.runpytest()
assert result.ret == 0
def test_rewrite_infinite_recursion(
pytester: Pytester, pytestconfig, monkeypatch
) -> None:
"""Fix infinite recursion when writing pyc files: if an import happens to be triggered when writing the pyc
file, this would cause another call to the hook, which would trigger another pyc writing, which could
trigger another import, and so on. (#3506)"""
from _pytest.assertion import rewrite as rewritemod
pytester.syspathinsert()
pytester.makepyfile(test_foo="def test_foo(): pass")
pytester.makepyfile(test_bar="def test_bar(): pass")
original_write_pyc = rewritemod._write_pyc
write_pyc_called = []
def spy_write_pyc(*args, **kwargs):
# make a note that we have called _write_pyc
write_pyc_called.append(True)
# try to import a module at this point: we should not try to rewrite this module
assert hook.find_spec("test_bar") is None
return original_write_pyc(*args, **kwargs)
monkeypatch.setattr(rewritemod, "_write_pyc", spy_write_pyc)
monkeypatch.setattr(sys, "dont_write_bytecode", False)
hook = AssertionRewritingHook(pytestconfig)
spec = hook.find_spec("test_foo")
assert spec is not None
module = importlib.util.module_from_spec(spec)
hook.exec_module(module)
assert len(write_pyc_called) == 1
| TestIssue11239 |
python | dagster-io__dagster | python_modules/libraries/dagster-airbyte/dagster_airbyte/managed/generated/sources.py | {
"start": 18414,
"end": 19364
} | class ____(GeneratedAirbyteSource):
@public
def __init__(self, name: str, start_date: str, store_hash: str, access_token: str):
"""Airbyte Source for Bigcommerce.
Documentation can be found at https://docs.airbyte.com/integrations/sources/bigcommerce
Args:
name (str): The name of the destination.
start_date (str): The date you would like to replicate data. Format: YYYY-MM-DD.
store_hash (str): The hash code of the store. For https://api.bigcommerce.com/stores/HASH_CODE/v3/, The store's hash code is 'HASH_CODE'.
access_token (str): Access Token for making authenticated requests.
"""
self.start_date = check.str_param(start_date, "start_date")
self.store_hash = check.str_param(store_hash, "store_hash")
self.access_token = check.str_param(access_token, "access_token")
super().__init__("Bigcommerce", name)
| BigcommerceSource |
python | huggingface__transformers | src/transformers/models/mm_grounding_dino/modeling_mm_grounding_dino.py | {
"start": 23774,
"end": 27879
} | class ____(PreTrainedModel):
config: MMGroundingDinoConfig
base_model_prefix = "model"
main_input_name = "pixel_values"
input_modalities = ("image", "text")
@torch.no_grad()
def _init_weights(self, module):
std = self.config.init_std
if isinstance(module, MMGroundingDinoLearnedPositionEmbedding):
init.uniform_(module.row_embeddings.weight)
init.uniform_(module.column_embeddings.weight)
elif isinstance(module, MMGroundingDinoMultiscaleDeformableAttention):
init.constant_(module.sampling_offsets.weight, 0.0)
default_dtype = torch.get_default_dtype()
thetas = torch.arange(module.n_heads, dtype=torch.int64).to(default_dtype) * (
2.0 * math.pi / module.n_heads
)
grid_init = torch.stack([thetas.cos(), thetas.sin()], -1)
grid_init = (
(grid_init / grid_init.abs().max(-1, keepdim=True)[0])
.view(module.n_heads, 1, 1, 2)
.repeat(1, module.n_levels, module.n_points, 1)
)
for i in range(module.n_points):
grid_init[:, :, i, :] *= i + 1
init.copy_(module.sampling_offsets.bias, grid_init.view(-1))
init.constant_(module.attention_weights.weight, 0.0)
init.constant_(module.attention_weights.bias, 0.0)
init.xavier_uniform_(module.value_proj.weight)
init.constant_(module.value_proj.bias, 0.0)
init.xavier_uniform_(module.output_proj.weight)
init.constant_(module.output_proj.bias, 0.0)
elif isinstance(module, MMGroundingDinoBiMultiHeadAttention):
init.xavier_uniform_(module.vision_proj.weight)
init.zeros_(module.vision_proj.bias)
init.xavier_uniform_(module.text_proj.weight)
init.zeros_(module.text_proj.bias)
init.xavier_uniform_(module.values_vision_proj.weight)
init.zeros_(module.values_vision_proj.bias)
init.xavier_uniform_(module.values_text_proj.weight)
init.zeros_(module.values_text_proj.bias)
init.xavier_uniform_(module.out_vision_proj.weight)
init.zeros_(module.out_vision_proj.bias)
init.xavier_uniform_(module.out_text_proj.weight)
init.zeros_(module.out_text_proj.bias)
elif isinstance(module, MMGroundingDinoFusionLayer):
init.constant_(module.vision_param, 1e-4)
init.constant_(module.text_param, 1e-4)
elif isinstance(module, (nn.Linear, nn.Conv2d, nn.BatchNorm2d)):
init.normal_(module.weight, mean=0.0, std=std)
if module.bias is not None:
init.zeros_(module.bias)
elif isinstance(module, (nn.LayerNorm, nn.GroupNorm)):
init.ones_(module.weight)
init.zeros_(module.bias)
elif isinstance(module, nn.Embedding):
init.normal_(module.weight, mean=0.0, std=std)
# Here we need the check explicitly, as we slice the weight in the `zeros_` call, so it looses the flag
if module.padding_idx is not None and not getattr(module.weight, "_is_hf_initialized", False):
init.zeros_(module.weight[module.padding_idx])
elif isinstance(module, MMGroundingDinoMLPPredictionHead):
init.constant_(module.layers[-1].weight, 0)
init.constant_(module.layers[-1].bias, 0)
if hasattr(module, "reference_points") and not self.config.two_stage:
init.xavier_uniform_(module.reference_points.weight, gain=1.0)
init.constant_(module.reference_points.bias, 0.0)
if hasattr(module, "level_embed"):
init.normal_(module.level_embed)
if isinstance(module, MMGroundingDinoContrastiveEmbedding):
init.constant_(module.bias, -math.log((1 - 0.01) / 0.01))
def _set_gradient_checkpointing(self, module, value=False):
if isinstance(module, MMGroundingDinoDecoder):
module.gradient_checkpointing = value
| MMGroundingDinoPreTrainedModel |
python | charliermarsh__ruff | crates/ruff_linter/resources/test/fixtures/flake8_bugbear/B021.py | {
"start": 664,
"end": 829
} | class ____:
f"hello {VARIABLE}!"
def baz():
f"""I'm probably a docstring: {VARIABLE}!"""
print(f"""I'm a normal string""")
f"""Don't detect me!"""
| bar2 |
python | pytorch__pytorch | test/torch_np/numpy_tests/fft/test_helper.py | {
"start": 5872,
"end": 6248
} | class ____(TestCase):
def test_definition(self):
x = [0, 1, 2, 3, 4]
assert_array_almost_equal(9 * fft.rfftfreq(9), x)
assert_array_almost_equal(9 * pi * fft.rfftfreq(9, pi), x)
x = [0, 1, 2, 3, 4, 5]
assert_array_almost_equal(10 * fft.rfftfreq(10), x)
assert_array_almost_equal(10 * pi * fft.rfftfreq(10, pi), x)
| TestRFFTFreq |
python | pypa__pip | src/pip/_vendor/rich/console.py | {
"start": 2099,
"end": 2758
} | class ____:
pass
NO_CHANGE = NoChange()
try:
_STDIN_FILENO = sys.__stdin__.fileno() # type: ignore[union-attr]
except Exception:
_STDIN_FILENO = 0
try:
_STDOUT_FILENO = sys.__stdout__.fileno() # type: ignore[union-attr]
except Exception:
_STDOUT_FILENO = 1
try:
_STDERR_FILENO = sys.__stderr__.fileno() # type: ignore[union-attr]
except Exception:
_STDERR_FILENO = 2
_STD_STREAMS = (_STDIN_FILENO, _STDOUT_FILENO, _STDERR_FILENO)
_STD_STREAMS_OUTPUT = (_STDOUT_FILENO, _STDERR_FILENO)
_TERM_COLORS = {
"kitty": ColorSystem.EIGHT_BIT,
"256color": ColorSystem.EIGHT_BIT,
"16color": ColorSystem.STANDARD,
}
| NoChange |
python | django-extensions__django-extensions | django_extensions/logging/filters.py | {
"start": 108,
"end": 1102
} | class ____(logging.Filter):
def filter(self, record):
from django.conf import settings
from django.core.cache import cache
# Rate is specified as 1 messages logged per N seconds. (aka cache timeout)
rate = getattr(settings, "RATE_LIMITER_FILTER_RATE", 10)
prefix = getattr(settings, "RATE_LIMITER_FILTER_PREFIX", "ratelimiterfilter")
subject = record.getMessage()
cache_key = "%s:%s" % (prefix, md5(subject).hexdigest())
cache_count_key = "%s:count" % cache_key
result = cache.get_many([cache_key, cache_count_key])
value = result.get(cache_key)
cntr = result.get(cache_count_key)
if not cntr:
cntr = 1
cache.set(cache_count_key, cntr, rate + 60)
if value:
cache.incr(cache_count_key)
return False
record.msg = "[%sx] %s" % (cntr, record.msg)
cache.set(cache_key, time.time(), rate)
return True
| RateLimiterFilter |
python | apache__thrift | test/crossrunner/report.py | {
"start": 3566,
"end": 7203
} | class ____(TestReporter):
def __init__(self, testdir, test, prog):
super(ExecReporter, self).__init__()
self._test = test
self._prog = prog
self.logpath = self.test_logfile(test.name, prog.kind, testdir)
self.out = None
def begin(self):
self._start()
self._open()
if self.out and not self.out.closed:
self._print_header()
else:
self._log.debug('Output stream is not available.')
def end(self, returncode):
self._lock.acquire()
try:
if self.out and not self.out.closed:
self._print_footer(returncode)
self._close()
self.out = None
else:
self._log.debug('Output stream is not available.')
finally:
self._lock.release()
def killed(self):
print(file=self.out)
print('Server process is successfully killed.', file=self.out)
self.end(None)
def died(self):
print(file=self.out)
print('*** Server process has died unexpectedly ***', file=self.out)
self.end(None)
_init_failure_exprs = {
'server': list(map(re.compile, [
'[Aa]ddress already in use',
'Could not bind',
'EADDRINUSE',
])),
'client': list(map(re.compile, [
'[Cc]onnection refused',
'Could not connect to',
'Could not open UNIX ', # domain socket (rb)
'ECONNREFUSED',
'econnrefused', # erl
'CONNECTION-REFUSED-ERROR', # cl
'connect ENOENT', # nodejs domain socket
'No such file or directory', # domain socket
'Sockets.TcpClient.Connect', # csharp
])),
}
def maybe_false_positive(self):
"""Searches through log file for socket bind error.
Returns True if suspicious expression is found, otherwise False"""
try:
if self.out and not self.out.closed:
self.out.flush()
exprs = self._init_failure_exprs[self._prog.kind]
def match(line):
for expr in exprs:
if expr.search(line):
self._log.info("maybe false positive: %s" % line)
return True
with logfile_open(self.logpath, 'r') as fp:
if any(map(match, fp)):
return True
except (KeyboardInterrupt, SystemExit):
raise
except Exception as ex:
self._log.warn('[%s]: Error while detecting false positive: %s' % (self._test.name, str(ex)))
self._log.info(traceback.print_exc())
return False
def _open(self):
self.out = logfile_open(self.logpath, 'w+')
def _close(self):
self.out.close()
def _print_header(self):
self._print_date()
print('Executing: %s' % ' '.join(self._prog.command), file=self.out)
print('Directory: %s' % self._prog.workdir, file=self.out)
print('config:delay: %s' % self._test.delay, file=self.out)
print('config:timeout: %s' % self._test.timeout, file=self.out)
self._print_bar()
self.out.flush()
def _print_footer(self, returncode=None):
self._print_bar()
if returncode is not None:
print('Return code: %d (negative values indicate kill by signal)' % returncode, file=self.out)
else:
print('Process is killed.', file=self.out)
self._print_exec_time()
self._print_date()
| ExecReporter |
python | sympy__sympy | sympy/polys/matrices/exceptions.py | {
"start": 306,
"end": 398
} | class ____(Exception):
"""Base class for errors raised by DomainMatrix"""
pass
| DMError |
python | doocs__leetcode | solution/0900-0999/0949.Largest Time for Given Digits/Solution.py | {
"start": 0,
"end": 467
} | class ____:
def largestTimeFromDigits(self, arr: List[int]) -> str:
cnt = [0] * 10
for v in arr:
cnt[v] += 1
for h in range(23, -1, -1):
for m in range(59, -1, -1):
t = [0] * 10
t[h // 10] += 1
t[h % 10] += 1
t[m // 10] += 1
t[m % 10] += 1
if cnt == t:
return f'{h:02}:{m:02}'
return ''
| Solution |
python | huggingface__transformers | tests/models/qwen3_omni_moe/test_processing_qwen3_omni_moe.py | {
"start": 1268,
"end": 13970
} | class ____(ProcessorTesterMixin, unittest.TestCase):
processor_class = Qwen3OmniMoeProcessor
model_id = "Qwen/Qwen2.5-Omni-7B"
@classmethod
def _setup_image_processor(cls):
image_processor_class = cls._get_component_class_from_processor("image_processor")
return image_processor_class.from_pretrained(
cls.model_id, size={"shortest_edge": 28 * 28, "longest_edge": 56 * 56}
)
@classmethod
def _setup_video_processor(cls):
video_processor_class = cls._get_component_class_from_processor("video_processor")
return video_processor_class.from_pretrained(
cls.model_id, size={"shortest_edge": 28 * 28, "longest_edge": 56 * 56}
)
def prepare_audio_inputs(self, batch_size: int = 3):
"""This function prepares a list of numpy audios."""
audio_inputs = [np.random.rand(160000) * 2 - 1] * batch_size
return audio_inputs
@require_torch
def _test_apply_chat_template(
self,
modality: str,
batch_size: int,
return_tensors: str,
input_name: str,
processor_name: str,
input_data: list[str],
):
processor = self.get_processor()
if processor.chat_template is None:
self.skipTest("Processor has no chat template")
if processor_name not in self.processor_class.get_attributes():
self.skipTest(f"{processor_name} attribute not present in {self.processor_class}")
batch_messages = [
[
{
"role": "user",
"content": [{"type": "text", "text": "Describe this."}],
},
]
] * batch_size
# Test that jinja can be applied
formatted_prompt = processor.apply_chat_template(batch_messages, add_generation_prompt=True, tokenize=False)
self.assertEqual(len(formatted_prompt), batch_size)
# Test that tokenizing with template and directly with `self.tokenizer` gives same output
formatted_prompt_tokenized = processor.apply_chat_template(
batch_messages, add_generation_prompt=True, tokenize=True, return_tensors=return_tensors
)
add_special_tokens = True
if processor.tokenizer.bos_token is not None and formatted_prompt[0].startswith(processor.tokenizer.bos_token):
add_special_tokens = False
tok_output = processor.tokenizer(
formatted_prompt, return_tensors=return_tensors, add_special_tokens=add_special_tokens
)
expected_output = tok_output.input_ids
self.assertListEqual(expected_output.tolist(), formatted_prompt_tokenized.tolist())
# Test that kwargs passed to processor's `__call__` are actually used
tokenized_prompt_100 = processor.apply_chat_template(
batch_messages,
add_generation_prompt=True,
tokenize=True,
padding="max_length",
truncation=True,
return_tensors=return_tensors,
max_length=100,
)
self.assertEqual(len(tokenized_prompt_100[0]), 100)
# Test that `return_dict=True` returns text related inputs in the dict
out_dict_text = processor.apply_chat_template(
batch_messages,
add_generation_prompt=True,
tokenize=True,
return_dict=True,
return_tensors=return_tensors,
)
self.assertTrue(all(key in out_dict_text for key in ["input_ids", "attention_mask"]))
self.assertEqual(len(out_dict_text["input_ids"]), batch_size)
self.assertEqual(len(out_dict_text["attention_mask"]), batch_size)
# Test that with modality URLs and `return_dict=True`, we get modality inputs in the dict
for idx, url in enumerate(input_data[:batch_size]):
batch_messages[idx][0]["content"] = [batch_messages[idx][0]["content"][0], {"type": modality, "url": url}]
out_dict = processor.apply_chat_template(
batch_messages,
add_generation_prompt=True,
tokenize=True,
return_dict=True,
return_tensors=return_tensors,
num_frames=2, # by default no more than 2 frames, otherwise too slow
)
input_name = getattr(self, input_name)
self.assertTrue(input_name in out_dict)
self.assertEqual(len(out_dict["input_ids"]), batch_size)
self.assertEqual(len(out_dict["attention_mask"]), batch_size)
if modality == "video":
# qwen pixels don't scale with bs same way as other models, calculate expected video token count based on video_grid_thw
expected_video_token_count = 0
for thw in out_dict["video_grid_thw"]:
expected_video_token_count += thw[0] * thw[1] * thw[2]
mm_len = expected_video_token_count
elif modality == "audio":
mm_len = batch_size
else:
mm_len = batch_size * 1200
self.assertEqual(len(out_dict[input_name]), mm_len)
return_tensor_to_type = {"pt": torch.Tensor, "np": np.ndarray, None: list}
for k in out_dict:
self.assertIsInstance(out_dict[k], return_tensor_to_type[return_tensors])
@unittest.skip("Skipping but this one is important, should be fixed ASAP")
@parameterized.expand([(1, "pt"), (2, "pt")])
def test_apply_chat_template_image(self, batch_size: int, return_tensors: str):
pass
@require_av
def test_apply_chat_template_video_frame_sampling(self):
processor = self.get_processor()
if processor.chat_template is None:
self.skipTest("Processor has no chat template")
signature = inspect.signature(processor.__call__)
if "videos" not in {*signature.parameters.keys()} or (
signature.parameters.get("videos") is not None
and signature.parameters["videos"].annotation == inspect._empty
):
self.skipTest("Processor doesn't accept videos at input")
messages = [
[
{
"role": "user",
"content": [
{"type": "text", "text": "What is shown in this video?"},
],
},
]
]
formatted_prompt = processor.apply_chat_template(messages, add_generation_prompt=True, tokenize=False)
self.assertEqual(len(formatted_prompt), 1)
formatted_prompt_tokenized = processor.apply_chat_template(messages, add_generation_prompt=True, tokenize=True)
expected_output = processor.tokenizer(formatted_prompt, return_tensors=None).input_ids
self.assertListEqual(expected_output, formatted_prompt_tokenized)
out_dict = processor.apply_chat_template(messages, add_generation_prompt=True, tokenize=True, return_dict=True)
self.assertListEqual(list(out_dict.keys()), ["input_ids", "attention_mask"])
# Add video URL for return dict and load with `num_frames` arg
messages[0][0]["content"].append(
{
"type": "video",
"url": url_to_local_path(
"https://huggingface.co/datasets/raushan-testing-hf/videos-test/resolve/main/tiny_video.mp4"
),
}
)
num_frames = 3
out_dict_with_video = processor.apply_chat_template(
messages,
add_generation_prompt=True,
tokenize=True,
return_dict=True,
num_frames=num_frames,
)
self.assertTrue(self.videos_input_name in out_dict_with_video)
self.assertEqual(len(out_dict_with_video[self.videos_input_name]), 7728)
# Load with `fps` arg
fps = 1
out_dict_with_video = processor.apply_chat_template(
messages,
add_generation_prompt=True,
tokenize=True,
return_dict=True,
fps=fps,
)
self.assertTrue(self.videos_input_name in out_dict_with_video)
self.assertEqual(len(out_dict_with_video[self.videos_input_name]), 7728)
# Load with `fps` and `num_frames` args, should raise an error
with self.assertRaises(ValueError):
out_dict_with_video = processor.apply_chat_template(
messages,
add_generation_prompt=True,
tokenize=True,
return_dict=True,
fps=fps,
num_frames=num_frames,
)
# Load without any arg should load the whole video
out_dict_with_video = processor.apply_chat_template(
messages,
add_generation_prompt=True,
tokenize=True,
return_dict=True,
)
self.assertTrue(self.videos_input_name in out_dict_with_video)
self.assertEqual(len(out_dict_with_video[self.videos_input_name]), 23184)
# Load video as a list of frames (i.e. images). NOTE: each frame should have same size
# because we assume they come from one video
messages[0][0]["content"][-1] = {
"type": "video",
"url": [
"https://www.ilankelman.org/stopsigns/australia.jpg",
"https://www.ilankelman.org/stopsigns/australia.jpg",
],
}
out_dict_with_video = processor.apply_chat_template(
messages,
add_generation_prompt=True,
tokenize=True,
return_dict=True,
)
self.assertTrue(self.videos_input_name in out_dict_with_video)
self.assertEqual(len(out_dict_with_video[self.videos_input_name]), 7600)
# When the inputs are frame URLs/paths we expect that those are already
# sampled and will raise an error is asked to sample again.
with self.assertRaises(ValueError):
out_dict_with_video = processor.apply_chat_template(
messages,
add_generation_prompt=True,
tokenize=True,
return_dict=True,
do_sample_frames=True,
num_frames=num_frames,
)
@require_librosa
@require_av
def test_chat_template_audio_from_video(self):
processor = self.get_processor()
if processor.chat_template is None:
self.skipTest("Processor has no chat template")
signature = inspect.signature(processor.__call__)
if "videos" not in {*signature.parameters.keys()} or (
signature.parameters.get("videos") is not None
and signature.parameters["videos"].annotation == inspect._empty
):
self.skipTest(f"{self.processor_class} does not support video inputs")
if "feature_extractor" not in self.processor_class.get_attributes():
self.skipTest(f"feature_extractor attribute not present in {self.processor_class}")
video_file_path = hf_hub_download(
repo_id="raushan-testing-hf/videos-test", filename="sample_demo_1.mp4", repo_type="dataset"
)
messages = [
{
"role": "user",
"content": [
{"type": "video", "path": video_file_path},
{"type": "text", "text": "Which of these animals is making the sound?"},
],
},
{
"role": "assistant",
"content": [{"type": "text", "text": "It is a cow."}],
},
{
"role": "user",
"content": [
{"type": "text", "text": "Tell me all about this animal."},
],
},
]
formatted_prompt = processor.apply_chat_template([messages], add_generation_prompt=True, tokenize=False)
self.assertEqual(len(formatted_prompt), 1) # batch size=1
out_dict = processor.apply_chat_template(
messages,
add_generation_prompt=True,
tokenize=True,
return_dict=True,
return_tensors="pt",
load_audio_from_video=True,
)
self.assertTrue(self.audio_input_name in out_dict)
self.assertTrue(self.videos_input_name in out_dict)
# should always have input_ids and attention_mask
self.assertEqual(len(out_dict["input_ids"]), 1) # batch-size=1
self.assertEqual(len(out_dict["attention_mask"]), 1) # batch-size=1
self.assertEqual(len(out_dict[self.audio_input_name]), 1) # 1 audio in the conversation
self.assertEqual(len(out_dict[self.videos_input_name]), 145912) # 1 video in the conversation
| Qwen3OmniMoeProcessorTest |
python | ray-project__ray | python/ray/util/client/server/proxier.py | {
"start": 32810,
"end": 36320
} | class ____(ray_client_pb2_grpc.RayletLogStreamerServicer):
def __init__(self, proxy_manager: ProxyManager):
super().__init__()
self.proxy_manager = proxy_manager
def Logstream(self, request_iterator, context):
request_iterator = RequestIteratorProxy(request_iterator)
client_id = _get_client_id_from_context(context)
if client_id == "":
return
logger.debug(f"New logstream connection from client {client_id}: ")
channel = None
# We need to retry a few times because the LogClient *may* connect
# Before the DataClient has finished connecting.
for i in range(LOGSTREAM_RETRIES):
channel = self.proxy_manager.get_channel(client_id)
if channel is not None:
break
logger.warning(f"Retrying Logstream connection. {i+1} attempts failed.")
time.sleep(LOGSTREAM_RETRY_INTERVAL_SEC)
if channel is None:
context.set_code(grpc.StatusCode.NOT_FOUND)
context.set_details(
"Logstream proxy failed to connect. Channel for client "
f"{client_id} not found."
)
return None
stub = ray_client_pb2_grpc.RayletLogStreamerStub(channel)
resp_stream = stub.Logstream(
request_iterator, metadata=[("client_id", client_id)]
)
try:
for resp in resp_stream:
yield resp
except Exception:
logger.exception("Proxying Logstream failed!")
def serve_proxier(
host: str,
port: int,
gcs_address: Optional[str],
*,
redis_username: Optional[str] = None,
redis_password: Optional[str] = None,
session_dir: Optional[str] = None,
runtime_env_agent_address: Optional[str] = None,
):
# Initialize internal KV to be used to upload and download working_dir
# before calling ray.init within the RayletServicers.
# NOTE(edoakes): redis_address and redis_password should only be None in
# tests.
if gcs_address is not None:
gcs_cli = GcsClient(address=gcs_address)
ray.experimental.internal_kv._initialize_internal_kv(gcs_cli)
from ray._private.grpc_utils import create_grpc_server_with_interceptors
server = create_grpc_server_with_interceptors(
max_workers=CLIENT_SERVER_MAX_THREADS,
thread_name_prefix="ray_client_proxier",
options=GRPC_OPTIONS,
asynchronous=False,
)
proxy_manager = ProxyManager(
gcs_address,
session_dir=session_dir,
redis_username=redis_username,
redis_password=redis_password,
runtime_env_agent_address=runtime_env_agent_address,
)
task_servicer = RayletServicerProxy(None, proxy_manager)
data_servicer = DataServicerProxy(proxy_manager)
logs_servicer = LogstreamServicerProxy(proxy_manager)
ray_client_pb2_grpc.add_RayletDriverServicer_to_server(task_servicer, server)
ray_client_pb2_grpc.add_RayletDataStreamerServicer_to_server(data_servicer, server)
ray_client_pb2_grpc.add_RayletLogStreamerServicer_to_server(logs_servicer, server)
if not is_localhost(host):
add_port_to_grpc_server(server, f"127.0.0.1:{port}")
add_port_to_grpc_server(server, f"{host}:{port}")
server.start()
return ClientServerHandle(
task_servicer=task_servicer,
data_servicer=data_servicer,
logs_servicer=logs_servicer,
grpc_server=server,
)
| LogstreamServicerProxy |
python | TheAlgorithms__Python | data_compression/huffman.py | {
"start": 297,
"end": 2727
} | class ____:
def __init__(self, freq: int, left: Letter | TreeNode, right: Letter | TreeNode):
self.freq: int = freq
self.left: Letter | TreeNode = left
self.right: Letter | TreeNode = right
def parse_file(file_path: str) -> list[Letter]:
"""
Read the file and build a dict of all letters and their
frequencies, then convert the dict into a list of Letters.
"""
chars: dict[str, int] = {}
with open(file_path) as f:
while True:
c = f.read(1)
if not c:
break
chars[c] = chars[c] + 1 if c in chars else 1
return sorted((Letter(c, f) for c, f in chars.items()), key=lambda x: x.freq)
def build_tree(letters: list[Letter]) -> Letter | TreeNode:
"""
Run through the list of Letters and build the min heap
for the Huffman Tree.
"""
response: list[Letter | TreeNode] = list(letters)
while len(response) > 1:
left = response.pop(0)
right = response.pop(0)
total_freq = left.freq + right.freq
node = TreeNode(total_freq, left, right)
response.append(node)
response.sort(key=lambda x: x.freq)
return response[0]
def traverse_tree(root: Letter | TreeNode, bitstring: str) -> list[Letter]:
"""
Recursively traverse the Huffman Tree to set each
Letter's bitstring dictionary, and return the list of Letters
"""
if isinstance(root, Letter):
root.bitstring[root.letter] = bitstring
return [root]
treenode: TreeNode = root
letters = []
letters += traverse_tree(treenode.left, bitstring + "0")
letters += traverse_tree(treenode.right, bitstring + "1")
return letters
def huffman(file_path: str) -> None:
"""
Parse the file, build the tree, then run through the file
again, using the letters dictionary to find and print out the
bitstring for each letter.
"""
letters_list = parse_file(file_path)
root = build_tree(letters_list)
letters = {
k: v for letter in traverse_tree(root, "") for k, v in letter.bitstring.items()
}
print(f"Huffman Coding of {file_path}: ")
with open(file_path) as f:
while True:
c = f.read(1)
if not c:
break
print(letters[c], end=" ")
print()
if __name__ == "__main__":
# pass the file path to the huffman function
huffman(sys.argv[1])
| TreeNode |
python | huggingface__transformers | src/transformers/models/levit/configuration_levit.py | {
"start": 807,
"end": 5147
} | class ____(PreTrainedConfig):
r"""
This is the configuration class to store the configuration of a [`LevitModel`]. It is used to instantiate a LeViT
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 LeViT
[facebook/levit-128S](https://huggingface.co/facebook/levit-128S) architecture.
Configuration objects inherit from [`PreTrainedConfig`] and can be used to control the model outputs. Read the
documentation from [`PreTrainedConfig`] for more information.
Args:
image_size (`int`, *optional*, defaults to 224):
The size of the input image.
num_channels (`int`, *optional*, defaults to 3):
Number of channels in the input image.
kernel_size (`int`, *optional*, defaults to 3):
The kernel size for the initial convolution layers of patch embedding.
stride (`int`, *optional*, defaults to 2):
The stride size for the initial convolution layers of patch embedding.
padding (`int`, *optional*, defaults to 1):
The padding size for the initial convolution layers of patch embedding.
patch_size (`int`, *optional*, defaults to 16):
The patch size for embeddings.
hidden_sizes (`list[int]`, *optional*, defaults to `[128, 256, 384]`):
Dimension of each of the encoder blocks.
num_attention_heads (`list[int]`, *optional*, defaults to `[4, 8, 12]`):
Number of attention heads for each attention layer in each block of the Transformer encoder.
depths (`list[int]`, *optional*, defaults to `[4, 4, 4]`):
The number of layers in each encoder block.
key_dim (`list[int]`, *optional*, defaults to `[16, 16, 16]`):
The size of key in each of the encoder blocks.
drop_path_rate (`int`, *optional*, defaults to 0):
The dropout probability for stochastic depths, used in the blocks of the Transformer encoder.
mlp_ratios (`list[int]`, *optional*, defaults to `[2, 2, 2]`):
Ratio of the size of the hidden layer compared to the size of the input layer of the Mix FFNs in the
encoder blocks.
attention_ratios (`list[int]`, *optional*, defaults to `[2, 2, 2]`):
Ratio of the size of the output dimension compared to input dimension of attention layers.
initializer_range (`float`, *optional*, defaults to 0.02):
The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
Example:
```python
>>> from transformers import LevitConfig, LevitModel
>>> # Initializing a LeViT levit-128S style configuration
>>> configuration = LevitConfig()
>>> # Initializing a model (with random weights) from the levit-128S style configuration
>>> model = LevitModel(configuration)
>>> # Accessing the model configuration
>>> configuration = model.config
```"""
model_type = "levit"
def __init__(
self,
image_size=224,
num_channels=3,
kernel_size=3,
stride=2,
padding=1,
patch_size=16,
hidden_sizes=[128, 256, 384],
num_attention_heads=[4, 8, 12],
depths=[4, 4, 4],
key_dim=[16, 16, 16],
drop_path_rate=0,
mlp_ratio=[2, 2, 2],
attention_ratio=[2, 2, 2],
initializer_range=0.02,
**kwargs,
):
super().__init__(**kwargs)
self.image_size = image_size
self.num_channels = num_channels
self.kernel_size = kernel_size
self.stride = stride
self.padding = padding
self.hidden_sizes = hidden_sizes
self.num_attention_heads = num_attention_heads
self.depths = depths
self.key_dim = key_dim
self.drop_path_rate = drop_path_rate
self.patch_size = patch_size
self.attention_ratio = attention_ratio
self.mlp_ratio = mlp_ratio
self.initializer_range = initializer_range
self.down_ops = [
["Subsample", key_dim[0], hidden_sizes[0] // key_dim[0], 4, 2, 2],
["Subsample", key_dim[0], hidden_sizes[1] // key_dim[0], 4, 2, 2],
]
__all__ = ["LevitConfig"]
| LevitConfig |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/sql/elements.py | {
"start": 66243,
"end": 66856
} | class ____(roles.InElementRole, KeyedColumnElement[_T]):
"""Refer to another column's VALUES or SET expression in an INSERT or
UPDATE statement.
See the public-facing :func:`_sql.from_dml_column` constructor for
background.
.. versionadded:: 2.1
"""
def __init__(self, column: _DMLOnlyColumnArgument[_T]):
self.column = coercions.expect(roles.ColumnArgumentRole, column)
self.type = self.column.type
__visit_name__ = "dmltargetcopy"
_traverse_internals: _TraverseInternalsType = [
("column", InternalTraversal.dp_clauseelement),
]
| DMLTargetCopy |
python | apache__airflow | providers/google/tests/unit/google/cloud/operators/test_translate_speech.py | {
"start": 1284,
"end": 7144
} | class ____:
@mock.patch("airflow.providers.google.cloud.operators.translate_speech.CloudSpeechToTextHook")
@mock.patch("airflow.providers.google.cloud.operators.translate_speech.CloudTranslateHook")
def test_minimal_green_path(self, mock_translate_hook, mock_speech_hook):
mock_speech_hook.return_value.recognize_speech.return_value = RecognizeResponse(
results=[
SpeechRecognitionResult(
alternatives=[SpeechRecognitionAlternative(transcript="test speech recognition result")]
)
]
)
mock_translate_hook.return_value.translate.return_value = [
{
"translatedText": "sprawdzić wynik rozpoznawania mowy",
"detectedSourceLanguage": "en",
"model": "base",
"input": "test speech recognition result",
}
]
op = CloudTranslateSpeechOperator(
audio=RecognitionAudio({"uri": "gs://bucket/object"}),
config=RecognitionConfig({"encoding": "LINEAR16"}),
target_language="pl",
format_="text",
source_language=None,
model="base",
gcp_conn_id=GCP_CONN_ID,
task_id="id",
impersonation_chain=IMPERSONATION_CHAIN,
)
context = mock.MagicMock()
return_value = op.execute(context=context)
mock_speech_hook.assert_called_once_with(
gcp_conn_id=GCP_CONN_ID,
impersonation_chain=IMPERSONATION_CHAIN,
)
mock_translate_hook.assert_called_once_with(
gcp_conn_id=GCP_CONN_ID,
impersonation_chain=IMPERSONATION_CHAIN,
)
mock_speech_hook.return_value.recognize_speech.assert_called_once_with(
audio=RecognitionAudio({"uri": "gs://bucket/object"}),
config=RecognitionConfig({"encoding": "LINEAR16"}),
)
mock_translate_hook.return_value.translate.assert_called_once_with(
values="test speech recognition result",
target_language="pl",
format_="text",
source_language=None,
model="base",
)
assert return_value == [
{
"translatedText": "sprawdzić wynik rozpoznawania mowy",
"detectedSourceLanguage": "en",
"model": "base",
"input": "test speech recognition result",
}
]
@mock.patch("airflow.providers.google.cloud.operators.translate_speech.CloudSpeechToTextHook")
@mock.patch("airflow.providers.google.cloud.operators.translate_speech.CloudTranslateHook")
def test_bad_recognition_response(self, mock_translate_hook, mock_speech_hook):
mock_speech_hook.return_value.recognize_speech.return_value = RecognizeResponse(
results=[SpeechRecognitionResult()]
)
op = CloudTranslateSpeechOperator(
audio=RecognitionAudio({"uri": "gs://bucket/object"}),
config=RecognitionConfig({"encoding": "LINEAR16"}),
target_language="pl",
format_="text",
source_language=None,
model="base",
gcp_conn_id=GCP_CONN_ID,
task_id="id",
)
with pytest.raises(AirflowException) as ctx:
op.execute(context=None)
err = ctx.value
assert "it should contain 'alternatives' field" in str(err)
mock_speech_hook.assert_called_once_with(
gcp_conn_id=GCP_CONN_ID,
impersonation_chain=None,
)
mock_translate_hook.assert_called_once_with(
gcp_conn_id=GCP_CONN_ID,
impersonation_chain=None,
)
mock_speech_hook.return_value.recognize_speech.assert_called_once_with(
audio=RecognitionAudio({"uri": "gs://bucket/object"}),
config=RecognitionConfig({"encoding": "LINEAR16"}),
)
mock_translate_hook.return_value.translate.assert_not_called()
@mock.patch("airflow.providers.google.cloud.operators.translate_speech.FileDetailsLink.persist")
@mock.patch("airflow.providers.google.cloud.operators.translate_speech.CloudSpeechToTextHook")
@mock.patch("airflow.providers.google.cloud.operators.translate_speech.CloudTranslateHook")
def test_no_audio_uri(self, mock_translate_hook, mock_speech_hook, file_link_mock):
mock_speech_hook.return_value.recognize_speech.return_value = RecognizeResponse(
results=[
SpeechRecognitionResult(
alternatives=[SpeechRecognitionAlternative(transcript="test speech recognition result")]
)
]
)
mock_translate_hook.return_value.translate.return_value = [
{
"translatedText": "sprawdzić wynik rozpoznawania mowy",
"detectedSourceLanguage": "en",
"model": "base",
"input": "test speech recognition result",
}
]
op = CloudTranslateSpeechOperator(
audio=RecognitionAudio({"content": b"set content data instead of uri"}),
config=RecognitionConfig({"encoding": "LINEAR16"}),
target_language="pl",
format_="text",
source_language=None,
model="base",
gcp_conn_id=GCP_CONN_ID,
task_id="id",
impersonation_chain=IMPERSONATION_CHAIN,
)
op.execute(context=mock.MagicMock())
mock_speech_hook.return_value.recognize_speech.assert_called_once_with(
audio=RecognitionAudio({"content": b"set content data instead of uri"}),
config=RecognitionConfig({"encoding": "LINEAR16"}),
)
assert op.audio.uri == ""
file_link_mock.assert_not_called()
| TestCloudTranslateSpeech |
python | nedbat__coveragepy | tests/test_oddball.py | {
"start": 22186,
"end": 24101
} | class ____(CoverageTest):
"""Tests of exec."""
def test_correct_filename(self) -> None:
# https://github.com/coveragepy/coveragepy/issues/380
# Bug was that exec'd files would have their lines attributed to the
# calling file. Make two files, both with ~30 lines, but no lines in
# common. Line 30 in to_exec.py was recorded as line 30 in main.py,
# but now it's fixed. :)
self.make_file(
"to_exec.py",
"""\
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
print("var is {}".format(var)) # line 31
""",
)
self.make_file(
"main.py",
"""\
namespace = {'var': 17}
with open("to_exec.py", encoding="utf-8") as to_exec_py:
code = compile(to_exec_py.read(), 'to_exec.py', 'exec')
exec(code, globals(), namespace)
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
print("done") # line 35
""",
)
cov = coverage.Coverage()
self.start_import_stop(cov, "main")
_, statements, missing, _ = cov.analysis("main.py")
assert statements == [1, 2, 3, 4, 35]
assert missing == []
_, statements, missing, _ = cov.analysis("to_exec.py")
assert statements == [31]
assert missing == []
def test_unencodable_filename(self) -> None:
# https://github.com/coveragepy/coveragepy/issues/891
self.make_file("bug891.py", r"""exec(compile("pass", "\udcff.py", "exec"))""")
cov = coverage.Coverage()
self.start_import_stop(cov, "bug891")
# Saving would fail trying to encode \udcff.py
cov.save()
files = [os.path.basename(f) for f in cov.get_data().measured_files()]
assert "bug891.py" in files
| ExecTest |
python | pypa__setuptools | setuptools/_distutils/fancy_getopt.py | {
"start": 1172,
"end": 17196
} | class ____:
"""Wrapper around the standard 'getopt()' module that provides some
handy extra functionality:
* short and long options are tied together
* options have help strings, and help text can be assembled
from them
* options set attributes of a passed-in object
* boolean options can have "negative aliases" -- eg. if
--quiet is the "negative alias" of --verbose, then "--quiet"
on the command line sets 'verbose' to false
"""
def __init__(self, option_table=None):
# The option table is (currently) a list of tuples. The
# tuples may have 3 or four values:
# (long_option, short_option, help_string [, repeatable])
# if an option takes an argument, its long_option should have '='
# appended; short_option should just be a single character, no ':'
# in any case. If a long_option doesn't have a corresponding
# short_option, short_option should be None. All option tuples
# must have long options.
self.option_table = option_table
# 'option_index' maps long option names to entries in the option
# table (ie. those 3-tuples).
self.option_index = {}
if self.option_table:
self._build_index()
# 'alias' records (duh) alias options; {'foo': 'bar'} means
# --foo is an alias for --bar
self.alias = {}
# 'negative_alias' keeps track of options that are the boolean
# opposite of some other option
self.negative_alias = {}
# These keep track of the information in the option table. We
# don't actually populate these structures until we're ready to
# parse the command-line, since the 'option_table' passed in here
# isn't necessarily the final word.
self.short_opts = []
self.long_opts = []
self.short2long = {}
self.attr_name = {}
self.takes_arg = {}
# And 'option_order' is filled up in 'getopt()'; it records the
# original order of options (and their values) on the command-line,
# but expands short options, converts aliases, etc.
self.option_order = []
def _build_index(self):
self.option_index.clear()
for option in self.option_table:
self.option_index[option[0]] = option
def set_option_table(self, option_table):
self.option_table = option_table
self._build_index()
def add_option(self, long_option, short_option=None, help_string=None):
if long_option in self.option_index:
raise DistutilsGetoptError(
f"option conflict: already an option '{long_option}'"
)
else:
option = (long_option, short_option, help_string)
self.option_table.append(option)
self.option_index[long_option] = option
def has_option(self, long_option):
"""Return true if the option table for this parser has an
option with long name 'long_option'."""
return long_option in self.option_index
def get_attr_name(self, long_option):
"""Translate long option name 'long_option' to the form it
has as an attribute of some object: ie., translate hyphens
to underscores."""
return long_option.translate(longopt_xlate)
def _check_alias_dict(self, aliases, what):
assert isinstance(aliases, dict)
for alias, opt in aliases.items():
if alias not in self.option_index:
raise DistutilsGetoptError(
f"invalid {what} '{alias}': option '{alias}' not defined"
)
if opt not in self.option_index:
raise DistutilsGetoptError(
f"invalid {what} '{alias}': aliased option '{opt}' not defined"
)
def set_aliases(self, alias):
"""Set the aliases for this option parser."""
self._check_alias_dict(alias, "alias")
self.alias = alias
def set_negative_aliases(self, negative_alias):
"""Set the negative aliases for this option parser.
'negative_alias' should be a dictionary mapping option names to
option names, both the key and value must already be defined
in the option table."""
self._check_alias_dict(negative_alias, "negative alias")
self.negative_alias = negative_alias
def _grok_option_table(self): # noqa: C901
"""Populate the various data structures that keep tabs on the
option table. Called by 'getopt()' before it can do anything
worthwhile.
"""
self.long_opts = []
self.short_opts = []
self.short2long.clear()
self.repeat = {}
for option in self.option_table:
if len(option) == 3:
long, short, help = option
repeat = 0
elif len(option) == 4:
long, short, help, repeat = option
else:
# the option table is part of the code, so simply
# assert that it is correct
raise ValueError(f"invalid option tuple: {option!r}")
# Type- and value-check the option names
if not isinstance(long, str) or len(long) < 2:
raise DistutilsGetoptError(
f"invalid long option '{long}': must be a string of length >= 2"
)
if not ((short is None) or (isinstance(short, str) and len(short) == 1)):
raise DistutilsGetoptError(
f"invalid short option '{short}': must a single character or None"
)
self.repeat[long] = repeat
self.long_opts.append(long)
if long[-1] == '=': # option takes an argument?
if short:
short = short + ':'
long = long[0:-1]
self.takes_arg[long] = True
else:
# Is option is a "negative alias" for some other option (eg.
# "quiet" == "!verbose")?
alias_to = self.negative_alias.get(long)
if alias_to is not None:
if self.takes_arg[alias_to]:
raise DistutilsGetoptError(
f"invalid negative alias '{long}': "
f"aliased option '{alias_to}' takes a value"
)
self.long_opts[-1] = long # XXX redundant?!
self.takes_arg[long] = False
# If this is an alias option, make sure its "takes arg" flag is
# the same as the option it's aliased to.
alias_to = self.alias.get(long)
if alias_to is not None:
if self.takes_arg[long] != self.takes_arg[alias_to]:
raise DistutilsGetoptError(
f"invalid alias '{long}': inconsistent with "
f"aliased option '{alias_to}' (one of them takes a value, "
"the other doesn't"
)
# Now enforce some bondage on the long option name, so we can
# later translate it to an attribute name on some object. Have
# to do this a bit late to make sure we've removed any trailing
# '='.
if not longopt_re.match(long):
raise DistutilsGetoptError(
f"invalid long option name '{long}' "
"(must be letters, numbers, hyphens only"
)
self.attr_name[long] = self.get_attr_name(long)
if short:
self.short_opts.append(short)
self.short2long[short[0]] = long
def getopt(self, args: Sequence[str] | None = None, object=None): # noqa: C901
"""Parse command-line options in args. Store as attributes on object.
If 'args' is None or not supplied, uses 'sys.argv[1:]'. If
'object' is None or not supplied, creates a new OptionDummy
object, stores option values there, and returns a tuple (args,
object). If 'object' is supplied, it is modified in place and
'getopt()' just returns 'args'; in both cases, the returned
'args' is a modified copy of the passed-in 'args' list, which
is left untouched.
"""
if args is None:
args = sys.argv[1:]
if object is None:
object = OptionDummy()
created_object = True
else:
created_object = False
self._grok_option_table()
short_opts = ' '.join(self.short_opts)
try:
opts, args = getopt.getopt(args, short_opts, self.long_opts)
except getopt.error as msg:
raise DistutilsArgError(msg)
for opt, val in opts:
if len(opt) == 2 and opt[0] == '-': # it's a short option
opt = self.short2long[opt[1]]
else:
assert len(opt) > 2 and opt[:2] == '--'
opt = opt[2:]
alias = self.alias.get(opt)
if alias:
opt = alias
if not self.takes_arg[opt]: # boolean option?
assert val == '', "boolean option can't have value"
alias = self.negative_alias.get(opt)
if alias:
opt = alias
val = 0
else:
val = 1
attr = self.attr_name[opt]
# The only repeating option at the moment is 'verbose'.
# It has a negative option -q quiet, which should set verbose = False.
if val and self.repeat.get(attr) is not None:
val = getattr(object, attr, 0) + 1
setattr(object, attr, val)
self.option_order.append((opt, val))
# for opts
if created_object:
return args, object
else:
return args
def get_option_order(self):
"""Returns the list of (option, value) tuples processed by the
previous run of 'getopt()'. Raises RuntimeError if
'getopt()' hasn't been called yet.
"""
if self.option_order is None:
raise RuntimeError("'getopt()' hasn't been called yet")
else:
return self.option_order
def generate_help(self, header=None): # noqa: C901
"""Generate help text (a list of strings, one per suggested line of
output) from the option table for this FancyGetopt object.
"""
# Blithely assume the option table is good: probably wouldn't call
# 'generate_help()' unless you've already called 'getopt()'.
# First pass: determine maximum length of long option names
max_opt = 0
for option in self.option_table:
long = option[0]
short = option[1]
ell = len(long)
if long[-1] == '=':
ell = ell - 1
if short is not None:
ell = ell + 5 # " (-x)" where short == 'x'
if ell > max_opt:
max_opt = ell
opt_width = max_opt + 2 + 2 + 2 # room for indent + dashes + gutter
# Typical help block looks like this:
# --foo controls foonabulation
# Help block for longest option looks like this:
# --flimflam set the flim-flam level
# and with wrapped text:
# --flimflam set the flim-flam level (must be between
# 0 and 100, except on Tuesdays)
# Options with short names will have the short name shown (but
# it doesn't contribute to max_opt):
# --foo (-f) controls foonabulation
# If adding the short option would make the left column too wide,
# we push the explanation off to the next line
# --flimflam (-l)
# set the flim-flam level
# Important parameters:
# - 2 spaces before option block start lines
# - 2 dashes for each long option name
# - min. 2 spaces between option and explanation (gutter)
# - 5 characters (incl. space) for short option name
# Now generate lines of help text. (If 80 columns were good enough
# for Jesus, then 78 columns are good enough for me!)
line_width = 78
text_width = line_width - opt_width
big_indent = ' ' * opt_width
if header:
lines = [header]
else:
lines = ['Option summary:']
for option in self.option_table:
long, short, help = option[:3]
text = wrap_text(help, text_width)
if long[-1] == '=':
long = long[0:-1]
# Case 1: no short option at all (makes life easy)
if short is None:
if text:
lines.append(f" --{long:<{max_opt}} {text[0]}")
else:
lines.append(f" --{long:<{max_opt}}")
# Case 2: we have a short option, so we have to include it
# just after the long option
else:
opt_names = f"{long} (-{short})"
if text:
lines.append(f" --{opt_names:<{max_opt}} {text[0]}")
else:
lines.append(f" --{opt_names:<{max_opt}}")
for ell in text[1:]:
lines.append(big_indent + ell)
return lines
def print_help(self, header=None, file=None):
if file is None:
file = sys.stdout
for line in self.generate_help(header):
file.write(line + "\n")
def fancy_getopt(options, negative_opt, object, args: Sequence[str] | None):
parser = FancyGetopt(options)
parser.set_negative_aliases(negative_opt)
return parser.getopt(args, object)
WS_TRANS = {ord(_wschar): ' ' for _wschar in string.whitespace}
def wrap_text(text, width):
"""wrap_text(text : string, width : int) -> [string]
Split 'text' into multiple lines of no more than 'width' characters
each, and return the list of strings that results.
"""
if text is None:
return []
if len(text) <= width:
return [text]
text = text.expandtabs()
text = text.translate(WS_TRANS)
chunks = re.split(r'( +|-+)', text)
chunks = [ch for ch in chunks if ch] # ' - ' results in empty strings
lines = []
while chunks:
cur_line = [] # list of chunks (to-be-joined)
cur_len = 0 # length of current line
while chunks:
ell = len(chunks[0])
if cur_len + ell <= width: # can squeeze (at least) this chunk in
cur_line.append(chunks[0])
del chunks[0]
cur_len = cur_len + ell
else: # this line is full
# drop last chunk if all space
if cur_line and cur_line[-1][0] == ' ':
del cur_line[-1]
break
if chunks: # any chunks left to process?
# if the current line is still empty, then we had a single
# chunk that's too big too fit on a line -- so we break
# down and break it up at the line width
if cur_len == 0:
cur_line.append(chunks[0][0:width])
chunks[0] = chunks[0][width:]
# all-whitespace chunks at the end of a line can be discarded
# (and we know from the re.split above that if a chunk has
# *any* whitespace, it is *all* whitespace)
if chunks[0][0] == ' ':
del chunks[0]
# and store this line in the list-of-all-lines -- as a single
# string, of course!
lines.append(''.join(cur_line))
return lines
def translate_longopt(opt):
"""Convert a long option name to a valid Python identifier by
changing "-" to "_".
"""
return opt.translate(longopt_xlate)
| FancyGetopt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.