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
|
plotly__plotly.py
|
plotly/graph_objs/cone/_hoverlabel.py
|
{
"start": 233,
"end": 11220
}
|
class ____(_BaseTraceHierarchyType):
_parent_path_str = "cone"
_path_str = "cone.hoverlabel"
_valid_props = {
"align",
"alignsrc",
"bgcolor",
"bgcolorsrc",
"bordercolor",
"bordercolorsrc",
"font",
"namelength",
"namelengthsrc",
"showarrow",
}
@property
def align(self):
"""
Sets the horizontal alignment of the text content within hover
label box. Has an effect only if the hover label text spans
more two or more lines
The 'align' property is an enumeration that may be specified as:
- One of the following enumeration values:
['left', 'right', 'auto']
- A tuple, list, or one-dimensional numpy array of the above
Returns
-------
Any|numpy.ndarray
"""
return self["align"]
@align.setter
def align(self, val):
self["align"] = val
@property
def alignsrc(self):
"""
Sets the source reference on Chart Studio Cloud for `align`.
The 'alignsrc' property must be specified as a string or
as a plotly.grid_objs.Column object
Returns
-------
str
"""
return self["alignsrc"]
@alignsrc.setter
def alignsrc(self, val):
self["alignsrc"] = val
@property
def bgcolor(self):
"""
Sets the background color of the hover labels for this trace
The 'bgcolor' property is a color and may be specified as:
- A hex string (e.g. '#ff0000')
- An rgb/rgba string (e.g. 'rgb(255,0,0)')
- An hsl/hsla string (e.g. 'hsl(0,100%,50%)')
- An hsv/hsva string (e.g. 'hsv(0,100%,100%)')
- A named CSS color: see https://plotly.com/python/css-colors/ for a list
- A list or array of any of the above
Returns
-------
str|numpy.ndarray
"""
return self["bgcolor"]
@bgcolor.setter
def bgcolor(self, val):
self["bgcolor"] = val
@property
def bgcolorsrc(self):
"""
Sets the source reference on Chart Studio Cloud for `bgcolor`.
The 'bgcolorsrc' property must be specified as a string or
as a plotly.grid_objs.Column object
Returns
-------
str
"""
return self["bgcolorsrc"]
@bgcolorsrc.setter
def bgcolorsrc(self, val):
self["bgcolorsrc"] = val
@property
def bordercolor(self):
"""
Sets the border color of the hover labels for this trace.
The 'bordercolor' property is a color and may be specified as:
- A hex string (e.g. '#ff0000')
- An rgb/rgba string (e.g. 'rgb(255,0,0)')
- An hsl/hsla string (e.g. 'hsl(0,100%,50%)')
- An hsv/hsva string (e.g. 'hsv(0,100%,100%)')
- A named CSS color: see https://plotly.com/python/css-colors/ for a list
- A list or array of any of the above
Returns
-------
str|numpy.ndarray
"""
return self["bordercolor"]
@bordercolor.setter
def bordercolor(self, val):
self["bordercolor"] = val
@property
def bordercolorsrc(self):
"""
Sets the source reference on Chart Studio Cloud for
`bordercolor`.
The 'bordercolorsrc' property must be specified as a string or
as a plotly.grid_objs.Column object
Returns
-------
str
"""
return self["bordercolorsrc"]
@bordercolorsrc.setter
def bordercolorsrc(self, val):
self["bordercolorsrc"] = val
@property
def font(self):
"""
Sets the font used in hover labels.
The 'font' property is an instance of Font
that may be specified as:
- An instance of :class:`plotly.graph_objs.cone.hoverlabel.Font`
- A dict of string/value properties that will be passed
to the Font constructor
Returns
-------
plotly.graph_objs.cone.hoverlabel.Font
"""
return self["font"]
@font.setter
def font(self, val):
self["font"] = val
@property
def namelength(self):
"""
Sets the default length (in number of characters) of the trace
name in the hover labels for all traces. -1 shows the whole
name regardless of length. 0-3 shows the first 0-3 characters,
and an integer >3 will show the whole name if it is less than
that many characters, but if it is longer, will truncate to
`namelength - 3` characters and add an ellipsis.
The 'namelength' property is a integer and may be specified as:
- An int (or float that will be cast to an int)
in the interval [-1, 9223372036854775807]
- A tuple, list, or one-dimensional numpy array of the above
Returns
-------
int|numpy.ndarray
"""
return self["namelength"]
@namelength.setter
def namelength(self, val):
self["namelength"] = val
@property
def namelengthsrc(self):
"""
Sets the source reference on Chart Studio Cloud for
`namelength`.
The 'namelengthsrc' property must be specified as a string or
as a plotly.grid_objs.Column object
Returns
-------
str
"""
return self["namelengthsrc"]
@namelengthsrc.setter
def namelengthsrc(self, val):
self["namelengthsrc"] = val
@property
def showarrow(self):
"""
Sets whether or not to show the hover label arrow/triangle
pointing to the data point.
The 'showarrow' property must be specified as a bool
(either True, or False)
Returns
-------
bool
"""
return self["showarrow"]
@showarrow.setter
def showarrow(self, val):
self["showarrow"] = val
@property
def _prop_descriptions(self):
return """\
align
Sets the horizontal alignment of the text content
within hover label box. Has an effect only if the hover
label text spans more two or more lines
alignsrc
Sets the source reference on Chart Studio Cloud for
`align`.
bgcolor
Sets the background color of the hover labels for this
trace
bgcolorsrc
Sets the source reference on Chart Studio Cloud for
`bgcolor`.
bordercolor
Sets the border color of the hover labels for this
trace.
bordercolorsrc
Sets the source reference on Chart Studio Cloud for
`bordercolor`.
font
Sets the font used in hover labels.
namelength
Sets the default length (in number of characters) of
the trace name in the hover labels for all traces. -1
shows the whole name regardless of length. 0-3 shows
the first 0-3 characters, and an integer >3 will show
the whole name if it is less than that many characters,
but if it is longer, will truncate to `namelength - 3`
characters and add an ellipsis.
namelengthsrc
Sets the source reference on Chart Studio Cloud for
`namelength`.
showarrow
Sets whether or not to show the hover label
arrow/triangle pointing to the data point.
"""
def __init__(
self,
arg=None,
align=None,
alignsrc=None,
bgcolor=None,
bgcolorsrc=None,
bordercolor=None,
bordercolorsrc=None,
font=None,
namelength=None,
namelengthsrc=None,
showarrow=None,
**kwargs,
):
"""
Construct a new Hoverlabel object
Parameters
----------
arg
dict of properties compatible with this constructor or
an instance of
:class:`plotly.graph_objs.cone.Hoverlabel`
align
Sets the horizontal alignment of the text content
within hover label box. Has an effect only if the hover
label text spans more two or more lines
alignsrc
Sets the source reference on Chart Studio Cloud for
`align`.
bgcolor
Sets the background color of the hover labels for this
trace
bgcolorsrc
Sets the source reference on Chart Studio Cloud for
`bgcolor`.
bordercolor
Sets the border color of the hover labels for this
trace.
bordercolorsrc
Sets the source reference on Chart Studio Cloud for
`bordercolor`.
font
Sets the font used in hover labels.
namelength
Sets the default length (in number of characters) of
the trace name in the hover labels for all traces. -1
shows the whole name regardless of length. 0-3 shows
the first 0-3 characters, and an integer >3 will show
the whole name if it is less than that many characters,
but if it is longer, will truncate to `namelength - 3`
characters and add an ellipsis.
namelengthsrc
Sets the source reference on Chart Studio Cloud for
`namelength`.
showarrow
Sets whether or not to show the hover label
arrow/triangle pointing to the data point.
Returns
-------
Hoverlabel
"""
super().__init__("hoverlabel")
if "_parent" in kwargs:
self._parent = kwargs["_parent"]
return
if arg is None:
arg = {}
elif isinstance(arg, self.__class__):
arg = arg.to_plotly_json()
elif isinstance(arg, dict):
arg = _copy.copy(arg)
else:
raise ValueError("""\
The first argument to the plotly.graph_objs.cone.Hoverlabel
constructor must be a dict or
an instance of :class:`plotly.graph_objs.cone.Hoverlabel`""")
self._skip_invalid = kwargs.pop("skip_invalid", False)
self._validate = kwargs.pop("_validate", True)
self._set_property("align", arg, align)
self._set_property("alignsrc", arg, alignsrc)
self._set_property("bgcolor", arg, bgcolor)
self._set_property("bgcolorsrc", arg, bgcolorsrc)
self._set_property("bordercolor", arg, bordercolor)
self._set_property("bordercolorsrc", arg, bordercolorsrc)
self._set_property("font", arg, font)
self._set_property("namelength", arg, namelength)
self._set_property("namelengthsrc", arg, namelengthsrc)
self._set_property("showarrow", arg, showarrow)
self._process_kwargs(**dict(arg, **kwargs))
self._skip_invalid = False
|
Hoverlabel
|
python
|
kamyu104__LeetCode-Solutions
|
Python/find-the-original-typed-string-i.py
|
{
"start": 37,
"end": 288
}
|
class ____(object):
def possibleStringCount(self, word):
"""
:type word: str
:rtype: int
"""
return len(word)-sum(word[i] != word[i+1] for i in xrange(len(word)-1))
# Time: O(n)
# Space: O(1)
# array
|
Solution
|
python
|
catalyst-team__catalyst
|
catalyst/callbacks/metrics/accuracy.py
|
{
"start": 190,
"end": 3939
}
|
class ____(BatchMetricCallback):
"""Accuracy metric callback.
Computes multiclass accuracy@topk for the specified values of `topk`.
Args:
input_key: input key to use for metric calculation, specifies our `y_pred`
target_key: output key to use for metric calculation, specifies our `y_true`
topk: specifies which accuracy@K to log
num_classes: number of classes to calculate ``topk`` if ``accuracy_args`` is None
log_on_batch: boolean flag to log computed metrics every batch
prefix: metric prefix
suffix: metric suffix
Examples:
.. code-block:: python
import torch
from torch.utils.data import DataLoader, TensorDataset
from catalyst import dl
# sample data
num_samples, num_features, num_classes = int(1e4), int(1e1), 4
X = torch.rand(num_samples, num_features)
y = (torch.rand(num_samples,) * num_classes).to(torch.int64)
# pytorch loaders
dataset = TensorDataset(X, y)
loader = DataLoader(dataset, batch_size=32, num_workers=1)
loaders = {"train": loader, "valid": loader}
# model, criterion, optimizer, scheduler
model = torch.nn.Linear(num_features, num_classes)
criterion = torch.nn.CrossEntropyLoss()
optimizer = torch.optim.Adam(model.parameters())
scheduler = torch.optim.lr_scheduler.MultiStepLR(optimizer, [2])
# model training
runner = dl.SupervisedRunner(
input_key="features",
output_key="logits",
target_key="targets",
loss_key="loss"
)
runner.train(
model=model,
criterion=criterion,
optimizer=optimizer,
scheduler=scheduler,
loaders=loaders,
logdir="./logdir",
num_epochs=3,
valid_loader="valid",
valid_metric="accuracy03",
minimize_valid_metric=False,
verbose=True,
callbacks=[
dl.AccuracyCallback(
input_key="logits", target_key="targets", num_classes=num_classes
),
dl.PrecisionRecallF1SupportCallback(
input_key="logits", target_key="targets", num_classes=num_classes
),
dl.AUCCallback(input_key="logits", target_key="targets"),
],
)
.. note::
Metric names depending on input parameters:
- ``topk = None`` ---> see \
:py:mod:`catalyst.metrics.functional._misc.get_default_topk`
- ``topk = (1,)`` ---> ``"accuracy01"``
- ``topk = (1, 3)`` ---> ``"accuracy01"``, ``"accuracy03"``
- ``topk = (1, 3, 5)`` ---> ``"accuracy01"``, ``"accuracy03"``, ``"accuracy05"``
You can find them in ``runner.batch_metrics``, ``runner.loader_metrics`` or
``runner.epoch_metrics``.
.. note::
Please follow the `minimal examples`_ sections for more use cases.
.. _`minimal examples`: https://github.com/catalyst-team/catalyst#minimal-examples # noqa: E501, W505
"""
def __init__(
self,
input_key: str,
target_key: str,
topk: Iterable[int] = None,
num_classes: int = None,
log_on_batch: bool = True,
prefix: str = None,
suffix: str = None,
):
"""Init."""
super().__init__(
metric=AccuracyMetric(
topk=topk,
num_classes=num_classes,
prefix=prefix,
suffix=suffix,
),
input_key=input_key,
target_key=target_key,
log_on_batch=log_on_batch,
)
|
AccuracyCallback
|
python
|
huggingface__transformers
|
src/transformers/models/pixtral/modeling_pixtral.py
|
{
"start": 14849,
"end": 18219
}
|
class ____(nn.Module):
def __init__(self, config):
super().__init__()
self.config = config
self.layers = torch.nn.ModuleList()
for _ in range(config.num_hidden_layers):
self.layers.append(PixtralAttentionLayer(config))
self.gradient_checkpointing = False
def forward(
self,
inputs_embeds,
attention_mask: Optional[torch.Tensor] = None,
position_embeddings: Optional[tuple[torch.Tensor, torch.Tensor]] = None,
output_attentions: Optional[bool] = None,
output_hidden_states: Optional[bool] = None,
return_dict: Optional[bool] = None,
**kwargs: Unpack[FlashAttentionKwargs],
) -> Union[tuple, BaseModelOutput]:
r"""
Args:
inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
Embeddings which serve as input to the Transformer.
attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
- 1 for tokens that are **not masked**,
- 0 for tokens that are **masked**.
[What are attention masks?](../glossary#attention-mask)
output_attentions (`bool`, *optional*):
Whether or not to return the attentions tensors of all attention layers. See `attentions` under
returned tensors for more detail.
output_hidden_states (`bool`, *optional*):
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors
for more detail.
return_dict (`bool`, *optional*):
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
"""
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
output_hidden_states = (
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
)
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
encoder_states = () if output_hidden_states else None
all_attentions = () if output_attentions else None
hidden_states = inputs_embeds
for encoder_layer in self.layers:
if output_hidden_states:
encoder_states = encoder_states + (hidden_states,)
layer_outputs = encoder_layer(
hidden_states,
attention_mask,
position_embeddings=position_embeddings,
output_attentions=output_attentions,
**kwargs,
)
hidden_states = layer_outputs[0]
if output_attentions:
all_attentions = all_attentions + (layer_outputs[1],)
if output_hidden_states:
encoder_states = encoder_states + (hidden_states,)
if not return_dict:
return tuple(v for v in [hidden_states, encoder_states, all_attentions] if v is not None)
return BaseModelOutput(
last_hidden_state=hidden_states, hidden_states=encoder_states, attentions=all_attentions
)
@auto_docstring
|
PixtralTransformer
|
python
|
catalyst-team__catalyst
|
examples/detection/models/centernet.py
|
{
"start": 559,
"end": 1053
}
|
class ____(nn.Module):
"""(conv => BN => ReLU) * 2"""
def __init__(self, in_ch, out_ch):
super().__init__()
self.conv = nn.Sequential(
nn.Conv2d(in_ch, out_ch, 3, padding=1),
nn.BatchNorm2d(out_ch),
nn.ReLU(inplace=True),
nn.Conv2d(out_ch, out_ch, 3, padding=1),
nn.BatchNorm2d(out_ch),
nn.ReLU(inplace=True),
)
def forward(self, x):
x = self.conv(x)
return x
|
DoubleConv
|
python
|
langchain-ai__langchain
|
libs/langchain/langchain_classic/agents/output_parsers/react_single_input.py
|
{
"start": 695,
"end": 3341
}
|
class ____(AgentOutputParser):
"""Parses ReAct-style LLM calls that have a single tool input.
Expects output to be in one of two formats.
If the output signals that an action should be taken,
should be in the below format. This will result in an AgentAction
being returned.
```
Thought: agent thought here
Action: search
Action Input: what is the temperature in SF?
```
If the output signals that a final answer should be given,
should be in the below format. This will result in an AgentFinish
being returned.
```
Thought: agent thought here
Final Answer: The temperature is 100 degrees
```
"""
@override
def get_format_instructions(self) -> str:
return FORMAT_INSTRUCTIONS
@override
def parse(self, text: str) -> AgentAction | AgentFinish:
includes_answer = FINAL_ANSWER_ACTION in text
regex = (
r"Action\s*\d*\s*:[\s]*(.*?)[\s]*Action\s*\d*\s*Input\s*\d*\s*:[\s]*(.*)"
)
action_match = re.search(regex, text, re.DOTALL)
if action_match:
if includes_answer:
msg = f"{FINAL_ANSWER_AND_PARSABLE_ACTION_ERROR_MESSAGE}: {text}"
raise OutputParserException(msg)
action = action_match.group(1).strip()
action_input = action_match.group(2)
tool_input = action_input.strip(" ")
tool_input = tool_input.strip('"')
return AgentAction(action, tool_input, text)
if includes_answer:
return AgentFinish(
{"output": text.split(FINAL_ANSWER_ACTION)[-1].strip()},
text,
)
if not re.search(r"Action\s*\d*\s*:[\s]*(.*?)", text, re.DOTALL):
msg = f"Could not parse LLM output: `{text}`"
raise OutputParserException(
msg,
observation=MISSING_ACTION_AFTER_THOUGHT_ERROR_MESSAGE,
llm_output=text,
send_to_llm=True,
)
if not re.search(
r"[\s]*Action\s*\d*\s*Input\s*\d*\s*:[\s]*(.*)",
text,
re.DOTALL,
):
msg = f"Could not parse LLM output: `{text}`"
raise OutputParserException(
msg,
observation=MISSING_ACTION_INPUT_AFTER_ACTION_ERROR_MESSAGE,
llm_output=text,
send_to_llm=True,
)
msg = f"Could not parse LLM output: `{text}`"
raise OutputParserException(msg)
@property
def _type(self) -> str:
return "react-single-input"
|
ReActSingleInputOutputParser
|
python
|
coleifer__peewee
|
tests/reflection.py
|
{
"start": 1428,
"end": 1553
}
|
class ____(TestModel):
category_id = ForeignKeyField(Category, column_name='category_id')
category = CharField()
|
Nugget
|
python
|
hyperopt__hyperopt
|
hyperopt/tests/integration/test_mongoexp.py
|
{
"start": 4319,
"end": 7957
}
|
class ____(hyperopt.tests.test_base.TestTrials):
def setUp(self):
self.temp_mongo = TempMongo()
self.temp_mongo.__enter__()
self.trials = MongoTrials(
self.temp_mongo.connection_string("foo"), exp_key=None
)
def tearDown(self, *args):
self.temp_mongo.__exit__(*args)
def with_mongo_trials(f, exp_key=None):
def wrapper():
with TempMongo() as temp_mongo:
trials = MongoTrials(temp_mongo.connection_string("foo"), exp_key=exp_key)
print("Length of trials: ", len(trials.results))
f(trials)
wrapper.__name__ = f.__name__
return wrapper
def _worker_thread_fn(host_id, n_jobs, timeout, dbname="foo", logfilename=None):
mw = MongoWorker(
mj=TempMongo.mongo_jobs(dbname),
logfilename=logfilename,
workdir="mongoexp_test_dir",
)
try:
while n_jobs:
mw.run_one(host_id, timeout, erase_created_workdir=True)
print("worker: %s ran job" % str(host_id))
n_jobs -= 1
except ReserveTimeout:
print("worker timed out:", host_id)
pass
def with_worker_threads(n_threads, dbname="foo", n_jobs=sys.maxsize, timeout=10.0):
"""
Decorator that will run a test with some MongoWorker threads in flight
"""
def newth(ii):
return threading.Thread(
target=_worker_thread_fn, args=(("hostname", ii), n_jobs, timeout, dbname)
)
def deco(f):
def wrapper(*args, **kwargs):
# --start some threads
threads = list(map(newth, list(range(n_threads))))
[th.start() for th in threads]
try:
return f(*args, **kwargs)
finally:
[th.join() for th in threads]
wrapper.__name__ = f.__name__
return wrapper
return deco
@with_mongo_trials
def test_with_temp_mongo(trials):
pass # -- just verify that the decorator can run
@with_mongo_trials
def test_new_trial_ids(trials):
a = trials.new_trial_ids(1)
b = trials.new_trial_ids(2)
c = trials.new_trial_ids(3)
assert len(a) == 1
assert len(b) == 2
assert len(c) == 3
s = set()
s.update(a)
s.update(b)
s.update(c)
assert len(s) == 6
@with_mongo_trials
def test_attachments(trials):
blob = b"abcde"
assert "aname" not in trials.attachments
trials.attachments["aname"] = blob
assert "aname" in trials.attachments
assert trials.attachments["aname"] == blob
assert trials.attachments["aname"] == blob
blob2 = b"zzz"
trials.attachments["aname"] = blob2
assert "aname" in trials.attachments
assert trials.attachments["aname"] == blob2
assert trials.attachments["aname"] == blob2
del trials.attachments["aname"]
assert "aname" not in trials.attachments
@with_mongo_trials
def test_delete_all_on_attachments(trials):
trials.attachments["aname"] = "a"
trials.attachments["aname2"] = "b"
assert "aname2" in trials.attachments
trials.delete_all()
assert "aname" not in trials.attachments
assert "aname2" not in trials.attachments
def test_handles_are_independent():
with TempMongo() as tm:
t1 = tm.mongo_jobs("t1")
t2 = tm.mongo_jobs("t2")
assert len(t1) == 0
assert len(t2) == 0
# test that inserting into t1 doesn't affect t2
t1.insert({"a": 7})
assert len(t1) == 1
assert len(t2) == 0
def passthrough(x):
assert os.path.split(os.getcwd()).count("mongoexp_test_dir") == 1, (
"cwd is %s" % os.getcwd()
)
return x
|
TestMongoTrials
|
python
|
bokeh__bokeh
|
tests/unit/bokeh/server/test_auth_provider.py
|
{
"start": 2508,
"end": 3259
}
|
class ____:
def test_no_endpoints(self) -> None:
def func(filename: str):
am = bsa.AuthModule(filename)
assert am.endpoints == []
with_file_contents("""
def get_user(): pass
def get_login_url(): pass
""", func, suffix='.py')
with_file_contents("""
def get_user(): pass
login_url = "/foo"
""", func, suffix='.py')
def test_login_url_endpoint(self) -> None:
def func(filename: str):
am = bsa.AuthModule(filename)
assert am.endpoints[0][0] == '/foo'
assert issubclass(am.endpoints[0][1], RequestHandler)
with_file_contents("""
from tornado.web import RequestHandler
def get_user(): pass
login_url = "/foo"
|
TestAuthModule_properties
|
python
|
doocs__leetcode
|
solution/3200-3299/3208.Alternating Groups II/Solution.py
|
{
"start": 0,
"end": 353
}
|
class ____:
def numberOfAlternatingGroups(self, colors: List[int], k: int) -> int:
n = len(colors)
ans = cnt = 0
for i in range(n << 1):
if i and colors[i % n] == colors[(i - 1) % n]:
cnt = 1
else:
cnt += 1
ans += i >= n and cnt >= k
return ans
|
Solution
|
python
|
wandb__wandb
|
tests/system_tests/test_functional/dspy/dspy_callback_unexpected.py
|
{
"start": 27,
"end": 997
}
|
class ____(dspy.Module):
def __init__(self) -> None:
super().__init__()
self.predict = dspy.Predict("question: str -> answer: str")
def main() -> None:
from wandb.integration.dspy import WandbDSPyCallback
with wandb.init(project="dspy-system-test-unexpected") as run:
cb = WandbDSPyCallback(log_results=True, run=run)
class FakeEvaluate:
def __init__(self) -> None:
self.devset = []
self.num_threads = 1
self.auto = "light"
program = MinimalProgram()
cb.on_evaluate_start(
call_id="c1", instance=FakeEvaluate(), inputs={"program": program}
)
# Pass an unexpected outputs type (not EvaluationResult)
class NotAnEvaluationResult:
pass
cb.on_evaluate_end(
call_id="c1", outputs=NotAnEvaluationResult(), exception=None
)
if __name__ == "__main__":
main()
|
MinimalProgram
|
python
|
cherrypy__cherrypy
|
cherrypy/tutorial/tut05_derived_objects.py
|
{
"start": 102,
"end": 343
}
|
class ____ wish. In most real-world applications, you will probably
want to create a central base class used for all your pages, which takes
care of things like printing a common page header and footer.
"""
import os.path
import cherrypy
|
you
|
python
|
apache__avro
|
lang/py/avro/tool.py
|
{
"start": 1770,
"end": 5888
}
|
class ____(http.server.BaseHTTPRequestHandler):
def do_POST(self) -> None:
self.responder = responder
call_request_reader = avro.ipc.FramedReader(self.rfile)
call_request = call_request_reader.read_framed_message()
resp_body = self.responder.respond(call_request)
self.send_response(200)
self.send_header("Content-Type", "avro/binary")
self.end_headers()
resp_writer = avro.ipc.FramedWriter(self.wfile)
resp_writer.write_framed_message(resp_body)
if server_should_shutdown:
print("Shutting down server.", file=sys.stderr)
quitter = threading.Thread(target=self.server.shutdown)
quitter.daemon = True
quitter.start()
def run_server(uri: str, proto: str, msg: str, datum: object) -> None:
global responder
global server_should_shutdown
url_obj = urllib.parse.urlparse(uri)
if url_obj.hostname is None:
raise RuntimeError(f"uri {uri} must have a hostname.")
if url_obj.port is None:
raise RuntimeError(f"uri {uri} must have a port.")
server_addr = (url_obj.hostname, url_obj.port)
server_should_shutdown = False
responder = GenericResponder(proto, msg, datum)
server = http.server.HTTPServer(server_addr, GenericHandler)
print(f"Port: {server.server_port}")
sys.stdout.flush()
server.allow_reuse_address = True
print("Starting server.", file=sys.stderr)
server.serve_forever()
def send_message(uri, proto, msg, datum) -> None:
url_obj = urllib.parse.urlparse(uri)
client = avro.ipc.HTTPTransceiver(url_obj.hostname, url_obj.port)
requestor = avro.ipc.Requestor(avro.protocol.parse(Path(proto).read_text()), client)
print(requestor.request(msg, datum))
def _parse_args() -> argparse.Namespace:
"""Parse the command-line arguments"""
parser = argparse.ArgumentParser()
subparsers = parser.add_subparsers(required=True, dest="command") if sys.version_info >= (3, 7) else parser.add_subparsers(dest="command")
subparser_dump = subparsers.add_parser("dump", help="Dump an avro file")
subparser_dump.add_argument("input_file", type=argparse.FileType("rb"))
subparser_rpcreceive = subparsers.add_parser("rpcreceive", help="receive a message")
subparser_rpcreceive.add_argument("uri")
subparser_rpcreceive.add_argument("proto")
subparser_rpcreceive.add_argument("msg")
subparser_rpcreceive.add_argument("-file", type=argparse.FileType("rb"), required=False)
subparser_rpcsend = subparsers.add_parser("rpcsend", help="send a message")
subparser_rpcsend.add_argument("uri")
subparser_rpcsend.add_argument("proto")
subparser_rpcsend.add_argument("msg")
subparser_rpcsend.add_argument("-file", type=argparse.FileType("rb"))
return parser.parse_args()
def main_dump(args: argparse.Namespace) -> int:
print("\n".join(f"{d!r}" for d in avro.datafile.DataFileReader(args.input_file, avro.io.DatumReader())))
return 0
def main_rpcreceive(args: argparse.Namespace) -> int:
datum = None
if args.file:
with avro.datafile.DataFileReader(args.file, avro.io.DatumReader()) as dfr:
datum = next(dfr)
run_server(args.uri, args.proto, args.msg, datum)
return 0
def main_rpcsend(args: argparse.Namespace) -> int:
datum = None
if args.file:
with avro.datafile.DataFileReader(args.file, avro.io.DatumReader()) as dfr:
datum = next(dfr)
send_message(args.uri, args.proto, args.msg, datum)
return 0
def main() -> int:
args = _parse_args()
if args.command == "dump":
return main_dump(args)
if args.command == "rpcreceive":
return main_rpcreceive(args)
if args.command == "rpcsend":
return main_rpcsend(args)
return 1
if __name__ == "__main__":
if os.path.dirname(avro.io.__file__) in sys.path:
warnings.warn(
"Invoking avro/tool.py directly is likely to lead to a name collision "
"with the python io module. Try doing `python -m avro.tool` instead."
)
sys.exit(main())
|
GenericHandler
|
python
|
apache__airflow
|
airflow-ctl/src/airflowctl/api/datamodels/generated.py
|
{
"start": 52872,
"end": 53153
}
|
class ____(BaseModel):
"""
Backfill collection serializer for responses in dry-run mode.
"""
backfills: Annotated[list[DryRunBackfillResponse], Field(title="Backfills")]
total_entries: Annotated[int, Field(title="Total Entries")]
|
DryRunBackfillCollectionResponse
|
python
|
modin-project__modin
|
modin/core/dataframe/algebra/groupby.py
|
{
"start": 1327,
"end": 33074
}
|
class ____(TreeReduce):
"""
Builder class for GroupBy aggregation functions.
Attributes
----------
ID_LEVEL_NAME : str
It's supposed that implementations may produce multiple temporary
columns per one source column in an intermediate phase. In order
for these columns to be processed accordingly at the Reduce phase,
an implementation must store unique names for such temporary
columns in the ``ID_LEVEL_NAME`` level. Duplicated names are not allowed.
_GROUPBY_REDUCE_IMPL_FLAG : str
Attribute indicating that a callable should be treated as an
implementation for one of the TreeReduce phases rather than an
arbitrary aggregation. Note: this attribute should be considered private.
"""
ID_LEVEL_NAME: str = "__ID_LEVEL_NAME__"
_GROUPBY_REDUCE_IMPL_FLAG: str = "__groupby_reduce_impl_func__"
@classmethod
def register(
cls,
map_func: Union[str, dict, Callable[..., pandas.DataFrame]],
reduce_func: Optional[Union[str, dict, Callable[..., pandas.DataFrame]]] = None,
**call_kwds: dict,
) -> Callable[..., PandasQueryCompiler]:
"""
Build template GroupBy aggregation function.
Resulted function is applied in parallel via TreeReduce algorithm.
Parameters
----------
map_func : str, dict or callable(pandas.core.groupby.DataFrameGroupBy) -> pandas.DataFrame
Function to apply to the `GroupByObject` at the map phase. If ``str`` was passed it will
be treated as a DataFrameGroupBy's method name.
reduce_func : str, dict or callable(pandas.core.groupby.DataFrameGroupBy) -> pandas.DataFrame, optional
Function to apply to the ``DataFrameGroupBy`` at the reduce phase. If not specified
will be set the same as 'map_func'.
**call_kwds : dict
Kwargs that will be passed to the returned function.
Returns
-------
callable
Function that takes query compiler and executes GroupBy aggregation
with TreeReduce algorithm.
"""
if reduce_func is None:
reduce_func = map_func
def build_fn(name):
return lambda df, *args, **kwargs: getattr(df, name)(*args, **kwargs)
if isinstance(map_func, str):
map_func = build_fn(map_func)
if isinstance(reduce_func, str):
reduce_func = build_fn(reduce_func)
assert not (
isinstance(map_func, dict) ^ isinstance(reduce_func, dict)
) and not (
callable(map_func) ^ callable(reduce_func)
), "Map and reduce functions must be either both dict or both callable."
return lambda *args, **kwargs: cls.caller(
*args, map_func=map_func, reduce_func=reduce_func, **kwargs, **call_kwds
)
@classmethod
def register_implementation(
cls,
map_func: Callable[..., pandas.DataFrame],
reduce_func: Callable[..., pandas.DataFrame],
) -> None:
"""
Register callables to be recognized as an implementations of tree-reduce phases.
Parameters
----------
map_func : callable(pandas.core.groupby.DataFrameGroupBy) -> pandas.DataFrame
Callable to register.
reduce_func : callable(pandas.core.groupby.DataFrameGroupBy) -> pandas.DataFrame
Callable to register.
"""
setattr(map_func, cls._GROUPBY_REDUCE_IMPL_FLAG, True)
setattr(reduce_func, cls._GROUPBY_REDUCE_IMPL_FLAG, True)
@classmethod
def map(
cls,
df: pandas.DataFrame,
map_func: Callable[..., pandas.DataFrame],
axis: int,
groupby_kwargs: dict,
agg_args: list,
agg_kwargs: dict,
other: Optional[pandas.DataFrame] = None,
by=None,
drop: bool = False,
) -> pandas.DataFrame:
"""
Execute Map phase of GroupByReduce.
Groups DataFrame and applies map function. Groups will be
preserved in the results index for the following reduce phase.
Parameters
----------
df : pandas.DataFrame
Serialized frame to group.
map_func : dict or callable(pandas.DataFrameGroupBy) -> pandas.DataFrame
Function to apply to the `GroupByObject`.
axis : {0, 1}
Axis to group and apply aggregation function along. 0 means index axis
when 1 means column axis.
groupby_kwargs : dict
Dictionary which carries arguments for `pandas.DataFrame.groupby`.
agg_args : list-like
Positional arguments to pass to the aggregation functions.
agg_kwargs : dict
Keyword arguments to pass to the aggregation functions.
other : pandas.DataFrame, optional
Serialized frame, whose columns are used to determine the groups.
If not specified, `by` parameter is used.
by : level index name or list of such labels, optional
Index levels, that is used to determine groups.
If not specified, `other` parameter is used.
drop : bool, default: False
Indicates whether or not by-data came from the `self` frame.
Returns
-------
pandas.DataFrame
GroupBy aggregation result for one particular partition.
"""
# Set `as_index` to True to track the metadata of the grouping object
# It is used to make sure that between phases we are constructing the
# right index and placing columns in the correct order.
groupby_kwargs["as_index"] = True
groupby_kwargs["observed"] = True
# We have to filter func-dict BEFORE inserting broadcasted 'by' columns
# to avoid multiple aggregation results for 'by' cols in case they're
# present in the func-dict:
apply_func = cls.get_callable(
map_func,
df,
# We won't be able to preserve the order as the Map phase would likely
# produce some temporary columns that won't fit into the original
# aggregation order. It doesn't matter much as we restore the original
# order at the Reduce phase.
preserve_aggregation_order=False,
)
if other is not None:
# Other is a broadcasted partition that represents 'by' data to group on.
# If 'drop' then the 'by' data came from the 'self' frame, thus
# inserting missed columns to the partition to group on them.
if drop or isinstance(
other := other.squeeze(axis=axis ^ 1), pandas.DataFrame
):
df = pandas.concat(
[df] + [other[[o for o in other if o not in df]]],
axis=1,
)
other = list(other.columns)
by_part = other
else:
by_part = by
result = apply_func(
df.groupby(by=by_part, axis=axis, **groupby_kwargs), *agg_args, **agg_kwargs
)
# Result could not always be a frame, so wrapping it into DataFrame
return pandas.DataFrame(result)
@classmethod
def reduce(
cls,
df: pandas.DataFrame,
reduce_func: Union[dict, Callable[..., pandas.DataFrame]],
axis: int,
groupby_kwargs: dict,
agg_args: list,
agg_kwargs: dict,
partition_idx: int = 0,
drop: bool = False,
method: Optional[str] = None,
finalizer_fn: Optional[Callable[[pandas.DataFrame], pandas.DataFrame]] = None,
) -> pandas.DataFrame:
"""
Execute Reduce phase of GroupByReduce.
Combines groups from the Map phase and applies reduce function.
Parameters
----------
df : pandas.DataFrame
Serialized frame which contain groups to combine.
reduce_func : dict or callable(pandas.DataFrameGroupBy) -> pandas.DataFrame
Function to apply to the `GroupByObject`.
axis : {0, 1}
Axis to group and apply aggregation function along. 0 means index axis
when 1 means column axis.
groupby_kwargs : dict
Dictionary which carries arguments for `pandas.DataFrame.groupby`.
agg_args : list-like
Positional arguments to pass to the aggregation functions.
agg_kwargs : dict
Keyword arguments to pass to the aggregation functions.
partition_idx : int, default: 0
Internal index of column partition to which this function is applied.
drop : bool, default: False
Indicates whether or not by-data came from the `self` frame.
method : str, optional
Name of the groupby function. This is a hint to be able to do special casing.
finalizer_fn : callable(pandas.DataFrame) -> pandas.DataFrame, optional
A callable to execute at the end a groupby kernel against groupby result.
Returns
-------
pandas.DataFrame
GroupBy aggregation result.
"""
# Wrapping names into an Index should be unnecessary, however
# there is a bug in pandas with intersection that forces us to do so:
# https://github.com/pandas-dev/pandas/issues/39699
by_part = pandas.Index(df.index.names)
groupby_kwargs = groupby_kwargs.copy()
as_index = groupby_kwargs.get("as_index", True)
# Set `as_index` to True to track the metadata of the grouping object
groupby_kwargs["as_index"] = True
# since now index levels contain out 'by', in the reduce phace
# we want to group on these levels
groupby_kwargs["level"] = list(range(len(df.index.names)))
apply_func = cls.get_callable(reduce_func, df)
result = apply_func(
df.groupby(axis=axis, **groupby_kwargs), *agg_args, **agg_kwargs
)
if not as_index:
idx = df.index
GroupBy.handle_as_index_for_dataframe(
result,
by_part,
by_cols_dtypes=(
idx.dtypes.values
if isinstance(idx, pandas.MultiIndex) and hasattr(idx, "dtypes")
else (idx.dtype,)
),
by_length=len(by_part),
selection=reduce_func.keys() if isinstance(reduce_func, dict) else None,
partition_idx=partition_idx,
drop=drop,
method=method,
inplace=True,
)
# Result could not always be a frame, so wrapping it into DataFrame
result = pandas.DataFrame(result)
if result.index.name == MODIN_UNNAMED_SERIES_LABEL:
result.index.name = None
return result if finalizer_fn is None else finalizer_fn(result)
@classmethod
def caller(
cls,
query_compiler: PandasQueryCompiler,
by,
map_func: Union[dict, Callable[..., pandas.DataFrame]],
reduce_func: Union[dict, Callable[..., pandas.DataFrame]],
axis: int,
groupby_kwargs: dict,
agg_args: list,
agg_kwargs: dict,
drop: bool = False,
method: Optional[str] = None,
default_to_pandas_func: Optional[Callable[..., pandas.DataFrame]] = None,
finalizer_fn: Optional[Callable[[pandas.DataFrame], pandas.DataFrame]] = None,
) -> PandasQueryCompiler:
"""
Execute GroupBy aggregation with TreeReduce approach.
Parameters
----------
query_compiler : PandasQueryCompiler
Frame to group.
by : PandasQueryCompiler, column or index label, Grouper or list of such
Object that determine groups.
map_func : dict or callable(pandas.DataFrameGroupBy) -> pandas.DataFrame
Function to apply to the `GroupByObject` at the Map phase.
reduce_func : dict or callable(pandas.DataFrameGroupBy) -> pandas.DataFrame
Function to apply to the `GroupByObject` at the Reduce phase.
axis : {0, 1}
Axis to group and apply aggregation function along. 0 means index axis
when 1 means column axis.
groupby_kwargs : dict
Dictionary which carries arguments for pandas.DataFrame.groupby.
agg_args : list-like
Positional arguments to pass to the aggregation functions.
agg_kwargs : dict
Keyword arguments to pass to the aggregation functions.
drop : bool, default: False
Indicates whether or not by-data came from the `self` frame.
method : str, optional
Name of the GroupBy aggregation function. This is a hint to be able to do special casing.
default_to_pandas_func : callable(pandas.DataFrameGroupBy) -> pandas.DataFrame, optional
The pandas aggregation function equivalent to the `map_func + reduce_func`.
Used in case of defaulting to pandas. If not specified `map_func` is used.
finalizer_fn : callable(pandas.DataFrame) -> pandas.DataFrame, optional
A callable to execute at the end a groupby kernel against groupby result.
Returns
-------
PandasQueryCompiler
QueryCompiler which carries the result of GroupBy aggregation.
"""
is_unsupported_axis = axis != 0
# Defaulting to pandas in case of an empty frame as we can't process it properly.
# Higher API level won't pass empty data here unless the frame has delayed
# computations. So we apparently lose some laziness here (due to index access)
# because of the inability to process empty groupby natively.
is_empty_data = (
len(query_compiler.columns) == 0 or len(query_compiler.index) == 0
)
is_grouping_using_by_arg = (
groupby_kwargs.get("level", None) is None and by is not None
)
is_unsupported_by_arg = isinstance(by, pandas.Grouper) or (
not hashable(by) and not isinstance(by, type(query_compiler))
)
if (
is_unsupported_axis
or is_empty_data
or (is_grouping_using_by_arg and is_unsupported_by_arg)
):
if default_to_pandas_func is None:
default_to_pandas_func = (
(lambda grp: grp.agg(map_func))
if isinstance(map_func, dict)
else map_func
)
default_to_pandas_func = GroupByDefault.register(default_to_pandas_func)
return default_to_pandas_func(
query_compiler,
by=by,
axis=axis,
groupby_kwargs=groupby_kwargs,
agg_args=agg_args,
agg_kwargs=agg_kwargs,
drop=drop,
)
# The bug only occurs in the case of Categorical 'by', so we might want to check whether any of
# the 'by' dtypes is Categorical before going into this branch, however triggering 'dtypes'
# computation if they're not computed may take time, so we don't do it
if not groupby_kwargs.get("sort", True) and isinstance(
by, type(query_compiler)
):
ErrorMessage.mismatch_with_pandas(
operation="df.groupby(categorical_by, sort=False)",
message=(
"the groupby keys will be sorted anyway, although the 'sort=False' was passed. "
+ "See the following issue for more details: "
+ "https://github.com/modin-project/modin/issues/3571"
),
)
groupby_kwargs = groupby_kwargs.copy()
groupby_kwargs["sort"] = True
map_fn, reduce_fn = cls.build_map_reduce_functions(
by=by,
axis=axis,
groupby_kwargs=groupby_kwargs,
map_func=map_func,
reduce_func=reduce_func,
agg_args=agg_args,
agg_kwargs=agg_kwargs,
drop=drop,
method=method,
finalizer_fn=finalizer_fn,
)
# If `by` is a ModinFrame, then its partitions will be broadcasted to every
# `self` partition in a way determined by engine (modin_frame.groupby_reduce)
# Otherwise `by` was already bound to the Map function in `build_map_reduce_functions`.
broadcastable_by = getattr(by, "_modin_frame", None)
apply_indices = list(map_func.keys()) if isinstance(map_func, dict) else None
if (
broadcastable_by is not None
and groupby_kwargs.get("as_index", True)
and broadcastable_by.has_materialized_dtypes
):
new_index = ModinIndex(
# actual value will be assigned on a parent update
value=None,
axis=0,
dtypes=broadcastable_by.dtypes,
)
else:
new_index = None
new_modin_frame = query_compiler._modin_frame.groupby_reduce(
axis,
broadcastable_by,
map_fn,
reduce_fn,
apply_indices=apply_indices,
new_index=new_index,
)
result = query_compiler.__constructor__(new_modin_frame)
return result
@classmethod
def get_callable(
cls,
agg_func: Union[dict, Callable[..., pandas.DataFrame]],
df: pandas.DataFrame,
preserve_aggregation_order: bool = True,
) -> Callable[..., pandas.DataFrame]:
"""
Build aggregation function to apply to each group at this particular partition.
If it's dictionary aggregation — filters aggregation dictionary for keys which
this particular partition contains, otherwise do nothing with passed function.
Parameters
----------
agg_func : dict or callable(pandas.DataFrameGroupBy) -> pandas.DataFrame
Aggregation function.
df : pandas.DataFrame
Serialized partition which contains available columns.
preserve_aggregation_order : bool, default: True
Whether to manually restore the order of columns for the result specified
by the `agg_func` keys (only makes sense when `agg_func` is a dictionary).
Returns
-------
callable(pandas.core.groupby.DataFrameGroupBy) -> pandas.DataFrame
Aggregation function that can be safely applied to this particular partition.
"""
if not isinstance(agg_func, dict):
return agg_func
grp_has_id_level = df.columns.names[0] == cls.ID_LEVEL_NAME
# The 'id' level prevents us from a lookup for the original
# partition's columns. So dropping the level.
partition_columns = frozenset(
df.columns.droplevel(0) if grp_has_id_level else df.columns
)
partition_dict = {k: v for k, v in agg_func.items() if k in partition_columns}
return cls._build_callable_for_dict(
partition_dict, preserve_aggregation_order, grp_has_id_level
)
@classmethod
def _build_callable_for_dict(
cls,
agg_dict: dict,
preserve_aggregation_order: bool = True,
grp_has_id_level: bool = False,
) -> Callable[..., pandas.DataFrame]:
"""
Build callable for an aggregation dictionary.
Parameters
----------
agg_dict : dict
Aggregation dictionary.
preserve_aggregation_order : bool, default: True
Whether to manually restore the order of columns for the result specified
by the `agg_func` keys (only makes sense when `agg_func` is a dictionary).
grp_has_id_level : bool, default: False
Whether the frame we're grouping on has intermediate columns
(see ``cls.ID_LEVEL_NAME``).
Returns
-------
callable(pandas.core.groupby.DataFrameGroupBy) -> pandas.DataFrame
"""
# We have to keep this import away from the module level to avoid circular import
from modin.pandas.utils import walk_aggregation_dict
# We now filter aggregation functions into those that could be applied natively
# using pandas (pandas_grp_obj.agg(**native_aggs)) and those that require
# special treatment (custom_aggs).
custom_aggs = {}
native_aggs = {}
result_columns = []
for col, func, func_name, col_renaming_required in walk_aggregation_dict(
agg_dict
):
# Filter dictionary
dict_to_add = (
custom_aggs if cls.is_registered_implementation(func) else native_aggs
)
new_value = func if func_name is None else (func_name, func)
old_value = dict_to_add.get(col, None)
if old_value is not None:
ErrorMessage.catch_bugs_and_request_email(
failure_condition=not isinstance(old_value, list),
extra_log="Expected for all aggregation values to be a list when at least "
+ f"one column has multiple aggregations. Got: {old_value} {type(old_value)}",
)
old_value.append(new_value)
else:
# Pandas knows that it has to modify the resulting columns if it meets
# a function wrapped into a list. Renaming is required if either a new
# column name was explicitly specified, or multiple functions were
# specified per one column, or if any other column in the aggregation
# is going to be renamed.
dict_to_add[col] = [new_value] if col_renaming_required else new_value
# Construct resulting columns
if col_renaming_required:
func_name = str(func) if func_name is None else func_name
result_columns.append(
(*(col if isinstance(col, tuple) else (col,)), func_name)
)
else:
result_columns.append(col)
result_columns = pandas.Index(result_columns)
def aggregate_on_dict(grp_obj, *args, **kwargs):
"""Aggregate the passed groupby object."""
if len(native_aggs) == 0:
native_agg_res = None
elif grp_has_id_level:
# Adding the 'id' level to the aggregation keys so they match `grp_obj` columns
native_aggs_modified = {
(
cls.ID_LEVEL_NAME,
*(key if isinstance(key, tuple) else (key,)),
): value
for key, value in native_aggs.items()
}
native_agg_res = grp_obj.agg(native_aggs_modified)
# Dropping the 'id' level from the resulted frame
native_agg_res.columns = native_agg_res.columns.droplevel(0)
else:
native_agg_res = grp_obj.agg(native_aggs)
custom_results = []
insert_id_levels = False
for col, func, func_name, col_renaming_required in walk_aggregation_dict(
custom_aggs
):
if grp_has_id_level:
cols_without_ids = grp_obj.obj.columns.droplevel(0)
if isinstance(cols_without_ids, pandas.MultiIndex):
# We may have multiple columns matching the `col` in
# a MultiIndex case, that's why use `.get_locs` here
col_pos = cols_without_ids.get_locs(col)
else:
# `pandas.Index` doesn't have `.get_locs` method
col_pos = cols_without_ids.get_loc(col)
agg_key = grp_obj.obj.columns[col_pos]
else:
agg_key = [col]
result = func(grp_obj[agg_key])
# The `func` may have discarded an ID-level if there were any.
# So checking for this again.
result_has_id_level = result.columns.names[0] == cls.ID_LEVEL_NAME
insert_id_levels |= result_has_id_level
if col_renaming_required:
func_name = str(func) if func_name is None else func_name
if result_has_id_level:
result.columns = pandas.MultiIndex.from_tuples(
[
# `old_col[0]` stores values from the 'id'
# level, the ones we want to preserve here
(old_col[0], col, func_name)
for old_col in result.columns
],
names=[
result.columns.names[0],
result.columns.names[1],
None,
],
)
else:
result.columns = pandas.MultiIndex.from_tuples(
[(col, func_name)] * len(result.columns),
names=[result.columns.names[0], None],
)
custom_results.append(result)
if insert_id_levels:
# As long as any `result` has an id-level we have to insert the level
# into every `result` so the number of levels matches
for idx, ext_result in enumerate(custom_results):
if ext_result.columns.names[0] != cls.ID_LEVEL_NAME:
custom_results[idx] = pandas.concat(
[ext_result],
keys=[cls.ID_LEVEL_NAME],
names=[cls.ID_LEVEL_NAME],
axis=1,
copy=False,
)
if native_agg_res is not None:
native_agg_res = pandas.concat(
[native_agg_res],
keys=[cls.ID_LEVEL_NAME],
names=[cls.ID_LEVEL_NAME],
axis=1,
copy=False,
)
native_res_part = [] if native_agg_res is None else [native_agg_res]
parts = [*native_res_part, *custom_results]
if parts:
result = pandas.concat(parts, axis=1, copy=False)
else:
result = pandas.DataFrame(columns=result_columns)
# The order is naturally preserved if there's no custom aggregations
if preserve_aggregation_order and len(custom_aggs):
result = result.reindex(result_columns, axis=1)
return result
return aggregate_on_dict
@classmethod
def is_registered_implementation(cls, func: Callable) -> bool:
"""
Check whether the passed `func` was registered as a TreeReduce implementation.
Parameters
----------
func : callable
Returns
-------
bool
"""
return callable(func) and hasattr(func, cls._GROUPBY_REDUCE_IMPL_FLAG)
@classmethod
def build_map_reduce_functions(
cls,
by,
axis: int,
groupby_kwargs: dict,
map_func: Union[dict, Callable[..., pandas.DataFrame]],
reduce_func: Union[dict, Callable[..., pandas.DataFrame]],
agg_args: list,
agg_kwargs: dict,
drop: bool = False,
method: Optional[str] = None,
finalizer_fn: Callable[[pandas.DataFrame], pandas.DataFrame] = None,
) -> tuple[Callable, Callable]:
"""
Bind appropriate arguments to map and reduce functions.
Parameters
----------
by : BaseQueryCompiler, column or index label, Grouper or list of such
Object that determine groups.
axis : {0, 1}
Axis to group and apply aggregation function along. 0 means index axis
when 1 means column axis.
groupby_kwargs : dict
Dictionary which carries arguments for pandas.DataFrame.groupby.
map_func : dict or callable(pandas.DataFrameGroupBy) -> pandas.DataFrame
Function to apply to the `GroupByObject` at the Map phase.
reduce_func : dict or callable(pandas.DataFrameGroupBy) -> pandas.DataFrame
Function to apply to the `GroupByObject` at the Reduce phase.
agg_args : list-like
Positional arguments to pass to the aggregation functions.
agg_kwargs : dict
Keyword arguments to pass to the aggregation functions.
drop : bool, default: False
Indicates whether or not by-data came from the `self` frame.
method : str, optional
Name of the GroupBy aggregation function. This is a hint to be able to do special casing.
finalizer_fn : callable(pandas.DataFrame) -> pandas.DataFrame, optional
A callable to execute at the end a groupby kernel against groupby result.
Returns
-------
Tuple of callable
Tuple of map and reduce functions with bound arguments.
"""
# if by is a query compiler, then it will be broadcasted explicit via
# groupby_reduce method of the modin frame and so we don't want secondary
# implicit broadcastion via passing it as an function argument.
if hasattr(by, "_modin_frame"):
by = None
def _map(
df: pandas.DataFrame,
other: Optional[pandas.DataFrame] = None,
**kwargs: dict,
) -> pandas.DataFrame:
def wrapper(
df: pandas.DataFrame, other: Optional[pandas.DataFrame] = None
) -> pandas.DataFrame:
return cls.map(
df,
other=other,
axis=axis,
by=by,
groupby_kwargs=groupby_kwargs.copy(),
map_func=map_func,
agg_args=agg_args,
agg_kwargs=agg_kwargs,
drop=drop,
**kwargs,
)
try:
result = wrapper(df, other)
# This will happen with Arrow buffer read-only errors. We don't want to copy
# all the time, so this will try to fast-path the code first.
except ValueError:
result = wrapper(df.copy(), other if other is None else other.copy())
return result
def _reduce(df: pandas.DataFrame, **call_kwargs: dict) -> pandas.DataFrame:
def wrapper(df: pandas.DataFrame):
return cls.reduce(
df,
axis=axis,
groupby_kwargs=groupby_kwargs,
reduce_func=reduce_func,
agg_args=agg_args,
agg_kwargs=agg_kwargs,
drop=drop,
method=method,
finalizer_fn=finalizer_fn,
**call_kwargs,
)
try:
result = wrapper(df)
# This will happen with Arrow buffer read-only errors. We don't want to copy
# all the time, so this will try to fast-path the code first.
except ValueError:
result = wrapper(df.copy())
return result
return _map, _reduce
|
GroupByReduce
|
python
|
dagster-io__dagster
|
python_modules/libraries/dagster-airbyte/dagster_airbyte/managed/generated/sources.py
|
{
"start": 77905,
"end": 79140
}
|
class ____(GeneratedAirbyteSource):
@public
def __init__(
self,
name: str,
domain: str,
client_id: str,
client_secret: str,
run_look_ids: Optional[list[str]] = None,
):
"""Airbyte Source for Looker.
Documentation can be found at https://docs.airbyte.com/integrations/sources/looker
Args:
name (str): The name of the destination.
domain (str): Domain for your Looker account, e.g. airbyte.cloud.looker.com,looker.[clientname].com,IP address
client_id (str): The Client ID is first part of an API3 key that is specific to each Looker user. See the docs for more information on how to generate this key.
client_secret (str): The Client Secret is second part of an API3 key.
run_look_ids (Optional[List[str]]): The IDs of any Looks to run
"""
self.domain = check.str_param(domain, "domain")
self.client_id = check.str_param(client_id, "client_id")
self.client_secret = check.str_param(client_secret, "client_secret")
self.run_look_ids = check.opt_nullable_list_param(run_look_ids, "run_look_ids", str)
super().__init__("Looker", name)
|
LookerSource
|
python
|
joblib__joblib
|
joblib/memory.py
|
{
"start": 10855,
"end": 33811
}
|
class ____(Logger):
"""Callable object decorating a function for caching its return value
each time it is called.
Methods are provided to inspect the cache or clean it.
Attributes
----------
func: callable
The original, undecorated, function.
location: string
The location of joblib cache. Depends on the store backend used.
backend: str
Type of store backend for reading/writing cache files.
Default is 'local', in which case the location is the path to a
disk storage.
ignore: list or None
List of variable names to ignore when choosing whether to
recompute.
mmap_mode: {None, 'r+', 'r', 'w+', 'c'}
The memmapping mode used when loading from cache
numpy arrays. See numpy.load for the meaning of the different
values.
compress: boolean, or integer
Whether to zip the stored data on disk. If an integer is
given, it should be between 1 and 9, and sets the amount
of compression. Note that compressed arrays cannot be
read by memmapping.
verbose: int, optional
The verbosity flag, controls messages that are issued as
the function is evaluated.
cache_validation_callback: callable, optional
Callable to check if a result in cache is valid or is to be recomputed.
When the function is called with arguments for which a cache exists,
the callback is called with the cache entry's metadata as its sole
argument. If it returns True, the cached result is returned, else the
cache for these arguments is cleared and the result is recomputed.
"""
# ------------------------------------------------------------------------
# Public interface
# ------------------------------------------------------------------------
def __init__(
self,
func,
location,
backend="local",
ignore=None,
mmap_mode=None,
compress=False,
verbose=1,
timestamp=None,
cache_validation_callback=None,
):
Logger.__init__(self)
self.mmap_mode = mmap_mode
self.compress = compress
self.func = func
self.cache_validation_callback = cache_validation_callback
self.func_id = _build_func_identifier(func)
self.ignore = ignore if ignore is not None else []
self._verbose = verbose
# retrieve store object from backend type and location.
self.store_backend = _store_backend_factory(
backend,
location,
verbose=verbose,
backend_options=dict(compress=compress, mmap_mode=mmap_mode),
)
if self.store_backend is not None:
# Create func directory on demand.
self.store_backend.store_cached_func_code([self.func_id])
self.timestamp = timestamp if timestamp is not None else time.time()
try:
functools.update_wrapper(self, func)
except Exception:
pass # Objects like ufunc don't like that
if inspect.isfunction(func):
doc = pydoc.TextDoc().document(func)
# Remove blank line
doc = doc.replace("\n", "\n\n", 1)
# Strip backspace-overprints for compatibility with autodoc
doc = re.sub("\x08.", "", doc)
else:
# Pydoc does a poor job on other objects
doc = func.__doc__
self.__doc__ = "Memoized version of %s" % doc
self._func_code_info = None
self._func_code_id = None
def _is_in_cache_and_valid(self, call_id):
"""Check if the function call is cached and valid for given arguments.
- Compare the function code with the one from the cached function,
asserting if it has changed.
- Check if the function call is present in the cache.
- Call `cache_validation_callback` for user define cache validation.
Returns True if the function call is in cache and can be used, and
returns False otherwise.
"""
# Check if the code of the function has changed
if not self._check_previous_func_code(stacklevel=4):
return False
# Check if this specific call is in the cache
if not self.store_backend.contains_item(call_id):
return False
# Call the user defined cache validation callback
metadata = self.store_backend.get_metadata(call_id)
if (
self.cache_validation_callback is not None
and not self.cache_validation_callback(metadata)
):
self.store_backend.clear_item(call_id)
return False
return True
def _cached_call(self, args, kwargs, shelving):
"""Call wrapped function and cache result, or read cache if available.
This function returns the wrapped function output or a reference to
the cached result.
Arguments:
----------
args, kwargs: list and dict
input arguments for wrapped function
shelving: bool
True when called via the call_and_shelve function.
Returns
-------
output: Output of the wrapped function if shelving is false, or a
MemorizedResult reference to the value if shelving is true.
metadata: dict containing the metadata associated with the call.
"""
args_id = self._get_args_id(*args, **kwargs)
call_id = (self.func_id, args_id)
_, func_name = get_func_name(self.func)
func_info = self.store_backend.get_cached_func_info([self.func_id])
location = func_info["location"]
if self._verbose >= 20:
logging.basicConfig(level=logging.INFO)
_, signature = format_signature(self.func, *args, **kwargs)
self.info(
textwrap.dedent(
f"""
Querying {func_name} with signature
{signature}.
(argument hash {args_id})
The store location is {location}.
"""
)
)
# Compare the function code with the previous to see if the
# function code has changed and check if the results are present in
# the cache.
if self._is_in_cache_and_valid(call_id):
if shelving:
return self._get_memorized_result(call_id), {}
try:
start_time = time.time()
output = self._load_item(call_id)
if self._verbose > 4:
self._print_duration(
time.time() - start_time, context="cache loaded "
)
return output, {}
except Exception:
# XXX: Should use an exception logger
_, signature = format_signature(self.func, *args, **kwargs)
self.warn(
"Exception while loading results for {}\n {}".format(
signature, traceback.format_exc()
)
)
if self._verbose > 10:
self.warn(
f"Computing func {func_name}, argument hash {args_id} "
f"in location {location}"
)
# Returns the output but not the metadata
return self._call(call_id, args, kwargs, shelving)
@property
def func_code_info(self):
# 3-tuple property containing: the function source code, source file,
# and first line of the code inside the source file
if hasattr(self.func, "__code__"):
if self._func_code_id is None:
self._func_code_id = id(self.func.__code__)
elif id(self.func.__code__) != self._func_code_id:
# Be robust to dynamic reassignments of self.func.__code__
self._func_code_info = None
if self._func_code_info is None:
# Cache the source code of self.func . Provided that get_func_code
# (which should be called once on self) gets called in the process
# in which self.func was defined, this caching mechanism prevents
# undesired cache clearing when the cached function is called in
# an environment where the introspection utilities get_func_code
# relies on do not work (typically, in joblib child processes).
# See #1035 for more info
# TODO (pierreglaser): do the same with get_func_name?
self._func_code_info = get_func_code(self.func)
return self._func_code_info
def call_and_shelve(self, *args, **kwargs):
"""Call wrapped function, cache result and return a reference.
This method returns a reference to the cached result instead of the
result itself. The reference object is small and picklable, allowing
to send or store it easily. Call .get() on reference object to get
result.
Returns
-------
cached_result: MemorizedResult or NotMemorizedResult
reference to the value returned by the wrapped function. The
class "NotMemorizedResult" is used when there is no cache
activated (e.g. location=None in Memory).
"""
# Return the wrapped output, without the metadata
return self._cached_call(args, kwargs, shelving=True)[0]
def __call__(self, *args, **kwargs):
# Return the output, without the metadata
return self._cached_call(args, kwargs, shelving=False)[0]
def __getstate__(self):
# Make sure self.func's source is introspected prior to being pickled -
# code introspection utilities typically do not work inside child
# processes
_ = self.func_code_info
# We don't store the timestamp when pickling, to avoid the hash
# depending from it.
state = self.__dict__.copy()
state["timestamp"] = None
# Invalidate the code id as id(obj) will be different in the child
state["_func_code_id"] = None
return state
def check_call_in_cache(self, *args, **kwargs):
"""Check if the function call is cached and valid for given arguments.
Does not call the function or do any work besides function inspection
and argument hashing.
- Compare the function code with the one from the cached function,
asserting if it has changed.
- Check if the function call is present in the cache.
- Call `cache_validation_callback` for user define cache validation.
Returns
-------
is_call_in_cache: bool
Whether or not the function call is in cache and can be used.
"""
call_id = (self.func_id, self._get_args_id(*args, **kwargs))
return self._is_in_cache_and_valid(call_id)
# ------------------------------------------------------------------------
# Private interface
# ------------------------------------------------------------------------
def _get_args_id(self, *args, **kwargs):
"""Return the input parameter hash of a result."""
return hashing.hash(
filter_args(self.func, self.ignore, args, kwargs),
coerce_mmap=self.mmap_mode is not None,
)
def _hash_func(self):
"""Hash a function to key the online cache"""
func_code_h = hash(getattr(self.func, "__code__", None))
return id(self.func), hash(self.func), func_code_h
def _write_func_code(self, func_code, first_line):
"""Write the function code and the filename to a file."""
# We store the first line because the filename and the function
# name is not always enough to identify a function: people
# sometimes have several functions named the same way in a
# file. This is bad practice, but joblib should be robust to bad
# practice.
func_code = "%s %i\n%s" % (FIRST_LINE_TEXT, first_line, func_code)
self.store_backend.store_cached_func_code([self.func_id], func_code)
# Also store in the in-memory store of function hashes
is_named_callable = (
hasattr(self.func, "__name__") and self.func.__name__ != "<lambda>"
)
if is_named_callable:
# Don't do this for lambda functions or strange callable
# objects, as it ends up being too fragile
func_hash = self._hash_func()
try:
_FUNCTION_HASHES[self.func] = func_hash
except TypeError:
# Some callable are not hashable
pass
def _check_previous_func_code(self, stacklevel=2):
"""
stacklevel is the depth a which this function is called, to
issue useful warnings to the user.
"""
# First check if our function is in the in-memory store.
# Using the in-memory store not only makes things faster, but it
# also renders us robust to variations of the files when the
# in-memory version of the code does not vary
try:
if self.func in _FUNCTION_HASHES:
# We use as an identifier the id of the function and its
# hash. This is more likely to falsely change than have hash
# collisions, thus we are on the safe side.
func_hash = self._hash_func()
if func_hash == _FUNCTION_HASHES[self.func]:
return True
except TypeError:
# Some callables are not hashable
pass
# Here, we go through some effort to be robust to dynamically
# changing code and collision. We cannot inspect.getsource
# because it is not reliable when using IPython's magic "%run".
func_code, source_file, first_line = self.func_code_info
try:
old_func_code, old_first_line = extract_first_line(
self.store_backend.get_cached_func_code([self.func_id])
)
except (IOError, OSError): # some backend can also raise OSError
self._write_func_code(func_code, first_line)
return False
if old_func_code == func_code:
return True
# We have differing code, is this because we are referring to
# different functions, or because the function we are referring to has
# changed?
_, func_name = get_func_name(
self.func, resolv_alias=False, win_characters=False
)
if old_first_line == first_line == -1 or func_name == "<lambda>":
if not first_line == -1:
func_description = "{0} ({1}:{2})".format(
func_name, source_file, first_line
)
else:
func_description = func_name
warnings.warn(
JobLibCollisionWarning(
"Cannot detect name collisions for function '{0}'".format(
func_description
)
),
stacklevel=stacklevel,
)
# Fetch the code at the old location and compare it. If it is the
# same than the code store, we have a collision: the code in the
# file has not changed, but the name we have is pointing to a new
# code block.
if not old_first_line == first_line and source_file is not None:
if os.path.exists(source_file):
_, func_name = get_func_name(self.func, resolv_alias=False)
num_lines = len(func_code.split("\n"))
with tokenize.open(source_file) as f:
on_disk_func_code = f.readlines()[
old_first_line - 1 : old_first_line - 1 + num_lines - 1
]
on_disk_func_code = "".join(on_disk_func_code)
possible_collision = (
on_disk_func_code.rstrip() == old_func_code.rstrip()
)
else:
possible_collision = source_file.startswith("<doctest ")
if possible_collision:
warnings.warn(
JobLibCollisionWarning(
"Possible name collisions between functions "
"'%s' (%s:%i) and '%s' (%s:%i)"
% (
func_name,
source_file,
old_first_line,
func_name,
source_file,
first_line,
)
),
stacklevel=stacklevel,
)
# The function has changed, wipe the cache directory.
# XXX: Should be using warnings, and giving stacklevel
if self._verbose > 10:
_, func_name = get_func_name(self.func, resolv_alias=False)
self.warn(
"Function {0} (identified by {1}) has changed.".format(
func_name, self.func_id
)
)
self.clear(warn=True)
return False
def clear(self, warn=True):
"""Empty the function's cache."""
func_id = self.func_id
if self._verbose > 0 and warn:
self.warn("Clearing function cache identified by %s" % func_id)
self.store_backend.clear_path(
[
func_id,
]
)
func_code, _, first_line = self.func_code_info
self._write_func_code(func_code, first_line)
def call(self, *args, **kwargs):
"""Force the execution of the function with the given arguments.
The output values will be persisted, i.e., the cache will be updated
with any new values.
Parameters
----------
*args: arguments
The arguments.
**kwargs: keyword arguments
Keyword arguments.
Returns
-------
output : object
The output of the function call.
metadata : dict
The metadata associated with the call.
"""
call_id = (self.func_id, self._get_args_id(*args, **kwargs))
# Return the output and the metadata
return self._call(call_id, args, kwargs)
def _call(self, call_id, args, kwargs, shelving=False):
# Return the output and the metadata
self._before_call(args, kwargs)
start_time = time.time()
output = self.func(*args, **kwargs)
return self._after_call(call_id, args, kwargs, shelving, output, start_time)
def _before_call(self, args, kwargs):
if self._verbose > 0:
print(format_call(self.func, args, kwargs))
def _after_call(self, call_id, args, kwargs, shelving, output, start_time):
self.store_backend.dump_item(call_id, output, verbose=self._verbose)
duration = time.time() - start_time
if self._verbose > 0:
self._print_duration(duration)
metadata = self._persist_input(duration, call_id, args, kwargs)
if shelving:
return self._get_memorized_result(call_id, metadata), metadata
if self.mmap_mode is not None:
# Memmap the output at the first call to be consistent with
# later calls
output = self._load_item(call_id, metadata)
return output, metadata
def _persist_input(self, duration, call_id, args, kwargs, this_duration_limit=0.5):
"""Save a small summary of the call using json format in the
output directory.
output_dir: string
directory where to write metadata.
duration: float
time taken by hashing input arguments, calling the wrapped
function and persisting its output.
args, kwargs: list and dict
input arguments for wrapped function
this_duration_limit: float
Max execution time for this function before issuing a warning.
"""
start_time = time.time()
argument_dict = filter_args(self.func, self.ignore, args, kwargs)
input_repr = dict((k, repr(v)) for k, v in argument_dict.items())
# This can fail due to race-conditions with multiple
# concurrent joblibs removing the file or the directory
metadata = {
"duration": duration,
"input_args": input_repr,
"time": start_time,
}
self.store_backend.store_metadata(call_id, metadata)
this_duration = time.time() - start_time
if this_duration > this_duration_limit:
# This persistence should be fast. It will not be if repr() takes
# time and its output is large, because json.dump will have to
# write a large file. This should not be an issue with numpy arrays
# for which repr() always output a short representation, but can
# be with complex dictionaries. Fixing the problem should be a
# matter of replacing repr() above by something smarter.
warnings.warn(
"Persisting input arguments took %.2fs to run."
"If this happens often in your code, it can cause "
"performance problems "
"(results will be correct in all cases). "
"The reason for this is probably some large input "
"arguments for a wrapped function." % this_duration,
stacklevel=5,
)
return metadata
def _get_memorized_result(self, call_id, metadata=None):
return MemorizedResult(
self.store_backend,
call_id,
metadata=metadata,
timestamp=self.timestamp,
verbose=self._verbose - 1,
)
def _load_item(self, call_id, metadata=None):
return self.store_backend.load_item(
call_id, metadata=metadata, timestamp=self.timestamp, verbose=self._verbose
)
def _print_duration(self, duration, context=""):
_, name = get_func_name(self.func)
msg = f"{name} {context}- {format_time(duration)}"
print(max(0, (80 - len(msg))) * "_" + msg)
# ------------------------------------------------------------------------
# Private `object` interface
# ------------------------------------------------------------------------
def __repr__(self):
return "{class_name}(func={func}, location={location})".format(
class_name=self.__class__.__name__,
func=self.func,
location=self.store_backend.location,
)
###############################################################################
# class `AsyncMemorizedFunc`
###############################################################################
|
MemorizedFunc
|
python
|
sqlalchemy__sqlalchemy
|
examples/association/dict_of_sets_with_default.py
|
{
"start": 2388,
"end": 3150
}
|
class ____(Base):
__tablename__ = "c"
b_id: Mapped[int] = mapped_column(ForeignKey("b.id"))
value: Mapped[int]
def __init__(self, value: int) -> None:
self.value = value
if __name__ == "__main__":
engine = create_engine("sqlite://", echo=True)
Base.metadata.create_all(engine)
session = Session(engine)
# only "A" is referenced explicitly. Using "collections",
# we deal with a dict of key/sets of integers directly.
session.add_all([A(collections={"1": {1, 2, 3}})])
session.commit()
a1 = session.scalars(select(A)).one()
print(a1.collections["1"])
a1.collections["1"].add(4)
session.commit()
a1.collections["2"].update([7, 8, 9])
session.commit()
print(a1.collections["2"])
|
C
|
python
|
getsentry__sentry
|
src/sentry/workflow_engine/models/data_condition_group.py
|
{
"start": 455,
"end": 617
}
|
class ____(TypedDict):
id: int
logic_type: DataConditionGroup.Type
conditions: list[DataConditionSnapshot]
@region_silo_model
|
DataConditionGroupSnapshot
|
python
|
google__jax
|
tests/tree_util_test.py
|
{
"start": 2941,
"end": 3388
}
|
class ____:
def __init__(self, x, y):
self.x = x
self.y = y
def __repr__(self):
return f"Special(x={self.x}, y={self.y})"
def tree_flatten(self):
return ((self.x, self.y), None)
@classmethod
def tree_unflatten(cls, aux_data, children):
return cls(*children)
def __eq__(self, other):
return type(self) is type(other) and (self.x, self.y) == (other.x, other.y)
@tree_util.register_pytree_with_keys_class
|
Special
|
python
|
ray-project__ray
|
python/ray/data/_internal/execution/progress_manager.py
|
{
"start": 2768,
"end": 5485
}
|
class ____(AbstractProgressBar):
"""Thin wrapper to provide identical interface to the ProgressBar.
Updates RichExecutionProgressManager internally.
"""
# If the name/description of the progress bar exceeds this length,
# it will be truncated.
MAX_NAME_LENGTH = 100
def __init__(
self,
name: str,
total: Optional[int] = None,
enabled: bool = True,
progress: Optional[Any] = None,
tid: Optional[Any] = None,
):
"""
Initialize sub-progress bar
Args:
name: name of sub-progress bar
total: total number of output rows. None for unknown.
enabled: whether progress bar is enabled.
progress: rich.Progress instance for the corresponding
sub-progress bar.
tid: rich.TaskId for the corresponding sub-progress bar task.
"""
# progress, tid type Optional[Any] due to conditional rich import.
if enabled:
assert progress is not None and tid is not None
else:
progress = None
tid = None
self._total = total
self._completed = 0
self._start_time = None
self._enabled = enabled
self._progress = progress
self._tid = tid
self._desc = truncate_operator_name(name, self.MAX_NAME_LENGTH)
def set_description(self, name: str) -> None:
self._desc = truncate_operator_name(name, self.MAX_NAME_LENGTH)
if self._enabled:
self._progress.update(self._tid, description=self._desc)
def get_description(self) -> str:
return self._desc
def _update(self, completed: int, total: Optional[int] = None) -> None:
assert self._enabled
if self._start_time is None:
self._start_time = time.time()
metrics = _get_progress_metrics(self._start_time, completed, total)
self._progress.update(
self._tid,
completed=metrics.completed,
total=metrics.total,
rate_str=metrics.rate_str,
count_str=metrics.count_str,
)
def update(self, increment: int = 0, total: Optional[int] = None) -> None:
if self._enabled and increment != 0:
if total is not None:
self._total = total
self._completed += increment
self._update(self._completed, self._total)
def complete(self) -> None:
if self._enabled:
self._update(self._completed, self._completed)
def __getstate__(self):
return {}
def __setstate__(self, state):
self.enabled = False # Progress bar is disabled on remote nodes.
|
SubProgressBar
|
python
|
Netflix__metaflow
|
metaflow/tutorials/01-playlist/playlist.py
|
{
"start": 382,
"end": 4106
}
|
class ____(FlowSpec):
"""
A flow to help you build your favorite movie playlist.
The flow performs the following steps:
1) Ingests a CSV file containing metadata about movies.
2) Loads two of the columns from the CSV into python lists.
3) In parallel branches:
- A) Filters movies by the genre parameter.
- B) Choose a random movie from a different genre.
4) Displays the top entries from the playlist.
"""
movie_data = IncludeFile(
"movie_data",
help="The path to a movie metadata file.",
default=script_path("movies.csv"),
)
genre = Parameter(
"genre", help="Filter movies for a particular genre.", default="Sci-Fi"
)
recommendations = Parameter(
"recommendations",
help="The number of movies to recommend in " "the playlist.",
default=5,
)
@step
def start(self):
"""
Parse the CSV file and load the values into a dictionary of lists.
"""
# For this example, we only need the movie title and the genres.
columns = ["movie_title", "genres"]
# Create a simple data frame as a dictionary of lists.
self.dataframe = dict((column, list()) for column in columns)
# Parse the CSV header.
lines = self.movie_data.split("\n")
header = lines[0].split(",")
idx = {column: header.index(column) for column in columns}
# Populate our dataframe from the lines of the CSV file.
for line in lines[1:]:
if not line:
continue
fields = line.rsplit(",", 4)
for column in columns:
self.dataframe[column].append(fields[idx[column]])
# Compute genre-specific movies and a bonus movie in parallel.
self.next(self.bonus_movie, self.genre_movies)
@step
def bonus_movie(self):
"""
This step chooses a random movie from a different genre.
"""
from random import choice
# Find all the movies that are not in the provided genre.
movies = [
(movie, genres)
for movie, genres in zip(
self.dataframe["movie_title"], self.dataframe["genres"]
)
if self.genre.lower() not in genres.lower()
]
# Choose one randomly.
self.bonus = choice(movies)
self.next(self.join)
@step
def genre_movies(self):
"""
Filter the movies by genre.
"""
from random import shuffle
# Find all the movies titles in the specified genre.
self.movies = [
movie
for movie, genres in zip(
self.dataframe["movie_title"], self.dataframe["genres"]
)
if self.genre.lower() in genres.lower()
]
# Randomize the title names.
shuffle(self.movies)
self.next(self.join)
@step
def join(self, inputs):
"""
Join our parallel branches and merge results.
"""
# Reassign relevant variables from our branches.
self.playlist = inputs.genre_movies.movies
self.bonus = inputs.bonus_movie.bonus
self.next(self.end)
@step
def end(self):
"""
Print out the playlist and bonus movie.
"""
print("Playlist for movies in genre '%s'" % self.genre)
for pick, movie in enumerate(self.playlist, start=1):
print("Pick %d: '%s'" % (pick, movie))
if pick >= self.recommendations:
break
print("Bonus Pick: '%s' from '%s'" % (self.bonus[0], self.bonus[1]))
if __name__ == "__main__":
PlayListFlow()
|
PlayListFlow
|
python
|
huggingface__transformers
|
src/transformers/models/mra/modeling_mra.py
|
{
"start": 30795,
"end": 31487
}
|
class ____(nn.Module):
def __init__(self, config):
super().__init__()
self.transform = MraPredictionHeadTransform(config)
# The output weights are the same as the input embeddings, but there is
# an output-only bias for each token.
self.decoder = nn.Linear(config.hidden_size, config.vocab_size, bias=True)
self.bias = nn.Parameter(torch.zeros(config.vocab_size))
def forward(self, hidden_states):
hidden_states = self.transform(hidden_states)
hidden_states = self.decoder(hidden_states)
return hidden_states
# Copied from transformers.models.bert.modeling_bert.BertOnlyMLMHead with Bert->Mra
|
MraLMPredictionHead
|
python
|
anthropics__anthropic-sdk-python
|
src/anthropic/types/beta/beta_tool_search_tool_result_block_param.py
|
{
"start": 668,
"end": 981
}
|
class ____(TypedDict, total=False):
content: Required[Content]
tool_use_id: Required[str]
type: Required[Literal["tool_search_tool_result"]]
cache_control: Optional[BetaCacheControlEphemeralParam]
"""Create a cache control breakpoint at this content block."""
|
BetaToolSearchToolResultBlockParam
|
python
|
falconry__falcon
|
examples/things_asgi.py
|
{
"start": 227,
"end": 988
}
|
class ____:
async def on_get(self, req, resp):
"""Handles GET requests"""
resp.status = falcon.HTTP_200 # This is the default status
resp.content_type = falcon.MEDIA_TEXT # Default is JSON, so override
resp.text = (
'\nTwo things awe me most, the starry sky '
'above me and the moral law within me.\n'
'\n'
' ~ Immanuel Kant\n\n'
)
# falcon.asgi.App instances are callable ASGI apps...
# in larger applications the app is created in a separate file
app = falcon.asgi.App()
# Resources are represented by long-lived class instances
things = ThingsResource()
# things will handle all requests to the '/things' URL path
app.add_route('/things', things)
|
ThingsResource
|
python
|
huggingface__transformers
|
src/transformers/models/idefics3/modeling_idefics3.py
|
{
"start": 12962,
"end": 14310
}
|
class ____(GradientCheckpointingLayer):
def __init__(self, config: Idefics3VisionConfig):
super().__init__()
self.embed_dim = config.hidden_size
self.self_attn = Idefics3VisionAttention(config)
self.layer_norm1 = nn.LayerNorm(self.embed_dim, eps=config.layer_norm_eps)
self.mlp = Idefics3VisionMLP(config)
self.layer_norm2 = nn.LayerNorm(self.embed_dim, eps=config.layer_norm_eps)
@auto_docstring
# Copied from transformers.models.siglip.modeling_siglip.SiglipEncoderLayer.forward
def forward(
self,
hidden_states: torch.Tensor,
attention_mask: 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,
attention_mask=attention_mask,
**kwargs,
)
hidden_states = residual + hidden_states
residual = hidden_states
hidden_states = self.layer_norm2(hidden_states)
hidden_states = self.mlp(hidden_states)
hidden_states = residual + hidden_states
return hidden_states
# Copied from transformers.models.siglip.modeling_siglip.SiglipEncoder with Siglip->Idefics3
|
Idefics3EncoderLayer
|
python
|
pytorch__pytorch
|
test/jit/test_decorator.py
|
{
"start": 146,
"end": 834
}
|
class ____(JitTestCase):
def test_decorator(self):
# Note: JitTestCase.checkScript() does not work with decorators
# self.checkScript(my_function_a, (1.0,))
# Error:
# RuntimeError: expected def but found '@' here:
# @my_decorator
# ~ <--- HERE
# def my_function_a(x: float) -> float:
# Do a simple torch.jit.script() test instead
fn = my_function_a
fx = torch.jit.script(fn)
self.assertEqual(fn(1.0), fx(1.0))
if __name__ == "__main__":
raise RuntimeError(
"This test is not currently used and should be "
"enabled in discover_tests.py if required."
)
|
TestDecorator
|
python
|
jmcnamara__XlsxWriter
|
xlsxwriter/test/comparison/test_background01.py
|
{
"start": 315,
"end": 851
}
|
class ____(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.set_filename("background01.xlsx")
def test_create_file(self):
"""Test the creation of an XlsxWriter file with a background image."""
workbook = Workbook(self.got_filename)
worksheet = workbook.add_worksheet()
worksheet.insert_image("E9", self.image_dir + "logo.jpg")
workbook.close()
self.assertExcelEqual()
|
TestCompareXLSXFiles
|
python
|
google__pytype
|
pytype/directors/parser.py
|
{
"start": 1387,
"end": 1493
}
|
class ____(LineRange):
name: str
annotation: str
@dataclasses.dataclass(frozen=True)
|
_VariableAnnotation
|
python
|
getsentry__sentry
|
src/sentry/explore/endpoints/explore_saved_query_detail.py
|
{
"start": 5786,
"end": 6771
}
|
class ____(ExploreSavedQueryBase):
publish_status = {
"POST": ApiPublishStatus.PRIVATE,
}
def has_feature(self, organization, request):
return features.has(
"organizations:visibility-explore-view", organization, actor=request.user
)
def post(self, request: Request, organization, query) -> Response:
"""
Update last_visited and increment visits counter
"""
if not self.has_feature(organization, request):
return self.respond(status=404)
query.visits = F("visits") + 1
query.last_visited = timezone.now()
query.save(update_fields=["visits", "last_visited"])
ExploreSavedQueryLastVisited.objects.create_or_update(
organization=organization,
user_id=request.user.id,
explore_saved_query=query,
values={"last_visited": timezone.now()},
)
return Response(status=204)
|
ExploreSavedQueryVisitEndpoint
|
python
|
great-expectations__great_expectations
|
great_expectations/datasource/fluent/snowflake_datasource.py
|
{
"start": 11442,
"end": 12526
}
|
class ____(FluentBaseModel):
"""
Information needed to connect to a Snowflake database.
Alternative to a connection string.
https://docs.snowflake.com/en/developer-guide/python-connector/sqlalchemy#additional-connection-parameters
"""
account: AccountIdentifier
user: str
password: Union[ConfigStr, str]
database: str = pydantic.Field(
...,
description="`database` that the Datasource is mapped to.",
)
schema_: str = pydantic.Field(
..., alias="schema", description="`schema` that the Datasource is mapped to."
) # schema is a reserved attr in BaseModel
warehouse: str
role: str
numpy: bool = False
@classmethod
def required_fields(cls) -> list[str]:
"""Returns the required fields for this model as defined in the schema."""
return cls.schema()["required"]
class Config:
@staticmethod
def schema_extra(schema: dict, model: type[ConnectionDetails]) -> None:
schema["properties"]["account"] = AccountIdentifier.get_schema()
|
ConnectionDetails
|
python
|
airbytehq__airbyte
|
airbyte-integrations/connectors/source-outbrain-amplify/source_outbrain_amplify/source.py
|
{
"start": 38394,
"end": 41271
}
|
class ____(OutbrainAmplifyStream, HttpSubStream):
primary_key = None
def __init__(self, authenticator, config, parent: Marketers, **kwargs):
super().__init__(parent=parent, **kwargs)
self.config = config
self._authenticator = authenticator
self._session = requests.sessions.Session()
def request_params(
self, stream_state: Mapping[str, Any], stream_slice: Mapping[str, any] = None, next_page_token: Mapping[str, Any] = None
) -> MutableMapping[str, Any]:
return {}
def next_page_token(self, response: requests.Response) -> Optional[Mapping[str, Any]]:
return None
def stream_slices(
self, sync_mode: SyncMode.full_refresh, cursor_field: List[str] = None, stream_state: Mapping[str, Any] = None
) -> Iterable[Optional[Mapping[str, Any]]]:
parent_stream_slices = self.parent.stream_slices(
sync_mode=SyncMode.full_refresh, cursor_field=cursor_field, stream_state=stream_state
)
for stream_slice in parent_stream_slices:
parent_records = self.parent.read_records(
sync_mode=SyncMode.full_refresh, cursor_field=cursor_field, stream_slice=stream_slice, stream_state=stream_state
)
for record in parent_records:
yield {"marketer_id": record.get("id")}
def parse_response(
self,
response: requests.Response,
stream_state: Mapping[str, Any],
stream_slice: Mapping[str, Any] = None,
next_page_token: Mapping[str, Any] = None,
) -> Iterable[Mapping]:
if response.json():
for x in response.json().get("results"):
x["marketer_id"] = stream_slice["marketer_id"]
yield x
def path(
self, stream_state: Mapping[str, Any] = None, stream_slice: Mapping[str, Any] = None, next_page_token: Mapping[str, Any] = None
) -> str:
stream_start, stream_end = self._get_time_interval(self.config.get("start_date"), self.config.get("end_date"))
stream_conversion_count = self._get_bool_conversion_count_by_click_date(
self.config.get("conversion_count", DEFAULT_REPORT_CONVERSION_COUNT_BY_CLICK_DATE)
)
return (
f"reports/marketers/{stream_slice['marketer_id']}/geo?from="
+ str(stream_start.date())
+ "&to="
+ str(stream_end.date())
+ "&breakdown="
+ str(self.config.get("geo_location_breakdown", DEFAULT_GEO_LOCATION_BREAKDOWN))
+ "&limit=500"
+ "&includeVideoStats=true"
+ "&conversionsByClickDate="
+ str(stream_conversion_count)
)
# Retrieve performance statistics for all marketer campaigns by geo.
# A special endpoint for retrieving geo data by campaign breakdown.
|
PerformanceReportMarketersByGeoPerformance
|
python
|
django__django
|
tests/custom_managers/models.py
|
{
"start": 2542,
"end": 2671
}
|
class ____(models.Manager):
def get_queryset(self):
return super().get_queryset().filter(fun=False)
|
BoringPeopleManager
|
python
|
apache__airflow
|
providers/amazon/tests/system/amazon/aws/tests/test_aws_auth_manager.py
|
{
"start": 5510,
"end": 7203
}
|
class ____:
"""
Run tests on Airflow using AWS auth manager with real credentials
"""
@classmethod
def teardown_class(cls):
cls.delete_avp_policy_store()
@classmethod
def delete_avp_policy_store(cls):
client = boto3.client("verifiedpermissions")
paginator = client.get_paginator("list_policy_stores")
pages = paginator.paginate()
policy_store_ids = [
store["policyStoreId"]
for page in pages
for store in page["policyStores"]
if "description" in store
and f"Created by system test TestAwsAuthManager: {env_id_cache}" in store["description"]
]
for policy_store_id in policy_store_ids:
client.delete_policy_store(policyStoreId=policy_store_id)
def test_login_admin_redirect(self, client_admin_permissions):
response = client_admin_permissions.post(
AUTH_MANAGER_FASTAPI_APP_PREFIX + "/login_callback",
follow_redirects=False,
data={"RelayState": "login-redirect"},
)
token = response.cookies.get(COOKIE_NAME_JWT_TOKEN)
assert response.status_code == 303
assert "location" in response.headers
assert response.headers["location"] == "/"
assert token is not None
def test_login_admin_token(self, client_admin_permissions):
response = client_admin_permissions.post(
AUTH_MANAGER_FASTAPI_APP_PREFIX + "/login_callback",
follow_redirects=False,
data={"RelayState": "login-token"},
)
assert response.status_code == 200
assert response.json()["access_token"]
|
TestAwsAuthManager
|
python
|
aio-libs__aiohttp
|
aiohttp/tracing.py
|
{
"start": 9609,
"end": 9776
}
|
class ____:
"""Parameters sent by the `on_request_headers_sent` signal"""
method: str
url: URL
headers: "CIMultiDict[str]"
|
TraceRequestHeadersSentParams
|
python
|
django__django
|
tests/custom_managers/models.py
|
{
"start": 717,
"end": 950
}
|
class ____(models.Manager):
def get_queryset(self):
return (
super()
.get_queryset()
.annotate(favorite_avg=models.Avg("favorite_books__favorite_thing_id"))
)
|
AnnotatedBookManager
|
python
|
doocs__leetcode
|
solution/0100-0199/0126.Word Ladder II/Solution.py
|
{
"start": 0,
"end": 1554
}
|
class ____:
def findLadders(
self, beginWord: str, endWord: str, wordList: List[str]
) -> List[List[str]]:
def dfs(path, cur):
if cur == beginWord:
ans.append(path[::-1])
return
for precursor in prev[cur]:
path.append(precursor)
dfs(path, precursor)
path.pop()
ans = []
words = set(wordList)
if endWord not in words:
return ans
words.discard(beginWord)
dist = {beginWord: 0}
prev = defaultdict(set)
q = deque([beginWord])
found = False
step = 0
while q and not found:
step += 1
for i in range(len(q), 0, -1):
p = q.popleft()
s = list(p)
for i in range(len(s)):
ch = s[i]
for j in range(26):
s[i] = chr(ord('a') + j)
t = ''.join(s)
if dist.get(t, 0) == step:
prev[t].add(p)
if t not in words:
continue
prev[t].add(p)
words.discard(t)
q.append(t)
dist[t] = step
if endWord == t:
found = True
s[i] = ch
if found:
path = [endWord]
dfs(path, endWord)
return ans
|
Solution
|
python
|
huggingface__transformers
|
src/transformers/models/vivit/modeling_vivit.py
|
{
"start": 7752,
"end": 10140
}
|
class ____(nn.Module):
def __init__(self, config: VivitConfig):
super().__init__()
if config.hidden_size % config.num_attention_heads != 0 and not hasattr(config, "embedding_size"):
raise ValueError(
f"The hidden size {config.hidden_size} is not a multiple of the number of attention "
f"heads {config.num_attention_heads}."
)
self.config = config
self.num_attention_heads = config.num_attention_heads
self.attention_head_size = int(config.hidden_size / config.num_attention_heads)
self.all_head_size = self.num_attention_heads * self.attention_head_size
self.dropout_prob = config.attention_probs_dropout_prob
self.scaling = self.attention_head_size**-0.5
self.is_causal = False
self.query = nn.Linear(config.hidden_size, self.all_head_size, bias=config.qkv_bias)
self.key = nn.Linear(config.hidden_size, self.all_head_size, bias=config.qkv_bias)
self.value = nn.Linear(config.hidden_size, self.all_head_size, bias=config.qkv_bias)
def forward(self, hidden_states: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:
batch_size = hidden_states.shape[0]
new_shape = batch_size, -1, self.num_attention_heads, self.attention_head_size
key_layer = self.key(hidden_states).view(*new_shape).transpose(1, 2)
value_layer = self.value(hidden_states).view(*new_shape).transpose(1, 2)
query_layer = self.query(hidden_states).view(*new_shape).transpose(1, 2)
attention_interface: Callable = eager_attention_forward
if self.config._attn_implementation != "eager":
attention_interface = ALL_ATTENTION_FUNCTIONS[self.config._attn_implementation]
context_layer, attention_probs = attention_interface(
self,
query_layer,
key_layer,
value_layer,
None,
is_causal=self.is_causal,
scaling=self.scaling,
dropout=0.0 if not self.training else self.dropout_prob,
)
new_context_layer_shape = context_layer.size()[:-2] + (self.all_head_size,)
context_layer = context_layer.reshape(new_context_layer_shape)
return context_layer, attention_probs
# Copied from transformers.models.vit.modeling_vit.ViTSelfOutput with ViT->Vivit
|
VivitSelfAttention
|
python
|
jazzband__django-simple-history
|
simple_history/models.py
|
{
"start": 35630,
"end": 36542
}
|
class ____(ForeignKey):
"""
Allows foreign keys to work properly from a historic instance.
If you use as_of queries to extract historical instances from
a model, and you have other models that are related by foreign
key and also historic, changing them to a HistoricForeignKey
field type will allow you to naturally cross the relationship
boundary at the same point in time as the origin instance.
A historic instance maintains an attribute ("_historic") when
it is historic, holding the historic record instance and the
timepoint used to query it ("_as_of"). HistoricForeignKey
looks for this and uses an as_of query against the related
object so the relationship is assessed at the same timepoint.
"""
forward_related_accessor_class = HistoricForwardManyToOneDescriptor
related_accessor_class = HistoricReverseManyToOneDescriptor
|
HistoricForeignKey
|
python
|
allegroai__clearml
|
clearml/backend_api/services/v2_13/queues.py
|
{
"start": 50408,
"end": 51836
}
|
class ____(Response):
"""
Response of queues.get_default endpoint.
:param id: Queue id
:type id: str
:param name: Queue name
:type name: str
"""
_service = "queues"
_action = "get_default"
_version = "2.13"
_schema = {
"definitions": {},
"properties": {
"id": {"description": "Queue id", "type": ["string", "null"]},
"name": {"description": "Queue name", "type": ["string", "null"]},
},
"type": "object",
}
def __init__(self, id: Optional[str] = None, name: Optional[str] = None, **kwargs: Any) -> None:
super(GetDefaultResponse, self).__init__(**kwargs)
self.id = id
self.name = name
@schema_property("id")
def id(self) -> Optional[str]:
return self._property_id
@id.setter
def id(self, value: Optional[str]) -> None:
if value is None:
self._property_id = None
return
self.assert_isinstance(value, "id", six.string_types)
self._property_id = value
@schema_property("name")
def name(self) -> Optional[str]:
return self._property_name
@name.setter
def name(self, value: Optional[str]) -> None:
if value is None:
self._property_name = None
return
self.assert_isinstance(value, "name", six.string_types)
self._property_name = value
|
GetDefaultResponse
|
python
|
numpy__numpy
|
numpy/distutils/system_info.py
|
{
"start": 24259,
"end": 24434
}
|
class ____(NotFoundError):
"""
Numeric (https://www.numpy.org/) module not found.
Get it from above location, install it, and retry setup.py."""
|
NumericNotFoundError
|
python
|
ipython__ipython
|
tests/test_interactiveshell.py
|
{
"start": 28021,
"end": 28531
}
|
class ____(ast.NodeTransformer):
"""Wraps all integers in a call to Integer()"""
# for Python 3.7 and earlier
def visit_Num(self, node):
if isinstance(node.value, int):
return ast.Call(
func=ast.Name(id="Integer", ctx=ast.Load()), args=[node], keywords=[]
)
return node
# For Python 3.8+
def visit_Constant(self, node):
if isinstance(node.value, int):
return self.visit_Num(node)
return node
|
IntegerWrapper
|
python
|
great-expectations__great_expectations
|
great_expectations/datasource/fluent/pandas_filesystem_datasource.py
|
{
"start": 720,
"end": 3175
}
|
class ____(_PandasFilePathDatasource):
"""Pandas based Datasource for filesystem based data assets."""
# class attributes
data_connector_type: ClassVar[Type[FilesystemDataConnector]] = FilesystemDataConnector
# these fields should not be passed to the execution engine
_EXTRA_EXCLUDED_EXEC_ENG_ARGS: ClassVar[set] = {
"base_directory",
"data_context_root_directory",
}
# instance attributes
type: Literal["pandas_filesystem"] = "pandas_filesystem"
# Filesystem specific attributes
base_directory: pathlib.Path
data_context_root_directory: Optional[pathlib.Path] = None
@override
def test_connection(self, test_assets: bool = True) -> None:
"""Test the connection for the PandasFilesystemDatasource.
Args:
test_assets: If assets have been passed to the PandasFilesystemDatasource, whether to test them as well.
Raises:
TestConnectionError: If the connection test fails.
""" # noqa: E501 # FIXME CoP
if not self.base_directory.exists():
raise TestConnectionError(f"Path: {self.base_directory.resolve()} does not exist.") # noqa: TRY003 # FIXME CoP
if self.assets and test_assets:
for asset in self.assets:
asset.test_connection()
@override
def _build_data_connector(
self, data_asset: FileDataAsset, glob_directive: str = "**/*", **kwargs
) -> None:
"""Builds and attaches the `FilesystemDataConnector` to the asset."""
if kwargs:
raise TypeError( # noqa: TRY003 # FIXME CoP
f"_build_data_connector() got unexpected keyword arguments {list(kwargs.keys())}"
)
data_asset._data_connector = self.data_connector_type.build_data_connector(
datasource_name=self.name,
data_asset_name=data_asset.name,
base_directory=self.base_directory,
glob_directive=glob_directive,
data_context_root_directory=self.data_context_root_directory,
)
# build a more specific `_test_connection_error_message`
data_asset._test_connection_error_message = (
self.data_connector_type.build_test_connection_error_message(
data_asset_name=data_asset.name,
glob_directive=glob_directive,
base_directory=self.base_directory,
)
)
|
PandasFilesystemDatasource
|
python
|
donnemartin__system-design-primer
|
solutions/system_design/sales_rank/sales_rank_mapreduce.py
|
{
"start": 55,
"end": 1921
}
|
class ____(MRJob):
def within_past_week(self, timestamp):
"""Return True if timestamp is within past week, False otherwise."""
...
def mapper(self, _, line):
"""Parse each log line, extract and transform relevant lines.
Emit key value pairs of the form:
(foo, p1), 2
(bar, p1), 2
(bar, p1), 1
(foo, p2), 3
(bar, p3), 10
(foo, p4), 1
"""
timestamp, product_id, category, quantity = line.split('\t')
if self.within_past_week(timestamp):
yield (category, product_id), quantity
def reducer(self, key, values):
"""Sum values for each key.
(foo, p1), 2
(bar, p1), 3
(foo, p2), 3
(bar, p3), 10
(foo, p4), 1
"""
yield key, sum(values)
def mapper_sort(self, key, value):
"""Construct key to ensure proper sorting.
Transform key and value to the form:
(foo, 2), p1
(bar, 3), p1
(foo, 3), p2
(bar, 10), p3
(foo, 1), p4
The shuffle/sort step of MapReduce will then do a
distributed sort on the keys, resulting in:
(category1, 1), product4
(category1, 2), product1
(category1, 3), product2
(category2, 3), product1
(category2, 7), product3
"""
category, product_id = key
quantity = value
yield (category, quantity), product_id
def reducer_identity(self, key, value):
yield key, value
def steps(self):
"""Run the map and reduce steps."""
return [
self.mr(mapper=self.mapper,
reducer=self.reducer),
self.mr(mapper=self.mapper_sort,
reducer=self.reducer_identity),
]
if __name__ == '__main__':
SalesRanker.run()
|
SalesRanker
|
python
|
jina-ai__jina
|
tests/unit/yaml/dummy_gateway.py
|
{
"start": 361,
"end": 1654
}
|
class ____(Gateway):
def __init__(
self, arg1: str = None, arg2: str = None, arg3: str = 'default-arg3', **kwargs
):
super().__init__(**kwargs)
self.arg1 = arg1
self.arg2 = arg2
self.arg3 = arg3
async def setup_server(self):
from fastapi import FastAPI
app = FastAPI(
title='Dummy Server',
)
@app.get(path='/', response_model=DummyResponseModel)
def _get_response():
return {
'arg1': self.arg1,
'arg2': self.arg2,
'arg3': self.arg3,
}
@app.get(
path='/stream',
response_model=ProcessedResponseModel,
)
async def _process(text: str):
doc = None
async for docs in self.streamer.stream_docs(
docs=DocumentArray([Document(text=text)]),
exec_endpoint='/',
):
doc = docs[0]
return {'text': doc.text, 'tags': doc.tags}
self.server = Server(Config(app, host=self.host, port=self.port))
async def run_server(self):
await self.server.serve()
async def shutdown(self):
self.server.should_exit = True
await self.server.shutdown()
|
DummyGateway
|
python
|
google__pytype
|
pytype/pyc/opcodes.py
|
{
"start": 5470,
"end": 5666
}
|
class ____(OpcodeWithArg):
_FLAGS = HAS_JREL | HAS_ARGUMENT | STORE_JUMP | PUSHES_BLOCK
__slots__ = ("stack_depth",)
# --------------------------------------------------------
|
SETUP_EXCEPT_311
|
python
|
getsentry__sentry
|
tests/sentry/manager/test_group_manager.py
|
{
"start": 245,
"end": 1568
}
|
class ____(TestCase):
def test_get_groups_by_external_issue(self) -> None:
external_issue_key = "api-123"
group = self.create_group()
integration_model, _ = self.create_provider_integration_for(
group.organization,
self.user,
provider="jira",
external_id="some_id",
name="Hello world",
metadata={"base_url": "https://example.com"},
)
integration = serialize_integration(integration=integration_model)
self.create_integration_external_issue(
group=group, integration=integration, key=external_issue_key
)
affected_groups_no_orgs = Group.objects.get_groups_by_external_issue(
integration,
[],
external_issue_key,
)
assert set(affected_groups_no_orgs) == set()
affected_groups_wrong_key = Group.objects.get_groups_by_external_issue(
integration,
[group.organization],
"invalid",
)
assert set(affected_groups_wrong_key) == set()
affected_groups = Group.objects.get_groups_by_external_issue(
integration,
[group.organization],
external_issue_key,
)
assert set(affected_groups) == {group}
|
SentryManagerTest
|
python
|
pydantic__pydantic
|
pydantic-core/tests/serializers/test_bytes.py
|
{
"start": 4809,
"end": 6041
}
|
class ____:
def __init__(self, **kwargs):
for key, value in kwargs.items():
setattr(self, key, value)
def test_bytes_mode_set_via_model_config_not_serializer_config():
s = SchemaSerializer(
core_schema.model_schema(
BasicModel,
core_schema.model_fields_schema(
{
'foo': core_schema.model_field(core_schema.bytes_schema()),
}
),
config=core_schema.CoreConfig(ser_json_bytes='base64'),
)
)
bm = BasicModel(foo=b'foobar')
assert s.to_python(bm) == {'foo': b'foobar'}
assert s.to_json(bm) == b'{"foo":"Zm9vYmFy"}'
assert s.to_python(bm, mode='json') == {'foo': 'Zm9vYmFy'}
# assert doesn't override serializer config
# in V3, we can change the serialization settings provided to to_json to override model config settings,
# but that'd be a breaking change
BasicModel.__pydantic_serializer__ = s
assert to_json(bm, bytes_mode='utf8') == b'{"foo":"Zm9vYmFy"}'
assert to_json({'foo': b'some bytes'}, bytes_mode='base64') == b'{"foo":"c29tZSBieXRlcw=="}'
assert to_json({'bar': bm}, bytes_mode='base64') == b'{"bar":{"foo":"Zm9vYmFy"}}'
|
BasicModel
|
python
|
coleifer__peewee
|
tests/db_tests.py
|
{
"start": 25418,
"end": 28096
}
|
class ____(BaseTestCase):
def test_proxy_context_manager(self):
db = Proxy()
class User(Model):
username = TextField()
class Meta:
database = db
self.assertRaises(AttributeError, User.create_table)
sqlite_db = SqliteDatabase(':memory:')
db.initialize(sqlite_db)
User.create_table()
with db:
self.assertFalse(db.is_closed())
self.assertTrue(db.is_closed())
def test_db_proxy(self):
db = Proxy()
class BaseModel(Model):
class Meta:
database = db
class User(BaseModel):
username = TextField()
class Tweet(BaseModel):
user = ForeignKeyField(User, backref='tweets')
message = TextField()
sqlite_db = SqliteDatabase(':memory:')
db.initialize(sqlite_db)
self.assertEqual(User._meta.database.database, ':memory:')
self.assertEqual(Tweet._meta.database.database, ':memory:')
self.assertTrue(User._meta.database.is_closed())
self.assertTrue(Tweet._meta.database.is_closed())
sqlite_db.connect()
self.assertFalse(User._meta.database.is_closed())
self.assertFalse(Tweet._meta.database.is_closed())
sqlite_db.close()
def test_proxy_decorator(self):
db = DatabaseProxy()
@db.connection_context()
def with_connection():
self.assertFalse(db.is_closed())
@db.atomic()
def with_transaction():
self.assertTrue(db.in_transaction())
@db.manual_commit()
def with_manual_commit():
self.assertTrue(db.in_transaction())
db.initialize(SqliteDatabase(':memory:'))
with_connection()
self.assertTrue(db.is_closed())
with_transaction()
self.assertFalse(db.in_transaction())
with_manual_commit()
self.assertFalse(db.in_transaction())
def test_proxy_bind_ctx_callbacks(self):
db = Proxy()
class BaseModel(Model):
class Meta:
database = db
class Hook(BaseModel):
data = BlobField() # Attaches hook to configure blob-type.
self.assertTrue(Hook.data._constructor is bytearray)
class CustomSqliteDB(SqliteDatabase):
sentinel = object()
def get_binary_type(self):
return self.sentinel
custom_db = CustomSqliteDB(':memory:')
with custom_db.bind_ctx([Hook]):
self.assertTrue(Hook.data._constructor is custom_db.sentinel)
self.assertTrue(Hook.data._constructor is bytearray)
|
TestDBProxy
|
python
|
numpy__numpy
|
numpy/distutils/cpuinfo.py
|
{
"start": 11191,
"end": 12915
}
|
class ____(CPUInfoBase):
info = None
def __init__(self):
if self.info is not None:
return
info = command_info(arch='arch',
machine='machine')
info['sysctl_hw'] = key_value_from_command('sysctl hw', sep='=')
self.__class__.info = info
def _not_impl(self): pass
def _getNCPUs(self):
return int(self.info['sysctl_hw'].get('hw.ncpu', 1))
def _is_Power_Macintosh(self):
return self.info['sysctl_hw']['hw.machine']=='Power Macintosh'
def _is_i386(self):
return self.info['arch']=='i386'
def _is_ppc(self):
return self.info['arch']=='ppc'
def __machine(self, n):
return self.info['machine'] == 'ppc%s'%n
def _is_ppc601(self): return self.__machine(601)
def _is_ppc602(self): return self.__machine(602)
def _is_ppc603(self): return self.__machine(603)
def _is_ppc603e(self): return self.__machine('603e')
def _is_ppc604(self): return self.__machine(604)
def _is_ppc604e(self): return self.__machine('604e')
def _is_ppc620(self): return self.__machine(620)
def _is_ppc630(self): return self.__machine(630)
def _is_ppc740(self): return self.__machine(740)
def _is_ppc7400(self): return self.__machine(7400)
def _is_ppc7450(self): return self.__machine(7450)
def _is_ppc750(self): return self.__machine(750)
def _is_ppc403(self): return self.__machine(403)
def _is_ppc505(self): return self.__machine(505)
def _is_ppc801(self): return self.__machine(801)
def _is_ppc821(self): return self.__machine(821)
def _is_ppc823(self): return self.__machine(823)
def _is_ppc860(self): return self.__machine(860)
|
DarwinCPUInfo
|
python
|
tensorflow__tensorflow
|
tensorflow/dtensor/python/tests/collective_test.py
|
{
"start": 13481,
"end": 23008
}
|
class ____(test_util.DTensorBaseTest):
# Create two independent global AllReduce ops that should get combined.
def testGlobalAllReduceCombiner(self):
self.skipForDeviceType(['TPU'],
'This test requires 8 TPU cores.',
unless_device_count_equals_to=8)
# Create and use an eight-device mesh just for this test.
global_ids = test_util.create_device_ids_array((8,))
local_ids = np.ravel(global_ids).tolist()
mesh_dict = {
device: layout_lib.Mesh([_MESH_DIM_X], global_ids, local_ids,
test_util.create_device_list((8,), device))
for device in ('CPU', 'GPU', 'TPU')
}
mesh = self.configTestMesh(mesh_dict)
fully_replicated_layout_1d = Layout.replicated(mesh, rank=1)
first_dimension_sharded_layout_2d = Layout.batch_sharded(
mesh, _MESH_DIM_X, 2)
@polymorphic_function.function
def func(a, b):
a = math_ops.reduce_sum(a, axis=[0])
b = math_ops.reduce_sum(b, axis=[0])
# Do something with the results before adding them, to make sure the MLIR
# pass can handle dependent ops sandwiched between two all-reduce ops.
return gen_math_ops.square(a) + gen_math_ops.square(b)
row = constant_op.constant(np.array([[1., 2.0]]), dtype=dtypes.float32)
a = array_ops.repeat(row, repeats=[8], axis=0)
b = gen_array_ops.reverse_v2(a, axis=[1])
expected_result = func(a, b)
a = api.relayout(a, first_dimension_sharded_layout_2d)
b = api.relayout(b, first_dimension_sharded_layout_2d)
dtensor_result = func(a, b)
self.assertDTensorEqual(expected_result, fully_replicated_layout_1d,
dtensor_result)
# Create two independent global AllReduce ops that should get combined.
# Create two independent global AllReduce ops with different reductions, that
# should not get combined
def testGlobalAllReduceCombinerDifferentReduce(self):
self.skipForDeviceType(['TPU'],
'This test requires 8 TPU cores.',
unless_device_count_equals_to=8)
# Create and use an eight-device mesh just for this test.
global_ids = test_util.create_device_ids_array((8,))
local_ids = np.ravel(global_ids).tolist()
mesh_dict = {
device: layout_lib.Mesh([_MESH_DIM_X], global_ids, local_ids,
test_util.create_device_list((8,), device))
for device in ('CPU', 'GPU', 'TPU')
}
mesh = self.configTestMesh(mesh_dict)
fully_replicated_layout_1d = Layout.replicated(mesh, rank=1)
first_dimension_sharded_layout_2d = Layout.batch_sharded(
mesh, _MESH_DIM_X, 2)
@polymorphic_function.function
def func(a, b):
a = math_ops.reduce_sum(a, axis=[0])
b = math_ops.reduce_mean(b, axis=[0])
# Do something with the results before adding them, to make sure the MLIR
# pass can handle dependent ops sandwiched between two all-reduce ops.
return gen_math_ops.square(a) + gen_math_ops.square(b)
row = constant_op.constant(np.array([[1., 2.0]]), dtype=dtypes.float32)
a = array_ops.repeat(row, repeats=[8], axis=0)
b = gen_array_ops.reverse_v2(a, axis=[1])
expected_result = func(a, b)
a = api.relayout(a, first_dimension_sharded_layout_2d)
b = api.relayout(b, first_dimension_sharded_layout_2d)
dtensor_result = func(a, b)
self.assertDTensorEqual(expected_result, fully_replicated_layout_1d,
dtensor_result)
# Create two independent subgroup AllReduce ops that should get combined.
def testSubgroupAllReduceCombiner(self):
self.skipForDeviceType(['TPU'],
'This test requires 8 TPU cores.',
unless_device_count_equals_to=8)
# Create and use an eight-device mesh just for this test.
global_ids = test_util.create_device_ids_array((4, 2))
local_ids = np.ravel(global_ids).tolist()
mesh_dict = {
device: layout_lib.Mesh(_MESH_DIMS, global_ids, local_ids,
test_util.create_device_list((4, 2), device))
for device in ('CPU', 'GPU', 'TPU')
}
mesh = self.configTestMesh(mesh_dict)
fully_sharded_layout_2d = Layout(_MESH_DIMS, mesh)
@polymorphic_function.function
def func(a, b):
a = math_ops.reduce_sum(a, axis=[0])
b = math_ops.reduce_sum(b, axis=[0])
# Do something with the results before adding them, to make sure the MLIR
# pass can handle dependent ops sandwiched between two all-reduce ops.
return gen_math_ops.square(a) + gen_math_ops.square(b)
row = constant_op.constant(np.array([[1., 2.0]]), dtype=dtypes.float32)
a = array_ops.repeat(row, repeats=[8], axis=0)
b = gen_array_ops.reverse_v2(a, axis=[1])
expected_result = func(a, b)
a = api.relayout(a, fully_sharded_layout_2d)
b = api.relayout(b, fully_sharded_layout_2d)
dtensor_result = func(a, b)
self.assertDTensorEqual(expected_result, Layout([_MESH_DIM_Y], mesh),
dtensor_result)
# TODO(b/188605096): also add a MixedPrecisionReduceScatter test
def testMixedPrecisionAllReduce(self):
has_enable_dtensor_mixed_precision_reduce = (
'DTENSOR_ENABLE_MIXED_PRECISION_REDUCE' in os.environ
)
has_dtensor_reduce_in_bfloat16_max_group_size = (
'DTENSOR_REDUCE_IN_BFLOAT16_MAX_GROUP_SIZE' in os.environ
)
if has_dtensor_reduce_in_bfloat16_max_group_size:
old_dtensor_reduce_in_bfloat16_max_group_size = os.environ[
'DTENSOR_REDUCE_IN_BFLOAT16_MAX_GROUP_SIZE']
os.environ['DTENSOR_ENABLE_MIXED_PRECISION_REDUCE'] = ''
os.environ['DTENSOR_REDUCE_IN_BFLOAT16_MAX_GROUP_SIZE'] = '4'
self.skipForDeviceType(['GPU'],
'GPUs do not support bfloat16 reduce')
self.skipForDeviceType(['TPU'],
'This test requires 8 TPU cores.',
unless_device_count_equals_to=8)
# Create and use an 8-device mesh just for this test. Mixed-precision
# AllReduce will be in effect since the reduction will be across 8 devices
# which is larger than the max group size flag value of 4.
global_ids = test_util.create_device_ids_array((8,))
local_ids = np.ravel(global_ids).tolist()
mesh_dict = {
device: layout_lib.Mesh([_MESH_DIM_X], global_ids, local_ids,
test_util.create_device_list((8,), device))
for device in ('CPU', 'GPU', 'TPU')
}
mesh = self.configTestMesh(mesh_dict)
replicated_layout_1d = Layout.replicated(mesh, rank=1)
first_dim_sharded_layout_1d = Layout.batch_sharded(
mesh, _MESH_DIM_X, rank=2)
@polymorphic_function.function
def func(x):
return math_ops.reduce_sum(x, axis=0)
# Reduce across 8 devices.
inp = constant_op.constant(
np.arange(48.).reshape((8, 6)), dtype=dtypes.bfloat16)
expected_result = np.sum(inp, axis=0)
inp_dtensor = api.relayout(inp, first_dim_sharded_layout_1d)
dtensor_result = func(inp_dtensor)
self.assertDTensorEqual(
expected_result, replicated_layout_1d, dtensor_result)
if not has_enable_dtensor_mixed_precision_reduce:
del os.environ['DTENSOR_ENABLE_MIXED_PRECISION_REDUCE']
if has_dtensor_reduce_in_bfloat16_max_group_size:
os.environ['DTENSOR_REDUCE_IN_BFLOAT16_MAX_GROUP_SIZE'] = (
old_dtensor_reduce_in_bfloat16_max_group_size
)
else:
del os.environ['DTENSOR_REDUCE_IN_BFLOAT16_MAX_GROUP_SIZE']
# Create two independent AllReduce ops with indirect dependency, that should
# not get combined.
def testAllReduceCombinerWithIndirectDependency(self):
# The purpose of this test is to validate the depdency check in AllReduce
# AllReduce combiner (dtensor_allreduce_combine_optimization). Specifically,
# the side effects from indirect dependency.
self.skipForDeviceType(['TPU'],
'This test requires 8 TPU cores.',
unless_device_count_equals_to=8)
# Create and use an eight-device mesh just for this test.
global_ids = test_util.create_device_ids_array((8,))
local_ids = np.ravel(global_ids).tolist()
mesh_dict = {
device: layout_lib.Mesh([_MESH_DIM_X], global_ids, local_ids,
test_util.create_device_list((8,), device))
for device in ('CPU', 'GPU', 'TPU')
}
mesh = self.configTestMesh(mesh_dict)
first_dim_sharded_layout_1d = Layout.batch_sharded(
mesh, _MESH_DIM_X, rank=1)
init_value = constant_op.constant(np.ones(32), dtype=dtypes.float32)
init_value = api.relayout(init_value, first_dim_sharded_layout_1d)
# 2nd reduction indrectly depend on the 1st reduction
@polymorphic_function.function
def func(v):
a = math_ops.reduce_sum(v)
v.assign_add(v+a)
b = math_ops.reduce_sum(v)
return b
v = d_variable.DVariable(init_value)
dtensor_result = func(v)
# Replicate the scenario above without using dtensor
expected_result = constant_op.constant(np.ones(32), dtype=dtypes.float32)
expected_result += expected_result + math_ops.reduce_sum(expected_result)
expected_result = math_ops.reduce_sum(expected_result)
self.assertDTensorEqual(
expected_result, Layout.replicated(mesh=mesh, rank=0), dtensor_result
)
if __name__ == '__main__':
test.main()
|
CollectiveTestWithCustomMesh
|
python
|
charliermarsh__ruff
|
crates/ruff_linter/resources/test/fixtures/pep8_naming/N802.py
|
{
"start": 852,
"end": 1023
}
|
class ____(BaseHTTPRequestHandler):
def do_GET(self):
pass
def dont_GET(self):
pass
from http.server import CGIHTTPRequestHandler
|
MyRequestHandler
|
python
|
cython__cython
|
Cython/Shadow.py
|
{
"start": 2536,
"end": 2721
}
|
class ____:
def __call__(self, x):
return x
def __enter__(self):
pass
def __exit__(self, exc_type, exc_value, traceback):
pass
|
_EmptyDecoratorAndManager
|
python
|
tensorflow__tensorflow
|
tensorflow/python/checkpoint/checkpoint_test.py
|
{
"start": 2665,
"end": 6197
}
|
class ____(test.TestCase):
@test_util.run_in_graph_and_eager_modes(assert_no_eager_garbage=True)
def testAddVariable(self):
obj = NonLayerTrackable()
with self.assertRaisesRegex(ValueError, "do not specify shape"):
trackable_utils.add_variable(
obj, name="shape_specified_twice", shape=[], initializer=1)
constant_initializer = trackable_utils.add_variable(
obj, name="constant_initializer", initializer=1)
with variable_scope.variable_scope("some_variable_scope"):
ones_initializer = trackable_utils.add_variable(
obj,
name="ones_initializer",
shape=[2],
initializer=init_ops.ones_initializer(dtype=dtypes.float32))
bare_initializer = trackable_utils.add_variable(
obj,
name="bare_initializer",
shape=[2, 2],
dtype=dtypes.float64,
initializer=init_ops.zeros_initializer)
# Even in graph mode, there are no naming conflicts between objects, only
# naming conflicts within an object.
other_duplicate = resource_variable_ops.ResourceVariable(
name="duplicate", initial_value=1.)
duplicate = trackable_utils.add_variable(
obj, name="duplicate", shape=[])
with self.assertRaisesRegex(ValueError, "'duplicate'.*already declared"):
trackable_utils.add_variable(obj, name="duplicate", shape=[])
self.evaluate(trackable_utils.gather_initializers(obj))
self.assertEqual("constant_initializer:0", constant_initializer.name)
self.assertEqual(1, self.evaluate(constant_initializer))
self.assertEqual("some_variable_scope/ones_initializer:0",
ones_initializer.name)
self.assertAllEqual([1, 1], self.evaluate(ones_initializer))
self.assertAllEqual([[0., 0.],
[0., 0.]], self.evaluate(bare_initializer))
self.assertEqual("a_variable:0", obj.a_variable.name)
self.assertEqual("duplicate:0", other_duplicate.name)
if context.executing_eagerly():
# When executing eagerly, there's no uniquification of variable names. The
# checkpoint name will be the same.
self.assertEqual("duplicate:0", duplicate.name)
else:
# The .name attribute may be globally influenced, but the checkpoint name
# won't be (tested below).
self.assertEqual("duplicate_1:0", duplicate.name)
expected_checkpoint_names = {
"a_variable/.ATTRIBUTES/VARIABLE_VALUE",
"bare_initializer/.ATTRIBUTES/VARIABLE_VALUE",
"constant_initializer/.ATTRIBUTES/VARIABLE_VALUE",
"duplicate/.ATTRIBUTES/VARIABLE_VALUE",
"ones_initializer/.ATTRIBUTES/VARIABLE_VALUE",
}
actual_checkpoint_names = _get_all_checkpoint_names(obj)
self.assertEqual(expected_checkpoint_names, set(actual_checkpoint_names))
def testInitNotCalled(self):
class NoInit(autotrackable.AutoTrackable):
def __init__(self):
pass
# __init__ for Trackable will be called implicitly.
trackable_utils.add_variable(NoInit(), "var", shape=[])
def testShapeDtype(self):
root = autotrackable.AutoTrackable()
v1 = trackable_utils.add_variable(
root, name="v1", initializer=3., dtype=dtypes.float64)
self.assertEqual(dtypes.float64, v1.dtype)
v2 = trackable_utils.add_variable(
root,
name="v2",
shape=[3],
initializer=init_ops.ones_initializer,
dtype=dtypes.float64)
self.assertEqual(dtypes.float64, v2.dtype)
self.assertAllEqual([1., 1., 1.], self.evaluate(v2))
|
InterfaceTests
|
python
|
sqlalchemy__sqlalchemy
|
test/base/test_utils.py
|
{
"start": 59652,
"end": 59722
}
|
class ____(IdentitySetTest):
obj_type = NoHash
|
NoHashIdentitySetTest
|
python
|
doocs__leetcode
|
lcof2/剑指 Offer II 059. 数据流的第 K 大数值/Solution.py
|
{
"start": 0,
"end": 437
}
|
class ____:
def __init__(self, k: int, nums: List[int]):
self.q = []
self.size = k
for num in nums:
self.add(num)
def add(self, val: int) -> int:
heappush(self.q, val)
if len(self.q) > self.size:
heappop(self.q)
return self.q[0]
# Your KthLargest object will be instantiated and called as such:
# obj = KthLargest(k, nums)
# param_1 = obj.add(val)
|
KthLargest
|
python
|
protocolbuffers__protobuf
|
python/google/protobuf/internal/proto_test.py
|
{
"start": 4152,
"end": 5083
}
|
class ____(unittest.TestCase):
def test_serialize_length_prefixed(self, message_module, expected):
number_of_messages = 3
out = io.BytesIO()
for index in range(0, number_of_messages):
msg = message_module.TestAllTypes(
optional_int32=index, optional_string='hi'
)
proto.serialize_length_prefixed(msg, out)
self.assertEqual(out.getvalue(), expected)
def test_parse_length_prefixed(self, message_module, input_bytes):
expected_number_of_messages = 3
input_io = io.BytesIO(input_bytes)
index = 0
while True:
msg = proto.parse_length_prefixed(message_module.TestAllTypes, input_io)
if msg is None:
break
self.assertEqual(msg.optional_int32, index)
self.assertEqual(msg.optional_string, 'hi')
index += 1
self.assertEqual(index, expected_number_of_messages)
if __name__ == '__main__':
unittest.main()
|
LengthPrefixedWithGolden
|
python
|
dagster-io__dagster
|
python_modules/libraries/dagster-azure/dagster_azure/blob/compute_log_manager.py
|
{
"start": 1132,
"end": 16735
}
|
class ____(TruncatingCloudStorageComputeLogManager, ConfigurableClass):
"""Logs op compute function stdout and stderr to Azure Blob Storage.
This is also compatible with Azure Data Lake Storage.
Users should not instantiate this class directly. Instead, use a YAML block in ``dagster.yaml``. Examples provided below
will show how to configure with various credentialing schemes.
Args:
storage_account (str): The storage account name to which to log.
container (str): The container (or ADLS2 filesystem) to which to log.
secret_credential (Optional[dict]): Secret credential for the storage account. This should be
a dictionary with keys `client_id`, `client_secret`, and `tenant_id`.
access_key_or_sas_token (Optional[str]): Access key or SAS token for the storage account.
default_azure_credential (Optional[dict]): Use and configure DefaultAzureCredential.
Cannot be used with sas token or secret key config.
local_dir (Optional[str]): Path to the local directory in which to stage logs. Default:
``dagster_shared.seven.get_system_temp_directory()``.
prefix (Optional[str]): Prefix for the log file keys.
upload_interval (Optional[int]): Interval in seconds to upload partial log files blob storage. By default, will only upload when the capture is complete.
show_url_only (bool): Only show the URL of the log file in the UI, instead of fetching and displaying the full content. Default False.
inst_data (Optional[ConfigurableClassData]): Serializable representation of the compute
log manager when newed up from config.
Examples:
Using an Azure Blob Storage account with an `AzureSecretCredential <https://learn.microsoft.com/en-us/python/api/azure-identity/azure.identity.clientsecretcredential?view=azure-python>`_:
.. code-block:: YAML
compute_logs:
module: dagster_azure.blob.compute_log_manager
class: AzureBlobComputeLogManager
config:
storage_account: my-storage-account
container: my-container
secret_credential:
client_id: my-client-id
client_secret: my-client-secret
tenant_id: my-tenant-id
prefix: "dagster-test-"
local_dir: "/tmp/cool"
upload_interval: 30
show_url_only: false
Using an Azure Blob Storage account with a `DefaultAzureCredential <https://learn.microsoft.com/en-us/python/api/azure-identity/azure.identity.defaultazurecredential?view=azure-python>`_:
.. code-block:: YAML
compute_logs:
module: dagster_azure.blob.compute_log_manager
class: AzureBlobComputeLogManager
config:
storage_account: my-storage-account
container: my-container
default_azure_credential:
exclude_environment_credential: false
prefix: "dagster-test-"
local_dir: "/tmp/cool"
upload_interval: 30
show_url_only: false
Using an Azure Blob Storage account with an access key:
.. code-block:: YAML
compute_logs:
module: dagster_azure.blob.compute_log_manager
class: AzureBlobComputeLogManager
config:
storage_account: my-storage-account
container: my-container
access_key_or_sas_token: my-access-key
prefix: "dagster-test-"
local_dir: "/tmp/cool"
upload_interval: 30
show_url_only: false
"""
def __init__(
self,
storage_account: str,
container: str,
secret_credential: Optional[dict] = None,
local_dir: Optional[str] = None,
inst_data: Optional[ConfigurableClassData] = None,
prefix: str = "dagster",
upload_interval: Optional[int] = None,
default_azure_credential: Optional[dict] = None,
access_key_or_sas_token: Optional[str] = None,
show_url_only: bool = False,
):
self._show_url_only = check.bool_param(show_url_only, "show_url_only")
self._storage_account = check.str_param(storage_account, "storage_account")
self._container = check.str_param(container, "container")
self._blob_prefix = self._clean_prefix(check.str_param(prefix, "prefix"))
self._default_azure_credential = check.opt_dict_param(
default_azure_credential, "default_azure_credential"
)
self._access_key_or_sas_token = check.opt_str_param(
access_key_or_sas_token, "access_key_or_sas_token"
)
check.opt_dict_param(secret_credential, "secret_credential")
check.opt_dict_param(default_azure_credential, "default_azure_credential")
if secret_credential is not None:
self._blob_client = create_blob_client(
storage_account, ClientSecretCredential(**secret_credential)
)
elif self._access_key_or_sas_token:
self._blob_client = create_blob_client(storage_account, self._access_key_or_sas_token)
else:
credential = DefaultAzureCredential(**self._default_azure_credential)
self._blob_client = create_blob_client(storage_account, credential)
self._container_client = self._blob_client.get_container_client(container)
self._download_urls = {}
# proxy calls to local compute log manager (for subscriptions, etc)
base_dir: str = local_dir if local_dir else seven.get_system_temp_directory()
self._local_manager = LocalComputeLogManager(base_dir)
self._subscription_manager = PollingComputeLogSubscriptionManager(self)
self._upload_interval = check.opt_int_param(upload_interval, "upload_interval")
self._inst_data = check.opt_inst_param(inst_data, "inst_data", ConfigurableClassData)
super().__init__()
@property
def inst_data(self) -> Optional[ConfigurableClassData]:
return self._inst_data
@classmethod
def config_type(cls):
return {
"storage_account": StringSource,
"container": StringSource,
"access_key_or_sas_token": Field(Noneable(StringSource), is_required=False),
"secret_credential": Field(
Noneable(
Shape(
{
"client_id": StringSource,
"client_secret": StringSource,
"tenant_id": StringSource,
}
),
),
is_required=False,
),
"default_azure_credential": Field(
Noneable(Permissive(description="keyword arguments for DefaultAzureCredential")),
is_required=False,
default_value=None,
),
"local_dir": Field(Noneable(StringSource), is_required=False, default_value=None),
"prefix": Field(StringSource, is_required=False, default_value="dagster"),
"upload_interval": Field(Noneable(int), is_required=False, default_value=None),
"show_url_only": Field(bool, is_required=False, default_value=False),
}
@classmethod
def from_config_value(
cls, inst_data: ConfigurableClassData, config_value: Mapping[str, Any]
) -> Self:
return cls(inst_data=inst_data, **config_value)
@property
def local_manager(self) -> LocalComputeLogManager:
return self._local_manager
@property
def upload_interval(self) -> Optional[int]:
return self._upload_interval if self._upload_interval else None
def _clean_prefix(self, prefix: str) -> str:
parts = prefix.split("/")
return "/".join([part for part in parts if part])
def _resolve_path_for_namespace(self, namespace: Sequence[str]) -> Sequence[str]:
return [self._blob_prefix, "storage", *namespace]
def _blob_key(self, log_key: Sequence[str], io_type: ComputeIOType, partial=False) -> str:
check.inst_param(io_type, "io_type", ComputeIOType)
extension = IO_TYPE_EXTENSION[io_type]
[*namespace, filebase] = log_key
filename = f"{filebase}.{extension}"
if partial:
filename = f"{filename}.partial"
paths = [*self._resolve_path_for_namespace(namespace), filename]
return "/".join(paths) # blob path delimiter
def delete_logs(
self, log_key: Optional[Sequence[str]] = None, prefix: Optional[Sequence[str]] = None
):
self.local_manager.delete_logs(log_key=log_key, prefix=prefix)
if log_key:
prefix_path = "/".join([self._blob_prefix, "storage", *log_key])
elif prefix:
# add the trailing '/' to make sure that ['a'] does not match ['apple']
prefix_path = "/".join([self._blob_prefix, "storage", *prefix, ""])
else:
prefix_path = None
blob_list = {
b.name for b in list(self._container_client.list_blobs(name_starts_with=prefix_path))
}
to_remove = None
if log_key:
# filter to the known set of keys
known_keys = [
self._blob_key(log_key, ComputeIOType.STDOUT),
self._blob_key(log_key, ComputeIOType.STDERR),
self._blob_key(log_key, ComputeIOType.STDOUT, partial=True),
self._blob_key(log_key, ComputeIOType.STDERR, partial=True),
]
to_remove = [key for key in known_keys if key in blob_list]
elif prefix:
to_remove = list(blob_list)
else:
check.failed("Must pass in either `log_key` or `prefix` argument to delete_logs")
if to_remove:
self._container_client.delete_blobs(*to_remove)
def download_url_for_type(
self, log_key: Sequence[str], io_type: ComputeIOType
) -> Optional[str]:
if not self.is_capture_complete(log_key):
return None
blob_key = self._blob_key(log_key, io_type)
if blob_key in self._download_urls:
return self._download_urls[blob_key]
blob = self._container_client.get_blob_client(blob_key)
user_delegation_key = None
account_key = None
if hasattr(self._blob_client.credential, "account_key"):
account_key = self._blob_client.credential.account_key
else:
user_delegation_key = self._request_user_delegation_key(self._blob_client)
sas = generate_blob_sas(
self._storage_account,
self._container,
blob_key,
account_key=account_key,
user_delegation_key=user_delegation_key,
expiry=datetime.now() + timedelta(hours=6),
permission=BlobSasPermissions(read=True),
)
url = blob.url + "?" + sas
self._download_urls[blob_key] = url
return url
def _get_shell_cmd_for_type(self, log_key: Sequence[str], io_type: ComputeIOType):
blob_key = self._blob_key(log_key, io_type)
return f"az storage blob download --auth-mode login --account-name {self._storage_account} --container-name {self._container} --name {blob_key}"
@contextmanager
def capture_logs(self, log_key: Sequence[str]) -> Iterator[CapturedLogContext]:
with super().capture_logs(log_key) as local_context:
if not self._show_url_only:
yield local_context
else:
out_key = self._blob_key(log_key, ComputeIOType.STDOUT)
err_key = self._blob_key(log_key, ComputeIOType.STDERR)
azure_base_url = self._container_client.url
out_url = f"{azure_base_url}/{out_key}"
err_url = f"{azure_base_url}/{err_key}"
yield CapturedLogContext(
local_context.log_key,
external_stdout_url=out_url,
external_stderr_url=err_url,
shell_cmd=LogRetrievalShellCommand(
stdout=self._get_shell_cmd_for_type(log_key, ComputeIOType.STDOUT),
stderr=self._get_shell_cmd_for_type(log_key, ComputeIOType.STDERR),
),
)
def _request_user_delegation_key(
self,
blob_service_client: BlobServiceClient,
) -> UserDelegationKey:
"""Creates user delegation key when a service principal is used or other authentication other than
account key.
"""
# Get a user delegation key that's valid for 1 day
delegation_key_start_time = datetime.now(timezone.utc)
delegation_key_expiry_time = delegation_key_start_time + timedelta(days=1)
user_delegation_key = blob_service_client.get_user_delegation_key(
key_start_time=delegation_key_start_time,
key_expiry_time=delegation_key_expiry_time,
)
return user_delegation_key
def display_path_for_type(self, log_key: Sequence[str], io_type: ComputeIOType) -> str:
if not self.is_capture_complete(log_key):
return self.local_manager.get_captured_local_path(log_key, IO_TYPE_EXTENSION[io_type])
blob_key = self._blob_key(log_key, io_type)
return f"https://{self._storage_account}.blob.core.windows.net/{self._container}/{blob_key}"
def cloud_storage_has_logs(
self, log_key: Sequence[str], io_type: ComputeIOType, partial: bool = False
) -> bool:
blob_key = self._blob_key(log_key, io_type, partial=partial)
blob_objects = self._container_client.list_blobs(blob_key)
exact_matches = [blob for blob in blob_objects if blob.name == blob_key]
return len(exact_matches) > 0
def _upload_file_obj(
self, data: IO[bytes], log_key: Sequence[str], io_type: ComputeIOType, partial=False
):
blob_key = self._blob_key(log_key, io_type, partial=partial)
blob = self._container_client.get_blob_client(blob_key)
blob.upload_blob(data, **{"overwrite": partial}) # type: ignore
def download_from_cloud_storage(
self, log_key: Sequence[str], io_type: ComputeIOType, partial=False
):
path = self.local_manager.get_captured_local_path(
log_key, IO_TYPE_EXTENSION[io_type], partial=partial
)
ensure_dir(os.path.dirname(path))
blob_key = self._blob_key(log_key, io_type, partial=partial)
with open(path, "wb") as fileobj:
blob = self._container_client.get_blob_client(blob_key)
blob.download_blob().readinto(fileobj)
def get_log_keys_for_log_key_prefix(
self, log_key_prefix: Sequence[str], io_type: ComputeIOType
) -> Sequence[Sequence[str]]:
directory = self._resolve_path_for_namespace(log_key_prefix)
blobs = self._container_client.list_blobs(name_starts_with="/".join(directory))
results = []
list_key_prefix = list(log_key_prefix)
for blob in blobs:
full_key = blob.name
filename, blob_io_type = full_key.split("/")[-1].split(".")
if blob_io_type != IO_TYPE_EXTENSION[io_type]:
continue
results.append(list_key_prefix + [filename])
return results
def on_subscribe(self, subscription):
self._subscription_manager.add_subscription(subscription)
def on_unsubscribe(self, subscription):
self._subscription_manager.remove_subscription(subscription)
|
AzureBlobComputeLogManager
|
python
|
kamyu104__LeetCode-Solutions
|
Python/count-number-of-possible-root-nodes.py
|
{
"start": 2495,
"end": 3313
}
|
class ____(object):
def rootCount(self, edges, guesses, k):
"""
:type edges: List[List[int]]
:type guesses: List[List[int]]
:type k: int
:rtype: int
"""
cnt = [0]
def memoization(u, p):
if (u, p) not in memo:
memo[u, p] = int((p, u) in lookup)
for v in adj[u]:
if v == p:
continue
cnt[0] += 1
memo[u, p] += memoization(v, u)
return memo[u, p]
adj = collections.defaultdict(list)
for u, v in edges:
adj[u].append(v)
adj[v].append(u)
lookup = {(u, v) for u, v in guesses}
memo = {}
return sum(memoization(i, -1) >= k for i in adj.iterkeys())
|
Solution3
|
python
|
walkccc__LeetCode
|
solutions/2214. Minimum Health to Beat Game/2214.py
|
{
"start": 0,
"end": 134
}
|
class ____:
def minimumHealth(self, damage: list[int], armor: int) -> int:
return 1 + sum(damage) - min(max(damage), armor)
|
Solution
|
python
|
google__jax
|
tests/mesh_utils_test.py
|
{
"start": 7687,
"end": 28986
}
|
class ____(test_util.JaxTestCase):
@parameterized.named_parameters(
('1x2x1_t', (1, 2, 1), True),
('4x4x4_t', (4, 4, 4), True),
('4x4x4_f', (4, 4, 4), False),
('8x8x16_t', (8, 8, 16), True),
('8x8x16_f', (8, 8, 16), False),
)
def test_get_physical_tpu_mesh(self, xyz, reorder):
x, y, z = xyz
jax_devices = mock_tpu_devices(x, y, z, 'TPU v4', True, reorder=reorder)
normalized = mesh_utils._get_physical_tpu_mesh(jax_devices)
self.assertEqual(normalized.shape, xyz)
# major_to_minor: x, y, z
for i in range(x):
for j in range(y):
for k in range(z):
self.assertEqual(normalized[i, j, k].coords, (i, j, k))
def test_get_physical_tpu_mesh_with_subslice_TPU_v2_1x1(self):
one_device_per_chip = False # Each TPU v2 chip has 2 devices.
device_list = mock_tpu_devices(1, 1, 1, 'TPU v2', one_device_per_chip)
device_array = mesh_utils._get_physical_tpu_mesh(device_list)
self.assertEqual(device_array.shape, (1, 1, 2))
# A subslice that includes the device at (0, 0, 0): core #0 of the
# device at (x, y, z) == (0, 0, 0).
subslice0 = mesh_utils._get_physical_tpu_mesh([device_array[0, 0, 0]])
self.assertEqual(subslice0.shape, (1, 1, 1))
self.assertEqual(subslice0[0, 0, 0], device_array[0, 0, 0])
self.assertEqual(subslice0[0, 0, 0].coords, (0, 0, 0))
self.assertEqual(subslice0[0, 0, 0].core_on_chip, 0)
# Another subsublice, without the device at (0, 0, 0): core #1 of
# the device at (x, y, z) == (0, 0, 0).
subslice1 = mesh_utils._get_physical_tpu_mesh([device_array[0, 0, 1]])
self.assertEqual(subslice1.shape, (1, 1, 1))
self.assertEqual(subslice1[0, 0, 0], device_array[0, 0, 1])
self.assertEqual(subslice1[0, 0, 0].coords, (0, 0, 0))
self.assertEqual(subslice1[0, 0, 0].core_on_chip, 1)
def test_get_physical_tpu_mesh_with_subslice_TPU_v4_1x2x1(self):
one_device_per_chip = True # For TPU v4, chip == device.
device_list = mock_tpu_devices(1, 2, 1, 'TPU v4', one_device_per_chip)
device_array = mesh_utils._get_physical_tpu_mesh(device_list)
self.assertEqual(device_array.shape, (1, 2, 1))
# A subslice that includes the device at (0, 0, 0).
subslice0 = mesh_utils._get_physical_tpu_mesh([device_array[0, 0, 0]])
self.assertEqual(subslice0.shape, (1, 1, 1))
self.assertEqual(subslice0[0, 0, 0], device_array[0, 0, 0])
# Another subsublice, without the device at (0, 0, 0).
subslice1 = mesh_utils._get_physical_tpu_mesh([device_array[0, 1, 0]])
self.assertEqual(subslice1.shape, (1, 1, 1))
self.assertEqual(subslice1[0, 0, 0], device_array[0, 1, 0])
def test_get_physical_tpu_mesh_with_subslice_TPU_v5e_4x4(self):
one_device_per_chip = True # For TPU v5e, chip == device.
device_list = mock_tpu_devices(4, 4, 1, 'TPU v5e', one_device_per_chip)
device_array = mesh_utils._get_physical_tpu_mesh(device_list)
# `device_array` is isomorphic with a 4x4 grid (z coord == 0).
self.assertEqual(device_array.shape, (4, 4, 1))
# Two subslices: each subslice has shape (4, 2); first one starts
# at (x=0, y=0), the other at (x=0, y=2); visually, the left
# and right halves of the (4, 4) grid.
for start_y in (0, 2):
subslice_devices = []
for x in range(4):
for delta_y in range(2):
subslice_devices.append(device_array[x, start_y + delta_y, 0])
logging.info(
'start_y=%s subslice_devices=%s', start_y, subslice_devices
)
subslice = mesh_utils._get_physical_tpu_mesh(subslice_devices)
self.assertEqual(subslice.shape, (4, 2, 1))
for x in range(4):
for delta_y in range(2):
self.assertEqual(
subslice[x, delta_y],
device_array[x, start_y + delta_y, 0],
)
def test_get_physical_tpu_mesh_with_bad_subslice(self):
one_device_per_chip = True # For TPU v5e, chip == device.
device_list = mock_tpu_devices(4, 4, 1, 'TPU v5e', one_device_per_chip)
device_array = mesh_utils._get_physical_tpu_mesh(device_list)
self.assertEqual(device_array.shape, (4, 4, 1))
# Second subslice from
# test_get_physical_tpu_mesh_with_subslice_TPU_v5e_4x4, without
# the device from its top-left corner (device from (0, 2, 0)).
start_y = 2
subslice_devices = []
for x in range(4):
for delta_y in range(2):
if (x == 0) and (delta_y == 0):
# Skip device from (0, 2, 0).
continue
subslice_devices.append(device_array[x, start_y + delta_y, 0])
# subslice_devices are obviously not a cuboid: only 7 devices.
with self.assertRaises(AssertionError):
mesh_utils._get_physical_tpu_mesh(subslice_devices)
# Make it a bit harder, such that just a simple test on
# len(subslice_devices) is not enough: 8 devices, but two of them
# are identical (device from (2, 2, 0) is duplicated.
subslice_devices.append(device_array[2, 2, 0])
with self.assertRaisesRegex(AssertionError, 'not a contiguous cuboid'):
mesh_utils._get_physical_tpu_mesh(subslice_devices)
@parameterized.named_parameters(
('2x2x1', mock_2x2x1_devices, [1, 1, 4], [(), (), (0, 1, 2)]),
('2x2x4', mock_2x2x4_devices, [1, 4, 4], [(), (2,), (0, 1)]),
('4x4x4', mock_4x4x4_devices, [1, 16, 4], [(), (1, 2), (0,)]),
('4x4x8a', mock_4x4x8_devices, [1, 16, 8], [(), (0, 1), (2,)]),
('4x4x8b', mock_4x4x8_devices, [1, 8, 16], [(), (2,), (0, 1)]),
('4x4x8c', mock_4x4x8_devices, [16, 8, 1], [(0, 1), (2,), ()]),
('4x8x8', mock_4x8x8_devices, [1, 32, 8], [(), (0, 2), (1,)]),
('8x8x8', mock_8x8x8_devices, [1, 64, 8], [(), (1, 2), (0,)]),
('8x8x16', mock_8x8x16_devices, [1, 64, 16], [(), (0, 1), (2,)]),
('8x8', mock_8x8_devices, [8, 8], [(1,), (0, 2)]),
)
def test_create_device_mesh_for_nd_torus(
self, devices, mesh_shape, expected_assignment
):
jax_devices = devices(True)
physical_mesh = mesh_utils._get_physical_tpu_mesh(jax_devices)
_, assignment = mesh_utils._create_device_mesh_for_nd_torus(
physical_mesh, mesh_shape
)
# The expected assignment is specified as a list, where each element is a
# sequence of physical axis assigned. We convert this into assignment
# matrix.
expected_assignment_matrix = np.ones(
[physical_mesh.ndim, len(mesh_shape)], dtype=np.int64
)
for logical_axis, axis_assignment in enumerate(expected_assignment):
for physical_axis in axis_assignment:
expected_assignment_matrix[physical_axis, logical_axis] = (
physical_mesh.shape[physical_axis]
)
self.assertArraysEqual(assignment, expected_assignment_matrix)
def test_create_device_mesh_non_int_error(self):
with self.assertRaisesRegex(
ValueError,
"`mesh_shape` passed to `create_device_mesh` should be a sequence of ints"):
mesh_utils.create_device_mesh(((4,), 4))
@parameterized.named_parameters(
('2x2x1', mock_2x2x1_devices,),
('2x2x4', mock_2x2x4_devices, ),
('4x4x4', mock_4x4x4_devices,),
('4x4x8', mock_4x4x8_devices,),
('4x8x8', mock_4x8x8_devices, ),
('8x8', mock_8x8_devices),
)
def test_create_device_mesh_has_computable_global_shape(self, devices):
def factorize(n, max_factors=3):
if max_factors == 1 or n == 1:
yield (n, ) * max_factors
return
for i in range(2, n+1):
if n % i == 0:
for remaining in factorize(n // i, max_factors=max_factors - 1):
yield (i, *remaining)
jax_devices = devices(True)
for mesh_shape in factorize(len(jax_devices), max_factors=3):
mesh = mesh_utils.create_device_mesh(mesh_shape, devices=jax_devices,
allow_split_physical_axes=True)
mesh = mesh_lib.Mesh(mesh, ('a', 'b', 'c'))
sharding = NamedSharding(mesh, PartitionSpec('a', 'b', 'c'))
computed_global_shape = local_to_global_shape(sharding, (1, 1, 1))
self.assertFalse(
np.any([x is None for x in computed_global_shape]),
f'{mesh_shape=}, {computed_global_shape=} is not uniform')
sharding = NamedSharding(mesh, PartitionSpec(('a', 'c',), 'b'))
computed_global_shape = local_to_global_shape(sharding, (1, 1, 1))
self.assertFalse(
np.any([x is None for x in computed_global_shape]),
f'{mesh_shape=}, {computed_global_shape=} is not uniform')
@parameterized.named_parameters(
('2x2x1', mock_2x2x1_devices, [1, 1, 4], [(), (), (0, 1, 2)]),
('2x2x4', mock_2x2x4_devices, [1, 4, 4], [(), (2,), (0, 1)]),
('4x4x4', mock_4x4x4_devices, [1, 16, 4], [(), (1, 2), (0,)]),
('4x4x8a', mock_4x4x8_devices, [1, 16, 8], [(), (0, 1), (2,)]),
('4x4x8b', mock_4x4x8_devices, [1, 8, 16], [(), (2,), (0, 1)]),
('4x4x8c', mock_4x4x8_devices, [16, 8, 1], [(0, 1), (2,), ()]),
('4x8x8', mock_4x8x8_devices, [1, 32, 8], [(), (0, 2), (1,)]),
('8x8x8', mock_8x8x8_devices, [1, 64, 8], [(), (1, 2), (0,)]),
('8x8x16', mock_8x8x16_devices, [1, 64, 16], [(), (0, 1), (2,)]),
('8x8', mock_8x8_devices, [8, 8], [(1,), (0, 2)]),
)
def test_create_device_mesh_for_nd_torus_split_axes_backward_compatible(
self, devices, mesh_shape, expected_assignment
):
jax_devices = devices(True)
physical_mesh = mesh_utils._get_physical_tpu_mesh(jax_devices)
_, assignment = mesh_utils._create_device_mesh_for_nd_torus_splitting_axes(
physical_mesh, mesh_shape
)
# The expected assignment is specified as a list, where each element is a
# sequence of physical axis assigned. We convert this into assignment
# matrix.
expected_assignment_matrix = np.ones(
[physical_mesh.ndim, len(mesh_shape)], dtype=np.int64
)
for logical_axis, axis_assignment in enumerate(expected_assignment):
for physical_axis in axis_assignment:
expected_assignment_matrix[physical_axis, logical_axis] = (
physical_mesh.shape[physical_axis]
)
self.assertArraysEqual(assignment, expected_assignment_matrix)
@parameterized.named_parameters(
(
'4x4x4a',
mock_4x4x4_devices,
[2, 1, 32],
[
[1, 1, 4],
[1, 1, 4],
[2, 1, 2],
],
),
(
'4x4x4b',
mock_4x4x4_devices,
[8, 8, 1],
[
[1, 4, 1],
[2, 2, 1],
[4, 1, 1],
],
),
(
'4x4x8a',
mock_4x4x8_devices,
[2, 2, 8, 4],
[
[1, 1, 1, 4],
[2, 2, 1, 1],
[1, 1, 8, 1],
],
),
(
'4x4x8b',
mock_4x4x8_devices,
[2, 4, 1, 16],
[
[1, 1, 1, 4],
[1, 1, 1, 4],
[2, 4, 1, 1],
],
),
(
'4x8x8',
mock_4x8x8_devices,
[1, 128, 2],
[
[1, 2, 2],
[1, 8, 1],
[1, 8, 1],
],
),
(
'8x8',
mock_8x8_devices,
[2, 1, 32, 1],
[
[1, 1, 8, 1],
[2, 1, 4, 1],
[1, 1, 1, 1],
],
),
)
def test_create_device_mesh_for_nd_torus_split_axes_can_handle_axes_split(
self, devices, mesh_shape, assignment_matrix
):
jax_devices = devices(True)
physical_mesh = mesh_utils._get_physical_tpu_mesh(jax_devices)
logical_mesh, assignment = mesh_utils._create_device_mesh_for_nd_torus(
physical_mesh, mesh_shape, allow_split_physical_axes=True
)
self.assertEqual(logical_mesh.shape, tuple(mesh_shape))
self.assertArraysEqual(
assignment, np.array(assignment_matrix, dtype=np.int64)
)
@parameterized.named_parameters(
('2X4x4x4a', (1, 16, 4), (2, 1, 1)),
('2X4x4x4b', (1, 4, 16), (1, 2, 1)),
)
def test_create_hybrid_device_mesh(self, mesh_shape, dcn_mesh_shape):
devices = mock_tpu_devices(4, 4, 4, 'TPU v4', True, 2)
mesh = mesh_utils.create_hybrid_device_mesh(
mesh_shape, dcn_mesh_shape, devices)
total_mesh_shape = tuple(
m1 * m2 for m1, m2 in zip(mesh_shape, dcn_mesh_shape))
self.assertEqual(mesh.shape, total_mesh_shape)
@parameterized.named_parameters(
('2X4x4x4a', (1, 16, 4), (2, 1, 1)),
('2X4x4x4b', (1, 4, 16), (1, 2, 1)),
)
def test_create_hybrid_device_mesh_device_sorting(
self,
mesh_shape: tuple[int, ...],
dcn_mesh_shape: tuple[int, ...],
):
devices = mock_tpu_devices(4, 4, 4, 'TPU v4', True, 2)
reversed_slices_devices = list(
np.flip(np.array(devices).reshape(2, -1), axis=0).flat)
mesh = mesh_utils.create_hybrid_device_mesh(
mesh_shape,
dcn_mesh_shape,
devices,
should_sort_granules_by_key=False,
)
sorted_slices_mesh = mesh_utils.create_hybrid_device_mesh(
mesh_shape,
dcn_mesh_shape,
reversed_slices_devices,
should_sort_granules_by_key=True,
)
np.testing.assert_array_equal(mesh, sorted_slices_mesh)
self.assertSetEqual(
{0, 1},
{d.slice_index for d in sorted_slices_mesh.flat},
)
reversed_slices_mesh = mesh_utils.create_hybrid_device_mesh(
mesh_shape,
dcn_mesh_shape,
reversed_slices_devices,
should_sort_granules_by_key=False,
)
self.assertSetEqual(
{1, 0},
{d.slice_index for d in reversed_slices_mesh.flat},
)
@parameterized.named_parameters(
# Physical ring order over tray
('2x2_1d', mock_2x2_devices, [8], [0, 1, 2, 3, 6, 7, 4, 5]),
# Reshaped physical ring order over tray
('2x2_2d', mock_2x2_devices, [2, 4], [[0, 1, 2, 3],
[6, 7, 4, 5]]),
# 4 per-tray rings
('4x4_2d', mock_4x4_devices, [4, 8], [[ 0, 1, 2, 3, 10, 11, 8, 9],
[ 4, 5, 6, 7, 14, 15, 12, 13],
[16, 17, 18, 19, 26, 27, 24, 25],
[20, 21, 22, 23, 30, 31, 28, 29]]),
)
def test_v3_create_device_mesh(self, devices, mesh_shape,
expected_device_id_mesh):
global_devices = devices()
mesh = mesh_utils.create_device_mesh(
mesh_shape, devices=global_devices, contiguous_submeshes=False)
device_id_mesh = np.vectorize(lambda d: d.id)(mesh)
self.assertAllClose(np.array(expected_device_id_mesh), device_id_mesh)
@parameterized.named_parameters(
# Ring order over tray
('4x2_1d', mock_4x2_v5e_devices, [8], [0, 1, 2, 3, 7, 6, 5, 4]),
# Iota order
('2x2x2_1d', mock_2x2x2_v5e_devices, [8], [0, 4, 2, 6, 1, 5, 3, 7]),
)
def test_v5e_create_device_mesh(self, devices, mesh_shape,
expected_device_id_mesh):
global_devices = devices()
mesh = mesh_utils.create_device_mesh(
mesh_shape, devices=global_devices, contiguous_submeshes=False)
device_id_mesh = np.vectorize(lambda d: d.id)(mesh)
self.assertAllClose(np.array(expected_device_id_mesh), device_id_mesh)
def _assert_contiguous_submeshes(self, global_device_mesh):
global_mesh = Mesh(global_device_mesh, list(range(global_device_mesh.ndim)))
max_process_index = max(d.process_index
for d in global_device_mesh.flatten())
for p_idx in range(max_process_index + 1):
# Raises an error if non-contiguous
global_mesh._local_mesh(p_idx)
def test_create_contiguous_submeshes_for_tpu_v4(self):
v4 = mesh_utils._TPU_V4
for topology, mesh_shapes in mesh_utils._TRANSPOSE_TRICKS.items():
logging.vlog(1, "topology: %s", topology)
devices = mock_tpu_devices(topology[0], topology[1], topology[2], v4,
one_device_per_chip=True)
for mesh_shape in mesh_shapes:
logging.vlog(1, " mesh_shape: %s", mesh_shape)
mesh = mesh_utils.create_device_mesh(
mesh_shape, devices=devices, contiguous_submeshes=True)
self._assert_contiguous_submeshes(mesh)
def test_create_contiguous_submeshes_for_tpu_v4_leading_1_dims(self):
v4 = mesh_utils._TPU_V4
for topology, mesh_shapes in mesh_utils._TRANSPOSE_TRICKS.items():
logging.vlog(1, "topology: %s", topology)
devices = mock_tpu_devices(topology[0], topology[1], topology[2], v4,
one_device_per_chip=True)
for mesh_shape in mesh_shapes:
logging.vlog(1, ' mesh_shape: %s', (1, 1) + mesh_shape + (1, 1))
mesh = mesh_utils.create_device_mesh(
(1, 1) + mesh_shape + (1, 1),
devices=devices,
contiguous_submeshes=True)
self._assert_contiguous_submeshes(mesh)
def test_create_contiguous_submeshes_errors(self):
v4 = mesh_utils._TPU_V4
topology = (4, 4, 8)
mesh_shape = (1, 16, 8)
devices = mock_tpu_devices(topology[0], topology[1], topology[2], v4,
one_device_per_chip=True)
with self.assertRaisesWithLiteralMatch(
ValueError,
"create_device_mesh cannot create contiguous submeshes for "
"physical mesh topology (4, 4, 8)"):
mesh_utils.create_device_mesh(
mesh_shape, devices=devices, contiguous_submeshes=True)
topology = (4, 8, 8)
mesh_shape = (1, 128, 2)
devices = mock_tpu_devices(topology[0], topology[1], topology[2], v4,
one_device_per_chip=True)
with self.assertRaisesWithLiteralMatch(
ValueError,
"create_device_mesh cannot create contiguous submeshes for mesh_shape "
"(1, 128, 2) and physical mesh topology (4, 8, 8). "
'Available mesh_shapes: [(64, 4), (4, 64)]'):
mesh_utils.create_device_mesh(
mesh_shape, devices=devices, contiguous_submeshes=True
)
@parameterized.named_parameters(
# <-logical-> <-physical->
('1x1x2', [1, 1, 2], [1, 1, 1], [[[0, 1]]]),
('2x1x4', [2, 1, 4], [2, 2, 1], [[[0, 1, 2, 3]], [[6, 7, 4, 5]]]),
('4x1x2', [4, 1, 2], [2, 2, 1], [[[0, 1]], [[2, 3]], [[6, 7]], [[4, 5]]]),
('4x2x2', [4, 2, 2], [2, 2, 2], [[[0, 1], [2, 3]],
[[6, 7], [4, 5]],
[[8, 9], [10, 11]],
[[14, 15], [12, 13]]]),
('8x2', [2, 8], [2, 2, 2], [[0, 1, 2, 3, 6, 7, 4, 5],
[8, 9, 10, 11, 14, 15, 12, 13]]),
('4x4x2', [4, 4, 2], [2, 2, 4], [[[0, 1], [2, 3],
[6, 7], [4, 5]],
[[8, 9], [10, 11],
[14, 15], [12, 13]],
[[16, 17], [18, 19],
[22, 23], [20, 21]],
[[24, 25], [26, 27],
[30, 31], [28, 29]]]),
('4x2x4', [4, 2, 4], [2, 2, 4], [[[0, 1, 2, 3], [6, 7, 4, 5]],
[[8, 9, 10, 11], [14, 15, 12, 13]],
[[16, 17, 18, 19], [22, 23, 20, 21]],
[[24, 25, 26, 27], [30, 31, 28, 29]]]),
('8x4', [8, 4], [2, 2, 4], [[0, 1, 2, 3], [6, 7, 4, 5],
[8, 9, 10, 11], [14, 15, 12, 13],
[16, 17, 18, 19], [22, 23, 20, 21],
[24, 25, 26, 27], [30, 31, 28, 29]]),
('4x8', [4, 8], [2, 2, 4], [[0, 1, 2, 3, 6, 7, 4, 5],
[8, 9, 10, 11, 14, 15, 12, 13],
[16, 17, 18, 19, 22, 23, 20, 21],
[24, 25, 26, 27, 30, 31, 28, 29]]),
)
def test_v7x_create_device_mesh(
self, logical_mesh_shape, physical_mesh_shape, expected_device_id_mesh
):
global_devices = mock_tpu_devices(
physical_mesh_shape[0],
physical_mesh_shape[1],
physical_mesh_shape[2],
mesh_utils._TPU_7X,
one_device_per_chip=False,
)
mesh = mesh_utils.create_device_mesh(
logical_mesh_shape, devices=global_devices, contiguous_submeshes=False
)
device_id_mesh = np.vectorize(lambda d: d.id)(mesh)
self.assertAllClose(device_id_mesh, np.array(expected_device_id_mesh))
def test_v7x_create_device_mesh_fallback(self):
devices = mock_tpu_devices(2, 4, 4, mesh_utils._TPU_7X,
one_device_per_chip=False)
mesh = mesh_utils.create_device_mesh(
(1, 32), devices=devices[:32], contiguous_submeshes=False)
self.assertEqual(mesh.shape, (1, 32))
mesh = mesh_utils.create_device_mesh(
(1, 32), devices=devices[32:], contiguous_submeshes=False)
self.assertEqual(mesh.shape, (1, 32))
def int64_array(x) -> np.ndarray:
return np.array(x, dtype=np.int64)
def get_int_mesh(shape: Sequence[int]) -> np.ndarray:
return np.arange(np.prod(shape), dtype=np.int64).reshape(shape)
|
MeshUtilsTest
|
python
|
airbytehq__airbyte
|
airbyte-integrations/connectors/source-github/source_github/github_schema.py
|
{
"start": 69324,
"end": 69724
}
|
class ____(sgqlc.types.Enum):
"""The possible subject types of a pull request review comment.
Enumeration Choices:
* `FILE`: A comment that has been made against the file of a pull
request
* `LINE`: A comment that has been made against the line of a pull
request
"""
__schema__ = github_schema
__choices__ = ("FILE", "LINE")
|
PullRequestReviewThreadSubjectType
|
python
|
apache__airflow
|
devel-common/src/sphinx_exts/operators_and_hooks_ref.py
|
{
"start": 18589,
"end": 18959
}
|
class ____(BaseJinjaReferenceDirective):
"""Generate list of queues"""
def render_content(
self, *, tags: set[str] | None, header_separator: str = DEFAULT_HEADER_SEPARATOR
) -> str:
return _common_render_list_content(
header_separator=header_separator, resource_type="queues", template="queues.rst.jinja2"
)
|
QueuesDirective
|
python
|
joke2k__faker
|
faker/providers/color/he_IL/__init__.py
|
{
"start": 98,
"end": 1555
}
|
class ____(ColorProvider):
"""Implement color provider for ``he_IL`` locale."""
"""Source : https://he.wikipedia.org/wiki/%D7%95%D7%99%D7%A7%D7%99%D7%A4%D7%93%D7%99%D7%94:%D7%A2%D7%A8%D7%9B%D7%AA_%D7%A6%D7%91%D7%A2%D7%99%D7%9D#%D7%98%D7%91%D7%9C%D7%94_%D7%96%D7%95_%D7%9E%D7%A8%D7%90%D7%94_%D7%90%D7%AA_%D7%98%D7%95%D7%95%D7%97_%D7%94%D7%92%D7%95%D7%95%D7%A0%D7%99%D7%9D_%D7%A9%D7%9C_%D7%9B%D7%9E%D7%94_%D7%A6%D7%91%D7%A2%D7%99%D7%9D_%D7%A0%D7%A4%D7%95%D7%A6%D7%99%D7%9D""" # NOQA
all_colors = OrderedDict(
(
("אדום", "#FF0000"),
("אוכרה", "#DDAA33"),
("אינדיגו", "#4B0082"),
("אפור", "#7F7F7F"),
("ארגמן", "#7F003F"),
("ורוד", "#FF007F"),
("זהב", "#FFDF00"),
("חאקי", "#C3B091"),
("חום", "#7F3F00"),
("טורקיז", "#40E0D0"),
("ירוק", "#00FF00"),
("כחול", "#0000FF"),
("כסף", "#C0C0C0"),
("כתום", "#FF7F00"),
("לבן", "#FFFFFF"),
("מג'נטה", "#FF00FF"),
("סגול", "#7F00FF"),
("צהוב", "#FFFF00"),
("ציאן", "#00FFFF"),
("קרדינל", "#C41E3A"),
("שחור", "#000000"),
("שני", "#7F0000"),
("תכלת", "#007FFF"),
)
)
safe_colors = (
"אדום",
"ירוק",
"כחול",
"צהוב",
"ציאן",
"מג'נטה",
"לבן",
)
|
Provider
|
python
|
openai__openai-python
|
src/openai/types/responses/tool_choice_apply_patch.py
|
{
"start": 197,
"end": 319
}
|
class ____(BaseModel):
type: Literal["apply_patch"]
"""The tool to call. Always `apply_patch`."""
|
ToolChoiceApplyPatch
|
python
|
sqlalchemy__sqlalchemy
|
test/sql/test_types.py
|
{
"start": 17226,
"end": 17308
}
|
class ____(TypeDecorator):
impl = String()
cache_ok = True
|
SomeTypeDecorator
|
python
|
pytorch__pytorch
|
test/dynamo/test_functions.py
|
{
"start": 118342,
"end": 154366
}
|
class ____(torch._dynamo.test_case.TestCaseWithNestedGraphBreaks):
def test_func_default_tensor_args(self):
"""
Tests that we indeed reference (and mutate) "the one" default tensor arg
stored on the globally allocated function object, both from the orig and
compiled function
"""
def func():
return global_func_with_default_tensor_args()
cnts = torch._dynamo.testing.CompileCounter()
compiled_func = torch.compile(func, backend=cnts)
for i in range(4):
if i % 2 == 0:
x, kw_x = func()
else:
x, kw_x = compiled_func()
# the inner func mutates += 1 each call
self.assertTrue(same(x, torch.ones_like(x) + i))
self.assertTrue(same(kw_x, torch.ones_like(kw_x) + i))
# Calling compiled_func twice does not recompile
self.assertEqual(cnts.frame_count, 1)
self.assertEqual(cnts.op_count, 2)
# But with a change to the guarded default tensor, we do recompile
with patch.object(
global_func_with_default_tensor_args,
"__defaults__",
(torch.ones((3, 4, 5)),),
):
x, kw_x = compiled_func()
self.assertEqual(cnts.frame_count, 2)
self.assertEqual(cnts.op_count, 4)
with patch.object(
global_func_with_default_tensor_args,
"__kwdefaults__",
{"kw_x": torch.ones((3, 4, 5))},
):
x, kw_x = compiled_func()
self.assertEqual(cnts.frame_count, 3)
self.assertEqual(cnts.op_count, 6)
@torch._dynamo.config.patch(assume_dunder_attributes_remain_unchanged=False)
def test_meth_default_tensor_args(self):
"""
Tests that we indeed reference (and mutate) "the one" default tensor arg
stored on the globally allocated function object, both from the orig and
compiled function
"""
mod = WrapperModule()
cnts = torch._dynamo.testing.CompileCounter()
compiled_mod = torch.compile(mod, backend=cnts)
for i in range(4):
if i % 2 == 0:
x, kw_x = mod()
else:
x, kw_x = compiled_mod()
# the inner func mutates += 1 each call
self.assertTrue(same(x, torch.ones_like(x) + i))
self.assertTrue(same(kw_x, torch.ones_like(kw_x) + i))
# Calling compiled_func twice does not recompile
self.assertEqual(cnts.frame_count, 1)
self.assertEqual(cnts.op_count, 2)
# But with a change to the guarded default tensor, we do recompile
with patch.object(
ModuleWithDefaultTensorArgsMethod.forward,
"__defaults__",
(torch.ones((3, 4, 5)),),
):
x, kw_x = compiled_mod()
self.assertEqual(cnts.frame_count, 2)
self.assertEqual(cnts.op_count, 4)
with patch.object(
ModuleWithDefaultTensorArgsMethod.forward,
"__kwdefaults__",
{"kw_x": torch.ones((3, 4, 5))},
):
x, kw_x = compiled_mod()
self.assertEqual(cnts.frame_count, 3)
self.assertEqual(cnts.op_count, 6)
def test_func_default_torch_args(self):
"""
Tests other types of torch types as function default (size, dtype, device)
"""
def func_with_default_torch_args(
dt=torch.float16, ds=torch.Size((1, 2, 3)), dd=torch.device("cpu")
):
return torch.ones(ds, dtype=dt, device=dd)
def func():
return func_with_default_torch_args()
cnts = torch._dynamo.testing.CompileCounter()
compiled_func = torch.compile(func, backend=cnts)
out = func()
compiled_out = compiled_func()
self.assertEqual(out.dtype, compiled_out.dtype)
self.assertEqual(out.device, compiled_out.device)
self.assertEqual(out.size(), compiled_out.size())
self.assertEqual(cnts.frame_count, 1)
self.assertEqual(cnts.op_count, 1)
def test_dataclass_factory(self):
@dataclass
class Output:
scalar: int = 2
named_tensors: dict[str, torch.Tensor] = field(default_factory=dict)
lists: list[torch.Tensor] = field(default_factory=list)
def scale(self):
return self.scalar * 2
def fn(x):
# Check default dict assignment
a = Output(1)
# Check that dataclass methods can be inlined
scaled_value = a.scale()
# Check that normal assignment works
b = Output(5, named_tensors={"x": x})
# Check default int assignment
c = Output()
# Check that the default members are properly initialized
if isinstance(a.named_tensors, dict):
x = torch.sin(x)
# Change dataclass
c.scalar = 6
c.named_tensors["x"] = x
# Return dataclaass as well to check reconstruction
return c, torch.cos(x) * scaled_value + b.named_tensors["x"] + c.scalar
cnts = torch._dynamo.testing.CompileCounter()
compiled_fn = torch.compile(fn, backend=cnts, fullgraph=True)
x = torch.randn(4)
eager_dataclass, out = fn(x)
compiled_dataclass, compiled_out = compiled_fn(x)
self.assertEqual(eager_dataclass.scalar, compiled_dataclass.scalar)
self.assertEqual(
eager_dataclass.named_tensors["x"], compiled_dataclass.named_tensors["x"]
)
self.assertTrue(same(out, compiled_out))
self.assertEqual(cnts.frame_count, 1)
self.assertEqual(cnts.op_count, 5)
def test_dataclass_nested(self):
@dataclass
class Base:
outer_a: int
outer_b: int
@dataclass
class Derived(Base):
inner_a: Any = field(default_factory=list)
def fn(x):
l = Derived(1, 2)
return l.outer_a * x
opt_fn = torch.compile(fn, backend="eager", fullgraph=True)
x = torch.randn(4)
res = fn(x)
ref = opt_fn(x)
self.assertEqual(ref, res)
def test_listlike_of_tensors_contains_constant(self):
for listlike in [set, list]:
def fn(x):
x.add_(1)
s = listlike([x])
res = 1 in s
return res
opt_fn = torch.compile(fn, backend="eager", fullgraph=True)
x = torch.randn(1)
ref = opt_fn(x)
res = fn(x)
self.assertEqual(ref, res)
def test_cast_tensor_single_elem(self):
with torch._dynamo.config.patch({"capture_scalar_outputs": True}):
for t, val in [
(float, 1.0),
(float, 1),
(float, True),
(int, 1),
(int, False),
# (int, 1.0), # fails due to a >= 0 comparison in sym_int
]: # , bool, complex]: no casting for sym_bool, no sym_complex
def fn(x):
x = x + 1
return t(x)
opt_fn = torch.compile(
fn, backend="eager", fullgraph=True, dynamic=False
)
x = torch.tensor([val])
res = fn(x)
ref = opt_fn(x)
self.assertEqual(ref, res)
# Cannot handle non single-elem
with self.assertRaises(ValueError):
fn(torch.tensor([val] * 2))
with self.assertRaises(torch._dynamo.exc.TorchRuntimeError):
opt_fn(torch.tensor([val] * 2))
def test_set_construction(self):
def fn(x):
y = x.add_(1)
s = set({x})
s.add(y)
return len(s)
opt_fn = torch.compile(fn, backend="eager", fullgraph=True)
x = torch.randn(4)
res = fn(x)
ref = opt_fn(x)
self.assertEqual(ref, res)
@parametrize("_type", [set, frozenset], name_fn=lambda t: t.__name__)
def test_set_call___init__(self, _type):
@make_test
def fn(a, b):
s = _type({"apple", "banana", "cherry"})
s.__init__({"google", "microsoft", "apple"})
# frozenset should remain the same while set gets updated
if "banana" in s:
return a + b
else:
return a - b
fn(self)
@parametrize(
"method_name",
[
"copy",
"difference",
"intersection",
"symmetric_difference",
"union",
],
)
def test_frozenset_return_type(self, method_name):
@make_test
def fn(a, b):
set1 = frozenset({"apple", "banana", "cherry"})
set2 = frozenset({"google", "microsoft", "apple"})
if method_name == "copy":
result = set1.copy()
else:
result = getattr(set1, method_name)(set2)
if type(result) is frozenset:
x = a + b
else:
x = a - b
return x
fn(self)
def test_frozenset_construction(self):
def fn(x):
s = frozenset({x})
t = frozenset(s)
return len(t)
opt_fn = torch.compile(fn, backend="eager", fullgraph=True)
x = torch.randn(4)
res = fn(x)
ref = opt_fn(x)
self.assertEqual(ref, res)
def test_frozenset_reconstruction(self):
d = {}
f = frozenset()
d[f] = torch.randn(4)
def fn(x):
k = frozenset()
torch._dynamo.graph_break()
return d[k] * x
opt_fn = torch.compile(fn, backend="eager")
x = torch.randn(4)
res = fn(x)
ref = opt_fn(x)
self.assertEqual(ref, res)
def test_frozenset_illegal_call_method(self):
def fn_add():
s = frozenset((1, 2, 3))
s.add({2})
return len(s)
def fn_pop():
s = frozenset((1, 2, 3))
s.pop()
return len(s)
def fn_update():
s = frozenset((1, 2, 3))
s.update({4, 5, 6})
return len(s)
def fn_remove():
s = frozenset((1, 2, 3))
s.remove(2)
return len(s)
def fn_discard():
s = frozenset((1, 2, 3))
s.discard(2)
return len(s)
def fn_clear():
s = frozenset((1, 2, 3))
s.clear()
return len(s)
for fn in [fn_add, fn_pop, fn_update, fn_remove, fn_discard, fn_clear]:
torch._dynamo.reset()
opt_fn = torch.compile(fn, backend="eager", fullgraph=True)
with self.assertRaises(torch._dynamo.exc.InternalTorchDynamoError):
opt_fn()
def test_is_tensor_tensor(self):
def fn(x, y):
if x is y:
return x * 2
else:
return x + y
fn_opt = torch.compile(backend="eager", fullgraph=True, dynamic=True)(fn)
x = torch.zeros(2)
y = torch.ones(2)
self.assertEqual(fn(x, y), fn_opt(x, y))
self.assertEqual(fn(x, x), fn_opt(x, x))
def test_is_not_tensor_tensor(self):
def fn(x, y):
if x is not y:
return x * 2
else:
return x + y
fn_opt = torch.compile(backend="eager", fullgraph=True, dynamic=True)(fn)
x = torch.zeros(2)
y = torch.ones(2)
self.assertEqual(fn(x, y), fn_opt(x, y))
self.assertEqual(fn(x, x), fn_opt(x, x))
def test_is_mutated_tensor_tensor(self):
def fn(x):
y = x.add_(1)
return x is y
fn_opt = torch.compile(backend="eager", fullgraph=True, dynamic=True)(fn)
z = torch.ones(4)
self.assertEqual(fn(z), fn_opt(z))
def test_is_mutated_tensor_tensor_across_graph_break(self):
def fn(x):
y = x.add_(1)
cond = x is y
x.add_(1)
# The real tensor values are recovered when graph breaking.
# Hence we recover the invariant.
torch._dynamo.graph_break()
x.add_(1)
return x is y, cond
fn_opt = torch.compile(backend="eager", dynamic=True)(fn)
z = torch.ones(4)
self.assertEqual(fn(z), fn_opt(z))
def test_is_mutated_tensor_tensor(self):
def fn(x):
y = x.add_(1)
return y is x
fn_opt = torch.compile(backend="eager", fullgraph=True, dynamic=True)(fn)
z = torch.ones(4, 1)
self.assertEqual(fn(z), fn_opt(z))
def test_is_init_in_compile_mutated_tensor_tensor(self):
def fn(x):
z = x.clone()
y = z.add_(1)
return y is z
fn_opt = torch.compile(backend="eager", fullgraph=True, dynamic=True)(fn)
z = torch.ones(4, 1)
self.assertEqual(fn(z), fn_opt(z))
def test_is_init_in_compile_vmapped_mutated_tensor_tensor(self):
def fn(z):
x = z.clone()
y = torch.vmap(torch.Tensor.acos_)(x)
_ = y is z
return y is x
fn_opt = torch.compile(backend="eager", fullgraph=True, dynamic=True)(fn)
z = torch.ones(4, 1)
self.assertEqual(fn(z), fn_opt(z))
def test_is_vmapped_mutated_tensor_tensor(self):
def fn(x):
y = torch.vmap(torch.Tensor.acos_)(x)
return y is x
fn_opt = torch.compile(backend="eager", fullgraph=True, dynamic=True)(fn)
z = torch.ones(4, 1)
self.assertEqual(fn(z), fn_opt(z))
def test_is_init_in_compile_vmapped_mutated_tensor_tensor_multi_arg(self):
def fn(y, z):
a = y.clone()
b = z.clone()
def g(a, b):
return a.acos_(), b.acos_()
c, d = torch.vmap(g)(a, b)
return a is c is b is d
fn_opt = torch.compile(backend="eager", fullgraph=True, dynamic=True)(fn)
y = torch.ones(4, 2)
z = torch.ones(4, 10)
self.assertEqual(fn(y, z), fn_opt(y, z))
self.assertEqual(fn(y, y), fn_opt(y, y))
def test_in_set_would_fail_broadcast(self):
param = torch.zeros(5)
param2 = torch.zeros(5, 10)
tensor_list = set()
tensor_list.add(param2)
assert param not in tensor_list
def fn(param, param2):
param.add_(1)
tensor_list = set([param2])
return param in tensor_list
cnts = torch._dynamo.testing.CompileCounter()
opt_fn = torch.compile(fn, backend=cnts, fullgraph=True)
self.assertEqual(opt_fn(param, param2), fn(param, param2))
self.assertEqual(cnts.frame_count, 1)
# Test aliased
self.assertEqual(opt_fn(param, param), fn(param, param))
self.assertEqual(cnts.frame_count, 2) # Recompiles
def test_in_set_inplace(self):
param = torch.zeros(5)
param2 = torch.zeros(5, 10)
tensor_list = set()
tensor_list.add(param2)
assert param not in tensor_list
def fn(param, param2):
y = param.add_(1) # Tensor method
z = torch.Tensor.add_(y, 1) # torch function
tensor_list = set([param2])
return y in tensor_list and z in tensor_list
cnts = torch._dynamo.testing.CompileCounter()
opt_fn = torch.compile(fn, backend=cnts, fullgraph=True)
self.assertEqual(opt_fn(param, param2), fn(param, param2))
self.assertEqual(cnts.frame_count, 1)
# Test aliased
self.assertEqual(opt_fn(param, param), fn(param, param))
self.assertEqual(cnts.frame_count, 2) # Recompiles
def test_reconstructed_name(self):
lst = []
@torch._dynamo.disable
def disallowed(g):
lst.append(g.__name__)
def f():
def g():
return ()
disallowed(g)
opt_f = torch.compile(f, backend="eager")
opt_f()
f()
self.assertEqual(len(lst), 2)
self.assertEqual(lst[0], lst[1])
def test_zip_strict(self):
def fn(x, ys, zs):
x = x.clone()
for y, z in zip(ys, zs, strict=True):
x += y * z
return x, zip(ys, zs)
opt_fn = torch.compile(fn, backend="eager")
nopython_fn = torch.compile(fn, backend="eager", fullgraph=True)
x = torch.ones(3)
ys = [1.0, 2.0, 3.0]
zs = [2.0, 5.0, 8.0]
ref = fn(x, ys, zs)
res = opt_fn(x, ys, zs)
self.assertEqual(ref[0], res[0])
self.assertEqual(list(ref[1]), list(res[1]))
self.assertIsInstance(res[1], zip)
# If nopython, should raise UserError
with self.assertRaisesRegex(torch._dynamo.exc.UserError, "zip()"):
nopython_fn(x, ys[:1], zs)
with self.assertRaisesRegex(torch._dynamo.exc.UserError, "zip()"):
nopython_fn(x, ys, zs[:1])
# Should cause fallback if allow graph break
with self.assertRaisesRegex(ValueError, "zip()"):
opt_fn(x, ys[:1], zs)
with self.assertRaisesRegex(ValueError, "zip()"):
opt_fn(x, ys, zs[:1])
@unittest.skipIf(not TEST_MULTIGPU, "detected only one GPU")
def test_gpu_current_device(self):
def fn(x):
y = torch.empty(
(2, 3),
dtype=torch.float32,
device=torch.accelerator.current_device_index(),
)
y.copy_(x)
return torch.sin(y + y.device.index)
counter = torch._dynamo.testing.CompileCounter()
opt_fn = torch.compile(backend=counter, fullgraph=True)(fn)
with torch.accelerator.device_index(0):
x = torch.randn(2, 3)
self.assertEqual(opt_fn(x), fn(x))
self.assertEqual(counter.frame_count, 1)
with torch.accelerator.device_index(1):
self.assertEqual(opt_fn(x), fn(x))
self.assertEqual(counter.frame_count, 2)
def test_fn_with_attr(self):
def fn(x):
if fn.pred:
return torch.relu(x * 2)
else:
return torch.abs(x + 3)
t = torch.ones(3)
counter = torch._dynamo.testing.CompileCounter()
fn.pred = True
opt_fn_0 = torch.compile(fullgraph=True, backend=counter)(fn)
self.assertEqual(opt_fn_0(t), fn(t))
self.assertEqual(counter.frame_count, 1)
fn.pred = False
opt_fn_1 = torch.compile(fullgraph=True, backend=counter)(fn)
self.assertEqual(opt_fn_1(t), fn(t))
self.assertEqual(counter.frame_count, 2)
def test_str_handler_for_user_defined_object(self):
"""
Confirms handler behaviour for `str` is the same between eager and dynamo.
Compares a user defined object with custom `__str__` method and without.
"""
class CustomStr:
def __str__(self):
return "ok"
def foo_custom_str(x):
a = CustomStr()
return x, str(a)
eager_custom_str = foo_custom_str(torch.ones(4))
dynamo_custom_str = torch.compile(foo_custom_str, fullgraph=True)(torch.ones(4))
self.assertEqual(eager_custom_str[1], dynamo_custom_str[1])
self.assertEqual(eager_custom_str[1], "ok")
class DefaultStr:
pass
def foo_default_str(x):
a = DefaultStr()
return x, str(a)
eager_default_str = foo_default_str(torch.ones(4))
dynamo_default_str = torch.compile(foo_default_str, fullgraph=True)(
torch.ones(4)
)
# Check that the tensor output from eager and dynamo modes are the same
self.assertEqual(eager_default_str[0], dynamo_default_str[0])
# Check that the class name (without memory address) is the same in both modes
eager_class_name = eager_default_str[1].split(" object at")[0]
dynamo_class_name = dynamo_default_str[1].split(" object at")[0]
self.assertEqual(eager_class_name, dynamo_class_name)
def test_pybind_object(self):
def fn(x, pybind_obj):
if pybind_obj.result:
return torch.cos(x)
return torch.sin(x)
opt_fn = torch.compile(fn, backend="eager", fullgraph=True)
pybind_obj = torch._C._dynamo.guards.GuardDebugInfo(True, ["a==1"], 0)
x = torch.randn(4)
self.assertEqual(opt_fn(x, pybind_obj), fn(x, pybind_obj))
pybind_obj = torch._C._dynamo.guards.GuardDebugInfo(False, ["a==1"], 1)
x = torch.randn(4)
self.assertEqual(opt_fn(x, pybind_obj), fn(x, pybind_obj))
def test_tree_map(self):
def fn(a, b, index):
def call(index):
mapped_attributes = torch.utils._pytree.tree_map_only(
torch.Tensor,
lambda x: x[index],
(a, b),
)
return mapped_attributes
return call(index)
a = torch.randn(4, 2, 5)
b = torch.randn(4, 2, 5, 5)
compiled_fn = torch.compile(fn, fullgraph=True)
compiled_res = compiled_fn(a, b, torch.tensor([2]))
reference_res = fn(a, b, torch.tensor([2]))
self.assertTrue(same(compiled_res, reference_res))
def test_fx_map_aggregate(self):
def fn(inputs, f):
return torch.fx.node.map_aggregate(inputs, f)
opt_fn = torch.compile(fn, backend="eager", fullgraph=True)
x = [torch.randn(4), [torch.randn(4), torch.randn(4)]]
def f(y):
return y * 2
ref = fn(x, f)
res = opt_fn(x, f)
self.assertEqual(ref, res)
# Check type(res) is immutable_list
self.assertTrue(type(ref) is type(res))
x = {
"a": torch.randn(4),
"b": [torch.randn(4), torch.randn(4)],
}
ref = fn(x, f)
res = opt_fn(x, f)
self.assertEqual(ref, res)
self.assertTrue(type(ref) is type(res))
def test_fx_immutable_list_mutation_not_allowed(self):
def fn(inputs, x, f=lambda x: x * 2):
immutable_inputs = torch.fx.immutable_collections.immutable_list(inputs)
try:
immutable_inputs.append(x)
except TypeError:
pass
return torch.fx.node.map_aggregate(immutable_inputs, f)
opt_fn = torch.compile(fn, backend="eager", fullgraph=True)
inputs = [torch.randn(4), [torch.randn(4), torch.randn(4)]]
x = torch.randn(4)
self.assertEqual(fn(inputs, x), opt_fn(inputs, x))
def test_udf_tuple(self):
class MyTuple(tuple): # noqa: SLOT001
def len_mulitply_2(self):
return len(self) * 2
def __contains__(self, val):
# Ensure that overridden method is traced
self.checked = True
return super().__contains__(val)
def fn(x, tup):
if 3 in tup:
x = torch.cos(x)
else:
x = torch.sin(x)
return x * tup.len_mulitply_2()
opt_fn = torch.compile(fn, backend="eager", fullgraph=True)
x = torch.randn(4)
ref_tup = MyTuple([1, 2, 3])
ref = fn(x, ref_tup)
res_tup = MyTuple([1, 2, 3])
res = opt_fn(x, res_tup)
self.assertEqual(ref, res)
self.assertTrue(ref_tup.checked)
self.assertTrue(res_tup.checked)
def test_udf_tuple_construction(self):
class MyTuple(tuple): # noqa: SLOT001
pass
def fn(x):
tup = MyTuple([1, 2, 3])
if 3 in tup:
x = torch.cos(x)
else:
x = torch.sin(x)
return x, tup
opt_fn = torch.compile(fn, backend="eager", fullgraph=True)
x = torch.randn(4)
ref_x, ref_tup = fn(x)
res_x, res_tup = opt_fn(x)
self.assertEqual(ref_x, res_x)
self.assertEqual(ref_tup, res_tup)
def test_udf_tuple_construction_custom_new(self):
class MyTuple(tuple): # noqa: SLOT001
def __new__(cls, *args, **kwargs):
return super().__new__(cls, [1, 2, 3])
def fn(x):
tup = MyTuple()
if 3 in tup:
x = torch.cos(x)
else:
x = torch.sin(x)
return x, tup
opt_fn = torch.compile(fn, backend="eager", fullgraph=True)
x = torch.randn(4)
ref_x, ref_tup = fn(x)
res_x, res_tup = opt_fn(x)
self.assertEqual(ref_x, res_x)
self.assertEqual(ref_tup, res_tup)
def test_udf_namedtuple(self):
class MyTuple(NamedTuple):
a: torch.Tensor
b: torch.Tensor
class PairTensor(MyTuple):
def __new__(cls, a, b):
return super().__new__(cls, a, b)
def __add__(self, other):
return PairTensor(self.a + other.a, self.b + other.b)
def fn(pair1, pair2):
return pair1 + pair2
opt_fn = torch.compile(fn, backend="eager", fullgraph=True)
pair1 = PairTensor(torch.randn(4), torch.randn(2, 8))
pair2 = PairTensor(torch.randn(1), torch.randn(2, 1))
ref = fn(pair1, pair2)
res = opt_fn(pair1, pair2)
self.assertEqual(ref.a, res.a)
self.assertEqual(ref.b, res.b)
def test_udf_tuple_reconstruction(self):
class MyTuple(tuple): # noqa: SLOT001
pass
def fn(x, klass):
x = x * 2
sc_tuple = tuple.__new__(klass, [x])
if isinstance(sc_tuple, MyTuple):
sc_tuple.attr = 3
return sc_tuple
opt_fn = torch.compile(fn, backend="eager", fullgraph=True)
x = torch.randn(4)
ref = fn(x, MyTuple)
res = opt_fn(x, MyTuple)
self.assertEqual(ref, res)
self.assertTrue(isinstance(res, MyTuple))
self.assertEqual(ref.attr, res.attr)
ref = fn(x, tuple)
res = opt_fn(x, tuple)
self.assertEqual(ref, res)
self.assertTrue(isinstance(res, tuple))
def test_udf_list(self):
class MyList(list): # noqa: SLOT001
def len_mulitply_2(self):
return len(self) * 2
def __contains__(self, val):
# Ensure that overridden method is traced
self.checked = True
return super().__contains__(val)
def __getitem__(self, idx):
# Tests that the reconstruction logic does not call the
# overridden __getitem__ method.
raise RuntimeError("Should not be called")
def fn(x, lst):
if 3 in lst:
x = torch.cos(x)
else:
x = torch.sin(x)
lst.append(4)
return x * lst.len_mulitply_2()
opt_fn = torch.compile(fn, backend="eager", fullgraph=True)
x = torch.randn(4)
ref_lst = MyList([1, 2, 3])
ref = fn(x, ref_lst)
res_lst = MyList([1, 2, 3])
res = opt_fn(x, res_lst)
self.assertEqual(ref, res)
self.assertEqual(len(ref_lst), len(res_lst))
self.assertTrue(ref_lst.checked)
self.assertTrue(res_lst.checked)
def test_udf_list_slice(self):
class MyList(list): # noqa: SLOT001
def len_mulitply_2(self):
return len(self) * 2
def fn(x, lst):
lst.append(4)
return x * lst.len_mulitply_2() * sum(lst[1:3])
opt_fn = torch.compile(fn, backend="eager", fullgraph=True)
x = torch.randn(4)
ref_lst = MyList([1, 2, 3])
ref = fn(x, ref_lst)
res_lst = MyList([1, 2, 3])
res = opt_fn(x, res_lst)
self.assertEqual(ref, res)
self.assertEqual(len(ref_lst), len(res_lst))
def test_udf_list_reconstruction(self):
class MyList(list): # noqa: SLOT001
# def __new__(cls, *args, **kwargs):
# return super().__new__(cls, *args, **kwargs)
pass
def fn(x, klass):
x = x * 2
sc_list = list.__new__(klass)
sc_list.append(x)
if isinstance(sc_list, MyList):
sc_list.attr = 3
return sc_list
opt_fn = torch.compile(fn, backend="eager", fullgraph=True)
x = torch.randn(4)
ref = fn(x, MyList)
res = opt_fn(x, MyList)
self.assertEqual(ref, res)
self.assertTrue(isinstance(res, MyList))
self.assertEqual(ref.attr, res.attr)
ref = fn(x, list)
res = opt_fn(x, list)
self.assertEqual(ref, res)
self.assertTrue(isinstance(res, list))
def test_sys_recursionlimit(self):
def fn(x):
return x.sin() * sys.getrecursionlimit()
opt_fn = torch.compile(fn, backend="eager", fullgraph=True)
x = torch.randn(4)
self.assertEqual(fn(x), opt_fn(x))
def test_keyword(self):
def fn(x, word):
if keyword.iskeyword(word):
return torch.sin(x)
return torch.cos(x)
opt_fn = torch.compile(fn, backend="eager", fullgraph=True)
x = torch.randn(4)
word = "None"
self.assertEqual(fn(x, word), opt_fn(x, word))
word = "dynamo"
self.assertEqual(fn(x, word), opt_fn(x, word))
def test_func_attrs(self):
def f(x=4, y=2):
pass
def fn(x):
try:
f.dynamo + 1
except AttributeError:
x = torch.sin(x)
code = f.__code__
defaults = f.__defaults__
return x * len(defaults) * code.co_argcount
opt_fn = torch.compile(fn, backend="eager", fullgraph=True)
x = torch.randn(4)
self.assertEqual(fn(x), opt_fn(x))
def test_functools_partial_id(self):
def gn(a, b):
return a + b
partial_gn = functools.partial(gn, a=3)
def fn(x):
d = {id(partial_gn): 5}
return partial_gn(b=x) * d[id(partial_gn)]
opt_fn = torch.compile(fn, backend="eager", fullgraph=True)
x = torch.randn(4)
self.assertEqual(fn(x), opt_fn(x))
def test_functional_compile(self):
def get_torch_functional_functions():
s = set()
for name in torch.functional.__all__:
method = getattr(torch.functional, name)
s.add(method)
return s
functions = get_torch_functional_functions()
self.assertTrue(len(functions) > 0)
for func in functions:
compiled_func = torch.compile(func)
self.assertTrue(callable(compiled_func))
def test_skip_function_call_very_weird_value(self):
class weird: # noqa: UP004
def __getattribute__(self, name):
if name == "__qualname__":
raise AttributeError("test")
w = weird()
a = SkipFunctionVariable(value=w)
with self.assertRaises(Unsupported):
a.call_function(None, [], {})
def test_inspect_method_source(self):
class Mod(torch.nn.Module):
def __init__(self):
super().__init__()
def check(self, x):
return x * 2
def forward(self, x):
return x * 2
mod = Mod()
def fn(x):
inspect.signature(mod.check).parameters.items()
return mod(x)
opt_fn = torch.compile(fn, backend="eager", fullgraph=True)
x = torch.randn(4)
ref = fn(x)
res = opt_fn(x)
self.assertEqual(ref, res)
def test_property_class_transmute(self):
class PropertyGetter:
def __call__(self, obj):
return True
p = property(PropertyGetter())
class Mod(torch.nn.Module):
def forward(self, x):
if self.p:
return x + 1
else:
raise RuntimeError("whoops")
mod = Mod()
mod.__class__ = type(mod.__class__.__name__, (mod.__class__,), {"p": p})
opt_mod = torch.compile(mod, backend="eager", fullgraph=True)
x = torch.randn(1)
self.assertEqual(opt_mod(x), x + 1)
def test_property_functools_partial(self):
def p_getter(obj, *, delta: int):
# Use instance state + a bound constant
return (getattr(obj, "flag", 0) + delta) > 0
class Mod(torch.nn.Module):
def __init__(self, flag: int):
super().__init__()
self.flag = flag
# fget is a functools.partial object
p = property(functools.partial(p_getter, delta=1))
def forward(self, x):
if self.p: # calls p_getter(self, delta=1)
return x + 1
else:
raise RuntimeError("whoops")
mod = Mod(flag=1)
opt_mod = torch.compile(mod, backend="eager", fullgraph=True)
x = torch.randn(1)
self.assertEqual(opt_mod(x), x + 1)
def test_full_with_tensor_fill_value(self):
"""Test that torch.full works correctly with dynamic tensor fill_value"""
# Test with tensor fill_value (the bug case)
def func_tensor(x):
return torch.full((2,), x, dtype=torch.float64)
func_compiled = torch.compile(func_tensor)
# Test with different values
x1 = torch.tensor(5.0, dtype=torch.float64)
x2 = torch.tensor(10.0, dtype=torch.float64)
result1 = func_compiled(x1)
expected1 = torch.full((2,), x1, dtype=torch.float64)
self.assertEqual(result1, expected1)
# This is where the bug occurred - second call reused first value
result2 = func_compiled(x2)
expected2 = torch.full((2,), x2, dtype=torch.float64)
self.assertEqual(result2, expected2)
# Test with different dtypes
for dtype in [torch.float32, torch.float64, torch.int32, torch.int64]:
def func_typed(x):
return torch.full((3,), x, dtype=dtype)
func_typed_compiled = torch.compile(func_typed)
x_typed = torch.tensor(7, dtype=dtype)
result = func_typed_compiled(x_typed)
expected = torch.full((3,), x_typed, dtype=dtype)
self.assertEqual(result, expected)
# Test with non-tensor fill_value (scalar) to ensure we didn't break existing behavior
def func_scalar(size):
return torch.full((size,), 42.0, dtype=torch.float32)
func_scalar_compiled = torch.compile(func_scalar)
result_scalar = func_scalar_compiled(5)
expected_scalar = torch.full((5,), 42.0, dtype=torch.float32)
self.assertEqual(result_scalar, expected_scalar)
# Test with different scalar values
def func_scalar_param():
# Test multiple calls with different hardcoded scalar values
a = torch.full((2,), 3.14, dtype=torch.float32)
b = torch.full((2,), 2.71, dtype=torch.float32)
return a, b
func_scalar_param_compiled = torch.compile(func_scalar_param)
result_a, result_b = func_scalar_param_compiled()
self.assertEqual(result_a, torch.full((2,), 3.14, dtype=torch.float32))
self.assertEqual(result_b, torch.full((2,), 2.71, dtype=torch.float32))
instantiate_parametrized_tests(FunctionTests)
instantiate_parametrized_tests(DefaultsTests)
if __name__ == "__main__":
from torch._dynamo.test_case import run_tests
run_tests()
|
DefaultsTests
|
python
|
graphql-python__graphene
|
graphene/tests/issues/test_313.py
|
{
"start": 75,
"end": 140
}
|
class ____(graphene.ObjectType):
rand = graphene.String()
|
Query
|
python
|
marshmallow-code__marshmallow
|
src/marshmallow/fields.py
|
{
"start": 2481,
"end": 15900
}
|
class ____(typing.Generic[_InternalT]):
"""Base field from which all other fields inherit.
This class should not be used directly within Schemas.
:param dump_default: If set, this value will be used during serialization if the
input value is missing. If not set, the field will be excluded from the
serialized output if the input value is missing. May be a value or a callable.
:param load_default: Default deserialization value for the field if the field is not
found in the input data. May be a value or a callable.
:param data_key: The name of the dict key in the external representation, i.e.
the input of `load` and the output of `dump`.
If `None`, the key will match the name of the field.
:param attribute: The name of the key/attribute in the internal representation, i.e.
the output of `load` and the input of `dump`.
If `None`, the key/attribute will match the name of the field.
Note: This should only be used for very specific use cases such as
outputting multiple fields for a single attribute, or using keys/attributes
that are invalid variable names, unsuitable for field names. In most cases,
you should use ``data_key`` instead.
:param validate: Validator or collection of validators that are called
during deserialization. Validator takes a field's input value as
its only parameter and returns a boolean.
If it returns `False`, an :exc:`ValidationError` is raised.
:param required: Raise a :exc:`ValidationError` if the field value
is not supplied during deserialization.
:param allow_none: Set this to `True` if `None` should be considered a valid value during
validation/deserialization. If set to `False` (the default), `None` is considered invalid input.
If ``load_default`` is explicitly set to `None` and ``allow_none`` is unset,
`allow_none` is implicitly set to ``True``.
:param load_only: If `True` skip this field during serialization, otherwise
its value will be present in the serialized data.
:param dump_only: If `True` skip this field during deserialization, otherwise
its value will be present in the deserialized object. In the context of an
HTTP API, this effectively marks the field as "read-only".
:param error_messages: Overrides for `Field.default_error_messages`.
:param metadata: Extra information to be stored as field metadata.
.. versionchanged:: 3.0.0b8
Add ``data_key`` parameter for the specifying the key in the input and
output data. This parameter replaced both ``load_from`` and ``dump_to``.
.. versionchanged:: 3.13.0
Replace ``missing`` and ``default`` parameters with ``load_default`` and ``dump_default``.
.. versionchanged:: 3.24.0
`Field <marshmallow.fields.Field>` should no longer be used as a field within a `Schema <marshmallow.Schema>`.
Use `Raw <marshmallow.fields.Raw>` or another `Field <marshmallow.fields.Field>` subclass instead.
.. versionchanged:: 4.0.0
Remove ``context`` property.
"""
# Some fields, such as Method fields and Function fields, are not expected
# to exist as attributes on the objects to serialize. Set this to False
# for those fields
_CHECK_ATTRIBUTE = True
#: Default error messages for various kinds of errors. The keys in this dictionary
#: are passed to `Field.make_error`. The values are error messages passed to
#: :exc:`marshmallow.exceptions.ValidationError`.
default_error_messages: dict[str, str] = {
"required": "Missing data for required field.",
"null": "Field may not be null.",
"validator_failed": "Invalid value.",
}
def __init__(
self,
*,
load_default: typing.Any = missing_,
dump_default: typing.Any = missing_,
data_key: str | None = None,
attribute: str | None = None,
validate: types.Validator | typing.Iterable[types.Validator] | None = None,
required: bool = False,
allow_none: bool | None = None,
load_only: bool = False,
dump_only: bool = False,
error_messages: dict[str, str] | None = None,
metadata: typing.Mapping[str, typing.Any] | None = None,
) -> None:
self.dump_default = dump_default
self.load_default = load_default
self.attribute = attribute
self.data_key = data_key
self.validate = validate
if validate is None:
self.validators = []
elif callable(validate):
self.validators = [validate]
elif utils.is_iterable_but_not_string(validate):
self.validators = list(validate)
else:
raise ValueError(
"The 'validate' parameter must be a callable "
"or a collection of callables."
)
# If allow_none is None and load_default is None
# None should be considered valid by default
self.allow_none = load_default is None if allow_none is None else allow_none
self.load_only = load_only
self.dump_only = dump_only
if required is True and load_default is not missing_:
raise ValueError("'load_default' must not be set for required fields.")
self.required = required
metadata = metadata or {}
self.metadata = metadata
# Collect default error message from self and parent classes
messages: dict[str, str] = {}
for cls in reversed(self.__class__.__mro__):
messages.update(getattr(cls, "default_error_messages", {}))
messages.update(error_messages or {})
self.error_messages = messages
self.parent: Field | Schema | None = None
self.name: str | None = None
self.root: Schema | None = None
def __repr__(self) -> str:
return (
f"<fields.{self.__class__.__name__}(dump_default={self.dump_default!r}, "
f"attribute={self.attribute!r}, "
f"validate={self.validate}, required={self.required}, "
f"load_only={self.load_only}, dump_only={self.dump_only}, "
f"load_default={self.load_default}, allow_none={self.allow_none}, "
f"error_messages={self.error_messages})>"
)
def __deepcopy__(self, memo):
return copy.copy(self)
def get_value(
self,
obj: typing.Any,
attr: str,
accessor: (
typing.Callable[[typing.Any, str, typing.Any], typing.Any] | None
) = None,
default: typing.Any = missing_,
) -> _InternalT:
"""Return the value for a given key from an object.
:param obj: The object to get the value from.
:param attr: The attribute/key in `obj` to get the value from.
:param accessor: A callable used to retrieve the value of `attr` from
the object `obj`. Defaults to `marshmallow.utils.get_value`.
"""
accessor_func = accessor or utils.get_value
check_key = attr if self.attribute is None else self.attribute
return accessor_func(obj, check_key, default)
def _validate(self, value: typing.Any) -> None:
"""Perform validation on ``value``. Raise a :exc:`ValidationError` if validation
does not succeed.
"""
self._validate_all(value)
@property
def _validate_all(self) -> typing.Callable[[typing.Any], None]:
return And(*self.validators)
def make_error(self, key: str, **kwargs) -> ValidationError:
"""Helper method to make a `ValidationError` with an error message
from ``self.error_messages``.
"""
try:
msg = self.error_messages[key]
except KeyError as error:
class_name = self.__class__.__name__
message = (
f"ValidationError raised by `{class_name}`, but error key `{key}` does "
"not exist in the `error_messages` dictionary."
)
raise AssertionError(message) from error
if isinstance(msg, (str, bytes)):
msg = msg.format(**kwargs)
return ValidationError(msg)
def _validate_missing(self, value: typing.Any) -> None:
"""Validate missing values. Raise a :exc:`ValidationError` if
`value` should be considered missing.
"""
if value is missing_ and self.required:
raise self.make_error("required")
if value is None and not self.allow_none:
raise self.make_error("null")
def serialize(
self,
attr: str,
obj: typing.Any,
accessor: (
typing.Callable[[typing.Any, str, typing.Any], typing.Any] | None
) = None,
**kwargs,
):
"""Pulls the value for the given key from the object, applies the
field's formatting and returns the result.
:param attr: The attribute/key to get from the object.
:param obj: The object to access the attribute/key from.
:param accessor: Function used to access values from ``obj``.
:param kwargs: Field-specific keyword arguments.
"""
if self._CHECK_ATTRIBUTE:
value = self.get_value(obj, attr, accessor=accessor)
if value is missing_:
default = self.dump_default
value = default() if callable(default) else default
if value is missing_:
return value
else:
value = None
return self._serialize(value, attr, obj, **kwargs)
# If value is None, None may be returned
@typing.overload
def deserialize(
self,
value: None,
attr: str | None = None,
data: typing.Mapping[str, typing.Any] | None = None,
**kwargs,
) -> None | _InternalT: ...
# If value is not None, internal type is returned
@typing.overload
def deserialize(
self,
value: typing.Any,
attr: str | None = None,
data: typing.Mapping[str, typing.Any] | None = None,
**kwargs,
) -> _InternalT: ...
def deserialize(
self,
value: typing.Any,
attr: str | None = None,
data: typing.Mapping[str, typing.Any] | None = None,
**kwargs,
) -> _InternalT | None:
"""Deserialize ``value``.
:param value: The value to deserialize.
:param attr: The attribute/key in `data` to deserialize.
:param data: The raw input data passed to `Schema.load <marshmallow.Schema.load>`.
:param kwargs: Field-specific keyword arguments.
:raise ValidationError: If an invalid value is passed or if a required value
is missing.
"""
# Validate required fields, deserialize, then validate
# deserialized value
self._validate_missing(value)
if value is missing_:
_miss = self.load_default
return _miss() if callable(_miss) else _miss
if self.allow_none and value is None:
return None
output = self._deserialize(value, attr, data, **kwargs)
self._validate(output)
return output
# Methods for concrete classes to override.
def _bind_to_schema(self, field_name: str, parent: Schema | Field) -> None:
"""Update field with values from its parent schema. Called by
`Schema._bind_field <marshmallow.Schema._bind_field>`.
:param field_name: Field name set in schema.
:param parent: Parent object.
"""
self.parent = self.parent or parent
self.name = self.name or field_name
self.root = self.root or (
self.parent.root if isinstance(self.parent, Field) else self.parent
)
def _serialize(
self, value: _InternalT | None, attr: str | None, obj: typing.Any, **kwargs
) -> typing.Any:
"""Serializes ``value`` to a basic Python datatype. Noop by default.
Concrete :class:`Field` classes should implement this method.
Example: ::
class TitleCase(Field):
def _serialize(self, value, attr, obj, **kwargs):
if not value:
return ""
return str(value).title()
:param value: The value to be serialized.
:param attr: The attribute or key on the object to be serialized.
:param obj: The object the value was pulled from.
:param kwargs: Field-specific keyword arguments.
:return: The serialized value
"""
return value
def _deserialize(
self,
value: typing.Any,
attr: str | None,
data: typing.Mapping[str, typing.Any] | None,
**kwargs,
) -> _InternalT:
"""Deserialize value. Concrete :class:`Field` classes should implement this method.
:param value: The value to be deserialized.
:param attr: The attribute/key in `data` to be deserialized.
:param data: The raw input data passed to the `Schema.load <marshmallow.Schema.load>`.
:param kwargs: Field-specific keyword arguments.
:raise ValidationError: In case of formatting or validation failure.
:return: The deserialized value.
.. versionchanged:: 3.0.0
Added ``**kwargs`` to signature.
"""
return value
|
Field
|
python
|
pytorch__pytorch
|
torch/_dynamo/variables/misc.py
|
{
"start": 59579,
"end": 65990
}
|
class ____(VariableTracker):
"""
Wrapper around `numpy.*`. Currently, is able to trace a small subset of numpy functions as well as numpy dtypes.
"""
constant_fold_functions = (tnp.issubdtype,)
def __init__(self, value, **kwargs) -> None:
super().__init__(**kwargs)
self.value = value
@classmethod
def can_constant_fold_through(cls, fn):
mod = fn.__module__.split(".")
assert len(mod) >= 2 and mod[:2] == ["torch", "_numpy"]
return fn in cls.constant_fold_functions
@classmethod
def get_constant_collection_for_func(cls, fn):
mod = fn.__module__.split(".")
assert len(mod) >= 2 and mod[:2] == ["torch", "_numpy"]
return np_constant_collections_map.get(fn)
def call_function(
self,
tx: "InstructionTranslator",
args: "list[VariableTracker]",
kwargs: "dict[str, VariableTracker]",
) -> "VariableTracker":
if not config.trace_numpy:
unimplemented(
gb_type="attempted to trace numpy function with config.trace_numpy=False",
context=f"numpy function: {self.value}, args: {args}, kwargs: {kwargs}",
explanation=f"Attempted to trace numpy function {self.value} "
"while `torch._dynamo.config.trace_numpy` was set to False.",
hints=[
"Set `torch._dynamo.config.trace_numpy` to True to trace numpy functions.",
],
)
from ..utils import numpy_to_tensor_wrapper
from .tensor import NumpyNdarrayVariable
func = get_np_to_tnp_map().get(self.value)
if func is None:
unimplemented(
gb_type="attempted to trace numpy function unsupported by PyTorch",
context=f"numpy function: {self.value}, args: {args}, kwargs: {kwargs} (corresponding torch function: {func})",
explanation=f"Can't find numpy numpy function {self.value} in torch._numpy.",
hints=[
*graph_break_hints.SUPPORTABLE,
],
)
# We are dealing with a function that produces a const collection type (np.dtype, np.iinfo/np.finfo)
if (
collection_variable_typ := self.get_constant_collection_for_func(func)
) is not None:
try:
return collection_variable_typ(
self.value(
*[x.as_python_constant() for x in args],
**{k: v.as_python_constant() for k, v in kwargs.items()},
)
)
except AsPythonConstantNotImplementedError:
unimplemented(
gb_type="numpy function that produces a const collection type encountered non-const arguments",
context=f"numpy function: {self.value}, args: {args}, kwargs: {kwargs} (corresponding torch function: {func})",
explanation=f"numpy function {self.value} that produces a const collection type "
"(e.g. np.dtype, np.iinfo/np.finfo) "
"received arguments that are not constant.",
hints=[
*graph_break_hints.USER_ERROR,
],
)
else:
if (
func.__module__ == "torch._numpy.random"
and config.use_numpy_random_stream
):
unimplemented(
gb_type="attempted to trace torch._numpy.random function with config.use_numpy_random_stream=True",
context=f"numpy function: {self.value}, args: {args}, kwargs: {kwargs} (corresponding torch function: {func})",
explanation=f"Attempted to trace {self.value} when `torch._dynamo.config.use_numpy_random_stream` "
"is set to True.",
hints=[
"Set `torch._dynamo.config.use_numpy_random_stream` to False.",
f"Avoid calling {self.value}.",
],
)
args, kwargs = NumpyNdarrayVariable.patch_args(func.__name__, args, kwargs)
if self.can_constant_fold_through(func) and (
check_unspec_or_constant_args(args, kwargs)
):
# constant fold
return variables.ConstantVariable.create(
self.as_python_constant()(
*[x.as_python_constant() for x in args],
**{k: v.as_python_constant() for k, v in kwargs.items()},
),
)
# TODO Add all the functions that go from constants to constants to can_constant_fold_through
proxy = tx.output.create_proxy(
"call_function",
numpy_to_tensor_wrapper(func),
*proxy_args_kwargs(args, kwargs),
)
return NumpyNdarrayVariable.create(tx, proxy)
def call_method(
self,
tx: "InstructionTranslator",
name,
args: "list[VariableTracker]",
kwargs: "dict[str, VariableTracker]",
) -> "VariableTracker":
unimplemented(
gb_type="attempted to trace numpy.* function as a method",
context=f"numpy function: {self.value}, args: {args}, kwargs: {kwargs}",
explanation="Tracing numpy.* functions as methods is not supported.",
hints=[
*graph_break_hints.DIFFICULT,
],
)
def as_python_constant(self):
return self.value
def as_proxy(self):
if config.trace_numpy:
# Can replace with EnumType once we drop 3.10 support
if isinstance(self.value, enum.EnumMeta):
# This is mostly for np._CopyMode
return self.value
if isinstance(self.value, type):
# This handles numpy dtype attributes such as np.float32
# We return a string as we don't want to serialize non-PyTorch objects in the output FX graph
# In torch/_numpy we normalize strings to their dtypes when the input is a dtype, as NumPy does
return self.value.__name__
return super().as_proxy()
# Used to keep track of NULLs pushed on the stack for Python 3.11 function calls
|
NumpyVariable
|
python
|
ray-project__ray
|
python/ray/llm/_internal/serve/core/configs/openai_api_models.py
|
{
"start": 1602,
"end": 1734
}
|
class ____(vLLMChatCompletionStreamResponse):
model_config = ConfigDict(arbitrary_types_allowed=True)
|
ChatCompletionStreamResponse
|
python
|
charliermarsh__ruff
|
crates/ruff_linter/resources/test/fixtures/flake8_annotations/annotation_presence.py
|
{
"start": 2774,
"end": 2925
}
|
class ____:
@decorator()
def __init__(self: "Foo", foo: int):
...
# Regression test for: https://github.com/astral-sh/ruff/issues/7711
|
Foo
|
python
|
celery__celery
|
t/unit/app/test_schedules.py
|
{
"start": 3356,
"end": 8966
}
|
class ____:
def crontab(self, *args, **kwargs):
return crontab(*args, **dict(kwargs, app=self.app))
def test_crontab_reduce(self):
c = self.crontab('*')
assert c == loads(dumps(c))
c = self.crontab(
minute='1',
hour='2',
day_of_week='3',
day_of_month='4',
month_of_year='5',
nowfun=utcnow)
assert c == loads(dumps(c))
def test_range_steps_not_enough(self):
with pytest.raises(crontab_parser.ParseException):
crontab_parser(24)._range_steps([1])
def test_parse_star(self):
assert crontab_parser(24).parse('*') == set(range(24))
assert crontab_parser(60).parse('*') == set(range(60))
assert crontab_parser(7).parse('*') == set(range(7))
assert crontab_parser(31, 1).parse('*') == set(range(1, 31 + 1))
assert crontab_parser(12, 1).parse('*') == set(range(1, 12 + 1))
def test_parse_range(self):
assert crontab_parser(60).parse('1-10') == set(range(1, 10 + 1))
assert crontab_parser(24).parse('0-20') == set(range(0, 20 + 1))
assert crontab_parser().parse('2-10') == set(range(2, 10 + 1))
assert crontab_parser(60, 1).parse('1-10') == set(range(1, 10 + 1))
def test_parse_range_wraps(self):
assert crontab_parser(12).parse('11-1') == {11, 0, 1}
assert crontab_parser(60, 1).parse('2-1') == set(range(1, 60 + 1))
def test_parse_groups(self):
assert crontab_parser().parse('1,2,3,4') == {1, 2, 3, 4}
assert crontab_parser().parse('0,15,30,45') == {0, 15, 30, 45}
assert crontab_parser(min_=1).parse('1,2,3,4') == {1, 2, 3, 4}
def test_parse_steps(self):
assert crontab_parser(8).parse('*/2') == {0, 2, 4, 6}
assert crontab_parser().parse('*/2') == {i * 2 for i in range(30)}
assert crontab_parser().parse('*/3') == {i * 3 for i in range(20)}
assert crontab_parser(8, 1).parse('*/2') == {1, 3, 5, 7}
assert crontab_parser(min_=1).parse('*/2') == {
i * 2 + 1 for i in range(30)
}
assert crontab_parser(min_=1).parse('*/3') == {
i * 3 + 1 for i in range(20)
}
def test_parse_composite(self):
assert crontab_parser(8).parse('*/2') == {0, 2, 4, 6}
assert crontab_parser().parse('2-9/5') == {2, 7}
assert crontab_parser().parse('2-10/5') == {2, 7}
assert crontab_parser(min_=1).parse('55-5/3') == {55, 58, 1, 4}
assert crontab_parser().parse('2-11/5,3') == {2, 3, 7}
assert crontab_parser().parse('2-4/3,*/5,0-21/4') == {
0, 2, 4, 5, 8, 10, 12, 15, 16, 20, 25, 30, 35, 40, 45, 50, 55,
}
assert crontab_parser().parse('1-9/2') == {1, 3, 5, 7, 9}
assert crontab_parser(8, 1).parse('*/2') == {1, 3, 5, 7}
assert crontab_parser(min_=1).parse('2-9/5') == {2, 7}
assert crontab_parser(min_=1).parse('2-10/5') == {2, 7}
assert crontab_parser(min_=1).parse('2-11/5,3') == {2, 3, 7}
assert crontab_parser(min_=1).parse('2-4/3,*/5,1-21/4') == {
1, 2, 5, 6, 9, 11, 13, 16, 17, 21, 26, 31, 36, 41, 46, 51, 56,
}
assert crontab_parser(min_=1).parse('1-9/2') == {1, 3, 5, 7, 9}
def test_parse_errors_on_empty_string(self):
with pytest.raises(ParseException):
crontab_parser(60).parse('')
def test_parse_errors_on_empty_group(self):
with pytest.raises(ParseException):
crontab_parser(60).parse('1,,2')
def test_parse_errors_on_empty_steps(self):
with pytest.raises(ParseException):
crontab_parser(60).parse('*/')
def test_parse_errors_on_negative_number(self):
with pytest.raises(ParseException):
crontab_parser(60).parse('-20')
def test_parse_errors_on_lt_min(self):
crontab_parser(min_=1).parse('1')
with pytest.raises(ValueError):
crontab_parser(12, 1).parse('0')
with pytest.raises(ValueError):
crontab_parser(24, 1).parse('12-0')
def test_parse_errors_on_gt_max(self):
crontab_parser(1).parse('0')
with pytest.raises(ValueError):
crontab_parser(1).parse('1')
with pytest.raises(ValueError):
crontab_parser(60).parse('61-0')
def test_expand_cronspec_eats_iterables(self):
assert crontab._expand_cronspec(iter([1, 2, 3]), 100) == {1, 2, 3}
assert crontab._expand_cronspec(iter([1, 2, 3]), 100, 1) == {1, 2, 3}
def test_expand_cronspec_invalid_type(self):
with pytest.raises(TypeError):
crontab._expand_cronspec(object(), 100)
def test_repr(self):
assert '*' in repr(self.crontab('*'))
def test_eq(self):
assert (self.crontab(day_of_week='1, 2') ==
self.crontab(day_of_week='1-2'))
assert (self.crontab(day_of_month='1, 16, 31') ==
self.crontab(day_of_month='*/15'))
assert (
self.crontab(
minute='1', hour='2', day_of_week='5',
day_of_month='10', month_of_year='5') ==
self.crontab(
minute='1', hour='2', day_of_week='5',
day_of_month='10', month_of_year='5'))
assert crontab(minute='1') != crontab(minute='2')
assert (self.crontab(month_of_year='1') !=
self.crontab(month_of_year='2'))
assert object() != self.crontab(minute='1')
assert self.crontab(minute='1') != object()
assert crontab(month_of_year='1') != schedule(10)
|
test_crontab_parser
|
python
|
pypa__pipenv
|
pipenv/patched/pip/_internal/commands/inspect.py
|
{
"start": 697,
"end": 3324
}
|
class ____(Command):
"""
Inspect the content of a Python environment and produce a report in JSON format.
"""
ignore_require_venv = True
usage = """
%prog [options]"""
def add_options(self) -> None:
self.cmd_opts.add_option(
"--local",
action="store_true",
default=False,
help=(
"If in a virtualenv that has global access, do not list "
"globally-installed packages."
),
)
self.cmd_opts.add_option(
"--user",
dest="user",
action="store_true",
default=False,
help="Only output packages installed in user-site.",
)
self.cmd_opts.add_option(cmdoptions.list_path())
self.parser.insert_option_group(0, self.cmd_opts)
def run(self, options: Values, args: List[str]) -> int:
cmdoptions.check_list_path_option(options)
dists = get_environment(options.path).iter_installed_distributions(
local_only=options.local,
user_only=options.user,
skip=set(stdlib_pkgs),
)
output = {
"version": "1",
"pip_version": __version__,
"installed": [self._dist_to_dict(dist) for dist in dists],
"environment": default_environment(),
# TODO tags? scheme?
}
print_json(data=output)
return SUCCESS
def _dist_to_dict(self, dist: BaseDistribution) -> Dict[str, Any]:
res: Dict[str, Any] = {
"metadata": dist.metadata_dict,
"metadata_location": dist.info_location,
}
# direct_url. Note that we don't have download_info (as in the installation
# report) since it is not recorded in installed metadata.
direct_url = dist.direct_url
if direct_url is not None:
res["direct_url"] = direct_url.to_dict()
else:
# Emulate direct_url for legacy editable installs.
editable_project_location = dist.editable_project_location
if editable_project_location is not None:
res["direct_url"] = {
"url": path_to_url(editable_project_location),
"dir_info": {
"editable": True,
},
}
# installer
installer = dist.installer
if dist.installer:
res["installer"] = installer
# requested
if dist.installed_with_dist_info:
res["requested"] = dist.requested
return res
|
InspectCommand
|
python
|
bokeh__bokeh
|
tests/unit/bokeh/embed/test_wrappers__embed.py
|
{
"start": 1619,
"end": 1796
}
|
class ____:
def test_render(self) -> None:
assert bew.wrap_in_safely("code\nmorecode") == """\
Bokeh.safely(function() {
code
morecode
});\
"""
|
Test_wrap_in_safely
|
python
|
vyperlang__vyper
|
vyper/exceptions.py
|
{
"start": 9125,
"end": 9197
}
|
class ____(VyperException):
"""Illegal function call."""
|
CallViolation
|
python
|
pytorch__pytorch
|
torch/_inductor/template_heuristics/triton.py
|
{
"start": 90831,
"end": 91593
}
|
class ____(
MMPlusMMTemplateConfigMixin, CPUConfigHeuristic
):
"""MM Plus MM template heuristic for CPU"""
def __init__(self) -> None:
super().__init__()
# Override mm_configs to use mm_plus_mm_configs
self.mm_configs = self.mm_plus_mm_configs
# NOTE: overriding exhaustive configs here to be the same as mm_configs
# as we haven't validated exhaustive support here yet
# TODO(coconutruben): remove this once we have validated exhaustive support
# for scaled_mm
self.exhaustive_configs = self.mm_plus_mm_configs
# XPU template-specific classes
@register_template_heuristic(mm_template.uid, "xpu")
@register_template_heuristic(bmm_template.uid, "xpu")
|
CPUMMPlusMMTemplateConfigHeuristic
|
python
|
anthropics__anthropic-sdk-python
|
src/anthropic/types/beta/beta_mcp_tool_result_block.py
|
{
"start": 273,
"end": 439
}
|
class ____(BaseModel):
content: Union[str, List[BetaTextBlock]]
is_error: bool
tool_use_id: str
type: Literal["mcp_tool_result"]
|
BetaMCPToolResultBlock
|
python
|
django__django
|
django/db/migrations/operations/fields.py
|
{
"start": 245,
"end": 2638
}
|
class ____(Operation):
def __init__(self, model_name, name, field=None):
self.model_name = model_name
self.name = name
self.field = field
@cached_property
def model_name_lower(self):
return self.model_name.lower()
@cached_property
def name_lower(self):
return self.name.lower()
def is_same_model_operation(self, operation):
return self.model_name_lower == operation.model_name_lower
def is_same_field_operation(self, operation):
return (
self.is_same_model_operation(operation)
and self.name_lower == operation.name_lower
)
def references_model(self, name, app_label):
name_lower = name.lower()
if name_lower == self.model_name_lower:
return True
if self.field:
return bool(
field_references(
(app_label, self.model_name_lower),
self.field,
(app_label, name_lower),
)
)
return False
def references_field(self, model_name, name, app_label):
model_name_lower = model_name.lower()
# Check if this operation locally references the field.
if model_name_lower == self.model_name_lower:
if name == self.name:
return True
if self.field:
if (
hasattr(self.field, "from_fields")
and name in self.field.from_fields
):
return True
elif self.field.generated and any(
field_name == name
for field_name, *_ in Model._get_expr_references(
self.field.expression
)
):
return True
# Check if this operation remotely references the field.
if self.field is None:
return False
return bool(
field_references(
(app_label, self.model_name_lower),
self.field,
(app_label, model_name_lower),
name,
)
)
def reduce(self, operation, app_label):
return super().reduce(operation, app_label) or not operation.references_field(
self.model_name, self.name, app_label
)
|
FieldOperation
|
python
|
huggingface__transformers
|
src/transformers/models/gemma2/modular_gemma2.py
|
{
"start": 18807,
"end": 22231
}
|
class ____(GemmaModel):
def __init__(self, config: Gemma2Config):
super().__init__(config)
self.layers = nn.ModuleList(
[Gemma2DecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
)
self.rotary_emb = Gemma2RotaryEmbedding(config)
def forward(
self,
input_ids: Optional[torch.LongTensor] = None,
attention_mask: Optional[torch.Tensor] = None,
position_ids: Optional[torch.LongTensor] = None,
past_key_values: Optional[Cache] = None,
inputs_embeds: Optional[torch.FloatTensor] = None,
use_cache: Optional[bool] = None,
cache_position: Optional[torch.LongTensor] = None,
**kwargs: Unpack[TransformersKwargs],
) -> BaseModelOutputWithPast:
if (input_ids is None) ^ (inputs_embeds is not None):
raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
if inputs_embeds is None:
inputs_embeds: torch.Tensor = self.embed_tokens(input_ids)
if use_cache and past_key_values is None:
past_key_values = DynamicCache(config=self.config)
if cache_position is None:
past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
cache_position = torch.arange(
past_seen_tokens, past_seen_tokens + inputs_embeds.shape[1], device=inputs_embeds.device
)
if position_ids is None:
position_ids = cache_position.unsqueeze(0)
# It may already have been prepared by e.g. `generate`
if not isinstance(causal_mask_mapping := attention_mask, dict):
# Prepare mask arguments
mask_kwargs = {
"config": self.config,
"input_embeds": inputs_embeds,
"attention_mask": attention_mask,
"cache_position": cache_position,
"past_key_values": past_key_values,
"position_ids": position_ids,
}
# Create the masks
causal_mask_mapping = {
"full_attention": create_causal_mask(**mask_kwargs),
"sliding_attention": create_sliding_window_causal_mask(**mask_kwargs),
}
# embed positions
hidden_states = inputs_embeds
position_embeddings = self.rotary_emb(hidden_states, position_ids)
# normalized
# Gemma2 downcasts the below to float16, causing sqrt(3072)=55.4256 to become 55.5
# See https://github.com/huggingface/transformers/pull/29402
normalizer = torch.tensor(self.config.hidden_size**0.5, dtype=hidden_states.dtype)
hidden_states = hidden_states * normalizer
for decoder_layer in self.layers[: self.config.num_hidden_layers]:
hidden_states = decoder_layer(
hidden_states,
attention_mask=causal_mask_mapping[decoder_layer.attention_type],
position_embeddings=position_embeddings,
position_ids=position_ids,
past_key_values=past_key_values,
cache_position=cache_position,
**kwargs,
)
hidden_states = self.norm(hidden_states)
return BaseModelOutputWithPast(
last_hidden_state=hidden_states,
past_key_values=past_key_values,
)
|
Gemma2Model
|
python
|
joke2k__faker
|
faker/providers/date_time/hy_AM/__init__.py
|
{
"start": 46,
"end": 791
}
|
class ____(DateTimeProvider):
DAY_NAMES = {
"0": "Կիրակի",
"1": "Երկուշաբթի",
"2": "Երեքշաբթի",
"3": "Չորեքշաբթի",
"4": "Հինգշաբթի",
"5": "Ուրբաթ",
"6": "Շաբաթ",
}
MONTH_NAMES = {
"01": "Հունվար",
"02": "Փետրվար",
"03": "Մարտ",
"04": "Ապրիլ",
"05": "Մայիս",
"06": "Հունիս",
"07": "Հուլիս",
"08": "Օգոստոս",
"09": "Սեպտեմբեր",
"10": "Հոկտեմբեր",
"11": "Նոյեմբեր",
"12": "Դեկտեմբեր",
}
def day_of_week(self):
day = self.date("%w")
return self.DAY_NAMES[day]
def month_name(self):
month = self.month()
return self.MONTH_NAMES[month]
|
Provider
|
python
|
getsentry__sentry
|
tests/sentry/notifications/notification_action/test_issue_alert_registry_handlers.py
|
{
"start": 2377,
"end": 11729
}
|
class ____(BaseWorkflowTest):
def setUp(self) -> None:
super().setUp()
self.project = self.create_project()
self.detector = self.create_detector(project=self.project)
self.workflow = self.create_workflow(environment=self.environment)
self.rule = self.create_project_rule(project=self.project)
self.alert_rule_workflow = self.create_alert_rule_workflow(
workflow=self.workflow, rule_id=self.rule.id
)
self.action = self.create_action(
type=Action.Type.DISCORD,
integration_id="1234567890",
config={"target_identifier": "channel456", "target_type": ActionTarget.SPECIFIC},
data={"tags": "environment,user,my_tag"},
)
self.group, self.event, self.group_event = self.create_group_event()
self.event_data = WorkflowEventData(
event=self.group_event, workflow_env=self.environment, group=self.group
)
self.action.workflow_id = self.workflow.id
class TestHandler(BaseIssueAlertHandler):
@classmethod
def get_additional_fields(cls, action: Action, mapping: ActionFieldMapping):
return {"tags": "environment,user,my_tag"}
@classmethod
def get_target_display(cls, action: Action, mapping: ActionFieldMapping):
return {}
self.handler = TestHandler()
def test_create_rule_instance_from_action_missing_properties_raises_value_error(self) -> None:
class TestHandler(BaseIssueAlertHandler):
@classmethod
def get_additional_fields(cls, action: Action, mapping: ActionFieldMapping):
return {"tags": "environment,user,my_tag"}
handler = TestHandler()
with pytest.raises(ValueError):
handler.create_rule_instance_from_action(self.action, self.detector, self.event_data)
def test_create_rule_instance_from_action_missing_workflow_id_raises_value_error(self) -> None:
job = WorkflowEventData(
event=self.group_event, workflow_env=self.environment, group=self.group
)
action = self.create_action(
type=Action.Type.DISCORD,
integration_id="1234567890",
config={"target_identifier": "channel456", "target_type": ActionTarget.SPECIFIC},
data={"tags": "environment,user,my_tag"},
)
with pytest.raises(ValueError):
self.handler.create_rule_instance_from_action(action, self.detector, job)
def test_create_rule_instance_from_action_missing_rule_raises_value_error(self) -> None:
job = WorkflowEventData(
event=self.group_event, workflow_env=self.environment, group=self.group
)
alert_rule = self.create_alert_rule(projects=[self.project], organization=self.organization)
self.create_alert_rule_workflow(workflow=self.workflow, alert_rule_id=alert_rule.id)
action = self.create_action(
type=Action.Type.DISCORD,
integration_id="1234567890",
config={"target_identifier": "channel456", "target_type": ActionTarget.SPECIFIC},
data={"tags": "environment,user,my_tag"},
)
with pytest.raises(ValueError):
self.handler.create_rule_instance_from_action(action, self.detector, job)
def test_create_rule_instance_from_action(self) -> None:
"""Test that create_rule_instance_from_action creates a Rule with correct attributes"""
rule = self.handler.create_rule_instance_from_action(
self.action, self.detector, self.event_data
)
assert isinstance(rule, Rule)
assert rule.id == self.action.id
assert rule.project == self.detector.project
assert rule.environment_id is not None
assert self.workflow.environment is not None
assert rule.environment_id == self.workflow.environment.id
assert rule.label == rule.label
assert rule.data == {
"actions": [
{
"id": "sentry.integrations.discord.notify_action.DiscordNotifyServiceAction",
"server": "1234567890",
"channel_id": "channel456",
"tags": "environment,user,my_tag",
"legacy_rule_id": self.rule.id,
}
],
}
assert rule.status == ObjectStatus.ACTIVE
assert rule.source == RuleSource.ISSUE
@with_feature("organizations:workflow-engine-ui-links")
def test_create_rule_instance_from_action_with_workflow_engine_ui_feature_flag(self) -> None:
"""Test that create_rule_instance_from_action creates a Rule with correct attributes"""
rule = self.handler.create_rule_instance_from_action(
self.action, self.detector, self.event_data
)
assert isinstance(rule, Rule)
assert rule.id == self.action.id
assert rule.project == self.detector.project
assert rule.environment_id is not None
assert self.workflow.environment is not None
assert rule.environment_id == self.workflow.environment.id
assert rule.label == self.detector.name
assert rule.data == {
"actions": [
{
"id": "sentry.integrations.discord.notify_action.DiscordNotifyServiceAction",
"server": "1234567890",
"channel_id": "channel456",
"tags": "environment,user,my_tag",
"workflow_id": self.workflow.id,
}
]
}
assert rule.status == ObjectStatus.ACTIVE
assert rule.source == RuleSource.ISSUE
def test_create_rule_instance_from_action_no_environment(self) -> None:
"""Test that create_rule_instance_from_action creates a Rule with correct attributes"""
self.create_workflow()
job = WorkflowEventData(event=self.group_event, workflow_env=None, group=self.group)
rule = self.handler.create_rule_instance_from_action(self.action, self.detector, job)
assert isinstance(rule, Rule)
assert rule.id == self.action.id
assert rule.project == self.detector.project
assert rule.environment_id is None
assert rule.label == rule.label
assert rule.data == {
"actions": [
{
"id": "sentry.integrations.discord.notify_action.DiscordNotifyServiceAction",
"server": "1234567890",
"channel_id": "channel456",
"tags": "environment,user,my_tag",
"legacy_rule_id": self.rule.id,
}
],
}
assert rule.status == ObjectStatus.ACTIVE
assert rule.source == RuleSource.ISSUE
@with_feature("organizations:workflow-engine-ui-links")
def test_create_rule_instance_from_action_no_environment_with_workflow_engine_ui_feature_flag(
self,
):
"""Test that create_rule_instance_from_action creates a Rule with correct attributes"""
self.create_workflow()
job = WorkflowEventData(event=self.group_event, workflow_env=None, group=self.group)
rule = self.handler.create_rule_instance_from_action(self.action, self.detector, job)
assert isinstance(rule, Rule)
assert rule.id == self.action.id
assert rule.project == self.detector.project
assert rule.environment_id is None
assert rule.label == self.detector.name
assert rule.data == {
"actions": [
{
"id": "sentry.integrations.discord.notify_action.DiscordNotifyServiceAction",
"server": "1234567890",
"channel_id": "channel456",
"tags": "environment,user,my_tag",
"workflow_id": self.workflow.id,
}
]
}
assert rule.status == ObjectStatus.ACTIVE
assert rule.source == RuleSource.ISSUE
@mock.patch("sentry.notifications.notification_action.types.invoke_future_with_error_handling")
@mock.patch("sentry.notifications.notification_action.types.activate_downstream_actions")
@mock.patch("uuid.uuid4")
def test_invoke_legacy_registry(
self, mock_uuid, mock_activate_downstream_actions, mock_invoke_future_with_error_handling
):
# Test that invoke_legacy_registry correctly processes the action
mock_uuid.return_value = uuid.UUID("12345678-1234-5678-1234-567812345678")
# Mock callback and futures
mock_callback = mock.Mock()
mock_futures = [mock.Mock()]
mock_activate_downstream_actions.return_value = {"some_key": (mock_callback, mock_futures)}
self.handler.invoke_legacy_registry(self.event_data, self.action, self.detector)
# Verify activate_downstream_actions called with correct args
mock_activate_downstream_actions.assert_called_once_with(
mock.ANY, self.event_data.event, "12345678-1234-5678-1234-567812345678" # Rule instance
)
# Verify callback execution
mock_invoke_future_with_error_handling.assert_called_once_with(
self.event_data, mock_callback, mock_futures
)
|
TestBaseIssueAlertHandler
|
python
|
PrefectHQ__prefect
|
src/integrations/prefect-github/prefect_github/schemas/graphql_schema.py
|
{
"start": 253653,
"end": 254009
}
|
class ____(sgqlc.types.Type):
"""
See source code for more info.
"""
__schema__ = graphql_schema
__field_names__ = ("check_suite", "client_mutation_id")
check_suite = sgqlc.types.Field("CheckSuite", graphql_name="checkSuite")
client_mutation_id = sgqlc.types.Field(String, graphql_name="clientMutationId")
|
CreateCheckSuitePayload
|
python
|
PrefectHQ__prefect
|
src/prefect/exceptions.py
|
{
"start": 11230,
"end": 11341
}
|
class ____(PrefectException):
"""Raised when attempting to unpause a run that isn't paused."""
|
NotPausedError
|
python
|
huggingface__transformers
|
src/transformers/models/roformer/modeling_roformer.py
|
{
"start": 26870,
"end": 27581
}
|
class ____(nn.Module):
def __init__(self, config):
super().__init__()
self.transform = RoFormerPredictionHeadTransform(config)
# The output weights are the same as the input embeddings, but there is
# an output-only bias for each token.
self.decoder = nn.Linear(config.embedding_size, config.vocab_size, bias=True)
self.bias = nn.Parameter(torch.zeros(config.vocab_size))
def forward(self, hidden_states):
hidden_states = self.transform(hidden_states)
hidden_states = self.decoder(hidden_states)
return hidden_states
# Copied from transformers.models.bert.modeling_bert.BertOnlyMLMHead with Bert->RoFormer
|
RoFormerLMPredictionHead
|
python
|
django__django
|
tests/admin_inlines/models.py
|
{
"start": 2283,
"end": 2403
}
|
class ____(models.Model):
dummy = models.IntegerField()
holder = models.ForeignKey(Holder2, models.CASCADE)
|
Inner2
|
python
|
weaviate__weaviate-python-client
|
weaviate/collections/classes/config.py
|
{
"start": 61931,
"end": 62077
}
|
class ____(_ConfigBase):
encoding: Optional[_MuveraConfig]
aggregation: str
MultiVector = _MultiVectorConfig
@dataclass
|
_MultiVectorConfig
|
python
|
scipy__scipy
|
scipy/signal/tests/test_peak_finding.py
|
{
"start": 32211,
"end": 36023
}
|
class ____:
def test_find_peaks_exact(self):
"""
Generate a series of gaussians and attempt to find the peak locations.
"""
sigmas = [5.0, 3.0, 10.0, 20.0, 10.0, 50.0]
num_points = 500
test_data, act_locs = _gen_gaussians_even(sigmas, num_points)
widths = np.arange(0.1, max(sigmas))
found_locs = find_peaks_cwt(test_data, widths, gap_thresh=2, min_snr=0,
min_length=None)
xp_assert_equal(found_locs, act_locs,
check_dtype=False,
err_msg="Found maximum locations did not equal those expected"
)
def test_find_peaks_withnoise(self):
"""
Verify that peak locations are (approximately) found
for a series of gaussians with added noise.
"""
sigmas = [5.0, 3.0, 10.0, 20.0, 10.0, 50.0]
num_points = 500
test_data, act_locs = _gen_gaussians_even(sigmas, num_points)
widths = np.arange(0.1, max(sigmas))
noise_amp = 0.07
rng = np.random.default_rng(18181911)
test_data += (rng.random(num_points) - 0.5)*(2*noise_amp)
found_locs = find_peaks_cwt(test_data, widths, min_length=15,
gap_thresh=1, min_snr=noise_amp / 5)
err_msg ='Different number of peaks found than expected'
assert len(found_locs) == len(act_locs), err_msg
diffs = np.abs(found_locs - act_locs)
max_diffs = np.array(sigmas) / 5
np.testing.assert_array_less(diffs, max_diffs, 'Maximum location differed' +
f'by more than {max_diffs}')
def test_find_peaks_nopeak(self):
"""
Verify that no peak is found in
data that's just noise.
"""
noise_amp = 1.0
num_points = 100
rng = np.random.RandomState(181819141)
test_data = (rng.rand(num_points) - 0.5)*(2*noise_amp)
widths = np.arange(10, 50)
found_locs = find_peaks_cwt(test_data, widths, min_snr=5, noise_perc=30)
assert len(found_locs) == 0
def test_find_peaks_with_non_default_wavelets(self):
x = gaussian(200, 2)
widths = np.array([1, 2, 3, 4])
a = find_peaks_cwt(x, widths, wavelet=gaussian)
xp_assert_equal(a, np.asarray([100]), check_dtype=False)
def test_find_peaks_window_size(self):
"""
Verify that window_size is passed correctly to private function and
affects the result.
"""
sigmas = [2.0, 2.0]
num_points = 1000
test_data, act_locs = _gen_gaussians_even(sigmas, num_points)
widths = np.arange(0.1, max(sigmas), 0.2)
noise_amp = 0.05
rng = np.random.RandomState(18181911)
test_data += (rng.rand(num_points) - 0.5)*(2*noise_amp)
# Possibly contrived negative region to throw off peak finding
# when window_size is too large
test_data[250:320] -= 1
found_locs = find_peaks_cwt(test_data, widths, gap_thresh=2, min_snr=3,
min_length=None, window_size=None)
with pytest.raises(AssertionError):
assert found_locs.size == act_locs.size
found_locs = find_peaks_cwt(test_data, widths, gap_thresh=2, min_snr=3,
min_length=None, window_size=20)
assert found_locs.size == act_locs.size
def test_find_peaks_with_one_width(self):
"""
Verify that the `width` argument
in `find_peaks_cwt` can be a float
"""
xs = np.arange(0, np.pi, 0.05)
test_data = np.sin(xs)
widths = 1
found_locs = find_peaks_cwt(test_data, widths)
np.testing.assert_equal(found_locs, 32)
|
TestFindPeaksCwt
|
python
|
huggingface__transformers
|
src/transformers/models/conditional_detr/modeling_conditional_detr.py
|
{
"start": 44619,
"end": 46285
}
|
class ____(PreTrainedModel):
config: ConditionalDetrConfig
base_model_prefix = "model"
main_input_name = "pixel_values"
input_modalities = ("image",)
_no_split_modules = [r"ConditionalDetrConvEncoder", r"ConditionalDetrEncoderLayer", r"ConditionalDetrDecoderLayer"]
@torch.no_grad()
def _init_weights(self, module):
std = self.config.init_std
xavier_std = self.config.init_xavier_std
if isinstance(module, ConditionalDetrMHAttentionMap):
init.zeros_(module.k_linear.bias)
init.zeros_(module.q_linear.bias)
init.xavier_uniform_(module.k_linear.weight, gain=xavier_std)
init.xavier_uniform_(module.q_linear.weight, gain=xavier_std)
elif isinstance(module, ConditionalDetrLearnedPositionEmbedding):
init.uniform_(module.row_embeddings.weight)
init.uniform_(module.column_embeddings.weight)
if 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.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])
# Copied from transformers.models.detr.modeling_detr.DetrEncoder with Detr->ConditionalDetr,DETR->ConditionalDETR
|
ConditionalDetrPreTrainedModel
|
python
|
cython__cython
|
Demos/benchmarks/bm_richards_cclass.py
|
{
"start": 6443,
"end": 6916
}
|
class ____(Task):
def __init__(self,i,p,w,s,r):
Task.__init__(self,i,0,None,s,r)
def fn(self, pkt: Packet | None, r: IdleTaskRec):
i = r
i.count -= 1
if i.count == 0:
return self.hold()
elif i.control & 1 == 0:
i.control //= 2
return self.release(I_DEVA)
else:
i.control = i.control//2 ^ 0xd008
return self.release(I_DEVB)
# WorkTask
A = ord('A')
|
IdleTask
|
python
|
dagster-io__dagster
|
python_modules/libraries/dagster-dlt/dagster_dlt/components/dlt_load_collection/scaffolder.py
|
{
"start": 626,
"end": 3347
}
|
class ____(NamedTuple):
imports: list[str]
pipelines_and_sources: Mapping[str, PipelineAndSource]
def _extract_pipeline_and_source_from_init_file(
node: ast.FunctionDef,
) -> PipelineAndSource:
"""Given a function body AST node, extracts the source code for the
local Pipeline and DltSource objects.
"""
pipeline_src = None
source_src = None
for stmt in node.body:
if isinstance(stmt, ast.Assign):
target = stmt.targets[0]
if isinstance(target, ast.Name):
var_name = target.id
if var_name == "pipeline":
pipeline_src = ast.unparse(stmt)
elif var_name == "data":
source_src = ast.unparse(stmt)
return PipelineAndSource(check.not_none(pipeline_src), check.not_none(source_src))
def _extract_pipelines_and_sources_from_pipeline_file(
file_path: Path,
) -> ParsedPipelineAndSource:
"""Process a Python file and generate a new file with pipeline and data definitions."""
imports = []
pipelines_and_sources = {}
source = file_path.read_text()
tree = ast.parse(source)
# Create new file content
new_content = []
new_content.append('"""Generated pipeline and data definitions."""\n')
# Add imports from original file
for node in tree.body:
if isinstance(node, ast.Import) or isinstance(node, ast.ImportFrom):
imports.append(ast.unparse(node).replace("from ", "from ."))
# Process each function
for node in tree.body:
if isinstance(node, ast.FunctionDef):
pipelines_and_sources[node.name.removeprefix("load_")] = (
_extract_pipeline_and_source_from_init_file(node)
)
return ParsedPipelineAndSource(imports, pipelines_and_sources)
def _process_pipeline(src: str) -> str:
return src.replace(", dev_mode=True", "")
def _construct_pipeline_source_file(
file_path: Path,
parsed_pipeline_and_source: ParsedPipelineAndSource,
) -> None:
"""Construct a new pipeline source file from a set of pipeline and source definitions."""
new_content = []
for import_line in parsed_pipeline_and_source.imports:
new_content.append(import_line)
new_content.append("\n")
for load_name, (
pipeline_src,
source_src,
) in parsed_pipeline_and_source.pipelines_and_sources.items():
new_content.append(source_src.replace("data =", f"{load_name}_source ="))
new_content.append(
_process_pipeline(pipeline_src).replace("pipeline =", f"{load_name}_pipeline =")
)
new_content.append("")
file_path.write_text("\n".join(new_content))
|
ParsedPipelineAndSource
|
python
|
ApeWorX__ape
|
src/ape/types/coverage.py
|
{
"start": 9675,
"end": 12440
}
|
class ____(BaseModel):
"""
An individual source file with coverage collected.
"""
source_id: str
"""
The ID of the source covered.
"""
contracts: list[ContractCoverage] = []
"""
Coverage for each contract in the source file.
"""
@property
def statements(self) -> list[CoverageStatement]:
"""
All valid coverage lines from every function in every contract in this source.
"""
return list(itertools.chain.from_iterable(c.statements for c in self.contracts))
@property
def lines_covered(self) -> NonNegativeInt:
"""
All lines with a hit count greater than zero from every function
in every contract in this source.
"""
return sum(c.lines_covered for c in self.contracts)
@property
def lines_valid(self) -> NonNegativeInt:
"""
The number of lines valid for coverage.
"""
return len(self.statements)
@property
def miss_count(self) -> NonNegativeInt:
"""
The number of lines missed.
"""
return self.lines_valid - self.lines_covered
@property
def line_rate(self) -> float:
"""
The number of lines hit divided by number of lines.
"""
return self.lines_covered / self.lines_valid if self.lines_valid > 0 else 0
@property
def total_functions(self) -> NonNegativeInt:
"""
The total number of functions in this source.
"""
return sum(len(c.functions) for c in self.contracts)
@property
def function_hits(self) -> NonNegativeInt:
"""
The number of functions with a hit counter greater than zero.
"""
return sum(c.function_hits for c in self.contracts)
@property
def function_rate(self) -> float:
"""
The rate of functions hit versus total functions.
"""
return self.function_hits / self.total_functions if self.total_functions > 0 else 0
def model_dump(self, *args, **kwargs) -> dict:
attribs = super().model_dump(*args, **kwargs)
# Add coverage stats.
attribs["lines_covered"] = self.lines_covered
attribs["lines_valid"] = self.lines_valid
attribs["line_rate"] = self.line_rate
return attribs
def include(self, contract_name: str) -> ContractCoverage:
"""
Ensure a contract is included in the report.
"""
for contract in self.contracts:
if contract.name == contract_name:
return contract
# Include the contract.
contract_cov = ContractCoverage(name=contract_name)
self.contracts.append(contract_cov)
return contract_cov
|
ContractSourceCoverage
|
python
|
getsentry__sentry
|
tests/sentry/workflow_engine/processors/test_data_condition_group.py
|
{
"start": 11712,
"end": 13780
}
|
class ____(TestEvaluationConditionCase):
def setUp(self) -> None:
super().setUp()
self.data_condition_group.logic_type = DataConditionGroup.Type.NONE
def test_evaluate_data_conditions__all_conditions_pass__fails(self) -> None:
result = evaluate_data_conditions(
self.get_conditions_to_evaluate(10), self.data_condition_group.logic_type
)
expected_result = ProcessedDataConditionGroup(
logic_result=TriggerResult.FALSE,
condition_results=[],
)
assert result == expected_result
def test_evaluate_data_conditions__one_condition_pass__fails(self) -> None:
result = evaluate_data_conditions(
self.get_conditions_to_evaluate(4), self.data_condition_group.logic_type
)
expected_result = ProcessedDataConditionGroup(
logic_result=TriggerResult.FALSE,
condition_results=[],
)
assert result == expected_result
def test_evaluate_data_conditions__no_conditions_pass__passes(self) -> None:
result = evaluate_data_conditions(
self.get_conditions_to_evaluate(1), self.data_condition_group.logic_type
)
expected_result = ProcessedDataConditionGroup(
logic_result=TriggerResult.TRUE,
condition_results=[],
)
assert result == expected_result
def test_evaluate_data_conditions__error_with_no_pass__tainted_true(self) -> None:
error = ConditionError(msg="test error")
with (
mock.patch.object(self.data_condition, "evaluate_value", return_value=None),
mock.patch.object(self.data_condition_two, "evaluate_value", return_value=error),
):
result = evaluate_data_conditions(
self.get_conditions_to_evaluate(10), self.data_condition_group.logic_type
)
assert result.logic_result.triggered is True
assert result.logic_result.error == error
assert result.condition_results == []
|
TestEvaluateConditionGroupTypeNone
|
python
|
pytorch__pytorch
|
test/test_fx_passes.py
|
{
"start": 6399,
"end": 6828
}
|
class ____(OperatorSupport):
def is_node_supported(self, submodules, node: torch.fx.Node) -> bool:
return (node.op == "call_function" and
node.target in {operator.add, operator.getitem,
torch.ops.aten.view,
torch.ops.aten.permute,
torch.ops.aten.std_mean})
@instantiate_parametrized_tests
|
MockOperatorSupport
|
python
|
PyCQA__pyflakes
|
pyflakes/messages.py
|
{
"start": 5993,
"end": 6163
}
|
class ____(Message):
"""
Indicates an except: block as not the last exception handler.
"""
message = 'default \'except:\' must be last'
|
DefaultExceptNotLast
|
python
|
django__django
|
tests/one_to_one/models.py
|
{
"start": 814,
"end": 977
}
|
class ____(models.Model):
place = models.OneToOneField(Place, models.SET_NULL, null=True)
serves_cocktails = models.BooleanField(default=True)
|
UndergroundBar
|
python
|
huggingface__transformers
|
tests/models/speecht5/test_processing_speecht5.py
|
{
"start": 1202,
"end": 7063
}
|
class ____(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.tmpdirname = tempfile.mkdtemp()
tokenizer = SpeechT5Tokenizer(SAMPLE_VOCAB)
tokenizer.save_pretrained(cls.tmpdirname)
feature_extractor_map = {
"feature_size": 1,
"padding_value": 0.0,
"sampling_rate": 16000,
"do_normalize": False,
"num_mel_bins": 80,
"hop_length": 16,
"win_length": 64,
"win_function": "hann_window",
"fmin": 80,
"fmax": 7600,
"mel_floor": 1e-10,
"reduction_factor": 2,
"return_attention_mask": True,
}
feature_extractor = SpeechT5FeatureExtractor(**feature_extractor_map)
tokenizer = SpeechT5Tokenizer.from_pretrained(cls.tmpdirname)
processor = SpeechT5Processor(tokenizer=tokenizer, feature_extractor=feature_extractor)
processor.save_pretrained(cls.tmpdirname)
def get_tokenizer(self, **kwargs):
return SpeechT5Tokenizer.from_pretrained(self.tmpdirname, **kwargs)
def get_feature_extractor(self, **kwargs):
return SpeechT5FeatureExtractor.from_pretrained(self.tmpdirname, **kwargs)
@classmethod
def tearDownClass(cls):
shutil.rmtree(cls.tmpdirname, ignore_errors=True)
def test_save_load_pretrained_default(self):
tokenizer = self.get_tokenizer()
feature_extractor = self.get_feature_extractor()
processor = SpeechT5Processor(tokenizer=tokenizer, feature_extractor=feature_extractor)
processor.save_pretrained(self.tmpdirname)
processor = SpeechT5Processor.from_pretrained(self.tmpdirname)
self.assertEqual(processor.tokenizer.get_vocab(), tokenizer.get_vocab())
self.assertIsInstance(processor.tokenizer, SpeechT5Tokenizer)
self.assertEqual(processor.feature_extractor.to_json_string(), feature_extractor.to_json_string())
self.assertIsInstance(processor.feature_extractor, SpeechT5FeatureExtractor)
def test_save_load_pretrained_additional_features(self):
with tempfile.TemporaryDirectory() as tmpdir:
processor = SpeechT5Processor(
tokenizer=self.get_tokenizer(), feature_extractor=self.get_feature_extractor()
)
processor.save_pretrained(tmpdir)
tokenizer_add_kwargs = SpeechT5Tokenizer.from_pretrained(tmpdir, bos_token="(BOS)", eos_token="(EOS)")
feature_extractor_add_kwargs = SpeechT5FeatureExtractor.from_pretrained(
tmpdir, do_normalize=False, padding_value=1.0
)
processor = SpeechT5Processor.from_pretrained(
tmpdir, bos_token="(BOS)", eos_token="(EOS)", do_normalize=False, padding_value=1.0
)
self.assertEqual(processor.tokenizer.get_vocab(), tokenizer_add_kwargs.get_vocab())
self.assertIsInstance(processor.tokenizer, SpeechT5Tokenizer)
self.assertEqual(processor.feature_extractor.to_json_string(), feature_extractor_add_kwargs.to_json_string())
self.assertIsInstance(processor.feature_extractor, SpeechT5FeatureExtractor)
def test_feature_extractor(self):
feature_extractor = self.get_feature_extractor()
tokenizer = self.get_tokenizer()
processor = SpeechT5Processor(tokenizer=tokenizer, feature_extractor=feature_extractor)
raw_speech = floats_list((3, 1000))
input_feat_extract = feature_extractor(audio=raw_speech, return_tensors="np")
input_processor = processor(audio=raw_speech, return_tensors="np")
for key in input_feat_extract:
self.assertAlmostEqual(input_feat_extract[key].sum(), input_processor[key].sum(), delta=1e-2)
def test_feature_extractor_target(self):
feature_extractor = self.get_feature_extractor()
tokenizer = self.get_tokenizer()
processor = SpeechT5Processor(tokenizer=tokenizer, feature_extractor=feature_extractor)
raw_speech = floats_list((3, 1000))
input_feat_extract = feature_extractor(audio_target=raw_speech, return_tensors="np")
input_processor = processor(audio_target=raw_speech, return_tensors="np")
for key in input_feat_extract:
self.assertAlmostEqual(input_feat_extract[key].sum(), input_processor[key].sum(), delta=1e-2)
def test_tokenizer(self):
feature_extractor = self.get_feature_extractor()
tokenizer = self.get_tokenizer()
processor = SpeechT5Processor(tokenizer=tokenizer, feature_extractor=feature_extractor)
input_str = "This is a test string"
encoded_processor = processor(text=input_str)
encoded_tok = tokenizer(input_str)
for key in encoded_tok:
self.assertListEqual(encoded_tok[key], encoded_processor[key])
def test_tokenizer_target(self):
feature_extractor = self.get_feature_extractor()
tokenizer = self.get_tokenizer()
processor = SpeechT5Processor(tokenizer=tokenizer, feature_extractor=feature_extractor)
input_str = "This is a test string"
encoded_processor = processor(text_target=input_str)
encoded_tok = tokenizer(input_str)
for key in encoded_tok:
self.assertListEqual(encoded_tok[key], encoded_processor[key])
def test_tokenizer_decode(self):
feature_extractor = self.get_feature_extractor()
tokenizer = self.get_tokenizer()
processor = SpeechT5Processor(tokenizer=tokenizer, feature_extractor=feature_extractor)
predicted_ids = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]]
decoded_processor = processor.batch_decode(predicted_ids)
decoded_tok = tokenizer.batch_decode(predicted_ids)
self.assertListEqual(decoded_tok, decoded_processor)
|
SpeechT5ProcessorTest
|
python
|
neetcode-gh__leetcode
|
python/0802-find-eventual-safe-states.py
|
{
"start": 0,
"end": 496
}
|
class ____:
def eventualSafeNodes(self, graph: List[List[int]]) -> List[int]:
n = len(graph)
safe = {}
res = []
def dfs(i):
if i in safe:
return safe[i]
safe[i] = False
for nei in graph[i]:
if not dfs(nei):
return safe[i]
safe[i] = True
return safe[i]
for i in range(len(graph)):
if dfs(i): res.append(i)
return res
|
Solution
|
python
|
pydata__xarray
|
xarray/tests/test_backends.py
|
{
"start": 189566,
"end": 193917
}
|
class ____(NetCDF3Only, CFEncodedBase):
# verify that we can read and write netCDF3 files as long as we have scipy
# or netCDF4-python installed
file_format: T_NetcdfTypes = "NETCDF3_64BIT"
def test_write_store(self) -> None:
# there's no specific store to test here
pass
@requires_scipy
@requires_netCDF4
def test_engine(self) -> None:
data = create_test_data()
with pytest.raises(ValueError, match=r"unrecognized engine"):
data.to_netcdf("foo.nc", engine="foobar") # type: ignore[call-overload]
with create_tmp_file() as tmp_file:
data.to_netcdf(tmp_file)
with pytest.raises(ValueError, match=r"unrecognized engine"):
open_dataset(tmp_file, engine="foobar")
with pytest.raises(
TypeError,
match=re.escape("file objects are not supported by the netCDF4 backend"),
):
data.to_netcdf(BytesIO(), engine="netcdf4")
with pytest.raises(
TypeError,
match=re.escape("file objects are not supported by the netCDF4 backend"),
):
open_dataset(BytesIO(), engine="netcdf4")
bytes_io = BytesIO()
data.to_netcdf(bytes_io, engine="scipy")
with pytest.raises(ValueError, match=r"unrecognized engine"):
open_dataset(bytes_io, engine="foobar")
def test_cross_engine_read_write_netcdf3(self) -> None:
data = create_test_data()
valid_engines: set[T_NetcdfEngine] = set()
if has_netCDF4:
valid_engines.add("netcdf4")
if has_scipy:
valid_engines.add("scipy")
for write_engine in valid_engines:
for format in self.netcdf3_formats:
with create_tmp_file() as tmp_file:
data.to_netcdf(tmp_file, format=format, engine=write_engine)
for read_engine in valid_engines:
with open_dataset(tmp_file, engine=read_engine) as actual:
# hack to allow test to work:
# coord comes back as DataArray rather than coord,
# and so need to loop through here rather than in
# the test function (or we get recursion)
[
assert_allclose(data[k].variable, actual[k].variable)
for k in data.variables
]
def test_encoding_unlimited_dims(self) -> None:
ds = Dataset({"x": ("y", np.arange(10.0))})
with self.roundtrip(ds, save_kwargs=dict(unlimited_dims=["y"])) as actual:
assert actual.encoding["unlimited_dims"] == set("y")
assert_equal(ds, actual)
# Regression test for https://github.com/pydata/xarray/issues/2134
with self.roundtrip(ds, save_kwargs=dict(unlimited_dims="y")) as actual:
assert actual.encoding["unlimited_dims"] == set("y")
assert_equal(ds, actual)
ds.encoding = {"unlimited_dims": ["y"]}
with self.roundtrip(ds) as actual:
assert actual.encoding["unlimited_dims"] == set("y")
assert_equal(ds, actual)
# Regression test for https://github.com/pydata/xarray/issues/2134
ds.encoding = {"unlimited_dims": "y"}
with self.roundtrip(ds) as actual:
assert actual.encoding["unlimited_dims"] == set("y")
assert_equal(ds, actual)
@requires_scipy
def test_roundtrip_via_bytes(self) -> None:
original = create_test_data()
netcdf_bytes = original.to_netcdf()
roundtrip = load_dataset(netcdf_bytes)
assert_identical(roundtrip, original)
@pytest.mark.xfail(
reason="scipy.io.netcdf_file closes files upon garbage collection"
)
@requires_scipy
def test_roundtrip_via_file_object(self) -> None:
original = create_test_data()
f = BytesIO()
original.to_netcdf(f)
assert not f.closed
restored = open_dataset(f)
assert not f.closed
assert_identical(restored, original)
restored.close()
assert not f.closed
@requires_h5netcdf
@requires_netCDF4
@pytest.mark.filterwarnings("ignore:use make_scale(name) instead")
|
TestGenericNetCDFData
|
python
|
run-llama__llama_index
|
llama-index-integrations/readers/llama-index-readers-service-now/tests/test_snow_kb_reader.py
|
{
"start": 1933,
"end": 3619
}
|
class ____:
"""Mock password grant flow for ServiceNow authentication."""
def __init__(self, *args, **kwargs):
pass
@pytest.fixture
def mock_pysnc_imports():
"""Mock pysnc imports for testing."""
with patch.dict("sys.modules", {"pysnc": MagicMock(), "pysnc.auth": MagicMock()}):
sys.modules["pysnc"].ServiceNowClient = MockServiceNowClient
sys.modules["pysnc"].GlideRecord = MagicMock()
sys.modules["pysnc.auth"].ServiceNowPasswordGrantFlow = MockPasswordGrantFlow
yield
@pytest.fixture
def snow_reader(mock_pysnc_imports):
"""Fixture to create a SnowKBReader instance with mocked dependencies."""
with patch(
"llama_index.readers.service_now.base.ServiceNowClient", MockServiceNowClient
):
with patch(
"llama_index.readers.service_now.base.ServiceNowPasswordGrantFlow",
MockPasswordGrantFlow,
):
from llama_index.readers.service_now import SnowKBReader
from llama_index.readers.service_now.base import FileType
# Create custom parsers dictionary with mock parsers
custom_parsers = {
FileType.HTML: MockCustomParser(), # HTML parser is required
FileType.PDF: MockCustomParser(),
FileType.DOCUMENT: MockCustomParser(),
}
return SnowKBReader(
instance="test.service-now.com",
custom_parsers=custom_parsers,
username="test_user",
password="test_pass",
client_id="test_client_id",
client_secret="test_client_secret",
)
|
MockPasswordGrantFlow
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.